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/Day04.kt | chasebleyl | 573,058,526 | false | {"Kotlin": 15274} |
// Formatted "N-N", where input is string and N represents an Integer
fun String.toAssignment() = this.split("-").let { splitSections ->
Assignment(splitSections[0].toInt(), splitSections[1].toInt())
}
data class Assignment(
val lowerSection: Int,
val upperSection: Int,
) {
fun encapsulates(assignment: Assignment) = this.lowerSection <= assignment.lowerSection
&& this.upperSection >= assignment.upperSection
fun overlaps(assignment: Assignment) =
if (this.lowerSection >= assignment.lowerSection && this.lowerSection <= assignment.upperSection) true
else if (this.upperSection <= assignment.upperSection && this.upperSection >= assignment.lowerSection) true
else if (assignment.lowerSection >= this.lowerSection && assignment.lowerSection <= this.upperSection) true
else assignment.upperSection <= this.upperSection && assignment.upperSection >= this.lowerSection
}
fun main() {
fun part1(input: List<String>): Int {
var encapsulatedCounter = 0
input.forEach { assignments ->
val splitAssignments = assignments.split(",")
val assignmentOne = splitAssignments[0].toAssignment()
val assignmentTwo = splitAssignments[1].toAssignment()
if (assignmentOne.encapsulates(assignmentTwo) || assignmentTwo.encapsulates(assignmentOne)) {
encapsulatedCounter += 1
}
}
return encapsulatedCounter
}
fun part2(input: List<String>): Int {
var overlappedCounter = 0
input.forEach { assignments ->
val splitAssignments = assignments.split(",")
val assignmentOne = splitAssignments[0].toAssignment()
val assignmentTwo = splitAssignments[1].toAssignment()
if (assignmentOne.overlaps(assignmentTwo)) {
overlappedCounter += 1
}
}
return overlappedCounter
}
val input = readInput("Day04")
val testInput = readInput("Day04_test")
// PART 1
check(part1(testInput) == 2)
println(part1(input))
// PART 2
check(part2(testInput) == 4)
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | f2f5cb5fd50fb3e7fb9deeab2ae637d2e3605ea3 | 2,162 | aoc-2022 | Apache License 2.0 |
src/Day02.kt | b0n541 | 571,797,079 | false | {"Kotlin": 17810} | fun main() {
fun parsePlayerGesture(move: String) = when (move) {
"A", "X" -> Move.ROCK
"B", "Y" -> Move.PAPER
"C", "Z" -> Move.SCISSORS
else -> error("Unknown gesture $move")
}
fun findMoveFollowingStrategy(strategy: String, firstPlayerMove: Move) = when (strategy) {
"X" -> firstPlayerMove.beats()
"Y" -> firstPlayerMove
"Z" -> firstPlayerMove.beatenBy()
else -> error("Unknown strategy $strategy")
}
fun parseMovesIndependently(line: String): Pair<Move, Move> {
val moves = line.split(" ")
return Pair(parsePlayerGesture(moves[0]), parsePlayerGesture(moves[1]))
}
fun parseMovesWithFollowingStrategy(line: String): Pair<Move, Move> {
val moves = line.split(" ")
val firstPlayerMove = parsePlayerGesture(moves[0])
return Pair(firstPlayerMove, findMoveFollowingStrategy(moves[1], firstPlayerMove))
}
fun calculateGameOutcome(move: Pair<Move, Move>): Int {
if (move.second.beats() == move.first) {
return 6
}
if (move.first == move.second) {
return 3
}
return 0
}
fun calculateScore(move: Pair<Move, Move>): Int {
return move.second.score + calculateGameOutcome(move)
}
fun part1(input: List<String>): Int {
return input.map { line -> parseMovesIndependently(line) }
.sumOf { move -> calculateScore(move) }
}
fun part2(input: List<String>): Int {
return input.map { line -> parseMovesWithFollowingStrategy(line) }
.sumOf { move -> calculateScore(move) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
val resultTest1 = part1(testInput)
println("Test 1: $resultTest1")
check(resultTest1 == 15)
val resultTest2 = part2(testInput)
println("Test 2: $resultTest2")
check(resultTest2 == 12)
val input = readInput("Day02")
val resultPart1 = part1(input)
println("Part 1: $resultPart1")
check(resultPart1 == 14297)
val resultPart2 = part2(input)
println("Part 2: $resultPart2")
check(resultPart2 == 10498)
}
enum class Move(val score: Int) {
ROCK(1) {
override fun beats() = SCISSORS
override fun beatenBy() = PAPER
},
PAPER(2) {
override fun beats() = ROCK
override fun beatenBy() = SCISSORS
},
SCISSORS(3) {
override fun beats() = PAPER
override fun beatenBy() = ROCK
};
abstract fun beats(): Move
abstract fun beatenBy(): Move
}
| 0 | Kotlin | 0 | 0 | d451f1aee157fd4d47958dab8a0928a45beb10cf | 2,620 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | Olivki | 573,156,936 | false | {"Kotlin": 11297} | import RoundResult.DRAW
import RoundResult.LOSS
import RoundResult.WIN
import RpsShape.PAPER
import RpsShape.ROCK
import RpsShape.SCISSORS
fun main() {
val opponentShapeMap = mapOf("A" to ROCK, "B" to PAPER, "C" to SCISSORS)
val desiredShapeMap = mapOf("X" to ROCK, "Y" to PAPER, "Z" to SCISSORS)
val desiredResultMap = mapOf("X" to LOSS, "Y" to DRAW, "Z" to WIN)
fun List<String>.splitInputs() = asSequence()
.filter { it.isNotBlank() }
.map { it.trim().split(' ') }
fun part1(input: List<String>) = input
.splitInputs()
.map { (a, b) -> opponentShapeMap.getValue(a) to desiredShapeMap.getValue(b) }
.map { (opponent, player) ->
val result = when (opponent) {
player.strongAgainst -> WIN
player -> DRAW
else -> LOSS
}
(player.ordinal + 1) + result.score
}
.toList()
fun part2(input: List<String>) = input
.splitInputs()
.map { (a, b) -> opponentShapeMap.getValue(a) to desiredResultMap.getValue(b) }
.map { (opponent, desiredResult) ->
val shapeToPlay = when (desiredResult) {
LOSS -> opponent.strongAgainst
DRAW -> opponent
WIN -> opponent.weakAgainst
}
(shapeToPlay.ordinal + 1) + desiredResult.score
}
.toList()
val testInput = readTestInput("Day02")
// p1
with(part1(testInput)) {
check(this[0] == 8)
check(this[1] == 1)
check(this[2] == 6)
check(sum() == 15)
}
// p2
with(part2(testInput)) {
check(this[0] == 4)
check(this[1] == 1)
check(this[2] == 7)
check(sum() == 12)
}
val input = readInput("Day02")
println(part1(input).sum())
println(part2(input).sum())
}
private enum class RoundResult(val score: Int) {
LOSS(0),
DRAW(3),
WIN(6),
}
private enum class RpsShape(strongAgainst: String, weakAgainst: String) {
ROCK("scissors", "paper"),
PAPER("rock", "scissors"),
SCISSORS("paper", "rock");
val strongAgainst: RpsShape by lazy { RpsShape.valueOf(strongAgainst.uppercase()) }
val weakAgainst: RpsShape by lazy { RpsShape.valueOf(weakAgainst.uppercase()) }
} | 0 | Kotlin | 0 | 1 | 51c408f62589eada3d8454740c9f6fc378e2d09b | 2,298 | aoc-2022 | Apache License 2.0 |
src/Day10.kt | thpz2210 | 575,577,457 | false | {"Kotlin": 50995} | private class Solution10(input: List<String>) {
val states = input.fold(mutableListOf(1)) { acc, command -> executeCommand(command, acc) }
private fun executeCommand(command: String, acc: MutableList<Int>): MutableList<Int> {
val split = command.split(" ")
acc.addAll(
when (split[0]) {
"noop" -> listOf(acc.last())
"addx" -> listOf(acc.last(), acc.last() + split[1].toInt())
else -> throw IllegalArgumentException()
}
)
return acc
}
fun part1() = listOf(20, 60, 100, 140, 180, 220).sumOf { it * states[it - 1] }
fun part2() = (0..5).map { y -> (0..40).map { x -> getPixel(x, y) }.joinToString("") }
private fun getPixel(x: Int, y: Int): Char {
val sprite = (states[y * 40 + x]..states[y * 40 + x] + 2)
return if (x + 1 in sprite) '#' else ' '
}
}
fun main() {
val testSolution = Solution10(readInput("Day10_test"))
check(testSolution.part1() == 13140)
check(
testSolution.part2() == listOf(
"## ## ## ## ## ## ## ## ## ## ",
"### ### ### ### ### ### ### ",
"#### #### #### #### #### ",
"##### ##### ##### ##### ",
"###### ###### ###### #### ",
"####### ####### ####### "
)
)
val solution = Solution10(readInput("Day10"))
println(solution.part1())
println(solution.part2().joinToString("\n"))
}
| 0 | Kotlin | 0 | 0 | 69ed62889ed90692de2f40b42634b74245398633 | 1,556 | aoc-2022 | Apache License 2.0 |
src/nativeMain/kotlin/xyz/justinhorton/aoc2022/Day11.kt | justinhorton | 573,614,839 | false | {"Kotlin": 39759, "Shell": 611} | package xyz.justinhorton.aoc2022
/**
* https://adventofcode.com/2022/day/11
*/
class Day11(override val input: String) : Day() {
override fun part1(): String {
val monkeys = parseMonkeyInput()
return calcMonkeyBizLevel(monkeys, 20) { it / 3 }.toString()
}
override fun part2(): String {
val monkeys = parseMonkeyInput()
val divisorProduct = monkeys.map { it.testDivisor }.reduce { acc, it -> acc * it }
return calcMonkeyBizLevel(monkeys, 10_000) { it % divisorProduct }.toString()
}
private fun parseMonkeyInput(): List<Monkey> {
return input.trim().split("\n\n")
.map { monkeyInput ->
val lines = monkeyInput.lines()
val startingItems = lines[1].replace(",", "")
.split(" ")
.mapNotNull { it.toLongOrNull() }
val expression = lines[2].substringAfter("= old ")
val operator = when (expression.first()) {
'*' -> Operator.Mul
'+' -> Operator.Add
else -> throw UnsupportedOperationException()
}
val term2: Term = when (val rawTerm2 = expression.split(" ").last()) {
"old" -> Term.Old
else -> Term.Literal(rawTerm2.toLong())
}
val divisor = lines[3].split(" ").last().toInt()
val ifTrueMonkey = lines[4].split(" ").last().toInt()
val ifFalseMonkey = lines[5].split(" ").last().toInt()
Monkey(
startingItems.map { Item(it) }.toMutableList(),
BinaryExpression(Term.Old, term2, operator),
divisor,
ifTrueMonkey,
ifFalseMonkey
)
}
}
private fun calcMonkeyBizLevel(monkeys: List<Monkey>, numRounds: Int, bizControlFn: (Long) -> Long): Long {
val monkeyBizLevels = mutableMapOf<Int, Long>().withDefault { 0 }
for (round in 1..numRounds) {
for ((i: MonkeyId, m: Monkey) in monkeys.withIndex()) {
for (item in m.items) {
item.worryLevel = bizControlFn(m.operation.eval(item.worryLevel))
if (item.worryLevel % m.testDivisor == 0L) {
monkeys[m.ifTrueMonkey].items += item
} else {
monkeys[m.ifFalseMonkey].items += item
}
}
monkeyBizLevels[i] = monkeyBizLevels.getValue(i) + m.items.size
m.items.clear()
}
}
val topBusinessmen = monkeyBizLevels.entries.sortedByDescending { it.value }
return topBusinessmen.take(2).map { it.value }.reduce { acc, it -> acc * it }
}
}
private typealias MonkeyId = Int
private data class Monkey(
val items: MutableList<Item>,
val operation: BinaryExpression,
val testDivisor: Int,
val ifTrueMonkey: MonkeyId,
val ifFalseMonkey: MonkeyId
)
private class Item(var worryLevel: Long) {
override fun toString(): String = "Item(w=$worryLevel)"
}
private data class BinaryExpression(val first: Term, val second: Term, val operator: Operator) {
fun eval(old: Long): Long {
val t1 = first.resolve(old)
val t2 = second.resolve(old)
return when (operator) {
is Operator.Mul -> t1 * t2
is Operator.Add -> t1 + t2
}
}
}
private sealed class Term {
fun resolve(old: Long): Long = when (this) {
is Literal -> value
is Old -> old
}
data class Literal(val value: Long) : Term()
object Old : Term()
}
private sealed class Operator {
object Mul : Operator()
object Add : Operator()
}
| 0 | Kotlin | 0 | 1 | bf5dd4b7df78d7357291c7ed8b90d1721de89e59 | 3,823 | adventofcode2022 | MIT License |
src/main/kotlin/days/aoc2021/Day8.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2021
import days.Day
class Day8 : Day(2021, 8) {
override fun partOne(): Any {
return calculateFrequencyOfCertainOutputs(inputList)
}
override fun partTwo(): Any {
return calculateOutputValueSum(inputList)
}
fun calculateFrequencyOfCertainOutputs(inputLines: List<String>): Int {
val uniqueSizes = setOf(2, 3, 4, 7)
return inputLines.sumBy { line ->
line.substringAfter('|').trim().split("\\s".toRegex()).filter {
it.length in uniqueSizes
}.count()
}
}
fun calculateOutputValueSum(inputLines: List<String>): Int {
return inputLines.sumBy { line ->
line.substringBefore('|').split("\\s".toRegex()).map { it.toSet() }.let { sets ->
val a = sets.first { it.size == 3 }.minus(sets.first { it.size == 2}).first()
val f = sets.filter { it.size == 6 }.reduce { a, b -> a intersect b }.intersect(sets.first { it.size == 2 }).first()
val c = sets.first { it.size == 2 }.minus(setOf(f)).first()
val d = sets.filter { it.size == 5 }.reduce { a, b -> a intersect b }.intersect(sets.first { it.size == 4 }).minus(setOf(c, f)).first()
val b = sets.first { it.size == 4 }.minus(setOf(c, d, f)).first()
val g = sets.filter { it.size == 6 }.reduce { a, b -> a intersect b }.minus(setOf(a, f, c, d, b)).first()
val e = sets.first { it.size == 7 }.minus(setOf(a, b, c, d, f, g)).first()
val signalToValues = listOf(
setOf(a, b, c, e, f, g),
setOf(c, f),
setOf(a, c, d, e, g),
setOf(a, c, d, f, g),
setOf(b, c, d, f),
setOf(a, b, d, f, g),
setOf(a, b, d, e, f, g),
setOf(a, c, f),
setOf(a, b, c, d, e, f, g),
setOf(a, b, c, d, f, g)
)
signalToValues.forEachIndexed { index, s -> println("For $index the signals are $s") }
var multiplier = 1000
line.substringAfter('|').trim().split("\\s".toRegex()).map { s ->
val current = s.toCharArray().toSet()
val value = signalToValues.indexOf(current) * multiplier
println ("For $s value is $value")
multiplier /= 10
value
}.sum()
}
}
}
} | 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 2,544 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
src/Day15.kt | jvmusin | 572,685,421 | false | {"Kotlin": 86453} | import kotlin.math.abs
fun main() {
data class Position(val x: Int, val y: Int) {
fun distance(p: Position) = abs(x - p.x) + abs(y - p.y)
}
data class SensorBeacon(val sensor: Position, val beacon: Position) {
fun distance() = sensor.distance(beacon)
}
fun parse(input: List<String>): List<SensorBeacon> {
val r = Regex("Sensor at x=(?<x1>.*), y=(?<y1>.*): closest beacon is at x=(?<x2>.*), y=(?<y2>.*)").toPattern()
val pairs = input.map { r.matcher(it).also { m -> m.find() } }.map {
val x1 = it.group("x1")
val y1 = it.group("y1")
val x2 = it.group("x2")
val y2 = it.group("y2")
SensorBeacon(
Position(x1.toInt(), y1.toInt()),
Position(x2.toInt(), y2.toInt())
)
}
return pairs
}
fun part1(input: List<String>): Int {
val pairs = parse(input)
val all = pairs.map { it.beacon } + pairs.map { it.sensor }.toSet()
val minX = all.minOf { it.x }
val maxX = all.maxOf { it.x }
val maxDistance = pairs.maxOf { it.distance() }
val Y = 2000000
// val Y = 10
var cnt = 0
for (x in minX - maxDistance - 1..maxX + maxDistance + 1) {
val p = Position(x, Y)
if (p in all) continue
val anyFail = pairs.any { (sensor, beacon) -> sensor.distance(p) <= sensor.distance(beacon) }
if (anyFail) {
cnt++
}
}
return cnt
}
fun sum(to: Int) = to * (to + 1L) / 2
fun sum(from: Int, to: Int) = if (from > to) 0 else sum(to) - sum(from - 1)
fun part2(input: List<String>): Long {
val pairs = parse(input)
val max = 4000000
val multiplier = 4000000
var tf = 0L
for (y in 0..max) {
val segments = mutableListOf(max + 1..max + 1)
for ((sensor, beacon) in pairs) {
val dist = sensor.distance(beacon)
val r = dist - abs(y - sensor.y)
if (r >= 0) {
val left = maxOf(0, sensor.x - r)
val right = minOf(max, sensor.x + r)
segments += left..right
}
}
segments.sortBy { it.first }
var start = 0
for (s in segments) {
val cnt = s.first - start
if (cnt > 0) {
val sumX = sum(start, s.first - 1)
val sumY = cnt * y.toLong()
tf += sumX * multiplier + sumY
}
start = maxOf(start, s.last + 1)
}
}
return tf
}
@Suppress("DuplicatedCode")
run {
val day = String.format("%02d", 15)
val testInput = readInput("Day${day}_test")
val input = readInput("Day$day")
println("Part 1 test - " + part1(testInput))
println("Part 1 real - " + part1(input))
println("---")
println("Part 2 test - " + part2(testInput))
println("Part 2 real - " + part2(input))
}
}
| 1 | Kotlin | 0 | 0 | 4dd83724103617aa0e77eb145744bc3e8c988959 | 3,147 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | bigtlb | 573,081,626 | false | {"Kotlin": 38940} | fun main() {
fun score(round: String, strategy: Int = 1): Int {
var score = 0
var (them, you) = round.uppercase().toCharArray().filterNot { it == ' ' }
//For strategy 2, choos what you throw by seeing if you should win, lose, or draw
if (strategy == 2){
you = when (you){
// x = lose
'X' -> "XYZ"[("ABC".indexOf(them) + 2) % 3]
// z = win
'Z' -> "XYZ"[("ABC".indexOf(them) + 1) % 3]
else -> "XYZ"["ABC".indexOf(them)]
}
}
// Points for your choise
score += when (you) {
'X' -> 1 // rock
'Y' -> 2 // paper
'Z' -> 3 // scissors
else -> 0
}
score += when {
(them == 'A' && you == 'Y') || // them = rock, you = paper
(them == 'B' && you == 'Z') || // them = paper, you = scissors
(them == 'C' && you == 'X') // them = scissors and you = rock
-> 6
"ABC".indexOf(them) == "XYZ".indexOf(you) -> 3
else -> 0
}
return score
}
fun part1(input: List<String>): Int {
return input.fold(0) { acc, round -> acc + score(round) }
}
fun part2(input: List<String>): Int {
return input.fold(0) { acc, round -> acc + score(round, 2) }
}
// 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 | d8f76d3c75a30ae00c563c997ed2fb54827ea94a | 1,653 | aoc-2022-demo | Apache License 2.0 |
src/main/kotlin/com/colinodell/advent2023/Day07.kt | colinodell | 726,073,391 | false | {"Kotlin": 114923} | package com.colinodell.advent2023
class Day07(private val input: List<String>) {
class Hand(private val cards: List<Char>, val bid: Int, private val joker: Char) : Comparable<Hand> {
// Number of jokers in this hand
private val jokerCount = cards.count { it == joker }
// The strength of this hand as a string, which makes it easy to compare to other hands.
// Possible values include:
// - High card: "11111" (1 of each card)
// - One pair: "2111" (2 cards with the same label, 1 of all other cards)
// - Two pair: "221" (2 cards with one label, 2 cards with another label, and 1 left over)
// - Three of a kind: "311" (3 cards with one label, 1 of all other cards)
// - Full house would be "32" (3 of one card, 2 of another)
// - Four of a kind would be "41" (4 of one card, 1 of all other cards)
// - Five of a kind would be "5" (5 of one card)
private val strength = cards
// Group all non-jokers by card count
.filter { it != joker }
.groupingBy { it }
.eachCount()
// We don't need to know the card labels beyond this point, just the counts
.map { it.value }
// No cards? We must have all jokers
.ifEmpty { listOf(0) }
// Sort in descending order
.sortedDescending()
// If we have jokers, add them to whatever has the highest count to further strengthen the hand
.toMutableList()
.apply { if (jokerCount > 0) this[0] += jokerCount }
// Convert to a string representation for easy comparison
.joinToString { it.toString() }
// The values of each card, used as a tie-breaker when putting hands in order of strength
private val cardValues = cards.map {
when (it) {
joker -> 1
'T' -> 10
'J' -> 11
'Q' -> 12
'K' -> 13
'A' -> 14
else -> it.toString().toInt()
}
}
// Compare by strength, then by card values
override fun compareTo(other: Hand) = when (val c = strength.compareTo(other.strength)) {
0 -> cardValues.compareTo(other.cardValues)
else -> c
}
override fun toString() = "$cards ($strength)"
}
private fun calculateTotalWinnings(joker: Char = '\u0000') = input
.map {
val (cards, bid) = it.split(" ")
Hand(cards.toList(), bid.toInt(), joker)
}
.sorted()
.mapIndexed { rank, hand -> hand.bid * (rank + 1) }
.sum()
fun solvePart1() = calculateTotalWinnings()
fun solvePart2() = calculateTotalWinnings(joker = 'J')
}
| 0 | Kotlin | 0 | 0 | 97e36330a24b30ef750b16f3887d30c92f3a0e83 | 2,819 | advent-2023 | MIT License |
src/Day07.kt | wooodenleg | 572,658,318 | false | {"Kotlin": 30668} | sealed interface SystemItem {
val name: String
val size: Int
}
data class Directory(
override val name: String,
val parent: Directory?,
) : SystemItem {
override val size: Int get() = contents.sumOf(SystemItem::size)
val contents: MutableList<SystemItem> = mutableListOf()
val nestedContents: List<SystemItem>
get() = contents.flatMap { item ->
when (item) {
is Directory -> listOf(item) + item.nestedContents
is File -> listOf(item)
}
}
}
data class File(
override val name: String,
override val size: Int
) : SystemItem
fun buildFileStructure(input: List<String>): Directory {
val root = Directory("/", null)
var currentDirectory = root
val currentContentList = mutableListOf<String>()
fun handleEndOfContent() {
if (currentContentList.isNotEmpty()) {
currentDirectory.fillWithItems(currentContentList)
currentContentList.clear()
}
}
for (line in input) {
if (!line.startsWith("$")) {
currentContentList.add(line)
continue
}
// Is command
handleEndOfContent()
if (line == "$ ls") continue // ignore ls commnands
val dirName = line.split(" ")[2]
currentDirectory = if (dirName == "..") {
currentDirectory.parent ?: error("Attempt to go above root dir")
} else {
currentDirectory.contents
.filterIsInstance<Directory>()
.first { it.name == dirName }
}
}
handleEndOfContent()
return root
}
fun Directory.fillWithItems(items: List<String>) {
for (item in items) {
if (item.startsWith("dir")) {
val (_, dirName) = item.split(" ")
contents.add(Directory(dirName, this))
} else {
val (size, fileName) = item.split(" ")
contents.add(File(fileName, size.toInt()))
}
}
}
fun main() {
fun part1(input: List<String>): Int {
val root = buildFileStructure(input.drop(1))
val relevantDirectories = root.nestedContents
.filterIsInstance<Directory>()
.filter { it.size <= 100000 }
return relevantDirectories.sumOf { it.size }
}
fun part2(input: List<String>): Int {
val root = buildFileStructure(input.drop(1))
val freeSpace = 70_000_000 - root.size
val spaceNeeded = 30_000_000 - freeSpace
return root.nestedContents.filterIsInstance<Directory>()
.filter { it.size >= spaceNeeded }
.minByOrNull { it.size }
?.size ?: 0
}
val testInput = readInputLines("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInputLines("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | ff1f3198f42d1880e067e97f884c66c515c8eb87 | 2,893 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/hopkins/aoc/day7/main.kt | edenrox | 726,934,488 | false | {"Kotlin": 88215} | package com.hopkins.aoc.day7
import java.io.File
const val debug = true
const val part = 2
val defaultCardOrder: List<String> =
listOf("A", "K", "Q", "J", "T", "9", "8", "7", "6", "5", "4", "3", "2", "1")
val allCards =
if (part == 1) {
defaultCardOrder
} else {
// In part 2, "J" is a joker and it is a low-value card
defaultCardOrder.filter { it != "J" } + listOf("J")
}
enum class HandType {
FIVE_OF_A_KIND,
FOUR_OF_A_KIND,
FULL_HOUSE,
THREE_OF_A_KIND,
TWO_PAIR,
ONE_PAIR,
HIGH_CARD
}
/** Advent of Code 2023: Day 7 */
fun main() {
val inputFile = File("input/input7.txt")
val lines: List<String> = inputFile.readLines()
val hands: List<CamelHand> = lines.map { readHand(it) }
if (debug) {
println("All Cards: $allCards")
println("Hands:")
hands.take(5).forEach { println(" $it") }
}
val sortedHands: List<CamelHand> =
hands.sortedWith(compareBy( { it.type }, { it.getCardsValues() } ))
if (debug) {
println("Sorted Hands:")
sortedHands.take(500).takeLast(20).forEach { println(" $it") }
}
val topValue = hands.size
val handValues: List<Long> =
sortedHands.mapIndexed { index, camelHand -> ((topValue - index) * camelHand.bid).toLong() }
if (debug) {
println("Top Value: $topValue")
println("Hand values:")
handValues.take(5).forEach { println(" $it") }
}
val result = handValues.sum()
println("Result: $result")
// Part1 = 250474325 (correct)
// Part2 = 249010224 (incorrect)
}
/** Returns a [CamelHand] instance parsed from the specified line. */
fun readHand(line: String): CamelHand {
// Format: <Cards> <Bid>
// Example: 32T3K 765
val (cards, bidString) = line.trim().split(" ")
return CamelHand(cards, bidString.toInt())
}
fun transformHand(cards: String): String {
if (part == 1) {
// Part 1: no jokers in the deck
return cards
}
if (!cards.contains("J")) {
// Part 2: no jokers in the hand
return cards
}
if (cards == "JJJJJ") {
return cards
}
val cardMap = cards.filter { it != 'J' }.groupingBy { it }.eachCount()
val maxCount = cardMap.values.max()
val bestCard =
cardMap.filter { entry -> entry.value == maxCount }.minBy { entry -> allCards.indexOf(entry.key.toString()) }
return cards.replace("J", bestCard.key.toString())
}
/** Figure out the best hand which can be formed from the specified cards. */
fun calculateType(cards: String) : HandType {
// Group and count cards by type
val cardMap = cards.groupingBy { it }.eachCount()
// Sort by descending count
val cardCountList: List<Int> = cardMap.values.sortedDescending()
val max = cardCountList.first()
return when (max) {
5 -> HandType.FIVE_OF_A_KIND
4 -> HandType.FOUR_OF_A_KIND
3 -> if (cardCountList[1] == 2) { HandType.FULL_HOUSE } else { HandType.THREE_OF_A_KIND }
2 -> if (cardCountList[1] == 2) { HandType.TWO_PAIR } else { HandType.ONE_PAIR }
else -> HandType.HIGH_CARD
}
}
/** Represents a set of 5 cards and a bid value. */
class CamelHand(val cards: String, val bid: Int) {
val type: HandType = calculateType(transformHand(cards))
/** Returns a string that represents the value of the cards (00 being high, 13 being low). */
fun getCardsValues(): String =
cards.map { allCards.indexOf(it.toString()) }.joinToString("") { String.format("%02d", it) }
override fun toString(): String = "Hand {type=$type cards=$cards cardValues=${getCardsValues()} bid=$bid}"
}
| 0 | Kotlin | 0 | 0 | 45dce3d76bf3bf140d7336c4767e74971e827c35 | 3,667 | aoc2023 | MIT License |
y2018/src/main/kotlin/adventofcode/y2018/Day16.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2018
import adventofcode.io.AdventSolution
import adventofcode.language.elfcode.*
object Day16 : AdventSolution(2018, 16, "Chronal Classification") {
override fun solvePartOne(input: String) =
parse(input).first.count { example ->
allOperations.count { operation -> example.isSolvedBy(operation) } >= 3
}
override fun solvePartTwo(input: String): Int {
val (examples, program) = parse(input)
val operations = findOperationsFromExamples(examples)
val registers = IntArray(4)
for (instruction in program) {
registers.execute(operations[instruction.opcode], instruction)
}
return registers[0]
}
private fun findOperationsFromExamples(examples: Sequence<Example>): List<Operation> {
val ambiguousOpcodes = allOperations.indices.associateWith { allOperations.toMutableSet() }.toSortedMap()
val foundOpcodes = sortedMapOf<Int, Operation>()
examples
.takeWhile { ambiguousOpcodes.isNotEmpty() }
.forEach { example ->
//the opcode of the example can only refer to operations that isSolvedBy the example
ambiguousOpcodes[example.instruction.opcode]?.retainAll { example.isSolvedBy(it) }
//remove all found opcodes/operations from the search.
//this can result in determining other opcodes/operations, so iterate.
while (ambiguousOpcodes.any { it.value.size == 1 }) {
//find all determined opcodes
ambiguousOpcodes.keys.filter { ambiguousOpcodes[it]!!.size == 1 }
.forEach { opCode ->
//move to found codes
val operation = ambiguousOpcodes.remove(opCode)!!.first()
foundOpcodes[opCode] = operation
//no other opcode can refer to this operator
ambiguousOpcodes.values.forEach { it -= operation }
}
}
}
//the map is sorted by opcode, so this results in a correctly indexed list of operators
return foundOpcodes.values.toList()
}
private fun parse(input: String): Pair<Sequence<Example>, Sequence<UnboundInstruction>> {
val (partOne, partTwo) = input.split("\n\n\n\n")
val examples = partOne.splitToSequence("\n\n")
.map {
val (before, op, after) = it.lines().map { line ->
line.filter { c -> c in ('0'..'9') || c == ' ' }
.trim()
.split(" ")
.map(String::toInt)
.toIntArray()
}
Example(
before,
UnboundInstruction(op[0], op[1], op[2], op[3]),
after
)
}
val program = partTwo.lineSequence()
.map {
it.split(" ")
.map(String::toInt)
.let { (a, b, c, d) -> UnboundInstruction(a, b, c, d) }
}
return (examples to program)
}
}
private class Example(val before: Registers, val instruction: UnboundInstruction, val after: Registers) {
fun isSolvedBy(op: Operation) = before.clone().apply { execute(op, instruction) }.contentEquals(after)
} | 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 3,680 | advent-of-code | MIT License |
src/main/kotlin/me/shutkin/assur/samples/Grouping.kt | shutkin | 135,262,745 | false | {"Kotlin": 58266} | package me.shutkin.assur.samples
import me.shutkin.assur.HistogramData
import me.shutkin.assur.getHistogramMedianValue
import me.shutkin.assur.logger.assurLog
fun grouping(samples: List<DoubleArray>, groupsNumber: Int, diffFunction: (DoubleArray, DoubleArray) -> Double = ::evalArraysDiff): List<Reference> {
val averageDiff = findAverageDiff(samples, diffFunction)
var diffFactor = 2.0
while (diffFactor > 0) {
val groups = MutableList<MutableSet<Int>>(1) { HashSet() }
samples.forEachIndexed { index, sample ->
val maxDiffsByGroup = groups.map { group -> group.map { diffFunction(sample, samples[it]) }.max() ?: 0.0 }
val minGroupDiff = maxDiffsByGroup.min() ?: 0.0
if (minGroupDiff < averageDiff * diffFactor) {
groups[maxDiffsByGroup.indexOf(minGroupDiff)].add(index)
} else {
val newGroup = HashSet<Int>()
newGroup.add(index)
groups.add(newGroup)
}
}
val minSamplesInGroup = samples.size / 80
val filtered = groups.filter { it.size >= minSamplesInGroup }
assurLog("Build ${filtered.size} samples group with diff factor $diffFactor")
if (filtered.size >= groupsNumber) {
val referencesData = filtered.map { group ->
Reference(0, 0.0, group.size.toDouble() / samples.size,
DoubleArray(samples[0].size) { group.map { sampleIndex -> samples[sampleIndex][it] }.sum() / group.size })
}.sortedBy { getHistogramMedianValue(HistogramData(0.0, 1.0, it.data), 0.5) }
return referencesData.mapIndexed { index, ref ->
Reference(index, evalAverageDiff(samples, ref.data, diffFunction), ref.popularity, ref.data) }
}
diffFactor *= 0.95
}
throw Exception("Can't collect $groupsNumber groups")
}
private fun evalAverageDiff(samples: List<DoubleArray>, referenceData: DoubleArray, diffFunction: (DoubleArray, DoubleArray) -> Double) =
samples.map { diffFunction(it, referenceData) }.average()
private fun findAverageDiff(samples: List<DoubleArray>, diffFunction: (DoubleArray, DoubleArray) -> Double): Double {
var sumDiffs = 0.0
var count = 0
samples.forEachIndexed { index, sample0 ->
(index + 1 until samples.size).forEach { sumDiffs += diffFunction(sample0, samples[it]); count++ }
}
return sumDiffs / count
}
fun evalArraysDiff(test: DoubleArray, sample: DoubleArray) =
test.indices.map {
val d1 = test[it] - sample[it]
val d2 = if (it > 0) {
(test[it] - test[it - 1]) - (sample[it] - sample[it - 1])
} else 0.0
d1 * d1 + d2 * d2 * d2 * d2
}.sum()
fun evalArraysDiffM(test: DoubleArray, sample: DoubleArray): Double {
val testHistogramData = HistogramData(0.0, 1.0, test)
val sampleHistogramData = HistogramData(0.0, 1.0, sample)
return (1 until 8).map {
val threshold = 1.0 * it / 8.0
val d = getHistogramMedianValue(testHistogramData, threshold) - getHistogramMedianValue(sampleHistogramData, threshold)
d * d
}.sum() / 8
}
| 0 | Kotlin | 0 | 0 | c867705ff97ca18ea1f26f1f69b085711d0a9bd1 | 2,938 | assur | Apache License 2.0 |
src/day12/day12.kt | Eynnzerr | 576,874,345 | false | {"Kotlin": 23356} | package day12
import java.io.File
import kotlin.math.min
val matrix = readAsMatrix("src/day12/input.txt")
val start = locate('S', matrix)
val end = locate('E', matrix)
val visited = Array(matrix.size) { BooleanArray(matrix[0].size) { false } }
var result = Int.MAX_VALUE
var steps = 0
fun main() {
// Obviously a DP problem. dp[i][j] means the minimum cost from start.
// dp[i][j] = 1 + min(dp[pos in 4 directions && dis <= 1])
// but will meet problems with iteration
// so consider another method: backtrack time-consuming!!!
bfs(start)
println("fewest steps: $result")
}
private fun bfs(current: Pair<Int, Int>) {
// update result to find the best solution.
if (current == end) {
println("find solution: $steps")
result = min(result, steps)
return
}
// find valid next hop.
val next = arrayOf(
current.first to current.second + 1,
current.first to current.second - 1,
current.first + 1 to current.second,
current.first - 1 to current.second
).filter {
it.first in matrix.indices &&
it.second in matrix[0].indices &&
!visited[it.first][it.second] &&
matrix[current.first][current.second] canReach matrix[it.first][it.second]
}
// backtrack.
for (pos in next){
visited[pos.first][pos.second] = true
steps ++
bfs(pos)
visited[pos.first][pos.second] = false
steps --
}
}
private fun readAsMatrix(src: String) = File(src)
.readLines()
.map {
it.toCharArray()
}
.toTypedArray()
private fun locate(target: Char, matrix: Array<CharArray>): Pair<Int, Int> {
matrix.forEachIndexed { index, chars ->
val second = chars.indexOf(target)
if (second != -1) return index to second
}
return -1 to -1
}
private fun Char.height() = when (this) {
'S' -> 0
'E' -> 25
else -> this - 'a'
}
private infix fun Char.canReach(next: Char) = this.height() >= next.height() - 1
| 0 | Kotlin | 0 | 0 | 92e85d65f62900d98284cbc9f6f9a3010efb21b7 | 2,020 | advent-of-code-2022 | Apache License 2.0 |
2020/src/year2021/day09/code.kt | eburke56 | 436,742,568 | false | {"Kotlin": 61133} | package year2021.day09
import util.readAllLines
data class Cell(val row: Int, val col: Int)
fun main() {
part1()
part2()
}
private fun part1() {
val grid = readGrid("input.txt")
val lows = findLows(grid).sumOf { grid[it.row][it.col] + 1 }
println(lows)
}
private fun part2() {
val grid = readGrid("input.txt")
val lows = findLows(grid)
val maxRow = grid.size - 1
val maxCol = grid[0].size - 1
val basins = mutableSetOf<Set<Cell>>()
while (lows.isNotEmpty()) {
val basin = mutableSetOf<Cell>()
testCell(grid, lows, maxRow, maxCol, basin)
basins.add(basin)
}
var product = 1
basins.sortedByDescending { it.size }.take(3).forEach { product *= it.size }
println(product)
}
private fun readGrid(filename: String) = readAllLines(filename).map { line -> line.toCharArray().map { it.code - '0'.code } }
private fun testCell(grid: List<List<Int>>,
lows: MutableSet<Cell>,
maxRow: Int,
maxCol: Int,
basin: MutableSet<Cell>,
cellUnderTest: Cell? = null) {
val cell = cellUnderTest ?: lows.first()
val row = cell.row
val col = cell.col
val currentValue = grid[row][col]
// stop at the top
if (currentValue == 9) {
return
}
basin.add(cell)
// don't re-test this cell if it's also a low
if (lows.contains(cell)) {
lows.remove(cell)
}
if (row > 0) {
val nextCell = Cell(row - 1, col)
if (!basin.contains(nextCell) && grid[row - 1][col] > currentValue) {
testCell(grid, lows, maxRow, maxCol, basin, nextCell)
}
}
if (row < maxRow) {
val nextCell = Cell(row + 1, col)
if (!basin.contains(nextCell) && grid[row + 1][col] > currentValue) {
testCell(grid, lows, maxRow, maxCol, basin, nextCell)
}
}
if (col > 0) {
val nextCell = Cell(row, col - 1)
if (!basin.contains(nextCell) && grid[row][col - 1] > currentValue) {
testCell(grid, lows, maxRow, maxCol, basin, nextCell)
}
}
if (col < maxCol) {
val nextCell = Cell(row, col + 1)
if (!basin.contains(nextCell) && grid[row][col + 1] > currentValue) {
testCell(grid, lows, maxRow, maxCol, basin, nextCell)
}
}
}
private fun findLows(grid: List<List<Int>>): MutableSet<Cell> {
val lows = mutableSetOf<Cell>()
val maxRow = grid.size - 1
for (i in 0..maxRow) {
val maxCol = grid[i].size - 1
for (j in 0..maxCol) {
if ((i == 0 || grid[i][j] < grid[i - 1][j])
&& (i == maxRow || grid[i][j] < grid[i + 1][j])
&& (j == 0 || grid[i][j] < grid[i][j - 1])
&& (j == maxCol || grid[i][j] < grid[i][j + 1])
) {
lows.add(Cell(i, j))
}
}
}
return lows
}
| 0 | Kotlin | 0 | 0 | 24ae0848d3ede32c9c4d8a4bf643bf67325a718e | 2,951 | adventofcode | MIT License |
2k23/aoc2k23/src/main/kotlin/02.kt | papey | 225,420,936 | false | {"Rust": 88237, "Kotlin": 63321, "Elixir": 54197, "Crystal": 47654, "Go": 44755, "Ruby": 24620, "Python": 23868, "TypeScript": 5612, "Scheme": 117} | package d02
import input.read
import java.util.*
fun main() {
println("Part 1: ${part1(read("02.txt"))}")
println("Part 2: ${part2(read("02.txt"))}")
}
class Game(input: String) {
enum class Color {
BLUE, RED, GREEN
}
private val id: Int
private var rounds: List<Map<Color, Int>>
private val balls: Map<Color, Int> = mapOf(
Color.BLUE to 14,
Color.RED to 12,
Color.GREEN to 13
)
private val GAME_DELIMITOR = ":"
private val ROUND_DELIMITOR = ";"
private val INNER_ROUND_DELIMITOR = ", "
init {
id = parseId(input)!!
rounds = parseRuns(input)
}
fun isValid(): Boolean {
return rounds.all { round ->
round.all { (color, count) ->
balls[color]!! >= count
}
}
}
fun getId(): Int {
return id
}
fun getFewest(): Int {
return rounds.fold(mutableMapOf<Color, Int>()) { acc, round ->
round.forEach { (color, count) ->
if (acc.getOrDefault(color, 0) < count) {
acc[color] = count
}
}
acc
}.values.reduce(Int::times)
}
private fun parseId(input: String): Int? {
return Regex("Game (\\d+):.*").find(input)?.let {
return it.groupValues[1].toInt()
}
}
private fun parseRuns(input: String): List<Map<Color, Int>> {
return input.substringAfter(GAME_DELIMITOR)
.trim()
.split(ROUND_DELIMITOR)
.map(::parseRounds)
}
private fun parseRounds(input: String): Map<Color, Int> {
return input.trim().split(INNER_ROUND_DELIMITOR).fold(mutableMapOf<Color, Int>()) { acc, c ->
Regex("(\\d+) (\\w+)").find(c)?.let { turn ->
val (count, color) = turn.destructured
acc[Color.valueOf(color.uppercase(Locale.getDefault()))] = count.toInt()
}
acc
}.toMap()
}
override fun toString(): String {
return "Game(id=$id, runs=$rounds)"
}
}
fun part1(lines: List<String>): Int {
return lines.map { Game(it) }
.filter(Game::isValid)
.sumOf(Game::getId)
}
fun part2(lines: List<String>): Int {
return lines.map { Game(it) }.sumOf(Game::getFewest)
}
| 0 | Rust | 0 | 3 | cb0ea2fc043ebef75aff6795bf6ce8a350a21aa5 | 2,336 | aoc | The Unlicense |
src/Day13.kt | thpz2210 | 575,577,457 | false | {"Kotlin": 50995} | import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.node.ArrayNode
import com.fasterxml.jackson.databind.node.IntNode
import com.fasterxml.jackson.databind.node.JsonNodeFactory
import java.lang.Integer.max
private class Solution13(input: List<String>) {
val pairs = input.chunked(3).map { it[0] to it[1] }
val packages = input.filter { it.isNotBlank() }.toMutableList()
fun part1() =
pairs.indices.filter { Comparator.compare(pairs[it].first, pairs[it].second) == RIGHT_ORDER }.sumOf { it + 1 }
fun part2(): Int {
val divider1 = "[[2]]"
val divider2 = "[[6]]"
packages.addAll(listOf(divider1, divider2))
val sorted = packages.sortedWith(Comparator)
return (sorted.indexOfFirst { it == divider1 } + 1) * (sorted.indexOfFirst { it == divider2 } + 1)
}
companion object {
const val RIGHT_ORDER = -1
const val EQUAL = 0
const val NOT_RIGHT_ORDER = 1
val Comparator =
Comparator<String> { left, right -> compare(ObjectMapper().readTree(left), ObjectMapper().readTree(right)) }
fun compare(left: JsonNode, right: JsonNode): Int {
if (left is IntNode && right is IntNode) {
return compareValues(left.intValue(), right.intValue())
} else if (left is ArrayNode && right is ArrayNode) {
for (i in (0 until max(left.size(), right.size()))) {
if (left.size() <= i) {
return RIGHT_ORDER
} else if (right.size() <= i) {
return NOT_RIGHT_ORDER
}
val c = compare(left[i], right[i])
if (c != 0) return c
}
return EQUAL
} else if (left is IntNode && right is ArrayNode) {
val node = JsonNodeFactory.instance.arrayNode()
node.add(left)
return compare(node, right)
} else {
val node = JsonNodeFactory.instance.arrayNode()
node.add(right)
return compare(left, node)
}
}
}
}
fun main() {
val comparator = Solution13.Comparator
check(comparator.compare("[1,1,3,1,1]", "[1,1,5,1,1]") == Solution13.RIGHT_ORDER)
check(comparator.compare("[[1],[2,3,4]]", "[[1],4]") == Solution13.RIGHT_ORDER)
check(comparator.compare("[9]", "[[8,7,6]]") == Solution13.NOT_RIGHT_ORDER)
check(comparator.compare("[[4,4],4,4]", "[[4,4],4,4,4]") == Solution13.RIGHT_ORDER)
check(comparator.compare("[7,7,7,7]", "[7,7,7]") == Solution13.NOT_RIGHT_ORDER)
check(comparator.compare("[]", "[3]") == Solution13.RIGHT_ORDER)
check(comparator.compare("[[[]]]", "[[]]") == Solution13.NOT_RIGHT_ORDER)
check(
comparator.compare(
"[1,[2,[3,[4,[5,6,7]]]],8,9]",
"[1,[2,[3,[4,[5,6,0]]]],8,9]"
) == Solution13.NOT_RIGHT_ORDER
)
val testSolution = Solution13(readInput("Day13_test"))
check(testSolution.part1() == 13)
check(testSolution.part2() == 140)
val solution = Solution13(readInput("Day13"))
println(solution.part1())
println(solution.part2())
}
| 0 | Kotlin | 0 | 0 | 69ed62889ed90692de2f40b42634b74245398633 | 3,294 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/days/Day08.kt | julia-kim | 569,976,303 | false | null | package days
import readInput
fun main() {
fun createTreeGrid(input: List<String>) = input.map {
it.map(Character::getNumericValue).toIntArray()
}.toTypedArray()
fun part1(input: List<String>): Int {
val array = createTreeGrid(input)
val cols = input[0].length
val rows = input.size
val columns = List(cols) { col -> array.map { it[col] } }
var visibleTrees = 0
array.forEachIndexed { i, row ->
row.forEachIndexed { j, height ->
var visible = false
val left = row.take(j)
if (left.all { it < height }) visible = true
val right = row.takeLast(cols - j - 1)
if (right.all { it < height }) visible = true
val top = columns[j].take(i)
if (top.all { it < height }) visible = true
val bottom = columns[j].takeLast(rows - i - 1)
if (bottom.all { it < height }) visible = true
if (visible) visibleTrees++
}
}
return visibleTrees
}
fun part2(input: List<String>): Int {
val array = createTreeGrid(input)
val cols = input[0].length
val rows = input.size
val columns = List(cols) { col -> array.map { it[col] } }
val scenicScore: MutableList<Int> = mutableListOf()
array.forEachIndexed { i, row ->
row.forEachIndexed { j, height ->
val left = row.take(j).reversed().takeIf { it.isNotEmpty() }
val l = left?.indexOfFirst { it >= height }?.let { if (it == -1) left.size else it + 1 } ?: 0
val right = row.takeLast(cols - j - 1).takeIf { it.isNotEmpty() }
val r = right?.indexOfFirst { it >= height }?.let { if (it == -1) right.size else it + 1 } ?: 0
val top = columns[j].take(i).reversed().takeIf { it.isNotEmpty() }
val t = top?.indexOfFirst { it >= height }?.let { if (it == -1) top.size else it + 1 } ?: 0
val bottom = columns[j].takeLast(rows - i - 1).takeIf { it.isNotEmpty() }
val b = bottom?.indexOfFirst { it >= height }?.let { if (it == -1) bottom.size else it + 1 } ?: 0
val score = r * l * t * b
scenicScore.add(score)
}
}
return scenicScore.max()
}
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 65188040b3b37c7cb73ef5f2c7422587528d61a4 | 2,582 | advent-of-code-2022 | Apache License 2.0 |
src/main/java/com/ncorti/aoc2021/Exercise14.kt | cortinico | 433,486,684 | false | {"Kotlin": 36975} | package com.ncorti.aoc2021
object Exercise14 {
private fun getInput(): Pair<Map<String, Char>, MutableMap<String, Long>> {
val input = getInputAsTest("14") { split("\n") }
val rules =
input.drop(2).map { it.split(" -> ") }.associate { (key, value) ->
key to value.toCharArray().first()
}
val counts = rules.map { (key, _) -> key to 0L }.toMap().toMutableMap()
input.first().windowed(2).forEach { counts[it] = counts.getOrDefault(it, 0L) + 1 }
return rules to counts
}
private fun runPolymerization(
rules: Map<String, Char>,
initialCounts: MutableMap<String, Long>,
steps: Int
): Long {
var counts = initialCounts
repeat(steps) {
val newCounts = mutableMapOf<String, Long>()
counts.forEach { (pair, count) ->
if (pair in rules && count != 0L) {
val char = rules[pair]!!
val firstPair = pair.toCharArray()[0] + char.toString()
newCounts[firstPair] = newCounts.getOrDefault(firstPair, 0) + count
val secondPair = char + pair.toCharArray()[1].toString()
newCounts[secondPair] = newCounts.getOrDefault(secondPair, 0) + count
}
}
counts = newCounts
}
val alphabet =
counts
.map { (pair, count) -> pair.toCharArray()[1] to count }
.groupingBy { it.first }
.aggregate { _, acc: Long?, (_, count), _ -> (acc ?: 0L) + count }
return alphabet.maxOf { it.value } - alphabet.minOf { it.value }
}
fun part1() = getInput().let { (rules, counts) -> runPolymerization(rules, counts, 10) }
fun part2() = getInput().let { (rules, counts) -> runPolymerization(rules, counts, 40) }
}
fun main() {
println(Exercise14.part1())
println(Exercise14.part2())
}
| 0 | Kotlin | 0 | 4 | af3df72d31b74857201c85f923a96f563c450996 | 1,962 | adventofcode-2021 | MIT License |
src/main/kotlin/Day08.kt | todynskyi | 573,152,718 | false | {"Kotlin": 47697} | fun main() {
fun part1(input: List<String>): Int {
val data: List<List<Int>> = input.map { line ->
line.toCharArray().map { it.toString().toInt() }
}
fun top(rowIndex: Int, colIndex: Int): Boolean {
return (0 until rowIndex).map { data[it][colIndex] }.all { data[rowIndex][colIndex] > it }
}
fun bottom(rowIndex: Int, colIndex: Int): Boolean {
return (rowIndex + 1 until data.size).map { data[it][colIndex] }.all { data[rowIndex][colIndex] > it }
}
fun left(rowIndex: Int, colIndex: Int): Boolean {
return (0 until colIndex).map { data[rowIndex][it] }.all { data[rowIndex][colIndex] > it }
}
fun right(rowIndex: Int, colIndex: Int, size: Int): Boolean {
return (colIndex + 1 until size).map { data[rowIndex][it] }.all { data[rowIndex][colIndex] > it }
}
val convered = data.mapIndexed { rowIndex, row ->
row.mapIndexed { colIndex, value ->
if (rowIndex == 0 || rowIndex == data.size - 1 || colIndex == 0 || colIndex == row.size - 1) {
1
} else {
if (
top(rowIndex, colIndex) ||
bottom(rowIndex, colIndex) ||
left(rowIndex, colIndex) ||
right(rowIndex, colIndex, row.size)
) 1 else 0
}
}
}
return convered.sumOf { it.sum() }
}
fun part2(input: List<String>): Int {
val data: List<List<Int>> = input.map { line ->
line.toCharArray().map { it.toString().toInt() }
}
fun top(rowIndex: Int, colIndex: Int): Int {
val neighborhoods = (rowIndex - 1..0).map { data[it][colIndex] }
val matched = neighborhoods.takeWhile { data[rowIndex][colIndex] > it }.count()
return if (neighborhoods.size > 1 && matched > 0 ) matched + 1 else matched
}
fun bottom(rowIndex: Int, colIndex: Int): Int {
val neighborhoods = (rowIndex + 1 until data.size).map { data[it][colIndex] }
val matched = neighborhoods.takeWhile { data[rowIndex][colIndex] > it }.count()
return if (neighborhoods.size > 1 && matched > 0 ) matched + 1 else matched
}
fun left(rowIndex: Int, colIndex: Int): Int {
val neighborhoods = (colIndex - 1..0).map { data[rowIndex][it] }
val matched = neighborhoods.takeWhile { data[rowIndex][colIndex] > it }.count()
return if (neighborhoods.size > 1 && matched > 0 ) matched + 1 else matched
}
fun right(rowIndex: Int, colIndex: Int, size: Int): Int {
val neighborhoods = (colIndex + 1 until size).map { data[rowIndex][it] }
val matched = neighborhoods.takeWhile { data[rowIndex][colIndex] > it }.count()
return if (neighborhoods.size > 1 && matched > 0 ) matched + 1 else matched
}
val convered = data.mapIndexed { rowIndex, row ->
row.mapIndexed { colIndex, value ->
if (rowIndex == 0 || rowIndex == data.size - 1 || colIndex == 0 || colIndex == row.size - 1) {
0
} else {
Math.max(1, top(rowIndex, colIndex)) *
Math.max(1, bottom(rowIndex, colIndex)) *
Math.max(1, left(rowIndex, colIndex)) *
Math.max(1, right(rowIndex, colIndex, row.size))
}
}
}
return (convered.maxOf { it.max() })
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
println(part2(testInput))
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5f9d9037544e0ac4d5f900f57458cc4155488f2a | 3,932 | KotlinAdventOfCode2022 | Apache License 2.0 |
src/year_2022/day_08/Day08.kt | scottschmitz | 572,656,097 | false | {"Kotlin": 240069} | package year_2022.day_08
import readInput
object Day08 {
/**
* @return
*/
fun solutionOne(text: List<String>): Int {
val forest = parseForest(text)
var visibleCount = text.first().length * 2 + (text.size - 2) * 2
for (i in 1..forest.first().size -2 ) {
for (j in 1..forest[i].size - 2) {
if (isTreeVisible(forest, i, j)) {
visibleCount +=1
}
}
}
return visibleCount
}
/**
* @return
*/
fun solutionTwo(text: List<String>): Int {
val forest = parseForest(text)
var currentMax = 0
forest.forEachIndexed { i, row ->
row.forEachIndexed { j, _ ->
val viewingDistance = calculateViewingDistance(forest, i, j)
if (viewingDistance > currentMax) {
currentMax = viewingDistance
}
}
}
return currentMax
}
private fun parseForest(text: List<String>): List<List<Int>> {
return text.map { line ->
line.toCharArray().map { Integer.parseInt("$it") }
}
}
private fun isTreeVisible(forest: List<List<Int>>, row: Int, column: Int): Boolean {
val treeHeight = forest[row][column]
val visibleFromLeft = forest[row].subList(0, column).max() < treeHeight
val visibleFromRight = forest[row].subList(column + 1, forest[row].size).max() < treeHeight
val columnHeights = forest.map { it[column] }
val visibleFromTop = columnHeights.subList(0, row).max() < treeHeight
val visibleFromBottom = columnHeights.subList(row + 1, columnHeights.size).max() < treeHeight
return visibleFromLeft || visibleFromRight || visibleFromTop || visibleFromBottom
}
private fun calculateViewingDistance(forest: List<List<Int>>, row: Int, column: Int): Int {
val treeHeight = forest[row][column]
var distanceToLeft = 0
for (i in column - 1 downTo 0) {
distanceToLeft += 1
if (treeHeight <= forest[row][i]) {
break
}
}
var distanceToRight = 0
for (i in column + 1 until forest[row].size) {
distanceToRight += 1
if (treeHeight <= forest[row][i]) {
break
}
}
var distanceToTop = 0
for (i in row - 1 downTo 0) {
distanceToTop += 1
if (treeHeight <= forest[i][column]) {
break
}
}
var distanceToBottom = 0
for (i in row + 1 until forest.size) {
distanceToBottom += 1
if (treeHeight <= forest[i][column]) {
break
}
}
return distanceToLeft * distanceToRight * distanceToTop * distanceToBottom
}
}
fun main() {
val inputText = readInput("year_2022/day_08/Day08.txt")
val solutionOne = Day08.solutionOne(inputText)
println("Solution 1: $solutionOne")
val solutionTwo = Day08.solutionTwo(inputText)
println("Solution 2: $solutionTwo")
} | 0 | Kotlin | 0 | 0 | 70efc56e68771aa98eea6920eb35c8c17d0fc7ac | 3,142 | advent_of_code | Apache License 2.0 |
src/com/mrxyx/algorithm/UnionFindAlg.kt | Mrxyx | 366,778,189 | false | null | package com.mrxyx.algorithm
/**
* 并查集 算法
*/
class UnionFindAlg {
/**
* 并查集查询算法
*/
internal class UF(private var count: Int) {
// 存储若干棵树
private val parent = IntArray(count)
// 记录树的“重量”
private val size = IntArray(count)
/**
* 将 p 和 q 连通
* */
fun union(p: Int, q: Int) {
val rootP = find(p)
val rootQ = find(q)
if (rootP == rootQ) return
// 优化点 小树接到大树下面,较平衡
if (size[rootP] > size[rootQ]) {
parent[rootQ] = rootP
size[rootP] += size[rootQ]
} else {
parent[rootP] = rootQ
size[rootQ] += size[rootP]
}
count--
}
/**
* 判断 p 和 q 是否互相连通
*/
fun connected(p: Int, q: Int): Boolean {
val rootP = find(p)
val rootQ = find(q)
// 处于同一棵树上的节点,相互连通
return rootP == rootQ
}
/**
* 返回节点 x 的根节点
*/
private fun find(x: Int): Int {
var x = x
while (parent[x] != x) {
// 优化点 进行路径压缩
parent[x] = parent[parent[x]]
x = parent[x]
}
return x
}
init {
for (i in 0 until count) {
parent[i] = i
size[i] = 1
}
}
}
/**
* 等式方程的可满足性
* https://leetcode-cn.com/problems/satisfiability-of-equality-equations/
* step 1、将equations中的算式根据==和!=分成两部分,
* step 2、 先处理==算式,使得他们通过相等关系各自勾结成门派;
* step 3、 然后处理!=算式,检查不等关系是否破坏了相等关系的连通性。
*/
fun equationsPossible(equations: Array<String>): Boolean {
val uf = UF(26)
for (eq: String in equations) {
if (eq[1] == '=') {
val x = eq[0]
val y = eq[3]
uf.union(x - 'a', y - 'a')
}
}
for (eq: String in equations) {
if (eq[1] == '!') {
val x = eq[0]
val y = eq[3]
//判断是否连通
if (uf.connected(x - 'a', y - 'a')) return false
}
}
return true
}
} | 0 | Kotlin | 0 | 0 | b81b357440e3458bd065017d17d6f69320b025bf | 2,590 | algorithm-test | The Unlicense |
src/main/kotlin/dev/bogwalk/batch4/Problem50.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch4
import dev.bogwalk.util.maths.isPrimeMRBI
import dev.bogwalk.util.maths.primeNumbers
import dev.bogwalk.util.search.binarySearch
/**
* Problem 50: Consecutive Prime Sum
*
* https://projecteuler.net/problem=50
*
* Goal: Return the smallest prime <= N that can be represented as the sum of the longest
* consecutive prime sequence.
*
* Constraints: 2 <= N <= 1e12
*
* e.g.: N = 100
* sum = 41 -> 2 + 3 + 5 + 7 + 11 + 13
* length = 6
*/
class ConsecutivePrimeSum {
// sieve generation of prime numbers is limited by memory
private val sieveLimit = 10_000_000L
/**
* Brute force solution shows that all valid sequences start at low primes, with only a few
* starting as high as the 4th, 8th, or 12th prime.
*
* If the sum of a sequence exceeds the given limit, the next sequence starting from a larger
* prime will be 1 prime longer from where it broke.
*
* SPEED (WORSE) 4.96s for N = 1e10
*
* @return pair of the smallest valid prime to the length of the generating prime sequence.
*/
fun consecutivePrimeSum(n: Long): Pair<Long, Int> {
val limit = minOf(n, sieveLimit).toInt()
val primes = primeNumbers(limit)
val size = primes.size
var smallest = 2L to 1
val maxI = minOf(size, 12)
var maxJ = size
for (i in 0 until maxI) {
for (j in i + smallest.second until maxJ) {
val seqSum = primes.subList(i, j).sumOf { it.toLong() }
if (seqSum > n) {
maxJ = j + 1
break
}
if (
seqSum <= limit && binarySearch(seqSum.toInt(), primes) ||
seqSum.isPrimeMRBI()
) {
val length = j - i
if (length > smallest.second) {
smallest = seqSum to length
}
}
}
}
return smallest
}
/**
* Solution optimised by generating a smaller list of cumulative sums of primes to loop
* through, of which only the last value can exceed the given limit.
*
* Nested loop starts backwards to get the longest sequence sum for each starting prime by
* subtracting cumulative sums, then breaking the internal loop if a valid sequence is found.
*
* SPEED (BETTER) 117.64ms for N = 1e10
*
* @return pair of the smallest valid prime to the length of the generating prime sequence.
*/
fun consecutivePrimeSumImproved(n: Long): Pair<Long, Int> {
val limit = minOf(n, sieveLimit).toInt()
val primes = primeNumbers(limit)
val cumulativeSum = mutableListOf(0L)
for (prime in primes) {
cumulativeSum.add(cumulativeSum.last() + prime)
if (cumulativeSum.last() > n) break
}
val size = cumulativeSum.lastIndex
var smallest = 2L to 1
for (i in 0..size) {
for (j in size downTo i + smallest.second) {
val seqSum = cumulativeSum[j] - cumulativeSum[i]
if (seqSum > n) continue
val length = j - i
if (
length > smallest.second &&
(seqSum <= limit && binarySearch(seqSum.toInt(), primes) ||
seqSum.isPrimeMRBI())
) {
smallest = seqSum to length
break
}
}
}
return smallest
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 3,592 | project-euler-kotlin | MIT License |
Algorithms/src/main/kotlin/MinimumAreaRectangle.kt | ILIYANGERMANOV | 557,496,216 | false | {"Kotlin": 74485} | import kotlin.math.pow
import kotlin.math.sqrt
typealias Point = IntArray
/**
* # Minimum Area Rectangle
*
* _Note: Time Limit Exceeded (not optimal)_
*
* Problem:
* https://leetcode.com/problems/minimum-area-rectangle/
*/
class MinimumAreaRectangle {
fun minAreaRect(points: Array<Point>): Int {
var minArea: Int? = null
chooseFourUnique(points) { a, b, c, d ->
if (parallel(a, b, c, d) && rectangle(a, b, c, d)) {
println("rect: ${a.toList()}, ${b.toList()}, ${c.toList()}, ${d.toList()}")
val area = area(a, b, c, d)
minArea = minArea?.let { minOf(it, area) } ?: area
}
}
return minArea ?: 0
}
private inline fun chooseFourUnique(
points: Array<Point>,
block: (Point, Point, Point, Point) -> Unit
) {
for (a in points) {
for (b in points) {
if (a sameAs b) continue
for (c in points) {
if (a sameAs c || b sameAs c) continue
for (d in points) {
if (a sameAs d || b sameAs d || c sameAs d) continue
block(a, b, c, d)
}
}
}
}
}
private infix fun Point.sameAs(other: Point): Boolean =
x() == other.x() && y() == other.y()
private fun area(
a: Point, b: Point,
c: Point, d: Point
): Int {
val minX = minOf(a.x(), b.x(), c.x(), d.x())
val maxX = maxOf(a.x(), b.x(), c.x(), d.x())
val minY = minOf(a.y(), b.y(), c.y(), d.y())
val maxY = maxOf(a.y(), b.y(), c.y(), d.y())
return (maxX - minX) * (maxY - minY)
}
private fun parallel(
a: Point, b: Point,
c: Point, d: Point,
): Boolean {
val points = arrayOf(a, b, c, d)
if (points.map { it.x() }.toSet().size > 2) return false
if (points.map { it.y() }.toSet().size > 2) return false
return true
}
/**
* Conditions for rectangle:
* - distance(a,b) == distance(c,d)
* - distance(a,c) == distance(b,d)
* - distance(a,d) == distance(b,c)
*
* @return whether four points form an rectangle, note: it might be rotated
*/
private fun rectangle(
a: Point, b: Point,
c: Point, d: Point
): Boolean = distance(a, b) == distance(c, d) &&
distance(a, c) == distance(b, d) &&
distance(a, d) == distance(b, c)
/**
* Formula:
* d=√((x2 – x1)² + (y2 – y1)²)
*/
private fun distance(p1: Point, p2: Point): Double = sqrt(
(p1.x().toDouble() - p2.x()).pow(2.0) +
(p1.y().toDouble() - p2.y()).pow(2.0)
)
private fun IntArray.x() = this[0]
private fun IntArray.y() = this[1]
} | 0 | Kotlin | 0 | 1 | 4abe4b50b61c9d5fed252c40d361238de74e6f48 | 2,847 | algorithms | MIT License |
src/main/kotlin/aoc2023/Day18.kt | Ceridan | 725,711,266 | false | {"Kotlin": 110767, "Shell": 1955} | package aoc2023
class Day18 {
fun part1(input: List<String>): Long {
val instructions = parseInput(input).map { it.instruction }
return calculateInterior(instructions)
}
fun part2(input: List<String>): Long {
val instructions = parseInput(input).map { it.decodeColor() }
return calculateInterior(instructions)
}
private fun calculateInterior(instructions: List<DigInstruction>): Long {
val doubleArea = calculateDoubleArea(instructions)
val border = instructions.sumOf { it.distance }
val inner = calculateInnerPoints(border, doubleArea)
return border + inner
}
// https://en.wikipedia.org/wiki/Pick%27s_theorem
private fun calculateInnerPoints(borderSize: Long, doubleArea: Long): Long = (doubleArea - borderSize + 2) / 2
// https://en.wikipedia.org/wiki/Shoelace_formula
private fun calculateDoubleArea(instructions: List<DigInstruction>): Long {
var detSum = 0L
var point = Point(0, 0)
for (instruction in instructions) {
detSum += when (instruction.direction) {
'R' -> point.y * (-instruction.distance)
'D' -> point.x * instruction.distance
'L' -> point.y * instruction.distance
'U' -> point.x * (-instruction.distance)
else -> throw IllegalArgumentException("Unknown direction ${instruction.direction}")
}
point += instruction.directionAsPoint().scale(instruction.distance.toInt())
}
return detSum
}
private fun parseInput(input: List<String>): List<ColoredDigInstruction> {
val instructions = mutableListOf<ColoredDigInstruction>()
for (instruction in input) {
val (direction, distance, color) = instruction.split(' ')
val digInstruction = DigInstruction(direction.first(), distance.toLong())
instructions.add(ColoredDigInstruction(digInstruction, color.drop(1).dropLast(1)))
}
return instructions
}
data class DigInstruction(val direction: Char, val distance: Long) {
fun directionAsPoint(): Point = when (direction) {
'R' -> 0 to 1
'D' -> 1 to 0
'L' -> 0 to -1
'U' -> -1 to 0
else -> throw IllegalArgumentException("Unknown direction $direction")
}
}
data class ColoredDigInstruction(val instruction: DigInstruction, val color: String) {
fun decodeColor(): DigInstruction {
val distance = color.drop(1).dropLast(1)
val direction = when (color.last()) {
'0' -> 'R'
'1' -> 'D'
'2' -> 'L'
'3' -> 'U'
else -> throw IllegalArgumentException("Unknown direction code ${color.last()}")
}
return DigInstruction(direction, distance.toLong(16))
}
}
}
fun main() {
val day18 = Day18()
val input = readInputAsStringList("day18.txt")
println("18, part 1: ${day18.part1(input)}")
println("18, part 2: ${day18.part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 18b97d650f4a90219bd6a81a8cf4d445d56ea9e8 | 3,122 | advent-of-code-2023 | MIT License |
2021/src/main/kotlin/day17_func.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parser
import utils.Solution
fun main() {
Day17Func.run()
}
object Day17Func : Solution<Day17Func.Rectangle>() {
override val name = "day17"
override val parser = Parser { input ->
val (xeq, yeq) = input.removePrefix("target area: ")
.split(", ")
val (xs, xe) = xeq.removePrefix("x=").split("..").map { it.toInt() }
val (ys, ye) = yeq.removePrefix("y=").split("..").map { it.toInt() }
return@Parser Rectangle(Point(xs, ys), Point(xe, ye))
}
private fun gravity(velocity: Vector) = velocity.copy(y = velocity.y - 1)
private fun drag(velocity: Vector): Vector {
return if (velocity.x > 0) {
velocity.copy(x = velocity.x - 1)
} else if (velocity.x < 0) {
velocity.copy(x = velocity.x + 1)
} else {
velocity
}
}
private fun simulate(position: Point, velocity: Vector, area: Rectangle, highest: Int = position.y): Int? {
val newPosition = position + velocity
if (newPosition in area) {
return highest
}
if (newPosition.y < area.bl.y || newPosition.x > area.tr.x) {
return null
}
return simulate(newPosition, gravity(drag(velocity)), area, maxOf(highest, newPosition.y))
}
override fun part1(input: Rectangle): Int {
val start = Point(0, 0)
val height = (1 .. 100).flatMap {
x -> (1.. 100).map {
y -> Vector(x, y)
}
}
.mapNotNull { simulate(start, it, input) }
.maxOrNull()!!
return height
}
override fun part2(input: Rectangle): Number? {
val start = Point(0, 0)
val heights = (1 .. input.tr.x).flatMap {
x -> (input.bl.y.. 100).map {
y -> Vector(x, y)
}
}
.mapNotNull { simulate(start, it, input) }
return heights.count()
}
data class Point(val x: Int, val y: Int) {
operator fun plus(v: Vector) = copy(x = x + v.x, y = y + v.y)
}
data class Vector(val x: Int, val y: Int)
data class Rectangle(val bl: Point, val tr: Point) {
operator fun contains(point: Point): Boolean {
return point.x in (bl.x .. tr.x) && point.y in (bl.y .. tr.y)
}
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 2,121 | aoc_kotlin | MIT License |
gcj/y2022/round2/c_small.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package gcj.y2022.round2
private fun solve(): String {
val n = readInt()
val kids = List(n) { readInts() }
val sweets = List(n + 1) { readInts() }
fun sqr(x: Int) = x.toLong() * x
fun dist(i: Int, j: Int) = sqr(kids[i][0] - sweets[j][0]) + sqr(kids[i][1] - sweets[j][1])
val dist = List(n) { i -> LongArray(n + 1) { j -> dist(i, j) } }
val can = BooleanArray(1 shl (2 * n + 1))
val howMask = IntArray(1 shl (2 * n + 1))
val howI = IntArray(1 shl (2 * n + 1))
val howJ = IntArray(1 shl (2 * n + 1))
val maskInit = 1 shl n
can[maskInit] = true
val maxMaskKids = maskInit - 1
for (mask in can.indices) {
val maskKids = mask and maxMaskKids
val maskSweets = mask and maxMaskKids.inv()
val m = maskKids.countOneBits()
if (maskSweets.countOneBits() != m + 1 || m == 0) continue
for (i in 0 until n) {
if (!mask.hasBit(i)) continue
var minDist = Long.MAX_VALUE
for (j in 0..n) {
if (!mask.hasBit(n + j)) continue
minDist = minOf(minDist, dist[i][j])
}
for (j in 0..n) {
if (j == 0 || !mask.hasBit(n + j) || dist[i][j] != minDist) continue
val newMask = mask xor (1 shl i) xor (1 shl (n + j))
if (can[newMask]) {
can[mask] = true
howMask[mask] = newMask
howI[mask] = i
howJ[mask] = j
}
}
}
}
var mask = can.lastIndex
if (!can[mask]) return "IMPOSSIBLE"
val ans = mutableListOf<String>()
while (mask != maskInit) {
ans.add("${howI[mask] + 1} ${howJ[mask] + 1}")
mask = howMask[mask]
}
return "POSSIBLE\n" + ans.joinToString("\n")
}
fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
private fun Int.bit(index: Int) = shr(index) and 1
private fun Int.hasBit(index: Int) = bit(index) != 0
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,886 | competitions | The Unlicense |
src/Day04.kt | riFaulkner | 576,298,647 | false | {"Kotlin": 9466} | fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { assignments ->
val assignmentPair = getAssignmentPair(assignments)
isFullyInclusivePair(assignmentPair)
}
}
fun part2(input: List<String>): Int {
return input.sumOf { assignments ->
val assignmentPair = getAssignmentPair(assignments)
hasOverlap(assignmentPair)
}
}
val testInput = readInput("inputs/Day04-example")
part1(testInput).println()
part2(testInput).println()
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("inputs/Day04")
part1(input).println()
part2(input).println()
}
fun hasOverlap(assignmentPair: Pair<String, String>): Int {
// if the aLow is > bHigh or if aHigh is < bLow
val (aLow, aHigh) = assignmentPair.first.splitToInts("-")
val (bLow, bHigh) = assignmentPair.second.splitToInts("-")
if (aLow > bHigh || aHigh < bLow) {
return 0
}
return 1
}
fun isFullyInclusivePair(assignmentPair: Pair<String, String>): Int {
if (pairAContainsB(assignmentPair.first, assignmentPair.second) || pairAContainsB(assignmentPair.second, assignmentPair.first)){
return 1
}
return 0
}
fun getAssignmentPair(fullAssignment: String): Pair<String, String> {
val (a, b) = fullAssignment.split(",")
return a to b
}
fun pairAContainsB(a: String, b: String): Boolean {
val (aLow, aHigh) = a.splitToInts("-")
val (bLow, bHigh) = b.splitToInts("-")
if (aLow <= bLow) {
if (bHigh <= aHigh) {
return true
}
}
return false
}
fun String.splitToInts(delimiter: String) = run { this.split(delimiter).map { it.toInt() }.toList() } | 0 | Kotlin | 0 | 0 | 33ca7468e17c47079fe2e922a3b74fd0887e1b62 | 1,766 | aoc-kotlin-2022 | Apache License 2.0 |
src/aoc2022/day11/AoC11.kt | Saxintosh | 576,065,000 | false | {"Kotlin": 30013} | package aoc2022.day11
import readLines
var isDivisor = true
var allDivisor = 1L
class Monkey(
private val items: MutableList<Long>,
val op: (Long) -> Long,
val divisor: Long,
val test: (Long) -> Int,
) {
var inspection = 0L
fun round(monkeys: List<Monkey>) {
items.forEach { item ->
inspection++
var wl = op(item)
if (isDivisor)
wl /= 3
wl %= allDivisor
val target = test(wl % divisor)
monkeys[target].items.add(wl)
}
items.clear()
}
}
fun parse(list: List<String>): List<Monkey> {
val l = list.windowed(7, 7, true).map { rows ->
val rWords = rows.map { it.trim().split(" ") }
val items = rWords[1].drop(2).map { it.removeSuffix(",").toLong() }.toMutableList()
val opConst = rWords[2][5].toLongOrNull()
val op: (Long) -> Long = when (rWords[2][4]) {
"+" -> {
{ it + (opConst ?: it) }
}
"*" -> {
{ it * (opConst ?: it) }
}
else -> throw Exception("Unexpected")
}
val divisor = rWords[3][3].toLong()
val m1 = rWords[4].last().toInt()
val m2 = rWords[5].last().toInt()
val test: (Long) -> Int = { if (it == 0L) m1 else m2 }
Monkey(items, op, divisor, test)
}
allDivisor = l.fold(1L) { d, m -> d * m.divisor }
return l
}
fun main() {
fun part1(lines: List<String>): Long {
val monkeys = parse(lines)
repeat(20) {
monkeys.forEach { it.round(monkeys) }
}
val (m1, m2) = monkeys.sortedBy { it.inspection }.takeLast(2)
return m1.inspection * m2.inspection
}
fun part2(lines: List<String>): Long {
isDivisor = false
val monkeys = parse(lines)
repeat(10000) {
monkeys.forEach { it.round(monkeys) }
}
val (m1, m2) = monkeys.sortedBy { it.inspection }.takeLast(2)
return m1.inspection * m2.inspection
}
readLines(10605L, 2713310158L, ::part1, ::part2)
} | 0 | Kotlin | 0 | 0 | 877d58367018372502f03dcc97a26a6f831fc8d8 | 1,772 | aoc2022 | Apache License 2.0 |
src/main/kotlin/cc/stevenyin/leetcode/_0150_EvaluateReversePolishNotation.kt | StevenYinKop | 269,945,740 | false | {"Kotlin": 107894, "Java": 9565} | package cc.stevenyin.leetcode
import java.util.*
/**
* https://leetcode.com/problems/evaluate-reverse-polish-notation/
* You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation (http://en.wikipedia.org/wiki/Reverse_Polish_notation).
*
* Evaluate the expression. Return an integer that represents the value of the expression.
*
* Note that:
*
* The valid operators are '+', '-', '*', and '/'.
* Each operand may be an integer or another expression.
* The division between two integers always truncates toward zero.
* There will not be any division by zero.
* The input represents a valid arithmetic expression in a reverse polish notation.
* The answer and all the intermediate calculations can be represented in a 32-bit integer.
*
*
* Example 1:
*
* Input: tokens = ["2","1","+","3","*"]
* Output: 9
* Explanation: ((2 + 1) * 3) = 9
* Example 2:
*
* Input: tokens = ["4","13","5","/","+"]
* Output: 6
* Explanation: (4 + (13 / 5)) = 6
* Example 3:
*
* Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
* Output: 22
* Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
* = ((10 * (6 / (12 * -11))) + 17) + 5
* = ((10 * (6 / -132)) + 17) + 5
* = ((10 * 0) + 17) + 5
* = (0 + 17) + 5
* = 17 + 5
* = 22
*
*
* Constraints:
*
* 1 <= tokens.length <= 104
* tokens[i] is either an operator: "+", "-", "*", or "/", or an integer in the range [-200, 200].
*/
class _0150_EvaluateReversePolishNotation {
fun evalRPN(tokens: Array<String>): Int {
val stack: Stack<Int> = Stack()
tokens.forEach {
when {
it in arrayOf("+", "-", "*", "/") -> stack.push(applyOperation(it, stack.pop(), stack.pop()))
else -> stack.push(it.toInt())
}
}
return stack.pop()
}
private fun applyOperation(op: String, first: Int, second: Int) = when(op) {
"+" -> second + first
"-" -> second - first
"*" -> second * first
"/" -> second / first
else -> 0
}
}
fun main() {
val solution = _0150_EvaluateReversePolishNotation()
println(solution.evalRPN(arrayOf("4","13","5","/","+")))
}
| 0 | Kotlin | 0 | 1 | 748812d291e5c2df64c8620c96189403b19e12dd | 2,225 | kotlin-demo-code | MIT License |
aoc-2023/src/main/kotlin/nerok/aoc/aoc2023/day06/Day06.kt | nerok | 572,862,875 | false | {"Kotlin": 113337} | package nerok.aoc.aoc2023.day06
import nerok.aoc.utils.Input
import kotlin.time.DurationUnit
import kotlin.time.measureTime
fun main() {
fun distances(time: Long): List<Long> {
val returnList = emptyList<Long>().toMutableList()
for (i in 0..time) {
returnList.add((time-i) * i)
}
return returnList
}
fun part1(input: List<String>): Long {
val times = input.first().removePrefix("Time:").split(" ").filter { it.isNotBlank() }.map { it.toLong() }
val distance = input.last().removePrefix("Distance:").split(" ").filter { it.isNotBlank() }.map { it.toLong() }
return times.zip(distance).map { game -> distances(game.first).filter { it > game.second }.size}.reduce { acc, i -> acc * i }.toLong()
}
fun part2(input: List<String>): Long {
val times = input.first().removePrefix("Time:").filterNot { it.isWhitespace() }.map { it.digitToInt().toLong() }.reduce { acc: Long, l: Long -> (acc * 10) + l }
val distance = input.last().removePrefix("Distance:").filterNot { it.isWhitespace() }.map { it.digitToInt().toLong() }.reduce { acc: Long, l: Long -> (acc * 10) + l }
val distanceList = distances(times)
return distanceList.filter { it > distance }.size.toLong()
}
// test if implementation meets criteria from the description, like:
val testInput = Input.readInput("Day06_test")
check(part1(testInput) == 288L)
check(part2(testInput) == 71503L)
val input = Input.readInput("Day06")
println("Part1:")
println(measureTime { println(part1(input)) }.toString(DurationUnit.SECONDS, 3))
println("Part2:")
println(measureTime { println(part2(input)) }.toString(DurationUnit.SECONDS, 3))
}
| 0 | Kotlin | 0 | 0 | 7553c28ac9053a70706c6af98b954fbdda6fb5d2 | 1,742 | AOC | Apache License 2.0 |
y2017/src/main/kotlin/adventofcode/y2017/Day20.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2017
import adventofcode.io.AdventSolution
import kotlin.math.abs
fun main()
{
Day20.solve()
}
object Day20 : AdventSolution(2017, 20, "Particle Swarm")
{
//this comparator is not correct, but works for my input :S
override fun solvePartOne(input: String): Int
{
val particles: List<Particle> = parse(input)
val nearestParticle = particles.minByOrNull { it.acceleration.magnitude }
return particles.indexOf(nearestParticle)
}
override fun solvePartTwo(input: String): Int
{
var particles: List<Particle> = parse(input)
//1000 is just a guess
repeat(1000) {
particles = particles.groupBy(Particle::position)
.values
.mapNotNull(List<Particle>::singleOrNull)
.map(Particle::tick)
}
return particles.size
}
}
private fun parse(input: String): List<Particle>
{
return input.splitToSequence(',', '\n')
.map { it.filter { it in "-0123456789" }.toInt() }
.chunked(3) { (x, y, z) -> Vector(x, y, z) }
.chunked(3) { (p, v, a) -> Particle(p, v, a) }
.toList()
}
data class Particle(
val position: Vector,
val velocity: Vector,
val acceleration: Vector
)
{
fun tick(): Particle = Particle(
position + velocity + acceleration,
velocity + acceleration,
acceleration
)
}
data class Vector(val x: Int, val y: Int, val z: Int)
{
operator fun plus(v: Vector) = Vector(x + v.x, y + v.y, z + v.z)
val magnitude get() = sequenceOf(x, y, z).map(::abs).sum()
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,614 | advent-of-code | MIT License |
2021/src/day19/Day19.kt | Bridouille | 433,940,923 | false | {"Kotlin": 171124, "Go": 37047} | package day19
import readInput
import java.lang.Math.abs
import java.util.*
import kotlin.math.pow
typealias BeaconPairList = List<Pair<Pair<Point, Point>, Pair<Point, Point>>>
data class Point(val x: Int, val y: Int, val z: Int) {
override fun toString() = "($x,$y,$z)"
// https://stackoverflow.com/questions/16452383/how-to-get-all-24-rotations-of-a-3-dimensional-array
private fun roll(p: Point) = Point(p.x, p.z, -p.y)
private fun turn(p: Point) = Point(-p.y, p.x, p.z)
fun permutations(): List<Point> {
val res = mutableListOf<Point>()
var p = this
for (cycle in 1..2) {
for (step in 1..3) {
p = roll(p)
res.add(p)
for (i in 1..3) {
p = turn(p)
res.add(p)
}
}
p = roll(turn(roll(p)))
}
return res
}
fun dist(other: Point) : Long {
return ((other.x - x).toFloat().pow(2) + (other.y - y).toFloat().pow(2) + (other.z - z).toFloat().pow(2)).toLong()
}
fun plus(other: Point) = Point(x + other.x, y + other.y, z + other.z)
fun minus(other: Point) = Point(x - other.x, y - other.y, z - other.z)
fun absolut() = Point(abs(x), abs(y), abs(z))
}
data class Scanner(val id: Int, var scans: List<Point>, var pos: Point? = null, var rotationIdx: Int? = null) {
fun manhattan(other: Scanner) = pos?.let {
other.pos?.let { otherPos ->
(it.x - otherPos.x) + (it.y - otherPos.y) + (it.z - otherPos.z)
} ?: -1
} ?: -1
}
fun List<String>.toScanners() : List<Scanner> {
val scanners = mutableListOf<Scanner>()
val listOfPoints = mutableListOf<Point>()
for (line in this.drop(1)) {
if (line.startsWith("--- scanner")) {
scanners.add(Scanner(scanners.size, mutableListOf<Point>().apply { addAll(listOfPoints) }))
listOfPoints.clear()
} else {
val coord = line.split(",").map { it.toInt() }
listOfPoints.add(Point(coord[0], coord[1], coord[2]))
}
}
scanners.add(Scanner(scanners.size, listOfPoints))
return scanners
}
/**
* Gets a list of fingerprints of all pairs of points in the given list
*/
fun getListOfFingerprints(beacons: List<Point>) : Map<Long, Pair<Point, Point>> {
val distances = mutableMapOf<Long, Pair<Point, Point>>()
for (i in beacons.indices) {
for (j in i+1 until beacons.size) {
val p1 = beacons[i]
val p2 = beacons[j]
val fingerprint = p1.absolut().dist(p2.absolut())
distances[fingerprint] = Pair(p1, p2)
}
}
return distances
}
/**
* From a list of fingerprints, return a list of pairs of pairs of points which have the same fingerprint
*/
fun getCommonBeacons(fingerprintsFromS1: Map<Long, Pair<Point, Point>>, s2Beacons: List<Point>): BeaconPairList {
val pairOfPoints = mutableListOf<Pair<Pair<Point, Point>, Pair<Point, Point>>>()
for (i in s2Beacons.indices) {
for (j in i+1 until s2Beacons.size) {
val p1 = s2Beacons[i]
val p2 = s2Beacons[j]
val fingerprint = p1.absolut().dist(p2.absolut())
if (fingerprintsFromS1.containsKey(fingerprint)) {
pairOfPoints.add(Pair(fingerprintsFromS1[fingerprint]!!, Pair(p1, p2)))
}
}
}
return pairOfPoints
}
fun findScannerPosition(commonBeacon: BeaconPairList, rotationIdx: Int): Point {
val listOfDiffs = mutableListOf<Point>()
for (pair in commonBeacon) {
val pair1 = pair.first
val pair2 = pair.second
val pair2Rotated = Pair(pair2.first.permutations()[rotationIdx], pair2.second.permutations()[rotationIdx])
val vecA = pair1.first.plus(pair1.second)
val vecB = pair2Rotated.first.plus(pair2Rotated.second)
listOfDiffs.add(vecA.minus(vecB))
}
return listOfDiffs.groupingBy { it }.eachCount().toList().sortedByDescending { it.second }.map {
Point(it.first.x / 2, it.first.y / 2, it.first.z / 2)
}.first()
}
/**
* For each pair, tries to rotate the second pair (point1 & point2)
* make a vector from p1 -> p2 and compare the distance
*/
fun findRotationIdx(commonBeacon: BeaconPairList): Int {
val aligned = mutableMapOf<Int, MutableList<Long>>()
for (i in 0 until 24) {
for (pair in commonBeacon) {
val firstPair = pair.first
val secondPair = pair.second
val p1 = secondPair.first.permutations()[i]
val p2 = secondPair.second.permutations()[i]
val vec1 = p1.plus(p2)
val vec2 = firstPair.first.plus(firstPair.second)
val dist = vec1.dist(vec2)
if (!aligned.containsKey(i)) {
aligned[i] = mutableListOf()
}
aligned[i]?.add(dist)
}
}
return aligned.toList().map {
it.first to it.second.groupingBy { it }.eachCount().toList().maxByOrNull { it.second }!!.second
}.maxByOrNull { it.second }!!.first
}
data class ScanOverlap(val commonBeacons: BeaconPairList, val scanner: Scanner)
fun findCommonBeacons(scanners: List<Scanner>): Set<Point> {
// Always process the scanners that have the most overlaps
val overlaps = PriorityQueue<ScanOverlap> { a, b ->
b.commonBeacons.size - a.commonBeacons.size
}
scanners.first().pos = Point(0, 0, 0)
val points = mutableSetOf<Point>().apply { addAll(scanners.first().scans) }
val matched = mutableListOf<Int>().apply { add(scanners.first().id) }
while (matched.size < scanners.size) {
for (scanner in scanners) {
if (matched.contains(scanner.id)) continue
val fingerPrints = getListOfFingerprints(points.toList())
val commonBeacons = getCommonBeacons(fingerPrints, scanner.scans)
overlaps.add(ScanOverlap(commonBeacons, scanner))
}
val mostOverlap = overlaps.remove()
val rotationIdx = findRotationIdx(mostOverlap.commonBeacons)
val scannerPos = findScannerPosition(mostOverlap.commonBeacons, rotationIdx)
// Translate the points of the scanner in our initial referencial
scanners.find { it.id == mostOverlap.scanner.id }!!.scans = mostOverlap.scanner.scans.map {
it.permutations()[rotationIdx].plus(scannerPos)
}
scanners.find { it.id == mostOverlap.scanner.id }!!.pos = scannerPos
points.addAll(mostOverlap.scanner.scans) // add the translated points into our global point pool
matched.add(mostOverlap.scanner.id)
overlaps.clear()
}
return points
}
fun part1(lines: List<String>) = findCommonBeacons(lines.toScanners()).size
fun part2(lines: List<String>) : Int {
val scanners = lines.toScanners()
findCommonBeacons(scanners)
var maxDist = Integer.MIN_VALUE
for (i in scanners.indices) {
for (j in i+1 until scanners.size) {
maxDist = maxOf(maxDist, scanners[i].manhattan(scanners[j]))
}
}
return maxDist
}
fun main() {
val testInput = readInput("day19/test")
println("part1(testInput) => " + part1(testInput))
println("part2(testInput) => " + part2(testInput))
val input = readInput("day19/input")
println("part1(input) => " + part1(input))
println("part2(input) => " + part2(input))
}
| 0 | Kotlin | 0 | 2 | 8ccdcce24cecca6e1d90c500423607d411c9fee2 | 7,395 | advent-of-code | Apache License 2.0 |
src/Day07.kt | zhiqiyu | 573,221,845 | false | {"Kotlin": 20644} | import kotlin.math.min
class InputParser(var input: List<String>, var root: DirTree) {
var cursor: DirTree
init {
cursor = root
}
fun parse() {
for (line in input) {
if (line.startsWith('$')) {
// command
var commands = line.split(" ")
if (commands.get(1) == "cd") {
when (commands.get(2)) {
".." -> cursor = cursor.parent!!
"/" -> cursor = root.members.get("/")!!
else -> cursor = cursor.members.get(commands.get(2))!!
}
}
} else {
var parts = line.split(" ")
assert(parts.size == 2)
if (!cursor.members.containsKey(parts.get(1))) {
if (parts.get(0) == "dir") {
cursor.addMember(DirTree(parts.get(1), 0, cursor))
} else {
cursor.addMember(DirTree(parts.get(1), parts.get(0).toInt(), cursor))
}
}
}
}
}
}
class DirTree(var name: String, var size: Int, var parent: DirTree?) {
var members: MutableMap<String, DirTree>
init {
members = HashMap<String, DirTree>()
}
fun addMember(item: DirTree) {
members.put(item.name, item)
}
fun calculateSize(): Int {
if (size > 0) {
return size
}
var result = 0
for (dir in members.values) {
result += dir.calculateSize()
}
size = -1 * result
return result
}
fun print(numSpaces: Int = 0): String {
var result = " ".repeat(numSpaces).plus("- ${name} (${if (size <= 0) "dir, size=".plus(size) else "file, size=".plus(size)})").plus("\n")
for (dir in members.values) {
result += dir.print(numSpaces+2)
}
return result
}
}
fun main() {
var result = 0
var result2 = Int.MAX_VALUE
var spaceNeeded = Int.MAX_VALUE
fun traverse(root: DirTree) {
if (root.size <= 0 && root.size >= -100000) {
result += -root.size
}
if (root.size <= 0 && root.size <= -spaceNeeded) {
result2 = min(result2, -root.size)
}
for (dir in root.members.values) {
if (dir.size <= 0) {
traverse(dir)
}
}
}
fun solution(input: List<String>) {
result = 0
result2 = Int.MAX_VALUE
var tree = DirTree("root", 0, null)
tree.addMember(DirTree("/", 0, tree))
var parser = InputParser(input, tree)
parser.parse()
tree.calculateSize()
spaceNeeded = 30000000 - (70000000 + tree.size)
// print(tree.print())
traverse(tree)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
solution(testInput)
check(result == 95437)
check(result2 == 24933642)
val input = readInput("Day07")
solution(input)
println("----------")
println(result)
println(result2)
}
| 0 | Kotlin | 0 | 0 | d3aa03b2ba2a8def927b94c2b7731663041ffd1d | 3,174 | aoc-2022 | Apache License 2.0 |
2022/src/test/kotlin/Day15.kt | jp7677 | 318,523,414 | false | {"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338} | import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import kotlin.math.absoluteValue
import kotlin.math.max
import kotlin.math.min
private data class Position15(val x: Int, val y: Int)
private data class Sensor(val position: Position15, val beacon: Position15) {
val distanceToBeacon: Int = (position.x - beacon.x).absoluteValue + (position.y - beacon.y).absoluteValue
fun knownRange(y: Int): IntRange? {
val distanceY = (this.position.y - y).absoluteValue
if (distanceY > distanceToBeacon) return null
val x1 = this.position.x - (distanceToBeacon - distanceY)
val x2 = this.position.x + (distanceToBeacon - distanceY)
return min(x1, x2)..max(x1, x2)
}
}
class Day15 : StringSpec({
"puzzle part 01" {
val sensors = getSensors().toList()
val row = 2000000
val knownRangeAtRow = sensors.mapNotNull { it.knownRange(row) }
val beaconsInRow = sensors.map { it.beacon }.toSet().count { it.y == row }
val countOfKnownAtRow = ((knownRangeAtRow.minOf { it.first })..(knownRangeAtRow.maxOf { it.last }))
.count { y -> knownRangeAtRow.any { y in it } }
val positionsAtRowWithoutBeacon = countOfKnownAtRow - beaconsInRow
positionsAtRowWithoutBeacon shouldBe 5832528
}
"puzzle part 02" {
val sensors = getSensors().toList()
val boundary = 4000000
val frequency = (0..boundary).firstNotNullOf { y ->
sensors.mapNotNull { it.knownRange(y) }
.map { max(it.first, 0)..min(it.last, boundary) }
.missing()
?.let { x -> x * 4000000 + y }
}
frequency shouldBe 13360899249595
}
})
private fun List<IntRange>.missing(): Long? = this.sortedBy { it.first }
.fold(0L) { acc, it ->
if (it.first > acc + 1) return acc + 1
max(acc, it.last.toLong())
}.let { null }
private val re = "x=(-?\\d+), y=(-?\\d+)".toRegex()
private fun getSensors() = getPuzzleInput("day15-input.txt").map { line ->
re.findAll(line).let { m ->
Sensor(
Position15(m.first().groupValues[1].toInt(), m.first().groupValues[2].toInt()),
Position15(m.last().groupValues[1].toInt(), m.last().groupValues[2].toInt())
)
}
}
| 0 | Kotlin | 1 | 2 | 8bc5e92ce961440e011688319e07ca9a4a86d9c9 | 2,309 | adventofcode | MIT License |
src/main/kotlin/aoc2023/Day11.kt | Ceridan | 725,711,266 | false | {"Kotlin": 110767, "Shell": 1955} | package aoc2023
import kotlin.math.abs
class Day11 {
fun part1(input: String): Long = calculateDistances(input, 2)
fun part2(input: String, expansionModifier: Int): Long = calculateDistances(input, expansionModifier)
private fun calculateDistances(input: String, expansionModifier: Int = 2): Long {
val galaxies = parseInput(input, expansionModifier)
var distances = 0L
for (i in 0..<galaxies.size - 1) {
for (j in i + 1..<galaxies.size) {
val (yi, xi) = galaxies[i]
val (yj, xj) = galaxies[j]
distances += abs(yi - yj) + abs(xi - xj)
}
}
return distances
}
private fun parseInput(input: String, expansionModifier: Int = 2): List<Point> {
val lines = input.split('\n')
val galaxyPoints = mutableListOf<Point>()
for (y in lines.indices) {
val chars = lines[y].toCharArray()
for (x in chars.indices) {
if (chars[x] == '#') {
galaxyPoints.add(y to x)
}
}
}
val emptyRows = IntRange(0, lines.size - 1).subtract(galaxyPoints.map { it.y }.toSet())
val emptyCols = IntRange(0, lines[0].length - 1).subtract(galaxyPoints.map { it.x }.toSet())
return galaxyPoints.map { galaxyPoint ->
val (y, x) = galaxyPoint
val rowsBefore = emptyRows.count { it < y }
val colsBefore = emptyCols.count { it < x }
Pair(y + rowsBefore * (expansionModifier - 1), x + colsBefore * (expansionModifier - 1))
}.toList()
}
}
fun main() {
val day11 = Day11()
val input = readInputAsString("day11.txt")
println("11, part 1: ${day11.part1(input)}")
println("11, part 2: ${day11.part2(input, 1000000)}")
}
| 0 | Kotlin | 0 | 0 | 18b97d650f4a90219bd6a81a8cf4d445d56ea9e8 | 1,834 | advent-of-code-2023 | MIT License |
src/Day03.kt | yalematta | 572,668,122 | false | {"Kotlin": 8442} |
fun main() {
fun findCommonItems(sacks: List<String>): Set<Char> {
return sacks
.map { it.toSet() }
.reduce { init, item -> init.intersect(item) }
}
fun getPriority(commonChars: Set<Char>): Int {
val items = ('a'..'z') + ('A'..'Z')
var priority = 0
commonChars.forEach { char ->
priority += items.indexOf(char) + 1
}
return priority
}
fun part1(input: List<String>): Int {
var priority = 0
input.forEach { rucksack ->
val length: Int = rucksack.length
val firstComp: String = rucksack.substring(0, length / 2)
val secondComp: String = rucksack.substring(length / 2)
val commonItems = findCommonItems(listOf(firstComp, secondComp))
priority += getPriority(commonItems)
}
return priority
}
fun part2(input: List<String>): Int {
val windowSize = 3
var priority = 0
val groups = input.windowed(size = windowSize, step = windowSize)
groups.forEach { sacks ->
val unique = findCommonItems(sacks)
priority += getPriority(unique)
}
return priority
}
// 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 | 2b43681cc2bd02e4838b7ad1ba04ff73c0422a73 | 1,501 | advent-of-code-2022 | Apache License 2.0 |
src/Day07.kt | zodiia | 573,067,225 | false | {"Kotlin": 11268} | package day07
import readInput
enum class FsNodeType { FILE, DIR }
data class FsNode(
var size: Long,
val type: FsNodeType,
val childNodes: HashMap<String, FsNode> = HashMap(),
) {
fun getNode(path: ArrayDeque<String>): FsNode {
if (path.size == 0) {
return this
}
return childNodes[path.first()]?.getNode(ArrayDeque(path).also { it.removeFirst() }) ?: throw IllegalStateException()
}
fun calculateSize(): Long {
if (!(size == 0L && childNodes.size > 0)) {
return size
}
size = childNodes.map { it.value.calculateSize() }.sum()
return size
}
}
fun main() {
fun parseFiles(input: List<String>): FsNode {
val rootNode = FsNode(0L, FsNodeType.DIR)
var cwd = ArrayDeque<String>()
input.forEach { line ->
if (line.startsWith("$ cd ")) {
when (line.substring(5)) {
"/" -> cwd = ArrayDeque()
".." -> cwd.removeLast()
else -> cwd.addLast(line.substring(5))
}
} else if (!line.startsWith("$")) {
val parts = line.split(' ')
val type = if (parts[0] == "dir") FsNodeType.DIR else FsNodeType.FILE
rootNode.getNode(cwd).childNodes[parts[1]] = FsNode(parts[0].toLongOrNull() ?: 0L, type)
}
}
rootNode.calculateSize()
return rootNode
}
fun getSumOfDirSizes(node: FsNode, maxSize: Long): Long {
var res = node.childNodes
.filter { it.value.type == FsNodeType.DIR }
.map { getSumOfDirSizes(it.value, maxSize) }
.sum()
if (node.size <= maxSize) {
res += node.size
}
return res
}
fun getSmallestDirOfAtLeast(node: FsNode, minSize: Long): Long {
val res = node.childNodes
.filter { it.value.type == FsNodeType.DIR }
.map { getSmallestDirOfAtLeast(it.value, minSize) }
.minOrNull() ?: Long.MAX_VALUE
if (node.size in minSize until res) {
return node.size
}
return res
}
fun part1(input: List<String>): Long {
return getSumOfDirSizes(parseFiles(input), 100000)
}
fun part2(input: List<String>): Long {
val root = parseFiles(input)
return getSmallestDirOfAtLeast(root, root.size - 40000000)
}
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 4f978c50bb7603adb9ff8a2f0280f8fdbc652bf2 | 2,528 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/aoc2021/Day03.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2021
import readInput
import kotlin.math.ceil
/**
* Given a list of binary numbers, this method creates a binary number by selecting the most common bit at each position
* of the input numbers
*
* @param input a list of equally width binary numbers as string
* @return a string representation of the binary number constructed of the most common bits of each of the input numbers
* for each position
*/
private fun getMostCommonBits(input: List<String>): String {
val bits = input.first().length
val maxIndex = bits - 1
// count how often each bit is set
val setBits = IntArray(bits)
input.map { it.toInt(2) }.forEach {
for (i in 0..maxIndex) {
setBits[i] += (it shr maxIndex - i) and 1
}
}
val threshold = ceil(input.size / 2f)
return buildString {
setBits.withIndex().forEach {
when {
it.value >= threshold -> append(1)
else -> append(0)
}
}
}
}
/**
* @return for a string representing a binary number, this method returns a new string with each bit flipped
*/
private fun String.inv() = this.replace("1", "3").replace("0", "1").replace("3", "0")
/**
* Iteratively shrinks the given input list by applying a filter function on all elements, until only one element remains
*
* @param input the input list to shrink
* @param filter the filter function to apply in each iteration. Input for the filter function is the currently selected
* bit of an input number and the most common bit for that position among all remaining input numbers
* @return the element passing the most filters
*/
private fun shrinkList(input: List<String>, filter: (Char, Char) -> Boolean): String {
var filteredList = input
var currentBit = 0
while (filteredList.size > 1) {
val mostCommonBits = getMostCommonBits(filteredList)
filteredList = filteredList.filter { filter(it[currentBit], mostCommonBits[currentBit]) }
currentBit++
}
return filteredList.first()
}
private fun part1(input: List<String>): Int {
val mostCommonBits = getMostCommonBits(input)
val gamma = mostCommonBits.toInt(2)
val epsilon = mostCommonBits.inv().toInt(2)
return gamma * epsilon
}
private fun part2(input: List<String>): Int {
val oxygen = shrinkList(input) { c1, c2 -> c1 == c2 }.toInt(2)
val co2 = shrinkList(input) { c1, c2 -> c1 != c2 }.toInt(2)
return oxygen * co2
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 198)
check(part2(testInput) == 230)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 2,782 | adventOfCode | Apache License 2.0 |
src/main/kotlin/problems/Day22.kt | PedroDiogo | 432,836,814 | false | {"Kotlin": 128203} | package problems
class Day22(override val input: String) : Problem {
override val number: Int = 22
private val inputRegex = """(on|off) x=(-?\d*)..(-?\d*),y=(-?\d*)..(-?\d*),z=(-?\d*)..(-?\d*)""".toRegex()
private val intervals = input.lines()
.map { inputRegex.find(it)!!.groupValues.drop(1) }
.map {
Pair(
it[0],
listOf(it[1].toInt()..it[2].toInt(), it[3].toInt()..it[4].toInt(), it[5].toInt()..it[6].toInt())
)
}
override fun runPartOne(): String {
val intervalsInRange = intervals.filter { interval -> interval.second.all { axis -> axis in (-50..50) } }
return onCubes(intervalsInRange)
.sumOf { it[0].count() * it[1].count() * it[2].count() }
.toString()
}
override fun runPartTwo(): String {
return onCubes(intervals)
.sumOf { 1L * it[0].count() * it[1].count() * it[2].count() }
.toString()
}
private fun onCubes(inputs: List<Pair<String, List<IntRange>>>): List<List<IntRange>> {
val currentIntervals = mutableListOf<List<IntRange>>()
val toVisit = inputs.toMutableList()
while (toVisit.isNotEmpty()) {
val (type, interval) = toVisit.removeAt(0)
val firstOverlap = currentIntervals.firstOrNull { currentInterval ->
currentInterval[0] in interval[0]
&& currentInterval[1] in interval[1]
&& currentInterval[2] in interval[2]
}
if (firstOverlap != null) {
val intervalSplitByOverlapPlanes = splitCubeByCubesPlanes(interval, firstOverlap)
if (type == "on") {
val nonOverlappingCubes =
intervalSplitByOverlapPlanes.filter { !(it[0] in firstOverlap[0] && it[1] in firstOverlap[1] && it[2] in firstOverlap[2]) }
toVisit.addAll(0, nonOverlappingCubes.map { Pair(type, it) })
} else {
val overlapSplitByIntervalPlanes = splitCubeByCubesPlanes(firstOverlap, interval)
val overlapIntervalMinusOff = overlapSplitByIntervalPlanes - intervalSplitByOverlapPlanes
currentIntervals.remove(firstOverlap)
currentIntervals.addAll(overlapIntervalMinusOff)
toVisit.add(0, Pair(type, interval))
}
} else {
if (type == "on") {
currentIntervals += interval
}
}
}
return currentIntervals
}
private fun splitCubeByCubesPlanes(cube: List<IntRange>, planesCube: List<IntRange>): List<List<IntRange>> {
return splitX(cube, planesCube[0].first - 1)
.flatMap { splitX(it, planesCube[0].last) }
.flatMap { splitY(it, planesCube[1].first - 1) }
.flatMap { splitY(it, planesCube[1].last) }
.flatMap { splitZ(it, planesCube[2].first - 1) }
.flatMap { splitZ(it, planesCube[2].last) }
}
private fun splitX(cube: List<IntRange>, x: Int): List<List<IntRange>> {
if (x !in cube[0]) {
return listOf(cube)
}
val splitX = listOf(cube[0].first..x, (x + 1)..cube[0].last)
return splitX
.filter { range -> !range.isEmpty() }
.map { range -> listOf(range, cube[1], cube[2]) }
}
private fun splitY(cube: List<IntRange>, y: Int): List<List<IntRange>> {
if (y !in cube[1]) {
return listOf(cube)
}
val splitY = listOf(cube[1].first..y, (y + 1)..cube[1].last)
return splitY
.filter { range -> !range.isEmpty() }
.map { range -> listOf(cube[0], range, cube[2]) }
}
private fun splitZ(cube: List<IntRange>, z: Int): List<List<IntRange>> {
if (z !in cube[2]) {
return listOf(cube)
}
val splitZ = listOf(cube[2].first..z, (z + 1)..cube[2].last)
return splitZ
.filter { range -> !range.isEmpty() }
.map { range -> listOf(cube[0], cube[1], range) }
}
operator fun IntRange.contains(other: IntRange): Boolean {
return this.first <= other.last && other.first <= this.last
}
} | 0 | Kotlin | 0 | 0 | 93363faee195d5ef90344a4fb74646d2d26176de | 4,303 | AdventOfCode2021 | MIT License |
src/main/kotlin/_2019/Day3.kt | thebrightspark | 227,161,060 | false | {"Kotlin": 548420} | package _2019
import aocRun
import range
import kotlin.math.abs
fun main() {
aocRun(puzzleInput) { input ->
val wiresRaw = input.split("\n")
val wire1 = parseWire(wiresRaw[0])
val wire2 = parseWire(wiresRaw[1])
val intersections = intersections(wire1, wire2)
return@aocRun intersections.map { Pair(it, it.dist()) }.minByOrNull { it.second }!!
}
aocRun(puzzleInput) { input ->
val wiresRaw = input.split("\n")
val wire1 = parseWire(wiresRaw[0])
val wire2 = parseWire(wiresRaw[1])
val intersections = intersections(wire1, wire2)
return@aocRun intersections.map {
// println("1")
val steps1 = steps(wire1, it)
// println("2")
val steps2 = steps(wire2, it)
val total = steps1 + steps2
// println("$it -> $steps1 + $steps2 = $total")
Pair(it, total)
}.minByOrNull { it.second }!!
}
}
private fun steps(wire: List<Line>, pos: Pos): Int {
var steps = 0
wire.forEach { line ->
line.positions.apply {
val index = indexOf(pos)
val s = if (index < 0) size - 1 else index
// println("$line -> $s")
steps += s
if (index >= 0)
return steps
}
}
return steps
}
private fun intersections(wire1: List<Line>, wire2: List<Line>): List<Pos> = mutableListOf<Pos>().apply {
wire1.forEach { line1 ->
wire2.forEach { line2 ->
line1.intersection(line2)?.let { add(it) }
}
}
}
private fun parseWire(inputWire: String): List<Line> {
var lastPos = Pos.ORIGIN
return inputWire.split(',').map {
val dir = Dir.valueOf(it[0].toString())
val num = it.substring(1).toInt()
val pos = lastPos.offset(dir, num)
val line = Line(lastPos, pos)
lastPos = pos
return@map line
}
}
private enum class Dir(val x: Int, val y: Int) {
U(0, 1),
D(0, -1),
L(-1, 0),
R(1, 0)
}
private data class Pos(val x: Int, val y: Int) {
companion object {
val ORIGIN = Pos(0, 0)
}
fun offset(dir: Dir, num: Int) = Pos(x + (dir.x * num), y + (dir.y * num))
fun dist(pos: Pos = ORIGIN) = abs(x - pos.x) + abs(y - pos.y)
}
private data class Line(val pos1: Pos, val pos2: Pos) {
init {
if (pos1 == pos2 || (pos1.x != pos2.x && pos1.y != pos2.y))
throw RuntimeException("The two positions $pos1 and $pos2 do not form a horizontal or vertical line!")
}
val positions by lazy {
if (pos1.x == pos2.x)
range(pos1.y, pos2.y).map { Pos(pos1.x, it) }
else
range(pos1.x, pos2.x).map { Pos(it, pos1.y) }
}
fun intersection(line: Line): Pos? {
positions.forEach { pos ->
if (pos != Pos.ORIGIN)
line.positions.find { it == pos }?.let { return it }
}
return null
}
}
private const val testInput1 = "R75,D30,R83,U83,L12,D49,R71,U7,L72\nU62,R66,U55,R34,D71,R55,D58,R83"
private const val testInput2 = "R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51\nU98,R91,D20,R16,D67,R40,U7,R15,U6,R7"
private const val testInput3 = "R8,U5,L5,D3\nU7,R6,D4,L4"
private const val puzzleInput =
"R991,U557,R554,U998,L861,D301,L891,U180,L280,D103,R828,D58,R373,D278,L352,D583,L465,D301,R384,D638,L648,D413,L511,U596,L701,U463,L664,U905,L374,D372,L269,U868,R494,U294,R661,U604,L629,U763,R771,U96,R222,U227,L97,D793,L924,U781,L295,D427,R205,D387,L455,D904,R254,D34,R341,U268,L344,D656,L715,U439,R158,U237,R199,U729,L428,D125,R487,D506,R486,D496,R932,D918,R603,U836,R258,U15,L120,U528,L102,D42,R385,U905,L472,D351,R506,U860,L331,D415,R963,D733,R108,D527,L634,U502,L553,D623,R973,U209,L632,D588,R264,U553,L768,D689,L708,D432,R247,U993,L146,U656,R710,U47,R783,U643,R954,U888,L84,U202,R495,U66,R414,U993,R100,D557,L326,D645,R975,U266,R143,U730,L491,D96,L161,U165,R97,D379,R930,D613,R178,D635,R192,U957,L450,U149,R911,U220,L914,U659,L67,D825,L904,U137,L392,U333,L317,U310,R298,D240,R646,U588,R746,U861,L958,D892,L200,U463,R246,D870,R687,U815,R969,U864,L972,U254,L120,D418,L567,D128,R934,D217,R764,U128,R146,U467,R690,U166,R996,D603,R144,D362,R885,D118,L882,U612,R270,U917,L599,D66,L749,D498,L346,D920,L222,U439,R822,U891,R458,U15,R831,U92,L164,D615,L439,U178,R409,D463,L452,U633,L683,U186,R402,D609,L38,D699,L679,D74,R125,D145,R424,U961,L353,U43,R794,D519,L359,D494,R812,D770,L657,U154,L137,U549,L193,D816,R333,U650,R49,D459,R414,U72,R313,U231,R370,U680,L27,D221,L355,U342,L597,U748,R821,D280,L307,U505,L160,U982,L527,D516,L245,U158,R565,D797,R99,D695,L712,U155,L23,U964,L266,U623,L317,U445,R689,U150,L41,U536,R638,D200,R763,D260,L234,U217,L881,D576,L223,U39,L808,D125,R950,U341,L405\n" +
"L993,D508,R356,U210,R42,D68,R827,D513,L564,D407,L945,U757,L517,D253,R614,U824,R174,D536,R906,D291,R70,D295,R916,D754,L892,D736,L528,D399,R76,D588,R12,U617,R173,D625,L533,D355,R178,D706,R139,D419,R460,U976,L781,U973,L931,D254,R195,U42,R555,D151,R226,U713,L755,U398,L933,U264,R352,U461,L472,D810,L257,U901,R429,U848,L181,D362,R404,D234,L985,D392,R341,U608,L518,D59,L804,D219,L366,D28,L238,D491,R265,U131,L727,D504,R122,U461,R732,D411,L910,D884,R954,U341,L619,D949,L570,D823,R646,D226,R197,U892,L691,D294,L955,D303,R490,D469,L503,D482,R390,D741,L715,D187,R378,U853,L70,D903,L589,D481,L589,U911,R45,U348,R214,D10,R737,D305,R458,D291,R637,D721,R440,U573,R442,D407,L63,U569,L903,D936,R518,U859,L370,D888,R498,D759,R283,U469,R548,D185,R808,D81,L629,D761,R807,D878,R712,D183,R382,D484,L791,D371,L188,D397,R645,U679,R415,D446,L695,U174,R707,D36,R483,U877,L819,D538,L277,D2,R200,D838,R837,U347,L865,D945,R958,U575,L924,D351,L881,U961,R899,U845,R816,U866,R203,D380,R766,D97,R38,U148,L999,D332,R543,U10,R351,U281,L460,U309,L543,U795,L639,D556,L882,D513,R722,U314,R531,D604,L418,U840,R864,D694,L530,U862,R559,D639,R689,D201,L439,D697,R441,U175,R558,D585,R92,D191,L533,D788,R154,D528,R341,D908,R811,U750,R172,D742,R113,U56,L517,D826,L250,D269,L278,U74,R285,U904,L221,U270,R296,U671,L535,U340,L206,U603,L852,D60,R648,D313,L282,D685,R482,U10,R829,U14,L12,U365,R996,D10,R104,U654,R346,D458,R219,U247,L841,D731,R115,U400,L731,D904,L487,U430,R612,U437,L865,D618,R747,U522,R309,U302,R9,U609,L201" | 0 | Kotlin | 0 | 0 | ac62ce8aeaed065f8fbd11e30368bfe5d31b7033 | 6,264 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/Day13.kt | PascalHonegger | 573,052,507 | false | {"Kotlin": 66208} | import kotlin.math.max
private sealed interface Packet : Comparable<Packet>
private data class ListPacket(val children: List<Packet>) : Packet {
override fun toString() = "[${children.joinToString()}]"
override fun compareTo(other: Packet): Int {
return when (other) {
is ListPacket -> {
for (i in 0 until (max(children.size, other.children.size))) {
val left = children.getOrNull(i) ?: return -1
val right = other.children.getOrNull(i) ?: return 1
left.compareTo(right).let {
if (it != 0) return it
}
}
return 0
}
is ItemPacket -> compareTo(ListPacket(listOf(other)))
}
}
}
private data class ItemPacket(val value: Int) : Packet {
override fun toString() = value.toString()
override fun compareTo(other: Packet): Int {
return when (other) {
is ListPacket -> ListPacket(listOf(this)).compareTo(other)
is ItemPacket -> value.compareTo(other.value)
}
}
}
private class PacketParser(val input: String) {
private var idx = 0
private fun consume() = input[idx++]
private fun peek() = input[idx]
private fun consumeNumber(): ItemPacket {
val number = buildString {
while (peek().isDigit()) {
append(consume())
}
}.toInt()
return ItemPacket(number)
}
private fun consumePacket(): Packet {
val next = peek()
return when {
next.isDigit() -> consumeNumber()
else -> consumeListPacket()
}
}
private fun consumeList(): List<Packet> = buildList {
add(consumePacket())
while (peek() == ',') {
consume()
add(consumePacket())
}
}
private fun consumeListPacket(): ListPacket {
check(consume() == '[')
val content = if (peek() == ']') emptyList() else consumeList()
check(consume() == ']')
return ListPacket(content)
}
val rootPacket = consumeListPacket()
}
fun main() {
fun String.toListPacket() = PacketParser(this).rootPacket
fun part1(input: List<String>): Int {
return input
.asSequence()
.chunked(3)
.map { (first, second, _) -> first.toListPacket() to second.toListPacket() }
.withIndex()
.filter { it.value.first <= it.value.second }
.sumOf { it.index + 1}
}
fun part2(input: List<String>): Int {
val dividerPackets = listOf(
ListPacket(listOf(ListPacket(listOf(ItemPacket(2))))),
ListPacket(listOf(ListPacket(listOf(ItemPacket(6))))),
)
return input
.filter { it.isNotEmpty() }
.map { it.toListPacket() }
.let { it + dividerPackets }
.sorted()
.withIndex()
.filter { it.value in dividerPackets }
.map { it.index + 1 }
.product()
}
val testInput = readInput("Day13_test")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2215ea22a87912012cf2b3e2da600a65b2ad55fc | 3,291 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | orirabi | 574,124,632 | false | {"Kotlin": 14153} |
val calc = mapOf(
Choice.ROCK to mapOf(
Choice.ROCK to Result.DRAW,
Choice.PAPER to Result.LOSS,
Choice.SCISSORS to Result.WIN,
),
Choice.PAPER to mapOf(
Choice.ROCK to Result.WIN,
Choice.PAPER to Result.DRAW,
Choice.SCISSORS to Result.LOSS,
),
Choice.SCISSORS to mapOf(
Choice.ROCK to Result.LOSS,
Choice.PAPER to Result.WIN,
Choice.SCISSORS to Result.DRAW,
),
)
enum class Result {
WIN {
override fun getPoints(): Int = 6
},
LOSS{
override fun getPoints(): Int = 0
},
DRAW{
override fun getPoints(): Int = 3
};
abstract fun getPoints(): Int
companion object {
fun parse(s: String): Result {
return when (s) {
"X" -> LOSS
"Y" -> DRAW
"Z" -> WIN
else -> throw IllegalStateException("Cannot parse $s")
}
}
}
}
enum class Choice {
ROCK {
override fun getPoints(): Int = 1
},
PAPER {
override fun getPoints(): Int = 2
},
SCISSORS {
override fun getPoints(): Int = 3
};
companion object {
fun parse(s: String): Choice {
return when (s) {
"A" -> ROCK
"B" -> PAPER
"C" -> SCISSORS
"X" -> ROCK
"Y" -> PAPER
"Z" -> SCISSORS
else -> throw IllegalStateException("Cannot parse $s")
}
}
}
fun against(that: Choice): Result {
return calc[this]!![that]!!
}
fun forResult(result: Result): Choice {
if (result == Result.DRAW) {
return this
}
return calc[this]!!.filter { it.value != result && it.value != Result.DRAW }.keys.single()
}
abstract fun getPoints(): Int
}
fun main() {
fun getStrategyResult1(input: List<String>): Int {
return input.asSequence()
.map {
val split = it.split(" ")
val opponent = Choice.parse(split.first())
val mine = Choice.parse(split.last())
val result = mine.against(opponent)
mine.getPoints() + result.getPoints()
}
.sum()
}
fun getStrategyResult2(input: List<String>): Int {
return input.asSequence()
.map {
val split = it.split(" ")
val opponent = Choice.parse(split.first())
val result = Result.parse(split.last())
val myPlay = opponent.forResult(result)
val points = myPlay.getPoints() + result.getPoints()
points
}
.sum()
}
val strategy = readInput("Day02")
println(getStrategyResult1(strategy))
println(getStrategyResult2(strategy))
}
| 0 | Kotlin | 0 | 0 | 41cb10eac3234ae77ed7f3c7a1f39c2f9d8c777a | 2,892 | AoC-2022 | Apache License 2.0 |
kotlin/08.kt | NeonMika | 433,743,141 | false | {"Kotlin": 68645} | class Day8 : Day<List<Day8.Input>>("08") {
data class Input(val segments: List<String>, val outputs: List<String>)
enum class SegmentNumber(val segments: String, val int: Int) {
ZERO("abcefg", 0),
ONE("cf", 1),
TWO("acdeg", 2),
THREE("acdfg", 3),
FOUR("bcdf", 4),
FIVE("abdfg", 5),
SIX("abdefg", 6),
SEVEN("acf", 7),
EIGHT("abcdefg", 8),
NINE("abcdfg", 9);
}
val uniqueNumberLengths = setOf(
SegmentNumber.ONE.segments.length,
SegmentNumber.FOUR.segments.length,
SegmentNumber.SEVEN.segments.length,
SegmentNumber.EIGHT.segments.length
)
override fun dataStar1(lines: List<String>): List<Input> =
lines.map { line -> line.split("|").run { Input(get(0).strings(), get(1).strings()) } }
override fun dataStar2(lines: List<String>): List<Input> = dataStar1(lines)
override fun star1(data: List<Input>): Number {
return data.flatMap { it.outputs }.count { it.length in uniqueNumberLengths }
}
override fun star2(data: List<Input>): Number {
var sum = 0
for (input in data) {
val inputCounts = input.segments.flatMap { it.toList() }.groupingBy { it }.eachCount()
// a: 7 (unique) without 1 (unique)
val a = (input.segments.find { it.length == 3 }!!.toSet() - input.segments.find { it.length == 2 }!!
.toSet()).single()
// b: Only segment that is lit 6 times
val b = inputCounts.filter { (_, v) -> v == 6 }.map { it.key }.single()
// c: The second segment besides a that is lit in 8 out of 10 digits
val c = inputCounts.filter { (k, v) -> v == 8 && k != a }.map { it.key }.single()
// e: Only segment that is lit 4 times
val e = inputCounts.filter { (_, v) -> v == 4 }.map { it.key }.single()
// f: Only segment that is lit 9 times
val f = inputCounts.filter { (_, v) -> v == 9 }.map { it.key }.single()
// d: 4 (unique) without b, c and f
val d = (input.segments.find { it.length == 4 }!!.toSet() - setOf(b, c, f)).single()
// g: remaining segment
val g = ("abcdefg".toSet() - setOf(a, b, c, d, e, f)).single()
val mapping = mapOf(
a to 'a',
b to 'b',
c to 'c',
d to 'd',
e to 'e',
f to 'f',
g to 'g'
)
val fixedOutput = input.outputs.map { wrongNumberSegments: String ->
SegmentNumber.values().find { segmentNumber ->
val fixed = wrongNumberSegments.map { letter -> mapping[letter] }.sortedBy { it }.joinToString("")
segmentNumber.segments == fixed
}!!.int
}.joinToString("").toInt()
sum += fixedOutput
}
return sum
}
}
fun main() {
Day8()()
} | 0 | Kotlin | 0 | 0 | c625d684147395fc2b347f5bc82476668da98b31 | 3,001 | advent-of-code-2021 | MIT License |
src/Day09.kt | wooodenleg | 572,658,318 | false | {"Kotlin": 30668} | import kotlin.math.absoluteValue
val String.asDirection get() = Direction.values().first { it.name.first().toString() == this }
class Knot(
startOffset: IntOffset,
private val childKnot: Knot? = null
) {
private var location: IntOffset = startOffset
private val visitedPositions = mutableListOf(location)
val visited get() = visitedPositions.toList().distinct()
val ropeTail: Knot get() = childKnot?.ropeTail ?: this
fun parentUpdated(parentLocation: IntOffset) {
if (location.distanceTo(parentLocation) <= 1) return // ignore changes where parent is still touching
val offset = parentLocation - location
val targetOffset = when {
offset.x == 0 -> {
IntOffset(0, offset.y / offset.y.absoluteValue)
}
offset.y == 0 -> {
IntOffset(offset.x / offset.x.absoluteValue, 0)
}
else -> {
val horizontalDirection = if (offset.x > 0) Direction.Right else Direction.Left
val verticalDirection = if (offset.y > 0) Direction.Up else Direction.Down
horizontalDirection.offset + verticalDirection.offset
}
}
location += targetOffset
visitedPositions.add(location)
childKnot?.parentUpdated(location)
}
}
fun parseInstructions(input: List<String>): List<Direction> = input
.flatMap { line ->
val (dir, count) = line.split(" ")
val direction = dir.asDirection
List(count.toInt()) { direction }
}
fun buildRope(length: Int, initialOffset: IntOffset = IntOffset(0, 0)): Knot {
var lastKnot = Knot(initialOffset, null)
repeat(length - 1) { // -1 because we already have the last knot
val newKnot = Knot(initialOffset, lastKnot)
lastKnot = newKnot
}
return lastKnot
}
fun main() {
fun part1(input: List<String>): Int {
val instructions = parseInstructions(input)
var headLocation = IntOffset(0, 0)
val tail = Knot(headLocation)
for (instruction in instructions) {
headLocation += instruction.offset
tail.parentUpdated(headLocation)
}
return tail.visited.size
}
fun part2(input: List<String>): Int {
val instructions = parseInstructions(input)
var headLocation = IntOffset(0, 0)
val firsKnot = buildRope(9)
for (instruction in instructions) {
headLocation += instruction.offset
firsKnot.parentUpdated(headLocation)
}
return firsKnot.ropeTail.visited.size
}
val testInput = readInputLines("Day09_test")
val test2Input = readInputLines("Day09_test2")
check(part1(testInput) == 13)
check(part2(test2Input) == 36)
val input = readInputLines("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | ff1f3198f42d1880e067e97f884c66c515c8eb87 | 2,878 | advent-of-code-2022 | Apache License 2.0 |
src/Day07.kt | iartemiev | 573,038,071 | false | {"Kotlin": 21075} | class Node(val name: String, var size: Int = 0, val parent: Node? = null) {
val children: MutableList<Node> = mutableListOf()
}
fun cd(rootNode: Node, currentNode: Node, arg: String): Node {
val toAncestor = ".."
val toRoot = "/"
return when (arg) {
toRoot -> rootNode
toAncestor -> currentNode.parent ?: rootNode
else -> currentNode.children.find { it.name == arg } ?: throw IllegalStateException("Directory $arg does not exist in ${currentNode.name}")
}
}
fun constructTree(input: List<String>): Node {
var currentNode = Node("/", 0)
val rootNode = currentNode
for (line in input) {
if (line.startsWith("$")) {
if (line.contains("cd")) {
val (_, _, operand) = line.split(" ")
currentNode = cd(rootNode, currentNode, operand)
}
} else {
val (dirOrSize, name) = line.split(" ")
if (dirOrSize == "dir") {
currentNode.children.add(Node(name, 0, currentNode))
} else {
val fileSize = dirOrSize.toInt()
currentNode.children.add(Node(name, fileSize, currentNode))
}
}
}
return rootNode
}
// DFS
fun computeDirSize(node: Node): Int {
if (node.children.size == 0) return node.size
var dirSize = 0
for (child in node.children) {
dirSize += computeDirSize(child)
}
node.size += dirSize
return node.size
}
fun calculateTotal(node: Node): Int {
if (node.children.size == 0) return 0
val threshold = 100000
var total = 0
for (child in node.children) {
total += calculateTotal(child)
}
if (node.size <= threshold) {
total += node.size
}
return total
}
fun findSufficientDir(node: Node, toDelete: Int): Int {
if (node.children.size == 0) return 0
var bestDir = node.size
for (child in node.children) {
val size = findSufficientDir(child, toDelete)
if (size in toDelete..bestDir) {
bestDir = size
}
}
return bestDir
}
fun main() {
fun part1(input: List<String>): Int {
val rootNode = constructTree(input)
computeDirSize(rootNode)
return calculateTotal(rootNode)
}
fun part2(input: List<String>): Int {
val rootNode = constructTree(input)
computeDirSize(rootNode)
return findSufficientDir(rootNode, rootNode.size - 40000000)
}
// 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))
}
| 0 | Kotlin | 0 | 0 | 8d2b7a974c2736903a9def65282be91fbb104ffd | 2,531 | advent-of-code | Apache License 2.0 |
src/main/kotlin/twenty/three/02.kt | itsabdelrahman | 726,503,458 | false | {"Kotlin": 8123} | package twenty.three
import java.io.File
fun main() {
val games = File("src/main/resources/twenty/three/02/1.txt")
.readLines()
.map(Game::from)
val output1 = games.filter {
it.isPossibleWith(
totalRed = 12,
totalGreen = 13,
totalBlue = 14,
)
}.sumOf {
it.id
}
println(output1)
val output2 = games.sumOf {
val (maximumRedCount, maximumGreenCount, maximumBlueCount) = Triple(
it.maximumCountOf(CubeColor.RED),
it.maximumCountOf(CubeColor.GREEN),
it.maximumCountOf(CubeColor.BLUE),
)
maximumRedCount * maximumGreenCount * maximumBlueCount
}
println(output2)
}
data class Game(
val id: Int,
val sets: List<GameSet>,
) {
fun isPossibleWith(
totalRed: Int,
totalGreen: Int,
totalBlue: Int,
): Boolean = sets.all {
it.isPossibleWith(
red = totalRed,
green = totalGreen,
blue = totalBlue,
)
}
fun maximumCountOf(color: CubeColor): Int = sets.maxOf { set ->
when (color) {
CubeColor.RED -> set.red
CubeColor.GREEN -> set.green
CubeColor.BLUE -> set.blue
}
}
companion object {
// Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
fun from(text: String): Game {
val (gameWithId, gameSets) = text.split(": ")
val id = gameWithId.replace("Game ", "").toInt()
val sets = gameSets.split("; ").map(GameSet::from)
return Game(id = id, sets = sets)
}
}
}
data class GameSet(
val red: Int,
val green: Int,
val blue: Int,
) {
fun isPossibleWith(
red: Int,
green: Int,
blue: Int,
): Boolean = this.red <= red && this.green <= green && this.blue <= blue
companion object {
// 3 blue, 4 red
fun from(text: String): GameSet {
val cubes = text.split(", ").map(Cube::from)
val cubesIndexedByColor = cubes.associateBy { it.color }
val redCube = cubesIndexedByColor[CubeColor.RED]
val greenCube = cubesIndexedByColor[CubeColor.GREEN]
val blueCube = cubesIndexedByColor[CubeColor.BLUE]
return GameSet(
red = redCube?.count ?: 0,
green = greenCube?.count ?: 0,
blue = blueCube?.count ?: 0,
)
}
}
}
data class Cube(
val count: Int,
val color: CubeColor,
) {
companion object {
// 3 blue
fun from(text: String): Cube {
val (count, color) = text.split(" ")
return Cube(count = count.toInt(), CubeColor.from(color))
}
}
}
enum class CubeColor {
RED,
GREEN,
BLUE;
companion object {
fun from(text: String): CubeColor = valueOf(text.uppercase())
}
}
| 0 | Kotlin | 0 | 0 | 81765d658ca1dd77b5e5418167ee519460baa4a5 | 2,944 | advent-of-code | Creative Commons Zero v1.0 Universal |
src/main/kotlin/SmokeBasin_9.kt | Flame239 | 433,046,232 | false | {"Kotlin": 64209} | val cave: Array<IntArray> by lazy {
readFile("SmokeBasin").split("\n").map { it.map { it.digitToInt() }.toIntArray() }.toTypedArray()
}
fun findLowestPoints(): List<Pair<Int, Int>> {
val h = cave.size
val w = cave[0].size
val lowestPoints = mutableListOf<Pair<Int, Int>>()
for (i in 0 until h) {
for (j in 0 until w) {
var lowest = true
val cur = cave[i][j]
if (i >= 1) {
lowest = lowest and (cur < cave[i - 1][j])
}
if (i <= h - 2) {
lowest = lowest and (cur < cave[i + 1][j])
}
if (j >= 1) {
lowest = lowest and (cur < cave[i][j - 1])
}
if (j <= w - 2) {
lowest = lowest and (cur < cave[i][j + 1])
}
if (lowest) {
lowestPoints.add(Pair(i, j))
}
}
}
return lowestPoints
}
fun findLowestPointsImproved(): List<Pair<Int, Int>> {
val h = cave.size
val w = cave[0].size
val lowestPoints = mutableListOf<Pair<Int, Int>>()
for (i in 0 until h) {
for (j in 0 until w) {
val cur = cave[i][j]
val surrounding = listOfNotNull(
cave[i].getOrNull(j + 1),
cave[i].getOrNull(j - 1),
cave.getOrNull(i - 1)?.get(j),
cave.getOrNull(i + 1)?.get(j),
)
if (cur < surrounding.minOrNull()!!) {
lowestPoints.add(Pair(i, j))
}
}
}
return lowestPoints
}
fun findRiskLevel(): Int = findLowestPoints().sumOf { (i, j) -> cave[i][j] + 1 }
fun findBasins(): Int {
val lowestPoints = findLowestPoints()
val basinSizes = IntArray(lowestPoints.size)
val visited = Array(cave.size) { BooleanArray(cave[0].size) }
lowestPoints.forEachIndexed { index, (i, j) ->
dfs(cave, visited, i, j, basinSizes, index)
}
return basinSizes.sortedArrayDescending().take(3).reduce(Int::times)
}
fun dfs(cave: Array<IntArray>, visited: Array<BooleanArray>, i: Int, j: Int, basinSizes: IntArray, curBasin: Int) {
visited[i][j] = true
basinSizes[curBasin]++
if (i >= 1 && !visited[i - 1][j] && isStillBasin(cave[i][j], cave[i - 1][j])) {
dfs(cave, visited, i - 1, j, basinSizes, curBasin)
}
if (i <= cave.size - 2 && !visited[i + 1][j] && isStillBasin(cave[i][j], cave[i + 1][j])) {
dfs(cave, visited, i + 1, j, basinSizes, curBasin)
}
if (j >= 1 && !visited[i][j - 1] && isStillBasin(cave[i][j], cave[i][j - 1])) {
dfs(cave, visited, i, j - 1, basinSizes, curBasin)
}
if (j <= cave[0].size - 2 && !visited[i][j + 1] && isStillBasin(cave[i][j], cave[i][j + 1])) {
dfs(cave, visited, i, j + 1, basinSizes, curBasin)
}
}
fun isStillBasin(curVal: Int, nextVal: Int) = curVal < nextVal && nextVal != 9
fun main() {
println(findRiskLevel())
println(findBasins())
} | 0 | Kotlin | 0 | 0 | ef4b05d39d70a204be2433d203e11c7ebed04cec | 2,978 | advent-of-code-2021 | Apache License 2.0 |
src/Day03.kt | maximilianproell | 574,109,359 | false | {"Kotlin": 17586} | fun main() {
fun part1(input: List<String>): Int {
return input.mapNotNull { items ->
val rucksack = Rucksack.createRucksack(items)
val sharedItem = rucksack.findDuplicateItem()
sharedItem?.priority
}.sum()
}
fun part2(input: List<String>): Int {
return buildList {
for (index in input.indices step 3) {
val char = findCharacterAppearingInAll(
input[index + 0],
input[index + 1],
input[index + 2],
)
add(char?.priority ?: 0)
}
}.sum()
}
val testInputString = """
vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw
""".trimIndent()
val input = readInput("Day03")
// val input = testInputString.lines()
println(part1(input))
println(part2(input))
}
private fun findCharacterAppearingInAll(vararg lines: String): Char? {
val maps = lines.map { string ->
string.groupBy { it }
}
val combinedString = lines.reduce { x1, x2 -> x1 + x2 }
val combinedMap = combinedString.groupBy { it }
combinedMap.keys.forEach { key ->
if (maps.all { map -> map.contains(key) })
return key
}
return null
}
/**
* Converts this Char to the priority defined in the problem statement:
* Lowercase item types a through z have priorities 1 through 26.
* Uppercase item types A through Z have priorities 27 through 52.
*/
private val Char.priority: Int
get() {
return if (this.isUpperCase()) (this - 38).code
else (this - 96).code
}
data class Rucksack(
val compartment1: String,
val compartment2: String
) {
companion object {
fun createRucksack(input: String): Rucksack {
val (firstHalf, secondHalf) = input.chunked(input.length / 2)
return Rucksack(
compartment1 = firstHalf,
compartment2 = secondHalf,
)
}
}
fun findDuplicateItem(): Char? {
val groupedChars = compartment2.groupBy { it }
compartment1.forEach { char ->
if (groupedChars.contains(char))
return char
}
return null
}
} | 0 | Kotlin | 0 | 0 | 371cbfc18808b494ed41152256d667c54601d94d | 2,403 | kotlin-advent-of-code-2022 | Apache License 2.0 |
solutions/aockt/y2022/Y2022D12.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2022
import io.github.jadarma.aockt.core.Solution
import java.util.*
object Y2022D12 : Solution {
/** Parse the [input] and return the map and the coordinates of the start and end [Point]s. */
private fun parseInput(input: String): Triple<HeightMap, Point, Point> {
lateinit var start: Point
lateinit var end: Point
var width = -1
var height = 0
val map = input
.lines()
.onEach { if (width == -1) width = it.length else require(it.length == width) }
.onEach { height++ }
.flatMapIndexed { row, line ->
line.mapIndexed { col, value ->
when (value) {
'S' -> 0.also { start = Point(row, col) }
'E' -> ('z' - 'a').also { end = Point(row, col) }
else -> value - 'a'
}
}
}
.toIntArray()
.let { HeightMap(width, height, it) }
return Triple(map, start, end)
}
/** Represents a discrete point in 2D space. */
private data class Point(val x: Int, val y: Int)
/** A square in a [HeightMap], at a given [location], which has a given [altitude]. */
private data class Tile(val location: Point, val altitude: Int)
/** A topographic map for hiking. */
private class HeightMap(val width: Int, val height: Int, private val altitudes: IntArray) {
init {
require(altitudes.size == width * height) { "Not all tiles in the map contain values." }
}
operator fun get(point: Point): Tile = Tile(point, altitudes[point.x * width + point.y])
private operator fun contains(point: Point): Boolean = with(point) { x in 0 until height && y in 0 until width }
private val Point.neighbors: List<Point>
get() = buildList(4) {
if (x > 0) add(Point(x - 1, y))
if (x < height - 1) add(Point(x + 1, y))
if (y > 0) add(Point(x, y - 1))
if (y < width - 1) add(Point(x, y + 1))
}
/**
* Determines the shortest path between the starting point and a tile that satisfies the condition in the
* [endSelector], returning the list of coordinates (including the starting location).
* This path works in reverse: it assumes you are climbing down from the [start].
*/
fun shortestPathBetween(start: Point, endSelector: (Tile) -> Boolean): List<Point> {
require(start in this)
var end: Point? = null
val distance = mutableMapOf<Point, Int>().withDefault { Int.MAX_VALUE }
val previous = mutableMapOf<Point, Point>()
val queue = PriorityQueue<Point> { a, b -> distance.getValue(a) compareTo distance.getValue(b) }
distance[start] = 0
queue.add(start)
while (queue.isNotEmpty()) {
val point = queue.remove()
if (endSelector(get(point))) {
end = point
break
}
point.neighbors
.filter { get(it).altitude >= get(point).altitude - 1 }
.forEach { neighbor ->
val altCost = distance.getValue(point) + 1
if (altCost < distance.getValue(neighbor)) {
val isInQueue = distance[neighbor] != null
distance[neighbor] = altCost
previous[neighbor] = point
if (!isInQueue) queue.add(neighbor)
}
}
}
return when (distance[end]) {
null -> emptyList()
else -> buildList {
var current = end?.also { add(it) } ?: return emptyList()
while (current != start) current = previous.getValue(current).also { add(it) }
}.reversed()
}
}
}
override fun partOne(input: String) =
parseInput(input)
.let { (map, start, end) -> map.shortestPathBetween(end) { it.location == start } }
.count().dec()
override fun partTwo(input: String) =
parseInput(input)
.let { (map, _, end) -> map.shortestPathBetween(end) { it.altitude == 0 } }
.count().dec()
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 4,451 | advent-of-code-kotlin-solutions | The Unlicense |
2015/src/main/kotlin/day21.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parse
import utils.Parser
import utils.Solution
import utils.selections
fun main() {
Day21.run()
}
object Day21 : Solution<Day21.Entity>() {
override val name = "day21"
override val parser = Parser { parseEntity(it) }
@Parse("Hit Points: {hp}\nDamage: {dmg}\nArmor: {armor}")
data class Entity(
val hp: Int,
val dmg: Int,
val armor: Int,
)
enum class Item(
val cost: Int,
val dmg: Int,
val armor: Int,
) {
// weapons
Dagger(8, 4, 0),
Shortsword(10, 5, 0),
Warhammer(25, 6, 0),
Longsword(40, 7, 0),
Greataxe(74, 8, 0),
// armor
Leather(13, 0, 1),
Chainmail(31, 0, 2),
Splintmail(53, 0, 3),
Bandedmail(75, 0, 4),
Platemail(102, 0, 5),
// rings
Damage1(25, 1, 0),
Damage2(50, 2, 0),
Damage3(100, 3, 0),
Defense1(20, 0, 1),
Defense2(40, 0, 2),
Defense3(80, 0, 3),
// quick hack for nothing
Nothing(0, 0, 0);
companion object {
val weapons = listOf(Dagger, Shortsword, Warhammer, Longsword, Greataxe)
val armor = listOf(Leather, Chainmail, Splintmail, Bandedmail, Platemail, Nothing)
val rings = listOf(Damage1, Damage2, Damage3, Defense1, Defense2, Defense3, Nothing, Nothing)
}
}
infix fun Entity.beats(other: Entity): Boolean {
val myDps = dmg - other.armor
val otherDps = other.dmg - armor
var myHp = hp
var otherHp = other.hp
while (myHp > 0) {
otherHp -= myDps
myHp -= otherDps
if (otherHp <= 0) {
return true
}
}
return false
}
private fun List<Item>.toEntity(): Entity {
return fold(Entity(100, 0, 0)) { entity, item ->
entity.copy(dmg = entity.dmg + item.dmg, armor = entity.armor + item.armor)
}
}
private fun generateOutfits(): Sequence<Pair<Int, Entity>> {
return sequence {
Item.weapons.forEach { weap ->
Item.armor.forEach { armor ->
Item.rings.selections(2).forEach { rings ->
val items = listOf(weap, armor) + rings
val char = items.toEntity()
yield(items.sumOf { it.cost } to char)
}
}
}
}
}
override fun part1(): Int {
val boss = input
return generateOutfits().filter { (_, it) -> it beats boss }.minOf { (cost, _) -> cost }
}
override fun part2(): Int {
val boss = input
return generateOutfits().filter { (_, it) -> !(it beats boss) }.maxOf { (cost, _) -> cost }
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 2,458 | aoc_kotlin | MIT License |
src/Day05.kt | TrevorSStone | 573,205,379 | false | {"Kotlin": 9656} | fun main() {
fun createStacks(input: List<String>) =
input
.filter { it.contains('[') }
.fold(mutableListOf<ArrayDeque<Char>>()) { stacks, line ->
val blocks = line.windowed(3, 4)
if (stacks.isEmpty()) {
repeat(blocks.size) { stacks.add(ArrayDeque()) }
}
blocks
.withIndex()
.filter { it.value.isNotBlank() }
.map { (index, value) -> IndexedValue(index, value[1]) }
.forEach { (index, value) -> stacks[index].addFirst(value) }
stacks
}
.toList()
fun part1(input: List<String>): String {
val stacks = createStacks(input)
input
.asSequence()
.filter { it.firstOrNull() == 'm' }
.map { line -> line.split(' ').mapNotNull { it.toIntOrNull() } }
.onEach { (count, from, to) ->
repeat(count) { stacks[to - 1].addLast(stacks[from - 1].removeLast()) }
}
.toList()
return stacks.map { it.last() }.joinToString(separator = "")
}
fun part2(input: List<String>): String {
val stacks = createStacks(input)
input
.asSequence()
.filter { it.firstOrNull() == 'm' }
.map { line -> line.split(' ').mapNotNull { it.toIntOrNull() } }
.onEach { (count, from, to) ->
val crates = buildList { repeat(count) { add(stacks[from - 1].removeLast()) } }
stacks[to - 1].addAll(crates.asReversed())
}
.toList()
return stacks.map { it.last() }.joinToString(separator = "")
}
val testInput = readInput("Day05_test")
check(part1(testInput).also { println(it) } == "CMZ")
check(part2(testInput).also { println(it) } == "MCD")
//
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2a48776f8bc10fe1d7e2bbef171bf65be9939400 | 1,836 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/y2016/Day24.kt | gaetjen | 572,857,330 | false | {"Kotlin": 325874, "Mermaid": 571} | package y2016
import util.Pos
import util.neighborsManhattan
import util.readInput
import util.timingStatistics
object Day24 {
data class Ducts(
val start: Pos,
val targets: List<Pos>,
val passages: Set<Pos>
) {
fun distance(p1: Pos, p2: Pos): Int {
var steps = 0
var frontier = setOf(p1)
val closed = mutableSetOf<Pos>()
while (p2 !in frontier) {
closed.addAll(frontier)
frontier = frontier.flatMap { s ->
s.neighborsManhattan().filter { it in passages && it !in closed }
}.toSet()
steps++
}
return steps
}
}
private fun parse(input: List<String>): Ducts {
var start = -1 to -1
val targets = mutableListOf<Pos>()
val passages = input.flatMapIndexed { row: Int, s: String ->
s.mapIndexed { col, c ->
if (c == '.' || c.isDigit()) {
if (c == '0') {
start = row to col
} else if (c.isDigit()) {
targets.add(row to col)
}
row to col
} else {
null
}
}
}.filterNotNull().toSet()
return Ducts(
start,
targets,
passages
)
}
fun part1(input: List<String>): Int {
val ducts = parse(input)
val pairDistances = getPairDistances(ducts)
return ducts.targets.flatMap {
val startDistance = pairDistances[ducts.start to it]!!
allVisitDistances(
startDistance,
it,
ducts.targets.toSet() - it,
pairDistances
)
}.min()
}
private fun getPairDistances(ducts: Ducts): MutableMap<Pair<Pos, Pos>, Int> {
val pairDistances = mutableMapOf<Pair<Pos, Pos>, Int>()
val allTargets = ducts.targets + ducts.start
allTargets.forEachIndexed { idx, p1 ->
allTargets.drop(idx + 1).forEach { p2 ->
val d = ducts.distance(p1, p2)
pairDistances[p1 to p2] = d
pairDistances[p2 to p1] = d
}
}
return pairDistances
}
fun allVisitDistances(
distanceSoFar: Int,
current: Pos,
unvisited: Set<Pos>,
distances: Map<Pair<Pos, Pos>, Int>,
returnTo: Pos? = null
): List<Int> {
if (unvisited.isEmpty()) {
return if (returnTo != null) {
listOf(distanceSoFar + distances[current to returnTo]!!)
} else {
listOf(distanceSoFar)
}
}
return unvisited.flatMap {
allVisitDistances(
distanceSoFar = distanceSoFar + distances[current to it]!!,
current = it,
unvisited = unvisited - it,
distances = distances,
returnTo = returnTo
)
}
}
fun part2(input: List<String>): Int {
val ducts = parse(input)
val pairDistances = getPairDistances(ducts)
return ducts.targets.flatMap {
val startDistance = pairDistances[ducts.start to it]!!
allVisitDistances(
startDistance,
it,
ducts.targets.toSet() - it,
pairDistances,
returnTo = ducts.start
)
}.min()
}
}
fun main() {
val testInput = """
###########
#0.1.....2#
#.#######.#
#4.......3#
###########
""".trimIndent().split("\n")
println("------Tests------")
println(Day24.part1(testInput))
println(Day24.part2(testInput))
println("------Real------")
val input = readInput("resources/2016/day24")
println("Part 1 result: ${Day24.part1(input)}")
println("Part 2 result: ${Day24.part2(input)}")
timingStatistics { Day24.part1(input) }
timingStatistics { Day24.part2(input) }
} | 0 | Kotlin | 0 | 0 | d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a | 4,137 | advent-of-code | Apache License 2.0 |
advent-of-code/src/main/kotlin/DayFifteen.kt | pauliancu97 | 518,083,754 | false | {"Kotlin": 36950} | import kotlin.math.max
typealias Qualities = List<Int>
class DayFifteen {
private fun getQuantitiesHelper(
ingredients: List<Qualities>,
remainingQuantity: Int,
quantitiesPerIngredient: List<Int>,
evaluator: (List<Int>) -> Unit
) {
if (quantitiesPerIngredient.size == ingredients.size - 1) {
evaluator(quantitiesPerIngredient + remainingQuantity)
} else {
val depth = quantitiesPerIngredient.size
val quantityUpperLimit = remainingQuantity - ingredients.size + depth + 1
for (quantity in 1..quantityUpperLimit) {
val updatedRemainingQuantity = remainingQuantity - quantity
val updatedQuantitiesPerIngredient = quantitiesPerIngredient + quantity
getQuantitiesHelper(
ingredients,
updatedRemainingQuantity,
updatedQuantitiesPerIngredient,
evaluator
)
}
}
}
private fun getQuantities(
ingredients: List<Qualities>,
quantity: Int
): Int? {
var maxMeasurementWithQuantities: Pair<Int, List<Int>>? = null
getQuantitiesHelper(ingredients, quantity, emptyList()) { quantities ->
val measurement = quantities.zip(ingredients)
.map { (qty, qualities) -> qualities.map { it * qty } }
.reduce { first, second -> first.zip(second).map { it.first + it.second } }
.reduce { first, second -> max(first, 0) * max(second, 0) }
val currentMaxMeasurementWithQuantities = maxMeasurementWithQuantities
if (currentMaxMeasurementWithQuantities != null) {
val (currentMeasurement, _) = currentMaxMeasurementWithQuantities
if (measurement > currentMeasurement) {
maxMeasurementWithQuantities = measurement to quantities
}
} else {
maxMeasurementWithQuantities = measurement to quantities
}
}
return maxMeasurementWithQuantities?.first
}
private fun readFirstIngredients(path: String): List<Qualities> {
val numberRegex = """[+-]?\d+""".toRegex()
val lines = readLines(path)
return lines
.map { line ->
val matchResults = numberRegex.findAll(line).toList()
matchResults
.mapNotNull { matchResult ->
matchResult.groupValues.firstOrNull()?.toIntOrNull()
}
.dropLast(1)
}
}
fun solvePartOne() {
val ingredients = readFirstIngredients("day_fifteen.txt")
val answer = getQuantities(ingredients,100)
println(answer)
}
}
fun main() {
DayFifteen().solvePartOne()
} | 0 | Kotlin | 0 | 0 | 3ba05bc0d3e27d9cbfd99ca37ca0db0775bb72d6 | 2,868 | advent-of-code-2015 | MIT License |
src/Day07.kt | dustinlewis | 572,792,391 | false | {"Kotlin": 29162} | fun main() {
fun part1(input: List<String>): Int {
val maxDirectorySize = 100000
val root = parseDirectoryTree(input)
return root.dirs.filter { it.dirSize < maxDirectorySize }.sumOf { it.dirSize }
}
fun part2(input: List<String>): Int {
val maxSystemSize = 70000000
val spaceNeeded = 30000000
val root = parseDirectoryTree(input)
val unusedSpace = maxSystemSize - root.dirSize
return root.dirs.filter { it.dirSize + unusedSpace >= spaceNeeded }.minOf { it.dirSize }
}
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
data class Node(
val name: String,
val size: Int = 0,
val isDir: Boolean = false,
val nodes: MutableList<Node> = mutableListOf(),
val parent: Node? = null
) {
val dirSize: Int
get() = size.plus(nodes.sumOf { it.dirSize })
val dirs: List<Node>
get() = if(isDir) listOf(this) + nodes.flatMap { it.dirs } else emptyList()
}
fun parseDirectoryTree(input: List<String>): Node {
val root = Node(name = "/", isDir = true)
var currentDir: Node? = root
input.drop(1).forEach { command ->
when {
command.contains("$ cd ") -> {
val dir = command.split("$ cd ")[1]
currentDir = if (dir == "..") {
currentDir?.parent
} else {
currentDir?.nodes?.find {
it.name == dir && it.isDir
}
}
}
command.contains("dir ") -> {
val dir = command.split("dir ")[1]
currentDir?.nodes?.add(Node(name = dir, isDir = true, parent = currentDir))
}
command.first().isDigit() -> {
val (size, name) = command.split(" ")
currentDir?.nodes?.add(Node(name = name, size = size.toInt(), parent = currentDir))
}
}
}
return root
} | 0 | Kotlin | 0 | 0 | c8d1c9f374c2013c49b449f41c7ee60c64ef6cff | 1,993 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/com/dr206/2022/Day04.kt | dr206 | 572,377,838 | false | {"Kotlin": 9200} | fun main() {
fun checkOverlapBasedOnPredicate(
pairOfIdRanges: String,
predicate: (Set<Int>, Set<Int>) -> Boolean
): Boolean {
val (idRange1, idRange2) = pairOfIdRanges.split(',')
val integers1 = idRange1.split('-').map { it.toInt() }
val range1 = (integers1[0]..integers1[1]).toSet()
val integers2 = idRange2.split('-').map { it.toInt() }
val range2 = (integers2[0]..integers2[1]).toSet()
return predicate(range1, range2)
}
fun part1(input: List<String>): Int {
val predicate = { a: Set<Int>, b: Set<Int> -> a.containsAll(b) || b.containsAll(a) }
return input.map {
checkOverlapBasedOnPredicate(it, predicate)
}.count { it }
}
fun part2(input: List<String>): Int {
val predicate = { a: Set<Int>, b: Set<Int> -> a.intersect(b).isNotEmpty() }
return input.map {
checkOverlapBasedOnPredicate(it, predicate)
}.count { it }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println("Part 1 ${part1(input)}")
println("Part 2 ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 57b2e7227d992de87a51094a971e952b3774fd11 | 1,290 | advent-of-code-in-kotlin | Apache License 2.0 |
src/Day12.kt | rbraeunlich | 573,282,138 | false | {"Kotlin": 63724} | fun main() {
fun parseInput(input: List<String>): ElevationMap {
val elevationMap = ElevationMap(-1 to -1, -1 to -1, mutableListOf())
input.forEachIndexed { index, line ->
elevationMap.grid.add(index, line.toCharArray())
if (line.contains("S", false)) {
elevationMap.start = line.indexOf('S', ignoreCase = false) to index
}
if (line.contains("E", false)) {
elevationMap.destination = line.indexOf('E', ignoreCase = false) to index
}
}
return elevationMap
}
fun filterNeighboringFieldsThatAreOffMap(
neighboringFields: List<Pair<Int, Int>>,
elevationMap: ElevationMap
): List<Pair<Int, Int>> {
return neighboringFields.filterNot {
it.first < 0 || it.second < 0 || it.first >= elevationMap.gridWidth || it.second >= elevationMap.gridHeight
}
}
fun findShortestPath(elevationMap: ElevationMap): Int {
fun filterNonReachableFields(
currentPosition: Pair<Int, Int>,
neighborignFields: List<Pair<Int, Int>>
): List<Pair<Int, Int>> {
val currentHeight = if (elevationMap.grid[currentPosition.second][currentPosition.first] == 'E') {
'z'
} else {
elevationMap.grid[currentPosition.second][currentPosition.first]
}
return neighborignFields.filter { neighbor ->
val neighborHeight = if (elevationMap.grid[neighbor.second][neighbor.first] == 'S') {
'a'
} else {
elevationMap.grid[neighbor.second][neighbor.first]
}
kotlin.math.abs(currentHeight - neighborHeight) == 1 || neighborHeight >= currentHeight
}
}
fun findShortestPathRec(
currentPosition: Pair<Int, Int>,
takenPath: List<Pair<Int, Int>>,
): List<Pair<Int, Int>>? {
if (elevationMap.visited[currentPosition.second][currentPosition.first] <= takenPath.size){
return null
} else {
elevationMap.visited[currentPosition.second][currentPosition.first] = takenPath.size
}
val neighborignFields =
filterNeighboringFieldsThatAreOffMap(currentPosition.neighboringFields(), elevationMap)
val reachableFields = filterNonReachableFields(currentPosition, neighborignFields)
// val uniqueReachableFields = reachableFields - takenPath
return if (reachableFields.contains(elevationMap.start)) {
takenPath
} else if (reachableFields.isEmpty()) {
null
} else {
val mapNotNull = reachableFields.mapNotNull { field ->
val possibleShortestPath = findShortestPathRec(field, takenPath + field)
possibleShortestPath
}
mapNotNull.minByOrNull { it.size }
}
}
val destination = elevationMap.destination
val findShortestPathRec = findShortestPathRec(destination, listOf(destination))
return findShortestPathRec?.size ?: Integer.MAX_VALUE
}
fun part1(input: List<String>): Int {
val elevationMap = parseInput(input)
return findShortestPath(elevationMap)
}
fun part2(input: List<String>): Int {
val elevationMap = parseInput(input)
val elevationMaps: List<ElevationMap> = elevationMap.grid.flatMapIndexed { y: Int, line ->
line.mapIndexed{ x, c ->
if(c == 'a' || c == 'S') {
val anotherElevationMap = parseInput(input)
anotherElevationMap.start = x to y
anotherElevationMap
} else {
null
}
}
}.filterNotNull()
return elevationMaps.parallelStream().mapToInt { findShortestPath(it) }.min().orElse(Integer.MAX_VALUE)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
println("Test 1 geschafft")
check(part2(testInput) == 29)
println("Test 2 geschafft")
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
private fun Pair<Int, Int>.neighboringFields(): List<Pair<Int, Int>> {
val right = this.first + 1 to this.second
val left = this.first - 1 to this.second
val up = this.first to this.second - 1
val down = this.first to this.second + 1
return listOf(right, left, up, down)
}
data class ElevationMap(
var start: Pair<Int, Int>,
var destination: Pair<Int, Int>,
val grid: MutableList<CharArray>,
) {
val gridWidth by lazy { grid[0].size }
val gridHeight by lazy { grid.size }
val visited: MutableList<IntArray> by lazy {
MutableList(grid.size) { IntArray(grid[0].size) { Integer.MAX_VALUE } }
}
} | 0 | Kotlin | 0 | 1 | 3c7e46ddfb933281be34e58933b84870c6607acd | 5,048 | advent-of-code-2022 | Apache License 2.0 |
src/main/year_2018/day18/day18.kt | rolf-rosenbaum | 572,864,107 | false | {"Kotlin": 80772} | package year_2018.day18
import Point
import findPattern
import readInput
typealias Forest = Map<Point, Char>
private const val TREE = '|'
private const val OPEN = '.'
private const val LUMBER_YARD = '#'
fun main() {
val input = readInput("main/year_2018/day18/Day18")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Int {
val forest = input.parse()
return forest.resourceValueList(11).last()
}
fun part2(input: List<String>): Int {
val stepCount = 1000000000
val forest = input.parse()
val resourceValueList = forest.resourceValueList()
val (stepsBeforePattern, patternSize) = resourceValueList.findPattern()
val indexInCycle = (stepCount - stepsBeforePattern) % patternSize
return resourceValueList.drop(stepsBeforePattern)[indexInCycle]
}
fun Forest.step(): Forest = this.keys.associateWith { here ->
when (this[here]) {
OPEN -> if (this.countNeighborsOfKind(here, TREE) >= 3) TREE else OPEN
TREE -> if (this.countNeighborsOfKind(here, LUMBER_YARD) >= 3) LUMBER_YARD else TREE
LUMBER_YARD -> if (countNeighborsOfKind(here, LUMBER_YARD) > 0 && countNeighborsOfKind(here, TREE) > 0) LUMBER_YARD else OPEN
else -> error("Something went wrong: $here, ${this[here]}")
}
}
private fun Forest.resourceValue(): Int = count { it.value == LUMBER_YARD } * count { it.value == TREE }
fun Forest.resourceValueList(n: Int = 600): List<Int> = generateSequence(this) { it.step() }.take(n).map { it.resourceValue() }.toList()
fun Forest.countNeighborsOfKind(p: Point, c: Char) = p.allNeighbours().count { this[it] == c }
fun List<String>.parse(): Forest = mutableMapOf<Point, Char>().apply {
forEachIndexed { y, line ->
line.forEachIndexed { x, c ->
this[Point(x, y)] = c
}
}
}
| 0 | Kotlin | 0 | 2 | 59cd4265646e1a011d2a1b744c7b8b2afe482265 | 1,825 | aoc-2022 | Apache License 2.0 |
kotlin/src/katas/kotlin/hackerrank/FormingMagicSquare.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.hackerrank
import nonstdlib.permutations
import nonstdlib.printed
import java.util.*
/**
* https://www.hackerrank.com/challenges/magic-square-forming
*/
fun main() {
val scanner = Scanner(System.`in`)
val i = generateSequence { scanner.nextLine() }.iterator()
main({ i.next() })
}
private fun main(readLine: () -> String, writeLine: (Any?) -> Unit = { println(it) }) {
val square = arrayOf(
readLine().split(" ").map { it.toInt() }.toTypedArray(),
readLine().split(" ").map { it.toInt() }.toTypedArray(),
readLine().split(" ").map { it.toInt() }.toTypedArray()
)
writeLine(formingMagicSquare(square))
}
fun formingMagicSquare(square: Array<Array<Int>>): Int {
val magicSquares = listOf(
arrayOf(
arrayOf(2, 7, 6),
arrayOf(9, 5, 1),
arrayOf(4, 3, 8)
),
arrayOf(
arrayOf(2, 9, 4),
arrayOf(7, 5, 3),
arrayOf(6, 1, 8)
),
arrayOf(
arrayOf(4, 3, 8),
arrayOf(9, 5, 1),
arrayOf(2, 7, 6)
),
arrayOf(
arrayOf(4, 9, 2),
arrayOf(3, 5, 7),
arrayOf(8, 1, 6)
),
arrayOf(
arrayOf(6, 1, 8),
arrayOf(7, 5, 3),
arrayOf(2, 9, 4)
),
arrayOf(
arrayOf(6, 7, 2),
arrayOf(1, 5, 9),
arrayOf(8, 3, 4)
),
arrayOf(
arrayOf(8, 1, 6),
arrayOf(3, 5, 7),
arrayOf(4, 9, 2)
),
arrayOf(
arrayOf(8, 3, 4),
arrayOf(1, 5, 9),
arrayOf(6, 7, 2)
)
)
return magicSquares
.map { it.distanceTo(square) }
.minOrNull()!!
}
private fun Array<Array<Int>>.distanceTo(square: Array<Array<Int>>): Int {
return 0.until(3).sumOf { col ->
0.until(3).sumOf { row ->
Math.abs(this[col][row] - square[col][row])
}
}
}
private fun printAllMagicSquares() {
listOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
.permutations()
.filter { it.isMagic() }
.map { it.printed() }
}
private fun List<Int>.isMagic(): Boolean {
val row1 = this[0] + this[1] + this[2]
val row2 = this[3] + this[4] + this[5]
val row3 = this[6] + this[7] + this[8]
val col1 = this[0] + this[3] + this[6]
val col2 = this[1] + this[4] + this[7]
val col3 = this[2] + this[5] + this[8]
val diagonal1 = this[0] + this[4] + this[8]
val diagonal2 = this[2] + this[4] + this[6]
val rowsAreEqual = row1 == row2 && row2 == row3
val colsAreEqual = col1 == col2 && col2 == col3
return rowsAreEqual && colsAreEqual &&
row1 == col1 && row1 == diagonal1 && diagonal1 == diagonal2
}
class FormingMagicSquareTests {
// TODO
/*
val square = arrayOf(
arrayOf(5, 3, 4),
arrayOf(1, 5, 8),
arrayOf(6, 4, 2)
)
*/
/*val square = arrayOf(
arrayOf(4, 9, 2),
arrayOf(3, 5, 7),
arrayOf(8, 1, 5)
)*/
/*val square = arrayOf(
arrayOf(4, 8, 2),
arrayOf(4, 5, 7),
arrayOf(6, 1, 6)
)*/
} | 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 3,191 | katas | The Unlicense |
src/main/kotlin/net/hiddevb/advent/advent2019/day06/main.kt | hidde-vb | 224,606,393 | false | null | package net.hiddevb.advent.advent2019.day06
import net.hiddevb.advent.common.initialize
import kotlin.math.floor
/**
* --- Day 6: Universal Orbit Map ---
*/
private val entry = "COM"
fun main() {
val fileStrings = initialize("Day 6: Universal Orbit Map", arrayOf("day6.txt"))
// println("Part 1: Basic")
// val solution1 = solveBasic(fileStrings[0])
// println("Solved!\nSolution: $solution1\n")
println("Part 2: Advanced")
val solution2 = solveAdvanced(fileStrings[0])
println("Solved!\nSolution: $solution2\n")
}
// Part 1
fun solveBasic(input: String): Int {
val orbits = getOrbits(input)
val masses = ArrayList<Mass>()
masses.add(Mass(entry, 0))
var x = 0
while(x < masses.size) {
for (orbit in orbits) {
if(orbit.center == masses[x].center) {
masses.add(Mass(orbit.moon, masses[x].distance + 1))
}
}
x++
}
return masses.map { it.distance }.sum()
}
// Part 2
fun solveAdvanced(input: String): Int {
val orbits = getOrbits(input)
return findShortestDistance(pathTo("YOU", orbits), pathTo("SAN", orbits))
}
private fun getOrbits(input: String) = input.split("\n").map { it.split(")") }.map { Orbit(it[0], it[1])}
private fun pathTo(center: String, orbits: List<Orbit>): List<String> {
val path = arrayListOf(center)
var currentCenter = center
while(!path.contains(entry)) {
for(orbit in orbits) {
if (orbit.moon == currentCenter) {
path.add(orbit.center)
currentCenter=orbit.center
break
}
}
}
return path
}
private fun findShortestDistance(path: List<String>, target: List<String>): Int {
val distances = ArrayList<Int>()
for(i in 0 until path.size) {
for(j in 0 until target.size) {
if(path[i] == target[j]) {
distances.add(i+j-2)
break
}
}
}
return distances.min()!!
}
data class Orbit(val center: String, val moon: String)
data class Mass(val center: String, val distance: Int)
| 0 | Kotlin | 0 | 0 | d2005b1bc8c536fe6800f0cbd05ac53c178db9d8 | 2,123 | advent-of-code-2019 | MIT License |
src/main/kotlin/aoc2023/Day08.kt | Ceridan | 725,711,266 | false | {"Kotlin": 110767, "Shell": 1955} | package aoc2023
class Day08 {
fun part1(input: List<String>): Int {
val (directions, network) = parseInput(input)
var node = "AAA"
var steps = 0
var directionIndex = 0
while (node != "ZZZ") {
node =
if (directions[directionIndex] == 'L') network[node]!!.first else network[node]!!.second
directionIndex = (directionIndex + 1) % directions.size
steps += 1
}
return steps
}
fun part2(input: List<String>): Long {
val (directions, network) = parseInput(input)
val aNodeMap =
network.keys.filter { it.endsWith('A') }.associateBy({ it }, { mutableListOf<Long>() })
val zNodes = network.keys.filter { it.endsWith('Z') }
for (aNode in aNodeMap.keys) {
var node = aNode
var steps = 0L
var directionIndex = 0
val cache = mutableSetOf<Pair<String, Int>>()
while (!cache.contains(node to directionIndex)) {
cache.add(node to directionIndex)
node =
if (directions[directionIndex] == 'L') network[node]!!.first else network[node]!!.second
directionIndex = (directionIndex + 1) % directions.size
steps += 1L
if (node in zNodes) aNodeMap[aNode]!!.add(steps)
}
}
return aNodeMap.values.flatten().toSet().reduce { acc, num -> lcm(acc, num) }
}
private fun parseInput(input: List<String>): Pair<CharArray, Map<String, Pair<String, String>>> {
val directions = input[0].toCharArray()
val network = mutableMapOf<String, Pair<String, String>>()
val nodeRegex = "^([A-Z0-9]{3}) = \\(([A-Z0-9]{3}), ([A-Z0-9]{3})\\)".toRegex()
for (i in 2..<input.size) {
val (node, nodeL, nodeR) = nodeRegex.find(input[i])!!.destructured
network[node] = nodeL to nodeR
}
return directions to network
}
}
fun main() {
val day08 = Day08()
val input = readInputAsStringList("day08.txt")
println("08, part 1: ${day08.part1(input)}")
println("08, part 2: ${day08.part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 18b97d650f4a90219bd6a81a8cf4d445d56ea9e8 | 2,197 | advent-of-code-2023 | MIT License |
src/Day02.kt | illarionov | 572,508,428 | false | {"Kotlin": 108577} | import HandShape.*
import RoundResult.*
enum class HandShape(val shapeScore: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3)
}
enum class RoundResult(val score: Int) {
LOST(0), DRAW(3), WON(6)
}
fun HandShape.roundResultAgainst(opponentShape: HandShape): RoundResult {
return when (shapeScore - opponentShape.shapeScore) {
0 -> DRAW
1 -> WON
2 -> LOST
-1 -> LOST
-2 -> WON
else -> error("Wrong result")
}
}
data class StrategyRecord(
val elfShape: HandShape,
val playerShape: HandShape
) {
val roundResult: RoundResult
get() = playerShape.roundResultAgainst(elfShape)
}
data class StrategyItemPart2(
val elfShape: HandShape,
val expectedResult: RoundResult
) {
val expectedShape: HandShape get() = HandShape.values().first {
it.roundResultAgainst(elfShape) == expectedResult
}
}
fun String.toStrategy(): StrategyRecord {
val res = this.split(" ")
return StrategyRecord(res[0].toElfShape(), res[1].toPlayerShape())
}
fun String.toStrategy2(): StrategyItemPart2 {
val res = this.split(" ")
return StrategyItemPart2(res[0].toElfShape(), res[1].toExpectedResult())
}
fun String.toElfShape(): HandShape = when (this) {
"A" -> ROCK
"B" -> PAPER
"C" -> SCISSORS
else -> error("Unknown string $this")
}
fun String.toPlayerShape(): HandShape = when (this) {
"X" -> ROCK
"Y" -> PAPER
"Z" -> SCISSORS
else -> error("Unknown string $this")
}
fun String.toExpectedResult(): RoundResult = when (this) {
"X" -> LOST
"Y" -> DRAW
"Z" -> WON
else -> error("Unknown string $this")
}
fun main() {
fun part1(input: List<StrategyRecord>): Int {
return input.sumOf { s -> s.roundResult.score + s.playerShape.shapeScore }
}
fun part2(input: List<StrategyItemPart2>): Int {
return input.sumOf { s ->
s.expectedResult.score + s.expectedShape.shapeScore
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
.map(String::toStrategy)
check(part1(testInput) == 15)
val input = readInput("Day02")
.map(String::toStrategy)
val totalScore1 = part1(input)
//check(totalScore1 == 13682)
println(totalScore1)
val input2 = readInput("Day02")
.map(String::toStrategy2)
val totalScore2 = part2(input2)
//check(totalScore2 == 12881)
println(totalScore2)
}
| 0 | Kotlin | 0 | 0 | 3c6bffd9ac60729f7e26c50f504fb4e08a395a97 | 2,482 | aoc22-kotlin | Apache License 2.0 |
src/Day12.kt | CrazyBene | 573,111,401 | false | {"Kotlin": 50149} | fun main() {
data class Node(val xPos: Int, val yPos: Int, val height: Char, val isStart: Boolean, val isEnd: Boolean) {
val neighbours = mutableListOf<Node>()
}
fun Char.isNextTo(otherChar: Char) = otherChar.code - code <= 1
fun List<String>.toHill(): List<List<Node>> {
val hill = this.mapIndexed { yPos, line ->
line.mapIndexed { xPos, char ->
val height = when (char) {
'S' -> 'a'
'E' -> 'z'
else -> char
}
Node(xPos, yPos, height, char == 'S', char == 'E')
}
}
val height = hill.size
val width = hill[0].size
for (y in 0 until height) {
for (x in 0 until width) {
val currentNode = hill[y][x]
val potentialNeighbours = mutableListOf<Node>()
if (x > 0)
potentialNeighbours.add(hill[y][x - 1])
if (x < width - 1)
potentialNeighbours.add(hill[y][x + 1])
if (y > 0)
potentialNeighbours.add(hill[y - 1][x])
if (y < height - 1)
potentialNeighbours.add(hill[y + 1][x])
currentNode.neighbours.addAll(
potentialNeighbours.filter {
currentNode.height.isNextTo(it.height)
}
)
}
}
return hill
}
fun solveWithDijkstra(nodes: List<Node>, startNodes: List<Node>): Pair<Map<Node, Int>, Map<Node, Node?>> {
val distances = nodes.associateWith { Int.MAX_VALUE }.toMutableMap()
val previous: MutableMap<Node, Node?> = nodes.associateWith { null }.toMutableMap()
val notYetVisited = mutableListOf<Node>()
notYetVisited.addAll(nodes)
startNodes.forEach {
distances[it] = 0
}
while (notYetVisited.isNotEmpty()) {
val currentNode = notYetVisited.sortedBy { distances[it] }.first()
notYetVisited.remove(currentNode)
for (neighbor in currentNode.neighbours) {
if (neighbor !in notYetVisited)
continue
val newDistance = distances[currentNode]!!.plus(1)
if (newDistance < distances[neighbor]!!) {
distances[neighbor] = newDistance
previous[neighbor] = currentNode
}
}
}
return distances to previous
}
fun evaluateSteps(previousGraph: Map<Node, Node?>, from: Node, until: List<Node>): Int {
var steps = 0
var checkNode: Node? = from
while (checkNode != null) {
if (checkNode in until)
return steps
steps++
checkNode = previousGraph[checkNode]
}
error("Could not find a way to the until(s).")
}
fun part1(input: List<String>): Int {
val nodes = input.toHill().flatten()
val startNode = nodes.first {
it.isStart
}
val endNode = nodes.first {
it.isEnd
}
val (_, previousGraph) = solveWithDijkstra(nodes, listOf(startNode))
var steps = 0
var checkNode: Node? = endNode
while (checkNode != null) {
steps++
checkNode = previousGraph[checkNode]
}
return evaluateSteps(previousGraph, endNode, listOf(startNode))
}
fun part2(input: List<String>): Int {
val nodes = input.toHill().flatten()
val possibleStartNodes = nodes.filter {
it.height == 'a'
}
val endNode = nodes.first {
it.isEnd
}
val (_, previousGraph) = solveWithDijkstra(nodes, possibleStartNodes)
return evaluateSteps(previousGraph, endNode, possibleStartNodes)
}
val testInput = readInput("Day12Test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12")
println("Question 1 - Answer: ${part1(input)}")
println("Question 2 - Answer: ${part2(input)}")
} | 0 | Kotlin | 0 | 0 | dfcc5ba09ca3e33b3ec75fe7d6bc3b9d5d0d7d26 | 4,180 | AdventOfCode2022 | Apache License 2.0 |
src/Day03.kt | drothmaler | 572,899,837 | false | {"Kotlin": 15196} | import ElfGroup.Companion.groupBadges
import Rucksack.Companion.groupElves
import Rucksack.Companion.toRucksacks
@JvmInline
value class Item(private val char: Char) {
val priority: Int
get() = when (char) {
in 'a'..'z' -> char.code - 97 + 1
in 'A'..'Z' -> char.code - 65 + 27
else -> throw IllegalArgumentException()
}
override fun toString(): String = char.toString()
}
data class Compartment(val items:Sequence<Item>) {
constructor(items: CharSequence) : this(items.asSequence().map { Item(it) })
override fun toString(): String = items.joinToString("")
}
data class Rucksack (val left: Compartment, val right: Compartment) {
constructor(items: String) : this(
Compartment(items.subSequence(0, items.length / 2)),
Compartment(items.subSequence(items.length / 2, items.length))
)
private val sharedItems = left.items.toSet().intersect(right.items.toSet())
val sharedItem = sharedItems.single()
val compartments = listOf(left.toString(), right.toString())
val items = left.items.toSet() + right.items.toSet()
companion object {
fun Sequence<String>.toRucksacks() = this.map { Rucksack(it) }
fun Sequence<Rucksack>.groupElves() = this.chunked(3).map { ElfGroup(it) }
}
}
@JvmInline
value class ElfGroup(private val elves: List<Rucksack>) {
val groupBadge get() = elves.map { it.items }.reduce { acc, items -> acc.intersect(items)}.single()
companion object {
val Sequence<ElfGroup>.groupBadges get() = this.map { it.groupBadge }
}
}
fun main() {
fun part1(input: Sequence<String>) = input.toRucksacks().sumOf { it.sharedItem.priority }
fun part2(input: Sequence<String>) = input.toRucksacks().groupElves().groupBadges.sumOf { it.priority }
val testInput = readSanitizedInput("Day03_test")
val testOutput = testInput.asSequence().toRucksacks().toList()
val testCompartments = testOutput.take(3).map { it.compartments }
val expectedCompartments = listOf(
listOf("vJrwpWtwJgWr", "hcsFMMfFFhFp"),
listOf("jqHRNqRjqzjGDLGL", "rsFMfFZSrLrFZsSL"),
listOf("PmmdzqPrV", "vPwwTWBwg")
)
check(testCompartments.count() == expectedCompartments.count())
testCompartments.zip(expectedCompartments).forEach { (actual, expected) ->
check(actual == expected)
}
val testShared = testOutput.map { it.sharedItem.toString() }
check(testShared == listOf(
"p", "L", "P", "v", "t", "s"
))
val test1Output = useSanitizedInput("Day03_test", ::part1)
check(test1Output == 157)
val testBadges = testOutput.asSequence().groupElves().groupBadges.map { it.toString() }.toList()
check(testBadges == listOf(
"r", "Z"
))
val test2Output = useSanitizedInput("Day03_test", ::part2)
check(test2Output == 70)
val output = useSanitizedInput("Day03", ::part1)
println(output)
val output2 = useSanitizedInput("Day03", ::part2)
println(output2)
}
| 0 | Kotlin | 0 | 0 | 1fa39ebe3e4a43e87f415acaf20a991c930eae1c | 3,040 | aoc-2022-in-kotlin | Apache License 2.0 |
src/algorithmsinanutshell/spatialtree/KDTree.kt | realpacific | 234,499,820 | false | null | package algorithmsinanutshell.spatialtree
import algorithmdesignmanualbook.print
import kotlin.math.pow
import kotlin.math.sqrt
/**
* K-d tree is a binary search tree with more than 1 dimensions (i.e k dimensions).
*
* A 2-d tree looks like given points ((3, 6), (17, 15), (13, 15), (6, 12), (9, 1), (2, 7), (10, 19))
*
*
* (3, 6) ----> compare x coordinate
* / \
* (2,7) (17, 15) ----y compare y
* / \
* (6,12) (13,15) ----x compare x
* \ /
* (9,1) (10,19) ----y
*
* At each level, the dimensions of points are compared in alternating manner.
*
*/
class KDTree(val array: Array<Array<Int>>) {
val tree: MultiDimNode
init {
require(array.isNotEmpty())
require(array.map { it.size }.distinct().size == 1)
tree = MultiDimNode(array[0])
for (i in 1..array.lastIndex) {
tree.insert(array[i], 0)
}
}
fun print() {
println(tree)
}
fun search() {
}
}
class MultiDimNode(val value: Array<Int>, var left: MultiDimNode? = null, var right: MultiDimNode? = null) {
fun insert(newValue: Array<Int>, height: Int) {
val numberOfDimensions = newValue.size
require(value.size == numberOfDimensions)
val dimensionIndexToCompare = height % numberOfDimensions
if (newValue[dimensionIndexToCompare] < value[dimensionIndexToCompare]) {
if (left == null) {
left = MultiDimNode(newValue)
} else {
left!!.insert(newValue, height + 1)
}
} else {
if (right == null) {
right = MultiDimNode(newValue)
} else {
right!!.insert(newValue, height + 1)
}
}
}
fun distanceFrom(target: Array<Int>): Double {
var sum = 0.0
for (i in 0..value.lastIndex) {
sum += (target[i] - value[i]).toDouble().pow(2)
}
return sqrt(sum).print {
"Distance ${target.toList()} ${value.toList()} = $it"
}
}
override fun toString(): String {
return "Node(${value.toList()}, left=$left, right=$right)"
}
}
fun main() {
val array = arrayOf(
arrayOf(3, 6), arrayOf(17, 15), arrayOf(13, 15),
arrayOf(6, 12), arrayOf(9, 1), arrayOf(2, 7), arrayOf(10, 19)
)
KDTree(array).print()
}
| 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 2,494 | algorithms | MIT License |
app/src/main/kotlin/day08/Day08.kt | W3D3 | 433,748,408 | false | {"Kotlin": 72893} | package day08
import common.InputRepo
import common.readSessionCookie
import common.solve
import kotlin.math.pow
fun main(args: Array<String>) {
val day = 8
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay08Part1, ::solveDay08Part2)
}
data class InputLine(val patterns: Collection<Set<Char>>, val outputValues: Collection<Set<Char>>)
private fun parseSignals(line: String): InputLine {
val uniquePatters = line.split("|")[0].trim().split(" ").map { s -> s.toCharArray().toSet() }
val outputPattern = line.split("|")[1].trim().split(" ").map { s -> s.toCharArray().toSet() }
return InputLine(uniquePatters, outputPattern)
}
fun solveDay08Part1(input: List<String>): Int {
return input.sumOf { line ->
parseSignals(line).outputValues.count { chars -> chars.size in setOf(2, 4, 3, 7) }
}
}
fun solveDay08Part2(input: List<String>): Int {
return input.sumOf { line ->
val (patterns, outputPatterns) = parseSignals(line)
val sizeToPattern = patterns.groupBy { p -> p.size }
val numToPattern = generateNumToPattern(sizeToPattern)
val patternToNum = numToPattern.entries.associate { (k, v) -> v to k }
outputPatterns.withIndex().sumOf { (index, outputPattern) ->
patternToNum[outputPattern]!! * 10.0.pow(outputPatterns.size - (index + 1)).toInt()
}
}
}
private fun generateNumToPattern(sizeToPattern: Map<Int, List<Set<Char>>>): HashMap<Int, Set<Char>> {
val numToPattern = HashMap<Int, Set<Char>>()
// 1, 4, 7, 8 are unique considering size of lines.
numToPattern[1] = sizeToPattern[2]!!.first()
numToPattern[4] = sizeToPattern[4]!!.first()
numToPattern[7] = sizeToPattern[3]!!.first()
numToPattern[8] = sizeToPattern[7]!!.first()
val rightLine = numToPattern[1]!! // Alias 1 to rightLine, to make things more readable
numToPattern[3] = sizeToPattern[5]!!.first { chars -> chars.containsAll(rightLine) } // 3 is the only 5 line digit with the right line turned on
val topL = numToPattern[4]!! subtract rightLine
numToPattern[5] = sizeToPattern[5]!!.first { chars -> chars.containsAll(topL) } // 5 is the only 5 line digit with a top L shape
numToPattern[2] = (sizeToPattern[5]!! subtract setOf(numToPattern[5]!!, numToPattern[3]!!)).first() // 2 is the only 5 line digit left
numToPattern[9] = sizeToPattern[6]!!.first { chars -> chars.containsAll(numToPattern[4]!!) } // 9 is the only 6 line digit with a 4 shape in it
numToPattern[0] = sizeToPattern[6]!!.first { chars -> (chars != numToPattern[9]) and chars.containsAll(rightLine) } // 0 is the only other 6 line digit with a right line (that is not 9)
numToPattern[6] = sizeToPattern[6]!!.subtract(setOf(numToPattern[9]!!, numToPattern[0]!!)).first() // 6 is the only 6 line digit left
return numToPattern
} | 0 | Kotlin | 0 | 0 | df4f21cd99838150e703bcd0ffa4f8b5532c7b8c | 2,998 | AdventOfCode2021 | Apache License 2.0 |
src/Day12.kt | dizney | 572,581,781 | false | {"Kotlin": 105380} | import java.util.LinkedList
object Day12 {
const val EXPECTED_PART1_CHECK_ANSWER = 31
const val EXPECTED_PART2_CHECK_ANSWER = 29
const val CHAR_START = 'S'
const val CHAR_DESTINATION = 'E'
const val CHAR_LOWEST = 'a'
}
fun main() {
fun List<String>.parseData(): Array<CharArray> =
map { it.toCharArray() }.toTypedArray()
fun Array<CharArray>.findLocationOfChar(char: Char) =
this.indexOfFirst { it.contains(char) }.let { vertIndex -> Location(this[vertIndex].indexOf(char), vertIndex) }
fun Array<CharArray>.findLocationsOfChar(char: Char): List<Location> {
val locationsOfChar = mutableListOf<Location>()
this.forEachIndexed { yIndex, listOfChars ->
listOfChars.forEachIndexed { xIndex, possibleChar ->
if (char == possibleChar) {
locationsOfChar.add(Location(xIndex, yIndex))
}
}
}
return locationsOfChar
}
fun Array<CharArray>.getValueAt(location: Location) = this[location.y][location.x]
fun Array<CharArray>.width() = this[0].size
fun Array<CharArray>.height() = this.size
fun Char.mapToHeightValue() = when (this) {
Day12.CHAR_START -> 'a'
Day12.CHAR_DESTINATION -> 'z'
else -> this
}
fun findShortestPath(grid: Array<CharArray>, start: Location): Int {
val destination = grid.findLocationOfChar('E')
val queue = LinkedList<Pair<Location, Int>>()
val visited = mutableSetOf<Location>()
queue.add(start to 0)
visited.add(start)
do {
val locationAndDistance = queue.remove()
val locationHeight = grid.getValueAt(locationAndDistance.first).mapToHeightValue()
if (locationAndDistance.first == destination) {
return locationAndDistance.second
}
val adjCells = listOf(
Location(locationAndDistance.first.x - 1, locationAndDistance.first.y),
Location(locationAndDistance.first.x + 1, locationAndDistance.first.y),
Location(locationAndDistance.first.x, locationAndDistance.first.y - 1),
Location(locationAndDistance.first.x, locationAndDistance.first.y + 1),
).filter { it.x >= 0 && it.y >= 0 && it.x < grid.width() && it.y < grid.height() }
for (adjLocation in adjCells) {
val height = grid.getValueAt(adjLocation).mapToHeightValue()
if ((height - locationHeight <= 1) && !visited.contains(
adjLocation
)
) {
queue.add(adjLocation to locationAndDistance.second + 1)
visited.add(adjLocation)
}
}
} while (queue.isNotEmpty())
return -1
}
fun part1(input: List<String>): Int {
val grid = input.parseData()
return findShortestPath(grid, grid.findLocationOfChar(Day12.CHAR_START))
}
fun part2(input: List<String>): Int {
val grid = input.parseData()
val locationsOfLowest = grid.findLocationsOfChar(Day12.CHAR_LOWEST) + grid.findLocationOfChar(Day12.CHAR_START)
return locationsOfLowest.map { findShortestPath(grid, it) }.filter { it != -1 }.also { println(it) }.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
check(part1(testInput) == Day12.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
check(part2(testInput) == Day12.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f684a4e78adf77514717d64b2a0e22e9bea56b98 | 3,715 | aoc-2022-in-kotlin | Apache License 2.0 |
jk/src/main/kotlin/leetcode/Solution_LeetCode_912_215_347_Quick_Sort_Related.kt | lchang199x | 431,924,215 | false | {"Kotlin": 86230, "Java": 23581} | package leetcode
import common.swap
import java.util.*
/**
* 快速排序相关的一些题目解法
*/
class Solution_LeetCode_912_215_347_Quick_Sort_Related {
/**
* 排序数组: LeetCode_912
* [](https://leetcode-cn.com/problems/sort-an-array/)
*/
fun sortArray(nums: IntArray): IntArray {
quickSort(nums, 0, nums.size - 1)
return nums
}
/**
* 数组中第k大元素: LeetCode_215
* [](https://leetcode-cn.com/problems/kth-largest-element-in-an-array/)
*
* 另堆排序解法
*/
fun findKthLargest(nums: IntArray, k: Int): Int {
return quickSelect(nums, 0, nums.size - 1, nums.size - k)
}
/**
* 前k个高频元素:LeetCode_347
* [](https://leetcode-cn.com/problems/top-k-frequent-elements/)
*/
fun topKFrequent(nums: IntArray, k: Int): IntArray {
val map = mutableMapOf<Int, Int>()
for (num in nums) {
map[num] = map.getOrDefault(num, 0) + 1
}
val list = mutableListOf<IntArray>()
map.forEach {
list.add(intArrayOf(it.key, it.value))
}
// list.size - k 大法好
return quickTopK(list, 0, list.size - 1, list.size - k)
}
private fun quickTopK(list: List<IntArray>, l: Int, r: Int, k: Int): IntArray {
val index = (l..r).random()
Collections.swap(list, index, r)
// 当randomizedPartition和partition写在一起时,记住时nums[r],不是nums[index]
val pivot = list[r][1]
var i = l - 1
// 当list.size == 1时这个for循环不会执行,导致i的值只会在后面自增一次,即k=1,但i=0
// 注意相同的情况kthLargest将k=1转化为了k=0
for (j in l until r) {
if (list[j][1] <= pivot) {
Collections.swap(list, ++i, j)
}
}
Collections.swap(list, ++i, r)
return if (k == i) {
list.subList(k, list.size).map { it[0] }.toIntArray()
} else if (k < i) {
quickTopK(list, l, i - 1, k)
} else {
quickTopK(list, i + 1, r, k)
}
}
private fun quickSort(nums: IntArray, l: Int, r: Int) {
if (l < r) {
val pos = randomizedPartition(nums, l, r)
quickSort(nums, l, pos - 1)
quickSort(nums, pos + 1, r)
}
}
private fun quickSelect(nums: IntArray, l: Int, r: Int, k: Int): Int {
val pos = randomizedPartition(nums, l, r)
return if (k == pos) {
nums[k]
} else if (k < pos) {
quickSelect(nums, l, pos - 1, k)
} else {
quickSelect(nums, pos + 1, r, k)
}
}
private fun randomizedPartition(nums: IntArray, l: Int, r: Int): Int {
val i = (l..r).random()
swap(nums, r, i)
return partition(nums, l, r)
}
private fun partition(nums: IntArray, l: Int, r: Int): Int {
val pivot = nums[r]
var i = l - 1
for (j in l until r) {
if (nums[j] <= pivot) {
i += 1
swap(nums, i, j)
}
}
swap(nums, i + 1, r)
return i + 1
}
}
fun main() {
println(
Solution_LeetCode_912_215_347_Quick_Sort_Related()
.sortArray(intArrayOf(1, 5, 3, 2, 4)).contentToString()
)
println(
Solution_LeetCode_912_215_347_Quick_Sort_Related()
.findKthLargest(intArrayOf(1, 5, 3, 2, 4), 2)
)
println(
Solution_LeetCode_912_215_347_Quick_Sort_Related()
.topKFrequent(intArrayOf(1), 1).contentToString()
)
println(
Solution_LeetCode_912_215_347_Quick_Sort_Related()
.topKFrequent(intArrayOf(1, 1, 5, 3, 3, 3, 2, 5, 4), 2).contentToString()
)
} | 0 | Kotlin | 0 | 0 | 52a008325dd54fed75679f3e43921fcaffd2fa31 | 3,817 | Codelabs | Apache License 2.0 |
src/AoC3.kt | Pi143 | 317,631,443 | false | null | import java.io.File
fun main() {
println("Starting Day 3 A Test 1")
calculateDay3PartA("Input/2020_Day3_A_Test1")
println("Starting Day 3 A Real")
calculateDay3PartA("Input/2020_Day3_A")
println("Starting Day 3 B Test 1")
calculateDay3PartB("Input/2020_Day3_A_Test1")
println("Starting Day 3 B Real")
calculateDay3PartB("Input/2020_Day3_A")
}
fun calculateDay3PartA(file: String) {
val day3Data = readDay3Data(file)
val movement = Pair(3, 1)
val treeCounter = countTrees(day3Data, movement)
println("$treeCounter trees hit.")
}
fun calculateDay3PartB(file: String) {
val day3Data = readDay3Data(file)
val movementList = ArrayList<Pair<Int,Int>>()
movementList.add(Pair(1,1))
movementList.add(Pair(3,1))
movementList.add(Pair(5,1))
movementList.add(Pair(7,1))
movementList.add(Pair(1,2))
var treeProduct = 1
for (movement in movementList){
val treeCounter = countTrees(day3Data, movement)
treeProduct *= treeCounter
}
println("$treeProduct is the treeproduct.")
}
fun countTrees( day3Data: MutableList<List<Boolean>>, movement: Pair<Int, Int>): Int {
var position = Pair(0, 0) //First=x=right; Second=y=down
var treeCounter = 0
val slideLength = day3Data.size
while (position.second < slideLength) {
if (isTree(position, day3Data)) {
treeCounter++
}
position = Pair(position.first + movement.first, position.second + movement.second)
}
return treeCounter
}
fun isTree(position: Pair<Int, Int>, day3Data: MutableList<List<Boolean>>): Boolean {
val patternLength = day3Data[0].size
val right = position.first % patternLength
val down = position.second
return day3Data[down][right]
}
fun readDay3Data(input: String): MutableList<List<Boolean>> {
val map: MutableList<List<Boolean>> = ArrayList()
File(localdir + input).forEachLine {
map.add(readMapLine(it))
}
return map
}
fun readMapLine(string: String): MutableList<Boolean> {
val rowList: MutableList<Boolean> = ArrayList()
string.forEach {
if (it == '#') {
rowList.add(true)
} else {
rowList.add(false)
}
}
return rowList
}
| 0 | Kotlin | 0 | 1 | fa21b7f0bd284319e60f964a48a60e1611ccd2c3 | 2,263 | AdventOfCode2020 | MIT License |
src/Day02.kt | tblechmann | 574,236,696 | false | {"Kotlin": 5756} | fun main() {
fun part1(input: List<String>): Int {
val scores = mapOf(
"A X" to 3 + 1,
"A Y" to 6 + 2,
"A Z" to 0 + 3,
"B X" to 0 + 1,
"B Y" to 3 + 2,
"B Z" to 6 + 3,
"C X" to 6 + 1,
"C Y" to 0 + 2,
"C Z" to 3 + 3,
)
return input.map { scores[it] }.sumOf { it!! }
}
fun part2(input: List<String>): Int {
val scores = mapOf(
"A X" to 0 + 3, /* Rock - Scissor */
"A Y" to 3 + 1, /* Rock - Rock */
"A Z" to 6 + 2, /* Rock - Paper */
"B X" to 0 + 1, /* Paper - Rock */
"B Y" to 3 + 2, /* Paper - Paper */
"B Z" to 6 + 3, /* Paper - Scissor */
"C X" to 0 + 2, /* Scissor - Paper */
"C Y" to 3 + 3, /* Scissor - Scissor */
"C Z" to 6 + 1, /* Scissor - Rock */
)
return input.map { scores[it] }.sumOf { it!! }
}
// 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 | 4a65f6468a0cddd8081f2f0e3c1a96935438755f | 1,262 | aoc2022 | Apache License 2.0 |
src/Day04.kt | ivancordonm | 572,816,777 | false | {"Kotlin": 36235} | fun main() {
fun part1(input: List<String>) =
input.map {
it.split(",").map { pairs -> pairs.split("-") }.map { pair -> pair.first().toInt() to pair.last().toInt() }
.let { pairs -> pairs.first().isFully(pairs.last()) }
}.count { it }
fun part2(input: List<String>) =
input.map {
it.split(",").map { pairs -> pairs.split("-") }.map { pair -> pair.first().toInt() to pair.last().toInt() }
.let { pairs -> pairs.first().isPartial(pairs.last()) }
}.count { it }
val testInput = readInput("Day04_test")
val input = readInput("Day04")
println(part1(testInput))
check(part1(testInput) == 2)
println(part1(input))
println(part2(testInput))
check(part2(testInput) == 4)
println(part2(input))
}
private fun Pair<Int, Int>.isFully(other: Pair<Int, Int>) =
(first <= other.first && second >= other.second) || (other.first <= first && other.second >= second)
private fun Pair<Int, Int>.isPartial(other: Pair<Int, Int>) = (first..second).any { it in (other.first..other.second)}
| 0 | Kotlin | 0 | 2 | dc9522fd509cb582d46d2d1021e9f0f291b2e6ce | 1,107 | AoC-2022 | Apache License 2.0 |
src/main/kotlin/day-09.kt | warriorzz | 434,696,820 | false | {"Kotlin": 16719} | package com.github.warriorzz.aoc
import java.nio.file.Files
import java.nio.file.Path
private fun main() {
println("Day 9:")
val positions: List<List<Point>> = Files.readAllLines(Path.of("./input/day-09.txt"))
.map { it.toCharArray().map { Point(it.digitToInt(), it.digitToInt() + 1) } }
positions.forEachIndexed { y, points ->
points.forEachIndexed point@{ x, point ->
if (y != 0) if (positions[y - 1][x].height <= point.height) return@point
if (y != positions.size - 1) if (positions[y + 1][x].height <= point.height) return@point
if (x != 0) if (positions[y][x - 1].height <= point.height) return@point
if (x != points.size - 1) if (positions[y][x + 1].height <= point.height) return@point
point.isRisk = true
}
}
val solution1 = positions.map { points ->
points.map { if (it.isRisk) it.riskLevel else 0 }.reduce { acc, i -> acc + i }
}.reduce { acc, i -> acc + i }
println("Solution part 1: $solution1")
val basins = mutableListOf<Int>()
positions.forEachIndexed { y, points ->
points.forEachIndexed { x, point ->
if (point.isRisk) {
basins.add(point.getBasinSize(positions, x, y))
}
}
}
val solution2 = basins.sortedDescending().first() * basins.sortedDescending()[1] * basins.sortedDescending()[2]
println("Solution part 2: $solution2")
}
data class Point(val height: Int, val riskLevel: Int, var isRisk: Boolean = false) {
private val alreadyUsed = mutableListOf<Pair<Int, Int>>()
fun getBasinSize(positions: List<List<Point>>, x: Int, y: Int): Int {
if (!isRisk) return 0
return getSurroundingBasinSpots(x, y, positions.map { it.map { it.height } })
}
private fun getSurroundingBasinSpots(x: Int, y: Int, positions: List<List<Int>>): Int {
alreadyUsed.add(x to y)
var basinSpots = 0
if (y != 0 && !alreadyUsed.contains(x to y - 1) && positions[y - 1][x] > positions[y][x] && positions[y - 1][x] != 9) basinSpots += getSurroundingBasinSpots(x, y - 1, positions)
if (x != 0 && !alreadyUsed.contains(x - 1 to y) && positions[y][x - 1] > positions[y][x] && positions[y][x - 1] != 9) basinSpots += getSurroundingBasinSpots(x - 1, y, positions)
if (y != positions.size - 1 && !alreadyUsed.contains(x to y + 1) && positions[y + 1][x] > positions[y][x] && positions[y + 1][x] != 9) basinSpots += getSurroundingBasinSpots(x, y + 1, positions)
if (x != positions[0].size - 1 && !alreadyUsed.contains(x + 1 to y) && positions[y][x + 1] > positions[y][x] && positions[y][x + 1] != 9) basinSpots += getSurroundingBasinSpots(x + 1, y, positions)
return basinSpots + 1
}
}
fun day09() = main()
| 0 | Kotlin | 1 | 0 | 0143f59aeb8212d4ff9d65ad30c7d6456bf28513 | 2,847 | aoc-21 | MIT License |
src/aoc2022/Day11.kt | RobertMaged | 573,140,924 | false | {"Kotlin": 225650} | package aoc2022
private typealias MonkeyId = Int
private data class Monkey(
val id: Int,
val holdingItems: ArrayDeque<Long>,
val operation: Pair<Char, Int>,
val divisibleBy: Int,
val decision: Pair<Int, Int>,
var inspectedItems: Long = 0
)
private fun List<String>.parseMonkeys(): Map<MonkeyId, Monkey> = filter { it.isNotBlank() }.chunked(6).map { monkeyNotes ->
val id = monkeyNotes.first().split(" ")[1].takeWhile { it.isDigit() }.toInt()
val startingItems = monkeyNotes[1].substringAfter("Starting items: ").chunked(2).filter { it.toIntOrNull() != null }
.map { it.toLong() }
val operation = monkeyNotes[2].substringAfter("Operation: new = ").split(" ")
val dividableBy = monkeyNotes[3].substringAfter("Test: divisible by ").toInt()
val receiverMonkeyIdWhenTrue = monkeyNotes[4].substringAfter(" monkey ").toInt()
val receiverMonkeyIdWhenFalse = monkeyNotes[5].substringAfter(" monkey ").toInt()
return@map Monkey(
id,
ArrayDeque(startingItems),
operation[1].first() to if (operation[2].toIntOrNull() != null) operation[2].toInt() else -1,
dividableBy,
receiverMonkeyIdWhenTrue to receiverMonkeyIdWhenFalse
)
}.associateBy { it.id }
fun main() {
fun Map<MonkeyId, Monkey>.startThrowingItems(rounds: Int, onWorryManage: (Long) -> Long): List<Monkey> {
repeat(rounds) {
for (monkey in this.values) {
monkey.inspectedItems += monkey.holdingItems.size
while (monkey.holdingItems.isNotEmpty()) {
val item = monkey.holdingItems.removeFirstOrNull() ?: continue
val worryOnItemInspection = when (monkey.operation.first) {
'+' -> if (monkey.operation.second == -1) item + item else item + monkey.operation.second
'*' -> if (monkey.operation.second == -1) item * item else item * monkey.operation.second
else -> error("wrong parse")
}
val managedWorry = onWorryManage(worryOnItemInspection)
val receiverMonkeyId = if (managedWorry % monkey.divisibleBy == 0L) monkey.decision.first
else monkey.decision.second
this.getValue(receiverMonkeyId).holdingItems.addLast(managedWorry)
}
}
}
return this.values.toList()
}
fun List<Monkey>.most2ActiveMonkeys() = sortedByDescending { it.inspectedItems }.take(2).let {
it[0].inspectedItems * it[1].inspectedItems
}
fun part1(input: List<String>): Long {
return input.parseMonkeys().startThrowingItems(rounds = 20) { it / 3 }.most2ActiveMonkeys()
}
fun part2(input: List<String>): Long {
val monkeys = input.parseMonkeys()
val totalDivisibleBy = monkeys.values.map { it.divisibleBy }.reduce { acc, i -> acc * i }
return monkeys.startThrowingItems(rounds = 10_000) { it % totalDivisibleBy }.most2ActiveMonkeys()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
check(part1(testInput).also(::println) == 10605L)
check(part2(testInput).also(::println) == 2713310158)
val input = readInput("Day11")
// println(part1(input))
check(part1(input).also(::println) == 55458L)
println(part2(input))
check(part2(input).also(::println) == 14508081294)
}
| 0 | Kotlin | 0 | 0 | e2e012d6760a37cb90d2435e8059789941e038a5 | 3,482 | Kotlin-AOC-2023 | Apache License 2.0 |
src/Day05.kt | richardmartinsen | 572,910,850 | false | {"Kotlin": 14993} | import java.util.Stack
fun main() {
fun part1(input: List<String>): String {
val chunks = input.first().split("\n").map { line ->
val chunk = line.chunked(4)
chunk
}
val rows = chunks.last()
val stacks = rows.map { Stack<String>() }
val c = chunks.filterNot { it == rows }
c.reversed().map {
it.forEachIndexed { i, v ->
if (v.trim().isNotEmpty()) stacks[i].push(v.trim())
}
}
val commands = input[1].split("\n").map {
it.split(" ")
}
commands.filterNot { it[0].isEmpty() }.forEach { command ->
repeat(command[1].toInt()) {
val from = command[3].toInt() - 1
val to = command[5].toInt() - 1
val pop = stacks[from].pop()
stacks[to].push(pop)
}
}
var solution = ""
stacks.forEach {
solution += it.pop().filter { it.isLetter() }
}
return solution
}
fun part2(input: List<String>): String {
val chunks = input.first().split("\n").map { line ->
val chunk = line.chunked(4)
chunk
}
val rows = chunks.last()
val stacks = rows.map { Stack<String>() }
val c = chunks.filterNot { it == rows }
c.reversed().map {
it.forEachIndexed { i, v ->
if (v.trim().isNotEmpty()) stacks[i].push(v.trim())
}
}
val commands = input[1].split("\n").map {
it.split(" ")
}
commands.filterNot { it[0].isEmpty() }.forEach { command ->
val tempStack = Stack<String>()
repeat(command[1].toInt()) {
val from = command[3].toInt() - 1
tempStack.push(stacks[from].pop())
}
repeat(command[1].toInt()) {
val to = command[5].toInt() - 1
stacks[to].push(tempStack.pop())
}
}
var solution = ""
stacks.forEach {
solution += it.pop().filter { it.isLetter() }
}
return solution
}
val input = readFileSplitEmptyline("Day05")
println(part1(input))
println(part2(input))
check(part1(input) == "PSNRGBTFT")
check(part2(input) == "BNTZFPMMW")
}
| 0 | Kotlin | 0 | 0 | bd71e11a2fe668d67d7ee2af5e75982c78cbe193 | 2,361 | adventKotlin | Apache License 2.0 |
src/main/kotlin/net/navatwo/adventofcode2023/day4/Day4Solution.kt | Nava2 | 726,034,626 | false | {"Kotlin": 100705, "Python": 2640, "Shell": 28} | package net.navatwo.adventofcode2023.day4
import net.navatwo.adventofcode2023.framework.ComputedResult
import net.navatwo.adventofcode2023.framework.Solution
sealed class Day4Solution : Solution<List<Day4Solution.Card>> {
data object Part1 : Day4Solution() {
override fun solve(input: List<Card>): ComputedResult {
var result = 0L
for (card in input) {
val winningNumbersMatched = card.computeWinningNumbers()
if (winningNumbersMatched >= 1) {
// 2^N
val score = 1 shl (winningNumbersMatched - 1)
result += score
}
}
return ComputedResult.Simple(result)
}
}
data object Part2 : Day4Solution() {
override fun solve(input: List<Card>): ComputedResult {
val winningNumbersPerCard = input.associateWith { it.computeWinningNumbers() }
// do a DFS of the winning cards
// compute the number of winning cards in reverse order, then sum them up
val winningCardsPerId = input.associateTo(HashMap(input.size)) { it.id to 1L }
for (card in input.reversed()) {
val winningNumbers = winningNumbersPerCard.getValue(card)
winningCardsPerId.computeIfPresent(card.id) { id, value ->
value + (1..winningNumbers).sumOf { winningCardsPerId.getValue(it + id) }
}
}
val result = winningCardsPerId.values.sum()
return ComputedResult.Simple(result)
}
}
override fun parse(lines: Sequence<String>): List<Card> {
return lines
.filter { it.isNotBlank() }
.map { line ->
val withoutPrefix = line.substring("Card ".length)
val idString = withoutPrefix.substring(0, withoutPrefix.indexOf(':'))
val id = idString.trimStart().toInt()
val (winningNumbersString, playableNumbersString) = withoutPrefix
.subSequence(idString.length + 2, withoutPrefix.length)
.split(" | ", limit = 2)
Card(
id = id,
winningNumbers = parseInts(winningNumbersString),
playableNumbers = parseInts(playableNumbersString),
)
}
.toList()
}
private fun parseInts(line: String): Set<Int> {
return line.splitToSequence(' ')
.filter { it.isNotBlank() }
.map { it.toInt() }
.toSet()
}
data class Card(
val id: Int,
val winningNumbers: Set<Int>,
val playableNumbers: Set<Int>,
) {
fun computeWinningNumbers(): Int = winningNumbers.count { it in playableNumbers }
}
}
| 0 | Kotlin | 0 | 0 | 4b45e663120ad7beabdd1a0f304023cc0b236255 | 2,480 | advent-of-code-2023 | MIT License |
2021/src/main/kotlin/Day08.kt | eduellery | 433,983,584 | false | {"Kotlin": 97092} | class Day08(private val input: List<String>) {
private fun List<String>.entries(): List<Entry> = this.map { it.split(" | ") }.map { (patterns, output) ->
patterns.split(" ").map { it.toSet() } to output.split(" ").map { it.toSet() }
}
private fun countUnique(entries: List<Entry>): Int =
entries.flatMap { it.second }.count { it.size in arrayOf(2, 3, 4, 7) }
private fun countAll(entries: List<Entry>): Int = entries.sumOf { (patterns, output) ->
val mappedDigits = mutableMapOf(
1 to patterns.first { it.size == 2 },
4 to patterns.first { it.size == 4 },
7 to patterns.first { it.size == 3 },
8 to patterns.first { it.size == 7 }
)
with(mappedDigits) {
put(3, patterns.filter { it.size == 5 }.first { it.containsAll(getValue(1)) })
put(2, patterns.filter { it.size == 5 }.first { it.intersect(getValue(4)).size == 2 })
put(5, patterns.filter { it.size == 5 }.first { it !in values })
put(9, patterns.filter { it.size == 6 }.first { it.containsAll(getValue(4)) })
put(6, patterns.filter { it.size == 6 }.first { it.intersect(getValue(1)).size == 1 })
put(0, patterns.filter { it.size == 6 }.first { it !in values })
}
val mappedPatterns = mappedDigits.entries.associateBy({ it.value }) { it.key }
output.joinToString("") { mappedPatterns.getValue(it).toString() }.toInt()
}
fun solve1(): Int {
return countUnique(input.entries())
}
fun solve2(): Int {
return countAll(input.entries())
}
} | 0 | Kotlin | 0 | 1 | 3e279dd04bbcaa9fd4b3c226d39700ef70b031fc | 1,631 | adventofcode-2021-2025 | MIT License |
src/day07/Day07.kt | iulianpopescu | 572,832,973 | false | {"Kotlin": 30777} | package day07
import readInput
private const val DAY = "07"
private const val DAY_TEST = "day${DAY}/Day${DAY}_test"
private const val DAY_INPUT = "day${DAY}/Day${DAY}"
fun main() {
fun parseInput(commands: List<String>): Directory {
val queue = ArrayDeque<Directory>()
queue.add(Directory("/")) // create root
var index = 1
while (index <= commands.lastIndex) {
if (commands[index] == "$ ls") {
val currentDirectory = queue.first()
index++
while (index <= commands.lastIndex && !commands[index].startsWith("$")) {
if (commands[index].startsWith("dir")) {
val dir = Directory(commands[index].removePrefix("dir "))
currentDirectory.directories.add(dir)
} else {
val (size, name) = commands[index].split(' ')
currentDirectory.files.add(File(name, size.toInt()))
}
index++
}
} else if (commands[index] == "$ cd ..") {
queue.removeFirst()
index++
} else if (commands[index].startsWith("$ cd ")) {
val dir = commands[index].removePrefix("$ cd ")
val currentDirectory = queue.first()
queue.add(0, currentDirectory.directories.single { dir == it.name })
index++
}
}
return queue.last() // should be root
}
fun computeSizes(root: Directory): Int {
val dirSize = root.files.sumOf { it.size } + root.directories.sumOf {
computeSizes(it)
}
root.size = dirSize
return dirSize
}
fun sum(root: Directory): Int {
var initialSum = if (root.size < 100000) root.size else 0
initialSum += root.directories.sumOf { sum(it) }
return initialSum
}
fun part1(input: List<String>): Int {
val root = parseInput(input)
computeSizes(root)
return sum(root)
}
val totalSpace = 70000000
val targetMinSpace = 30000000
var unusedSpace = 0
var minDirectory: Directory? = null
fun minDelete(root: Directory) {
if (unusedSpace + root.size >= targetMinSpace && (minDirectory == null || minDirectory!!.size > root.size)) {
minDirectory = root
}
root.directories.forEach { minDelete(it) }
}
fun part2(input: List<String>): Int {
val root = parseInput(input)
computeSizes(root)
unusedSpace = totalSpace - root.size
minDelete(root)
return minDirectory!!.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput(DAY_TEST)
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput(DAY_INPUT)
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()
) {
var size: Int = 0
}
| 0 | Kotlin | 0 | 0 | 4ff5afb730d8bc074eb57650521a03961f86bc95 | 3,211 | AOC2022 | Apache License 2.0 |
src/day4/main.kt | DonaldLika | 434,183,449 | false | {"Kotlin": 11805} | package day4
import assert
import readLines
fun main() {
fun part1(bingoBoard: Lottery): Int {
return bingoBoard.firstWinner()
}
fun part2(bingoBoard: Lottery): Int {
return bingoBoard.lastWinner()
}
// example
val testInput = readData("day4/test")
assert(part1(testInput) == 4512)
assert(part2(testInput) == 1924)
val input = readData("day4/input")
val part1Result = part1(input)
val part2Result = part2(input)
println("Result of part 1= $part1Result")
println("Result of part 2= $part2Result")
}
fun readData(fileName: String): Lottery {
val lines = readLines(fileName)
val draw = lines
.first()
.split(",").map { v -> v.toInt() }
val matrices = lines.asSequence().drop(2)
.filter { it.isNotEmpty() }
.map {
it.split("\\s+".toRegex())
.filter { nr -> nr.isNotBlank() }
.map { str -> str.toInt() }
}.chunked(5).map {
Board(it)
}.toList()
return Lottery(draw, matrices)
}
class Board(private val values: List<List<Int>>, var isWinner: Boolean = false) {
fun verifyDraw(draw: List<Int>): Boolean {
val completedRow = values.any {
draw.containsAll(it)
}
val completedColumn = values.indices.any {
draw.containsAll(values.map { v -> v[it] })
}
return completedRow || completedColumn
}
fun markAsWinner() {
this.isWinner = true
}
fun sumOfUnMarked(draw: List<Int>) = values
.flatMap { it.toList() }
.filter { !draw.contains(it) }
.sum()
}
data class Lottery(private val draws: List<Int>, private val boards: List<Board>) {
fun firstWinner(): Int {
for (i in 5 until draws.size) {
val currentDraws = draws.subList(0, i)
val firstWinner = announceWinners(currentDraws).firstOrNull()
if (firstWinner != null) {
return firstWinner.sumOfUnMarked(currentDraws) * currentDraws.last()
}
}
throw IllegalStateException("Cannot determine the winner")
}
fun lastWinner(): Int {
var winnerMatrix: Board? = null
var winnerDraws: List<Int>? = null
for (i in 5..draws.size) {
val currentDraws = draws.subList(0, i)
val lastWinner = announceWinners(currentDraws).lastOrNull()
if (lastWinner != null) {
winnerMatrix = lastWinner
winnerDraws = currentDraws
}
}
if (winnerMatrix == null || winnerDraws == null) {
throw IllegalStateException("Cannot determine the winner")
}
return winnerMatrix.sumOfUnMarked(winnerDraws) * winnerDraws.last()
}
private fun announceWinners(draw: List<Int>): List<Board> {
return boards
.filter { it.isWinner.not() } // was not marked as winner before
.filter { it.verifyDraw(draw) } // isWinner on current draw
.map {
it.markAsWinner()
it
}
}
} | 0 | Kotlin | 0 | 0 | b288f16ee862c0a685a3f9e4db34d71b16c3e457 | 3,132 | advent-of-code-2021 | MIT License |
src/Day18.kt | arhor | 572,349,244 | false | {"Kotlin": 36845} | import kotlin.math.abs
/*
# Notes
number of sides for N-dimensional figure is N * 2
point (x=2, y=2, z=5) adjacent points:
by x: (x=1, y=2, z=5)
(x=3, y=2, z=5)
by y: (x=2, y=1, z=5)
(x=2, y=3, z=5)
by z: (x=2, y=2, z=4)
(x=2, y=2, z=6)
for each point
try to find 4 diagonal points with the same plane
*/
fun main() {
val input = readInput {}
// println("Part 1: ${solvePuzzle1(input)}")
println("Part 2: ${solvePuzzle2(input)}")
}
private const val CUBE_SIDES_NUM = 6
private const val CONTACTING_SIDES_NUM = 2
private fun solvePuzzle1(input: List<String>): Int {
val data = parseInput(input)
val test = HashMap<Point3D, List<Point3D>>()
for (i in data.indices) {
val curr = data[i]
val adjacents = ArrayList<Point3D>()
for (j in ((i + 1)..data.lastIndex)) {
val next = data[j]
if (curr adjacentTo next) {
adjacents += next
}
}
test[curr] = adjacents
}
return (data.size * CUBE_SIDES_NUM) - test.values.sumOf { it.size * CONTACTING_SIDES_NUM }
}
private fun solvePuzzle2(input: List<String>): Int {
val data = parseInput(input).sortedWith(compareBy({ it.x }, { it.y }, { it.z }))
val test = HashMap<Point3D, List<Point3D>>()
var droplets = 0
for (i in data.indices) {
val curr = data[i]
val adjacents = ArrayList<Point3D>()
val diagonals = ArrayList<Point3D>()
for (j in ((i + 1)..data.lastIndex)) {
val next = data[j]
if (curr adjacentTo next) {
adjacents += next
}
if (curr diagonalTo next) {
diagonals += next
}
}
test[curr] = adjacents
if (diagonals.size == 4) {
for (j in ((i + 1)..data.lastIndex)) {
val next = data[j]
if (diagonals.all { it diagonalTo next }) {
println("Gotcha! air droplet surroundings ${listOf(curr) + diagonals + listOf(next)}")
droplets++
break
}
}
}
}
return (data.size * CUBE_SIDES_NUM) -
test.values.sumOf { it.size * CONTACTING_SIDES_NUM } -
(droplets * CUBE_SIDES_NUM)
}
private data class Point3D(val x: Int, val y: Int, val z: Int) {
infix fun adjacentTo(other: Point3D): Boolean {
return (x == other.x && y == other.y && abs(z - other.z) == 1)
|| (x == other.x && z == other.z && abs(y - other.y) == 1)
|| (z == other.z && y == other.y && abs(x - other.x) == 1)
}
infix fun diagonalTo(other: Point3D): Boolean {
return /*(abs(x - other.x) == 1 && abs(y - other.y) == 1 && abs(z - other.z) == 1)
|| */(x == other.x && abs(y - other.y) == 1 && abs(z - other.z) == 1)
|| (y == other.y && abs(z - other.z) == 1 && abs(x - other.x) == 1)
|| (z == other.z && abs(x - other.x) == 1 && abs(y - other.y) == 1)
}
}
private fun parseInput(input: List<String>): List<Point3D> = input.map { line ->
line.substringBefore(" *")
.split(",")
.map { it.toInt() }
.let { (x, y, z) -> Point3D(x, y, z) }
}
| 0 | Kotlin | 0 | 0 | 047d4bdac687fd6719796eb69eab2dd8ebb5ba2f | 3,253 | aoc-2022-in-kotlin | Apache License 2.0 |
src/day15/Day15.kt | MaxBeauchemin | 573,094,480 | false | {"Kotlin": 60619} | package day15
import readInput
import java.math.BigInteger
import kotlin.math.abs
data class Coordinate(val x: Int, val y: Int) {
fun distanceFrom(other: Coordinate) = abs(this.x - other.x) + abs(this.y - other.y)
fun upRight() = Coordinate(x + 1, y - 1)
fun upLeft() = Coordinate(x - 1, y - 1)
fun downRight() = Coordinate(x + 1, y + 1)
fun downLeft() = Coordinate(x - 1, y + 1)
}
val inputRegex = """Sensor at x=([-0-9]+), y=([-0-9]+): closest beacon is at x=([-0-9]+), y=([-0-9]+)""".toRegex()
data class Sensor(
val location: Coordinate,
val nearestBeacon: Coordinate
) {
val distanceToNearestBeacon = location.distanceFrom(nearestBeacon)
fun outsideLeft() = Coordinate(location.x - (distanceToNearestBeacon + 1), location.y)
fun outsideRight() = Coordinate(location.x + (distanceToNearestBeacon + 1), location.y)
fun outsideUp() = Coordinate(location.x, location.y - (distanceToNearestBeacon + 1))
fun outsideDown() = Coordinate(location.x, location.y + (distanceToNearestBeacon + 1))
}
fun parse(input: List<String>): List<Sensor> {
return input.mapNotNull { str ->
inputRegex.find(str)?.let { matchResult ->
val (x1, y1, x2, y2) = matchResult.destructured
Sensor(
location = Coordinate(x1.toInt(), y1.toInt()),
nearestBeacon = Coordinate(x2.toInt(), y2.toInt())
)
}
}
}
fun main() {
fun part1(input: List<String>, row: Int): Int {
val sensors = parse(input)
var emptyCount = 0
val startX = sensors.minOf { it.location.x - it.distanceToNearestBeacon }
val endX = sensors.maxOf { it.location.x + it.distanceToNearestBeacon }
for (x in startX..endX) {
Coordinate(x, row).also { spot ->
sensors.any { sensor ->
spot != sensor.nearestBeacon && sensor.location.distanceFrom(spot) <= sensor.distanceToNearestBeacon
}.also { empty ->
if (empty) emptyCount++
}
}
}
return emptyCount
}
fun part2(input: List<String>, maxRange: Int): BigInteger {
val sensors = parse(input)
fun calc(coordinate: Coordinate): BigInteger{
return (BigInteger.valueOf(coordinate.x.toLong()) * BigInteger.valueOf(4000000L)) + BigInteger.valueOf(coordinate.y.toLong())
}
fun foundIt(toCheckAgainst: List<Sensor>, coordinate: Coordinate, maxRange: Int): Boolean {
(0..maxRange).let {
if (coordinate.x !in it) return false
if (coordinate.y !in it) return false
}
return toCheckAgainst.all { sensor ->
sensor.distanceToNearestBeacon < sensor.location.distanceFrom(coordinate) //coordinate != sensor.nearestBeacon &&
}
}
sensors.forEach { sensor ->
val toCheckAgainst = sensors.minus(sensor)
val left = sensor.outsideLeft()
val up = sensor.outsideUp()
val right = sensor.outsideRight()
val down = sensor.outsideDown()
var currSpot = left
while (currSpot != up) {
if (foundIt(toCheckAgainst, currSpot, maxRange)) {
return calc(currSpot)
}
currSpot = currSpot.upRight()
}
while (currSpot != right) {
if (foundIt(toCheckAgainst, currSpot, maxRange)) {
return calc(currSpot)
}
currSpot = currSpot.downRight()
}
while (currSpot != down) {
if (foundIt(toCheckAgainst, currSpot, maxRange)) {
return calc(currSpot)
}
currSpot = currSpot.downLeft()
}
while (currSpot != left) {
if (foundIt(toCheckAgainst, currSpot, maxRange)) {
return calc(currSpot)
}
currSpot = currSpot.upLeft()
}
}
return BigInteger.ZERO
}
val testInput = readInput("Day15_test")
val input = readInput("Day15")
part1(testInput, 10).also {
println("Part 1 [Test] : $it")
check(it == 26)
}
println("Part 1 [Real] : ${part1(input, 2000000)}")
part2(testInput, 20).also {
println("Part 2 [Test] : $it")
check(it == BigInteger.valueOf(56000011L))
}
println("Part 2 [Real] : ${part2(input, 4000000)}")
}
| 0 | Kotlin | 0 | 0 | 38018d252183bd6b64095a8c9f2920e900863a79 | 4,557 | advent-of-code-2022 | Apache License 2.0 |
src/com/kingsleyadio/adventofcode/y2021/day14/Alternative.kt | kingsleyadio | 435,430,807 | false | {"Kotlin": 134666, "JavaScript": 5423} | package com.kingsleyadio.adventofcode.y2021.day14
import com.kingsleyadio.adventofcode.util.readInput
private fun solution(template: String, map: Map<String, Char>, steps: Int): Long {
fun tick(input: Map<String, Long>): Map<String, Long> = buildMap {
for ((pair, count) in input) {
val product = map.getValue(pair)
val first = "${pair[0]}$product"
put(first, getOrDefault(first, 0) + count)
val second = "$product${pair[1]}"
put(second, getOrDefault(second, 0) + count)
}
}
var pairs = buildMap<String, Long> { template.windowed(2).forEach { put(it, getOrDefault(it, 0) + 1) } }
repeat(steps) { pairs = tick(pairs) }
val charArray = LongArray(26)
pairs.forEach { (pair, count) -> pair.forEach { charArray[it - 'A'] += count } }
val max = charArray.maxOrNull()!!
val min = charArray.minOf { if (it == 0L) Long.MAX_VALUE else it }
return (max - min) / 2
}
fun main() {
readInput(2021, 14).useLines { lines ->
val iterator = lines.iterator()
val template = iterator.next()
iterator.next()
val map = buildMap { for (line in iterator) line.split(" -> ").let { (k, v) -> put(k, v[0]) } }
println(solution(template, map, 10))
println(solution(template, map, 40))
}
}
| 0 | Kotlin | 0 | 1 | 9abda490a7b4e3d9e6113a0d99d4695fcfb36422 | 1,335 | adventofcode | Apache License 2.0 |
src/main/kotlin/biz/koziolek/adventofcode/year2022/day05/day5.kt | pkoziol | 434,913,366 | false | {"Kotlin": 715025, "Shell": 1892} | package biz.koziolek.adventofcode.year2022.day05
import biz.koziolek.adventofcode.findInput
fun main() {
val inputFile = findInput(object {})
val (stacks, instructions) = parseCargo(inputFile.bufferedReader().readLines())
val movedStacks = moveCargo(stacks, instructions)
println(movedStacks)
val movedStacksAtOnce = moveCargo(stacks, instructions, atOnce = true)
println(movedStacksAtOnce)
}
data class Stacks(private val stacks: List<List<Char>>) {
val maxHeight = stacks.maxOf { it.size }
fun findTopOfEachStack() = stacks.map { it.last() }
fun execute(instruction: Instruction, atOnce: Boolean): Stacks {
val srcStack = stacks[instruction.from - 1]
val bottom = srcStack.subList(0, srcStack.size - instruction.count)
val top = srcStack.subList(srcStack.size - instruction.count, srcStack.size)
val new = stacks.mapIndexed { index, chars ->
when (index) {
instruction.from - 1 -> bottom
instruction.to - 1 -> chars + if (atOnce) top else top.reversed()
else -> chars
}
}
return Stacks(new)
}
override fun toString(): String {
val footer = (1..stacks.size).joinToString(separator = " ") {
" $it "
}
return (maxHeight - 1 downTo 0)
.joinToString(separator = "\n", postfix = "\n$footer") { rowIndex ->
stacks.joinToString(separator = " ") { stack ->
if (rowIndex < stack.size) {
"[${stack[rowIndex]}]"
} else {
" "
}
}
}
}
}
data class Instruction(
val count: Int,
val from: Int,
val to: Int,
)
fun parseCargo(lines: Iterable<String>): Pair<Stacks, List<Instruction>> {
val stacks = lines
.takeWhile { it.isNotEmpty() }
.reversed()
.drop(1)
.map { it.chunked(4) }
.fold((1..1000).map { emptyList<Char>() }.toList()) { acc, strings ->
acc.zip(strings) { a, b ->
if (b.isNotBlank()) {
a + listOf(b[1])
} else {
a
}
}
}
.let { Stacks(it) }
val instructions = lines
.drop(stacks.maxHeight + 2)
.mapNotNull { line ->
Regex("move ([0-9]+) from ([0-9]+) to ([0-9]+)")
.find(line)
?.let {
val count = it.groupValues[1].toInt()
val from = it.groupValues[2].toInt()
val to = it.groupValues[3].toInt()
Instruction(count, from, to)
}
}
return Pair(stacks, instructions)
}
fun moveCargo(stacks: Stacks, instructions: List<Instruction>, atOnce: Boolean = false): Stacks =
instructions.fold(stacks) { acc, instruction ->
acc.execute(instruction, atOnce)
}
fun readTopOfEachStack(stacks: Stacks): String =
stacks.findTopOfEachStack().joinToString("")
| 0 | Kotlin | 0 | 0 | 1b1c6971bf45b89fd76bbcc503444d0d86617e95 | 3,099 | advent-of-code | MIT License |
src/Day07.kt | Riari | 574,587,661 | false | {"Kotlin": 83546, "Python": 1054} | fun main() {
class Node(var name: String, var isFile: Boolean = false, var size: Int = 0) {
var parent: Node? = null
var children = mutableListOf<Node>()
fun add(node: Node) {
if (isFile) return
children.add(node)
node.parent = this
}
fun find(childName: String): Node? {
children.forEach {
if (it.name == childName) return it
}
return null
}
override fun toString(): String {
var s = "$name ("
s += if (isFile) "file" else "dir"
s += ", size=$size)\n"
if (children.isNotEmpty()) {
children.forEach {
s += " - $it"
}
}
return s
}
}
fun parseToTree(input: List<String>): Node {
var node = Node("/")
for (line in input) {
val parts = line.split(" ")
if (parts[0] == "$") {
if (parts[1] == "cd") {
val path = parts[2]
if (path == "..") {
node = node.parent!!
} else if (node.name != path) {
node = node.find(path)!!
}
}
} else {
if (parts[0] == "dir") {
// Encountered directory
node.add(Node(parts[1]))
} else {
// Encountered file
val size = parts[0].toInt()
var parent = node.parent
while (parent != null) {
parent.size += size
parent = parent.parent
}
node.size += size
node.add(Node(parts[1], true, size))
}
}
}
// Traverse back up to the root node
while (node.parent != null) {
node = node.parent!!
}
return node
}
fun sumDirectories(node: Node, maxSize: Int): Int {
var size = 0
for (child in node.children) {
if (child.isFile) continue
if (child.size <= maxSize) {
size += child.size
}
size += sumDirectories(child, maxSize)
}
return size
}
fun findSmallestDirSizeAbove(node: Node, size: Int): Int {
var smallest = node.size
for (child in node.children) {
if (child.isFile) continue
val innerSmallest = findSmallestDirSizeAbove(child, size)
if (innerSmallest in size until smallest) {
smallest = innerSmallest
}
}
return smallest
}
fun part1(node: Node): Int {
return sumDirectories(node, 100000)
}
fun part2(node: Node): Int {
val totalCapacity = 70000000
val required = 30000000
val available = totalCapacity - node.size
val toFree = required - available
return findSmallestDirSizeAbove(node, toFree)
}
val testInput = parseToTree(readInput("Day07_test"))
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = parseToTree(readInput("Day07"))
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8eecfb5c0c160e26f3ef0e277e48cb7fe86c903d | 3,388 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/de/jball/aoc2022/day11/Day11.kt | fibsifan | 573,189,295 | false | {"Kotlin": 43681} | package de.jball.aoc2022.day11
import de.jball.aoc2022.Day
class Day11(test: Boolean = false) : Day<Long>(test, 10605L, 2713310158L) {
private val monkeys = input
.chunked(7)
.map { parseMonkey(it) }
private val monkeys2 = input
.chunked(7)
.map { parseMonkey(it) }
private val inspectionCounters2 = MutableList(monkeys2.size) { 0L }
private val inspectionCounters = MutableList(monkeys.size) { 0L }
private fun parseMonkey(monkeyData: List<String>): Monkey {
val items = monkeyData[1].split(": ")[1].split(", ").map { it.toLong() }.toMutableList()
val operationData = monkeyData[2].split(" = old ")[1]
val operand = operationData.substringAfterLast(" ")
val operation = if (operationData.startsWith("+"))
fun (old: Long): Long {return old + if (operand=="old") old else operand.toLong()}
else fun(old: Long): Long {return old * if (operand=="old") old else operand.toLong()}
val divisor = monkeyData[3].substringAfterLast(" ").toLong()
val targetIfDivisible = monkeyData[4].substringAfterLast(" ").toInt()
val targetIfNotDivisible = monkeyData[5].substringAfterLast(" ").toInt()
return Monkey(items, operation, divisor, Pair(targetIfDivisible, targetIfNotDivisible))
}
override fun part1(): Long {
for (i in 1..20) {
monkeys.forEachIndexed { index, monkey ->
inspectionCounters[index] += monkey.items.size.toLong()
monkey.turn(monkeys, 0)
}
}
inspectionCounters.sortDescending()
return inspectionCounters[0]*inspectionCounters[1]
}
override fun part2(): Long {
monkeys2.forEach { monkey -> monkey.round2 = true }
for (i in 1..10000) {
monkeys2.forEachIndexed { index, monkey ->
inspectionCounters2[index] += monkey.items.size.toLong()
val modulus = monkeys2.map { it.divisor }.reduce { a, b -> a * b }
monkey.turn(monkeys2, modulus)
}
}
inspectionCounters2.sortDescending()
return inspectionCounters2[0]*inspectionCounters2[1]
}
}
class Monkey(
val items: MutableList<Long>,
private val operation: (old: Long) -> Long,
val divisor: Long,
private val targets: Pair<Int, Int>,
var round2: Boolean = false
) {
fun turn(monkeys: List<Monkey>, modulus: Long) {
while (items.isNotEmpty()) {
val item = items.removeFirst()
val target = inspect(item, modulus)
monkeys[target.first].items.add(target.second)
}
}
private fun inspect(item: Long, modulus: Long): Pair<Int, Long> {
val newWorryLevel = if (round2) operation(item)%modulus else operation(item)/3
return Pair(targetMonkey(newWorryLevel), newWorryLevel)
}
private fun targetMonkey(newWorryLevel: Long): Int {
return if (newWorryLevel % divisor == 0L) targets.first else targets.second
}
}
fun main() {
Day11().run()
}
| 0 | Kotlin | 0 | 3 | a6d01b73aca9b54add4546664831baf889e064fb | 3,059 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/day24.kt | gautemo | 572,204,209 | false | {"Kotlin": 78294} | import shared.Point
import shared.getText
fun main() {
val input = getText("day24.txt")
println(day24A(input))
println(day24B(input))
}
fun day24A(input: String) = bfsSearch(input) - 1
fun day24B(input: String) = bfsSearch(input, Triple(false, false, false))
private fun bfsSearch(input: String, goals: Triple<Boolean, Boolean, Boolean> = Triple(false, true, true)): Int {
val queue = mutableListOf(BlizzardMap(input, Point(1, 0), 0, goals))
val history = mutableListOf<String>()
while (queue.isNotEmpty()) {
val check = queue.removeAt(0)
if (check.goals.toList().all { it }) {
return check.minute
} else {
queue.addAll(check.next().filter {
!history.contains(it.state()) && queue.none { q -> q.state() == it.state() }
})
}
val maxGoalsFound = queue.maxOf { it.goals.toList().count { g -> g } }
queue.removeIf {
it.goals.toList().count { g -> g } < maxGoalsFound
}
history.add(check.state())
}
throw Exception()
}
private class BlizzardMap(
private val input: String,
val on: Point,
val minute: Int,
val goals: Triple<Boolean, Boolean, Boolean>,
) {
private val nextBlizzards = mutableListOf<Point>()
private val maxY = input.lines().size - 2
private val maxX = input.lines().first().length - 2
init {
for((y, line) in input.lines().withIndex()) {
for((x, c) in line.withIndex()) {
val blizzard = when (c) {
'^' -> {
val toY = (maxY - ((minute + 1) % maxY) + y) % maxY
Point(x, if(toY == 0) maxY else toY)
}
'>' -> {
Point(((minute + x) % maxX)+1, y)
}
'v' -> {
Point(x, ((minute + y) % maxY)+1)
}
'<' -> {
val toX = (maxX - ((minute + 1) % maxX) + x) % maxX
Point(if(toX == 0) maxX else toX, y)
}
else -> null
}
if (blizzard != null) nextBlizzards.add(blizzard)
}
}
}
fun next(): List<BlizzardMap> {
return listOf(
on,
Point(on.x - 1, on.y),
Point(on.x + 1, on.y),
Point(on.x, on.y - 1),
Point(on.x, on.y + 1),
).filter {
(it.x == 1 && it.y == 0) ||
(it.x == maxX && it.y == maxY + 1)
|| (it.x in 1..maxX
&& it.y in 1..maxY
&& !nextBlizzards.contains(it)
)
}.map {
val onStart = it.x == 1 && it.y == 0
val onGoal = it.x == maxX && it.y == maxY + 1
val newGoals = Triple(
goals.first || onGoal,
goals.second || (goals.first && onStart),
goals.first && goals.second && onGoal,
)
BlizzardMap(input, it, minute + 1, newGoals)
}
}
fun state() = "${on.x},${on.y}.${minute % maxX}.${minute % maxY}.$goals"
}
| 0 | Kotlin | 0 | 0 | bce9feec3923a1bac1843a6e34598c7b81679726 | 3,258 | AdventOfCode2022 | MIT License |
src/main/kotlin/aoc2022/Day07.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2022
import readInput
import java.util.*
sealed class FileSystemElement(val name: String, val parent: Directory?) {
abstract val size: Int
override fun hashCode() = Objects.hash(name, parent)
override fun equals(other: Any?) = other is FileSystemElement && this::class.isInstance(other) &&
Objects.equals(name, other.name) && Objects.equals(parent, other.parent)
}
class Directory(name: String, parent: Directory?) : FileSystemElement(name, parent) {
// could be cached and only updated when a new element is added, but works okay for this input size
override val size: Int
get() = elements.sumOf { it.size }
val elements = mutableSetOf<FileSystemElement>()
override fun toString(): String {
return "- $name (dir)\n" + elements.joinToString(separator = "\n") { " $it" }
.split("\n").joinToString(separator = "\n") { " $it" }
}
}
class File(name: String, override val size: Int, parent: Directory?) : FileSystemElement(name, parent) {
override fun toString() = "- $name (file, size=$size)"
}
fun main() {
/**
* Parses the given [input] into a root [Directory] structure, from which all other [FileSystemElement]s are reachable.
*/
fun parseDirectoryStructure(input: List<String>): Directory {
val root = Directory("/", null)
var currentDirectory = root
input.forEach {
when {
it.startsWith("$ cd /") -> currentDirectory = root
it.startsWith("$ cd ..") -> currentDirectory = currentDirectory.parent ?: root
it.startsWith("$ cd ") -> {
currentDirectory = currentDirectory.elements.filterIsInstance<Directory>()
.firstOrNull { e -> e.name == it.substring(5) } ?: run {
// in case we haven't executed a 'ls' command in this directory yet
val newDir = Directory(it.substring(4), currentDirectory)
currentDirectory.elements.add(newDir)
newDir
}
}
it.startsWith("$ ls") -> {} // ignore
it.startsWith("dir ") -> currentDirectory.elements.add(Directory(it.substring(4), currentDirectory))
else -> {
val (size: String, name: String) = it.split(" ")
currentDirectory.elements.add(File(name, size.toInt(), currentDirectory))
}
}
}
return root
}
/**
* Finds all the directories under the given [root] which matches the given [predicate]
*/
fun findDir(root: Directory, predicate: (Directory) -> Boolean): Set<Directory> {
val foundDirs = mutableSetOf<Directory>()
val dirsToCheck = mutableSetOf(root)
while (dirsToCheck.isNotEmpty()) {
val current = dirsToCheck.first()
if (predicate(current)) {
foundDirs.add(current)
}
dirsToCheck.remove(current)
dirsToCheck.addAll(current.elements.filterIsInstance<Directory>())
}
return foundDirs
}
fun part1(input: List<String>): Int {
val root = parseDirectoryStructure(input)
return findDir(root) { it.size <= 100000 }.sumOf { it.size }
}
fun part2(input: List<String>): Int {
val root = parseDirectoryStructure(input)
val total = 70000000
val required = 30000000
val free = total - root.size
val targetSize = required - free
return findDir(root) { it.size >= targetSize }.minOf { it.size }
}
val testInput = readInput("Day07_test", 2022)
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07", 2022)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 3,879 | adventOfCode | Apache License 2.0 |
src/main/kotlin/day07_treachery_of_whales/TreacheryOfWhales.kt | barneyb | 425,532,798 | false | {"Kotlin": 238776, "Shell": 3825, "Java": 567} | package day07_treachery_of_whales
import java.util.*
import kotlin.math.abs
/**
* Now for (efficient) optimization. Clearly the best position is between the
* min and max initial positions, and a brute force search of every position
* will get you an answer. There must be exactly one minimum. It's probably
* close to the mean. No need to search position-by-position.
*
* For part two: enter the strategy pattern! The optimization algorithm needn't
* change, only the cost function is different. Plug in a different strategy,
* and reuse all the (optimized!) search logic from part one as-is.
*/
fun main() {
util.solve(337833, ::partOne)
util.solve(96678050, ::partTwo)
}
fun partOne(input: String) =
search(input) { abs(it) }
private fun search(input: String, costToMove: (Int) -> Int): Int {
val crabs = input
.split(",")
.map(String::toInt)
val best = crabs
.average()
.toInt()
val queue: Queue<Int> = LinkedList()
queue.add(best)
while (queue.isNotEmpty()) {
val pivot = queue.remove()
val curr = crabs.sumOf { costToMove(it - pivot) }
val down = crabs.sumOf { costToMove(it - (pivot - 1)) }
val up = crabs.sumOf { costToMove(it - (pivot + 1)) }
if (curr <= down && curr <= up) {
return curr
} else if (down < curr) {
queue.add(pivot - ((curr - down) / 2).coerceAtLeast(1))
} else {
queue.add(pivot + ((curr - up) / 2).coerceAtLeast(1))
}
}
throw IllegalStateException("No minumum found?!")
}
fun partTwo(input: String) =
search(input) { (1..abs(it)).sum() }
| 0 | Kotlin | 0 | 0 | a8d52412772750c5e7d2e2e018f3a82354e8b1c3 | 1,655 | aoc-2021 | MIT License |
src/Day12.kt | LauwiMeara | 572,498,129 | false | {"Kotlin": 109923} | const val START_LETTER = 'S'
const val END_LETTER = 'E'
const val MIN_ELEVATION_LETTER = 'a'
const val MAX_ELEVATION_LETTER = 'z'
const val NUM_START_NODES = 989 // Found by running part2() once and looking at the size of startNodes.
data class Node(val pos: Point, val letter: Char)
fun main() {
fun initialiseUnvisitedNodes(input: List<Node>, startNode: Node): MutableMap<Node, Int> {
val unvisitedNodes = mutableMapOf<Node, Int>()
for (node in input) {
unvisitedNodes[node] = if (node == startNode) 0 else Int.MAX_VALUE
}
return unvisitedNodes
}
// Dijkstra's algorithm
fun getCostPerVisitedNode(unvisitedNodes: MutableMap<Node, Int>, startNode: Node): MutableMap<Node, Int> {
val visitedNodes = mutableMapOf<Node, Int>()
while(true) {
// Get currentNode.
val minCost = unvisitedNodes.values.min()
if (minCost == Int.MAX_VALUE) break // END_LETTER cannot be reached.
val currentNode = unvisitedNodes.entries.first { it.value == minCost }.key
unvisitedNodes.remove(currentNode)
visitedNodes[currentNode] = minCost
// If currentNode contains END_LETTER, stop searching.
if (currentNode.letter == END_LETTER) { break }
// Update the cost for all neighbouring nodes (nextNodes).
val neighbourPositions = listOf(
Point(currentNode.pos.x - 1, currentNode.pos.y),
Point(currentNode.pos.x, currentNode.pos.y + 1),
Point(currentNode.pos.x + 1, currentNode.pos.y),
Point(currentNode.pos.x, currentNode.pos.y - 1)
)
for (nPos in neighbourPositions) {
val nextNodeList = unvisitedNodes.keys.filter { it.pos == nPos }
if (nextNodeList.isEmpty()) continue
val nextNode = nextNodeList.single()
// We can only reach the nextNode with the following conditions:
// - NextNode cannot be startNode.
// - If currentNode contains START_LETTER, nextNode must be 'a'.
// - If nextNode contains END_LETTER, currentNode must be 'z'.
// - For all other cases: nextNode is at most one higher than currentNode.
if (nextNode != startNode &&
((currentNode.letter == START_LETTER && nextNode.letter == MIN_ELEVATION_LETTER) ||
(nextNode.letter == END_LETTER && currentNode.letter == MAX_ELEVATION_LETTER) ||
(nextNode.letter != END_LETTER && nextNode.letter - currentNode.letter <= 1))) {
unvisitedNodes[nextNode] = minCost + 1
}
}
}
return visitedNodes
}
fun part1(input: List<Node>): Int {
val startNode = input.single{it.letter == START_LETTER}
val unvisitedNodes = initialiseUnvisitedNodes(input, startNode)
// Search for the shortest path by getting the lowest cost from the startNode to all visitedNodes, until END_LETTER is found or cannot be reached.
val visitedNodes = getCostPerVisitedNode(unvisitedNodes, startNode)
// Return the cost of the node containing END_LETTER.
return visitedNodes.entries.first{it.key.letter == END_LETTER}.value
}
fun part2(input: List<Node>, printProgress: Boolean = true): Int {
val startNodes = input.filter{it.letter == START_LETTER || it.letter == MIN_ELEVATION_LETTER}
val possibleCosts = mutableListOf<Int>()
// Search for the shortest path by getting the lowest cost from the startNode to all visitedNodes, until END_LETTER is reached or cannot be reached.
for ((i, startNode) in startNodes.withIndex()) {
if (printProgress) {
println("Iteration: $i/$NUM_START_NODES")
}
val unvisitedNodes = initialiseUnvisitedNodes(input, startNode)
val visitedNodes = getCostPerVisitedNode(unvisitedNodes, startNode)
// If END_LETTER is reached, add the cost of the node to the list of possible costs.
if (visitedNodes.keys.any{it.letter == END_LETTER}) {
val cost = visitedNodes.entries.single{it.key.letter == END_LETTER}.value
if (printProgress) {
println("Cost: $cost")
}
possibleCosts.add(cost)
}
}
// Return the lowest possible cost.
return possibleCosts.filter{it > 0}.min()
}
val input = readInputAsStrings("Day12").mapIndexed{x, line -> line.mapIndexed{y, letter -> Node(Point(x, y), letter)}}.flatten()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 34b4d4fa7e562551cb892c272fe7ad406a28fb69 | 4,749 | AoC2022 | Apache License 2.0 |
src/year_2023/day_18/Day18.kt | scottschmitz | 572,656,097 | false | {"Kotlin": 240069} | package year_2023.day_18
import readInput
import util.*
interface IDig {
val direction: Direction
val distance: Int
}
data class DigStep(
override val direction: Direction,
override val distance: Int,
val color: String
): IDig
data class UpdatedDig(
override val direction: Direction,
override val distance: Int
): IDig
object Day18 {
/**
*
*/
fun solutionOne(text: List<String>): Long {
val digPlan = parseDigPlan(text)
val vertices = dig(digPlan)
return vertices.calculateArea(true)
}
/**
*
*/
fun solutionTwo(text: List<String>): Long {
val updatedDigPlan = parseDigPlan(text).map { oldPlan ->
val distance = Integer.parseInt(oldPlan.color.substring(0, oldPlan.color.length - 1), 16)
val direction = digitToDirection(oldPlan.color.last())
UpdatedDig(
direction = direction,
distance = distance
)
}
val vertices = dig(updatedDigPlan)
return vertices.calculateArea(true)
}
private fun parseDigPlan(text: List<String>): List<DigStep> {
return text.map { line ->
val split = line.split(" ")
DigStep(
direction = Direction.from(split[0].first()),
distance = split[1].toInt(),
color = split[2].substring(2, split[2].length - 1)
)
}
}
private fun dig(digPlan: List<IDig>): List<PointL> {
var currentPoint: PointL = 0L to 0L
val points = mutableListOf<PointL>()
digPlan.forEach { step ->
currentPoint = (currentPoint.first + (step.direction.delta.first * step.distance)
to currentPoint.second + (step.direction.delta.second * step.distance))
points.add(currentPoint)
}
return points
}
private fun digitToDirection(digit: Char): Direction {
return when (digit) {
'0' -> Direction.EAST
'1' -> Direction.SOUTH
'2' -> Direction.WEST
'3' -> Direction.NORTH
else -> throw IllegalArgumentException("Unhandled direction")
}
}
}
fun main() {
val text = readInput("year_2023/day_18/Day18.txt")
val solutionOne = Day18.solutionOne(text)
println("Solution 1: $solutionOne")
val solutionTwo = Day18.solutionTwo(text)
println("Solution 2: $solutionTwo")
}
| 0 | Kotlin | 0 | 0 | 70efc56e68771aa98eea6920eb35c8c17d0fc7ac | 2,462 | advent_of_code | Apache License 2.0 |
src/Day18.kt | jstapels | 572,982,488 | false | {"Kotlin": 74335} |
private data class Cube(val x: Int, val y:Int, val z:Int) {
val adjacents get() = listOf(
Cube(x - 1, y, z),
Cube(x + 1, y, z),
Cube(x, y - 1, z),
Cube(x, y + 1, z),
Cube(x, y, z - 1),
Cube(x, y, z + 1),
)
}
private typealias Grid = MutableMap<Int, MutableMap<Int, MutableMap<Int, Cube>>>
fun main() {
val day = 18
fun parseInput(input: List<String>) =
input.map { l -> l.split(",").map { it.toInt() } }
.map { (x, y, z) -> Cube(x, y, z) }
fun Grid.addCube(cube: Cube) =
this.getOrPut(cube.x) { mutableMapOf() }
.getOrPut(cube.y) { mutableMapOf() }
.put(cube.z, cube)
fun Grid.getAdjacents(cube: Cube) =
cube.adjacents
.mapNotNull { get(it.x)?.get(it.y)?.get(it.z) }
fun part1(input: List<String>): Int {
val data = parseInput(input)
val grid = mutableMapOf<Int, MutableMap<Int, MutableMap<Int, Cube>>>()
data.forEach { grid.addCube(it) }
return data.sumOf { 6 - grid.getAdjacents(it).size }
}
fun Grid.getEmpty(data: MutableList<Cube>): MutableSet<Cube> {
val minX = data.minOf { it.x } - 1
val maxX = data.maxOf { it.x } + 1
val minY = data.minOf { it.y } - 1
val maxY = data.maxOf { it.y } + 1
val minZ = data.minOf { it.z } - 1
val maxZ = data.maxOf { it.z } + 1
val explored = mutableSetOf<Cube>()
val search = mutableListOf(Cube(minX, minY, minZ))
while (search.isNotEmpty()) {
val node = search.removeFirst()
explored.add(node)
node.adjacents
.filter { it !in explored }
.filter { it !in data }
.filter { it !in search }
.filter { it.x >= minX && it.y >= minY && it.z >= minZ }
.filter { it.x <= maxX && it.y <= maxY && it.z <= maxZ }
.forEach {
search.add(it)
}
}
return explored
}
fun part2(input: List<String>): Int {
val data = parseInput(input).toMutableList()
val grid: Grid = mutableMapOf()
data.forEach { grid.addCube(it) }
val minX = data.minOf { it.x }
val maxX = data.maxOf { it.x }
val minY = data.minOf { it.y }
val maxY = data.maxOf { it.y }
val minZ = data.minOf { it.z }
val maxZ = data.maxOf { it.z }
val empties = grid.getEmpty(data)
(minX..maxX).forEach { x ->
(minY..maxY).forEach { y ->
(minZ..maxZ).forEach { z ->
val tc = Cube(x, y, z)
if (tc !in data && tc !in empties) {
grid.addCube(tc)
}
}
}
}
return data.sumOf { 6 - grid.getAdjacents(it).size }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${day.pad(2)}_test")
checkTest(64) { part1(testInput) }
checkTest(58) { part2(testInput) }
val input = readInput("Day${day.pad(2)}")
solution { part1(input) }
solution { part2(input) }
}
| 0 | Kotlin | 0 | 0 | 0d71521039231c996e2c4e2d410960d34270e876 | 3,217 | aoc22 | Apache License 2.0 |
2021/src/main/kotlin/day19.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Mat4i
import utils.Parser
import utils.Point3i
import utils.ROTS
import utils.Solution
import utils.Vec4i
import utils.product
import utils.productIndexed
import utils.withCounts
fun main() {
Day19.run()
}
object Day19 : Solution<List<Day19.Scanner>>() {
override val name = "day19"
override val parser = Parser { input ->
input.split("\n\n").map { scannerIn ->
scannerIn.lines().filter { it.isNotBlank() && !it.startsWith("---") }
.map { line ->
val (x, y, z) = line.split(",").map { it.toInt() }
Point3i(x, y, z)
}
}.mapIndexed { index, beacons -> Scanner(index, beacons) }
}
class Scanner(val index: Int, val beacons: List<Vec4i>, distances: Map<Int, Pair<Int, Int>>? = null) {
override fun toString() = "$index"
private val distances = distances ?: beacons.productIndexed { b1Index, b1, b2Index, b2 ->
b1.distanceSqr(b2) to (b1Index to b2Index)
}.groupBy { it.first }.mapValues { (_, v) ->
v.also { require(it.size == 1) { "Unexpected dupe distance in beacons" } }.first().second
}
fun translateTo(anchor: Scanner): Pair<Scanner, Vec4i>? {
val distanceOverlap = this.distances.keys intersect anchor.distances.keys
if (distanceOverlap.size < 12) {
return null
}
// we've got at least 12 similar distances, try to map beacons now.
// map every point to 24 possible transform matrices and find the
// transform matrix that gave the most overlapping beacons
val matPair = distanceOverlap.flatMap { dist ->
val (myB1, myB2) = this.distances[dist]!!
val (anchorB1, anchorB2) = anchor.distances[dist]!!
ROTS.mapNotNull { rot ->
// try to rotate the beacons in the distance pair
val rotB1 = rot * beacons[myB1]
val rotB2 = rot * beacons[myB2]
// the delta between these pairs should be the same now
// TODO(madis) is there a bug here as we're not considering rotB1 vs anchorB2 and vice versa?
if (rotB1 - anchor.beacons[anchorB1] == rotB2 - anchor.beacons[anchorB2]) {
val translation = Mat4i.translate(anchor.beacons[anchorB1] - rotB1)
(translation * rot)
} else if (rotB2 - anchor.beacons[anchorB1] == rotB1 - anchor.beacons[anchorB2]) {
val translation = Mat4i.translate(anchor.beacons[anchorB2] - rotB1)
(translation * rot)
} else null
}
}.withCounts().maxByOrNull { it.value }
// discard matrices that didn't yield at least 12 overlapping beacons
if (matPair == null || matPair.value < 12) {
return null
}
// transform the scanner with our transform matrix and also transform 0,0,0 to get scanner's position relative to
// the anchor
return Scanner(index, beacons.map { (matPair.key * it).asPoint }, distances) to matPair.key * Point3i(0,0,0)
}
}
private fun solve(input: List<Scanner>): List<Pair<Scanner, Vec4i>> {
val anchored = mutableListOf(input.first() to Point3i(0, 0, 0))
val scanners = input.drop(1).toMutableList()
while (scanners.isNotEmpty()) {
val beginSz = scanners.size
// iterate over scanners and try to anchor them
val iter = scanners.listIterator()
while (iter.hasNext()) {
val scanner = iter.next()
val matches = anchored.firstNotNullOfOrNull { (anchor, _) -> scanner.translateTo(anchor) }
if (matches != null) {
anchored.add(matches)
iter.remove()
}
}
require(scanners.size != beginSz) { "Couldn't anchor any scanner!" }
}
return anchored
}
override fun part1(input: List<Scanner>): Int {
return solve(input).flatMap { (scanner, _) -> scanner.beacons }.toSet().size
}
override fun part2(input: List<Scanner>): Number? {
return solve(input).map { (_, pos) -> pos }.product().maxOfOrNull { (pos1, pos2) -> pos1.distanceManhattan(pos2) }
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 3,980 | aoc_kotlin | MIT License |
src/main/kotlin/com/github/freekdb/aoc2019/Day04.kt | FreekDB | 228,241,398 | false | null | package com.github.freekdb.aoc2019
import java.io.File
// https://adventofcode.com/2019/day/4
fun main() {
val bounds =
File("input/day-04--input.txt")
.readLines()
.first()
.split("-")
val lowerBound = bounds[0].toInt()
val upperBound = bounds[1].toInt()
generatePossiblePasswords(lowerBound, upperBound)
println("Possible passwords count -- part 1: ${countPasswordsPart1(lowerBound, upperBound)}")
println("Possible passwords count -- part 2: ${countPasswordsPart2(lowerBound, upperBound)}")
}
// Brute force approach: generate possible passwords that meet the general criteria.
private fun generatePossiblePasswords(lowerBound: Int, upperBound: Int): Sequence<List<Int>> {
// General citeria:
// - Passwords are six-digit numbers.
// - Each number is within the range given in your puzzle input.
// - Going from left to right, the digits never decrease; they only ever increase or stay the same
// (like 111123 or 135679).
return sequence {
for (digit1 in 0..9) {
for (digit2 in digit1..9) {
for (digit3 in digit2..9) {
for (digit4 in digit3..9) {
for (digit5 in digit4..9) {
for (digit6 in digit5..9) {
val number = "$digit1$digit2$digit3$digit4$digit5$digit6".toInt()
if (number in lowerBound..upperBound) {
yield(listOf(digit1, digit2, digit3, digit4, digit5, digit6))
}
}
}
}
}
}
}
}
}
private fun countPasswordsPart1(lowerBound: Int, upperBound: Int): Int {
// Additional rule:
// - Two adjacent digits are the same (like 22 in 122345).
// -> We could generate five-digit numbers and "double" one of the five digits. This gives up to five possible
// six-digit passwords for each five-digit number.
return generatePossiblePasswords(lowerBound, upperBound)
.filter { it.toSet().size < 6 }
.count()
}
private fun countPasswordsPart2(lowerBound: Int, upperBound: Int): Int {
// Additional rules:
// - Two adjacent digits are the same (like 22 in 122345).
// -> We could generate five-digit numbers and "double" one of the five digits. This gives up to five possible
// six-digit passwords for each five-digit number.
// - The two adjacent matching digits are not part of a larger group of matching digits.
return generatePossiblePasswords(lowerBound, upperBound)
.filter { digits ->
digits
.groupingBy { digit -> digit }
.eachCount()
.values
.contains(2)
}
.count()
}
| 0 | Kotlin | 0 | 1 | fd67b87608bcbb5299d6549b3eb5fb665d66e6b5 | 2,905 | advent-of-code-2019 | Apache License 2.0 |
src/Day07.kt | Xacalet | 576,909,107 | false | {"Kotlin": 18486} | /**
* ADVENT OF CODE 2022 (https://adventofcode.com/2022/)
*
* Solution to day 7 (https://adventofcode.com/2022/day/7)
*
*/
private sealed interface Node
private data class FileNode(
val size: Long,
val name: String,
): Node
private data class DirectoryNode(
val name: String,
val parentNode: DirectoryNode? = null,
val contents: MutableMap<String, Node> = mutableMapOf(),
var size: Long = 0L,
): Node
fun main() {
fun part1(root: DirectoryNode): Long {
fun DirectoryNode.calcSize(sizes: MutableList<Long>): Long {
return contents.values.sumOf { content ->
when(content) {
is FileNode -> content.size
is DirectoryNode -> content.calcSize(sizes)
}
}.also { size ->
this.size = size
if (size <= 100_000) {
sizes.add(size)
}
}
}
return mutableListOf<Long>().let { sizes ->
root.calcSize(sizes)
sizes.sum()
}
}
fun part2(root: DirectoryNode): Long {
fun DirectoryNode.getSmallestDirToFreeSpace(spaceToFree: Long): DirectoryNode =
contents.values
.filterIsInstance(DirectoryNode::class.java)
.filter { dir -> dir.size >= spaceToFree }
.map { dir -> dir.getSmallestDirToFreeSpace(spaceToFree) }
.minByOrNull { dir -> dir.size } ?: this
val unusedSpace = 70_000_000L - root.size
val spaceToFree = 30_000_000L - unusedSpace
val directoryToDelete = root.getSmallestDirToFreeSpace(spaceToFree)
return directoryToDelete.size
}
fun buildFileSystem(outputLines: List<String>): DirectoryNode {
val root = DirectoryNode("/")
var currentDirectory: DirectoryNode = root
outputLines.forEach { line ->
when {
"\\$ cd (\\.\\.|/|(\\w+))".toRegex().matches(line) -> {
val (param) = "\\$ cd (.+)".toRegex().find(line)!!.destructured
currentDirectory = when(param) {
".." -> currentDirectory.parentNode!!
"/" -> root
else -> currentDirectory.contents[param] as DirectoryNode
}
}
"dir (\\w+)".toRegex().matches(line) -> {
val (name) = "dir (\\w+)".toRegex().find(line)!!.destructured
currentDirectory.contents[name] = DirectoryNode(name, currentDirectory)
}
"(\\d+) ([\\w.]+)".toRegex().matches(line) -> {
val (size, name) = "(\\d+) ([\\w.]+)".toRegex().find(line)!!.destructured
currentDirectory.contents[name] = FileNode(size.toLong(), name)
}
line == "$ ls" -> Unit
else -> throw IllegalArgumentException("Unknown command: $line")
}
}
return root
}
val fileSystem = buildFileSystem(readInputLines("day07_dataset"))
part1(fileSystem).println()
part2(fileSystem).println()
}
| 0 | Kotlin | 0 | 0 | 5c9cb4650335e1852402c9cd1bf6f2ba96e197b2 | 3,183 | advent-of-code-2022 | Apache License 2.0 |
kotlin/src/main/kotlin/AoC_Day14.kt | sviams | 115,921,582 | false | null | object AoC_Day14 {
val initialKnotState = (0..255).toList()
fun parseHashes(input: String) : List<String> {
val rows = (0 until 128).map { input + "-" + it }
return rows.map { AoC_Day10.solvePt2(it, initialKnotState) }
}
fun solvePt1(input: String) : Int {
val hashes = parseHashes(input)
val asd = hashes.flatMap { it.toCharArray().toList().map { char -> java.lang.Long.parseLong(char.toString(), 16).toString(2).padStart(4, '0') } }
val count = asd.fold(0) {acc, value -> acc + value.toCharArray().count { it == '1'}}
return count
}
fun findRowAndColOfUngrouped(input: List<List<Int>>) : Pair<Int, Int> {
input.foldIndexed(0) {acc, rowIndex, row ->
val firstIndex = row.indexOf(1)
if (firstIndex >= 0) return Pair(rowIndex, firstIndex) else acc
}
return Pair(-1, -1)
}
fun validAdjacents(current: Pair<Int,Int>) : List<Pair<Int,Int>> =
listOf(Pair(current.first-1, current.second), Pair(current.first+1, current.second), Pair(current.first, current.second-1), Pair(current.first, current.second+1)).filter { it.first in 0..127 && it.second in 0..127 }
fun setGroupValue(grid: List<List<Int>>, targetRow: Int, targetCol: Int, group: Int) : List<List<Int>> {
return grid.mapIndexed { rowIndex: Int, row: List<Int> -> if (rowIndex == targetRow) row.mapIndexed { colIndex: Int, col: Int -> if (colIndex == targetCol) group else col } else row }
}
// TODO: Clean up this mess
fun identifyCoordsOfGroup(grid: List<List<Int>>, current: Pair<Int, Int>, currentGroup: Int) : List<List<Int>> {
var state = grid
state = setGroupValue(state, current.first, current.second, currentGroup)
val adj = validAdjacents(current)
for (a in adj) {
state = if (state[a.first][a.second] == 1) identifyCoordsOfGroup(state, a, currentGroup) else state
}
return state
}
fun printGrid(grid: List<List<Int>>) {
println()
for (y in grid) {
for (x in y) {
print(x)
}
println()
}
}
data class State(val current: Pair<Int, Int>, val currentGroup: Int, val bits: List<List<Int>>)
fun solvePt2(input: String) : Int {
val hashes = parseHashes(input)
val bits = hashes.map { it.toCharArray().toList().map { char -> java.lang.Long.parseLong(char.toString(), 16).toString(2).padStart(4, '0') }.joinToString("").toCharArray().map { it.toInt() - 48} }
val startState = State(findRowAndColOfUngrouped(bits), 2, bits)
return generateSequence(startState) { (current, currentGroup, state) ->
val newBits = identifyCoordsOfGroup(state, current, currentGroup)
State(findRowAndColOfUngrouped(newBits), currentGroup + 1, newBits)
}.takeWhile { it.current.first != -1 }.last().bits.flatMap { it }.max()!!
}
} | 0 | Kotlin | 0 | 0 | 19a665bb469279b1e7138032a183937993021e36 | 2,960 | aoc17 | MIT License |
src/Day05.kt | anisch | 573,147,806 | false | {"Kotlin": 38951} | val regexOps = """move \d from \d to \d""".toRegex()
data class Ops(val move: Int, val from: Int, val to: Int)
fun createStack(list: List<String>): MutableMap<Int, MutableList<Char>> {
val stack = mutableMapOf<Int, MutableList<Char>>()
list
.takeWhile { it.isNotBlank() }
.dropLast(1)
.map { it.chunked(4) }
.map { it.map { box -> box[1] } }
.forEach {
it.forEachIndexed { idx, box ->
if (!box.isWhitespace()) {
stack[idx + 1]?.add(0, box) ?: mutableListOf(box)
}
}
}
return stack
}
fun createOps(list: List<String>): List<Ops> = list
.asSequence()
.dropWhile { !regexOps.matches(it) }
.map { it.replace("move ", "") }
.map { it.replace("from", "") }
.map { it.replace("to", "") }
.map { it.split(" ") }
.map { Ops(it[0].toInt(), it[1].toInt(), it[2].toInt()) }
.toList()
fun MutableList<*>.removeLast(i: Int) = repeat((1..i).count()) { removeAt(lastIndex) }
fun MutableMap<Int, MutableList<Char>>.topOfStackAsString() = toSortedMap()
.mapValues { it.value.last().toString() }
.values
.reduce { acc, s -> acc + s }
fun main() {
fun part1(input: List<String>): String {
val stack = createStack(input)
val ops = createOps(input)
ops.forEach { op ->
val size = stack[op.from]!!.size
val tmp = stack[op.from]!!.drop(size - op.move)
stack[op.to]!!.addAll(tmp.reversed())
stack[op.from]!!.removeLast(op.move)
}
return stack.topOfStackAsString()
}
fun part2(input: List<String>): String {
val stack = createStack(input)
val ops = createOps(input)
ops.forEach { op ->
val size = stack[op.from]!!.size
val tmp = stack[op.from]!!.drop(size - op.move)
stack[op.to]!!.addAll(tmp)
stack[op.from]!!.removeLast(op.move)
}
return stack.topOfStackAsString()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
val input = readInput("Day05")
check(part1(testInput) == "CMZ")
println(part1(input))
check(part2(testInput) == "MCD")
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4f45d264d578661957800cb01d63b6c7c00f97b1 | 2,391 | Advent-of-Code-2022 | Apache License 2.0 |
src/main/kotlin/net/voldrich/aoc2021/Day9.kt | MavoCz | 434,703,997 | false | {"Kotlin": 119158} | package net.voldrich.aoc2021
import net.voldrich.BaseDay
// https://adventofcode.com/2021/day/9/
fun main() {
Day9().run()
}
class Day9 : BaseDay() {
override fun task1() : Int {
val inputNums = input.lines().map { line -> line.trim().toCharArray().map { it.digitToInt() }.toList() }
val heightMap = HeightMap(inputNums)
return heightMap.getLowPoints().sumOf { it.value + 1 }
}
override fun task2() : Int {
val inputNums = input.lines().map { line -> line.trim().toCharArray().map { it.digitToInt() }.toList() }
val heightMap = HeightMap(inputNums)
val basins = heightMap.getLowPoints().map { heightMap.findBasin(it) }.sortedDescending()
return basins.take(3).fold(1) { v, prev -> v * prev }
}
class HeightMap(private val heightMap: List<List<Int>>) {
private val sx = heightMap.size
private val sy = heightMap[0].size
fun getLowPoints() : List<Point> {
val lowPoints = ArrayList<Point>()
for (y in 0 until sx) {
for (x in 0 until sy) {
val num = heightMap[y][x]
var isLocalMin = true
if (y > 0 && num >= heightMap[y-1][x]) isLocalMin = false
if (y+1 < sx && num >= heightMap[y+1][x]) isLocalMin = false
if (x > 0 && num >= heightMap[y][x-1]) isLocalMin = false
if (x+1 < sy && num >= heightMap[y][x+1]) isLocalMin = false
if (isLocalMin) {
lowPoints.add(Point(y, x, num))
}
}
}
return lowPoints
}
fun findBasin(point: Point): Int {
val basin = HashSet<Point>()
basin.add(point)
expandBasin(point, basin)
return basin.size
}
private fun expandBasin(startPoint : Point, basin : HashSet<Point>) {
if (startPoint.y > 0 ) considerBasinPoint(startPoint.y - 1, startPoint.x, startPoint, basin)
if (startPoint.y+1 < sx ) considerBasinPoint(startPoint.y + 1, startPoint.x, startPoint, basin)
if (startPoint.x > 0 ) considerBasinPoint(startPoint.y, startPoint.x - 1, startPoint, basin)
if (startPoint.x+1 < sy ) considerBasinPoint(startPoint.y, startPoint.x + 1, startPoint, basin)
}
private fun considerBasinPoint(y : Int, x : Int, prevPoint : Point, basin : HashSet<Point>) {
val point = Point(y, x, heightMap[y][x])
if (basin.contains(point) || point.value <= prevPoint.value || point.value == 9) return
basin.add(point)
expandBasin(point, basin)
}
}
data class Point(val y: Int, val x: Int, val value: Int)
}
| 0 | Kotlin | 0 | 0 | 0cedad1d393d9040c4cc9b50b120647884ea99d9 | 2,797 | advent-of-code | Apache License 2.0 |
src/Day08.kt | rinas-ink | 572,920,513 | false | {"Kotlin": 14483} | import java.lang.IllegalArgumentException
import java.lang.Integer.max
fun main() {
fun checkRow(row: List<Int>, res: MutableList<Boolean>) {
var highest = -1
for (i in row.indices) {
if (row[i] > highest) res[i] = true
highest = max(row[i], highest)
}
highest = -1
for (i in row.indices.reversed()) {
if (row[i] > highest) res[i] = true
highest = max(row[i], highest)
}
}
fun checkCol(matrix: List<List<Int>>, res: List<MutableList<Boolean>>, row: Int) {
var highest = -1
for (i in matrix.indices) {
if (matrix[i][row] > highest) res[i][row] = true
highest = max(matrix[i][row], highest)
}
highest = -1
for (i in matrix.indices.reversed()) {
if (matrix[i][row] > highest) res[i][row] = true
highest = max(matrix[i][row], highest)
}
}
fun part1(input: List<String>): Int {
val matrix = input.map { it.toList().map { it - '0' } }
val res = List(input.size) { MutableList(input.size) { false } }
for (i in matrix.indices) {
checkRow(matrix[i], res[i])
checkCol(matrix, res, i)
}
return res.sumOf { it.sumOf { it.compareTo(false) } }
}
fun visibleRight(i: Int, j: Int, matrix: List<List<Int>>): Int {
var res: Int = 0
for (k in j + 1..matrix[i].lastIndex) {
res++
if (matrix[i][k] >= matrix[i][j]) break
}
return res
}
fun visibleLeft(i: Int, j: Int, matrix: List<List<Int>>): Int {
var res: Int = 0
for (k in j - 1 downTo 0) {
res++
if (matrix[i][k] >= matrix[i][j]) break
}
return res
}
fun visibleTop(i: Int, j: Int, matrix: List<List<Int>>): Int {
var res: Int = 0
for (k in i - 1 downTo 0) {
res++
if (matrix[k][j] >= matrix[i][j]) break
}
return res
}
fun visibleBottom(i: Int, j: Int, matrix: List<List<Int>>): Int {
var res: Int = 0
for (k in i + 1..matrix.lastIndex) {
res++
if (matrix[k][j] >= matrix[i][j]) break
}
return res
}
fun part2(input: List<String>): Int {
var res = 0
val matrix = input.map { it.toList().map { it - '0' } }
for (i in matrix.indices) {
for (j in matrix[i].indices) {
res = max(
res, visibleLeft(i, j, matrix) * visibleRight(i, j, matrix) * visibleTop(
i, j, matrix
) * visibleBottom(i, j, matrix)
)
}
}
return res;
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 462bcba7779f7bfc9a109d886af8f722ec14c485 | 3,044 | anvent-kotlin | Apache License 2.0 |
src/Day09.kt | cisimon7 | 573,872,773 | false | {"Kotlin": 41406} | import kotlin.math.abs
import kotlin.math.sign
fun main() {
fun part1(commands: List<Pair<Direction, Int>>): Int {
val head = Knot.Head()
val tail = Knot.Tail()
commands.forEach { command ->
val (direction, count) = command
repeat(count) {
head.step(direction)
tail.step(head)
}
}
return tail.visitedStates.toSet().count()
}
fun part2(commands: List<Pair<Direction, Int>>): Int {
val head = Knot.Head()
val tails = List(9) { Knot.Tail() }
commands.forEach { command ->
val (direction, count) = command
repeat(count) {
head.step(direction)
tails.forEachIndexed { idx, tail ->
if (idx == 0) tail.step(head) else
tail.step(tails[idx - 1])
}
}
}
return tails.last().visitedStates.toSet().count()
}
fun parse(stringList: List<String>): List<Pair<Direction, Int>> {
return stringList.map {
val (dir, count) = it.split(" ").take(2)
when (dir) {
"R" -> Direction.RIGHT to count.toInt()
"U" -> Direction.UP to count.toInt()
"L" -> Direction.LEFT to count.toInt()
"D" -> Direction.DOWN to count.toInt()
else -> error("Unknown direction")
}
}
}
val testInput = readInput("Day09_test")
val testInput2 = readInput("Day09_test2")
check(part1(parse(testInput)) == 13)
check(part2(parse(testInput2)) == 36)
val input = readInput("Day09_input")
println(part1(parse(input)))
println(part2(parse(input)))
}
sealed class Knot {
open var x: Int = 0
open var y: Int = 0
data class Head(override var x: Int = 0, override var y: Int = 0) : Knot() {
fun step(direction: Direction) {
when (direction) {
Direction.UP -> this.y += 1
Direction.RIGHT -> this.x += 1
Direction.LEFT -> this.x -= 1
Direction.DOWN -> this.y -= 1
}
}
}
data class Tail(override var x: Int = 0, override var y: Int = 0) : Knot() {
val visitedStates = mutableListOf<Pair<Int, Int>>()
fun step(head: Knot) {
val (dx, dy) = (head.x - x) to (head.y - y)
when (abs(dx) to abs(dy)) {
(2 to 0) -> x += 1 * sign(dx.toDouble()).toInt()
(0 to 2) -> y += 1 * sign(dy.toDouble()).toInt()
(1 to 2) -> {
x += 1 * sign(dx.toDouble()).toInt()
y += 1 * sign(dy.toDouble()).toInt()
}
(2 to 1) -> {
x += 1 * sign(dx.toDouble()).toInt()
y += 1 * sign(dy.toDouble()).toInt()
}
(2 to 2) -> {
x += 1 * sign(dx.toDouble()).toInt()
y += 1 * sign(dy.toDouble()).toInt()
}
}
visitedStates.add(x to y)
}
}
}
enum class Direction {
UP, RIGHT, LEFT, DOWN
}
| 0 | Kotlin | 0 | 0 | 29f9cb46955c0f371908996cc729742dc0387017 | 3,199 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/day04/Day04.kt | mdenburger | 433,731,891 | false | {"Kotlin": 8573} | package day04
import java.io.File
fun main() {
val lines = File("src/main/kotlin/day04/day04-input.txt").readLines().toMutableList()
val numbers = lines.removeAt(0).split(",").map { it.toInt() }
val boards = mutableListOf<Board>()
while (lines.isNotEmpty()) {
boards.add(parseBoard(lines))
}
part1(numbers.toMutableList(), boards.toMutableList())
part2(numbers.toMutableList(), boards.toMutableList())
}
fun parseBoard(lines: MutableList<String>): Board {
lines.removeFirst() // empty line
val numbers = mutableListOf<Int>()
repeat(5) {
val row = lines.removeFirst().split(" ").filter { it.isNotEmpty() }.map { it.toInt() }
numbers += row
}
return Board(numbers)
}
fun part1(numbers: MutableList<Int>, boards: List<Board>) {
var drawn: Int
var winner: Board?
do {
drawn = numbers.removeFirst()
boards.forEach { it.mark(drawn) }
winner = boards.find { it.wins() }
} while (winner == null)
println(winner.score() * drawn)
}
fun part2(numbers: MutableList<Int>, boards: MutableList<Board>) {
var drawn: Int
var lastWinner: Board? = null
do {
drawn = numbers.removeFirst()
boards.forEach { it.mark(drawn) }
val winners = boards.filter { it.wins() }
if (winners.isNotEmpty()) {
boards.removeAll(winners)
lastWinner = winners.first()
}
} while (boards.isNotEmpty())
println(lastWinner!!.score() * drawn)
}
class Board(numbers: List<Int>) {
private val numbers = numbers.map { BoardNumber(it) }
fun mark(number: Int) {
numbers.find { it.value == number }?.mark()
}
fun wins(): Boolean = hasWinningRow() || hasWinningColumn()
private fun hasWinningRow(): Boolean =
numbers.chunked(5).any { row -> row.all { it.marked } }
private fun hasWinningColumn(): Boolean =
(0..4).any { col ->
(0..4).all { row ->
numbers[col + (row * 5)].marked
}
}
fun score(): Int =
numbers.filter { !it.marked }.sumOf { it.value }
}
class BoardNumber(val value: Int) {
var marked = false
fun mark() {
marked = true
}
}
| 0 | Kotlin | 0 | 0 | e890eec2acc2eea9c0432d092679aeb9de3f51b4 | 2,239 | aoc-2021 | MIT License |
src/Day11.kt | wgolyakov | 572,463,468 | false | null | fun main() {
class Monkey(val items: MutableList<Long>, val operation: (Long) -> Long,
val throwOper: (Long) -> Int, val divisible: Int) {
var inspectCount = 0L
}
fun parse(input: List<String>): List<Monkey> {
val monkeys = mutableListOf<Monkey>()
var i = 0
while (i < input.size) {
i++
val items = input[i++].substringAfter(" Starting items: ")
.split(", ").map { it.toLong() }.toMutableList()
val (oper, arg) = input[i++].substringAfter(" Operation: new = old ").split(' ')
val operation: (Long) -> Long = if (arg == "old") {
if (oper == "+") { a -> a + a } else { a -> a * a }
} else {
val x = arg.toInt()
if (oper == "+") { a -> a + x } else { a -> a * x }
}
val divisible = input[i++].substringAfter(" Test: divisible by ").toInt()
val trueThrow = input[i++].substringAfter(" If true: throw to monkey ").toInt()
val falseThrow = input[i++].substringAfter(" If false: throw to monkey ").toInt()
val throwOper: (Long) -> Int = { a -> if (a % divisible == 0L) trueThrow else falseThrow }
monkeys.add(Monkey(items, operation, throwOper, divisible))
i++
}
return monkeys
}
fun part1(input: List<String>): Long {
val monkeys = parse(input)
for (round in 1..20) {
for (monkey in monkeys) {
while (monkey.items.isNotEmpty()) {
var item = monkey.items.removeFirst()
monkey.inspectCount++
item = monkey.operation(item)
item /= 3
val toMonkey = monkey.throwOper(item)
monkeys[toMonkey].items.add(item)
}
}
}
return monkeys.map { it.inspectCount }.sorted().takeLast(2).let { (a, b) -> a * b }
}
fun part2(input: List<String>): Long {
val monkeys = parse(input)
val mod = monkeys.map { it.divisible.toLong() }.reduce { a, b -> a * b }
for (round in 1..10000) {
for (monkey in monkeys) {
while (monkey.items.isNotEmpty()) {
var item = monkey.items.removeFirst()
monkey.inspectCount++
item = monkey.operation(item)
while (item >= mod)
item %= mod
val toMonkey = monkey.throwOper(item)
monkeys[toMonkey].items.add(item)
}
}
}
return monkeys.map { it.inspectCount }.sorted().takeLast(2).let { (a, b) -> a * b }
}
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158L)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 789a2a027ea57954301d7267a14e26e39bfbc3c7 | 2,399 | advent-of-code-2022 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.