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/Day03.kt | dakr0013 | 572,861,855 | false | {"Kotlin": 105418} | import kotlin.streams.toList
import kotlin.test.assertEquals
fun main() {
fun part1(input: List<String>): Int {
return input
.map { rucksack ->
val firstCompartment =
rucksack.subSequence(0, rucksack.length / 2).chars().toList().toSet()
val secondCompartment =
rucksack.subSequence(rucksack.length / 2, rucksack.length).chars().toList().toSet()
val intersection = firstCompartment.intersect(secondCompartment)
intersection.first().also { println(it.toChar()) }
}
.map { itemType ->
if (itemType in 'a'.code..'z'.code) {
itemType - 'a'.code + 1
} else {
itemType - 'A'.code + 27
}
}
.sum()
}
fun part2(input: List<String>): Int {
return input
.windowed(3, 3)
.map { group ->
group
.map { it.chars().toList().toSet() }
.reduce { acc, ints -> acc.intersect(ints) }
.first()
}
.map { itemType ->
if (itemType in 'a'.code..'z'.code) {
itemType - 'a'.code + 1
} else {
itemType - 'A'.code + 27
}
}
.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
assertEquals(157, part1(testInput))
assertEquals(70, part2(testInput))
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 6b3adb09f10f10baae36284ac19c29896d9993d9 | 1,508 | aoc2022 | Apache License 2.0 |
src/Day07_part2.kt | abeltay | 572,984,420 | false | {"Kotlin": 91982, "Shell": 191} | fun main() {
fun part2(input: List<String>): Int {
data class Directory(
val name: String,
var size: Int = 0,
val subDirectories: MutableList<Directory> = mutableListOf()
)
fun changeDirectory(directory: Directory, name: String): Directory {
return directory.subDirectories.find { it.name == name } ?: Directory(name = name)
}
fun updateSize(directory: Directory): Int {
if (directory.subDirectories.isEmpty()) {
return directory.size
}
for (d in directory.subDirectories) {
directory.size += updateSize(d)
}
return directory.size
}
fun directorySizes(directory: Directory): List<Int> {
val sizes = mutableListOf(directory.size)
for (d in directory.subDirectories) {
sizes.addAll(directorySizes(d))
}
return sizes
}
val history = mutableListOf(Directory(name = "/"))
for (i in input.indices) {
val split = input[i].split(' ')
if (split[0] == "$") {
if (split[1] == "cd") {
when (split[2]) {
".." -> history.removeLast()
"/" -> while (history.size > 1) history.removeLast()
else -> history.add(changeDirectory(history.last(), split[2]))
}
}
} else {
val split = input[i].split(' ')
if (split[0] == "dir") {
history.last().subDirectories.add(Directory(name = split[1]))
} else {
history.last().size += split[0].toInt()
}
}
}
updateSize(history.first())
val directorySizes = directorySizes(history.first()).sorted()
val total = 70000000
val free = 30000000
val current = total - history.first().size
val toFree = free - current
return directorySizes.find { it > toFree }!!
}
val testInput = readInput("Day07_test")
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a51bda36eaef85a8faa305a0441efaa745f6f399 | 2,278 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/kr/co/programmers/P72413.kt | antop-dev | 229,558,170 | false | {"Kotlin": 695315, "Java": 213000} | package kr.co.programmers
import java.util.*
class P72413 {
companion object {
const val INF = (100_000 * 200) + 1
}
fun solution(n: Int, s: Int, a: Int, b: Int, fares: Array<IntArray>): Int {
// 지점 → (지점들,택시요금)
val paths = paths(n, fares)
// 다익스트라
val office = dijkstra(paths, s) // S → Other
val muzi = dijkstra(paths, a) // A → Other
val apeach = dijkstra(paths, b) // B → Other
// 합승 도착 지점 C를 기준으로 최소 비용 계산
var ans = INF
for (c in 1..n) {
val cost = office[c] + muzi[c] + apeach[c]
ans = minOf(ans, cost)
}
return ans
}
private fun paths(n: Int, fares: Array<IntArray>): Array<MutableList<Point>> {
val paths = Array(n + 1) { mutableListOf<Point>() }
for ((s, e, cost) in fares) {
paths[s] += Point(e, cost)
paths[e] += Point(s, cost)
}
return paths
}
private fun dijkstra(paths: Array<MutableList<Point>>, s: Int): IntArray {
val costs = IntArray(paths.size) { INF }
costs[s] = 0
val pq = LinkedList<Point>()
pq += Point(s, 0)
while (pq.isNotEmpty()) {
val curr = pq.poll()
for (next in paths[curr.n]) {
val nextCost = curr.cost + next.cost
if (nextCost < costs[next.n]) {
costs[next.n] = nextCost
pq += Point(next.n, nextCost)
}
}
}
return costs
}
data class Point(val n: Int, val cost: Int)
}
| 1 | Kotlin | 0 | 0 | 9a3e762af93b078a2abd0d97543123a06e327164 | 1,670 | algorithm | MIT License |
kotlin/src/com/s13g/aoc/aoc2020/Day16.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2020
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import com.s13g.aoc.mul
/**
* --- Day 16: Ticket Translation ---
* https://adventofcode.com/2020/day/16
*/
val rangeRegEx = """(.+): (\d+)-(\d+) or (\d+)-(\d+)""".toRegex()
class Day16 : Solver {
override fun solve(lines: List<String>): Result {
val (wordRanges, yourTicket, nearbyTickets) = parseInput(lines)
val allRanges = wordRanges.flatMap { listOf(it.value.range1, it.value.range2) }
val resultA = nearbyTickets.map { tixErrorRate(it, allRanges) }.sum()
val validTix = nearbyTickets.toMutableList().apply { add(yourTicket) }.filter { isValidTicket(it, allRanges) }
val allPlaces = setOf(*Array(yourTicket.size) { it })
val words = wordRanges.keys
// Map of word to viable placements. We start out with all positions and then remove bad ones.
val possiblePlaces = words.associateWith { allPlaces.toMutableSet() }
for (word in words) {
for (tix in validTix) {
for (i in tix.indices) {
// 'word' cannot be in position 'i' since it doesn't fit for ticket 'tix'.
if (!wordRanges[word]!!.isWithin(tix[i])) possiblePlaces[word]!!.remove(i)
}
}
}
val placements = reducePlaces(possiblePlaces)
val resultB = words.filter { it.startsWith("departure") }.map { yourTicket[placements[it]!!].toLong() }.mul()
return Result("$resultA", "$resultB")
}
/** Take possible placements and determine actual order/placements. */
private fun reducePlaces(placements: Map<String, MutableSet<Int>>): Map<String, Int> {
val result = mutableMapOf<String, Int>()
// Repeat until we have final placements for all words.
while (result.size != placements.size)
for (word in placements.keys) {
// If 'word' only has one possible location, put it there!
if (placements[word]!!.size == 1) {
val place = placements[word]!!.first()
result[word] = place
// Remove this position from all other words' possible placements.
placements.values.forEach { it.remove(place) }
}
}
return result
}
private fun isValidTicket(ticket: List<Int>, ranges: List<Range>): Boolean {
for (n in ticket) {
if (ranges.map { it.isWithin(n) }.count { it } == 0) return false
}
return true
}
private fun tixErrorRate(ticket: List<Int>, ranges: List<Range>) =
ticket.map { t -> if (ranges.map { it.isWithin(t) }.count { it } == 0) t else 0 }.sum()
private fun parseInput(lines: List<String>): Triple<Map<String, WordRange>, List<Int>, List<List<Int>>> {
val wordRanges = mutableMapOf<String, WordRange>()
val yourTicket = mutableListOf<Int>()
val nearbyTickets = mutableListOf<List<Int>>()
for (l in lines.indices) {
val rangeMatch = rangeRegEx.find(lines[l])
if (rangeMatch != null) {
val (word, from1, to1, from2, to2) = rangeMatch.destructured
wordRanges[word] = WordRange(Range(from1.toInt(), to1.toInt()), Range(from2.toInt(), to2.toInt()))
} else if ((l - 1) in lines.indices && lines[l - 1] == "your ticket:") {
yourTicket.addAll(lines[l].split(',').map { it.toInt() })
} else if ((l - 1) in lines.indices && lines[l - 1] == "nearby tickets:") {
lines.subList(l, lines.size).map { line -> nearbyTickets.add(line.split(',').map { it.toInt() }) }
break // We're done parsing after processing nearby tickets.
}
}
return Triple(wordRanges, yourTicket, nearbyTickets)
}
private data class Range(val from: Int, val to: Int)
private fun Range.isWithin(v: Int) = v in from..to
private data class WordRange(val range1: Range, val range2: Range)
private fun WordRange.isWithin(v: Int) = range1.isWithin(v) || range2.isWithin(v)
}
| 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 3,810 | euler | Apache License 2.0 |
2021/src/day13/Solution.kt | vadimsemenov | 437,677,116 | false | {"Kotlin": 56211, "Rust": 37295} | package day13
import java.nio.file.Files
import java.nio.file.Paths
fun main() {
fun log(field: Array<BooleanArray>) = buildString {
for (y in field[0].indices) {
for (x in field.indices) {
append(if (field[x][y]) '#' else '.')
}
append('\n')
}
}.let { System.err.println(it) }
fun fold(field: Array<BooleanArray>, fold: Pair<Boolean, Int>): Array<BooleanArray> =
if (fold.first) {
val foldX = fold.second
check(field[foldX].none { it })
val maxX = maxOf(foldX, field.size - 1 - foldX)
Array(maxX) { xx ->
BooleanArray(field[xx].size) { yy ->
val x1 = foldX - (maxX - xx)
val x2 = foldX + (maxX - xx)
(x1 >= 0 && field[x1][yy]) || (x2 < field.size && field[x2][yy])
}
}
} else {
val foldY = fold.second
val maxY = maxOf(foldY, field[0].size - foldY - 1)
check(field.none { it[foldY] })
Array(field.size) { xx ->
BooleanArray(maxY) { yy ->
val y1 = foldY - (maxY - yy)
val y2 = foldY + (maxY - yy)
(y1 >= 0 && field[xx][y1]) || (y2 < field[xx].size && field[xx][y2])
}
}
}
fun part1(input: Input): Int {
val maxX = input.first.maxOf { it.first }
val maxY = input.first.maxOf { it.second }
val field = Array(maxX + 1) {
BooleanArray(maxY + 1)
}
for ((x, y) in input.first) {
field[x][y] = true
}
return fold(field, input.second.first()).sumOf { it.count { it } }
}
fun part2(input: Input): Int {
val maxX = input.first.maxOf { it.first }
val maxY = input.first.maxOf { it.second }
var field = Array(maxX + 1) {
BooleanArray(maxY + 1)
}
for ((x, y) in input.first) {
field[x][y] = true
}
for (fold in input.second) {
field = fold(field, fold)
}
log(field)
return 42
}
check(part1(readInput("test-input.txt")) == 17)
check(part2(readInput("test-input.txt")) == 42)
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
private fun readInput(s: String): Input {
return Files.newBufferedReader(Paths.get("src/day13/$s")).readLines().let { lines ->
val coordinates = lines
.filter { !it.startsWith("fold along ") }
.filter { it.isNotBlank() }
.map {
val (x, y) = it.split(",").map { it.toInt() }
Pair(x, y)
}
val folds = lines
.filter { it.startsWith("fold along ") }
.map {
val (axis, coordinate) = it.substring("fold along ".length).split("=")
val axisRes = when(axis) {
"x" -> true
"y" -> false
else -> error("unknown axis: $axis")
}
Pair(axisRes, coordinate.toInt())
}
Pair(coordinates, folds)
}
}
private typealias Input = Pair<List<Pair<Int, Int>>, List<Pair<Boolean, Int>>> | 0 | Kotlin | 0 | 0 | 8f31d39d1a94c862f88278f22430e620b424bd68 | 2,865 | advent-of-code | Apache License 2.0 |
2022/src/test/kotlin/Day08.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
class Day08 : StringSpec({
"puzzle part 01" {
val (trees, maxX, maxY) = getTreesWithSizing()
val countOfVisibleTrees = (0..maxX).sumOf { x ->
(0..maxY).count { y ->
val height = trees[x][y]
(x - 1 downTo 0).none { trees[it][y] >= height } ||
(x + 1..maxX).none { trees[it][y] >= height } ||
(y - 1 downTo 0).none { trees[x][it] >= height } ||
(y + 1..maxY).none { trees[x][it] >= height }
}
}
countOfVisibleTrees shouldBe 1798
}
"puzzle part 02" {
val (trees, maxX, maxY) = getTreesWithSizing()
val maxScore = (1 until maxX).flatMap { x ->
(1 until maxY).map { y ->
val height = trees[x][y]
val left = (x - 1 downTo 0).firstOrNull { trees[it][y] >= height }?.let { x - it } ?: x
val right = (x + 1..maxX).firstOrNull { trees[it][y] >= height }?.let { it - x } ?: (maxX - x)
val up = (y - 1 downTo 0).firstOrNull { trees[x][it] >= height }?.let { y - it } ?: y
val down = (y + 1..maxY).firstOrNull { trees[x][it] >= height }?.let { it - y } ?: (maxY - y)
left * right * up * down
}
}.max()
maxScore shouldBe 259308
}
})
private fun getTreesWithSizing() = getPuzzleInput("day08-input.txt")
.map { it.map(Char::digitToInt).toIntArray() }
.toList().toTypedArray()
.let { Triple(it, it[0].size - 1, it.size - 1) }
| 0 | Kotlin | 1 | 2 | 8bc5e92ce961440e011688319e07ca9a4a86d9c9 | 1,623 | adventofcode | MIT License |
src/main/kotlin/dp/LIBFS.kt | yx-z | 106,589,674 | false | null | package dp
import util.OneArray
import util.max
import util.oneArrayOf
import util.toOneArray
// longest increasing back and forth subsequence
// given A[1..n], an array of (Int, Color) pair
// its ibfs, I[1..l] follows:
// 1 <= I[j] <= n
// A[I[j]] < A[I[j + 1]]
// If A[I[j]] is Red, then I[j + 1] > I[j]
// If A[I[j]] is Blue, then I[j + 1] < I[j]
// find the length of longest such sequence
fun main(args: Array<String>) {
val A = oneArrayOf(
1 to Color.Red,
1 to Color.Blue,
0 to Color.Red,
2 to Color.Blue,
5 to Color.Blue,
9 to Color.Red,
6 to Color.Blue,
6 to Color.Red,
4 to Color.Blue,
5 to Color.Red,
8 to Color.Red,
9 to Color.Blue,
7 to Color.Blue,
7 to Color.Red,
3 to Color.Red,
2 to Color.Red,
3 to Color.Blue,
8 to Color.Blue,
4 to Color.Red,
0 to Color.Blue
)
println(A.lbfs())
}
fun OneArray<Pair<Int, Color>>.lbfs(): Int {
val A = this
val n = A.size
// sort A to get an array of (index, value, Color) that descends in value
val sortedA = A.indices
.map { it to A[it] }
.toList()
.sortedByDescending { it.second.first }
.toOneArray()
// sortedA.prettyPrintln()
// dp(i) = len of longest such sequence starting @ A[i]
val dp = OneArray(n) { 0 }
// space complexity: O(n)
// base case:
// dp(i) = 1 if i is the index A having the maximum value
dp[sortedA[1].first] = 1
// recursive case:
// assume max{ } = 0
// dp(i) = 1 + max{ dp(k) : A[k] > A[i], k > i } if A[i] is Red, i in 1..n
// = 1 + max{ dp(k) : A[k] > A[i], k < i } if A[i] is Blue, i in 1..n
// = 0 o/w
// dependency: dp(i) depends on dp(k) where k is an index in A : A[i] > A[k]
// evaluation order: outer loop for i from sortedA[2]_1 to sortedA[n]_1
// that is a loop for idx from 2 to n in sortedA
for (idx in 2..n) {
val i = sortedA[idx].first
dp[i] = 1 + when (A[i].second) {
Color.Red -> (i + 1..n)
.filter { k -> A[k].first > A[i].first }
.map { k -> dp[k] }
.max() ?: 0
Color.Blue -> (1 until i)
.filter { k -> A[k].first > A[i].first }
.map { k -> dp[k] }
.max() ?: 0
}
}
// time complexity: O(n^2)
// dp.prettyPrintln()
// we want max_i{ dp(i) }
return dp.max() ?: 0
}
enum class Color {
Red, Blue;
} | 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 2,271 | AlgoKt | MIT License |
src/Day04.kt | zdenekobornik | 572,882,216 | false | null | fun main() {
fun part1(input: List<String>): Int {
return input.map {
it.split(',', limit = 2)
.map {
it.split('-', limit = 2).map(String::toInt)
}
}.count { (l, r) ->
(l[0] >= r[0] && l[1] <= r[1]) || (r[0] >= l[0] && r[1] <= l[1])
}
}
fun part2(input: List<String>): Int {
return input.map {
it.split(',', limit = 2)
.map {
it.split('-', limit = 2).map(String::toInt)
}
}.count { (left, right) ->
val (l0, l1) = left
val (r0, r1) = right
l0 in r0..r1 || l1 in r0..r1 || l0 >= r0 && l1 <= r1 || r0 >= l0 && r1 <= l1
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
checkResult(part1(testInput), 2)
checkResult(part2(testInput), 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f73e4a32802fa43b90c9d687d3c3247bf089e0e5 | 1,047 | advent-of-code-2022 | Apache License 2.0 |
src/questions/SummaryRanges.kt | realpacific | 234,499,820 | false | null | package questions
import utils.shouldBe
/**
* You are given a sorted unique integer array nums.
*
* Return the smallest sorted list of ranges that cover all the numbers in the array exactly.
* That is, each element of nums is covered by exactly one of the ranges,
* and there is no integer x such that x is in one of the ranges but not in nums.
*
* Each range [a,b] in the list should be output as:
* *"a->b" if a != b
* * "a" if a == b
*
* [Source](https://leetcode.com/problems/summary-ranges/)
*/
private fun summaryRanges(nums: IntArray): List<String> {
if (nums.isEmpty()) return emptyList()
if (nums.size == 1) return listOf(nums[0].toString())
val result = mutableListOf<String>()
findRange(nums, startIndex = 0, currentIndex = 1, result)
return result
}
private fun findRange(nums: IntArray, startIndex: Int, currentIndex: Int, result: MutableList<String>) {
if (currentIndex > nums.lastIndex) { // end
// add the remaining
val start = nums[startIndex]
val end = nums[nums.lastIndex]
addToList(start, end, result)
return
}
return if (nums[currentIndex - 1] == nums[currentIndex] - 1) { // Check if sequential i.e (prevElem+1 = current)
findRange(nums, startIndex = startIndex, currentIndex = currentIndex + 1, result)
} else {
val start = nums[startIndex]
val end = nums[currentIndex - 1]
addToList(start, end, result)
findRange(
nums,
startIndex = currentIndex, // start from current as current element is the one that violated
currentIndex = currentIndex + 1, // should be 1 step ahead of [startIndex]
result
)
}
}
private fun addToList(start: Int, end: Int, result: MutableList<String>) {
if (start == end) result.add("$start")
else result.add("$start->$end")
}
fun main() {
summaryRanges(nums = intArrayOf(-1)) shouldBe listOf("-1")
summaryRanges(nums = intArrayOf(0, 1, 2, 4, 5, 7)) shouldBe listOf("0->2", "4->5", "7")
summaryRanges(nums = intArrayOf(0, 2, 3, 4, 6, 8, 9)) shouldBe listOf("0", "2->4", "6", "8->9")
summaryRanges(nums = intArrayOf()) shouldBe listOf()
summaryRanges(nums = intArrayOf(0)) shouldBe listOf("0")
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 2,263 | algorithms | MIT License |
src/main/kotlin/Day02.kt | robfletcher | 724,814,488 | false | {"Kotlin": 18682} | class Day02 : Puzzle {
override fun test() {
val testInput = """
Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue
Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red
Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red
Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green""".trimIndent()
assert(part1(testInput.lineSequence()) == 8)
assert(part2(testInput.lineSequence()) == 2286)
}
fun parseHand(group: String) =
Regex("""(\d+) (\w+)""")
.findAll(group)
.map(MatchResult::groupValues)
.associate { (_, n, color) -> color to n.toInt() }
override fun part1(input: Sequence<String>): Int {
val bag = mapOf("red" to 12, "green" to 13, "blue" to 14)
return input.sumOf { line ->
val id = checkNotNull(Regex("""Game (\d+):""").find(line)).groupValues[1].toInt()
val possible = line.substringAfter(':').split(';').all { group ->
parseHand(group).all { it.value <= bag.getValue(it.key) }
}
if (possible) id else 0
}
}
override fun part2(input: Sequence<String>): Int =
input.fold(0) { acc, line ->
line
.substringAfter(':')
.split(';')
.fold(mapOf("red" to 0, "green" to 0, "blue" to 0)) { bag, group ->
parseHand(group).let { hand ->
bag.mapValues { (color, n) -> maxOf(n, hand[color] ?: 0) }
}
}
.run { acc + values.reduce(Int::times) }
}
} | 0 | Kotlin | 0 | 0 | cf10b596c00322ea004712e34e6a0793ba1029ed | 1,549 | aoc2023 | The Unlicense |
solutions/aockt/y2023/Y2023D12.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2023
import aockt.util.parse
import aockt.y2023.Y2023D12.Condition.Damaged
import aockt.y2023.Y2023D12.Condition.Operational
import aockt.y2023.Y2023D12.Condition.Unknown
import io.github.jadarma.aockt.core.Solution
object Y2023D12 : Solution {
/** The condition record of a spring. If unknown, can be assumed to be either of the other two. */
private enum class Condition { Operational, Damaged, Unknown }
/**
* An entry in the spring ledger.
* @property springs The condition of the springs in this entry.
* @property checksum The number and size of the runs of damaged springs.
*/
private data class ConditionRecord(val springs: List<Condition>, val checksum: List<Int>) {
/**
* The number of valid solutions tanking into account [Unknown] spring conditions, if any.
* If there are no unknown [springs], this value will be 1 if the [checksum] is valid, or 0 otherwise.
*/
fun validSolutions(cache: MutableMap<ConditionRecord, Long>): Long {
// If the valid solution has already been computed, reuse it.
cache[this]?.let { return it }
// If no springs left, either no checksums left to satisfy, or the record is invalid.
if (springs.isEmpty()) return if (checksum.isEmpty()) 1 else 0
// If some springs left, but no checksums, then all remaining springs must be operational.
// Unknowns can be assumed as operational, but if any known damaged left, the record is invalid.
if (checksum.isEmpty()) return if (springs.contains(Damaged)) 0 else 1
val spring = springs.first()
val expectedDamaged = checksum.first()
// If the next spring could be operational, then nothing to check, just ignore it.
val solutionsIfOperational =
if (spring != Damaged) ConditionRecord(springs.drop(1), checksum).validSolutions(cache)
else 0
// If the next spring could be damaged, check that all conditions for a valid damaged streak are met:
// - There must be at least as many springs left as the next expected checksum value.
// - The next checksum value's worth of springs must all be (or can be disambiguated into being) damaged.
// - After the streak, either there are no springs left to check, or the streak is properly ended by an
// operational spring (or one that can be disambiguated as such).
// If these conditions are met, then we should skip the current damaged streak (and maybe its terminator)
// entirely, satisfy the checksum, and process the remaining springs.
val solutionsIfSpringDamaged = when {
spring == Operational -> 0
expectedDamaged > springs.size -> 0
springs.take(expectedDamaged).any { it == Operational } -> 0
springs.size != expectedDamaged && springs[expectedDamaged] == Damaged -> 0
else -> ConditionRecord(springs.drop(expectedDamaged + 1), checksum.drop(1)).validSolutions(cache)
}
return solutionsIfOperational
.plus(solutionsIfSpringDamaged)
.also { result -> cache[this] = result }
}
}
/**
* Parse the [input] and return the list of condition records.
* @param input The puzzle input.
* @param unfold Whether to unfold the records before reading them.
*/
private fun parseInput(input: String, unfold: Boolean): List<ConditionRecord> = parse {
val lineRegex = Regex("""^([#.?]+) (\d[\d,]*\d)$""")
fun String.unfold(separator: Char): String = buildString(length.inc() + 5) {
val original = this@unfold
append(original)
repeat(4) { append(separator, original) }
}
input
.lineSequence()
.map { lineRegex.matchEntire(it)!!.destructured }
.map { (record, checksum) ->
if(unfold) record.unfold('?') to checksum.unfold(',')
else record to checksum
}
.map { (record, checksum) ->
ConditionRecord(
springs = record.map {
when(it) {
'.' -> Operational
'#' -> Damaged
'?' -> Unknown
else -> error("Impossible state")
}
},
checksum = checksum.split(',').map(String::toInt),
)
}
.toList()
}
/**
* Calculate the sum of valid solutions to all records.
* Cached only in the context of a solve, to keep parts isolated, and to not let it "cheat" if part function called
* multiple times.
*/
private fun List<ConditionRecord>.solve(): Long {
val cache: MutableMap<ConditionRecord, Long> = mutableMapOf()
return sumOf { it.validSolutions(cache) }
}
override fun partOne(input: String) = parseInput(input, unfold = false).solve()
override fun partTwo(input: String) = parseInput(input, unfold = true).solve()
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 5,255 | advent-of-code-kotlin-solutions | The Unlicense |
src/main/kotlin/dev/paulshields/aoc/day5/BinaryBoarding.kt | Pkshields | 318,658,287 | false | null | package dev.paulshields.aoc.day5
import dev.paulshields.aoc.common.readFileAsStringList
private const val lowerRowRegionId = 'F'
private const val lowerColumnRegionId = 'L'
private val rows = 0..127
private val columns = 0..7
fun main() {
println(" ** Day 5: Binary Boarding ** \n")
val boardingPasses = readFileAsStringList("/day5/BoardingPasses.txt")
val allAssignedSeatNumbers = boardingPasses.map {
val rowNumber = calculateRowNumber(it)
val seatNumber = calculateColumnNumber(it)
calculateSeatId(rowNumber, seatNumber)
}
val largestSeatNumber = allAssignedSeatNumbers.maxOrNull() ?: 0
println("There largest seat number is $largestSeatNumber!")
val mySeatNumber = (0..largestSeatNumber)
.toList()
.first {
seatNumbersIsNotAssigned(allAssignedSeatNumbers, it)
&& adjacentSeatNumbersAreAssigned(allAssignedSeatNumbers, it)
}
println("My seat number is $mySeatNumber!")
}
fun calculateRowNumber(seatSpecification: String) =
seatSpecification
.take(7)
.fold(rows) { range, regionId ->
binarySplitRangeByRegionId(range, regionId, lowerRowRegionId)
}
.first
fun calculateColumnNumber(seatSpecification: String) =
seatSpecification
.drop(7)
.fold(columns) { range, regionId ->
binarySplitRangeByRegionId(range, regionId, lowerColumnRegionId)
}
.first
private fun binarySplitRangeByRegionId(range: IntRange, regionId: Char, lowerRegionId: Char): IntRange {
val rangeLength = range.last - range.first
val binarySplitPosition = range.first + (rangeLength / 2)
return if (regionId == lowerRegionId) {
range.first .. binarySplitPosition
} else {
binarySplitPosition + 1 .. range.last
}
}
fun calculateSeatId(rowNumber: Int, columnNumber: Int) = (rowNumber * 8) + columnNumber
fun seatNumbersIsNotAssigned(allAssignedSeatNumbers: List<Int>, seatNumber: Int) =
!allAssignedSeatNumbers.contains(seatNumber)
fun adjacentSeatNumbersAreAssigned(allAssignedSeatNumbers: List<Int>, seatNumber: Int) =
allAssignedSeatNumbers.contains(seatNumber - 1) && allAssignedSeatNumbers.contains(seatNumber + 1)
| 0 | Kotlin | 0 | 0 | a7bd42ee17fed44766cfdeb04d41459becd95803 | 2,253 | AdventOfCode2020 | MIT License |
src/aoc2022/Day02.kt | FluxCapacitor2 | 573,641,929 | false | {"Kotlin": 56956} | package aoc2022
import Day
object Day02 : Day(2022, 2) {
// Read input from a file
private val split = input.lines()
// Split each line into a player and opponent move; they are separated by one space
.map { it.split(' ') }
override fun part1() {
val totalPointValue1 = split
.map { it.map(RPS::from) } // Convert the letters into either Rock, Paper, or Scissors
.sumOf { (opponentMove, playerMove) ->
// Get the point value of the turn.
val outcomeValue =
playerMove.against(opponentMove).pointValue // Winning gives 6 points, drawing gives 3 points, and losing rewards no points.
val shapeValue = playerMove.shapeValue // Rock = 1 point, Paper = 2 points, Scissors = 3 points
return@sumOf outcomeValue + shapeValue // The score for each round is the sum of the sub-scores.
}
// Print the result
println("Part 1 result: $totalPointValue1")
}
override fun part2() {
val totalPointValue2 = split
.map { RPS.from(it[0]) to Outcome.from(it[1]) } // Convert the strings into a nicer format
.sumOf { (opponentMove, outcome) ->
// The player's move must be computed based on the fixed outcome.
// An outcome of X means a loss, Y means a draw, and Z means a win.
val playerMove = RPS.values().find { it.against(opponentMove) == outcome }!!
val shapeValue = playerMove.shapeValue
val outcomeValue = outcome.pointValue
return@sumOf shapeValue + outcomeValue
}
println("Part 2 result: $totalPointValue2")
}
/**
* An enum that represents a shape (either Rock, Paper, or Scissors).
*/
enum class RPS(val shapeValue: Int) {
ROCK(1), PAPER(2), SCISSORS(3);
/**
* Plays this shape against the other shape, returning the outcome.
* For example: RPS.PAPER.against(RPS.ROCK) results in Outcome.WIN.
*/
fun against(other: RPS): Outcome = when (this) {
ROCK -> when (other) {
ROCK -> Outcome.DRAW
PAPER -> Outcome.LOSS
SCISSORS -> Outcome.WIN
}
PAPER -> when (other) {
ROCK -> Outcome.WIN
PAPER -> Outcome.DRAW
SCISSORS -> Outcome.LOSS
}
SCISSORS -> when (other) {
ROCK -> Outcome.LOSS
PAPER -> Outcome.WIN
SCISSORS -> Outcome.DRAW
}
}
companion object {
/**
* Converts a string (A/B/C or X/Y/Z) into a [RPS] object.
*/
fun from(string: String) = when (string) {
"A", "X" -> ROCK
"B", "Y" -> PAPER
"C", "Z" -> SCISSORS
else -> error("Invalid string: $string")
}
}
}
enum class Outcome(val pointValue: Int) {
WIN(6), LOSS(0), DRAW(3);
companion object {
fun from(outcomeString: String) = when (outcomeString) {
"X" -> LOSS
"Y" -> DRAW
"Z" -> WIN
else -> error("Invalid outcome string: $outcomeString")
}
}
}
}
| 0 | Kotlin | 0 | 0 | a48d13763db7684ee9f9129ee84cb2f2f02a6ce4 | 3,394 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | PauliusRap | 573,434,850 | false | {"Kotlin": 20299} | private const val CHAR_CODE_OFFSET_UPPERCASE = 64
private const val CHAR_CODE_OFFSET_LOWERCASE = 96
private const val POINTS_OFFSET_UPPERCASE = 26
fun main() {
fun getValueFromChar(char: Char) =
if (char.isUpperCase()) {
char.code - CHAR_CODE_OFFSET_UPPERCASE + POINTS_OFFSET_UPPERCASE
} else {
char.code - CHAR_CODE_OFFSET_LOWERCASE
}
fun getMatchingItemPoints(line: String): Int {
val midPoint = line.length / 2
val part1 = line.substring(0, midPoint)
val part2 = line.substring(midPoint)
var points = 0
part1.forEach {
if (part2.contains(it)) {
points = getValueFromChar(it)
}
}
return points
}
fun getMatchingItemPoints(lines: List<String>): Int {
var points = 0
lines[0].forEach {
if (lines[1].contains(it) && lines[2].contains(it)) {
points = getValueFromChar(it)
}
}
return points
}
fun splitIntoGroupsOfThree(input: List<String>): List<List<String>> {
var currentIndex = -1
return input.mapIndexedNotNull { index, _ ->
if (index - currentIndex == 3) {
currentIndex = index
listOf(input[index], input[index - 1], input[index - 2])
} else null
}
}
fun part1(input: List<String>) = input.sumOf { getMatchingItemPoints(it) }
fun part2(input: List<String>) = splitIntoGroupsOfThree(input).sumOf { getMatchingItemPoints(it) }
// test if implementation meets criteria from the description:
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 | df510c3afb104c03add6cf2597c433b34b3f7dc7 | 1,839 | advent-of-coding-2022 | Apache License 2.0 |
src/main/kotlin/ch/uzh/ifi/seal/bencher/prioritization/Prioritizer.kt | chrstphlbr | 227,602,878 | false | {"Kotlin": 918163, "Java": 29153} | package ch.uzh.ifi.seal.bencher.prioritization
import arrow.core.Either
import ch.uzh.ifi.seal.bencher.Benchmark
import kotlin.random.Random
interface Prioritizer {
// takes an Iterable of benchmarks and returns a prioritized list of these methods sorted by their priority (descending)
// might not include benchmarks if they are not relevant anymore (e.g., were removed according to static analysis, etc)
fun prioritize(benchs: Iterable<Benchmark>): Either<String, List<PrioritizedMethod<Benchmark>>>
companion object {
fun benchWithNoPrio(pb: PrioritizedMethod<Benchmark>): Boolean =
pb.priority.rank == -1 && pb.priority.total == -1
fun rankBenchs(benchs: Collection<PrioritizedMethod<Benchmark>>): List<PrioritizedMethod<Benchmark>> {
// remove not prioritized benchmarks
val filtered = benchs.filter { !benchWithNoPrio(it) }
val s = filtered.size
var lastValue = 0.0
var lastRank = 1
return filtered.mapIndexed { i, b ->
val v: Double = when (val v = b.priority.value) {
is PrioritySingle -> v.value
// sum up all prioritiy values to get a single value
is PriorityMultiple -> v.values.sum()
}
val rank = if (lastValue == v) {
lastRank
} else {
i + 1
}
lastRank = rank
lastValue = v
PrioritizedMethod(
method = b.method,
priority = Priority(rank = rank, total = s, value = b.priority.value)
)
}
}
}
}
interface PrioritizerMultipleSolutions : Prioritizer {
// random is used internally to decide which solution to pick in prioritize
val random: Random
// takes an Iterable of benchmarks and returns a prioritized list of these methods sorted by their priority (descending)
// might not include benchmarks if they are not relevant anymore (e.g., were removed according to static analysis, etc)
// provides a default implementation of Prioritizer.prioritize that works when multiple solutions are available:
// if there are multiple prioritized solutions (e.g., acquired through a multi-objective optimization algorithm), a randomly-selected best solution is returned
// use prioritizeMultipleSolutions to get all solutions
override fun prioritize(benchs: Iterable<Benchmark>): Either<String, List<PrioritizedMethod<Benchmark>>> =
prioritizeMultipleSolutions(benchs).map { solutions ->
val idx = random.nextInt().mod(solutions.size)
solutions[idx]
}
// prioritizeMultipleSolutions returns all prioritization solution for the provided benchmark Iterable
fun prioritizeMultipleSolutions(benchs: Iterable<Benchmark>): Either<String, List<List<PrioritizedMethod<Benchmark>>>>
}
| 0 | Kotlin | 2 | 4 | 06601fb4dda3b2996c2ba9b2cd612e667420006f | 3,006 | bencher | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2023/2023-13.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2023
import com.github.ferinagy.adventOfCode.Coord2D
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputText
fun main() {
val input = readInputText(2023, "13-input")
val test1 = readInputText(2023, "13-test1")
println("Part1:")
part1(test1).println()
part1(input).println()
println()
println("Part2:")
part2(test1).println()
part2(input).println()
}
private fun part1(input: String) = parse(input).sumOf { vertical(it) + 100 * horizontal(it) }
private fun part2(input: String) = parse(input).sumOf { vertical(it, 1) + 100 * horizontal(it, 1) }
private fun parse(input: String) = input.split("\n\n").map { block ->
block.lines().flatMapIndexed { y, line ->
line.mapIndexedNotNull { x, c ->
if (c == '#') Coord2D(x, y) else null
}
}
}
private fun vertical(rocks: List<Coord2D>, smudges: Int = 0): Int {
val min = rocks.minOf { it.x }
val max = rocks.maxOf { it.x }
return (min + 1..max).indexOfFirst { mirror ->
rocks.count {
val opposite = Coord2D(mirror - (it.x - mirror) - 1, it.y)
opposite.x in min..max && opposite !in rocks
} == smudges
} + 1
}
private fun horizontal(rocks: List<Coord2D>, smudges: Int = 0): Int {
val min = rocks.minOf { it.y }
val max = rocks.maxOf { it.y }
return (min + 1..max).indexOfFirst { mirror ->
rocks.count {
val opposite = Coord2D(it.x, mirror - (it.y - mirror) - 1)
opposite.y in min..max && opposite !in rocks
} == smudges
} + 1
}
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 1,652 | advent-of-code | MIT License |
src/day20/Day20.kt | Volifter | 572,720,551 | false | {"Kotlin": 65483} | package day20
import utils.*
const val KEY = 811589153
class Element<T>(val value: T) {
private var prev: Element<T> = this
private var next: Element<T> = this
private val sequence get() = generateSequence(this) { it.next }
private val reverseSequence get() = generateSequence(this) { it.prev }
fun append(element: Element<T>) {
element.next = next
element.prev = this
next.prev = element
next = element
}
private fun disconnect() {
prev.next = next
next.prev = prev
}
fun moveForward(offset: Int) {
disconnect()
prev.sequence.elementAt(offset).append(this)
}
fun moveBackward(offset: Int) {
disconnect()
prev.reverseSequence.elementAt(offset).append(this)
}
companion object {
fun <T> buildSequence(list: List<T>): Sequence<Element<T>> =
list
.drop(1)
.fold(Element(list.first())) { prev, value ->
Element(value).also { prev.append(it) }
}
.next
.sequence
}
}
fun mix(list: List<Long>, count: Int = 1): List<Long> {
val size = list.size
val sequence = Element.buildSequence(list)
val elements = sequence.take(size).toList()
repeat(count) {
elements.forEach { element ->
val forwardOffset = Math.floorMod(element.value, size - 1)
val backwardOffset = size - 1 - forwardOffset
if (forwardOffset < backwardOffset)
element.moveForward(forwardOffset)
else
element.moveBackward(backwardOffset)
}
}
return sequence
.map { it.value }
.dropWhile { it != 0L }
.take(size)
.toList()
}
fun part1(input: List<String>): Long {
val numbers = input.map { it.toLong() }
val mixed = mix(numbers)
return (1000..3000 step 1000).sumOf { mixed[it % mixed.size] }
}
fun part2(input: List<String>): Long {
val numbers = input.map { it.toLong() * KEY }
val mixed = mix(numbers, 10)
return (1000..3000 step 1000).sumOf { mixed[it % mixed.size] }
}
fun main() {
val testInput = readInput("Day20_test")
expect(part1(testInput), 3)
expect(part2(testInput), 1623178306)
val input = readInput("Day20")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | c2c386844c09087c3eac4b66ee675d0a95bc8ccc | 2,395 | AOC-2022-Kotlin | Apache License 2.0 |
src/Day02.kt | ochim | 579,680,353 | false | {"Kotlin": 3652} | fun main() {
val baseScores = mapOf(
'X' to 1, //Rock
'Y' to 2, //Paper
'Z' to 3 //Scissors
)
val roundScores = mapOf(
"A X" to 3,
"A Y" to 6,
"A Z" to 0,
"B X" to 0,
"B Y" to 3,
"B Z" to 6,
"C X" to 6,
"C Y" to 0,
"C Z" to 3,
)
fun part1(input: List<String>): Int {
return input.sumOf { str ->
val me = str[2]
baseScores[me]!! + roundScores[str]!!
}
}
fun part2(input: List<String>): Int {
return input.sumOf { str ->
val op = str[0]
val roundScore: Int = when (str[2]) {
'X' -> 0
'Y' -> 3
'Z' -> 6
else -> throw IllegalArgumentException()
}
val item = roundScores.firstNotNullOf { (key, value) -> if (key[0] == op && value == roundScore) key else null }
roundScore + baseScores[item[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")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | b5d34a8f0f3000c8ad4afd7726dd93171baee76e | 1,287 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day09.kt | konclave | 573,548,763 | false | {"Kotlin": 21601} | import kotlin.math.abs
class Dot {
private var x: Int = 0
private var y: Int = 0
private var visited: MutableSet<String> = mutableSetOf("0,0")
val visitedCount: Int
get() {
return visited.size
}
fun move(command: String): Pair<Int, Int> {
when (command) {
"R" -> {
x += 1
}
"U" -> {
y += 1
}
"L" -> {
x -= 1
}
"D" -> {
y -= 1
}
}
return Pair(x, y)
}
fun follow(coords: Pair<Int, Int>): Pair<Int, Int> {
val (destX, destY) = coords
if (abs(destX - x) > 1 && y != destY || abs(destY - y) > 1 && destX != x) {
x += if (destX - x > 0) 1 else -1
y += if (destY - y > 0) 1 else -1
} else {
if (abs(destX - x) > 1) {
x += if ((destX - x) > 0) destX - x - 1 else destX - x + 1
}
if (abs(destY - y) > 1) {
y += if ((destY - y) > 0) destY - y - 1 else destY - y + 1
}
}
visited.add("$x,$y")
return Pair(x, y)
}
}
fun main() {
fun solve1(input: List<String>): Int {
val head = Dot()
val tail = Dot()
input.forEach {
val (command, steps) = it.split(" ")
repeat(steps.toInt()) {
tail.follow(head.move(command))
}
}
return tail.visitedCount
}
fun solve2(input: List<String>): Int {
val rope: List<Dot> = List(9) { Dot() }
val head = Dot()
input.forEach {
val (command, steps) = it.split(" ")
repeat(steps.toInt()) {
val headCoords = head.move(command)
rope.fold(headCoords){ coords, dot ->
dot.follow(coords)
}
}
}
val tail = rope.last()
return tail.visitedCount
}
val input = readInput("Day09")
println(solve1(input))
println(solve2(input))
}
| 0 | Kotlin | 0 | 0 | 337f8d60ed00007d3ace046eaed407df828dfc22 | 2,107 | advent-of-code-2022 | Apache License 2.0 |
leetcode-75-kotlin/src/main/kotlin/FindTheDifferenceOfTwoArrays.kt | Codextor | 751,507,040 | false | {"Kotlin": 49566} | /**
* Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where:
*
* answer[0] is a list of all distinct integers in nums1 which are not present in nums2.
* answer[1] is a list of all distinct integers in nums2 which are not present in nums1.
* Note that the integers in the lists may be returned in any order.
*
*
*
* Example 1:
*
* Input: nums1 = [1,2,3], nums2 = [2,4,6]
* Output: [[1,3],[4,6]]
* Explanation:
* For nums1, nums1[1] = 2 is present at index 0 of nums2,
* whereas nums1[0] = 1 and nums1[2] = 3 are not present in nums2. Therefore, answer[0] = [1,3].
* For nums2, nums2[0] = 2 is present at index 1 of nums1,
* whereas nums2[1] = 4 and nums2[2] = 6 are not present in nums2. Therefore, answer[1] = [4,6].
* Example 2:
*
* Input: nums1 = [1,2,3,3], nums2 = [1,1,2,2]
* Output: [[3],[]]
* Explanation:
* For nums1, nums1[2] and nums1[3] are not present in nums2.
* Since nums1[2] == nums1[3], their value is only included once and answer[0] = [3].
* Every integer in nums2 is present in nums1. Therefore, answer[1] = [].
*
*
* Constraints:
*
* 1 <= nums1.length, nums2.length <= 1000
* -1000 <= nums1[i], nums2[i] <= 1000
* @see <a href="https://leetcode.com/problems/find-the-difference-of-two-arrays/">LeetCode</a>
*/
fun findDifference(nums1: IntArray, nums2: IntArray): List<List<Int>> {
val nums1Set = nums1.toHashSet()
val nums2Set = nums2.toHashSet()
val nums1Diff = nums1Set.subtract(nums2Set).toList()
val nums2Diff = nums2Set.subtract(nums1Set).toList()
return listOf(nums1Diff, nums2Diff)
}
| 0 | Kotlin | 0 | 0 | 0511a831aeee96e1bed3b18550be87a9110c36cb | 1,602 | leetcode-75 | Apache License 2.0 |
src/Day05.kt | hiteshchalise | 572,795,242 | false | {"Kotlin": 10694} | fun main() {
fun part1(input: List<String>): String {
val splitIndex = input.indexOfFirst { it.isEmpty() }
val stackInput = input.subList(0, splitIndex - 1)
val instructionInput = input.subList(splitIndex + 1, input.size)
val sanitizedStackInput = stackInput.map { line -> line.windowed(3, 4) }
val stacksOfCrate = List<ArrayDeque<Char>>(sanitizedStackInput.maxOf { it.size }) { ArrayDeque() }
for (line in sanitizedStackInput) {
line.forEachIndexed { index, crate ->
if (crate.isNotBlank()) stacksOfCrate[index].add(crate[1])
}
}
instructionInput.forEach { line ->
val (amount, from, to) = line.split(" ").filter { it.toIntOrNull() != null }.map { it.toInt() }
for(index in 0 until amount) {
stacksOfCrate[to - 1].addFirst(stacksOfCrate[from - 1].removeFirst())
}
}
return stacksOfCrate.map { it.first() }.joinToString("")
}
fun part2(input: List<String>): String {
val splitIndex = input.indexOfFirst { it.isEmpty() }
val stackInput = input.subList(0, splitIndex - 1)
val instructionInput = input.subList(splitIndex + 1, input.size)
val sanitizedStackInput = stackInput.map { line -> line.windowed(3, 4) }
val stacksOfCrate = List<ArrayDeque<Char>>(sanitizedStackInput.maxOf { it.size }) { ArrayDeque() }
for (line in sanitizedStackInput) {
line.forEachIndexed { index, crate ->
if (crate.isNotBlank()) stacksOfCrate[index].add(crate[1])
}
}
instructionInput.forEach { line ->
val (amount, from, to) = line.split(" ").filter { it.toIntOrNull() != null }.map { it.toInt() }
val removedItem = mutableListOf<Char>()
for(index in 0 until amount) {
removedItem.add(stacksOfCrate[from - 1].removeFirst())
}
stacksOfCrate[to - 1].addAll(0, removedItem)
}
return stacksOfCrate.map { it.first() }.joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e4d66d8d1f686570355b63fce29c0ecae7a3e915 | 2,383 | aoc-2022-kotlin | Apache License 2.0 |
src/com/kingsleyadio/adventofcode/y2022/day07/Alternative.kt | kingsleyadio | 435,430,807 | false | {"Kotlin": 134666, "JavaScript": 5423} | package com.kingsleyadio.adventofcode.y2022.day07
import com.kingsleyadio.adventofcode.util.readInput
fun main() {
val fsMap = buildFs()
part1(fsMap)
part2(fsMap)
}
fun part1(fs: Map<String, Int>) {
val result = fs.values.filter { it <= 100_000 }.sum()
println(result)
}
fun part2(fs: Map<String, Int>) {
val usedSpace = fs.getValue("")
val availableSpace = 70_000_000 - usedSpace
val neededSpace = 30_000_000 - availableSpace
var toDelete = Int.MAX_VALUE
for ((_, value) in fs) {
if (value in neededSpace..toDelete) toDelete = value
}
println(toDelete)
}
private fun buildFs(): Map<String, Int> {
val map = hashMapOf("" to 0)
var current = ""
readInput(2022, 7).forEachLine { line ->
val split = line.split(" ")
if (split[0] == "$") {
if (split[1] == "cd") {
current = when (split[2]) {
"/" -> ""
".." -> current.substringBeforeLast("/").also { map[it] = map.getValue(it) + map.getValue(current) }
else -> current + "/" + split[2]
}
}
} else if (split[0] == "dir") {
map.getOrPut(current + "/" + split[1]) { 0 }
} else {
map[current] = map.getValue(current) + split[0].toInt()
}
}
while (current != "") {
current = current.substringBeforeLast("/").also { map[it] = map.getValue(it) + map.getValue(current) }
}
return map
}
| 0 | Kotlin | 0 | 1 | 9abda490a7b4e3d9e6113a0d99d4695fcfb36422 | 1,503 | adventofcode | Apache License 2.0 |
src/adventofcode/day07/Day07.kt | bstoney | 574,187,310 | false | {"Kotlin": 27851} | package adventofcode.day07
import adventofcode.AdventOfCodeSolution
import adventofcode.peek
import java.util.Stack
fun main() {
Solution.solve()
}
object Solution : AdventOfCodeSolution<Int>() {
override fun solve() {
solve(7, 95437, 24933642)
}
override fun part1(input: List<String>): Int {
return getDirectories(input)
.filter { it.getSize() <= 100000 }
.peek { debug(it) }
.sumOf { it.getSize() }
}
override fun part2(input: List<String>): Int {
val directorySizes = getDirectories(input)
val availableSpace = 70000000 - directorySizes.maxOf { it.getSize() }
debug("Available space: $availableSpace")
val requiredSpace = 30000000 - availableSpace
debug("Required space: $requiredSpace")
return directorySizes
.asSequence()
.sortedBy { it.getSize() }
.filter { it.getSize() >= requiredSpace }
.peek { debug(it) }
.map { it.getSize() }
.first()
}
private fun getDirectories(input: List<String>): List<Directory> {
val iterator = input.iterator()
val dirs = mutableMapOf<String, Directory>()
val getDir = { path: String, parent: Directory? ->
dirs[path] ?: run {
val dir = Directory(path, parent)
dirs.putIfAbsent(path, dir)
dir
}
}
val currentPath = Stack<Directory>()
val root = getDir("/", null)
currentPath.push(root)
while (iterator.hasNext()) {
with(iterator.next()) {
val currentDir = currentPath.peek()
when {
equals("$ cd /") -> {
currentPath.empty()
currentPath.push(root)
}
equals("$ cd ..") -> {
currentPath.pop()
}
startsWith("$ cd ") -> {
currentPath.push(getDir("${currentDir.name}/${this.substring(5)}", currentDir))
}
equals("$ ls") -> {}
startsWith("dir ") -> {
currentDir.addDir(getDir("${currentDir.name}/${this.substring(4)}", currentDir))
}
else -> {
val (size, file) = this.split(" ", limit = 2)
currentDir.addFile(file, size.toInt())
}
}
}
}
return dirs.values.toList()
}
class Directory(
val name: String,
private val parent: Directory?,
private val dirs: ArrayList<Directory> = arrayListOf(),
private val files: MutableMap<String, Int> = mutableMapOf()
) {
private var size: Int? = null
fun addDir(dir: Directory) {
contentChanged()
dirs.add(dir)
}
fun addFile(name: String, size: Int) {
contentChanged()
files[name] = size
}
fun getSize(): Int {
return size ?: run {
val calculatedSize = dirs.sumOf { it.getSize() } + files.values.sum()
size = calculatedSize
calculatedSize
}
}
private fun contentChanged() {
size = null
parent?.contentChanged()
}
}
}
| 0 | Kotlin | 0 | 0 | 81ac98b533f5057fdf59f08940add73c8d5df190 | 3,480 | fantastic-chainsaw | Apache License 2.0 |
src/main/kotlin/de/tek/adventofcode/y2022/day12/HillClimbingAlgorithm.kt | Thumas | 576,671,911 | false | {"Kotlin": 192328} | package de.tek.adventofcode.y2022.day12
import de.tek.adventofcode.y2022.util.math.Direction
import de.tek.adventofcode.y2022.util.math.Graph
import de.tek.adventofcode.y2022.util.math.Grid
import de.tek.adventofcode.y2022.util.math.Point
import de.tek.adventofcode.y2022.util.readInputLines
class HeightMap(map: Array<Array<Char>>) : Grid<Char, HeightMap.Cell>(map, { position, char -> Cell(position, char) }) {
class Cell(val position: Point, private val mark: Char) {
fun isStartingPosition() = mark == 'S'
fun isGoal() = mark == 'E'
fun getElevation() =
if (isStartingPosition()) {
0
} else if (isGoal()) {
26
} else {
mark - 'a'
}
infix fun isReachableFrom(other: Cell) = this.getElevation() <= other.getElevation() + 1
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Cell) return false
if (position != other.position) return false
return true
}
override fun hashCode(): Int {
return position.hashCode()
}
override fun toString(): String {
return "Cell(position=$position, mark=$mark)"
}
}
fun getLengthOfShortestPath(): Int {
val edges = computeEdges()
val (start, end) = findStartEnd()
val shortestPath = Graph(edges).findShortestPath(start, end)
return shortestPath.size
}
private fun computeEdges(): Set<Pair<Cell, Cell>> {
val edges = mutableSetOf<Pair<Cell, Cell>>()
for (cell in this) {
for (direction in Direction.values()) {
val neighbourPosition = cell.position + direction.toVector()
val neighbour = at(neighbourPosition)
if (neighbour?.isReachableFrom(cell) == true) {
edges.add(Pair(cell, neighbour))
}
}
}
return edges
}
private fun findStartEnd(): Pair<Cell, Cell> {
var start: Cell? = null
var end: Cell? = null
for (cell in this) {
if (cell.isStartingPosition()) start = cell
if (cell.isGoal()) end = cell
if (start != null && end != null) break
}
if (start == null) {
throw IllegalArgumentException("The height map did not contain a start cell.")
} else if (end == null) {
throw IllegalArgumentException("The height map did not contain a goal.")
}
return Pair(start, end)
}
fun getLengthOfShortestPathFromLowestElevation(): Int {
val startEndCombinations = findPairsOfLowestElevationAndGoalCells()
val edges = computeEdges()
val graph = Graph(edges)
return startEndCombinations.map { graph.findShortestPath(it.first, it.second).size }.filter { it > 0 }.min()
}
private fun findPairsOfLowestElevationAndGoalCells(): List<Pair<Cell, Cell>> {
val lowestElevationCells = mutableListOf<Cell>()
var end: Cell? = null
for (cell in this) {
if (cell.getElevation() == 0) {
lowestElevationCells.add(cell)
} else if (cell.isGoal()) {
end = cell
}
}
if (end == null) {
throw IllegalArgumentException("The height map did not contain a goal.")
}
return lowestElevationCells.map { Pair(it, end) }
}
}
fun main() {
val input = readInputLines(HeightMap::class)
fun part1(input: List<String>): Int {
val array = input.map { it.toCharArray().toTypedArray() }.toTypedArray()
return HeightMap(array).getLengthOfShortestPath()
}
fun part2(input: List<String>): Int {
val array = input.map { it.toCharArray().toTypedArray() }.toTypedArray()
return HeightMap(array).getLengthOfShortestPathFromLowestElevation()
}
println("The shortest path has length ${part1(input)}.")
println(
"The fewest steps required to move starting from any square with elevation a to the location that should " +
"get the best signal is ${part2(input)}."
)
} | 0 | Kotlin | 0 | 0 | 551069a21a45690c80c8d96bce3bb095b5982bf0 | 4,254 | advent-of-code-2022 | Apache License 2.0 |
src/aoc2017/kot/Day14.kt | Tandrial | 47,354,790 | false | null | package aoc2017.kot
import toHexString
import java.math.BigInteger
object Day14 {
fun solve(input: String): Pair<Int, Int> {
val hashList = genHashList(input)
val partOne = hashList.sumBy { it.count { it == '1' } }
val hashArray = hashList.map { it.map { (it - '0') }.toIntArray() }.toTypedArray()
var currGroup = 2
// Loop over each Cell skipping assigned cells and assign groups with BFS starting from the current cell
for ((idRow, row) in hashArray.withIndex()) {
for ((idCol, cell) in row.withIndex()) {
if (cell == 1) {
hashArray[idRow][idCol] = currGroup
val queue = mutableListOf(listOf(idRow, idCol, currGroup))
// BFS: If the neighbour is set to 1 it's part of the group and wasn't yet explored
while (queue.isNotEmpty()) {
val (baseX, baseY, group) = queue.removeAt(0)
listOf(Pair(0, -1), Pair(0, 1), Pair(-1, 0), Pair(1, 0)).map { (x, y) -> Pair(baseX + x, baseY + y) }.forEach { (x, y) ->
if (x in (0 until hashArray.size) && y in (0 until hashArray[0].size) && hashArray[x][y] == 1) {
hashArray[x][y] = group
queue.add(listOf(x, y, group))
}
}
}
currGroup++
}
}
}
return Pair(partOne, currGroup - 2)
}
private fun genHashList(seed: String): List<String> = (0..127).map {
val hashIn = "$seed-$it".toCharArray().map { it.toInt() } + listOf(17, 31, 73, 47, 23)
val hash = Day10.partTwo(hashIn, 64).toHexString()
BigInteger(hash, 16).toString(2).padStart(128, '0')
}
}
fun main(args: Array<String>) {
val input = "vbqugkhl"
val (partOne, partTwo) = Day14.solve(input)
println("Part One = $partOne")
println("Part Two = $partTwo")
}
| 0 | Kotlin | 1 | 1 | 9294b2cbbb13944d586449f6a20d49f03391991e | 1,792 | Advent_of_Code | MIT License |
src/main/kotlin/mkuhn/aoc/Day18.kt | mtkuhn | 572,236,871 | false | {"Kotlin": 53161} | package mkuhn.aoc
fun day18part1(input: List<String>): Int {
val cubeField = input.map { Point3D.fromString(it) }.toSet()
return cubeField.countExposedFaces()
}
fun day18part2(input: List<String>): Int {
val cubeField = input.map { Point3D.fromString(it) }.toSet()
val airCubes = cubeField.invertCubes()
return airCubes.minBy { it.x } //a point where know is not in an air bubble
.findJoiningCubes(airCubes) //search for all linked cubes outside of the structure
.let { airCubes subtract it } //subtract those linked cubes from all air cubes, to leave just bubbles
.union(cubeField) //go back to the rock points, but fill in all the bubbles
.countExposedFaces()
}
fun Set<Point3D>.countExposedFaces() = sumOf { 6 - (it.getCardinalNeighbors().toSet() intersect this).size }
fun Point3D.findJoiningCubes(allPoints: Set<Point3D>): Set<Point3D> {
val allFound = mutableSetOf<Point3D>()
var n = listOf(this)
while(n.isNotEmpty()) {
allFound += n
n = n.flatMap { c -> c.getCardinalNeighbors() }.toSet()
.filter { it !in allFound }
.filter { it in allPoints }
}
return allFound
}
fun Set<Point3D>.invertCubes(): Set<Point3D> {
val bounds = this.getBounds(1)
return bounds.first.flatMap { x ->
bounds.second.flatMap { y ->
bounds.third.map { z ->
Point3D(x, y, z)
}
}
}.toSet() subtract this
}
fun Set<Point3D>.getBounds(buffer: Int = 0): Triple<IntRange, IntRange, IntRange> {
val xBounds = minOf { it.x }-buffer .. maxOf { it.x }+buffer
val yBounds = minOf { it.y }-buffer .. maxOf { it.y }+buffer
val zBounds = minOf { it.z }-buffer .. maxOf { it.z }+buffer
return Triple(xBounds, yBounds, zBounds)
}
data class Point3D(val x: Int, val y: Int, val z: Int) {
fun getCardinalNeighbors(): Set<Point3D> =
setOf(
Point3D(x-1, y, z), Point3D(x+1, y, z),
Point3D(x, y-1, z), Point3D(x, y+1, z),
Point3D(x, y, z-1), Point3D(x, y, z+1)
)
companion object {
fun fromString(str: String) = str.split(',')
.map { it.toInt() }
.let { (x, y, z) -> Point3D(x, y, z) }
}
} | 0 | Kotlin | 0 | 1 | 89138e33bb269f8e0ef99a4be2c029065b69bc5c | 2,253 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | pimts | 573,091,164 | false | {"Kotlin": 8145} | fun main() {
fun part1(input: List<String>): Int {
/*
A = X = ROCK = 1
B = Y = PAPER = 2
C = Z = SCISSORS = 3
*/
val finalScoresMap = mapOf(
"AX" to 4, "AY" to 8, "AZ" to 3,
"BX" to 1, "BY" to 5, "BZ" to 9,
"CX" to 7, "CY" to 2, "CZ" to 6,
)
return input.map { it.replace(" ", "") }
.sumOf { finalScoresMap[it] ?: 0 }
}
fun part2(input: List<String>): Int {
/*
A = ROCK = 1
B = PAPER = 2
C = SCISSORS = 3
X = LOSE = 0
Y = DRAW = 3
Z = WIN = 6
*/
val finalScoresMap = mapOf(
"AX" to 3, "AY" to 4, "AZ" to 8,
"BX" to 1, "BY" to 5, "BZ" to 9,
"CX" to 2, "CY" to 6, "CZ" to 7,
)
return input.map { it.replace(" ", "") }
.sumOf { finalScoresMap[it] ?: 0 }
}
// 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 | dc7abb10538bf6ad9950a079bbea315b4fbd011b | 1,236 | aoc-2022-in-kotlin | Apache License 2.0 |
src/day04/Day04.kt | Mini-Stren | 573,128,699 | false | null | package day04
import readInputLines
fun main() {
val day = 4
fun part1(input: List<String>): Int {
return input.elvesAssignments.count { (firstElfAssignment, secondElfAssignment) ->
fullyContainsOneAnother(firstElfAssignment, secondElfAssignment)
}
}
fun part2(input: List<String>): Int {
return input.elvesAssignments.count { (firstElfAssignment, secondElfAssignment) ->
(firstElfAssignment intersect secondElfAssignment).isNotEmpty()
}
}
val testInput = readInputLines("/day%02d/input_test".format(day))
val input = readInputLines("/day%02d/input".format(day))
check(part1(testInput) == 2)
println("part1 answer is ${part1(input)}")
check(part2(testInput) == 4)
println("part2 answer is ${part2(input)}")
}
private val List<String>.elvesAssignments: List<Pair<IntRange, IntRange>>
get() = map { line ->
line.split(",")
.map { it.split("-") }
.map { IntRange(it[0].toInt(), it[1].toInt()) }
.let { it[0] to it[1] }
}
private infix operator fun IntRange.contains(otherRange: IntRange): Boolean {
val intersection = this intersect otherRange
return otherRange.toSet() == intersection
}
private fun fullyContainsOneAnother(firstRange: IntRange, secondRange: IntRange): Boolean {
return firstRange contains secondRange || secondRange contains firstRange
}
| 0 | Kotlin | 0 | 0 | 40cb18c29089783c9b475ba23c0e4861d040e25a | 1,428 | aoc-2022-kotlin | Apache License 2.0 |
src/Day21.kt | Kvest | 573,621,595 | false | {"Kotlin": 87988} | fun main() {
val testInput = readInput("Day21_test")
val testOperations = testInput.toOperations()
check(part1(testOperations) == 152L)
check(part2(testOperations) == 301L)
val input = readInput("Day21")
val operations = input.toOperations()
println(part1(operations))
println(part2(operations))
}
private fun part1(operations: Map<String, MathOperation>): Long = getValue("root", operations)
private const val TARGET_OPERATION = "humn"
private fun part2(operations: Map<String, MathOperation>): Long {
val rootOp = operations.getValue("root")
val operand1Depends = dependsOn(rootOp.operand1, TARGET_OPERATION, operations)
val targetValue = getValue(
name = if (operand1Depends) rootOp.operand2 else rootOp.operand1,
operations = operations
)
return correctToValue(
name = if (operand1Depends) rootOp.operand1 else rootOp.operand2,
targetValue = targetValue,
targetOperationName = TARGET_OPERATION,
operations = operations
)
}
private fun correctToValue(
name: String,
targetValue: Long,
targetOperationName: String,
operations: Map<String, MathOperation>
): Long {
if (name == targetOperationName) {
return targetValue
}
val op = operations.getValue(name)
val operand1Depends = dependsOn(op.operand1, TARGET_OPERATION, operations)
val anotherOperandValue = getValue(
name = if (operand1Depends) op.operand2 else op.operand1,
operations = operations
)
val nextName = if (operand1Depends) op.operand1 else op.operand2
val nextTargetValue = when (op) {
is MathOperation.Divide ->
if (operand1Depends) {
targetValue * anotherOperandValue
} else {
anotherOperandValue / targetValue
}
is MathOperation.Minus ->
if (operand1Depends) {
targetValue + anotherOperandValue
} else {
anotherOperandValue - targetValue
}
is MathOperation.Multiply -> targetValue / anotherOperandValue
is MathOperation.Plus -> targetValue - anotherOperandValue
is MathOperation.Value -> error("Should not be here")
}
return correctToValue(nextName, nextTargetValue, targetOperationName, operations)
}
private fun dependsOn(
operationName: String,
targetDependency: String,
operations: Map<String, MathOperation>
): Boolean {
if (operationName == targetDependency) {
return true
}
return when (val op = operations.getValue(operationName)) {
is MathOperation.Value -> false
else ->
dependsOn(op.operand1, targetDependency, operations) || dependsOn(op.operand2, targetDependency, operations)
}
}
private fun getValue(name: String, operations: Map<String, MathOperation>): Long {
return when (val op = operations.getValue(name)) {
is MathOperation.Divide -> getValue(op.operand1, operations) / getValue(op.operand2, operations)
is MathOperation.Minus -> getValue(op.operand1, operations) - getValue(op.operand2, operations)
is MathOperation.Multiply -> getValue(op.operand1, operations) * getValue(op.operand2, operations)
is MathOperation.Plus -> getValue(op.operand1, operations) + getValue(op.operand2, operations)
is MathOperation.Value -> op.value
}
}
private fun List<String>.toOperations(): Map<String, MathOperation> = this.associate { row ->
val name = row.substringBefore(":")
val operationStr = row.substringAfter(": ")
val operation = when {
operationStr.contains('+') ->
MathOperation.Plus(
operand1 = operationStr.substringBefore(" + "),
operand2 = operationStr.substringAfter(" + ")
)
operationStr.contains('-') ->
MathOperation.Minus(
operand1 = operationStr.substringBefore(" - "),
operand2 = operationStr.substringAfter(" - ")
)
operationStr.contains('/') ->
MathOperation.Divide(
operand1 = operationStr.substringBefore(" / "),
operand2 = operationStr.substringAfter(" / ")
)
operationStr.contains('*') ->
MathOperation.Multiply(
operand1 = operationStr.substringBefore(" * "),
operand2 = operationStr.substringAfter(" * ")
)
else -> MathOperation.Value(operationStr.toLong())
}
name to operation
}
private sealed interface MathOperation {
class Value(val value: Long) : MathOperation
class Plus(val operand1: String, val operand2: String) : MathOperation
class Minus(val operand1: String, val operand2: String) : MathOperation
class Multiply(val operand1: String, val operand2: String) : MathOperation
class Divide(val operand1: String, val operand2: String) : MathOperation
}
private val MathOperation.operand1: String
get() = when (this) {
is MathOperation.Divide -> this.operand1
is MathOperation.Minus -> this.operand1
is MathOperation.Multiply -> this.operand1
is MathOperation.Plus -> this.operand1
is MathOperation.Value -> error("MathOperation.Value doesn't have operands")
}
private val MathOperation.operand2: String
get() = when (this) {
is MathOperation.Divide -> this.operand2
is MathOperation.Minus -> this.operand2
is MathOperation.Multiply -> this.operand2
is MathOperation.Plus -> this.operand2
is MathOperation.Value -> error("MathOperation.Value doesn't have operands")
} | 0 | Kotlin | 0 | 0 | 6409e65c452edd9dd20145766d1e0ea6f07b569a | 5,664 | AOC2022 | Apache License 2.0 |
src/main/kotlin/Day07.kt | robfletcher | 724,814,488 | false | {"Kotlin": 18682} | import Day07.HandType.*
import java.util.Comparator
class Day07 : Puzzle {
override fun test() {
val input = """
32T3K 765
T55J5 684
KK677 28
KTJJT 220
QQQJA 483""".trimIndent()
assert(part1(input.lineSequence()) == 6440)
assert(part2(input.lineSequence()) == 5905)
}
fun handComparator(cardRank: String) = object : Comparator<Hand> {
override fun compare(a: Hand, b: Hand): Int {
var result = a.type.compareTo(b.type)
if (result != 0) return result
var i = 0
while (i < a.cards.length) {
result = a.cards[i].let { cardRank.indexOf(it) }.compareTo(b.cards[i].let { cardRank.indexOf(it) })
if (result != 0) return result
i++
}
return 0
}
}
override fun part1(input: Sequence<String>) =
input
.associate { it.split(' ').let { (cards, bid) -> Hand(cards) to bid.toInt() } }
.toSortedMap(handComparator(CARDS_1))
.values
.foldIndexed(0) { i, sum, bid -> sum + (bid * (i + 1)) }
override fun part2(input: Sequence<String>) =
input
.associate { it.split(' ').let { (cards, bid) -> Hand(cards, true) to bid.toInt() } }
.toSortedMap(handComparator(CARDS_2))
.values
.foldIndexed(0) { i, sum, bid -> sum + (bid * (i + 1)) }
companion object {
const val CARDS_1 = "23456789TJQKA"
const val CARDS_2 = "J23456789TQKA"
}
data class Hand(
val cards: String,
val wildcards: Boolean = false
) {
val type: HandType =
cards
.run {
if (wildcards) {
val mostFrequent = filter { it != 'J' }.groupBy { it }.mapValues { it.value.size }.ifEmpty { mapOf('A' to 5) }.maxBy { it.value }.key
replace('J', mostFrequent)
} else {
this
}
}
.run { associate { c -> c to count { it == c } } }.run {
when {
size == 1 -> FiveOfAKind
size == 2 && values.max() == 4 -> FourOfAKind
size == 2 -> FullHouse
values.max() == 3 -> ThreeOfAKind
values.count { it == 2 } == 2 -> TwoPair
values.max() == 2 -> OnePair
else -> HighCard
}
}
override fun toString(): String {
return "Hand(cards=$cards, type=$type)"
}
}
enum class HandType {
HighCard, OnePair, TwoPair, ThreeOfAKind, FullHouse, FourOfAKind, FiveOfAKind
}
} | 0 | Kotlin | 0 | 0 | cf10b596c00322ea004712e34e6a0793ba1029ed | 2,420 | aoc2023 | The Unlicense |
src/Day05.kt | BionicCa | 574,904,899 | false | {"Kotlin": 20039} | private fun getVerticalStacks(input: List<String>): List<ArrayDeque<Char>> {
val strLen = input.last().length
val stackRows = input.map { line ->
val padLine = line.padEnd(strLen, ' ')
val row = mutableListOf<Char>()
for (i in 1 until strLen step 4) {
val c = padLine[i]
if (c != ' ') row.add(c)
else row.add('x')
}
return@map row
}
// transpose the list from rows to vertical stacks (was read in horizontally)
return transposeList(stackRows)
.map { col ->
col.filter { it != 'x' }
.reversed().toMutableList()
}
.map {
ArrayDeque(it)
}
}
// convert instructions into index values
private fun getInstructions(input: List<String>): List<List<Int>> =
input.map { line ->
line.split("move ", " from ", " to ")
.filter { it.isNotBlank() }
.mapIndexed { i, n ->
// subtract index values to match 0-index lists, but amount to move stays same
n.toInt() - if (i == 0) 0 else 1
}
}
fun main() {
fun part1(input: List<String>): String {
val stackRows = input.takeWhile { it.isNotEmpty() }.dropLast(1)
val stacks = getVerticalStacks(stackRows)
val instructions = getInstructions(input.drop(stackRows.size + 2))
for ((amount, stackFrom, stackTo) in instructions) {
for (index in 1..amount) {
val char = stacks[stackFrom].removeLast()
stacks[stackTo].addLast(char)
}
}
return stacks.map { it.last() }.joinToString("")
}
fun part2(input: List<String>): String {
val stackRows = input.takeWhile { it.isNotEmpty() }.dropLast(1)
val stacks = getVerticalStacks(stackRows)
val instructions = getInstructions(input.drop(stackRows.size + 2))
for ((amount, stackFrom, stackTo) in instructions) {
val charsToAdd = mutableListOf<Char>()
for (index in 1..amount) {
val char = stacks[stackFrom].removeLast()
charsToAdd.add(char)
}
stacks[stackTo].addAll(charsToAdd.reversed())
}
return stacks.map { it.last() }.joinToString("")
}
// val testInput = readInput("Day05_test")
// println(part1(testInput))
// println(part2(testInput))
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ed8bda8067386b6cd86ad9704bda5eac81bf0163 | 2,515 | AdventOfCode2022 | Apache License 2.0 |
src/Day02.kt | hijst | 572,885,261 | false | {"Kotlin": 26466} | fun main() {
fun calculateScore(game: Pair<String, String>): Int =
when (game) {
Pair("A", "X") -> 4
Pair("A", "Y") -> 8
Pair("A", "Z") -> 3
Pair("B", "X") -> 1
Pair("B", "Y") -> 5
Pair("B", "Z") -> 9
Pair("C", "X") -> 7
Pair("C", "Y") -> 2
Pair("C", "Z") -> 6
else -> throw(Error("Unexpected input: $game"))
}
fun Pair<String, String>.transformToOriginalStrategy(): Pair<String, String> =
when (this) {
Pair("A", "X") -> Pair("A", "Z")
Pair("A", "Y") -> Pair("A", "X")
Pair("A", "Z") -> Pair("A", "Y")
Pair("B", "X") -> Pair("B", "X")
Pair("B", "Y") -> Pair("B", "Y")
Pair("B", "Z") -> Pair("B", "Z")
Pair("C", "X") -> Pair("C", "Y")
Pair("C", "Y") -> Pair("C", "Z")
Pair("C", "Z") -> Pair("C", "X")
else -> throw(Error("Unexpected input: $this"))
}
fun part1(input: List<Pair<String, String>>): Int =
input.sumOf { game -> calculateScore(game) }
fun part2(input: List<Pair<String, String>>): Int =
input.sumOf { game -> calculateScore(game.transformToOriginalStrategy()) }
val testInput = readRockPaperScissors("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readRockPaperScissors("Day02_input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2258fd315b8933642964c3ca4848c0658174a0a5 | 1,515 | AoC-2022 | Apache License 2.0 |
src/main/kotlin/com/staricka/adventofcode2023/days/Day7.kt | mathstar | 719,656,133 | false | {"Kotlin": 107115} | package com.staricka.adventofcode2023.days
import com.staricka.adventofcode2023.framework.Day
class Day7: Day {
enum class CardRank {
A, K, Q, J, T, `9`, `8`, `7`, `6`, `5`, `4`, `3`, `2`, `1`
}
enum class CardRankWithJokers {
A, K, Q, T, `9`, `8`, `7`, `6`, `5`, `4`, `3`, `2`, `1`, J
}
enum class HandType {
FIVE_OF_A_KIND, FOUR_OF_A_KIND, FULL_HOUSE, THREE_OF_A_KIND, TWO_PAIR, ONE_PAIR, HIGH_CARD;
companion object {
fun determineType(hand: Hand): HandType {
return determineType(hand.cards.groupBy { it }.map { it.value.size }.sortedDescending())
}
fun determineType(hand: HandWithJokers): HandType {
val counts = hand.cards.groupBy { it }
val jokerCount = counts[CardRankWithJokers.J]?.size ?: 0
var sortedCounts = counts.filter { it.key != CardRankWithJokers.J }.map { it.value.size }.sortedDescending().toMutableList()
if (sortedCounts.size > 0) sortedCounts[0] += jokerCount else sortedCounts = mutableListOf(jokerCount)
return determineType(sortedCounts)
}
private fun determineType(sortedCounts: List<Int>): HandType {
if (sortedCounts[0] == 5) return FIVE_OF_A_KIND
if (sortedCounts[0] == 4) return FOUR_OF_A_KIND
if (sortedCounts[0] == 3 && sortedCounts[1] == 2) return FULL_HOUSE
if (sortedCounts[0] == 3) return THREE_OF_A_KIND
if (sortedCounts[0] == 2 && sortedCounts[1] >= 2) return TWO_PAIR
if (sortedCounts[0] == 2 ) return ONE_PAIR
return HIGH_CARD
}
}
}
data class Hand(val cards: List<CardRank>, val bid: Int): Comparable<Hand> {
override fun compareTo(other: Hand): Int {
return compareBy<Hand>(
{HandType.determineType(it)},
{it.cards[0]},
{it.cards[1]},
{it.cards[2]},
{it.cards[3]},
{it.cards[4]},
).compare(this, other)
}
companion object {
fun fromString(input: String): Hand {
val split = input.split(" ")
return Hand(
split[0].toCharArray().map { CardRank.valueOf(it.toString()) },
split[1].toInt()
)
}
}
}
data class HandWithJokers(val cards: List<CardRankWithJokers>, val bid: Int): Comparable<HandWithJokers> {
override fun compareTo(other: HandWithJokers): Int {
return compareBy<HandWithJokers>(
{HandType.determineType(it)},
{it.cards[0]},
{it.cards[1]},
{it.cards[2]},
{it.cards[3]},
{it.cards[4]},
).compare(this, other)
}
override fun toString(): String {
return cards.joinToString { it.name }
}
companion object {
fun fromString(input: String): HandWithJokers {
val split = input.split(" ")
return HandWithJokers(
split[0].toCharArray().map { CardRankWithJokers.valueOf(it.toString()) },
split[1].toInt()
)
}
}
}
override fun part1(input: String): Int {
val hands = input.lines().filter { it.isNotBlank() }
.map { Hand.fromString(it) }
.sortedDescending()
return hands.withIndex().sumOf { (i,hand) -> (i+1)*hand.bid }
}
override fun part2(input: String): Int {
val hands = input.lines().filter { it.isNotBlank() }
.map { HandWithJokers.fromString(it) }
.sortedDescending()
return hands.withIndex().sumOf { (i,hand) -> (i+1)*hand.bid }
}
} | 0 | Kotlin | 0 | 0 | 8c1e3424bb5d58f6f590bf96335e4d8d89ae9ffa | 3,906 | adventOfCode2023 | MIT License |
src/main/kotlin/se/saidaspen/aoc/aoc2016/Day11.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2016
import se.saidaspen.aoc.util.Day
import se.saidaspen.aoc.util.bfs
import se.saidaspen.aoc.util.pairWise
fun main() = Day11.run()
object Day11 : Day(2016, 11) {
private val itemsLocs = input.lines().map {
it.substring(it.indexOf("contains") + 8)
.split(",|and".toRegex())
.map { e -> e.replace(" a ", "").replace(" and", "").replace(".", "").trim() }
.filter { e -> e != "nothing relevant" }
.filter { e -> e.isNotEmpty() }
.map { e -> e.split(" ")[0][0].uppercase() + e.split(" ")[0][1] + e.split(" ")[1][0].uppercase() }
.toSet()
}.toList()
private val next: (State) -> Iterable<State> = { (floor, items) ->
val nextStates = mutableListOf<Triple<Boolean, MutableList<String>, State>>()
val pairWiseItems = items[floor].pairWise().map { mutableListOf(it.first, it.second) }
val singleItems = items[floor].map { mutableListOf(it) }
val possibleMoves = pairWiseItems.union(singleItems)
val possibleFloors = mutableListOf(floor - 1, floor + 1).filter { it in 0..3 }
for (move in possibleMoves) {
for (nextFloor in possibleFloors) {
val nextItems = mutableListOf(
items[0].toMutableSet(),
items[1].toMutableSet(),
items[2].toMutableSet(),
items[3].toMutableSet()
)
nextItems[floor].removeAll(move.toSet())
nextItems[nextFloor].addAll(move)
val nextState = State(nextFloor, nextItems)
if (nextState.isValid()) {
nextStates.add(Triple(nextFloor > floor, move, nextState))
}
}
}
val hasMoveTwoUp = (nextStates.any { it.first && it.second.size == 2 })
val hasMoveOneDown = (nextStates.any { !it.first && it.second.size == 1 })
nextStates
.filter { it.third.emptyFloorOptimization(items) } // If floors below are empty, don't move stuff back down to them
.filter { !hasMoveTwoUp || (!it.first || it.second.size == 2) } // If can move 2 up, then don't bother moving one up
.filter { !hasMoveOneDown || (it.first || it.second.size == 1) } // If can move 1 down, then don't bother moving two down
.map { it.third }
}
data class State(val floor: Int, val items: List<Set<String>>) {
fun isValid(): Boolean {
for (its in items) {
val chips = its.filter { it.endsWith("M") }
if (chips.isNotEmpty() && its.any { it.endsWith("G") })
if (!chips.all { its.contains(it.substring(0, 2) + "G") }) {
return false
}
}
return true
}
fun emptyFloorOptimization(itemsPrev : List<Set<String>>): Boolean {
val firstNonEmptyFloorPrev = itemsPrev.withIndex().first { it.value.isNotEmpty() }.index
val firstNonEmptyFloorNext = items.withIndex().first { it.value.isNotEmpty() }.index
if (firstNonEmptyFloorNext < firstNonEmptyFloorPrev) {
return false
}
return true
}
}
override fun part1(): Any {
val isEnd: (State) -> Boolean = { it.items[3].size == itemsLocs.flatten().size } // End state is that all items are at level 3
val bfs = bfs(State(0, itemsLocs), isEnd, next)
return if (bfs.first != null) bfs.second else "N/A"
}
override fun part2(): Any {
val extendedItems = itemsLocs.toMutableList()
val itemsF1 = extendedItems[0].toMutableSet()
itemsF1.addAll(setOf("ElG", "ElM", "DiG", "DiM"))
extendedItems[0] = itemsF1
val isEnd: (State) -> Boolean = { it.items[3].size == extendedItems.flatten().size } // End state is that all items are at level 3
val bfs = bfs(State(0, extendedItems), isEnd, next)
return if (bfs.first != null) bfs.second else "N/A"
}
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 4,077 | adventofkotlin | MIT License |
src/main/kotlin/dev/paulshields/aoc/day1/ReportRepair.kt | Pkshields | 318,658,287 | false | null | package dev.paulshields.aoc.day1
import dev.paulshields.aoc.common.readFileAsString
fun main() {
println(" ** Day 1: Report Repair ** \n")
val expenseReport = readFileAsString("/day1/ExpenseReport.txt")
.lines()
.mapNotNull { it.toIntOrNull() }
val validPair = findSum(expenseReport, 2020)
println("Found values ${validPair.first} and ${validPair.second} equal 2020!")
val solution = validPair.first * validPair.second
println("The first solution then, by multiplying these together, is $solution.")
val validTriple = findSumOfThree(expenseReport, 2020)
println("Also found values ${validTriple.first}, ${validTriple.second} and ${validTriple.third} equal 2020!")
val solutionTwo = validTriple.first * validTriple.second * validTriple.third
println("The second solution then, by multiplying these together, is $solutionTwo.")
}
fun findSum(possibleValues: List<Int>, result: Int): Pair<Int, Int> {
val sortedPossibleValues = possibleValues.sorted()
return sortedPossibleValues
.mapIndexedNotNull { index, possibleValueOne ->
sortedPossibleValues
.drop(index)
.dropWhile { possibleValueOne + it != result }
.take(1)
.map { Pair(possibleValueOne, it) }
.firstOrNull()
}.first()
}
fun findSumOfThree(possibleValues: List<Int>, result: Int): Triple<Int, Int, Int> {
val sortedPossibleValues = possibleValues.sorted()
return sortedPossibleValues
.mapIndexedNotNull { firstIndex, possibleValueOne ->
sortedPossibleValues
.drop(firstIndex)
.mapIndexedNotNull { secondIndex, possibleValueTwo ->
sortedPossibleValues
.drop(secondIndex)
.dropWhile { possibleValueOne + possibleValueTwo + it != result }
.take(1)
.map { Triple(possibleValueOne, possibleValueTwo, it) }
.firstOrNull()
}.firstOrNull()
}.first()
} | 0 | Kotlin | 0 | 0 | a7bd42ee17fed44766cfdeb04d41459becd95803 | 2,107 | AdventOfCode2020 | MIT License |
src/Day08.kt | xNakero | 572,621,673 | false | {"Kotlin": 23869} | object Day08 {
fun part1() = parseInput().filterTreesWithVisibility().count()
fun part2() = parseInput().scenicScores().max()
private fun parseInput(): Forest = readInput("day08")
.let {
Forest(it[0].length, it.joinToString("").chunked(1).map { e -> e.toInt() })
}
}
data class Forest(val width: Int, val trees: Trees) {
fun filterTreesWithVisibility() =
trees.filterIndexed { index, _ ->
isSideVisible(index, treesToTheLeft(index)) ||
isSideVisible(index, treesToTheRight(index)) ||
isSideVisible(index, treesAbove(index)) ||
isSideVisible(index, treesBelow(index))
}
fun scenicScores() =
trees.mapIndexed { index, tree ->
sideScenicScore(tree, treesToTheLeft(index).reversed()) *
sideScenicScore(tree, treesToTheRight(index)) *
sideScenicScore(tree, treesAbove(index).reversed()) *
sideScenicScore(tree, treesBelow(index))
}
private fun isSideVisible(index: Int, sideTrees: Trees) = sideTrees.none { it >= trees[index] }
private fun sideScenicScore(tree: Int, sideTrees: Trees) = sideTrees
.indexOfFirst { it >= tree }
.let { if (it == -1) sideTrees.size else it + 1 }
private fun treesToTheLeft(index: Int) = trees.subList(index - (index % width), index)
private fun treesToTheRight(index: Int) = trees.subList(index + 1, index + (width - index % width))
private fun treesAbove(index: Int) = trees.filterIndexed { i, _ -> i % width == index % width && i < index }
private fun treesBelow(index: Int) = trees.filterIndexed { i, _ -> i % width == index % width && i > index }
}
private typealias Trees = List<Int>
fun main() {
println(Day08.part1())
println(Day08.part2())
} | 0 | Kotlin | 0 | 0 | c3eff4f4c52ded907f2af6352dd7b3532a2da8c5 | 1,860 | advent-of-code-2022 | Apache License 2.0 |
src/Day14.kt | ked4ma | 573,017,240 | false | {"Kotlin": 51348} | import kotlin.math.max
import kotlin.math.min
/**
* [Day14](https://adventofcode.com/2022/day/14)
*/
private class Day14 {
data class Point(val x: Int, val y: Int)
}
fun main() {
fun toPathList(input: List<String>): List<List<Day14.Point>> = input.map { line ->
line.split(" -> ").map {
it.split(",").let { (x, y) -> Day14.Point(x.toInt(), y.toInt()) }
}
}
fun initMatrix(pathList: List<List<Day14.Point>>, minX: Int, maxX: Int, maxY: Int): Array<Array<Char>> {
val baseX = min(500, minX)
val matrix = Array(maxY + 1) { Array(maxX - baseX + 1) { '.' } }
pathList.forEach { path ->
path.zipWithNext { a, b ->
for (x in min(a.x, b.x)..max(a.x, b.x)) {
matrix[a.y][x - baseX] = '#'
}
for (y in min(a.y, b.y)..max(a.y, b.y)) {
matrix[y][a.x - baseX] = '#'
}
}
}
return matrix
}
fun fall(matrix: Array<Array<Char>>, minX: Int, maxX: Int, maxY: Int): Boolean {
val baseX = min(minX, 500)
var x = 500
var y = 0
while (true) {
if (y >= maxY) { // down
return false
} else if (matrix[y + 1][x - baseX] == '.') {
y++
} else if (x == minX) { // left-down
return false
} else if (matrix[y + 1][x - baseX - 1] == '.') {
x--
y++
} else if (x == maxX) { // right-down
return false
} else if (matrix[y + 1][x - baseX + 1] == '.') {
x++
y++
} else {
matrix[y][x - baseX] = 'o'
return true
}
}
}
fun part1(input: List<String>): Int {
val pathList = toPathList(input)
val (minX, maxX) = pathList.flatMap { it.map(Day14.Point::x) }.let {
it.min() to it.max()
}
val maxY = pathList.flatMap { it.map(Day14.Point::y) }.max()
val matrix = initMatrix(pathList, minX, maxX, maxY)
var count = 0
do {
val isRest = fall(matrix, minX, maxX, maxY)
count++
} while (isRest)
return count - 1
}
fun part2(input: List<String>): Int {
val pathList = toPathList(input)
val maxY = pathList.flatMap { it.map(Day14.Point::y) }.max() + 2
val (minX, maxX) = 0 to 1000
val matrix = initMatrix(pathList + listOf(listOf(
Day14.Point(minX, maxY), Day14.Point(maxX, maxY)
)), minX, maxX, maxY)
val baseX = min(minX, 500)
var count = 0
while (matrix[0][500 - baseX] == '.') {
fall(matrix, minX, maxX, maxY)
count++
}
return count
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14")
println(part1(input))
println(part2(input))
} | 1 | Kotlin | 0 | 0 | 6d4794d75b33c4ca7e83e45a85823e828c833c62 | 3,137 | aoc-in-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/dev/bogwalk/batch9/Problem94.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch9
import java.math.BigDecimal
import java.math.MathContext
import java.math.RoundingMode
/**
* Problem 94: Almost Equilateral Triangles
*
* https://projecteuler.net/problem=94
*
* Goal: Find the sum of the perimeters of all almost equilateral triangles with integral side
* lengths and integral areas and whose perimeters do not exceed N.
*
* Constraints: 15 <= N <= 1e18
*
* Almost Equilateral Triangle: A triangle that has 2 equal sides, with the third unique side
* differing by no more than 1 unit.
*
* e.g.: N = 16
* sum = 16 -> {(5, 5, 6)}
* N = 51
* sum = 66 -> {(5, 5, 6), (17, 17, 16)}
*/
class AlmostEquilateralTriangles {
/**
* Solution takes advantage of the observed pattern that all almost equilateral triangles
* alternate in having the unique side being 1 unit greater or less than the equal sides.
*
* Area of an almost equilateral triangles found using Heron's formula:
*
* sp = (a + b + c) / 2
* area = sqrt(sp * (sp - a) * (sp - b) * (sp - c))
*
* substitute a for all sides, e.g. if distinct side expected to be 1 unit greater:
* sp = (3a + 1) / 2
* area = sqrt(sp * (sp - a)^2 * (sp - a - 1))
*
* Note that BigDecimal is necessary to handle issues with large Doubles when N > 1e6.
*
* SPEED (WORSE) 9.99ms for N = 1e6
* 65.26s for N = 1e7
*/
fun perimeterSumOfAlmostEquilaterals(n: Long): Long {
var sum = 0L
var side = 5 // smallest valid triangle (5, 5, 6)
var validPerimeter = 16L
var toggle = -1 // side 5 used +1
while (validPerimeter <= n) {
sum += validPerimeter
val perimeter = 3L * ++side + toggle
val semiP = BigDecimal(perimeter / 2.0)
val a = side.toBigDecimal()
val inner = semiP * (semiP - a) * (semiP - a) * (semiP - (a + toggle.toBigDecimal()))
val area = inner.sqrt(MathContext(20, RoundingMode.HALF_UP))
validPerimeter = if (area * area == inner) {
toggle *= -1
perimeter
} else 0
}
return sum
}
/**
* Solution uses the observed pattern as above, as well as a sequential pattern that forms
* the next term based on the previous 2 valid triangle sides:
*
* {(5, +1), (17, -1), (65, +1), (241, -1), ...}
* when next unique side expected to be greater ->
* side_i = 4 * side_{i-1} - side_{i-2} + 2
* when next unique side expected to be smaller ->
* side_i = 4 * side_{i-1} - side_{i-2} - 2
*
* SPEED (BETTER) 2.6e+04ns for N = 1e6
* 4.3e+04ns for N = 1e7
*/
fun perimeterSumOfSequence(n: Long): Long {
var sum = 0L
val validSides = longArrayOf(1, 5) // smallest almost equilateral triangle (5, 5, 6)
var validPerimeter = 16L
var toggle = -1 // first triangle was +1
while (validPerimeter <= n) {
sum += validPerimeter
val nextValid = 4 * validSides[1] - validSides[0] + (toggle * 2)
validPerimeter = 3 * nextValid + toggle
toggle *= -1
validSides[0] = validSides[1]
validSides[1] = nextValid
}
return sum
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 3,398 | project-euler-kotlin | MIT License |
src/day18/Code.kt | fcolasuonno | 162,470,286 | false | null | package day18
import java.io.File
private val Coord.neighbours: List<Coord>
get() = listOf(
(first - 1) to (second - 1),
(first - 1) to (second),
(first - 1) to (second + 1),
(first) to (second - 1),
(first) to (second + 1),
(first + 1) to (second - 1),
(first + 1) to (second),
(first + 1) to (second + 1)
)
fun main(args: Array<String>) {
val name = if (false) "test.txt" else "input.txt"
val dir = ::main::class.java.`package`.name
val input = File("src/$dir/$name").readLines()
val parsed = parse(input)
println("Part 1 = ${part1(parsed, 100)}")
println("Part 2 = ${part2(parsed, 100)}")
}
typealias Coord = Pair<Int, Int>
fun parse(input: List<String>) = input.mapIndexed { y, s ->
s.withIndex().filter { it.value == '#' }.map { Coord(it.index, y) }
}.requireNoNulls().flatten().toSet() to input.size
fun part1(input: Pair<Set<Coord>, Int>, steps: Int): Any? =
generateSequence(input.first) { current: Set<Coord> ->
val keepOn = current.filter {
val n = it.neighbours
val on = current.count { it in n }
on == 2 || on == 3
}
val turnOn = current.map { it.neighbours }.flatten().distinct()
.filter { it.first in 0 until input.second && it.second in 0 until input.second && it.neighbours.count { it in current } == 3 }
(keepOn + turnOn).toSet()
}.drop(steps).first().size
fun part2(input: Pair<Set<Coord>, Int>, steps: Int): Any? = generateSequence(input.first) { current: Set<Coord> ->
val keepOn = current.filter {
val n = it.neighbours
val on = current.count { it in n }
on == 2 || on == 3
}
val turnOn = current.map { it.neighbours }.flatten().distinct()
.filter { it.first in 0 until input.second && it.second in 0 until input.second && it.neighbours.count { it in current } == 3 }
val next = keepOn + turnOn + listOf(
Coord(0, 0),
Coord(0, input.second - 1),
Coord(input.second - 1, 0),
Coord(input.second - 1, input.second - 1)
)
next.toSet()
}.drop(steps).first().size
| 0 | Kotlin | 0 | 0 | 24f54bf7be4b5d2a91a82a6998f633f353b2afb6 | 2,162 | AOC2015 | MIT License |
src/day4/Day04_B.kt | HGilman | 572,891,570 | false | {"Kotlin": 109639, "C++": 5375, "Python": 400} | package day4
import readInput
fun main() {
val testInput = readInput("day4/Day04_test")
check(Day4B.part1(testInput) == 2)
val input = readInput("day4/Day04")
println(Day4B.part1(input))
println(Day4B.part2(input))
}
object Day4B {
fun part1(input: List<String>) = getState(input).count { state ->
state == RangesRelativeState.ONE_CONTAINS_OTHER
}
fun part2(input: List<String>) = getState(input).count { state ->
state == RangesRelativeState.ONE_CONTAINS_OTHER || state == RangesRelativeState.PART_INTERSECTION
}
private fun getState(input: List<String>): List<RangesRelativeState> {
return input.map { it.split(',') }.map { (a: String, b: String) ->
val (a1, a2) = a.split('-').map { it.toInt() }
val (b1, b2) = b.split('-').map { it.toInt() }
getRelativeState(a1..a2, b1..b2)
}
}
enum class RangesRelativeState {
NO_INTERSECTION,
PART_INTERSECTION,
ONE_CONTAINS_OTHER
}
private fun getRelativeState(f: IntRange, s: IntRange): RangesRelativeState {
return if (f.last < s.first || s.last < f.first) {
RangesRelativeState.NO_INTERSECTION
} else if ((f.first >= s.first && f.last <= s.last) ||
(s.first >= f.first && s.last <= f.last)) {
RangesRelativeState.ONE_CONTAINS_OTHER
} else {
RangesRelativeState.PART_INTERSECTION
}
}
}
| 0 | Kotlin | 0 | 1 | d05a53f84cb74bbb6136f9baf3711af16004ed12 | 1,473 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | kenyee | 573,186,108 | false | {"Kotlin": 57550} |
fun main() { // ktlint-disable filename
val winningRoundValue = 6
val tieRoundValue = 3
val elfShapeValue = mapOf(
'A' to 1, // rock
'B' to 2, // paper
'C' to 3 // scissors
)
val myShapeValue = mapOf(
'X' to 1,
'Y' to 2,
'Z' to 3
)
val winValue = mapOf( // gets object that wins from specified object
3 to 1,
1 to 2,
2 to 3
)
val loseValue = mapOf( // gets object that wins from specified object
1 to 3,
2 to 1,
3 to 2
)
fun winScore(elfShape: Char, myShape: Char): Int {
val elfObject = elfShapeValue[elfShape]!!
val myObject = myShapeValue[myShape]!!
if (elfObject == myObject) return myObject + tieRoundValue
val myWin = (myObject == 1 && elfObject == 3) ||
(myObject == 2 && elfObject == 1) ||
(myObject == 3 && elfObject == 2)
return if (myWin) {
myObject + winningRoundValue
} else myObject
}
fun part1(input: List<String>): Int {
val score = input.sumOf { line ->
winScore(line[0], line[2])
}
return score
}
fun windrawloseScore(elfShape: Char, myShape: Char): Int {
val elfObject = elfShapeValue[elfShape]!!
return when (myShape) {
'X' -> { // lose
loseValue[elfObject]!! + 0
}
'Y' -> { // tie
elfObject + tieRoundValue
}
'Z' -> { // win
winValue[elfObject]!! + winningRoundValue
}
else -> 0
}
}
fun part2(input: List<String>): Int {
val score = input.sumOf { line ->
windrawloseScore(line[0], line[2])
}
return score
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
println("test result score: ${part1(testInput)}")
check(part1(testInput) == 15)
println("test result draw/win/lose score is: ${part2(testInput)}")
check(part2(testInput) == 12)
val input = readInput("Day02_input")
println("Score is: ${part1(input)}")
println("draw/win/lose score is: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 814f08b314ae0cbf8e5ae842a8ba82ca2171809d | 2,265 | KotlinAdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/be/twofold/aoc2021/Day04.kt | jandk | 433,510,612 | false | {"Kotlin": 10227} | package be.twofold.aoc2021
object Day04 {
fun part1(boards: List<Board>, inputs: IntArray): Int {
for (input in inputs) {
for (board in boards) {
val mark = board.mark(input)
if (mark != -1) {
return mark
}
}
}
return 0
}
fun part2(boards: List<Board>, inputs: IntArray): Int {
val allBoards = boards.toMutableList()
for (input in inputs) {
for (board in allBoards.toList()) {
val mark = board.mark(input)
if (mark != -1) {
if (allBoards.size == 1) {
return mark
}
allBoards.remove(board)
}
}
}
return 0
}
class Board(private val board: IntArray) {
fun get(x: Int, y: Int) = board[index(x, y)]
fun mark(n: Int): Int {
for (y in (0 until 5)) {
for (x in (0 until 5)) {
val index = index(x, y)
if (board[index] == n) {
board[index] = -1
return checkBingo(x, y, n)
}
}
}
return -1
}
private fun checkBingo(x: Int, y: Int, n: Int): Int {
if (checkRow(y) || checkColumn(x)) {
return board.filter { it > 0 }.sum() * n
}
return -1
}
private fun checkRow(y: Int) = (0 until 5).all { board[index(it, y)] == -1 }
private fun checkColumn(x: Int) = (0 until 5).all { board[index(x, it)] == -1 }
private fun index(x: Int, y: Int) = y * 5 + x
}
}
fun main() {
val input = Util.readFile("/day04.txt")
val inputs = input[0]
.split(',')
.map { it.toInt() }
.toIntArray()
val boards = input.asSequence()
.drop(2)
.filter { it.isNotEmpty() }
.map { s -> s.trim().split(Regex("\\s+")).map { it.toInt() } }
.chunked(5)
.map { Day04.Board(it.flatten().toIntArray()) }
.toList()
println("Part 1: ${Day04.part1(boards, inputs)}")
println("Part 2: ${Day04.part2(boards, inputs)}")
}
| 0 | Kotlin | 0 | 0 | 2408fb594d6ce7eeb2098bc2e38d8fa2b90f39c3 | 2,280 | aoc2021 | MIT License |
src/Day08.kt | mkulak | 573,910,880 | false | {"Kotlin": 14860} | fun main() {
fun part1(input: List<String>): Int {
val originalData = input.map { line -> line.map { it.code - '0'.code }.toIntArray() }
val visible = HashSet<Int>()
val width = originalData[0].size
val height = originalData.size
var data = originalData.map { it.clone() }
fun check(i: Int, j: Int, di: Int, dj: Int) {
val prev = data[i + di][j + dj]
if (data[i][j] > prev) {
visible += i * width + j
} else {
data[i][j] = prev
}
}
(1..(height - 2)).forEach { i ->
(1..(width - 2)).forEach { j ->
check(i, j, -1, 0)
}
}
data = originalData.map { it.clone() }
(1..(width - 2)).forEach { j ->
(1..(height - 2)).forEach { i ->
check(i, j, 0, -1)
}
}
data = originalData.map { it.clone() }
((height - 2) downTo 1).forEach { i ->
(1..(width - 2)).forEach { j ->
check(i, j, 1, 0)
}
}
data = originalData.map { it.clone() }
((width - 2) downTo 1).forEach { j ->
(1..(height - 2)).forEach { i ->
check(i, j, 0, 1)
}
}
return visible.size + height * 2 + width * 2 - 4
}
fun part2(input: List<String>): Long {
val originalData = input.map { line -> line.map { it.code - '0'.code }.toIntArray() }
val width = originalData[0].size
val height = originalData.size
fun getScenicScore(i: Int, j: Int): Long {
var upCount = 0L
for (y in (i - 1) downTo 0) {
upCount++
if (originalData[y][j] >= originalData[i][j]) break
}
var downCount = 0L
for (y in (i + 1)..(height - 1)) {
downCount++
if (originalData[y][j] >= originalData[i][j]) break
}
var leftCount = 0L
for (x in (j - 1) downTo 0) {
leftCount++
if (originalData[i][x] >= originalData[i][j]) break
}
var rightCount = 0L
for (x in (j + 1)..(width - 1)) {
rightCount++
if (originalData[i][x] >= originalData[i][j]) break
}
return upCount * downCount * leftCount * rightCount
}
return (1..(height - 2)).flatMap { i -> (1..(width - 2)).map { j -> i to j } }
.maxOf { (i, j) -> getScenicScore(i, j) }
}
val input = readInput("Day08")
println(part1(input)) // 1533
println(part2(input)) // 345744
}
| 0 | Kotlin | 0 | 0 | 3b4e9b32df24d8b379c60ddc3c007d4be3f17d28 | 2,699 | AdventOfKo2022 | Apache License 2.0 |
src/Day09.kt | rweekers | 573,305,041 | false | {"Kotlin": 38747} | import kotlin.math.sign
fun main() {
fun part1(headSteps: List<Point>): Int {
return determineTailSteps(headSteps).distinct().size
}
fun part2(headSteps: List<Point>): Int {
return (1..9).fold(headSteps) { acc, _ ->
determineTailSteps(acc)
}.distinct().size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
val testStepInstructions = parseStepInstructions(testInput)
val testHeadSteps = determineHeadSteps(testStepInstructions)
val testInputGold = readInput("Day09_test_gold")
val testStepInstructionsGold = parseStepInstructions(testInputGold)
val testHeadStepsGold = determineHeadSteps(testStepInstructionsGold)
check(part1(testHeadSteps) == 13)
check(part2(testHeadSteps) == 1)
check(part2(testHeadStepsGold) == 36)
val input = readInput("Day09")
val stepInstructions = parseStepInstructions(input)
val headSteps = determineHeadSteps(stepInstructions)
println(part1(headSteps))
println(part2(headSteps))
}
private fun determineTailSteps(headSteps: List<Point>): List<Point> {
val tailSteps = mutableListOf(Point(0, 0))
headSteps.forEach {
val lastTail = tailSteps.last()
if (!lastTail.touches(it)) {
tailSteps.add(lastTail.moveTowards(it))
}
}
return tailSteps
}
private fun parseStepInstructions(testInput: List<String>) = testInput.map {
val instructionString = it.split(" ")
StepInstruction(instructionString[0], instructionString[1].toInt())
}
private fun determineHeadSteps(instructions: List<StepInstruction>): List<Point> {
val init = mutableListOf(Point(0, 0))
val headSteps = instructions.fold(init) { acc, instruction ->
acc.addAll(acc.last().step(instruction))
acc
}
return headSteps
}
private data class StepInstruction(val direction: String, val steps: Int)
private fun Point.step(stepInstruction: StepInstruction): List<Point> {
return when (stepInstruction.direction) {
"U" -> (0 until stepInstruction.steps).fold(mutableListOf()) { acc, _ ->
val p = acc.lastOrNull() ?: this
acc.add(p.copy(y = p.y - 1))
acc
}
"D" -> (0 until stepInstruction.steps).fold(mutableListOf()) { acc, _ ->
val p = acc.lastOrNull() ?: this
acc.add(p.copy(y = p.y + 1))
acc
}
"L" -> (0 until stepInstruction.steps).fold(mutableListOf()) { acc, _ ->
val p = acc.lastOrNull() ?: this
acc.add(p.copy(x = p.x - 1))
acc
}
"R" -> (0 until stepInstruction.steps).fold(mutableListOf()) { acc, _ ->
val p = acc.lastOrNull() ?: this
acc.add(p.copy(x = p.x + 1))
acc
}
else -> throw IllegalArgumentException("Direction ${stepInstruction.direction} not known")
}
}
private fun Point.moveTowards(other: Point): Point =
Point(
(other.x - x).sign + x,
(other.y - y).sign + y
) | 0 | Kotlin | 0 | 1 | 276eae0afbc4fd9da596466e06866ae8a66c1807 | 3,083 | adventofcode-2022 | Apache License 2.0 |
src/main/kotlin/day11/part2/Part2.kt | bagguley | 329,976,670 | false | null | package day11.part2
import day11.data
fun main() {
var seats = data.map { it.toCharArray() }
while (true) {
val x = process2(seats)
if (compare2(x, seats)) break
seats = x
}
val z = seats.map { it.count { it == '#' } }.sum()
println(z)
}
fun process2(seats: List<CharArray>): List<CharArray> {
val width = seats.first().size
val height = seats.size
val result = mutableListOf<CharArray>()
seats.forEach { result.add(CharArray(width){'.'}) }
for (y in 0 until height) {
for (x in 0 until width) {
result[y][x] = newState2(seats, x, y)
}
}
return result
}
fun newState2(seats: List<CharArray>, x: Int, y: Int): Char {
val width = seats.first().size
val height = seats.size
val d = squaresToCheck2(seats, x, y, width, height)
return when (val seat = seats[y][x]) {
'L' -> if (d == 0) '#' else seat
'#' -> if (d >= 5) 'L' else seat
else -> seat
}
}
fun compare2(seats1: List<CharArray>, seats2: List<CharArray>): Boolean {
return seats1.zip(seats2).all{ it.first.contentEquals(it.second) }
}
fun squaresToCheck2(seats: List<CharArray>, startx: Int, starty: Int, width:Int, height: Int): Int{
var result = 0
result += first(seats, line(startx, starty, width, height, -1, -1))
result += first(seats, line(startx, starty, width, height, -1, 0))
result += first(seats, line(startx, starty, width, height, -1, 1))
result += first(seats, line(startx, starty, width, height, 0, -1))
result += first(seats, line(startx, starty, width, height, 0, 1))
result += first(seats, line(startx, starty, width, height, 1, -1))
result += first(seats, line(startx, starty, width, height, 1, 0))
result += first(seats, line(startx, starty, width, height, 1, 1))
return result
}
fun first(seats: List<CharArray>, sight: List<Pair<Int,Int>>): Int {
return if (sight.map{seats[it.second][it.first]}.find{it != '.'} == '#') 1 else 0
}
fun line(startx: Int, starty: Int, width:Int, height: Int, dx: Int, dy:Int): List<Pair<Int,Int>> {
val result = mutableListOf<Pair<Int,Int>>()
var x = startx + dx
var y = starty + dy
while (x in 0 until width && y in 0 until height) {
result.add(Pair(x, y))
x += dx
y += dy
}
return result
} | 0 | Kotlin | 0 | 0 | 6afa1b890924e9459f37c604b4b67a8f2e95c6f2 | 2,348 | adventofcode2020 | MIT License |
src/Day07.kt | ricardorlg-yml | 573,098,872 | false | {"Kotlin": 38331} | class Directory(
val name: String,
val parent: Directory? = null,
private val isDirectory: Boolean = true,
private val fileSize: Int = 0,
val subDirectories: MutableMap<String, Directory> = mutableMapOf(),
) {
val size: Int by lazy {
fileSize + subDirectories.values.sumOf { it.size }
}
fun findDirectories(predicate: (Directory) -> Boolean): List<Int> {
val stack = ArrayDeque<Directory>().apply { add(this@Directory) }
val response = mutableListOf<Int>()
while (stack.isNotEmpty()) {
val node = stack.removeFirst()
stack.addAll(node.subDirectories.values)
if (node.isDirectory && predicate(node)) response.add(node.size)
}
return response
}
override fun toString(): String {
return "${if (isDirectory) "Directory" else "File"} $name, size: ${if (isDirectory) size else fileSize}"
}
}
fun main() {
val totalSize = 70_000_000
val minSpaceSize = 30_000_000
fun parseProgram(lines: List<String>): Directory {
val root = Directory("/")
//assume that we start from root
var currentNode: Directory = root
for (line in lines) {
when {
line == "$ ls" -> continue
line == "$ cd /" -> currentNode = root
line == "$ cd .." -> currentNode = currentNode.parent!!
line.startsWith("$ cd") -> {
val name = line.substringAfterLast(" ")
currentNode = currentNode.subDirectories[name]!!
}
line.startsWith("dir") -> {
val name = line.substringAfterLast(" ")
currentNode.subDirectories[name] = Directory(name = name, parent = currentNode)
}
else -> {
val name = line.substringAfterLast(" ")
val size = line.substringBeforeLast(" ").toInt()
currentNode.subDirectories[name] =
Directory(name = name, parent = currentNode, isDirectory = false, fileSize = size)
}
}
}
return root
}
fun part1(input: List<String>): Int {
val rootDirectory = parseProgram(input)
return rootDirectory.findDirectories { directory -> directory.size <= 100_000 }.sum()
}
fun part2(input: List<String>): Int {
val rootDirectory = parseProgram(input)
val totalUsedSize = rootDirectory.size
val currentUnusedSpaceSize = totalSize - totalUsedSize
val neededSpace = minSpaceSize - currentUnusedSpaceSize
return rootDirectory.findDirectories { directory -> directory.size >= neededSpace }.min()
}
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 | d7cd903485f41fe8c7023c015e4e606af9e10315 | 2,968 | advent_code_2022 | Apache License 2.0 |
2023/src/day03/day03.kt | Bridouille | 433,940,923 | false | {"Kotlin": 171124, "Go": 37047} | package day03
import GREEN
import RESET
import printTimeMillis
import readInput
private fun isSymbol(input: List<String>, y: Int, x: Int) : Boolean {
if (y < 0 || y >= input.size) return false
if (x < 0 || x >= input[y].length) return false
val c = input[y][x]
return !c.isDigit() && c != '.'
}
private fun checkValid(input: List<String>, y: Int, x: Int) : Boolean {
return isSymbol(input, y - 1, x - 1) ||
isSymbol(input, y - 1, x) ||
isSymbol(input, y - 1, x + 1) ||
isSymbol(input, y, x - 1) ||
isSymbol(input, y, x + 1) ||
isSymbol(input, y + 1, x - 1) ||
isSymbol(input, y + 1, x) ||
isSymbol(input, y + 1, x + 1)
}
fun part1(input: List<String>): Int {
var sum = 0
for (y in input.indices) {
var number = 0
var isValid = false
for (x in input[y].indices) {
if (input[y][x].isDigit()) {
number = number * 10 + input[y][x].digitToInt()
if (!isValid) {
isValid = checkValid(input, y, x)
}
} else {
// println("number read = $number - isValid = $isValid")
if (isValid) {
sum += number
isValid = false
}
number = 0
}
}
if (isValid) sum += number
}
return sum
}
//
// Return a number read from position x in the string str
// and a set of the x positions of that number
//
private fun readDigit(str: String, x: Int) : Pair<Int?, Set<Int>> {
if (!str[x].isDigit()) return Pair(null, emptySet())
var start = x
while (start > 0 && str[start - 1].isDigit()) start--
var number = 0
val xPos = mutableSetOf<Int>()
while (start < str.length && str[start].isDigit()) {
xPos.add(start)
number = number * 10 + str[start].digitToInt()
start++
}
return Pair(number, xPos)
}
private fun findAdj(input: List<String>, y: Int, x: Int): List<Int> {
// Pair<Number + Number positions> = '467' -> setOf(0, 1, 2)
val numbers = mutableSetOf<Pair<Int?, Set<Int>>>()
// Top
if (y > 0) {
numbers.add(readDigit(input[y - 1], x - 1))
numbers.add(readDigit(input[y - 1], x))
numbers.add(readDigit(input[y - 1], x + 1))
}
// Same line
numbers.add(readDigit(input[y], x - 1))
numbers.add(readDigit(input[y], x + 1))
// Bottom
if (y + 1 < input.size) {
numbers.add(readDigit(input[y + 1], x - 1))
numbers.add(readDigit(input[y + 1], x))
numbers.add(readDigit(input[y + 1], x + 1))
}
return numbers.mapNotNull { it.first }
}
fun part2(input: List<String>): Int {
var sum = 0
for (y in input.indices) {
for (x in input[y].indices) {
if (input[y][x] == '*') {
val adj = findAdj(input, y, x)
if (adj.size >= 2) { // This is a gear
sum += adj.fold(1) { a, b -> a * b }
}
}
}
}
return sum
}
fun main() {
val testInput = readInput("day03_example.txt")
printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) }
printTimeMillis { print("part2 example = $GREEN" + part2(testInput) + RESET) }
val input = readInput("day03.txt")
printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) }
printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) }
}
| 0 | Kotlin | 0 | 2 | 8ccdcce24cecca6e1d90c500423607d411c9fee2 | 3,542 | advent-of-code | Apache License 2.0 |
src/Day07.kt | illarionov | 572,508,428 | false | {"Kotlin": 108577} | data class File(
val name: String,
val size: Long
)
class Node(
val name: String,
var parent: Node?,
val dirs: MutableMap<String, Node> = mutableMapOf(),
val files: MutableList<File> = mutableListOf()
) {
val size: Long
get() {
val fileSize = files.map(File::size).sum()
val dirsSize = dirs.values.map(Node::size).sum()
return fileSize + dirsSize
}
}
enum class ParseState {
WAITING_COMMAND,
PARSE_LS_OUTPUT
}
val cdDirPattern = Regex("""\$ cd (.+)""")
val dirItemPattern = Regex("""dir (.+)""")
val fileItemPattern = Regex("""(\d+) (.+)""")
fun List<String>.parseTree(): Node {
val root = Node(name = "/", null)
root.parent = root
var currentNode: Node = root
var state: ParseState = ParseState.WAITING_COMMAND
this.forEach { s ->
if (s.startsWith("$ ")) {
if (s == "$ ls") {
state = ParseState.PARSE_LS_OUTPUT
} else {
val dirName = cdDirPattern.matchEntire(s)?.groupValues?.get(1)
?: error("Can not parse command `$s`")
currentNode = when (dirName) {
".." -> currentNode.parent!!
"/" -> root
else -> {
currentNode.dirs[dirName]
?: error("No such directory $dirName")
}
}
state = ParseState.WAITING_COMMAND
}
} else {
check(state == ParseState.PARSE_LS_OUTPUT) {
"Waiting LS output on string `$s`"
}
val result = dirItemPattern.matchEntire(s)
if (result != null) {
val dirName = result.groups[1]!!.value
currentNode.dirs[dirName] = Node(dirName, currentNode)
} else {
val fileResult = fileItemPattern.matchEntire(s)?.groupValues
check(fileResult != null) { "Unknown command `$s`" }
currentNode.files += File(
name = fileResult[2],
size = fileResult[1].toLong(),
)
}
}
}
return root
}
fun main() {
fun getTotalSizeAtMost10000(root: Node): Long {
val childSizes = root.dirs.values.sumOf(::getTotalSizeAtMost10000)
val thisSize = root.size.let {
if (it <= 100000) it else 0
}
return thisSize + childSizes
}
fun part1(input: List<String>): Long {
val tree = input.parseTree()
return getTotalSizeAtMost10000(tree)
}
fun findMinDirAtLeast(toDelete: Long, root: Node): Long {
if (root.size < toDelete) return Long.MAX_VALUE
return minOf(root.dirs.values.minOfOrNull { d ->
findMinDirAtLeast(toDelete, d)
} ?: root.size, root.size)
}
fun part2(input: List<String>): Long {
val tree = input.parseTree()
val freeSpace = 70000000 - tree.size
check(freeSpace < 30000000)
val toDelete = 30000000 - freeSpace
return findMinDirAtLeast(toDelete, tree)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
val part1TestResult = part1(testInput)
println(part1TestResult)
check(part1TestResult == 95437L)
val input = readInput("Day07")
val part1Result = part1(input)
//check(part1Result == 1427048L)
println(part1Result)
val part2Result = part2(input)
//check(part2Result == 2940614L)
println(part2Result)
}
| 0 | Kotlin | 0 | 0 | 3c6bffd9ac60729f7e26c50f504fb4e08a395a97 | 3,608 | aoc22-kotlin | Apache License 2.0 |
src/year_2022/day_09/Day09.kt | scottschmitz | 572,656,097 | false | {"Kotlin": 240069} | package year_2022.day_09
import readInput
import kotlin.math.abs
enum class Direction(val letter: String, val xMod: Int, val yMod: Int) {
UP("U", 0, 1),
DOWN("D", 0, -1),
LEFT("L", -1, 0),
RIGHT("R", 1, 0),
;
}
data class Movement(
val direction: Direction,
val quantity: Int
)
data class Position(
val x: Int,
val y: Int
) {
fun isTouching(other: Position): Boolean {
return abs(x - other.x) < 2 && abs(y - other.y) < 2
}
fun calculatePositionToTouch(other: Position): Position {
var xMod = 0
var yMod = 0
if (x == other.x) {
// same x so need to move up/down
yMod = if (y < other.y) 1 else -1
} else if (y == other.y) {
// same y so need to move left/right
xMod = if (x < other.x) 1 else -1
} else {
// need to move on a diagonal to catch up
xMod = if (x < other.x) 1 else -1
yMod = if (y < other.y) 1 else -1
}
return Position(
x = x + xMod,
y = y + yMod
)
}
}
object Day09 {
/**
* @return unique placements of the tail if 2 ropes
*/
fun solutionOne(text: List<String>): Int {
val ropesCount = 2
val movements = parseMovements(text)
return calculateRopeMotion(ropesCount, movements).toSet().size
}
/**
* @return unique placements of the tail if 10 ropes
*/
fun solutionTwo(text: List<String>): Int {
val ropesCount = 10
val movements = parseMovements(text)
return calculateRopeMotion(ropesCount, movements).toSet().size
}
private fun parseMovements(text: List<String>): List<Movement> {
return text.map { line ->
val split = line.split(" ")
val direction = Direction.values().first { direction -> direction.letter == split[0] }
val quantity = Integer.parseInt(split[1])
Movement(direction, quantity)
}
}
/**
* @return the path of the tail
*/
private fun calculateRopeMotion(ropeCount: Int, movements: List<Movement>): List<Position> {
val startingPosition = Position(0, 0)
val ropes = mutableListOf<MutableList<Position>>()
for (i in 0 until ropeCount) {
ropes.add(mutableListOf(startingPosition))
}
movements.forEach { movement ->
for (i in 0 until movement.quantity) {
val currentHead = ropes[0].last()
val newHead = Position(
x = currentHead.x + movement.direction.xMod,
y = currentHead.y + movement.direction.yMod
)
ropes[0].add(newHead)
for (j in 1 until ropes.size) {
val leadingRopePos = ropes[j-1].last()
val ropePos = ropes[j].last()
if (!ropePos.isTouching(leadingRopePos)) {
val newRopePos = ropePos.calculatePositionToTouch(leadingRopePos)
ropes[j].add(newRopePos)
}
}
}
}
return ropes.last()
}
}
fun main() {
val inputText = readInput("year_2022/day_09/Day10.txt")
val solutionOne = Day09.solutionOne(inputText)
println("Solution 1: $solutionOne")
val solutionTwo = Day09.solutionTwo(inputText)
println("Solution 2: $solutionTwo")
} | 0 | Kotlin | 0 | 0 | 70efc56e68771aa98eea6920eb35c8c17d0fc7ac | 3,463 | advent_of_code | Apache License 2.0 |
src/main/kotlin/year2022/Day02.kt | forketyfork | 572,832,465 | false | {"Kotlin": 142196} | package year2022
class Day02 {
enum class Move(private val points: Int) {
ROCK(1), PAPER(2), SCISSORS(3);
fun score(other: Move): Int = when {
this == other -> Outcome.DRAW
this.ordinal == (other.ordinal + 1) % Move.entries.size -> Outcome.WIN
else -> Outcome.LOSE
}.points + this.points
fun loser() = Move.entries[(Move.entries.size + this.ordinal - 1) % Move.entries.size]
fun winner() = Move.entries[(this.ordinal + 1) % Move.entries.size]
companion object {
fun ofChar(c: Char): Move = when (c) {
'A', 'X' -> ROCK
'B', 'Y' -> PAPER
'C', 'Z' -> SCISSORS
else -> error("Unknown move: $c")
}
}
}
enum class Outcome(val code: Char, val points: Int) {
LOSE('X', 0), DRAW('Y', 3), WIN('Z', 6);
companion object {
fun ofChar(c: Char): Outcome = entries.find { it.code == c } ?: error("Unknown outcome: $c")
}
}
private fun calculateScore(input: List<String>, parser: (Pair<Char, Char>) -> Pair<Move, Move>): Int =
input.map { it.split(" ").map(String::first) }
.map { (p1, p2) -> p1 to p2 }
.map(parser)
.sumOf { (move1, move2) -> move2.score(move1) }
fun part1(input: String) = calculateScore(input.lines()) {
Move.ofChar(it.first) to Move.ofChar(it.second)
}
fun part2(input: String) = calculateScore(input.lines()) {
val move1 = Move.ofChar(it.first)
val outcome = Outcome.ofChar(it.second)
val move2 =
if (outcome == Outcome.LOSE) move1.loser() else if (outcome == Outcome.DRAW) move1 else move1.winner()
move1 to move2
}
}
| 0 | Kotlin | 0 | 0 | 5c5e6304b1758e04a119716b8de50a7525668112 | 1,787 | aoc-2022 | Apache License 2.0 |
src/Day10.kt | vi-quang | 573,647,667 | false | {"Kotlin": 49703} | import kotlin.math.abs
import kotlin.streams.asSequence
/**
* It's one line solution day for a change of pace.
*/
fun main() {
fun getSequence(input: List<String>): Map<Int, List<Pair<Int, Int>>> {
return input.stream().map { it.replace("addx ", "noop noop,noop") }
.asSequence()
.flatMap(Regex(" ")::splitToSequence)
.mapIndexed { index, line ->
val cycle = index + 1
line.replace(",noop", " $cycle|")
.replace("noop", "$cycle|0")
}
.flatMap(Regex(" ")::splitToSequence)
.map {
val token = it.split("|")
val cycle = token[0].toInt()
cycle to token[1].toInt()
}
.scan(Pair(0, 1)) { acc, pair ->
pair.first to (acc.second + pair.second)
}
.groupBy { it.first }
}
fun part1(input: List<String>): Int {
return getSequence(input)
.filter { it.key % 20 == 0 && it.key % 40 != 0 && it.key <= 220 }
.map { it.value.first() }
.sumOf { it.first * it.second }
}
fun part2(input: List<String>): List<String> {
return getSequence(input)
.map {
val entry = it.value.last()
val pixel = if (abs(entry.first % 40 - entry.second) < 2) '#' else '.'
pixel
}.windowed(40, 40)
.map { it.joinToString("") }
.toList()
}
val input = readInput(10)
println(part1(input))
part2(input).forEach {
println(it)
}
}
| 0 | Kotlin | 0 | 2 | ae153c99b58ba3749f16b3fe53f06a4b557105d3 | 1,634 | aoc-2022 | Apache License 2.0 |
src/Day02.kt | jgodort | 573,181,128 | false | null | import HandShape.*
import RoundResult.*
enum class HandShape(val points: Int) {
Rock(1),
Paper(2),
Scissors(3)
}
enum class RoundResult(val points: Int) {
WIN(6),
LOSE(0),
DRAW(3)
}
fun main() {
val inputData = readInput("Day2_input")
println("""Result 1 ${part1(inputData)}""")
println("""Result 2 ${part2(inputData)}""")
}
fun part1(input: String): Int {
fun String.convertToHandShape(): HandShape {
return when {
listOf("A", "X").any { it == this } -> Rock
listOf("B", "Y").any { it == this } -> Paper
listOf("C", "Z").any { it == this } -> Scissors
else -> error("Wrong Shape")
}
}
fun calculateRound(pair: Pair<HandShape, HandShape>) = when (pair) {
(Paper to Rock),
(Rock to Scissors),
(Scissors to Paper) -> 0
(Paper to Paper),
(Rock to Rock),
(Scissors to Scissors) -> 3
(Scissors to Rock),
(Rock to Paper),
(Paper to Scissors) -> 6
else -> error("Wrong Round")
}
fun resultScore(pair: Pair<HandShape, HandShape>): Int =
pair.second.points + calculateRound(pair)
return input
.lines()
.map { rounds ->
val game = rounds.split(" ")
game[0].convertToHandShape() to game[1].convertToHandShape()
}.sumOf { game -> resultScore(game) }
}
fun part2(input: String): Int {
fun convertToShape(shape: String): HandShape = when (shape) {
"A" -> Rock
"B" -> Paper
"C" -> Scissors
else -> error("Wrong Shape")
}
fun computeRoundResult(roundResult: String) = when (roundResult) {
"X" -> LOSE
"Y" -> DRAW
"Z" -> WIN
else -> error("Wrong Shape")
}
fun computeUserHand(roundResult: RoundResult, opponentHand: HandShape): HandShape = when (roundResult) {
WIN -> {
when (opponentHand) {
Rock -> Paper
Paper -> Scissors
Scissors -> Rock
}
}
LOSE -> {
when (opponentHand) {
Rock -> Scissors
Paper -> Rock
Scissors -> Paper
}
}
DRAW -> {
when (opponentHand) {
Rock -> Rock
Paper -> Paper
Scissors -> Scissors
}
}
}
return input.lines().sumOf { rounds ->
val game = rounds.split(" ")
val opponentHand = convertToShape(game[0])
val roundResult = computeRoundResult(game[1])
val userHand = computeUserHand(roundResult, opponentHand)
userHand.points + roundResult.points
}
}
| 0 | Kotlin | 0 | 0 | 355f476765948c79bfc61367c1afe446fe9f6083 | 2,745 | aoc2022Kotlin | Apache License 2.0 |
src/Day07.kt | oleksandrbalan | 572,863,834 | false | {"Kotlin": 27338} | fun main() {
val input = readInput("Day07")
.drop(1)
.filterNot { it.isEmpty() }
val root = Directory("/")
var node = root
input.forEach { row ->
when {
row.startsWith(COMMAND_CD) -> {
val dirName = row.drop(COMMAND_CD.length)
node = if (dirName == REF_GO_UP) {
requireNotNull(node.parent)
} else {
requireNotNull(node.children.find { it.name == dirName } as Directory)
}
}
row.startsWith(COMMAND_LS) -> {
// Empty ¯\_(ツ)_/¯
}
else -> {
val (size, name) = row.split(" ")
val child = if (size == TYPE_DIRECTORY) {
Directory(name, node)
} else {
File(name, size.toInt())
}
node.children.add(child)
}
}
}
val directories = root.directories
val part1 = directories
.filter { it.size < 100_000 }
.sumOf { it.size }
println("Part1: $part1")
val totalSize = root.size
val freeSpace = 70_000_000 - totalSize
val needToFree = 30_000_000 - freeSpace
val part2 = directories
.filter { it.size > needToFree }
.minOf { it.size }
println("Part2: $part2")
}
private sealed interface Node {
val name: String
val size: Int
}
private class File(
override val name: String,
override val size: Int
) : Node
private class Directory(
override val name: String,
val parent: Directory? = null,
val children: MutableList<Node> = mutableListOf()
) : Node {
override val size: Int by lazy {
children.fold(0) { acc, child -> acc + child.size }
}
val directories: List<Directory> by lazy {
children
.filterIsInstance<Directory>()
.flatMap { it.directories }
.plus(this)
}
}
private const val COMMAND_CD = "$ cd "
private const val COMMAND_LS = "$ ls"
private const val TYPE_DIRECTORY = "dir"
private const val REF_GO_UP = ".."
| 0 | Kotlin | 0 | 2 | 1493b9752ea4e3db8164edc2dc899f73146eeb50 | 2,138 | advent-of-code-2022 | Apache License 2.0 |
src/utils/NeighbourFunction.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package utils
import java.util.PriorityQueue
/**
* Thanks to [https://github.com/Mistborn94/advent-of-code-2023/blob/master/src/main/kotlin/day17/Day17.kt]
*/
typealias NeighbourFunction<K> = (K) -> Iterable<K>
typealias CostFunction<K> = (K, K) -> Int
typealias HeuristicFunction<K> = (K) -> Int
/**
* Implements A* search to find the shortest path between two vertices
*/
fun <K> findShortestPath(
start: K,
end: K,
neighbours: NeighbourFunction<K>,
cost: CostFunction<K> = { _, _ -> 1 },
heuristic: HeuristicFunction<K> = { 0 }
): GraphSearchResult<K> =
findShortestPathByPredicate(start, { it == end }, neighbours, cost, heuristic)
/**
* Implements A* search to find the shortest path between two vertices using a predicate to determine the ending vertex
*/
fun <K> findShortestPathByPredicate(
start: K,
endFunction: (K) -> Boolean,
neighbours: NeighbourFunction<K>,
cost: CostFunction<K> = { _, _ -> 1 },
heuristic: HeuristicFunction<K> = { 0 }
): GraphSearchResult<K> {
val toVisit = PriorityQueue(listOf(ScoredVertex(start, 0, heuristic(start))))
var endVertex: K? = null
val seenPoints: MutableMap<K, SeenVertex<K>> = mutableMapOf(start to SeenVertex(0, null))
while (endVertex == null) {
if (toVisit.isEmpty()) {
return GraphSearchResult(start, null, seenPoints)
}
val (currentVertex, currentScore) = toVisit.remove()
endVertex = if (endFunction(currentVertex)) currentVertex else null
val nextPoints = neighbours(currentVertex)
.filter { it !in seenPoints }
.map { next ->
ScoredVertex(
next,
currentScore + cost(currentVertex, next),
heuristic(next)
)
}
toVisit.addAll(nextPoints)
seenPoints.putAll(nextPoints.associate { it.vertex to SeenVertex(it.score, currentVertex) })
}
return GraphSearchResult(start, endVertex, seenPoints)
}
class GraphSearchResult<K>(val start: K, val end: K?, private val result: Map<K, SeenVertex<K>>) {
fun getScore(vertex: K) =
result[vertex]?.cost ?: throw IllegalStateException("Result for $vertex not available")
fun getScore() = end?.let { getScore(it) } ?: throw IllegalStateException("No path found")
fun getPath() =
end?.let { getPath(it, emptyList()) } ?: throw IllegalStateException("No path found")
fun seen(): Set<K> = result.keys
fun end(): K = end ?: throw IllegalStateException("No path found")
private tailrec fun getPath(endVertex: K, pathEnd: List<K>): List<K> {
val previous = result[endVertex]?.prev
return if (previous == null) {
listOf(endVertex) + pathEnd
} else {
getPath(previous, listOf(endVertex) + pathEnd)
}
}
}
data class SeenVertex<K>(val cost: Int, val prev: K?)
private data class ScoredVertex<K>(val vertex: K, val score: Int, val heuristic: Int) :
Comparable<ScoredVertex<K>> {
override fun compareTo(other: ScoredVertex<K>): Int =
(score + heuristic).compareTo(other.score + other.heuristic)
} | 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 3,173 | KotlinAdventOfCode | Apache License 2.0 |
ceria/19/src/main/kotlin/Solution.kt | VisionistInc | 317,503,410 | false | null | import java.io.File
fun main(args : Array<String>) {
val input = File(args.first()).readLines()
println("Solution 1: ${solution1(input)}")
println("Solution 2: ${solution2(input)}")
}
private fun solution1(input :List<String>) :Int {
var rulesMap = mutableMapOf<String, String>()
val rules = input.subList(0, input.indexOf(""))
var messages = input.subList(input.indexOf("") + 1, input.size)
for (rule in rules) {
val ruleNum = rule.substring(0, rule.indexOf(":"))
val ruleVal = rule.substring(rule.indexOf(" ") + 1, rule.length)
if (ruleVal.contains('|')) {
var stringified = "( ".plus(ruleVal.substring(0, ruleVal.indexOf("|") -1)).plus(" ) | ( ").plus(ruleVal.substring(ruleVal.indexOf("|") + 2 ) ).plus(" )")
rulesMap.put(ruleNum, "( ".plus(stringified).plus(" )"))
} else {
rulesMap.put(ruleNum, "( ".plus(ruleVal.replace("\"", "")).plus(" )"))
}
}
val pattern = "^".plus(buildRegex(rulesMap)).plus("$").toRegex()
return messages.filter{ pattern.containsMatchIn(it) }.size
}
// 348 == too low 450 == too high
private fun solution2(input :List<String>) :Int {
var rulesMap = mutableMapOf<String, String>()
val rules = input.subList(0, input.indexOf(""))
var messages = input.subList(input.indexOf("") + 1, input.size)
for (rule in rules) {
val ruleNum = rule.substring(0, rule.indexOf(":"))
val ruleVal = rule.substring(rule.indexOf(" ") + 1, rule.length)
if (ruleVal.contains('|')) {
var stringified = "( ".plus(ruleVal.substring(0, ruleVal.indexOf("|") -1)).plus(" ) | ( ").plus(ruleVal.substring(ruleVal.indexOf("|") + 2 ) ).plus(" )")
rulesMap.put(ruleNum, "( ".plus(stringified).plus(" )"))
} else {
rulesMap.put(ruleNum, "( ".plus(ruleVal.replace("\"", "")).plus(" )"))
}
}
// Manually modify the rules
// 8: 42 becomes
// 8: 42 | 42 8 which is essentially (42)+ (1 to n times)
// rulesMap.put("8", rulesMap.get("8").plus(" | ( 42 ( 42 + ) )"))
rulesMap.put("8", rulesMap.get("8").plus(" | ( ( 42 ) {2,} )"))
// 11: 42 31 becomes
// 11: 42 31 | 42 11 31 which is (42+ 31)
// rulesMap.put("11", rulesMap.get("11").plus( " | ( 42 ( 42 + ) 31 )"))
rulesMap.put("11", "( ( 42 * ) 42 31 )")
var pattern = "^".plus(buildRegex(rulesMap)).plus("$").toRegex()
// println(pattern)
// var filteredMessages = messages.filter{ pattern.containsMatchIn(it) }
// for (message in filteredMessages ) {
// val match = pattern.find(message)
// if (!message.equals(match?.value)) {
// println("------------------------------------------- " + message)
// }
// // println(match?.value)
// }
// println("*****************************************************")
// println("*****************************************************")
// messages.filter{ pattern.containsMatchIn(it) }.map{ println(it) }
return messages.filter{ pattern.containsMatchIn(it) }.size
}
private fun buildRegex(rules :Map<String, String>) :String {
var rulesMap = rules.toMutableMap()
while ( !allLetters(rulesMap.get("0")!!) ) {
for (rule in findReplacingRules(rulesMap)) {
var ruleVal = rulesMap.get(rule)!!
for ( (k, v) in rulesMap) {
// Split into tokens to make sure it's the full rule, and not partial, i.e. that it's rule "8" and not "88"
var parts = v.split(" ").toMutableList()
for (i in parts.indices) {
if (parts[i].equals(rule)) {
parts[i] = ruleVal
}
}
rulesMap.put(k, parts.joinToString(separator = " "))
}
}
// println("+++++++++++++++++++++++++++++")
}
return rulesMap.get("0")!!.replace(" ", "")
}
private fun findReplacingRules(rulesMap :Map<String, String>) :Set<String> {
var replacing = mutableSetOf<String>()
for ((rKey, rVal) in rulesMap) {
if (allLetters(rVal)) {
replacing.add(rKey)
}
}
return replacing
}
private fun allLetters(test :String) :Boolean {
var allLetters = true
for (v in test.split(" ")) {
if (!v.trim().equals("a") && !v.trim().equals("b") && !v.trim().equals("(")
&& !v.trim().equals(")") && !v.trim().equals("|") && !v.trim().equals("+")
&& !v.trim().equals("?") && !v.trim().equals("*") && !v.trim().equals("{2,}") ) {
allLetters = false
break
}
}
return allLetters
} | 0 | Rust | 0 | 0 | 002734670384aa02ca122086035f45dfb2ea9949 | 4,347 | advent-of-code-2020 | MIT License |
src/main/kotlin/pl/jpodeszwik/aoc2023/Day13.kt | jpodeszwik | 729,812,099 | false | {"Kotlin": 55101} | package pl.jpodeszwik.aoc2023
private fun findAnagram(ints: List<Int>, notEqualTo: Int? = null): Int? {
var biggestAnagram: Int? = null
var biggestAnagramLength = 0
for (i in 1..<ints.size) {
val toLeft = ints.subList(0, i).asReversed()
val toRight = ints.subList(i, ints.size)
var shorter: List<Int>
var longer: List<Int>
if (toLeft.size > toRight.size) {
longer = toLeft
shorter = toRight
} else {
longer = toRight
shorter = toLeft
}
if (shorter.indices.all { shorter[it] == longer[it] } && i != notEqualTo) {
val anagramLength = shorter.size
if (anagramLength >= biggestAnagramLength) {
biggestAnagramLength = anagramLength
biggestAnagram = i
}
}
}
return biggestAnagram
}
private fun solve1(lines: List<String>): Long {
val (columns, rows) = parsePicture(lines)
val columnAnagram = findAnagram(columns)
val rowAnagram = findAnagram(rows)
if (columnAnagram != null && rowAnagram != null) {
throw IllegalStateException()
}
return if (rowAnagram != null) {
rowAnagram.toLong() * 100
} else {
columnAnagram!!.toLong()
}
}
private fun part1(testCases: List<List<String>>) {
val result = testCases.sumOf(::solve1)
println("result: $result")
}
private fun solve2(lines: List<String>): Long {
val (columns, rows) = parsePicture(lines)
val originalColumn = findAnagram(columns)
val originalRow = findAnagram(rows)
for (row in rows.indices) {
for (col in columns.indices) {
columns[col] = flipBit(columns[col], row)
rows[row] = flipBit(rows[row], col)
val columnAnagram = findAnagram(columns, originalColumn)
val rowAnagram = findAnagram(rows, originalRow)
columns[col] = flipBit(columns[col], row)
rows[row] = flipBit(rows[row], col)
if (columnAnagram != null && rowAnagram != null) {
println("col $col row $row")
println("columnAnagram ${columnAnagram} rowAnagram ${rowAnagram}")
}
if (rowAnagram != null) {
return rowAnagram.toLong() * 100
} else if (columnAnagram != null) {
return columnAnagram.toLong()
}
}
}
throw IllegalStateException()
}
private fun parsePicture(lines: List<String>): Pair<ArrayList<Int>, ArrayList<Int>> {
val columns = ArrayList<Int>()
val rows = ArrayList<Int>()
lines.indices.forEach { row ->
var rowVal = 0
lines[0].indices.forEach { col ->
rowVal += (if (lines[row][col] == '#') 1 else 0) shl col
}
rows.add(rowVal)
}
lines[0].indices.forEach { col ->
var colVal = 0
lines.indices.forEach { row ->
colVal += (if (lines[row][col] == '#') 1 else 0) shl row
}
columns.add(colVal)
}
return Pair(columns, rows)
}
private fun part2(testCases: List<List<String>>) {
val result = testCases.sumOf(::solve2)
println("result: $result")
}
fun main() {
val file = loadEntireFile("/aoc2023/input13")
val testCases = file.split("\n\n")
.map { it.split("\n") }
part1(testCases)
part2(testCases)
} | 0 | Kotlin | 0 | 0 | 2b90aa48cafa884fc3e85a1baf7eb2bd5b131a63 | 3,386 | advent-of-code | MIT License |
2023/src/main/kotlin/Day08.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | object Day08 {
private data class Data(val directions: String, val nodes: Map<String, Node>)
private data class Node(val label: String, val left: String, val right: String)
fun part1(input: String): Int {
return cycleLength(parseInput(input), "AAA", "ZZZ")
}
fun part2(input: String): Long {
val maps = parseInput(input)
val cycles = maps.nodes.keys
.filter { it.endsWith("A") }
.map { cycleLength(maps, it, "Z").toLong() }
return leastCommonMultiple(cycles)
}
private fun cycleLength(data: Data, start: String, endsWith: String): Int {
var count = 0
var curr = start
while (!curr.endsWith(endsWith)) {
curr = when (data.directions[count % data.directions.length]) {
'L' -> data.nodes[curr]!!.left
else -> data.nodes[curr]!!.right
}
count++
}
return count
}
private fun leastCommonMultiple(numbers: List<Long>) = numbers.reduce { a, b -> leastCommonMultiple(a, b) }
private fun leastCommonMultiple(a: Long, b: Long) = a * (b / greatestCommonDivisor(a, b))
// Euclid's algorithm
private fun greatestCommonDivisor(a: Long, b: Long): Long = if (b == 0L) a else greatestCommonDivisor(b, a % b)
private fun parseInput(input: String): Data {
val lines = input.splitNewlines()
return Data(
directions = lines[0],
nodes = lines
.drop(2)
.map { Node(it.slice(0..2), it.slice(7..9), it.slice(12..14)) }
.associateBy { it.label }
)
}
} | 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 1,492 | advent-of-code | MIT License |
src/Day02.kt | f1qwase | 572,888,869 | false | {"Kotlin": 33268} | enum class RpsFigure(val value: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3);
fun play(other: RpsFigure): PlayResult {
return when ((this.ordinal - other.ordinal + 3) % 3) {
0 -> PlayResult.DRAW
1 -> PlayResult.WIN
2 -> PlayResult.LOSE
else -> throw IllegalStateException("Unexpected value: ${(this.ordinal - other.ordinal) % 3}")
}
}
companion object {
fun fromCode(s: String): RpsFigure = when (s) {
"A", "X" -> ROCK
"B", "Y" -> PAPER
"C", "Z" -> SCISSORS
else -> throw IllegalArgumentException("Unknown figure code: $s")
}
}
}
enum class PlayResult(val value: Int) {
LOSE(0),
DRAW(3),
WIN(6);
companion object {
fun fromCode(s: String): PlayResult = when (s) {
"X" -> LOSE
"Y" -> DRAW
"Z" -> WIN
else -> throw IllegalArgumentException("Unknown result code: $s")
}
}
}
fun main() {
fun part1(input: List<String>): Int = input.sumOf {
val (theirs, mine) = it.split(" ").map(RpsFigure::fromCode)
val result = mine.play(theirs)
result.value + mine.value
}
fun part2(input: List<String>): Int = input.sumOf {
val (theirsCode, resultCode) = it.split(" ")
val result = PlayResult.fromCode(resultCode)
val theirs = RpsFigure.fromCode(theirsCode)
val rpsVals = RpsFigure.values()
val mine = rpsVals.first { figure -> figure.play(theirs) == result }
result.value + mine.value
}
// 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))
check(part1(input) == 11873)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 3fc7b74df8b6595d7cd48915c717905c4d124729 | 1,908 | aoc-2022 | Apache License 2.0 |
src/day05/Day05_functional.kt | seastco | 574,758,881 | false | {"Kotlin": 72220} | package day05
import readLines
/**
* Credit goes to tginsberg (https://github.com/tginsberg/advent-2022-kotlin)
* I'm experimenting with his solutions to better learn functional programming in Kotlin.
* Files without the _functional suffix are my original solutions.
*/
private fun Iterable<Iterable<Char>>.tops(): String =
map { it.first() }.joinToString("")
private fun createStacks(input: List<String>): List<MutableList<Char>> {
val stackRows = input.takeWhile { it.contains('[') }
return (1..stackRows.last().length step 4).map { index -> // take index 1-9
stackRows // iterate over stackRows
.mapNotNull { it.getOrNull(index) } // lookup index for each stack row
.filter { it.isUpperCase() } // grab anything with uppercase, i.e. the crate
.toMutableList() // convert to mutable list
}
}
data class Instruction(val amount: Int, val source: Int, val target: Int)
private fun parseInstructions(input: List<String>): List<Instruction> =
input
.dropWhile { !it.startsWith("move") } // skip until you get to the instructions
.map { row ->
row.split(" ").let { parts -> // split each row and use "let" to pass as argument into next block
Instruction(parts[1].toInt(), parts[3].toInt() - 1, parts[5].toInt() - 1)
}
}
private fun performInstructions(stacks: List<MutableList<Char>>, instructions: List<Instruction>, reverse: Boolean) {
instructions.forEach { (amount, source, destination) -> // unpack each Instruction
// take the first n=amount elements from the source stack
val toBeMoved = stacks[source].take(amount)
// remove the first element from the source stack n=amount times
repeat(amount) { stacks[source].removeFirst() }
// add all the elements from toBeMoved in reverse order to the destination stack
stacks[destination].addAll(0, if (reverse) toBeMoved.reversed() else toBeMoved)
}
}
private fun part1(input: List<String>): String {
var stacks: List<MutableList<Char>> = createStacks(input)
var instructions: List<Instruction> = parseInstructions(input)
performInstructions(stacks, instructions, true)
return stacks.tops()
}
private fun part2(input: List<String>): String {
var stacks: List<MutableList<Char>> = createStacks(input)
var instructions: List<Instruction> = parseInstructions(input)
performInstructions(stacks, instructions, false)
return stacks.tops()
}
fun main() {
val testInput = readLines("day05/test")
println(part1(testInput))
println(part2(testInput))
val input = readLines("day05/input")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 2d8f796089cd53afc6b575d4b4279e70d99875f5 | 2,725 | aoc2022 | Apache License 2.0 |
2022/src/day04/day04.kt | Bridouille | 433,940,923 | false | {"Kotlin": 171124, "Go": 37047} | package day04
import GREEN
import RESET
import printTimeMillis
import readInput
data class Bound(val min: Int, val max: Int) {
fun contains(other: Bound) = min <= other.min && max >= other.max
fun overlap(other: Bound) = (min >= other.min && min <= other.max) || (max <= other.max && max >= other.min)
}
fun part1(input: List<String>) = input.fold(0) { acc, line ->
val first = line.split(",")[0].split("-").let { Bound(it[0].toInt(), it[1].toInt()) }
val second = line.split(",")[1].split("-").let { Bound(it[0].toInt(), it[1].toInt()) }
val increase = if (first.contains(second) || second.contains(first)) { 1 } else { 0 }
acc+ increase
}
fun part2(input: List<String>) = input.fold(0) { acc, line ->
val first = line.split(",")[0].split("-").let { Bound(it[0].toInt(), it[1].toInt()) }
val second = line.split(",")[1].split("-").let { Bound(it[0].toInt(), it[1].toInt()) }
val increase = if (first.overlap(second) || second.overlap(first)) { 1 } else { 0 }
acc+ increase
}
fun main() {
val testInput = readInput("day04_example.txt")
printTimeMillis { print("part1 example = $GREEN" + part1(testInput) + RESET) }
printTimeMillis { print("part2 example = $GREEN" + part2(testInput) + RESET) }
val input = readInput("day04.txt")
printTimeMillis { print("part1 input = $GREEN" + part1(input) + RESET) }
printTimeMillis { print("part2 input = $GREEN" + part2(input) + RESET) }
}
| 0 | Kotlin | 0 | 2 | 8ccdcce24cecca6e1d90c500423607d411c9fee2 | 1,447 | advent-of-code | Apache License 2.0 |
05/part_two.kt | ivanilos | 433,620,308 | false | {"Kotlin": 97993} | import java.io.File
import kotlin.math.*
fun readInput() : List<Line> {
val inputLines = File("input.txt")
.readLines()
.map { it.split("\n") }
val intRegex = """\d+""".toRegex()
val lines = inputLines.map{ inputLine -> Line(intRegex.findAll(inputLine[0])
.map{ it.value.toInt() }
.toList()) }
return lines
}
data class Pt(val x : Int, val y : Int)
class Line(points : List<Int>) {
private val a : Pt
private val b : Pt
init {
a = Pt(points[0], points[1])
b = Pt(points[2], points[3])
}
fun touchPoints() : HashSet<Pt> {
val result = HashSet<Pt>()
val deltaX = (b.x - a.x).sign
val deltaY = (b.y - a.y).sign
var curX = a.x
var curY = a.y
while(!(curX == b.x && curY == b.y)) {
result.add(Pt(curX, curY))
curX += deltaX
curY += deltaY
}
result.add(Pt(b.x, b.y))
return result
}
}
fun updatePointsFreq(pointsFreq : HashMap<Pt, Int>, line : Line) {
val pointsInLine = line.touchPoints()
for (point in pointsInLine) {
val curPointFreq = pointsFreq.getOrDefault(point, 0)
pointsFreq[point] = curPointFreq + 1
}
}
fun solve(lines : List<Line>) : Int {
val pointsFreq = hashMapOf<Pt, Int>()
for (line in lines) {
updatePointsFreq(pointsFreq, line)
}
return pointsFreq.filter{ it.value > 1 }.size
}
fun main() {
val lines = readInput()
val ans = solve(lines)
println(ans)
}
| 0 | Kotlin | 0 | 3 | a24b6f7e8968e513767dfd7e21b935f9fdfb6d72 | 1,561 | advent-of-code-2021 | MIT License |
aoc-day8/src/Day8.kt | rnicoll | 438,043,402 | false | {"Kotlin": 90620, "Rust": 1313} | import java.nio.file.Files
import java.nio.file.Path
import java.util.*
fun main() {
val scenarios = Files.readAllLines(Path.of("input")).map {
Scenario.parse(it)
}.toList()
part1(scenarios)
part2(scenarios)
}
fun part1(scenarios: List<Scenario>) {
val uniqueDigits = EnumSet.of(Digit.ONE, Digit.FOUR, Digit.SEVEN, Digit.EIGHT)
val uniqueCounts = uniqueDigits.map { it.active.size }.toSet()
val uniques = scenarios.sumOf { scenario ->
scenario.outputs.filter { uniqueCounts.contains(it.size) }.count()
}
println("$uniques")
}
fun part2(scenarios: List<Scenario>) {
var total = 0
scenarios.forEach { scenario ->
val display = resolveScenario(scenario.inputs, scenario.outputs)
total += display.toInt()
// println(display)
}
println(total)
}
private fun resolveScenario(inputs: List<EnumSet<Signal>>, outputs: List<EnumSet<Signal>>): String {
val digits = extractDigits(inputs)
return outputs.map {
digits.indexOf(it)
}.joinToString("")
}
private fun extractDigits(inputs: List<EnumSet<Signal>>): Array<EnumSet<Signal>> {
// Mapping from signal, to the potential display position it relates to
val digits = Array<EnumSet<Signal>>(10) { EnumSet.noneOf(Signal::class.java) }
var remaining: List<EnumSet<Signal>> = mutableListOf<EnumSet<Signal>>().also {
it.addAll(inputs)
}
digits[1] = inputs.single { it.size == 2 }
digits[4] = inputs.single { it.size == 4 }
digits[7] = inputs.single { it.size == 3 }
digits[8] = inputs.single { it.size == 7 }
remaining = remaining.filter { it !in digits }
require(remaining.size == 6)
val top: Signal = digits[7].single { it !in digits[1] }
println("For inputs $inputs top segment must be $top")
val zeroSixOrNine = inputs.filter { it.size == 6 }
require(zeroSixOrNine.size == 3)
digits[6] = findSix(zeroSixOrNine, digits[1])
remaining = remaining.filter { it !in digits }
require(remaining.size == 5)
val lowerRight = digits[6].single { it in digits[1] }
val upperRight = digits[1].single() { it != lowerRight }
digits[5] = inputs.filter { !it.contains(upperRight) }.single { it != digits[6] }
remaining = remaining.filter { it !in digits }
require(remaining.size == 4)
val lowerLeft = digits[6].single { it !in digits[5] }
digits[9] = zeroSixOrNine.single { candidate -> !candidate.contains(lowerLeft) }
remaining = remaining.filter { it !in digits }
require(remaining.size == 3)
digits[0] = zeroSixOrNine.single { it != digits[6] && it != digits[9] }
remaining = remaining.filter { it !in digits }
require(remaining.size == 2)
// 2, 3 left to find
digits[2] = remaining.single { it.contains(lowerLeft) }
digits[3] = remaining.single { !it.contains(lowerLeft) }
return digits
}
private fun findSix(candidates: List<EnumSet<Signal>>, one: EnumSet<Signal>)
= candidates.single { input ->
overlap(input, one) == 1
}
private fun overlap(a: EnumSet<Signal>, b: EnumSet<Signal>) = a.count { it in b } | 0 | Kotlin | 0 | 0 | 8c3aa2a97cb7b71d76542f5aa7f81eedd4015661 | 3,105 | adventofcode2021 | MIT License |
2022/src/main/kotlin/com/github/akowal/aoc/Day14.kt | akowal | 573,170,341 | false | {"Kotlin": 36572} | package com.github.akowal.aoc
import kotlin.math.max
import kotlin.math.min
class Day14 {
private val map = inputFile("day14").readLines()
.map { line ->
line.split(" -> ").map { point ->
point.split(",").map(String::toInt).let { (x, y) -> Point(x, y) }
}
}
.flatMap { wall ->
wall.windowed(2, 1).flatMap { (a, b) ->
if (a.x == b.x) {
(min(a.y, b.y)..max(a.y, b.y)).map { y -> Point(a.x, y) }
} else {
(min(a.x, b.x)..max(a.x, b.x)).map { x -> Point(x, a.y) }
}
}
}.toMutableSet()
private val origin = Point(500, 0)
private var stableGrains = 0
private var totalGrains = 0
init {
val floor = map.maxOf(Point::y) + 1
while (origin !in map) {
var grain = origin
while (grain.canFall() && grain.y < floor) {
when {
grain.down !in map -> grain = grain.down
grain.ldown !in map -> grain = grain.ldown
grain.rdown !in map -> grain = grain.rdown
}
if (grain.y >= floor && stableGrains == 0) {
stableGrains = totalGrains
}
}
map += grain
totalGrains++
}
}
fun solvePart1(): Int {
return stableGrains
}
fun solvePart2(): Int {
return totalGrains
}
private val Point.down get() = Point(x, y + 1)
private val Point.ldown get() = Point(x - 1, y + 1)
private val Point.rdown get() = Point(x + 1, y + 1)
private fun Point.canFall() = down !in map || ldown !in map || rdown !in map
}
fun main() {
val solution = Day14()
println(solution.solvePart1())
println(solution.solvePart2())
}
| 0 | Kotlin | 0 | 0 | 02e52625c1c8bd00f8251eb9427828fb5c439fb5 | 1,874 | advent-of-kode | Creative Commons Zero v1.0 Universal |
src/main/kotlin/aoc2020/ConwayCubes.kt | komu | 113,825,414 | false | {"Kotlin": 395919} | package komu.adventofcode.aoc2020
import komu.adventofcode.utils.nonEmptyLines
fun conwayCubes(input: String, fourDee: Boolean): Int {
var grid = ConwayGrid.parse(input)
repeat(6) {
grid = grid.step(fourDee)
}
return grid.activeCells.size
}
private data class ConwayPoint(val x: Int, val y: Int, val z: Int, val w: Int) {
operator fun plus(p: ConwayPoint) = ConwayPoint(x + p.x, y + p.y, z + p.z, w + p.w)
fun neighbors(fourDee: Boolean) =
neighborDeltas(fourDee).map { this + it }
companion object {
private fun neighborDeltas(fourDee: Boolean) =
sequence {
val ws = if (fourDee) -1..1 else 0..0
for (dx in -1..1)
for (dy in -1..1)
for (dz in -1..1)
for (dw in ws)
if (dx != 0 || dy != 0 || dz != 0 || dw != 0)
yield(ConwayPoint(dx, dy, dz, dw))
}.toList()
}
}
private class ConwayGrid(val activeCells: Set<ConwayPoint>) {
fun step(fourDee: Boolean) =
ConwayGrid(nextGenerationCoordinateCandidates().filter { p ->
val activeNeighbors = p.neighbors(fourDee).count { it in activeCells }
if (p in activeCells)
activeNeighbors == 2 || activeNeighbors == 3
else
activeNeighbors == 3
}.toSet())
private fun nextGenerationCoordinateCandidates() = sequence {
val xs = activeCells.map { it.x }.enlargedRange
val ys = activeCells.map { it.y }.enlargedRange
val zs = activeCells.map { it.z }.enlargedRange
val ws = activeCells.map { it.w }.enlargedRange
for (x in xs)
for (y in ys)
for (z in zs)
for (w in ws)
yield(ConwayPoint(x, y, z, w))
}
companion object {
fun parse(data: String): ConwayGrid {
val grid = data.nonEmptyLines()
val activeCells = mutableSetOf<ConwayPoint>()
for ((y, line) in grid.withIndex())
for ((x, c) in line.withIndex())
if (c == '#')
activeCells += ConwayPoint(x, y, 0, 0)
return ConwayGrid(activeCells)
}
private val List<Int>.enlargedRange: IntRange
get() = (minOrNull()!! - 1)..(maxOrNull()!! + 1)
}
}
| 0 | Kotlin | 0 | 0 | 8e135f80d65d15dbbee5d2749cccbe098a1bc5d8 | 2,450 | advent-of-code | MIT License |
src/year2023/15/Day15.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2023.`15`
import readInput
import utils.printlnDebug
private const val CURRENT_DAY = "15"
data class Label(
val data: String,
val operation: String,
val number: Int?,
) {
override fun toString(): String = "[$data $number]"
}
private fun parseLineInto(
line: String
): List<String> = line.split(",").filter { it.isNotBlank() }
// HASH Algorithm:
// Determine the ASCII code for the current character of the string.
// Increase the current value by the ASCII code you just determined.
// Set the current value to itself multiplied by 17.
// Set the current value to the remainder of dividing itself by 256.
private fun findHash(line: String): Int {
var hash = 0
line.forEach {
hash += it.code
hash *= 17
hash %= 256
}
return hash
}
private fun parseLineIntoLabels(
line: String
): List<Label> {
return line.split(",")
.filter { it.isNotBlank() }
.map {
if (it.contains("=")) {
val list = it.split("=")
Label(
data = list.first(),
operation = "=",
number = list[1].toInt(),
)
} else if (it.contains("-")) {
val list = it.split("-")
Label(
data = list.first(),
operation = "-",
number = null,
)
} else error("Illegal Line $it")
}
}
class MyHashMap {
private val hashMap = List(256) { mutableListOf<Label>() }
fun add(label: Label) {
val hash = findHash(label.data)
hashMap[hash].replaceAll { currentLabel ->
label.takeIf { it.data == currentLabel.data } ?: currentLabel
}
if (hashMap[hash].none { it.data == label.data }) {
hashMap[hash].add(label)
}
}
fun remove(label: Label) {
val hash = findHash(label.data)
hashMap[hash].removeAll { it.data == label.data }
}
override fun toString(): String {
var boxIndex = 0
val string = hashMap.joinToString("") {
boxIndex++
if (it.isNotEmpty()) {
"Box $boxIndex :$it\n"
} else {
""
}
}
return string
}
fun focusPower(): Int {
var sum = 0
hashMap.forEachIndexed { index, labels ->
var partialSum = 0
labels.forEachIndexed { indexInLine, label ->
val resSum = label.number!! * (index + 1) * (indexInLine + 1)
partialSum += resSum
}
sum += partialSum
}
return sum
}
}
fun main() {
fun part1(input: List<String>): Int {
val hashes = parseLineInto(input.first())
.map { findHash(it) }
printlnDebug { hashes }
return hashes.sum()
}
fun part2(input: List<String>): Int {
val mineHashMap = MyHashMap()
parseLineIntoLabels(input.first())
.forEach {
when (it.operation) {
"=" -> mineHashMap.add(it)
"-" -> mineHashMap.remove(it)
}
}
printlnDebug { mineHashMap }
return mineHashMap.focusPower()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${CURRENT_DAY}_test")
val part1Test = part1(testInput)
println(part1Test)
check(part1Test == 1320)
val part2Test = part2(testInput)
println(part2Test)
check(part2Test == 145)
val input = readInput("Day$CURRENT_DAY")
// Part 1
val part1 = part1(input)
println(part1)
check(part1 == 507769)
// Part 2
val part2 = part2(input)
println(part2)
check(part2 == 269747)
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 3,854 | KotlinAdventOfCode | Apache License 2.0 |
src/Day14.kt | JanTie | 573,131,468 | false | {"Kotlin": 31854} | fun main() {
fun Pair<Int, Int>.bottom() = this.copy(second = second + 1)
fun Pair<Int, Int>.bottomLeft() = this.copy(first = first - 1, second = second + 1)
fun Pair<Int, Int>.bottomRight() = this.copy(first = first + 1, second = second + 1)
fun Pair<Int, Int>.move(blockedFields: Set<Pair<Int, Int>>) =
listOf(bottom(), bottomLeft(), bottomRight()).firstOrNull { !blockedFields.contains(it) }
fun parseInput(input: List<String>) = input.flatMap {
it.split(" -> ")
.windowed(2)
.map {
it.map { it.split(",").map { it.toInt() } }.map { (x, y) -> x to y }
}.flatMap {
val (first, second) = it
val (firstX, firstY) = first
val (secondX, secondY) = second
if (firstX != secondX) {
if (firstX < secondX) {
(firstX..secondX)
} else {
(firstX downTo secondX)
}.map { x -> x to firstY }
} else {
if (firstY < secondY) {
(firstY..secondY)
} else {
(firstY downTo secondY)
}.map { y -> firstX to y }
}
}
}
.distinct()
fun part1(input: List<String>): Int {
val blockedFields = parseInput(input)
val maxY = blockedFields.maxOf { it.second }
val startField = 500 to 0
val fields = blockedFields.toMutableSet()
val initialSize = fields.size
var currentField = startField
while (currentField.second < maxY) {
val target = currentField.move(fields)
if (target != null) {
currentField = target
continue
} else {
fields.add(currentField)
currentField = startField
}
}
return fields.size - initialSize
}
fun part2(input: List<String>): Int {
val blockedFields = parseInput(input)
val maxY = blockedFields.maxOf { it.second } + 2
val startField = 500 to 0
val fields = blockedFields.toMutableSet()
val initialSize = fields.size
var currentField = startField
while (startField.move(fields) != null) {
val target = currentField.move(fields)
if (target != null && target.second < maxY) {
currentField = target
continue
} else {
fields.add(currentField)
currentField = startField
}
}
return fields.size - initialSize + 1
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test")
val input = readInput("Day14")
check(part1(testInput) == 24)
println(part1(input))
check(part2(testInput) == 93)
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 3452e167f7afe291960d41b6fe86d79fd821a545 | 2,993 | advent-of-code-2022 | Apache License 2.0 |
konfork-predicates/src/commonMain/kotlin/io/github/konfork/predicates/CheckDigits.kt | konfork | 557,451,504 | false | {"Kotlin": 142473, "Java": 904} | package io.github.konfork.predicates
fun isMod10(evenWeight: Int, oddWeight: Int): (String) -> Boolean {
val weightSequence = alternatingSequence(evenWeight, oddWeight)
return { isMod10(it, weightSequence, Int::times) }
}
fun isEan(length: Int): (String) -> Boolean {
val mod10Fn = isMod10(1, 3)
return { it.length == length && mod10Fn(it) }
}
fun isLuhn(s: String): Boolean =
isAllDigits(s) && validateMod10Checksum(s, alternatingSequence(1, 2)) { l, r ->
(l * r).let { (it / 10) + (it % 10) }
}
private fun isAllDigits(s: String): Boolean = s.all(Char::isDigit)
private val MOD11_DIGITS = Regex("[0-9]+[xX]?")
fun isMod11(weightSequence: Sequence<Int>): (String) -> Boolean = {
it.matches(MOD11_DIGITS) && validateMod11Checksum(it.map(Char::toMod11Int), weightSequence)
}
fun isMod11(startWeight: Int, endWeight: Int): (String) -> Boolean =
isMod11(repeatingCounterSequence(startWeight, endWeight))
private val isMod11Isbn10 = isMod11(9, 1)
fun isIsbn10(s: String): Boolean =
s.replace(Regex("[ -]"), "")
.let { it.length == 10 && isMod11Isbn10(it) }
private val isEan13 = isEan(13)
fun isIsbn13(s: String): Boolean = isEan13(s.replace(Regex("[ -]"), ""))
fun isIsbn(s: String): Boolean = isIsbn10(s) || isIsbn13(s)
private fun isMod10(s: String, weightSequence: Sequence<Int>, map: (Int, Int) -> Int): Boolean =
isAllDigits(s) && validateMod10Checksum(s, weightSequence, map)
private fun validateMod10Checksum(s: String, weightSequence: Sequence<Int>, map: (Int, Int) -> Int): Boolean =
weightedSum(s.map(Char::digitToInt).reversed(), weightSequence, map)
.let { it % 10 == 0 }
private fun alternatingSequence(even: Int, odd: Int): Sequence<Int> =
generateIndexedSequence { it % 2 == 0 }
.map { if (it) even else odd }
private fun <T : Any> generateIndexedSequence(generator: (Int) -> T): Sequence<T> =
generateSequence(0) { index -> index + 1 }
.map(generator)
private fun repeatingCounterSequence(start: Int, end: Int): Sequence<Int> =
if (start <= end) {
generateIndexedSequence { index -> start + index % (end - start + 1) }
} else {
generateIndexedSequence { index -> start - index % (start - end + 1) }
}
private fun validateMod11Checksum(s: List<Int>, weightSequence: Sequence<Int>): Boolean =
weightedSum(s.dropLast(1).reversed(), weightSequence, Int::times)
.let { it % 11 == s.last() }
private fun weightedSum(list: List<Int>, weightSequence: Sequence<Int>, map: (Int, Int) -> Int): Int =
list.asSequence()
.zip(weightSequence, map)
.sum()
private fun Char.toMod11Int(): Int =
when (this) {
'x' -> 10
'X' -> 10
else -> this.digitToInt()
}
| 1 | Kotlin | 0 | 4 | b75e6b96aa7c80efa5095a7763a22fcf614b10d8 | 2,753 | konfork | MIT License |
src/Day07.kt | kuolemax | 573,740,719 | false | {"Kotlin": 21104} | fun main() {
fun part1(input: List<String>): Int {
return findLessThanSizeDirectoryTotalSize(input)
}
fun part2(input: List<String>): Int {
val needSpace = 30_000_000
val totalSize = 70_000_000
return findTheSmallestDirectoryThatShouldBeDeleted(parseToDirectories(input), needSpace, totalSize)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24_933_642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
private fun findTheSmallestDirectoryThatShouldBeDeleted(directories: List<Directory>, needSpace: Int, totalSize: Int): Int {
val currentLeftSpace = totalSize - directories.maxBy { it.totalSize!! }.totalSize!!
val needLeftSpace = needSpace - currentLeftSpace
return directories
.filter { it.totalSize!! >= needLeftSpace }
.minBy { it.totalSize!! }
.totalSize!!
}
private fun findLessThanSizeDirectoryTotalSize(rows: List<String>): Int {
val files = parseToDirectories(rows)
return files.filter { it.totalSize!! < 100_000 }.sumOf { it.totalSize!! }
}
private fun parseToDirectories(rows: List<String>): MutableList<Directory> {
val files = mutableListOf<Directory>()
var currentDir: Directory? = null
rows.forEach { row ->
val trimRow = row.trim()
if (trimRow[0].isDigit()) {
// 文件
val (size, _) = trimRow.split(" ")
currentDir!!.size += size.toInt()
} else if (trimRow.startsWith("$ cd")) {
// 切换目录
val changeDirName = trimRow.replace("$ cd ", "")
// 返回上级目录
if (".." == changeDirName) {
currentDir = currentDir?.parent
} else {
val file = Directory(
name = changeDirName,
parent = currentDir
)
currentDir = file
files.add(file)
}
}
}
for (file in files) {
file.totalSize = computeTotalSize(file, files)
}
return files
}
data class Directory(
var name: String,
var parent: Directory? = null,
var size: Int = 0,
var totalSize: Int? = null,
var children: MutableList<Directory> = mutableListOf()
)
private fun computeTotalSize(file: Directory, files: List<Directory>): Int {
// 如果 totalSize 不为 null, 是设置过值的
if (file.totalSize != null) {
return file.totalSize!!.toInt()
}
// 找出所有子集的 totalSize
val children = files.filter { it.parent == file }
if (children.isEmpty()) {
// 叶子
return file.size
}
// 非叶子
var totalSize: Int = file.size
for (child in children) {
if (child.totalSize == null) {
totalSize += computeTotalSize(child, files)
continue
}
totalSize += child.totalSize!!.toInt()
}
return totalSize
} | 0 | Kotlin | 0 | 0 | 3045f307e24b6ca557b84dac18197334b8a8a9bf | 3,089 | aoc2022--kotlin | Apache License 2.0 |
src/Day09.kt | jwalter | 573,111,342 | false | {"Kotlin": 19975} | import kotlin.math.absoluteValue
fun main() {
data class Knot(var x: Int, var y: Int)
val down = 0 to -1
val up = 0 to 1
val right = 1 to 0
val left = -1 to 0
val visited = mutableSetOf<Pair<Int, Int>>()
fun moveInDirection(direction: Pair<Int, Int>, knots: List<Knot>) {
val h = knots.first()
h.x += direction.first
h.y += direction.second
knots.drop(1).forEachIndexed { index, knot ->
val delta = knots[index].x - knot.x to knots[index].y - knot.y
if (delta.first == 0 && delta.second.absoluteValue > 1) {
knot.y += delta.second / 2
} else if (delta.second == 0 && delta.first.absoluteValue > 1) {
knot.x += delta.first / 2
} else if (delta.first.absoluteValue + delta.second.absoluteValue > 2) {
knot.x += if (delta.first.absoluteValue > 1) {
delta.first / delta.first.absoluteValue
} else delta.first
knot.y += if (delta.second.absoluteValue > 1) {
delta.second / delta.second.absoluteValue
} else delta.second
}
}
val t = knots.last()
visited.add(t.x to t.y)
}
fun move(direction: String, knots: List<Knot>) {
when (direction) {
"D" -> moveInDirection(down, knots)
"U" -> moveInDirection(up, knots)
"R" -> moveInDirection(right, knots)
"L" -> moveInDirection(left, knots)
}
}
fun computeCoverage(input: List<String>, knots: List<Knot>) {
val moves = input.map { it.take(1) to it.drop(2).toInt() }
visited.clear()
visited.add(0 to 0)
val x =
moves.forEach { move ->
repeat(move.second) {
move(move.first, knots)
}
}
}
fun part1(input: List<String>): Int {
val knots = listOf(Knot(0,0), Knot(0,0))
computeCoverage(input, knots)
return visited.size
}
fun part2(input: List<String>): Int {
val knots = (0..9).map { Knot(0,0) }
computeCoverage(input, knots)
return visited.size
}
val testInput = readInput("Day09_test")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 576aeabd297a7d7ee77eca9bb405ec5d2641b441 | 2,427 | adventofcode2022 | Apache License 2.0 |
src/Day04.kt | BjornstadThomas | 572,616,128 | false | {"Kotlin": 9666} | fun main() {
fun splitString(input: String): List<Pair<Pair<Int, Int>, Pair<Int, Int>>> {
// val inputSplit = input.split("\r\n")
val inputSplit = input.lines().map {
val list = it.split(",").map { it.split("-") }
// println(list)
(list[0][0].toInt() to list[0][1].toInt()) to (list[1][0].toInt() to list[1][1].toInt())
}
println(inputSplit)
return inputSplit
}
fun checkIfItContainsFully(firstRange: Pair<Int, Int>, secondRange: Pair<Int, Int>): Boolean {
return firstRange.first <= secondRange.first && firstRange.second >= secondRange.second
}
fun getNumberOfPairsWithSectionsFullyOverlapping(liste: List<Pair<Pair<Int,Int>,Pair<Int,Int>>>): String {
return liste.count {checkIfItContainsFully(it.first, it.second) || checkIfItContainsFully(it.second, it.first) }.toString()
}
fun checkIfItContainsParts(firstRange: Pair<Int, Int>, secondRange: Pair<Int, Int>): Boolean {
return firstRange.first <= secondRange.first && firstRange.second >= secondRange.first
}
fun getNumberOfPairsWithSectionsParlyOverlapping(liste: List<Pair<Pair<Int,Int>,Pair<Int,Int>>>): String {
return liste.count {checkIfItContainsParts(it.first, it.second) || checkIfItContainsParts(it.second, it.first) }.toString()
}
fun part1(input: String): String {
val liste = splitString(input)
val containsFully = getNumberOfPairsWithSectionsFullyOverlapping(liste)
return containsFully
}
fun part2(input: String): String {
val liste = splitString(input)
val containsParts = getNumberOfPairsWithSectionsParlyOverlapping(liste)
return containsParts
}
val input = readInput("input_Day04")
println("Antall par hvor det dekker hverandres range fullstending (Del 1): " + part1(input))
println("Antall par hvor det delvis dekker hverandres range (Del 2): " + part2(input))
}
| 0 | Kotlin | 0 | 0 | 553e3381ca26e1e316ecc6c3831354928cf7463b | 1,973 | AdventOfCode-2022-Kotlin | Apache License 2.0 |
src/day05.kts | miedzinski | 434,902,353 | false | {"Kotlin": 22560, "Shell": 113} | data class Point(val x: Int, val y: Int)
class Line(val from: Point, val to: Point) {
fun isHorizontalOrVertical(): Boolean =
from.x == to.x || from.y == to.y
fun points(): Sequence<Point> {
fun diff(selector: (Point) -> Int): Int {
val from = selector(from)
val to = selector(to)
return when {
from < to -> 1
from > to -> -1
else -> 0
}
}
val dx = diff { it.x }
val dy = diff { it.y }
return generateSequence(from) {
with(it) { Point(x + dx, y + dy) }
}.takeWhile { it != to }
}
}
object Grid {
val points = mutableMapOf<Point, Int>().withDefault { 0 }
fun insert(point: Point) {
points[point] = points.getValue(point) + 1
}
fun countOverlapping(): Int = points.count { it.value > 1 }
}
val linePattern = "(\\d+),(\\d+) -> (\\d+),(\\d+)".toRegex()
val (horizontalsAndVerticals, diagonals) = generateSequence(::readLine).map {
val (x1, y1, x2, y2) = linePattern
.matchEntire(it)!!
.destructured
.toList()
.map(String::toInt)
Line(Point(x1, y1), Point(x2, y2))
}.partition { it.isHorizontalOrVertical() }
fun solve(lines: List<Line>): Int {
lines.asSequence()
.flatMap(Line::points)
.forEach(Grid::insert)
return Grid.countOverlapping()
}
println("part1: ${solve(horizontalsAndVerticals)}")
println("part2: ${solve(diagonals)}")
| 0 | Kotlin | 0 | 0 | 6f32adaba058460f1a9bb6a866ff424912aece2e | 1,502 | aoc2021 | The Unlicense |
2021/src/day22/Solution.kt | vadimsemenov | 437,677,116 | false | {"Kotlin": 56211, "Rust": 37295} | package day22
import java.nio.file.Files
import java.nio.file.Paths
import kotlin.system.measureTimeMillis
fun main() {
fun MutableList<Int>.inPlaceDistinct() {
sort()
var ptr = 1
for (i in 1 until this.size) {
if (this[i] != this[i - 1]) {
this[ptr++] = this[i]
}
}
while (size > ptr) {
removeLast()
}
}
fun solve(input: Input): Long {
val all = Array(3) { mutableListOf<Int>() }
for ((_, cuboid) in input) {
for (i in cuboid.indices) {
all[i].addAll(cuboid[i])
}
}
all.forEach { it.inPlaceDistinct() }
val (xs, ys, zs) = all
val state = Array(xs.size - 1) { Array(ys.size - 1) { BooleanArray(zs.size - 1) } }
for ((on, cuboid) in input) {
val (xRange, yRange, zRange) = cuboid.mapIndexed { index, interval ->
val (from, to) = interval.map { all[index].binarySearch(it) }
from until to
}
for (x in xRange) {
for (y in yRange) {
for (z in zRange) {
state[x][y][z] = on
}
}
}
}
var answer = 0L
for (i in state.indices) {
for (j in state[i].indices) {
for (k in state[i][j].indices) {
if (state[i][j][k]) {
answer += 1L * (xs[i + 1] - xs[i]) * (ys[j + 1] - ys[j]) * (zs[k + 1] - zs[k])
}
}
}
}
return answer
}
fun part1(input: Input): Int {
return solve(
input.filter { (_, cuboid) ->
cuboid.all { (from, to) -> from in -50..50 && to in -49..51 }
}
).toInt()
}
fun part2(input: Input): Long {
return solve(input)
}
check(part1(readInput("test-input.txt")) == 590784)
check(part2(readInput("test-input2.txt")) == 2758514936282235L)
val millis = measureTimeMillis {
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
System.err.println("Done in $millis ms")
}
private fun readInput(s: String): Input {
return Files.newBufferedReader(Paths.get("src/day22/$s")).readLines().map { line ->
val on = line.startsWith("on ")
if (!on) check(line.startsWith("off "))
val list = line.substring(if (on) 3 else 4).split(",").mapIndexed { index, range ->
check(range.matches("${"xyz"[index]}=-?\\d+..-?\\d+".toRegex()))
val (from, to) = range.substring(2).split("..").map { it.toInt() }
listOf(from, to + 1)
}
Pair(on, list)
}
}
private typealias Input = List<Pair<Boolean, List<List<Int>>>> | 0 | Kotlin | 0 | 0 | 8f31d39d1a94c862f88278f22430e620b424bd68 | 2,486 | advent-of-code | Apache License 2.0 |
src/Day08.kt | joshpierce | 573,265,121 | false | {"Kotlin": 46425} | import java.io.File
fun main() {
var lines: List<String> = File("Day08.txt").readLines()
// Setup our Forest List of Lists
var forest = lines.map { it.chunked(1) }
// Variable for Tracking Tree Score in Part Two
var maxTreeScore = 0
// Prints out your forest for you to see
//forest.forEach { it.forEach { print(it+" ") }; println() }
// Iterate Our Forest Rows
var visibleForest = forest.mapIndexed { idx, row ->
// Iterate Our Forest Columns
row.mapIndexed row@ { idx2, tree ->
// Get All Trees Above, Below, Left, and Right of Current Tree
var treesLeft = forest[idx].subList(0, idx2).reversed()
var treesRight = forest[idx].subList(idx2+1, forest[idx].size)
var treesAbove = forest.subList(0, idx).map { it[idx2] }.reversed()
var treesBelow = forest.subList(idx+1, forest.size).map { it[idx2] }
// For Part Two, we need to know how many trees are visible from each tree
var visibleTreesLeft = treesLeft.takeWhileInclusive { it < tree }.count()
var visibleTreesRight = treesRight.takeWhileInclusive { it < tree }.count()
var visibleTreesAbove = treesAbove.takeWhileInclusive { it < tree }.count()
var visibleTreesBelow = treesBelow.takeWhileInclusive { it < tree }.count()
//println("Tree: $idx, $idx2 -> $visibleTreesLeft, $visibleTreesRight, $visibleTreesAbove, $visibleTreesBelow")
// For Part Two Calculate The Tree Score and see if it's the new Max Tree Score
var treeScore = visibleTreesLeft * visibleTreesRight * visibleTreesAbove * visibleTreesBelow
if (treeScore > maxTreeScore) {
//println("Tree: $idx, $idx2 -> $treeScore [Current Max Tree Score]")
maxTreeScore = treeScore
} else {
//println("Tree: $idx, $idx2 -> $treeScore")
}
// If this is an edge tree, it's visible
if (idx == 0 || idx2 == 0 || idx == forest.size - 1 || idx2 == row.size - 1) {
//println("Edge: $idx, $idx2")
return@row 1
} else {
// If this is not an edge tree, check if it's visible from one of the edges
if (tree > treesLeft.sortedDescending()[0] ||
tree > treesRight.sortedDescending()[0] ||
tree > treesAbove.sortedDescending()[0] ||
tree > treesBelow.sortedDescending()[0])
{
//println("Not Edge: $idx, $idx2 -> Visible")
return@row 1
} else {
//println("Not Edge: $idx, $idx2 -> Not Visible")
return@row 0
}
}
}
}
// Print out the Visible Forest
//visibleForest.forEach { it.forEach { print(it.toString() + " ") }; println() }
// Display the Total Visible Trees and Max Tree Score
println("Total Visible Trees: " + visibleForest.map { it.sum() }.sum().toString())
println("Max Tree Score: " + maxTreeScore.toString())
}
// Added this function which I found here: https://stackoverflow.com/questions/56058246/takewhile-which-includes-the-actual-value-matching-the-predicate-takewhileinclu
// The existing TakeWhile in Kotlin doesn't include the value that matches the predicate, which is what we need for this problem.
fun <T> List<T>.takeWhileInclusive(predicate: (T) -> Boolean) = sequence {
with(iterator()) {
while (hasNext()) {
val next = next()
yield(next)
if (!predicate(next)) break
}
}
}
| 0 | Kotlin | 0 | 1 | fd5414c3ab919913ed0cd961348c8644db0330f4 | 3,735 | advent-of-code-22 | Apache License 2.0 |
kotlin/src/main/kotlin/year2023/Day01.kt | adrisalas | 725,641,735 | false | {"Kotlin": 130217, "Python": 1548} | package year2023
fun main() {
val input = readInput("Day01")
Day01.part1(input).println()
Day01.part2(input).println()
}
object Day01 {
fun part1(input: List<String>): Int {
return input.sumOf { line ->
val results = "[0-9]".toRegex().findAll(line)
val firstDigit = results.first().value
val lastDigit = results.last().value
"$firstDigit$lastDigit".toInt()
}
}
/**
* If we just use toRegex().findAll(line) then the last() may not be correct
* as we could have collision between some elements:
*
* Example: "twoeightwo"
* - Expected output -> 22
* - Using first() and last() -> 28. This is due to the collision with the t in: "eighTwo".
*
* This can be avoided finding the "first" match starting from the last part of the string.
*
* See: [Regex.lastMatch]
*/
fun part2(input: List<String>): Int {
return input.sumOf { line ->
val regex = "[0-9]|one|two|three|four|five|six|seven|eight|nine".toRegex()
val firstDigit = regex.firstMatch(line)?.toSingleDigit() ?: 0
val lastDigit = regex.lastMatch(line)?.toSingleDigit() ?: 0
"$firstDigit$lastDigit".toInt()
}
}
private fun Regex.firstMatch(line: String): String? {
return this.find(line)?.value
}
private fun Regex.lastMatch(line: String): String? {
var lastMatch: String? = null
var position = line.length
while (lastMatch == null && position >= 0) {
lastMatch = this.find(line, position)?.value
position--
}
return lastMatch
}
private fun String.toSingleDigit(): Int {
return when (this) {
"0", "zero" -> 0
"1", "one" -> 1
"2", "two" -> 2
"3", "three" -> 3
"4", "four" -> 4
"5", "five" -> 5
"6", "six" -> 6
"7", "seven" -> 7
"8", "eight" -> 8
"9", "nine" -> 9
else -> error("Invalid input")
}
}
}
| 0 | Kotlin | 0 | 2 | 6733e3a270781ad0d0c383f7996be9f027c56c0e | 2,118 | advent-of-code | MIT License |
src/Day02.kt | kpilyugin | 572,573,503 | false | {"Kotlin": 60569} | fun main() {
fun part1(input: List<String>): Int {
return input.sumOf {
val (a, b) = it.split(" ")
val their = a[0] - 'A'
val our = b[0] - 'X'
val score = when ((our - their + 3) % 3) {
1 -> 6
2 -> 0
else -> 3
}
our + 1 + score
}
}
fun part2(input: List<String>): Int {
return input.sumOf {
val (a, b) = it.split(" ")
val their = a[0] - 'A'
val our = when (b[0]) {
'X' -> (their + 2) % 3
'Y' -> their
else /*'Z'*/ -> (their + 1) % 3
}
val score = when (b[0]) {
'Y' -> 3
'Z' -> 6
else -> 0
}
our + 1 + score
}
}
val testInput = readInputLines("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInputLines("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 7f0cfc410c76b834a15275a7f6a164d887b2c316 | 1,073 | Advent-of-Code-2022 | Apache License 2.0 |
grind-75-kotlin/src/main/kotlin/BinarySearch.kt | Codextor | 484,602,390 | false | {"Kotlin": 27206} | /**
* Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums.
* If target exists, then return its index. Otherwise, return -1.
*
* You must write an algorithm with O(log n) runtime complexity.
*
*
*
* Example 1:
*
* Input: nums = [-1,0,3,5,9,12], target = 9
* Output: 4
* Explanation: 9 exists in nums and its index is 4
* Example 2:
*
* Input: nums = [-1,0,3,5,9,12], target = 2
* Output: -1
* Explanation: 2 does not exist in nums so return -1
*
*
* Constraints:
*
* 1 <= nums.length <= 10^4
* -10^4 < nums[i], target < 10^4
* All the integers in nums are unique.
* nums is sorted in ascending order.
* @see <a href="https://leetcode.com/problems/binary-search/">LeetCode</a>
*/
fun search(nums: IntArray, target: Int): Int {
return binarySearch(nums, target, 0, nums.size - 1)
}
private fun binarySearch(nums: IntArray, target: Int, start: Int, end: Int): Int {
if (start > end) {
return -1
}
val mid: Int = start + ((end - start) / 2)
return when {
nums[mid] == target -> mid
nums[mid] > target -> binarySearch(nums, target, start, mid - 1)
else -> binarySearch(nums, target, mid + 1, end)
}
}
| 0 | Kotlin | 0 | 0 | 87aa60c2bf5f6a672de5a9e6800452321172b289 | 1,260 | grind-75 | Apache License 2.0 |
src/Day04.kt | Derrick-Mwendwa | 573,947,669 | false | {"Kotlin": 8707} | fun main() {
val regex = Regex("""([0-9]+)-([0-9]+),([0-9]+)-([0-9]+)""")
fun part1(input: List<String>): Int {
val sections = input.map {
val (m1, m2, m3, m4) = regex.matchEntire(it)!!.destructured
IntRange(m1.toInt(), m2.toInt()) to IntRange(m3.toInt(), m4.toInt())
}
val duplicates = sections.map {
val intersect = it.first intersect it.second
if (intersect == it.first.toSet() || intersect == it.second.toSet()) 1 else 0
}
return duplicates.sum()
}
fun part2(input: List<String>): Int {
val sections = input.map {
val (m1, m2, m3, m4) = regex.matchEntire(it)!!.destructured
IntRange(m1.toInt(), m2.toInt()) to IntRange(m3.toInt(), m4.toInt())
}
val duplicates = sections.map {
val intersect = it.first intersect it.second
if (intersect.isNotEmpty()) 1 else 0
}
return duplicates.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 7870800afa54c831c143b5cec84af97e079612a3 | 1,230 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day03.kt | aaronbush | 571,776,335 | false | {"Kotlin": 34359} | import java.util.stream.Collectors.toSet
fun main() {
val priority = ('a'..'z').withIndex().associate { it.value to it.index + 1 } +
('a'..'z').withIndex().associate { it.value.uppercaseChar() to it.index + 27 }
fun String.bisect() = this.chunked(this.length / 2)
fun part1(input: List<String>): Int {
val compartments = input.map { it.bisect() }
val items = compartments.map { packContents ->
packContents.map { it.toSet() }
}
val commonItems = items.flatMap { packContents ->
packContents[0].intersect(packContents[1])
}
val packItemPriority = commonItems.map { priority.getOrDefault(it, 0) }
// println(compartments)
// println(items)
// println(commonItems)
// println(packItemPriority)
return packItemPriority.sum()
}
fun part2(input: List<String>): Int {
val groups = input.chunked(3)
val groupsItems = groups.map { groupItems ->
groupItems.map { it.toSet() }
}
val commonItems = groupsItems.flatMap { it[0].intersect(it[1]).intersect(it[2]) }
val groupItemPriority = commonItems.map { priority.getOrDefault(it, 0) }
// println(groupsItems)
// println(commonItems)
// println(groupItemPriority)
return groupItemPriority.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d76106244dc7894967cb8ded52387bc4fcadbcde | 1,643 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2021/2021-21.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2021
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputLines
import kotlin.math.max
fun main() {
val input = readInputLines(2021, "21-input")
val test1 = readInputLines(2021, "21-test1")
println("Part1:")
part1(test1).println()
part1(input).println()
println()
println("Part2:")
part2(test1).println()
part2(input).println()
}
private fun part1(input: List<String>): Int {
val players = input.map { Player(regex.matchEntire(it)!!.groupValues[1].toInt()) }.toMutableList()
val die = DeterministicDie(100)
var game = Game(players)
while (true) {
game = game.play(die.roll(3))
if (game.wins(1000) != -1) return die.count * game.players.minOf { it.score }
}
}
private fun part2(input: List<String>): Long {
val players = input.map { Player(regex.matchEntire(it)!!.groupValues[1].toInt()) }
val initialGame = Game(players)
cache.clear()
val results = initialGame.playDirac(21)
return max(results.first, results.second)
}
private val cache = mutableMapOf<Game, Pair<Long, Long>>()
private fun Game.playDirac(goal: Int): Pair<Long, Long> {
val cached = cache[this]
if (cached != null) return cached
var totalP1 = 0L
var totalP2 = 0L
possibleDiracRolls.forEach { (roll, count) ->
val newGame = play(roll)
val winner = newGame.wins(goal)
if (winner != -1) {
if (winner == 0) {
totalP1 += count
} else {
totalP2 += count
}
} else {
val (p1, p2) = newGame.playDirac(goal)
totalP1 += p1 * count
totalP2 += p2 * count
}
}
return (totalP1 to totalP2).also { cache[this] = it }
}
private val possibleDiracRolls: Map<Int, Int> by lazy {
val possible = mutableListOf<Int>()
for (i in 1..3) {
for (j in 1..3) {
for (k in 1..3) {
possible += i + j + k
}
}
}
possible.groupingBy { it }.eachCount()
}
private data class Game(val players: List<Player>, val currentPlayer: Int = 0)
private fun Game.play(roll: Int): Game {
val newPlayer = players[currentPlayer].move(roll)
val newPlayers = players.mapIndexed { index, player -> if (index != currentPlayer) player else newPlayer }
val nextIndex = (currentPlayer + 1) % players.size
return Game(newPlayers, nextIndex)
}
private fun Game.wins(goal: Int): Int = players.indexOfFirst { goal <= it.score }
private data class Player(val position: Int, val score: Int = 0)
private fun Player.move(roll: Int): Player {
var newPosition = position
newPosition += (roll % 10)
if (10 < newPosition) newPosition -= 10
return Player(newPosition, score + newPosition)
}
private class DeterministicDie(val max: Int) {
private var current = 1
var count: Int = 0
private set
fun roll(): Int {
count++
val result = current
current += 1
if (max < current) current -= max
return result
}
fun roll(count: Int): Int {
var result = 0
repeat(count) { result += roll() }
return result
}
}
private val regex = """Player \d starting position: (\d+)""".toRegex()
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 3,342 | advent-of-code | MIT License |
src/main/kotlin/dev/bogwalk/batch4/Problem41.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch4
import dev.bogwalk.util.combinatorics.permutations
import dev.bogwalk.util.maths.isPrime
import dev.bogwalk.util.strings.isPandigital
import kotlin.math.pow
/**
* Problem 41: Pandigital Prime
*
* https://projecteuler.net/problem=41
*
* Goal: Find the largest pandigital prime <= N or return -1 if none exists.
*
* Constraints: 10 <= N < 1e10
*
* e.g.: N = 100
* return -1, as no 2-digit pandigital primes exist; however,
* N = 10_000
* return 4231, as the smallest pandigital prime.
*/
class PandigitalPrime {
/**
* Project Euler specific implementation that returns the largest n-digit pandigital prime
* that exists.
*
* This solution checks primality of all pandigital permutations backwards starting from 9
* digits.
*
* N.B. There are only 538 pandigital primes & they are all either 4-/7-digit pandigitals, as
* explained in following function below.
*/
fun largestPandigitalPrimePE(): Int {
val magnitudes = List(9) { d -> (10.0).pow(d).toInt() }
println()
var n = 987_654_321
var digits = 9
var limit = magnitudes[digits - 1]
while (true) {
if (n.toString().isPandigital(digits) && n.isPrime()) break
n -= 2
if (n < limit) {
digits--
limit = magnitudes[digits - 1]
}
}
return n
}
fun largestPandigitalPrimeHR(n: Long): Int {
if (n < 1423L) return -1
return allPandigitalPrimes()
.asSequence()
.filter { it.toLong() <= n }
.first()
}
/**
* Solution optimised based on the following:
*
* - The smallest pandigital prime is 4-digits -> 1423.
*
* - Found using the brute force backwards search in the function above, the largest
* pandigital prime is 7-digits -> 7_652_413.
*
* - The above 2 proven bounds confirm that only 4- & 7-digit pandigitals can be prime
* numbers as all primes greater than 3 are of the form 6p(+/- 1) & so cannot be multiples
* of 3. If the sum of a pandigital's digits is a multiple of 3, then that number will be a
* multiple of 3 & thereby not a prime. Only 4- & 7-digit pandigitals have sums that are not
* divisible by 3.
*
* @return list of all pandigital primes sorted in descending order.
*/
private fun allPandigitalPrimes(): List<Int> {
val pandigitalPrimes = mutableListOf<Int>()
val digits = (7 downTo 1).toMutableList()
repeat(2) {
for (perm in permutations(digits, digits.size)) {
val num = perm.joinToString("").toInt()
if (num.isPrime()) {
pandigitalPrimes.add(num)
}
}
digits.removeIf { it > 4 }
}
return pandigitalPrimes.sortedDescending()
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 2,954 | project-euler-kotlin | MIT License |
src/Day07.kt | pmellaaho | 573,136,030 | false | {"Kotlin": 22024} | sealed class Node(val id: String) {
var parent: Folder? = null
var children: MutableList<Node> = mutableListOf()
fun addNode(node: Node) {
children.add(node)
}
fun findRoot(): Node {
var root = this
while (root.parent != null) {
root = root.parent!!
}
return root
}
abstract fun getContainedSize(): Int
override fun toString(): String {
var s = id
if (children.isNotEmpty()) {
s += " {" + children.map { it.toString() } + " }"
}
return s
}
}
class File(id: String, private val size: Int = 0) : Node(id) {
override fun getContainedSize() = size
companion object {
fun fromString(input: String): File {
val name = input.substringAfter(" ")
val size = input.substringBefore(" ").toInt()
return File(name, size)
}
}
}
class Folder(id: String) : Node(id) {
fun subdirectories(): List<Folder> {
val dirs: MutableList<Folder> = mutableListOf()
children.forEach {
if (it is Folder) {
dirs.add(it)
dirs.addAll(it.subdirectories())
}
}
return dirs
}
override fun getContainedSize(): Int {
return children.sumOf { it.getContainedSize() }
}
}
fun String.isCdRootCmd() = contains("cd /")
fun String.isDir() = contains("dir ")
fun String.isFile() = first().isDigit()
fun String.isPreviousDirCmd() = contains("cd ..")
fun String.isCdCmd() = contains(" cd ")
fun main() {
fun initDirTree(input: List<String>): Node {
var currentDir = Folder("/")
input.forEach {
when {
it.isCdRootCmd() -> {}
it.isDir() -> {
val node = Folder(it.substringAfter(" "))
node.parent = currentDir
currentDir.addNode(node)
}
it.isFile() -> {
val node = File.fromString(it)
node.parent = currentDir
currentDir.addNode(node)
}
it.isPreviousDirCmd() -> {
currentDir = currentDir.parent ?: currentDir
}
it.isCdCmd() -> {
currentDir = currentDir.children
.first { child -> child.id == it.substringAfter("cd ") } as Folder
}
else -> {}
}
}
return currentDir.findRoot()
}
/**
* find all of the directories with a total size of at most 100000,
* then calculate the sum of their total sizes.
*/
fun part1(input: List<String>): Int {
val root = initDirTree(input) as Folder
return root.subdirectories().filter {
it.getContainedSize() <= 1_000_00
}.sumOf { it.getContainedSize() }
}
/**
* Find the smallest directory that, if deleted, would free up enough (at least 8381165)
* space on the filesystem to run the update.
*/
fun part2(input: List<String>): Int {
val root = initDirTree(input) as Folder
val totalSpace = 70_000_000
val usedSpace = root.getContainedSize()
val freeSpace = totalSpace - usedSpace
val neededSpace = 30_000_000
val minSpaceToFree = neededSpace - freeSpace
return root.subdirectories().filter {
it.getContainedSize() >= minSpaceToFree
}.minByOrNull { it.getContainedSize() }!!.getContainedSize()
}
// test if implementation meets criteria from the description, like:
// val testInput = readInput("Day07_test")
// val res1 = part1(testInput)
// check(res1 == 95_437)
// val res2 = part2(testInput)
// check(res2 == 24_933_642) // test passes
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | cd13824d9bbae3b9debee1a59d05a3ab66565727 | 3,926 | AoC_22 | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem1061/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem1061
/**
* LeetCode page: [1061. Lexicographically Smallest Equivalent String](https://leetcode.com/problems/lexicographically-smallest-equivalent-string/);
*/
class Solution {
/* Complexity:
* Time O(M+N) and Space O(1) where M and N are the length of s1 and baseStr;
*/
fun smallestEquivalentString(s1: String, s2: String, baseStr: String): String {
return EquivalencyUnionFind().let {
it.union(s1, s2)
it.findSmallestEquivalentString(baseStr)
}
}
private class EquivalencyUnionFind {
/* Store the equivalency between lowercase. A lowercase is the parent of another if they are
* equivalent and its id is smaller. Here the so-called id is the distance from lowercase to
* 'a'. The initial parent of a lowercase is set to itself;
*/
private val parentIds = IntArray(26) { it }
fun findSmallestParent(char: Char): Char {
val id = char.id()
return 'a' + findSmallestParentId(id)
}
private fun Char.id(): Int {
require(this in 'a'..'z') { "Require lowercase" }
return this - 'a'
}
private fun findSmallestParentId(id: Int): Int {
var currId = id
while (currId != parentIds[currId]) {
currId = parentIds[currId]
}
return currId
}
fun union(char1: Char, char2: Char) {
unionBySmallerParentId(char1.id(), char2.id())
}
private fun unionBySmallerParentId(id1: Int, id2: Int) {
val parentId1 = findSmallestParentId(id1)
val parentId2 = findSmallestParentId(id2)
val (small, large) = if (parentId1 <= parentId2) parentId1 to parentId2 else parentId2 to parentId1
parentIds[id1] = small
parentIds[id2] = small
parentIds[large] = small
}
}
private fun EquivalencyUnionFind.union(s1: String, s2: String) {
require(s1.length == s2.length)
for (index in s1.indices) {
union(s1[index], s2[index])
}
}
private fun EquivalencyUnionFind.findSmallestEquivalentString(baseStr: String): String {
return buildString {
for (char in baseStr) {
val smallestEquivalentChar = findSmallestParent(char)
append(smallestEquivalentChar)
}
}
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,476 | hj-leetcode-kotlin | Apache License 2.0 |
src/cn/leetcode/codes/simple1/SimpleKotlin1.kt | shishoufengwise1234 | 258,793,407 | false | {"Java": 771296, "Kotlin": 68641} | package cn.leetcode.codes.simple1
import java.util.*
/*
*
* 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*
*/
/*
解题思路:
1. 对于数组内部两个值求和 一定会涉及到遍历、有可能集合是无序的、所以 必须采用遍历、而且是双层for循环进行遍历、才能数组里全部判断不能遗漏、
所以 外城循环即 正常循环数量、内层循环就是 外层循环的 -1
*/
fun main(array: Array<String>) {
val intArr = intArrayOf(2,3,9,7,23,78)
// val intArr = intArrayOf(3, 3)
val re1 = printIndex(intArr, 26)
val re2 = Simple_1_2().twoSum(intArr,26)
println(" re1 = ${Arrays.toString(re1)}")
println(" re2 = ${Arrays.toString(re2)}")
}
// kotlin 实现版本
private fun printIndex(intArr: IntArray, target: Int): IntArray {
var text: String? = null
var a: Int = 0
var b: Int = 0
val re = IntArray(2)
for (i in intArr.indices) {
println(" i = $i")
for (j in i + 1..intArr.size-1) {
if (intArr[i] + intArr[j] == target) {
a = i
b = j
text = " i = $i ,j = $j"
re[0] = i
re[1] = j
}
}
}
println("查询到结果 :text = $text , 数据: ${intArr[a]} ,${intArr[b]}")
return re
}
| 0 | Java | 0 | 0 | f917a262bcfae8cd973be83c427944deb5352575 | 1,867 | LeetCodeSimple | Apache License 2.0 |
src/_2022/Day03.kt | albertogarrido | 572,874,945 | false | {"Kotlin": 36434} | package _2022
import readInput
import java.lang.IllegalArgumentException
fun main() {
runTests(readInput("2022", "day03_test"))
runScenario(readInput("2022", "day03"))
}
private fun runScenario(input: List<String>) {
val rucksacks = input.map { buildRucksacks(it) }
println(part1(rucksacks))
println(part2(input))
}
private fun part1(input: List<Pair<String, String>>) = input.sumOf { rucksack ->
rucksack.first.first { it in rucksack.second }.priorityValue()
}
private fun part2(input: List<String>) = input.chunked(3).sumOf { group ->
group[0].first { it in group[1] && it in group[2] }.priorityValue()
}
private fun buildRucksacks(input: String) =
Pair(input.substring(0, input.length / 2), input.substring(input.length / 2, input.length))
/**
*Lowercase item types a through z have priorities 1 through 26.
*Uppercase item types A through Z have priorities 27 through 52.
*/
private fun Char.priorityValue(): Int {
if (!isLetter()) throw IllegalArgumentException("not a letter")
return if (isUpperCase()) {
code - 38
} else {
code - 96
}
}
private fun runTests(testInput: List<String>) {
val testRucksacks = testInput.map { buildRucksacks(it) }
val result = part1(testRucksacks)
check(result == 157) {
"expected 157, obtained $result"
}
val result2 = part2(testInput)
check(result2 == 70) {
"expected 70, obtained $result2"
}
}
| 0 | Kotlin | 0 | 0 | ef310c5375f67d66f4709b5ac410d3a6a4889ca6 | 1,451 | AdventOfCode.kt | Apache License 2.0 |
src/year_2021/day_06/Day06.kt | scottschmitz | 572,656,097 | false | {"Kotlin": 240069} | package year_2021.day_06
import readInput
import java.math.BigInteger
data class LanternFish(
val spawnTimer: Int,
val quantity: BigInteger,
) {
fun advance(): List<LanternFish> {
val newTime = spawnTimer - 1
return if (newTime < 0) {
listOf(
LanternFish(6, quantity),
LanternFish(8, quantity)
)
} else {
listOf(
LanternFish(newTime, quantity)
)
}
}
}
object Day06 {
/**
* @return
*/
fun solutionOne(text: String): BigInteger {
var fish = parseFish(text)
for (i in 0 until 80) {
fish = fish.flatMap { it.advance() }
.groupBy { it.spawnTimer }
.map { (timer, fishes) ->
LanternFish(
spawnTimer = timer,
quantity = fishes.sumOf { it.quantity }
)
}
}
return fish.sumOf { it.quantity }
}
/**
* @return
*/
fun solutionTwo(text: String): BigInteger {
var fish = parseFish(text)
for (i in 0 until 256) {
fish = fish.flatMap { it.advance() }
.groupBy { it.spawnTimer }
.map { (timer, fishes) ->
LanternFish(
spawnTimer = timer,
quantity = fishes.sumOf { it.quantity }
)
}
}
return fish.sumOf { it.quantity }
}
private fun parseFish(text: String): List<LanternFish> {
return text
.split(",")
.map { Integer.parseInt(it) }
.groupBy { it }
.map { (timer, fish) ->
LanternFish(timer, fish.size.toBigInteger())
}
}
}
fun main() {
val inputText = readInput("year_2021/day_06/Day06.txt")
val solutionOne = Day06.solutionOne(inputText.first())
println("Solution 1: $solutionOne")
val solutionTwo = Day06.solutionTwo(inputText.first())
println("Solution 2: $solutionTwo")
} | 0 | Kotlin | 0 | 0 | 70efc56e68771aa98eea6920eb35c8c17d0fc7ac | 2,126 | advent_of_code | Apache License 2.0 |
y2017/src/main/kotlin/adventofcode/y2017/Day25.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2017
import adventofcode.io.AdventSolution
object Day25 : AdventSolution(2017, 25, "The Halting Problem") {
override fun solvePartOne(input: String): String {
val (stepsUntilDiagnostic, turingMachine) = parseInstructions(input)
repeat(stepsUntilDiagnostic) {
turingMachine.step()
}
return turingMachine.tape.values.count { it == "1" }.toString()
}
override fun solvePartTwo(input: String): String {
return "Free Star!"
}
}
private fun parseInstructions(input: String): Pair<Int, TuringMachine> {
val instructions = input.lines()
val initialState = instructions[0].substringAfter("Begin in state ")
.dropLast(1)
val stepsUntilDiagnostic = instructions[1].substringAfter("Perform a diagnostic checksum after ")
.substringBefore(" steps.").toInt()
val transitionRules = (3 until instructions.size step 10)
.flatMap { lineNumber ->
readStateTransistions(instructions, lineNumber)
}
.associateBy { Pair(it.state, it.read) }
val turingMachine = TuringMachine(initialState, transitionRules)
return Pair(stepsUntilDiagnostic, turingMachine)
}
private fun readStateTransistions(instructions: List<String>, lineNumber: Int): List<Transition> {
val state = instructions[lineNumber].substringAfter("In state ")
.dropLast(1)
val t1 = readTransition(state, instructions, lineNumber + 1)
val t2 = readTransition(state, instructions, lineNumber + 5)
return listOf(t1, t2)
}
private fun readTransition(state: String, instructions: List<String>, lineNumber: Int): Transition {
val read = instructions[lineNumber].substringAfter("If the current value is ").dropLast(1)
val write = instructions[lineNumber + 1].substringAfter("- Write the value ").dropLast(1)
val moveDirection = instructions[lineNumber + 2].substringAfter("- Move one slot to the ").dropLast(1)
val nextState = instructions[lineNumber + 3].substringAfter("- Continue with state ").dropLast(1)
val move: Int = if (moveDirection == "right") 1 else -1
return Transition(state, read, write, move, nextState)
}
private data class TuringMachine(var state: String, val transitionRules: Map<Pair<String, String>, Transition>) {
val tape = mutableMapOf<Int, String>()
var position = 0
fun step() {
val read = tape[position] ?: "0"
val rule = transitionRules[Pair(state, read)]!!
tape[position] = rule.write
position += rule.move
state = rule.nextState
}
}
private data class Transition(val state: String, val read: String, val write: String, val move: Int, val nextState: String)
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 2,528 | advent-of-code | MIT License |
src/main/kotlin/aoc23/Day12.kt | tom-power | 573,330,992 | false | {"Kotlin": 254717, "Shell": 1026} | package aoc23
import aoc23.Day12Domain.SpringRecord
import aoc23.Day12Parser.toSpringRecords
import aoc23.Day12Parser.unfoldFiveTimes
import common.Strings.replaceFirst
import common.Year23
object Day12 : Year23 {
fun List<String>.part1(): Long =
toSpringRecords()
.sumOf(SpringRecord::possibleArrangements)
fun List<String>.part2(): Long =
toSpringRecords(unfoldFn = unfoldFiveTimes)
.sumOf(SpringRecord::possibleArrangements)
}
object Day12Domain {
private const val replacements = "#."
data class SpringRecord(
val springs: String,
val damagedGroupSizes: List<Int>
) {
private val cache: MutableMap<Pair<String, List<Int>>, Long> = mutableMapOf()
fun possibleArrangements(
remainingSprings: String = springs,
remainingDamagedGroupSizes: List<Int> = damagedGroupSizes,
): Long {
val key = Pair(remainingSprings, remainingDamagedGroupSizes)
cache[key]?.let { return it }
when {
remainingDamagedGroupSizes.isEmpty() -> {
return when {
remainingSprings.none { it == '#' } -> 1
else -> 0
}
}
remainingSprings.isEmpty() -> return 0
}
return when (remainingSprings.first()) {
'.' ->
possibleArrangements(
remainingSprings.drop(1),
remainingDamagedGroupSizes,
)
'?' ->
replacements.sumOf { replacement ->
possibleArrangements(
remainingSprings.replaceFirst('?', replacement),
remainingDamagedGroupSizes,
)
}
'#' -> {
val thisMaybeDamagedSprings = remainingSprings.takeWhile { it != '.' }
val thisDamagedGroupSize = remainingDamagedGroupSizes.first()
when {
thisMaybeDamagedSprings.all { it == '#' } ->
when {
thisMaybeDamagedSprings.count() != thisDamagedGroupSize -> 0
thisMaybeDamagedSprings.count() == thisDamagedGroupSize ->
possibleArrangements(
remainingSprings.drop(thisDamagedGroupSize),
remainingDamagedGroupSizes.drop(1),
)
else -> error("not possible")
}
else ->
replacements.sumOf { replacement ->
possibleArrangements(
remainingSprings.replaceFirst('?', replacement),
remainingDamagedGroupSizes,
)
}
}
}
else -> error("unknown spring type")
}.also { cache[key] = it }
}
}
}
object Day12Parser {
fun List<String>.toSpringRecords(unfoldFn: String.() -> String = { this }): List<SpringRecord> =
map { line ->
line.unfoldFn().split(" ").let { split ->
SpringRecord(
springs = split.first(),
damagedGroupSizes = split.last().split(",").map { it.toInt() }
)
}
}
val unfoldFiveTimes: String.() -> String = {
this.split(" ").run {
first().repeatFiveTimesWith('?') + " " + last().repeatFiveTimesWith(',')
}
}
private fun String.repeatFiveTimesWith(separator: Char): String = (this + separator).repeat(5).dropLast(1)
}
| 0 | Kotlin | 0 | 0 | baccc7ff572540fc7d5551eaa59d6a1466a08f56 | 3,974 | aoc | Apache License 2.0 |
src/Day02.kt | Arclights | 574,085,358 | false | {"Kotlin": 11490} | fun main() {
fun shapeScore(shape: SHAPE) = when (shape) {
SHAPE.ROCK -> 1
SHAPE.PAPER -> 2
SHAPE.SCISSORS -> 3
}
fun beatingShape(shape: SHAPE) = when (shape) {
SHAPE.ROCK -> SHAPE.PAPER
SHAPE.PAPER -> SHAPE.SCISSORS
SHAPE.SCISSORS -> SHAPE.ROCK
}
fun losingShape(shape: SHAPE) = when (shape) {
SHAPE.ROCK -> SHAPE.SCISSORS
SHAPE.PAPER -> SHAPE.ROCK
SHAPE.SCISSORS -> SHAPE.PAPER
}
fun roundScore(opponentShape: SHAPE, yourShape: SHAPE) = when {
yourShape == beatingShape(opponentShape) -> 6
opponentShape.ordinal == yourShape.ordinal -> 3
else -> 0
}
fun part1(input: List<String>): Int {
val strategy = input.map { line ->
val opponentShape = when (val char = line[0]) {
'A' -> SHAPE.ROCK
'B' -> SHAPE.PAPER
'C' -> SHAPE.SCISSORS
else -> throw IllegalArgumentException("Unknown input '$char'")
}
val yourShape = when (val char = line[2]) {
'X' -> SHAPE.ROCK
'Y' -> SHAPE.PAPER
'Z' -> SHAPE.SCISSORS
else -> throw IllegalArgumentException("Unknown input '$char'")
}
opponentShape to yourShape
}
return strategy.sumOf { (opponentShape, yourShape) ->
roundScore(opponentShape, yourShape) + shapeScore(yourShape)
}
}
fun part2(input: List<String>): Int {
val strategy = input.map { line ->
val opponentShape = when (val char = line[0]) {
'A' -> SHAPE.ROCK
'B' -> SHAPE.PAPER
'C' -> SHAPE.SCISSORS
else -> throw IllegalArgumentException("Unknown input '$char'")
}
val outcome = when (val char = line[2]) {
'X' -> OUTCOME.LOSE
'Y' -> OUTCOME.DRAW
'Z' -> OUTCOME.WIN
else -> throw IllegalArgumentException("Unknown input '$char'")
}
opponentShape to outcome
}
return strategy.sumOf { (opponentShape, outcome) ->
val yourShape = when (outcome) {
OUTCOME.LOSE -> losingShape(opponentShape)
OUTCOME.DRAW -> opponentShape
OUTCOME.WIN -> beatingShape(opponentShape)
}
roundScore(opponentShape, yourShape) + shapeScore(yourShape)
}
}
val testInput = readInput("Day02_test")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
enum class SHAPE {
ROCK,
PAPER,
SCISSORS
}
enum class OUTCOME {
LOSE,
DRAW,
WIN
} | 0 | Kotlin | 0 | 0 | 121a81ba82ba0d921bd1b689241ffa8727bc806e | 2,815 | advent_of_code_2022 | Apache License 2.0 |
src/main/kotlin/aoc/Day3.kt | dtsaryov | 573,392,550 | false | {"Kotlin": 28947} | package aoc
/**
* [AoC 2022: Day 3](https://adventofcode.com/2022/day/3)
*/
fun getRucksackPrioritiesSum(): Int {
val input = readInput("day3.txt") ?: return Int.MIN_VALUE
var sum = 0
for (s in input) {
sum += collectDuplicates(s).fold(0) { acc, ch -> acc + getCharPriority(ch) }
}
return sum
}
fun getGroupBadgesSum(): Int {
val input = readInput("day3.txt") ?: return Int.MIN_VALUE
var sum = 0
for (i in input.indices step 3) {
val strings = listOf(input[i], input[i + 1], input[i + 2])
sum += getCharPriority(findDuplicate(strings))
}
return sum
}
private fun findDuplicate(strings: List<String>): Char {
val chars = mutableMapOf<Char, Int>()
for ((i, s) in strings.withIndex()) {
for (ch in s) {
chars.compute(ch) { _, count ->
if (count == null) {
if (i == 0) 1
else 0
} else {
when (i) {
0 -> count
1 -> if (count == 1) 2 else count
2 -> if (count == 2) 3 else count
else -> 0
}
}
}
}
}
return chars.keys.find { ch -> chars[ch] == 3 }!!
}
private fun collectDuplicates(s: String): List<Char> {
val chars = mutableMapOf<Char, Int>()
for (i in s.indices) {
val c = s[i]
chars.compute(c) { _, count ->
if (i < s.length / 2) {
1
} else {
if (count == null) null
else count + 1
}
}
}
return chars.keys.mapNotNull { char ->
val count = chars[char]
if (count == null || count < 2) null
else char
}
}
private fun getCharPriority(char: Char): Int {
return if (char.isLowerCase())
char.code - 96
else
char.code - 38
} | 0 | Kotlin | 0 | 0 | 549f255f18b35e5f52ebcd030476993e31185ad3 | 1,948 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/days/Day16.kt | andilau | 399,220,768 | false | {"Kotlin": 85768} | package days
@AdventOfCodePuzzle(
name = "<NAME>",
url = "https://adventofcode.com/2020/day/16",
date = Date(day = 16, year = 2020)
)
class Day16(lines: List<String>) : Puzzle {
private val rules = lines.takeWhile(String::isNotEmpty).map(TicketRule.Companion::parse)
private val ownTicket = lines.dropWhile { it != "your ticket:" }.drop(1).first().split(",").map { it.toInt() }
private val allTickets = lines.dropWhile { it != "nearby tickets:" }.drop(1).map { row ->
row.split(",").map { it.toInt() }
}
override fun partOne(): Int =
allTickets.sumOf { ticket ->
ticket.filter { field ->
rules.none { rule -> rule.isValidValue(field) }
}.sum()
}
override fun partTwo(): Long {
val validTickets = allTickets.filter { ticket ->
ticket.all { field ->
rules.any { rule ->
rule.isValidValue(field)
}
}
}
val validRules: Map<TicketRule, MutableSet<Int>> = rules.associateWith { rule ->
ownTicket.indices.filter { index ->
validTickets.all { rule.isValidValue(it[index]) }
}.toMutableSet()
}
val mapping = mutableMapOf<TicketRule, Int>()
while (validRules.values.any { it.size > 1 }) {
validRules.entries
.filter { (_, columns) -> columns.size == 1 }
.map { (rule, columns) ->
val columnIndex = columns.first()
validRules.values.forEach { it.remove(columnIndex) }
mapping[rule] = columnIndex
}
}
return mapping.entries
.filter { (rule, _) -> rule.name.startsWith("departure") }
.map { (_, index) -> ownTicket[index].toLong() }
.reduce { a, b -> a * b }
}
data class TicketRule(val name: String, val firstRange: IntRange, val secondRange: IntRange) {
// departure location: 31-201 or 227-951
// departure station: 49-885 or 892-961
// departure platform: 36-248 or 258-974
// ...
companion object {
fun parse(line: String): TicketRule = TicketRule(
line.substringBefore(": "),
line.substringAfter(": ").substringBefore(" or ")
.split("-").let { it.first().toInt()..it.last().toInt() },
line.substringAfter(": ").substringAfter(" or ")
.split("-").let { it.first().toInt()..it.last().toInt() }
)
}
fun isValidValue(value: Int) = (value in firstRange) || (value in secondRange)
}
}
| 7 | Kotlin | 0 | 0 | 2809e686cac895482c03e9bbce8aa25821eab100 | 2,708 | advent-of-code-2020 | Creative Commons Zero v1.0 Universal |
app/src/main/kotlin/day04/Day04.kt | W3D3 | 433,748,408 | false | {"Kotlin": 72893} | package day04
import common.InputRepo
import common.readSessionCookie
import common.solve
import java.util.function.Consumer
fun main(args: Array<String>) {
val day = 4
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay04Part1, ::solveDay04Part2)
}
data class BingoTile(val value: Int, var marked: Boolean) {
override fun toString(): String {
return value.toString()
}
}
fun markTile(board: List<List<BingoTile>>, drawn: Int) {
board.forEach(Consumer { row -> row.forEach(Consumer { tile -> tile.marked = (tile.value == drawn) or tile.marked }) })
}
fun checkWinner(board: List<List<BingoTile>>): Boolean {
if (board.any { row -> row.all { tile -> tile.marked } }) {
return true
}
for (i in 0..4) {
if (board.all { row -> row[i].marked }) {
return true
}
}
return false
}
fun sumNonMarked(board: List<List<BingoTile>>): Int {
return board.sumOf { row -> row.sumOf { tile -> if (tile.marked) 0 else tile.value } }
}
private fun parseInput(input: List<String>): Pair<List<Int>, List<List<List<BingoTile>>>> {
val drawn = input.first().split(",").map(String::toInt)
val bingoBoards = input.drop(1)
.filterNot { s -> s.isBlank() }
.map { s ->
s.trim().split("\\s+".toRegex())
.map { numStr -> BingoTile(numStr.toInt(), false) }
}
.chunked(5)
return Pair(drawn, bingoBoards)
}
fun solveDay04Part1(input: List<String>): Int {
val (drawn, bingoBoards) = parseInput(input)
for (drawnBall in drawn) {
for (bingoBoard in bingoBoards) {
markTile(bingoBoard, drawnBall)
}
for (bingoBoard in bingoBoards) {
if (checkWinner(bingoBoard)) {
return sumNonMarked(bingoBoard) * drawnBall
}
}
}
return -1
}
fun solveDay04Part2(input: List<String>): Int {
val (drawn, bingoBoards) = parseInput(input)
val winningBoardsIndices = HashSet<Int>()
for (drawnBall in drawn) {
for (bingoBoard in bingoBoards) {
markTile(bingoBoard, drawnBall)
}
for (bingoBoard in bingoBoards) {
if (checkWinner(bingoBoard)) {
winningBoardsIndices.add(bingoBoards.indexOf(bingoBoard))
if (winningBoardsIndices.size == bingoBoards.size) {
return sumNonMarked(bingoBoard) * drawnBall
}
}
}
}
return -1
} | 0 | Kotlin | 0 | 0 | df4f21cd99838150e703bcd0ffa4f8b5532c7b8c | 2,561 | AdventOfCode2021 | Apache License 2.0 |
2023/src/main/kotlin/day17.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Graph
import utils.Grid
import utils.Parser
import utils.Solution
import utils.Vec2i
fun main() {
Day17.run()
}
object Day17 : Solution<Grid<Char>>() {
override val name = "day17"
override val parser = Parser.charGrid
data class Node(
val location: Vec2i,
val entryDirection: Vec2i,
)
data class Edge(
val from: Vec2i,
val direction: Vec2i,
val len: Int,
)
private val DIRECTIONS = listOf(Vec2i.UP, Vec2i.RIGHT, Vec2i.DOWN, Vec2i.LEFT)
private fun solve(moves: IntRange): Int {
val g = Graph<Node, Edge>(
edgeFn = { node ->
val edges = DIRECTIONS.filter { node.entryDirection.x != 0 && it.x == 0 || node.entryDirection.y != 0 && it.y == 0 }.flatMap { direction ->
moves.map { len ->
Edge(node.location, direction, len)
}.filter {
(node.location + (it.direction * it.len)) in input
}.map {
it to Node(node.location + (it.direction * it.len), it.direction)
}
}
edges
},
weightFn = { edge ->
val weight = (1 .. edge.len).sumOf {
input[edge.from + (edge.direction * it)] - '0'
}
weight
}
)
val end = Vec2i(input.width - 1, input.height - 1)
return g.shortestPath(
start = Node(Vec2i(0, 0), Vec2i(1, 1)),
heuristic = { node -> node.location.manhattanDistanceTo(end) },
end = { it.location == end },
).first
}
override fun part1() = solve(1 .. 3)
override fun part2() = solve(4 .. 10)
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 1,543 | aoc_kotlin | MIT License |
src/main/kotlin/com/briarshore/aoc2022/day05/SupplyStacksPuzzle.kt | steveswing | 579,243,154 | false | {"Kotlin": 47151} | package com.briarshore.aoc2022.day05
import println
import readInput
// [D]
// [N] [C]
// [Z] [M] [P]
// 1 2 3
//
// move 1 from 2 to 1
// move 3 from 1 to 3
// move 2 from 2 to 1
// move 1 from 1 to 2
//
enum class CraneModel {
M9000, M9001
}
fun main() {
data class Move(val count: Int, val from: Int, val to: Int, val model: CraneModel) {
fun apply(stacks: MutableList<ArrayDeque<Char>>) {
when {
model == CraneModel.M9000 -> {
repeat(count) { _ -> stacks[to - 1].addFirst(stacks[from - 1].removeFirst()) }
}
model == CraneModel.M9001 -> {
val crane = ArrayDeque<Char>()
repeat(count) { _ -> crane.addLast(stacks[from - 1].removeFirst()) }
repeat(count) { _ -> stacks[to - 1].addFirst(crane.removeLast()) }
}
}
}
}
val instructionRegex = Regex("move (?<count>\\d+) from (?<from>\\d+) to (?<to>\\d+)")
fun sharedPart(input: List<String>, craneModel: CraneModel): String {
var stacks: MutableList<ArrayDeque<Char>> = mutableListOf()
input.asSequence().map {
if (it.contains('[') || it.contains(']')) {
for (i in 1..it.length step 4) {
val crate = it[i]
if (crate != ' ') {
val stacksIndex = i / 4
if (stacks.isEmpty()) {
stacks = MutableList(it.length / 4 + 1) { _ -> ArrayDeque() }
}
stacks[stacksIndex].addLast(crate)
}
}
""
} else if (it.contains(" 1 2 3 ")) {
""
} else if (it.isNotBlank()) {
it
} else {
""
}
}
.filter { it.isNotBlank() }
.map { instructionRegex.matchEntire(it) }
.filterNotNull()
.map { it.groups }
.map { Move(it["count"]!!.value.toInt(), it["from"]!!.value.toInt(), it["to"]!!.value.toInt(), craneModel) }
.toList()
.forEach { it.apply(stacks) }
return stacks.map { it.first() }.joinToString("")
}
fun part1(input: List<String>): String {
return sharedPart(input, CraneModel.M9000)
}
fun part2(input: List<String>): String {
return sharedPart(input, CraneModel.M9001)
}
val sampleInput = readInput("d5p1-sample")
check(part1(sampleInput) == "CMZ")
val input = readInput("d5p1-input")
val part1 = part1(input)
check(part1 == "VWLCWGSDQ")
"part1 $part1".println()
check(part2(sampleInput) == "MCD")
val part2 = part2(input)
"part2 $part2".println()
check(part2 == "TCGLQSLPW")
}
| 0 | Kotlin | 0 | 0 | a0d19d38dae3e0a24bb163f5f98a6a31caae6c05 | 2,863 | 2022-AoC-Kotlin | Apache License 2.0 |
day06/src/main/kotlin/Day06.kt | bzabor | 160,240,195 | false | null | import kotlin.math.absoluteValue
class Day06(input: List<String>) {
private val landingPlaces = input.map { it ->
val (row, col) = it.split(", ").map { it.toInt() }
LandingPlace(row, col)
}
fun part1(): Int {
val gridSize = 1000
for (row in 0 until gridSize) {
for (col in 0 until gridSize) {
val nearestLandingPlace = nearestLandingPlace(row, col)
if (nearestLandingPlace != null) {
nearestLandingPlace.nearestList.add(Pair(row, col))
if (row == 0 || col == 0 || row == gridSize - 1 || col == gridSize - 1) {
nearestLandingPlace.isInfinite = true
}
}
}
}
var largestLandingPlace: LandingPlace? = null
var maxLandingPlaceSize = 0
for (landingPlace in landingPlaces.filterNot { it.isInfinite }) {
if (landingPlace.nearestList.size > maxLandingPlaceSize) {
maxLandingPlaceSize = landingPlace.nearestList.size
largestLandingPlace = landingPlace
}
}
println("largest landing place is ${largestLandingPlace?.id} with size of $maxLandingPlaceSize")
return maxLandingPlaceSize
}
private fun nearestLandingPlace(row: Int, col: Int): LandingPlace? {
val nearestPlaces = mutableListOf<LandingPlace>()
var minDistance = Int.MAX_VALUE
for (landingPlace in landingPlaces) {
val distance = pointToLandingPlaceDistance(row, col, landingPlace)
if (distance < minDistance) {
minDistance = distance
nearestPlaces.clear()
nearestPlaces.add(landingPlace)
} else if (distance == minDistance) {
nearestPlaces.add(landingPlace)
}
}
return if (nearestPlaces.size == 1) {
nearestPlaces[0]
} else {
null
}
}
private fun pointToLandingPlaceDistance(row: Int, col: Int, landingPlace: LandingPlace): Int {
return (landingPlace.row - row).absoluteValue + (landingPlace.col - col).absoluteValue
}
fun part2(): Int {
val gridRange = 10001
var locationWithTotalDistanceLessThan10000Count = 0
for (row in -gridRange..gridRange) {
for (col in -gridRange..gridRange) {
var distance = 0
for (landingPlace in landingPlaces) {
distance += pointToLandingPlaceDistance(row, col, landingPlace)
}
if (distance < 10000) {
locationWithTotalDistanceLessThan10000Count++
}
}
}
return locationWithTotalDistanceLessThan10000Count
}
}
class LandingPlace(val row: Int, val col: Int) {
val id: String = "$row:$col"
var isInfinite = false
val nearestList = mutableListOf<Pair<Int,Int>>()
}
| 0 | Kotlin | 0 | 0 | 14382957d43a250886e264a01dd199c5b3e60edb | 2,982 | AdventOfCode2018 | Apache License 2.0 |
src/aoc2023/Day08.kt | dayanruben | 433,250,590 | false | {"Kotlin": 79134} | package aoc2023
import checkValue
import readInput
fun main() {
val (year, day) = "2023" to "Day08"
fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)
fun lcm(a: Long, b: Long): Long = (a * b) / gcd(a, b)
fun List<Long>.lcm() = this.reduce { acc, n -> lcm(acc, n) }
fun parse(input: List<String>): Pair<String, Map<String, Pair<String, String>>> {
val inst = input.first()
val networkMap = input.drop(2).associate { line ->
val (node, lr) = line.split(" = ")
val (left, right) = lr.drop(1).dropLast(1).split(", ")
node to (left to right)
}
return inst to networkMap
}
fun minSteps(inst: String, networkMap: Map<String, Pair<String, String>>, start: String, isEnd: (String) -> Boolean): Long {
var steps = 0
var current = start
while (!isEnd(current)) {
current = when (inst[steps % inst.length]) {
'L' -> networkMap[current]?.first ?: ""
else -> networkMap[current]?.second ?: ""
}
steps++
}
return steps.toLong()
}
fun part1(input: List<String>): Long {
val (inst, networkMap) = parse(input)
return minSteps(inst, networkMap, "AAA") { it == "ZZZ" }
}
fun part2(input: List<String>): Long {
val (inst, networkMap) = parse(input)
return networkMap.keys.filter { it.last() == 'A' }.map { start ->
minSteps(inst, networkMap, start) { it.last() == 'Z' }
}.lcm()
}
val testInput1 = readInput(name = "${day}_p1_test1", year = year)
val testInput2 = readInput(name = "${day}_p1_test2", year = year)
val testInput3 = readInput(name = "${day}_p2_test", year = year)
val input = readInput(name = day, year = year)
checkValue(part1(testInput1), 2)
checkValue(part1(testInput2), 6)
println(part1(input))
checkValue(part2(testInput3), 6)
println(part2(input))
} | 1 | Kotlin | 2 | 30 | df1f04b90e81fbb9078a30f528d52295689f7de7 | 1,987 | aoc-kotlin | Apache License 2.0 |
src/Day09.kt | achugr | 573,234,224 | false | null | import kotlin.math.abs
enum class PlaneDirection(val x: Int, val y: Int) {
RIGHT(1, 0),
LEFT(-1, 0),
DOWN(0, -1),
UP(0, 1),
RIGHT_DOWN(1, -1),
RIGHT_UP(1, 1),
LEFT_DOWN(-1, -1),
LEFT_UP(-1, 1);
}
data class SegmentInput(val direction: PlaneDirection, val length: Int)
data class Point(val x: Int, val y: Int) {
fun adjacent(p: Point): Boolean {
return abs(x - p.x) <= 1 && abs(y - p.y) <= 1
}
fun directionTo(p: Point): PlaneDirection {
val xD = p.x - x
val yD = p.y - y
return PlaneDirection.values().find {
it.x == (if (xD == 0) 0 else xD / abs(xD)) && it.y == (if (yD == 0) 0 else yD / abs(yD))
} ?: throw RuntimeException("Incorrect move")
}
override fun toString(): String {
return "($x,$y)"
}
}
fun main() {
fun getPoints(input: List<String>): List<Point> {
val points = input.map {
it.split(" ").zipWithNext().map { command ->
val direction = when (command.first.toCharArray().first()) {
'R' -> PlaneDirection.RIGHT
'L' -> PlaneDirection.LEFT
'D' -> PlaneDirection.DOWN
'U' -> PlaneDirection.UP
else -> throw IllegalArgumentException("Unknown direction identifier")
}
SegmentInput(direction, command.second.toInt())
}.first()
}.fold(mutableListOf(Point(0, 0))) { acc, segment ->
val lastPoint = acc.last()
val points = (1..segment.length).map {
Point(lastPoint.x + segment.direction.x * it, lastPoint.y + segment.direction.y * it)
}
acc.addAll(points)
acc
}
return points
}
fun part1(input: List<String>): Int {
val points = getPoints(input)
val tailPath = mutableListOf(points[0])
var tail = 0
var head = 0
while (head < points.size) {
val headPoint = points[head]
if (!headPoint.adjacent(tailPath.last())) {
tailPath.add(points[head - 1])
tail++
}
head++
}
tailPath.add(points[0])
val uniqueTailPoints = tailPath.toSet()
return uniqueTailPoints.size
}
fun evaluateFollowerPath(points: List<Point>): List<Point> {
val tailPath = mutableListOf(points[0])
var head = 0
while (head < points.size) {
val headPoint = points[head]
val tailPoint = tailPath.last()
if (!tailPoint.adjacent(headPoint)) {
val moveDirection = tailPoint.directionTo(headPoint)
tailPath.add(Point(tailPoint.x + moveDirection.x, tailPoint.y + moveDirection.y))
}
head++
}
return tailPath.toList()
}
// not very efficient, but at least straightforward
fun part2(input: List<String>): Int {
val points = getPoints(input)
var path = points
repeat((1..9).count()) {
path = evaluateFollowerPath(path)
}
return path.toSet().size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09")
println(part1(testInput))
println(part2(testInput))
} | 0 | Kotlin | 0 | 0 | d91bda244d7025488bff9fc51ca2653eb6a467ee | 3,353 | advent-of-code-kotlin-2022 | Apache License 2.0 |
y2023/src/main/kotlin/adventofcode/y2023/Day23.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2023
import adventofcode.io.AdventSolution
import adventofcode.util.vector.Direction
import adventofcode.util.vector.SparseGrid
import adventofcode.util.vector.Vec2
fun main() {
Day23.solve()
}
object Day23 : AdventSolution(2023, 23, "A Long Walk") {
override fun solvePartOne(input: String): Any {
val lines = input.lines()
val start = lines.first().indexOfFirst { it == '.' }.let { Vec2(it, -1) }
val end = lines.last().indexOfFirst { it == '.' }.let { Vec2(it, lines.lastIndex) }
val grid = parse(input) + (end to 'v')
val paths = findPathLengths(start, grid)
val pathFrom = paths.groupBy { it.start }
val exit = end + Direction.DOWN.vector
return findLongestPath(start, exit, pathFrom)
}
override fun solvePartTwo(input: String): Any {
val lines = input.lines()
val start = lines.first().indexOfFirst { it == '.' }.let { Vec2(it, -1) }
val end = lines.last().indexOfFirst { it == '.' }.let { Vec2(it, lines.lastIndex) }
val grid = parse(input) + (end to 'v')
val directedPaths = findPathLengths(start, grid)
val paths = directedPaths + directedPaths.map { it.copy(start = it.end, end = it.start) }
val pathFrom = paths.groupBy { it.start }
val exit = end + Direction.DOWN.vector
return findLongestPath(start, exit, pathFrom)
}
private fun findPathLengths(start: Vec2, grid: Map<Vec2, Char>): Set<Segment> {
val segments = mutableSetOf<Segment>()
val intersections = mutableSetOf<Vec2>()
val unexplored = mutableListOf<Vec2>()
val initial = followPath(start, Direction.DOWN, grid)
segments += initial
unexplored += initial.end
while (unexplored.isNotEmpty()) {
val intersection = unexplored.removeLast()
if (intersection in intersections) continue
intersections += intersection
val newPaths = exits(intersection, grid).map { followPath(intersection, it, grid) }
segments += newPaths
unexplored += newPaths.map { it.end }.filter { it !in intersections }
}
return segments
}
private fun exits(cross: Vec2, grid: SparseGrid<Char>): List<Direction> = buildList {
if (grid[cross + Direction.UP.vector] == '^') add(Direction.UP)
if (grid[cross + Direction.RIGHT.vector] == '>') add(Direction.RIGHT)
if (grid[cross + Direction.DOWN.vector] == 'v') add(Direction.DOWN)
if (grid[cross + Direction.LEFT.vector] == '<') add(Direction.LEFT)
}
private fun followPath(cross: Vec2, dir: Direction, grid: SparseGrid<Char>): Segment {
val (pathLength, end) = generateSequence(cross + dir.vector + dir.vector to dir) { (pos, dir) ->
Direction.entries
.filter { it != dir.reverse }
.map { pos + it.vector to it }
.single { it.first in grid }
}.withIndex().first { grid[it.value.first]!! != '.' }
return Segment(cross, end.first + end.second.vector, pathLength + 3)
}
private fun findLongestPath(start: Vec2, exit: Vec2, pathsFrom: Map<Vec2, List<Segment>>): Int {
//Remapping intersections to indexes, so we can use a booleanArray to keep track of where we are. 2x speedup
val keys = (pathsFrom.keys + exit).toList().withIndex().associate { it.value to it.index }
val startKey = keys.getValue(start)
val exitKey = keys.getValue(exit)
val keysFrom =
pathsFrom.entries.associate { keys.getValue(it.key) to it.value.map { keys.getValue(it.end) to it.length } }
//using backtracking to keep track of which paths we've visited, instead of copying state. 2x speedup
val visited = BooleanArray(keys.size)
fun fullPath(intersection: Int, lengthSoFar: Int): Int {
visited[intersection] = true
val result = if (intersection == exitKey) lengthSoFar else {
keysFrom[intersection].orEmpty()
.filterNot { visited[it.first] }
.maxOfOrNull { (nextIntersection, pathLength) ->
fullPath(nextIntersection, lengthSoFar + pathLength)
} ?: 0
}
visited[intersection] = false
return result
}
return fullPath(startKey, 0) - 2
}
}
private data class Segment(val start: Vec2, val end: Vec2, val length: Int)
private fun parse(input: String) = input.lines().flatMapIndexed { y, line ->
line.mapIndexed { x, ch -> Vec2(x, y) to ch }
}.toMap().filterValues { it != '#' }
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 4,681 | advent-of-code | MIT License |
src/day07/Day07_functional.kt | seastco | 574,758,881 | false | {"Kotlin": 72220} | package day07
import readLines
/**
* Credit goes to tginsberg (https://github.com/tginsberg/advent-2022-kotlin)
* I'm experimenting with his solutions to better learn functional programming in Kotlin.
* Files without the _functional suffix are my original solutions.
*/
class Directory(val name: String) {
private val subDirs: MutableMap<String, Directory> = mutableMapOf()
private var sizeOfFiles: Int = 0
val size: Int
get() = sizeOfFiles + subDirs.values.sumOf { it.size }
fun addFile(size: Int) {
sizeOfFiles += size
}
fun traverse(dir: String): Directory =
subDirs.getOrPut(dir) { Directory(dir) }
fun find(predicate: (Directory) -> Boolean): List<Directory> =
subDirs.values.filter(predicate) + // filter any value with size <= 100k
subDirs.values.flatMap { it.find(predicate) } // call find(predicate) on subDirs
}
private fun parseInput(input: List<String>): Directory {
val callStack = ArrayDeque<Directory>().apply { add(Directory("/")) }
input.forEach { item ->
when {
item == "$ ls" -> {} // no-op
item.startsWith("dir") -> {} // no-op
item == "$ cd /" -> callStack.removeIf { it.name != "/" }
item == "$ cd .." -> callStack.removeFirst()
item.startsWith("$ cd") -> {
val name = item.substringAfterLast(" ") // parse out directory name
callStack.addFirst(callStack.first().traverse(name)) // add directory to subdirectory of parent
}
else -> {
val size = item.substringBefore(" ").toInt()
callStack.first().addFile(size) // add file size to current directory
}
}
}
return callStack.last() // return root directory
}
private fun part1(input: List<String>): Int {
val rootDirectory = parseInput(input)
return rootDirectory.find { it.size <= 100_000 }.sumOf{ it.size }
}
private fun part2(input: List<String>): Int {
val rootDirectory = parseInput(input)
val unusedSpace = 70_000_000 - rootDirectory.size
val deficit = 30_000_000 - unusedSpace
return rootDirectory.find { it.size >= deficit }.minBy { it.size }.size
}
fun main() {
println(part1(readLines("day07/test")))
println(part1(readLines("day07/input")))
println(part2(readLines("day07/test")))
println(part2(readLines("day07/input")))
} | 0 | Kotlin | 0 | 0 | 2d8f796089cd53afc6b575d4b4279e70d99875f5 | 2,428 | aoc2022 | Apache License 2.0 |
src/main/kotlin/nl/tiemenschut/aoc/y2023/day18.kt | tschut | 723,391,380 | false | {"Kotlin": 61206} | package nl.tiemenschut.aoc.y2023
import nl.tiemenschut.aoc.lib.dsl.aoc
import nl.tiemenschut.aoc.lib.dsl.day
import nl.tiemenschut.aoc.lib.dsl.parser.InputParser
import nl.tiemenschut.aoc.lib.util.Direction
import nl.tiemenschut.aoc.lib.util.Direction.*
import nl.tiemenschut.aoc.lib.util.points.Point
import nl.tiemenschut.aoc.lib.util.points.by
import kotlin.math.abs
data class DigPlanRow(val direction: Direction, val steps: Int)
typealias DigPlan = List<DigPlanRow>
object DigPlanParser : InputParser<DigPlan> {
private fun String.toDirection() =
if (this == "U") UP else if (this == "D") DOWN else if (this == "R") RIGHT else LEFT
override fun parse(input: String) = "([RDLU]) (\\d+).*".toRegex().findAll(input).map {
it.groupValues.let { (_, d, s) -> DigPlanRow(d.toDirection(), s.toInt()) }
}.toList()
}
object DigPlanPart2Parser : InputParser<DigPlan> {
private fun String.toDirection() =
if (this == "3") UP else if (this == "1") DOWN else if (this == "0") RIGHT else LEFT
override fun parse(input: String) = ".*\\(#(.{5})(.)\\)".toRegex().findAll(input).map {
it.groupValues.let { (_, s, d) -> DigPlanRow(d.toDirection(), s.toInt(16)) }
}.toList()
}
fun main() {
aoc {
puzzle { 2023 day 18 }
fun Point<Int>.moved(d: Direction, count: Int): Point<Int> = when (d) {
UP -> x by y - count
Direction.DOWN -> x by y + count
LEFT -> x - count by y
Direction.RIGHT -> x + count by y
}
fun List<Point<Int>>.surface() = abs(this.windowed(2).sumOf { (p, q) ->
(p.x + q.x).toLong() * (q.y - p.y).toLong()
} / 2)
fun List<Point<Int>>.length(): Long =
this.windowed(2, step = 1).sumOf { (p, q) -> p.manhattanDistance(q).toLong() }
part1 { input ->
DigPlanParser.parse(input).runningFold((0 by 0) as Point<Int>) { acc, digPlanRow ->
acc.moved(digPlanRow.direction, digPlanRow.steps)
}.let {
it.surface() + it.length() / 2 + 1
}
}
part2 { input ->
DigPlanPart2Parser.parse(input).runningFold((0 by 0) as Point<Int>) { acc, digPlanRow ->
acc.moved(digPlanRow.direction, digPlanRow.steps)
}.let {
it.surface() + it.length() / 2 + 1
}
}
}
}
| 0 | Kotlin | 0 | 1 | a1ade43c29c7bbdbbf21ba7ddf163e9c4c9191b3 | 2,400 | aoc-2023 | The Unlicense |
src/Day07.kt | floblaf | 572,892,347 | false | {"Kotlin": 28107} | fun main() {
abstract class Content {
abstract val name: String
abstract val size: Int
}
class Folder(
override val name: String,
val parent: Folder? = null,
val content: MutableList<Content> = mutableListOf(),
) : Content() {
override val size: Int
get() = content.sumOf { it.size }
override fun toString(): String {
return "$name=$content"
}
}
class File(override val name: String, override val size: Int) : Content() {
override fun toString(): String {
return name
}
}
fun Folder.flattenFolders() : List<Folder> {
return listOf(this) + this.content.filterIsInstance<Folder>().flatMap { it.flattenFolders() }
}
fun part1(input: Folder): Int {
return input.flattenFolders().filter { it.size < 100_000 }.sumOf { it.size }
}
fun part2(input: Folder): Int {
val neededSpace = 30_000_000 - (70_000_000 - input.size)
return input.flattenFolders().sortedBy { it.size }
.first { it.size > neededSpace }
.size
}
val input = readInput("Day07")
val root = Folder("/")
var current = root
fun moveTo(name: String) {
current = current.content
.filterIsInstance<Folder>()
.find { it.name == name }
?: throw IllegalStateException("$name not found in ${current.name}")
}
fun addFolder(name: String) {
current.content.add(Folder(name, parent = current))
}
fun addFile(name: String, size: Int) {
current.content.add(File(name, size))
}
fun goBack() {
current = current.parent ?: throw IllegalStateException("Can't go back from ${current.name}")
}
input.drop(1).forEach { line ->
when {
line == "$ ls" -> { /*nothing*/ }
line == "$ cd .." -> goBack()
line.startsWith("$ cd") -> moveTo(line.split(" ").last())
line.startsWith("dir") -> addFolder(line.split(" ").last())
else -> line.split(" ").let { addFile(it.last(), it.first().toInt()) }
}
}
println(root)
println(part1(root))
println(part2(root))
}
| 0 | Kotlin | 0 | 0 | a541b14e8cb401390ebdf575a057e19c6caa7c2a | 2,231 | 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.