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/main/kotlin/cc/stevenyin/algorithms/_02_sorts/_04_MergeSort.kt | StevenYinKop | 269,945,740 | false | {"Kotlin": 107894, "Java": 9565} | package cc.stevenyin.algorithms._02_sorts
import cc.stevenyin.algorithms.RandomType
import cc.stevenyin.algorithms.testSortAlgorithm
class _04_MergeSort: SortAlgorithm {
override val name: String
get() = "MergeSort_Recursive"
override fun <T : Comparable<T>> sort(array: Array<T>) {
// 维护变量在算法运行过程中的定义是写好算法的基础
val left = 0
val right = array.size - 1
mergeSort(array, left, right)
}
private fun <T : Comparable<T>> mergeSort(array: Array<T>, left: Int, right: Int): Unit {
if (left >= right) {
return
}
val mid = left + (right - left) / 2
mergeSort(array, left, mid)
mergeSort(array, mid + 1, right)
merge(array, left, mid, right)
}
private fun <T: Comparable<T>> merge(array: Array<T>, left: Int, middle: Int, right: Int) {
val aux = arrayOfNulls<Comparable<T>>(right - left + 1)
// copy the range of the data to `aux` array
for (i in left .. right) {
aux[i - left] = array[i];
}
// 8 6 2 3
// ^
// cur
// i j
var i = left
var j = middle + 1
for (cursor in left .. right) {
if (i > middle) {
array[cursor] = aux[j - left] as T
j ++
continue
} else if (j > right) {
array[cursor] = aux[i - left] as T
i ++
continue
}
val l = aux[i - left] as T
val r = aux[j - left] as T
if (l < r) {
array[cursor] = l
i ++
} else {
array[cursor] = r
j ++
}
}
}
}
fun main() {
testSortAlgorithm(15, RandomType.NEARLY_ORDERED, _01_SelectionSort(), _02_InsertionSort(), _04_MergeSort())
}
// 5, 3, 6, 1, 7, 2
// 3, 5, 6, 1, 7, 2
// 3, 5, 6, 1, 7, 2
| 0 | Kotlin | 0 | 1 | 748812d291e5c2df64c8620c96189403b19e12dd | 1,982 | kotlin-demo-code | MIT License |
src/main/kotlin/aoc22/Day04.kt | asmundh | 573,096,020 | false | {"Kotlin": 56155} | package aoc22
import readInput
fun day4part1(input: List<String>): Int =
input.count { inp ->
inp.split(",").let {
it[0].surrounds(it[1]) ||
it[1].surrounds(it[0])
}
}
fun day4part2(input: List<String>): Int =
input.count { inp ->
inp.split(",").let {
it[0].occursIn(it[1]) ||
it[1].occursIn(it[0])
}
}
fun main() {
val input = readInput("Day04")
println(day4part1(input))
println(day4part2(input))
}
fun String.occursIn(other: String): Boolean {
val firstAssignment = splitToPair()
val secondAssignment = other.splitToPair()
return (secondAssignment.first in firstAssignment.first..firstAssignment.second) ||
(secondAssignment.second in firstAssignment.first..firstAssignment.second) ||
(firstAssignment.second in secondAssignment.first..secondAssignment.second) ||
(firstAssignment.first in secondAssignment.first..secondAssignment.second)
}
fun String.surrounds(other: String): Boolean {
val firstAssignment = splitToPair()
val secondAssignment = other.splitToPair()
return (secondAssignment.first in firstAssignment.first..firstAssignment.second) &&
(secondAssignment.second in firstAssignment.first..firstAssignment.second)
}
fun String.splitToPair(): Pair<Int, Int> {
val numbers = split("-")
return numbers[0].toInt() to numbers[1].toInt()
}
| 0 | Kotlin | 0 | 0 | 7d0803d9b1d6b92212ee4cecb7b824514f597d09 | 1,436 | advent-of-code | Apache License 2.0 |
src/Day04.kt | rmyhal | 573,210,876 | false | {"Kotlin": 17741} | fun main() {
fun part1(input: List<String>): Int {
return fullOverlap(input)
}
fun part2(input: List<String>): Int {
return partialOverlap(input)
}
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
private fun fullOverlap(input: List<String>) =
input
.map { pair -> pair.split(",").map { it.split("-") } }
.map { (first, second) -> first.map { it.toInt() }.toRange() to second.map { it.toInt() }.toRange() }
.count { (first, second) -> first contains second || second contains first }
private fun partialOverlap(input: List<String>) =
input
.map { pair -> pair.split(",").map { it.split("-") } }
.map { (first, second) -> first.map { it.toInt() }.toRange() to second.map { it.toInt() }.toRange() }
.count { (first, second) -> first overlaps second || second overlaps first }
private fun List<Int>.toRange(): IntRange = IntRange(get(0), get(1))
// checks for partial overlap
private infix fun IntRange.overlaps(other: IntRange) = first in other || last in other
// checks for full overlap
private infix fun IntRange.contains(other: IntRange) = first >= other.first && last <= other.last | 0 | Kotlin | 0 | 0 | e08b65e632ace32b494716c7908ad4a0f5c6d7ef | 1,169 | AoC22 | Apache License 2.0 |
src/Day02.kt | ManueruEd | 573,678,383 | false | {"Kotlin": 10647} | fun main() {
val shapeScores = mapOf("X" to 1, "Y" to 2, "Z" to 3)
fun testMatch(a: String, b: String): Int {
when {
(a == "A" && b == "X") ||
(a == "B" && b == "Y") ||
(a == "C" && b == "Z") -> {
println("$a $b draw")
val shapeScore = shapeScores[b]
return 3 + shapeScore!!
}
(a == "A" && b == "Z") ||
(a == "B" && b == "X") ||
(a == "C" && b == "Y")
-> {
println("$a $b you lost")
val shapeScore = shapeScores[b]
return shapeScore!!
}
else -> {
println("$a $b you win")
return 6 + shapeScores[b]!!
}
}
}
fun part1(input: List<String>): Int {
val a = input
.map {
it.split(" ")
}
.map { (a, b) ->
testMatch(a, b)
}
return a.sum()
}
fun getShapeToLossFor(input: String): String {
return when (input) {
"A" -> "Z"
"B" -> "X"
else -> "Y"
}
}
fun getShapeToWinFor(input: String): String {
return when (input) {
"A" -> "Y"
"B" -> "Z"
else -> "X"
}
}
fun getShapeToDrawFor(input: String): String {
return when (input) {
"A" -> "X"
"B" -> "Y"
else -> "Z"
}
}
fun part2(input: List<String>): Int {
val a = input
.map {
it.split(" ")
}
.map { (a, b) ->
val changeShape = when (b) {
"X" -> {
//loss
getShapeToLossFor(a)
}
"Y" -> {
//draw
getShapeToDrawFor(a)
}
else -> {
//win
getShapeToWinFor(a)
}
}
testMatch(a, changeShape)
}
return a.sum()
}
// 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 | 09f3357e059e31fda3dd2dfda5ce603c31614d77 | 2,534 | AdventOfCode2022 | Apache License 2.0 |
src/Day02.kt | 3n3a-archive | 573,389,832 | false | {"Kotlin": 41221, "Shell": 534} | fun Day02() {
fun getMappedChar( map: Map<Char, Char>, input: Char): Char? {
return map.get(input)
}
fun getPointsForPlayer2( winner: Int, chosenItem: Char? ): Int {
var points = 0
when(winner) {
0 -> points += 3
1 -> points += 0
2 -> points += 6
}
when(chosenItem) {
'R' -> points += 1
'P' -> points += 2
'S' -> points += 3
}
return points
}
fun rockPaperScissor(player1: Char, player2: Char): Int {
// return 1 --> player 1 wins
// return 2 --> player 2 wins
// return 0 --> draw
// HAndle exception of Scissor beats Paper
if (player1 == 'S' && player2 == 'P') {
return 1
} else if (player2 == 'S' && player1 == 'P') {
return 2
}
val player1GameResults = player1.compareTo(player2)
when(player1GameResults) {
1 -> return 2
0 -> return 0
-1 -> return 1
else -> println("todo")
}
return 99
}
fun preprocess(input: List<String>): List<List<Char?>> {
val replacementMap = mapOf('A' to 'R', 'B' to 'P', 'C' to 'S', 'X' to 'R', 'Y' to 'P', 'Z' to 'S',)
return input
.map {
it.split(" ").map {
getMappedChar(replacementMap, it.toCharArray()[0] )
}
}
}
fun part1(input: List<String>): Int {
val processed = preprocess(input)
var sumOfPoints = 0
for (element in processed) {
val gameStats = rockPaperScissor(element[0] ?: 'E', element[1] ?: 'E')
val points = getPointsForPlayer2(gameStats, element[1])
sumOfPoints += points
}
return sumOfPoints
}
fun getWinningMove(char: Char?): Char {
when(char) {
'R' -> return 'P'
'P' -> return 'S'
'S' -> return 'R'
}
return 'E'
}
fun getLosingMove(char: Char?): Char {
when(char) {
'R' -> return 'S'
'P' -> return 'R'
'S' -> return 'P'
}
return 'E'
}
fun getDesiredOutcome(player1: Char?, outcome: Char?): Char? {
val x = 'R'
val y = 'P'
val z = 'S'
when(outcome) {
x -> return getLosingMove(player1)
y -> return player1 // draw
z -> return getWinningMove(player1)
}
return 'E'
}
fun part2(input: List<String>): Int {
val processed = preprocess(input)
var sumOfPoints = 0
for (element in processed) {
val player2 = getDesiredOutcome(element[0], element[1])
val gameStats = rockPaperScissor(element[0] ?: 'E', player2 ?: 'E')
val points = getPointsForPlayer2(gameStats, player2)
sumOfPoints += points
}
return sumOfPoints
}
// test if implementation meets criteria from the description, like:
// val testInput = readInput("Day02_test")
// check(part1(testInput) == 15)
val input = readInput("Day02")
println("1: " + part1(input))
println("2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | fd25137d2d2df0aa629e56981f18de52b25a2d28 | 3,262 | aoc_kt | Apache License 2.0 |
y2015/src/main/kotlin/adventofcode/y2015/Day19.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2015
import adventofcode.io.AdventSolution
object Day19 : AdventSolution(2015, 19, "Medicine for Rudolph") {
override fun solvePartOne(input: String) = parse(input)
.let { (transitions, molecule) -> newMolecules(molecule, transitions) }
.count()
.toString()
override fun solvePartTwo(input: String): String {
val (_, molecule) = parse(input)
val c = molecule.count { it.isUpperCase() } - molecule.count("Rn") - molecule.count("Ar") - 2 * molecule.count("Y") - 1
return c.toString()
}
private fun String.count(literal: String) = literal.toRegex().findAll(this).count()
private fun parse(input: String): Pair<Map<String, Set<String>>, String> {
val (rewriteRules, other) = input.lines().partition { "=>" in it }
val transitions = rewriteRules.map { it.substringBefore(" =>") to it.substringAfter("=> ") }
.groupBy({ it.first }, { it.second }).mapValues { it.value.toSet() }
val molecule = other.last()
return transitions to molecule
}
private fun newMolecules(molecule: String, transitions: Map<String, Set<String>>) =
transitions.flatMap { (source, targets) ->
Regex.fromLiteral(source).findAll(molecule).toList().flatMap { matchResult ->
targets.map { t -> molecule.replaceRange(matchResult.range, t) }
}
}.toSet()
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,308 | advent-of-code | MIT License |
src/main/kotlin/de/startat/aoc2023/Day7.kt | Arondc | 727,396,875 | false | {"Kotlin": 194620} | package de.startat.aoc2023
import de.startat.aoc2023.HandType.*
import java.util.*
data class D7Play(val cards: List<Card>, val bid: Int) {
val type: HandType
val jokeredType : HandType
init {
fun determineType(groupedCards : SortedMap<Int, List<Card>>) : HandType = when {
groupedCards.any { (_, v) -> v.size == 5 } -> FiveOfAKind
groupedCards.any { (_, v) -> v.size == 4 } -> FourOfAKind
groupedCards.any { (_, v) -> v.size == 3 } && groupedCards.any { (_, v) -> v.size == 2 } -> FullHouse
groupedCards.any { (_, v) -> v.size == 3 } -> ThreeOfAKind
groupedCards.filter { (_,v) -> v.size == 2 }.count() == 2 -> TwoPair
groupedCards.any { (_,v) -> v.size == 2 } -> OnePair
else -> HighCard
}
val groupedCards = cards.groupBy { it.value }.toSortedMap { a, b -> a.compareTo(b) }
type = determineType(groupedCards)
val jokerValues = listOf('2', '3', '4', '5', '6', '7', '8', '9', 'T', 'Q', 'K', 'A')
val jokeredTypes = jokerValues.map { jv ->
val jGroupedCards = cards.map { c ->
if (c.face == 'J') Card(
jv,
cardValuesS2[jv]!!
) else c
}. groupBy { it.value }.toSortedMap { a, b -> a.compareTo(b) }
determineType(jGroupedCards)
}.toList()
jokeredType = jokeredTypes.min()
}
}
enum class HandType{
FiveOfAKind,FourOfAKind,FullHouse,ThreeOfAKind,TwoPair,OnePair,HighCard
}
class Card(val face: Char, val value: Int) : Comparable<Card> {
companion object {
fun ofStar1(char: Char) = Card(char, cardValues[char]!!)
fun ofStar2(char: Char) = Card(char, cardValuesS2[char]!!)
}
override fun compareTo(other: Card): Int = other.value.compareTo(this.value)
override fun toString(): String = "$face|$value"
}
val cardValues = mapOf(
'2' to 2,
'3' to 3,
'4' to 4,
'5' to 5,
'6' to 6,
'7' to 7,
'8' to 8,
'9' to 9,
'T' to 10,
'J' to 11,
'Q' to 12,
'K' to 13,
'A' to 14,
)
val cardValuesS2 =mapOf (
'J' to 1,
'2' to 2,
'3' to 3,
'4' to 4,
'5' to 5,
'6' to 6,
'7' to 7,
'8' to 8,
'9' to 9,
'T' to 10,
'Q' to 12,
'K' to 13,
'A' to 14,
)
class Day7 {
fun star1() {
var plays = parsePlays1(day7input)
plays = sortPlays1(plays)
plays.forEachIndexed{ idx,p -> println("${idx+1} $p ${p.type}") }
val winnings = calculateWinnings(plays)
println(winnings)
}
fun star2() {
var plays = parsePlays2(day7input)
plays = sortPlays2(plays)
plays.forEachIndexed{ idx,p -> println("${idx+1} $p ${p.jokeredType}") }
val winnings = calculateWinnings(plays)
println(winnings)
}
private fun calculateWinnings(plays: List<D7Play>) =
plays.mapIndexed { idx, p -> (idx + 1) * p.bid }.reduce { acc, p -> acc + p }
private fun sortPlays1(plays: List<D7Play>) = plays.sortedWith(
compareBy<D7Play> { it.type }.thenBy { it.cards[0] }.thenBy { it.cards[1] }.thenBy { it.cards[2] }
.thenBy { it.cards[3] }.thenBy { it.cards[4] },
).reversed()
private fun sortPlays2(plays: List<D7Play>) = plays.sortedWith(
compareBy<D7Play> { it.jokeredType }.thenBy { it.cards[0] }.thenBy { it.cards[1] }.thenBy { it.cards[2] }
.thenBy { it.cards[3] }.thenBy { it.cards[4] },
).reversed()
private fun parsePlays1(input : String) = input.lines().map { line ->
val handAndBid = line.split(" ")
val cards: List<Card> = handAndBid[0].map { Card.ofStar1(it) }
val bid = handAndBid[1].toInt()
D7Play(cards, bid)
}
private fun parsePlays2(input : String) = input.lines().map { line ->
val handAndBid = line.split(" ")
val cards: List<Card> = handAndBid[0].map { Card.ofStar2(it) }
val bid = handAndBid[1].toInt()
D7Play(cards, bid)
}
}
val day7testInput = """
32T3K 765
T55J5 684
KK677 28
KTJJT 220
QQQJA 483
""".trimIndent()
val day7input = """
676AA 840
5J666 204
J4563 922
7373J 199
64882 944
TK9KK 457
54JA5 787
T8889 294
96TTT 503
88T88 662
J333A 524
K8T82 994
23552 253
2T8JJ 588
26772 972
J6Q6T 777
36A2A 5
KKKK3 509
T2T2T 793
9T49T 326
66QAQ 442
2TJ87 572
QKJK4 824
5A755 107
3847K 556
K7682 855
AJAJ3 882
44499 830
4J4KK 110
5AA5A 489
J5578 497
A3583 992
9A58A 452
Q2366 703
AA22J 749
5J522 534
Q7JQ7 802
7757Q 43
27338 239
TTT24 485
6488K 495
22QJQ 936
9AAJQ 194
222J9 959
QJA4K 809
2QQTQ 59
9J22J 109
44A33 714
A5AAJ 600
34QKK 924
698JA 148
82229 661
22423 951
AA495 516
A6J99 483
366A3 818
5549T 863
2A22A 397
ATKQ5 746
999K5 717
KQ622 375
4J448 722
KK55A 707
JJ224 622
555J3 190
7J74J 913
33AA8 570
22K23 522
3J7A7 200
53533 843
2Q5JJ 362
224QQ 638
8AA98 17
T99TT 916
Q94QQ 856
88Q68 606
824T4 289
8937Q 926
959A6 1000
274KA 407
74Q6K 72
93Q9K 828
486Q4 21
4KT94 702
AAA22 884
TT882 304
AAAT7 112
99399 138
999KJ 317
9KT7Q 346
TK99Q 644
39JQ7 247
88585 615
K83J8 981
QQQQK 625
66AKK 171
244JT 538
Q5394 12
KJJJK 458
88KK8 724
65566 993
JT89Q 45
T88TT 740
22299 618
8J73J 426
3JQJA 558
TT66T 804
Q6A74 654
66844 369
A5A6A 413
96TK3 161
33262 365
KKA39 225
J22T7 288
AKA96 37
A2KQ7 473
92A83 871
44555 642
33533 797
J2322 885
3J769 743
8Q866 812
QKKQQ 898
83Q94 946
8T3QK 233
J3Q3Q 823
73J94 157
AQJ5A 985
JTTTT 469
8AA2K 906
J92T9 983
2T4T4 803
3677J 596
4QAA3 505
666Q6 817
QQQAA 351
878QQ 541
6T622 178
33838 368
A2822 366
TT6AA 811
873AK 518
KKKK8 964
93833 682
KQJQK 16
AAAA3 242
54J89 866
92A9K 982
4QQQ6 665
QT979 185
36666 331
A4AAA 301
3QJQ2 590
K4298 460
Q66QJ 356
4888J 70
K3K55 149
47478 532
QQQTT 11
QQ2Q5 295
8588J 719
5A3JK 65
54225 106
J8QQK 324
KKQQ8 124
A2887 617
AQ2A6 907
2J72Q 711
AAAJA 248
JJA27 91
92J8Q 837
A8883 121
66446 341
888JQ 63
55296 651
332J8 555
T82J6 496
38538 241
32322 917
2T333 562
Q589J 891
35K55 419
23Q2A 685
Q3Q3Q 293
A8739 723
55599 114
77733 424
KKJJA 49
64J36 581
T3A5K 601
35A2K 563
3KK5K 453
55A66 383
62222 699
AAJ23 209
33343 394
9JJ99 921
A92TA 672
TT4T4 955
5T593 101
KKJ55 763
33383 833
66566 22
82272 645
4AJ27 914
63966 523
6K246 312
Q48J7 54
K77TK 174
J7578 510
KA6AA 342
9K898 798
9AT97 175
75555 493
22522 713
6A2KA 647
Q73Q3 561
A72A7 627
87J43 491
QQ3TQ 410
766T7 938
A666A 280
8AAJA 998
988J9 989
T4TT6 147
42A2Q 860
K8J75 637
9A9Q7 376
AKKJA 911
KA464 582
JJ59T 353
9AAAA 751
22K56 781
777K7 552
9TJ88 111
T46KK 551
2963K 593
53358 205
A4T87 267
77667 886
23QA3 197
Q8745 632
9K888 29
AA2J4 623
JTATT 78
24242 800
9Q94Q 206
8T989 939
46556 321
3A33A 140
KT345 382
99A97 98
KJK4A 28
TJ54J 732
2J789 877
22AJ2 847
KK222 849
55AA6 58
3J333 115
9KK37 126
9666A 995
6A833 821
79J5T 487
TT7J7 415
56349 372
T9723 229
42JA4 734
KKQ33 954
AA444 721
2K222 151
44445 928
A3894 244
Q88T8 436
88555 888
46666 850
8J222 492
4QJQ4 193
2J2J2 842
44644 814
T999T 650
9A643 223
TK9A9 484
4J546 810
3KKK7 62
K4499 327
56568 38
2AJKQ 952
4774A 657
547JJ 806
89949 571
246Q7 8
33AA6 116
76T64 254
88899 323
66T86 736
6KKK7 827
77666 224
K4T4T 792
Q68QQ 839
KTKT6 292
TQK26 88
63T9A 905
2292A 434
8QQQQ 39
53872 363
99JAK 704
7J273 795
QQQ77 23
92492 774
886TT 975
683K2 35
46857 759
K2549 389
468AA 526
27A22 521
J4J29 565
85T34 836
56542 359
K48AK 835
8987T 908
46644 347
495QK 678
22Q84 373
78775 60
33929 881
QQQQA 466
55537 15
223KK 261
QQ363 949
2TTTT 135
AAA8A 468
2A68J 227
88883 319
5QJ76 664
5K357 635
8K68K 3
99499 567
A6292 213
6T9KT 421
9K999 64
T8675 344
4Q44Q 46
88488 990
44A44 235
A5929 861
55J56 266
A77AQ 336
7757K 471
QQQQJ 291
K7J96 480
33239 652
J2AAA 263
77477 929
J6TJT 540
5J5A5 290
A5A7J 776
28K96 260
2255Q 958
K3596 18
2JAJT 900
K5555 329
57385 102
3T528 130
57775 461
TTTT9 942
3TQ35 160
K8333 335
JJKKK 53
74477 865
84K3K 187
245J3 86
5396T 310
T9A37 963
K2J2K 528
89233 991
7547J 499
J9TKT 919
KK8QK 196
5575T 779
58528 84
85228 584
JJTTT 367
QQQTQ 853
9J999 619
58JT5 862
2227T 609
66K6K 683
7Q58Q 411
666J4 71
6877Q 816
A5555 400
K779A 848
7A66K 195
K2TK2 602
7QQ9T 962
J38QK 659
97789 603
K887K 700
AJAA4 557
TQ428 449
79JQ4 219
QKKKK 527
999TQ 81
92992 667
2T22T 4
T58AA 566
J9595 154
58685 2
82J85 478
4J444 692
K7877 24
98899 74
2333J 298
9J327 950
8K694 826
2K9A5 639
JT7J6 459
K2A77 728
6T7TT 385
KKKKA 343
K28J8 144
6668A 883
7Q7J4 927
A3A6A 741
9JT68 760
66363 273
4848J 320
45454 339
33663 752
TJT5T 438
666A6 504
J5J55 851
23222 808
48443 834
95K95 258
8J2KK 656
44844 40
4TAJ5 744
8947T 546
222KQ 455
TKK99 515
6K55J 604
A32J9 841
K4444 99
K59A4 349
TA8AA 819
24J72 429
4939K 535
KQ3K8 318
2AKJ3 500
KKATT 517
JT752 454
3A2A5 550
46JTK 901
KKKTK 202
66662 511
63665 681
2AKQ3 640
7J692 542
4KK8K 393
33AAT 904
KK5KK 669
TT333 218
95Q6J 807
44334 401
8Q888 931
AAAQA 620
K6KK8 42
5TJ88 433
TTJT2 737
986JQ 113
75JA2 467
833A9 357
82Q4J 432
AKTAK 965
68886 694
35A93 137
33939 974
K454K 980
K9JKT 14
QQ34Q 910
4A6T5 896
93953 646
382J9 127
32726 377
75999 537
9392Q 697
A33AA 128
6584Q 237
A66AQ 894
67777 720
63333 674
T74Q2 846
T2222 756
AJTQA 630
48848 984
55636 392
3T8J4 948
5Q55J 575
6633Q 108
52K63 441
QTTTQ 337
84688 48
T7777 123
666T6 738
22227 381
2522A 757
55448 285
37389 633
JJJJJ 189
79799 259
82TTJ 747
9T95T 477
55587 610
499J9 416
TT5TT 612
29A53 414
5T5T5 36
92279 435
79T22 61
QA666 398
428K2 785
8883J 13
5577K 282
TJ78T 332
JA97J 238
TJ52K 214
QQ23Q 388
Q8Q5Q 786
Q69Q9 333
TTJKT 531
7JA62 680
52KJJ 987
77876 153
J3KK8 966
7Q7Q6 420
T4TA6 228
4T265 83
33933 873
83384 771
68K6K 340
33A9A 668
T7J33 50
3J76K 559
AAKK3 673
KJQQ6 322
24A4A 539
T45J4 969
3K5A3 428
AA6A6 687
2K788 380
7A975 971
8JQQ8 895
Q245J 574
QJQQJ 281
T8QTQ 405
4244J 624
QT5J9 350
4JKK7 51
JJ977 262
A8282 360
A958T 446
64Q43 822
K5K2K 348
J4TT4 684
27K98 150
48KJ7 501
9AA89 44
J4T3T 265
49878 472
73798 864
34335 69
254K6 255
J77JK 589
4KTJQ 256
287JJ 708
54TQ7 230
Q4KK4 727
565Q6 758
A7AAA 80
Q3K94 276
2J89K 897
JKJK8 286
28AK6 598
432KA 903
4888K 852
J77QT 870
56J56 636
KKKJ2 180
78877 134
7JJJ7 257
T8T8J 25
6TTTT 979
KKKJK 79
4Q6JJ 370
J3A37 361
44434 27
J8868 139
AAK8K 172
KQ8A8 440
Q6696 641
55525 796
6JJJ6 595
45JTQ 594
3K25K 250
AA343 671
5533T 173
674Q5 465
26999 34
9A9A9 677
5QT55 119
22229 20
3JQQJ 947
2626A 564
K5K5K 163
K7K7J 611
79769 854
K8KQ8 374
5726K 437
A66Q8 390
956J9 569
TT788 794
52867 791
22A6J 406
97999 986
K7748 100
TQ953 82
99A99 474
2T223 136
8666J 519
33723 303
TT3TT 243
J3QQ4 125
787JJ 26
A2QAQ 626
JJJJ6 371
92JQQ 482
36Q6T 167
AAAA5 451
3555T 597
K3K33 513
5228Q 252
5T393 967
T8T88 953
QQ464 427
56558 735
25822 226
546Q3 879
555T5 66
5JQ57 945
8338K 768
2J222 358
QQ44Q 418
3KJ98 536
85644 355
939AA 67
A25A2 6
9TTJ2 655
8K666 973
JT83K 391
76J77 876
QQT55 447
2K25K 957
52J22 545
2AT94 354
K22J2 1
33935 152
K6J3T 709
K3J38 813
9J9KK 498
QTJ24 832
J5454 634
86KKJ 770
4386K 338
KKQKQ 762
94T4T 578
25552 328
Q8835 742
767Q7 631
Q5K55 613
64287 307
22666 30
44494 915
KAAKA 867
78Q77 520
TK4TT 553
7Q77J 417
38Q4J 297
666JK 456
A8KAA 143
A997A 912
QQQ66 977
3A37A 210
T3T37 716
5954J 412
2Q22Q 384
79J54 270
QJA8Q 221
43A8T 512
62228 815
6569A 203
A6AAJ 878
5J545 616
75557 249
9QTQQ 245
52626 695
A77J7 182
78QJ8 543
AJAJA 605
74K82 729
77J22 874
34T5J 766
88337 548
9T794 423
32662 887
298TT 621
694J8 95
46995 166
J333J 778
2AA92 890
23288 679
67T94 755
T7242 893
KK7K7 789
55455 838
A899T 302
9T555 220
2A555 731
QQTJ7 643
99599 184
K746A 399
8798A 159
TJ63T 395
999T9 573
K8KT8 857
67666 753
KKK44 675
744KK 628
232J4 155
97777 706
4T446 507
7463T 933
35862 629
J9Q8K 334
88348 345
57T67 845
999J6 868
K4QQ7 968
QQA9Q 997
449QQ 892
64K32 169
855TT 689
899J6 488
KQ78J 296
66858 754
99Q38 653
T253J 576
75J27 162
J8JJJ 494
6KKKK 402
6963T 31
Q444A 686
666J6 745
7J777 544
T8TA8 772
9AQAQ 978
Q8292 19
33K33 750
AJ399 156
48AJK 476
TQT33 179
83A5K 131
32J2T 92
J2J28 663
7QJ75 314
J8T38 475
6K3AT 7
TTJ7J 932
7T584 820
Q5497 32
T33TT 490
J69J6 782
A5576 999
38A38 77
63686 533
38838 103
88887 309
77769 464
57335 439
9T8TK 909
53J33 599
8K49T 222
22T28 701
75756 207
777JJ 216
2TQJT 271
557Q7 236
K8TTK 47
JK67J 275
36524 181
TAJ8T 718
74397 448
2JQ92 158
3J838 765
4582A 97
QK933 956
66222 93
86JQ5 443
7JJ42 502
5T5A5 607
4ATTT 299
JJ8J8 305
TTATA 996
9KK9K 872
3AJAA 725
A4242 387
97K57 408
7K677 445
99429 94
393Q6 805
J7K77 306
JTAJ6 767
Q6447 696
972AT 710
2QQQ2 90
Q4Q4K 403
3KJ3K 56
55485 930
7J577 462
9ATA8 614
T9J79 712
59J64 170
89TT3 10
86866 586
AJ924 118
555J5 396
36J36 211
6TJJK 240
4447K 730
33AAJ 941
AQ24A 829
569Q2 943
44K4K 234
9Q263 773
55T58 923
J6J66 902
3734J 141
Q7Q4J 278
QQ5QA 587
TT9AT 579
TKK3T 75
89KK2 269
QQQQ6 961
332K6 698
33J3Q 186
K9875 268
696A9 330
TJA43 858
9Q66Q 76
2TJTJ 799
28866 775
J444J 880
Q8K54 470
3KQ84 33
JJ443 177
J6TTK 274
AT66A 217
98888 889
99998 283
TQ2KA 554
622J9 379
59T5T 188
27722 287
54778 769
Q84AJ 783
9TTT7 264
4J42Q 690
32JTT 165
4QQQQ 918
3QQJQ 325
883A4 486
3Q284 201
AKAAA 251
73JA5 164
72626 705
A7342 514
42222 272
7J32K 404
JK4T3 117
33373 215
QA256 284
T4T4A 899
TTATT 825
55KK2 934
J929A 246
QJ4K8 425
5A837 279
JJ888 431
KQKJ6 386
AJ8A8 89
JJJA7 9
388J4 970
88J88 120
78J69 133
AT3T7 506
K9929 960
2QTJK 976
28289 935
84AJ4 940
328J2 577
7344J 525
77997 715
3J6J6 925
949J6 277
9TAT9 733
235QA 920
8J282 409
825KJ 364
7Q7Q7 212
54772 315
7AA7A 104
6A985 547
22228 129
K5KJK 693
252T8 726
K3KK3 176
33377 560
3KK2J 132
4J875 183
92T47 68
5Q376 748
T46KT 313
4JJ8J 801
745Q7 585
Q2K47 549
43525 875
AKK79 41
T8858 580
Q6976 688
8A8AA 761
2K6KK 168
4848T 788
53232 988
T9389 869
KJ34J 96
77T44 859
J8333 300
J5J35 122
923KK 57
88828 352
3864J 529
4AQQK 608
33QT3 378
33759 530
444Q4 937
72454 450
77A66 831
2K22A 790
485A5 52
98T68 208
78772 481
QQ7QQ 73
95A59 479
93T52 780
995KK 192
96J66 670
59995 105
72575 764
T3769 422
86656 739
55Q55 508
J6569 658
6QQT2 145
A9T68 232
JKK92 691
TT82Q 463
J4477 591
K5AK3 648
22552 676
355QQ 142
3T7A2 444
TQTTT 316
JJJJQ 844
64729 666
TKTKK 568
K2975 198
K8K99 430
5855J 660
J4A43 583
2224T 85
727Q2 146
T4JTK 308
4J3KQ 784
QAJAQ 311
45884 191
484K8 649
JAA66 592
49848 87
AATAT 231
57QQ5 55
""".trimIndent() | 0 | Kotlin | 0 | 0 | 660d1a5733dd533aff822f0e10166282b8e4bed9 | 18,070 | AOC2023 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/com/groundsfam/advent/y2021/d08/Day08.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2021.d08
import com.groundsfam.advent.DATAPATH
import com.groundsfam.advent.timed
import kotlin.io.path.div
import kotlin.io.path.useLines
fun segmentsToDigit(segments: Set<Char>) = when (segments) {
"abcefg".toSet() -> 0
"cf".toSet() -> 1
"acdeg".toSet() -> 2
"acdfg".toSet() -> 3
"bcdf".toSet() -> 4
"abdfg".toSet() -> 5
"abdefg".toSet() -> 6
"acf".toSet() -> 7
"abcdefg".toSet() -> 8
"abcdfg".toSet() -> 9
else -> throw RuntimeException("Invalid segments $segments")
}
data class Note(val signalPatterns: Set<Set<Char>>, val outputValue: List<String>) {
// signalMap sends the segment in this note to the standard segment name for the same physical segment
private val segmentMap: Map<Char, Char>
init {
val map = mutableMapOf<Char, Char>()
val counts = "abcdefg".groupBy { c ->
signalPatterns.count { c in it }
}
// these segments appear a unique number of times across all digits
map[counts[6]!!.first()] = 'b'
map[counts[4]!!.first()] = 'e'
map[counts[9]!!.first()] = 'f'
// segment c appears in the digit 1, along with f
signalPatterns
.first { it.size == 2 }
.first { it !in map.keys }
.also { map[it] = 'c' }
// segments a and c appear in eight digits
counts[8]!!
.first { it !in map.keys }
.also { map[it] = 'a' }
// segment d appears in the digit 4, g does not
signalPatterns
.first { it.size == 4 }
.first { it !in map.keys }
.also { map[it] = 'd' }
// segments d and g appear in seven digits
counts[7]!!
.first { it !in map.keys }
.also { map[it] = 'g' }
segmentMap = map
}
val decodedOutput: Int get() =
outputValue
.map { codedSegments ->
codedSegments.mapTo(mutableSetOf()) { c -> segmentMap[c]!! }
}
.fold(0) { n, decodedSegments ->
n * 10 + segmentsToDigit(decodedSegments)
}
}
fun main() = timed {
val notes: List<Note> = (DATAPATH / "2021/day08.txt").useLines { lines ->
lines.mapTo(mutableListOf()) { line ->
line.split(" | ").let { (first, second) ->
val signalPatterns = first
.split(" ")
.mapTo(mutableSetOf()) {
it.toSet()
}
Note(signalPatterns, second.split(" "))
}
}
}
notes
.sumOf { note ->
note.outputValue.count { it.length in setOf(2, 3, 4, 7) }
}
.also { println("Part one: $it") }
notes
.sumOf { it.decodedOutput }
.also { println("Part two: $it") }
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 2,866 | advent-of-code | MIT License |
grind-75-kotlin/src/main/kotlin/FloodFill.kt | Codextor | 484,602,390 | false | {"Kotlin": 27206} | /**
* An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image.
*
* You are also given three integers sr, sc, and color.
* You should perform a flood fill on the image starting from the pixel image[sr][sc].
*
* To perform a flood fill, consider the starting pixel,
* plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel,
* plus any pixels connected 4-directionally to those pixels (also with the same color), and so on.
* Replace the color of all of the aforementioned pixels with color.
*
* Return the modified image after performing the flood fill.
*
*
*
* Example 1:
*
*
* Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2
* Output: [[2,2,2],[2,2,0],[2,0,1]]
* Explanation: From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel),
* all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.
* Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.
* Example 2:
*
* Input: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0
* Output: [[0,0,0],[0,0,0]]
* Explanation: The starting pixel is already colored 0, so no changes are made to the image.
*
*
* Constraints:
*
* m == image.length
* n == image[i].length
* 1 <= m, n <= 50
* 0 <= image[i][j], color < 2^16
* 0 <= sr < m
* 0 <= sc < n
* @see <a href="https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/">LeetCode</a>
*/
fun floodFill(image: Array<IntArray>, sr: Int, sc: Int, color: Int): Array<IntArray> {
val startingPixelColor = image[sr][sc]
if (startingPixelColor == color) {
return image
}
fun recursiveFill(startingRow: Int, startingColumn: Int) {
image[startingRow][startingColumn] = color
directions.map { Pair(startingRow + it.first, startingColumn + it.second) }
.filter { pixel ->
pixel.first in 0 until image.size &&
pixel.second in 0 until image[0].size &&
image[pixel.first][pixel.second] == startingPixelColor
}.forEach { pixel ->
recursiveFill(pixel.first, pixel.second)
}
}
recursiveFill(sr, sc)
return image
}
private val directions = listOf(
Pair(-1, 0),
Pair(1, 0),
Pair(0, -1),
Pair(0, 1)
)
| 0 | Kotlin | 0 | 0 | 87aa60c2bf5f6a672de5a9e6800452321172b289 | 2,487 | grind-75 | Apache License 2.0 |
src/year2015/day12/Day12.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2015.day12
import readInput
fun main() {
val input = readInput("2015", "Day12")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>) = input.first()
.split("(\\[|]|,|:|\\{|})".toRegex())
.sumOf { it.toIntOrNull() ?: 0 }
private fun part2(input: List<String>) = sumOfNotRed(input.first())
private fun sumOfNotRed(input: String): Int {
if (input.isArray()) {
return input.removeBrackets().children().sumOf { it.toIntOrNull() ?: sumOfNotRed(it) }
}
if (input.isObject()) {
val children = input.removeBrackets().children()
val hasRed = children.any { it.startsWith("\"red\":") || it.endsWith(":\"red\"") }
if (hasRed) return 0
val values = children.map { it.substringAfter(':') }
return values.sumOf { it.toIntOrNull() ?: sumOfNotRed(it) }
}
return input.toIntOrNull() ?: 0
}
private fun String.isObject() = startsWith("{")
private fun String.isArray() = startsWith("[")
private fun String.removeBrackets() = substring(1, lastIndex)
private fun String.children(): List<String> {
if (isEmpty()) return emptyList()
val children = mutableListOf<String>()
var start = 0
var bracketCount = 0
this.forEachIndexed { i, c ->
when (c) {
'{', '[' -> bracketCount++
'}', ']' -> bracketCount--
}
if (c == ',' && bracketCount == 0) {
children += substring(start, i)
start = i + 1
}
}
children += substring(start, length)
return children
} | 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 1,572 | AdventOfCode | Apache License 2.0 |
src/y2016/Day22.kt | gaetjen | 572,857,330 | false | {"Kotlin": 325874, "Mermaid": 571} | package y2016
import util.Pos
import util.printGrid
import util.readInput
data class DiskNode(
val pos: Pos,
val size: Int,
val used: Int,
val avail: Int,
val percent: Int
) {
companion object {
fun fromString(string: String): DiskNode {
val els = string.split(Regex("\\s+"))
val (posX, posY) = els[0].replace("x", "").replace("y", "").split('-').takeLast(2)
val nums = els.drop(1).map { it.dropLast(1).toInt() }
return DiskNode(
posX.toInt() to posY.toInt(),
nums[0],
nums[1],
nums[2],
nums[3]
)
}
}
}
object Day22 {
private fun parse(input: List<String>): List<DiskNode> {
return input.drop(2).map {
DiskNode.fromString(it)
}
}
fun part1(input: List<String>): Int {
val parsed = parse(input)
val toRemove = parsed.count {
it.avail >= it.used && it.used > 0
}
val useds = parsed.map { it.used }.sorted().dropWhile { it == 0 }
var avails = parsed.map { it.avail }.sorted()
println(useds)
println(avails)
println(parsed.map { it.size }.sorted())
var viables = 0
useds.forEach { used ->
avails = avails.dropWhile { it < used }
viables += avails.size
}
return viables - toRemove
}
fun part2(input: List<String>): Int {
val parsed = parse(input)
printGrid(
parsed.associate {
it.pos to if(it.size <= 500) "_" else "#"
}
)
val blockers = parsed.filter { it.size > 500 }
println(blockers)
println(parsed.sortedBy { it.percent }.take(4))
val maxX = parsed.maxOf { it.pos.first }
val empty = parsed.first { it.used == 0 }
val distanceToTarget = empty.pos.second + empty.pos.first + maxX
return distanceToTarget + 5 * (maxX - 1)
}
}
fun main() {
val testInput = """
root@ebhq-gridcenter# df -h
Filesystem Size Used Avail Use%
/dev/grid/node-x0-y0 10T 8T 2T 80%
/dev/grid/node-x0-y1 11T 6T 5T 54%
/dev/grid/node-x0-y2 32T 28T 4T 87%
/dev/grid/node-x1-y0 9T 7T 2T 77%
/dev/grid/node-x1-y1 8T 0T 8T 0%
/dev/grid/node-x1-y2 11T 7T 4T 63%
/dev/grid/node-x2-y0 10T 6T 4T 60%
/dev/grid/node-x2-y1 9T 8T 1T 88%
/dev/grid/node-x2-y2 9T 6T 3T 66%
""".trimIndent().split("\n")
println("------Tests------")
println(Day22.part1(testInput))
println(Day22.part2(testInput))
println("------Real------")
val input = readInput("resources/2016/day22")
println(Day22.part1(input))
println(Day22.part2(input))
} | 0 | Kotlin | 0 | 0 | d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a | 2,918 | advent-of-code | Apache License 2.0 |
aoc-2023/src/main/kotlin/aoc/aoc15.kts | triathematician | 576,590,518 | false | {"Kotlin": 615974} | import aoc.AocParser.Companion.parselines
import aoc.*
import aoc.util.getDayInput
val testInput = """
rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7
""".parselines
fun String.hash(): Int {
var hash = 0
for (i in 0 until length) {
hash = (17 * (hash + get(i).code)) % 256
}
return hash
}
println("HASH".hash())
// part 1
fun List<String>.part1(): Int = first().split(",").sumOf { it.hash() }
// part 2
fun List<String>.part2(): Int {
val boxes = (0..255).associateWith { mutableMapOf<String, Int>() }
first().split(",").onEach {
val eq = it.indexOf("=")
val min = it.indexOf("-")
val label = it.substring(0, maxOf(eq, min))
val value = if (eq > 0) it.substring(eq + 1).toInt() else 0
val hash = label.hash()
val box = boxes[hash]!!
if (eq > 0) {
// this will overwrite current value or add another on the end
box[label] = value
} else {
box.remove(label)
}
}
return boxes.entries.sumOf { (num, content) ->
content.entries.withIndex().sumOf { (index, value) ->
(num + 1) * (index + 1) * value.value
}
}
}
// calculate answers
val day = 15
val input = getDayInput(day, 2023)
val testResult = testInput.part1()
val testResult2 = testInput.part2()
val answer1 = input.part1().also { it.print }
val answer2 = input.part2().also { it.print }
// print results
AocRunner(day,
test = { "$testResult, $testResult2" },
part1 = { answer1 },
part2 = { answer2 }
).run()
| 0 | Kotlin | 0 | 0 | 7b1b1542c4bdcd4329289c06763ce50db7a75a2d | 1,565 | advent-of-code | Apache License 2.0 |
src/main/kotlin/day7/Day7.kt | cyril265 | 433,772,262 | false | {"Kotlin": 39445, "Java": 4273} | package day7
import readToList
import kotlin.math.abs
val input = readToList("day7.txt").first().split(",").map { it.toInt() }
fun main() {
println(part1())
println(part2())
}
private fun part1(): Int {
val sorted = input.sorted()
val size = sorted.size
val median = if (size % 2 == 0) {
(sorted[size / 2] + sorted[size / 2 - 1]) / 2.0
} else {
sorted[size / 2].toDouble()
}.toInt()
return sorted.sumOf { pos -> abs(pos - median) }
}
private fun part2(): Int {
val minPosition = input.minOf { it }
val maxPosition = input.maxOf { it }
return (minPosition..maxPosition)
.minOf { possiblePosition ->
input.sumOf { crabPosition -> distanceBetween(crabPosition, possiblePosition) }
}
}
private fun distanceBetween(crabPosition: Int, possiblePosition: Int) =
gaussSum(abs(crabPosition - possiblePosition))
private fun gaussSum(n: Int) = (n * n + n) / 2
| 0 | Kotlin | 0 | 0 | 1ceda91b8ef57b45ce4ac61541f7bc9d2eb17f7b | 952 | aoc2021 | Apache License 2.0 |
src/day16/Code.kt | fcolasuonno | 162,470,286 | false | null | package day16
import java.io.File
fun main(args: Array<String>) {
val name = if (true) "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)}")
println("Part 2 = ${part2(parsed)}")
}
data class Sue(val name: String, val attribs: Map<String, Int>)
private val lineStructure = """Sue (\d+): (\w+): (\d+), (\w+): (\d+), (\w+): (\d+)""".toRegex()
val detect = mapOf(
"children" to 3,
"cats" to 7,
"samoyeds" to 2,
"pomeranians" to 3,
"akitas" to 0,
"vizslas" to 0,
"goldfish" to 5,
"trees" to 3,
"cars" to 2,
"perfumes" to 1
)
fun parse(input: List<String>) = input.map {
lineStructure.matchEntire(it)?.destructured?.let {
val sue = it.toList()
Sue(sue.first(), sue.drop(1).chunked(2).map { (attr, number) -> attr to number.toInt() }.toMap())
}
}.requireNoNulls()
fun part1(input: List<Sue>): Any? = input.single { sue ->
detect.filterKeys { it in sue.attribs.keys } == sue.attribs
}.name
fun part2(input: List<Sue>): Any? {
val exclusions = listOf("cats", "trees", "pomeranians", "goldfish")
val exact = detect - exclusions
return input.single { sue ->
exact.filterKeys { it in sue.attribs.keys } == sue.attribs - exclusions &&
(sue.attribs["cats"] ?: Int.MAX_VALUE) > detect.getValue("cats") &&
(sue.attribs["trees"] ?: Int.MAX_VALUE) > detect.getValue("trees") &&
(sue.attribs["pomeranians"] ?: 0) < detect.getValue("pomeranians") &&
(sue.attribs["goldfish"] ?: 0) < detect.getValue("goldfish")
}.name
}
| 0 | Kotlin | 0 | 0 | 24f54bf7be4b5d2a91a82a6998f633f353b2afb6 | 1,716 | AOC2015 | MIT License |
src/main/kotlin/days/Day7.kt | broersma | 574,686,709 | false | {"Kotlin": 20754} | package days
class Day7 : Day(7) {
private fun sizeOfPath(tree: Map<List<String>, Set<Any>>, path: List<String>): Int {
return tree[path]!!
.map { if (it is List<*>) sizeOfPath(tree, it as List<String>) else it as Int }
.sum()
}
override fun partOne(): Int {
var tree = mutableMapOf<List<String>, MutableSet<Any>>()
var path = mutableListOf<String>()
inputString.split("$ ").drop(2).map { it.trim() }.forEach {
if (it.startsWith("cd")) {
val targetDir = it.split(" ")[1]
if (targetDir == "..") {
path.removeLast()
} else {
if (!tree.containsKey(path)) {
tree[path.toList()] = mutableSetOf()
}
tree[path.toList()]!!.add(path + targetDir)
path.add(targetDir)
}
} else if (it.startsWith("ls")) {
it.split("\n").drop(1).filter { !it.startsWith("dir ") }.forEach {
val parts = it.split(" ")
val size = parts[0].toInt()
if (!tree.containsKey(path)) {
tree[path.toList()] = mutableSetOf()
}
tree[path.toList()]!!.add(size)
}
}
}
return tree.map { sizeOfPath(tree, it.key) }.filter { it <= 100_000 }.sum()
}
override fun partTwo(): Int {
var tree = mutableMapOf<List<String>, MutableSet<Any>>()
var path = mutableListOf<String>()
inputString.split("$ ").drop(2).map { it.trim() }.forEach {
if (it.startsWith("cd")) {
val targetDir = it.split(" ")[1]
if (targetDir == "..") {
path.removeLast()
} else {
if (!tree.containsKey(path)) {
tree[path.toList()] = mutableSetOf()
}
tree[path.toList()]!!.add(path + targetDir)
path.add(targetDir)
}
} else if (it.startsWith("ls")) {
it.split("\n").drop(1).filter { !it.startsWith("dir ") }.forEach {
val parts = it.split(" ")
val size = parts[0].toInt()
if (!tree.containsKey(path)) {
tree[path.toList()] = mutableSetOf()
}
tree[path.toList()]!!.add(size)
}
}
}
val unusedSpace = 70000000 - sizeOfPath(tree, listOf())
val minimalDeletedSize = 30000000 - unusedSpace
return tree.map { sizeOfPath(tree, it.key) }.filter { it > minimalDeletedSize }.min()
}
}
| 0 | Kotlin | 0 | 0 | cd3f87e89f7518eac07dafaaeb0f6adf3ecb44f5 | 2,823 | advent-of-code-2022-kotlin | Creative Commons Zero v1.0 Universal |
logicsolver/src/main/kotlin/nl/hiddewieringa/logicsolver/Input.kt | hiddewie | 147,922,971 | false | null | package nl.hiddewieringa.logicsolver
import java.util.regex.Pattern
data class LogicSolveError(override val message: String) : Exception(message)
data class Coordinate(val a: Int, val b: Int) : Comparable<Coordinate> {
override fun compareTo(other: Coordinate): Int {
return compareBy<Coordinate>({ it.a }, { it.b })
.compare(this, other)
}
}
val sudokuRange = (1..9)
fun coordinates(range: IntRange, x: (i: Int) -> Int, y: (I: Int) -> Int): Set<Coordinate> {
return range.map {
Coordinate(x(it), y(it))
}.toSet()
}
val sudokuPuzzleValues = (1..9).toSet()
fun Collection<Coordinate>.translate(dx: Int, dy: Int): Set<Coordinate> {
return map {
Coordinate(it.a + dx, it.b + dy)
}.toSet()
}
fun Collection<Coordinate>.translateX(dx: Int): Set<Coordinate> {
return translate(dx, 0)
}
fun Collection<Coordinate>.translateY(dy: Int): Set<Coordinate> {
return translate(0, dy)
}
fun row(range: IntRange, i: Int): Set<Coordinate> {
return coordinates(range, { i }, { it })
}
fun column(range: IntRange, i: Int): Set<Coordinate> {
return coordinates(range, { it }, { i })
}
fun block(i: Int, width: Int, height: Int): Set<Coordinate> {
return coordinates((1..(width * height)), {
1 + height * ((i - 1) / height) + (it - 1) / width
}, {
1 + width * ((i - 1) % height) + (it - 1) % width
})
}
fun diagonalTB(): Set<Coordinate> {
return coordinates(sudokuRange, { it }, { sudokuRange.max()!! + 1 - it })
}
fun diagonalBT(): Set<Coordinate> {
return coordinates(sudokuRange, { it }, { it })
}
fun hyperBlock(i: Int): Set<Coordinate> {
return coordinates(sudokuRange, {
2 + 4 * ((i - 1) / 2) + (it - 1) / 3
}, {
2 + 4 * ((i - 1) % 2) + (it - 1) % 3
})
}
val sudokuCoordinates = sudokuRange.flatMap { i ->
sudokuRange.map { j ->
Coordinate(i, j)
}
}
fun readSudokuValueMapFromString(s: String): Map<Coordinate, Int> {
return readValueMapFromString(s, sudokuCoordinates)
}
fun validSudokuValue(value: String): Boolean {
return value.length == 1 && value.toIntOrNull() != null && value.toInt() >= 1 && value.toInt() <= 9
}
fun readValueMapFromString(s: String, coordinates: List<Coordinate>): Map<Coordinate, Int> {
val split = s.split(Pattern.compile("\\s+")).filter { it.isNotEmpty() }
if (split.size != coordinates.size) {
throw Exception("Input size (${split.size}) should be ${coordinates.size} non-whitespace strings")
}
return split.zip(coordinates.sorted())
.filter { validSudokuValue(it.first) }
.map { it.second to it.first.toInt() }
.toMap()
}
val sudokuGroups = sudokuRange.flatMap {
listOf(row(sudokuRange, it), column(sudokuRange, it), block(it, 3, 3))
}
class Sudoku(values: Map<Coordinate, Int>) : SudokuInput(values, sudokuGroups, sudokuCoordinates, sudokuPuzzleValues) {
companion object {
fun readFromString(s: String): Sudoku {
return Sudoku(readSudokuValueMapFromString(s))
}
}
}
val hyperGroups = sudokuGroups + (1..4).map { hyperBlock(it) }
class SudokuHyper(values: Map<Coordinate, Int>) : SudokuInput(values, hyperGroups, sudokuCoordinates, sudokuPuzzleValues) {
companion object {
fun readFromString(s: String): SudokuHyper {
return SudokuHyper(readSudokuValueMapFromString(s))
}
}
}
class SudokuX(values: Map<Coordinate, Int>) : SudokuInput(values, sudokuGroups + listOf(diagonalBT(), diagonalTB()), sudokuCoordinates, sudokuPuzzleValues) {
companion object {
fun readFromString(s: String): SudokuX {
return SudokuX(readSudokuValueMapFromString(s))
}
}
}
val doubleSudokuRange = (1..15)
val doubleSudokuCoordinates = doubleSudokuRange.flatMap { i ->
sudokuRange.map { j ->
Coordinate(i, j)
}
}
val doubleSudokuGroups = doubleSudokuRange.map { row(sudokuRange, it) } +
sudokuRange.flatMap { i -> listOf(column(sudokuRange, i), column(sudokuRange, i).translateX(6)) } +
doubleSudokuRange.map { block(it, 3, 3) }
class SudokuDouble(values: Map<Coordinate, Int>) : SudokuInput(values, doubleSudokuGroups, doubleSudokuCoordinates, sudokuPuzzleValues) {
companion object {
fun readFromString(s: String): SudokuDouble {
return SudokuDouble(readValueMapFromString(s, doubleSudokuCoordinates))
}
}
}
val samuraiCoordinates = (sudokuCoordinates +
sudokuCoordinates.translate(6, 6) +
sudokuCoordinates.translate(12, 12) +
sudokuCoordinates.translateX(12) +
sudokuCoordinates.translateY(12)
).toSet().toList()
val samuraiGroups = (sudokuGroups +
sudokuGroups.map { it.translate(6, 6) } +
sudokuGroups.map { it.translate(12, 12) } +
sudokuGroups.map { it.translateX(12) } +
sudokuGroups.map { it.translateY(12) }
).toSet().toList()
class SudokuSamurai(values: Map<Coordinate, Int>) : SudokuInput(values, samuraiGroups, samuraiCoordinates, sudokuPuzzleValues) {
companion object {
fun readFromString(s: String): SudokuSamurai {
return SudokuSamurai(readValueMapFromString(s, samuraiCoordinates))
}
}
}
val sudokuTinyRange = (1..6)
val sudokuTinyCoordinates = sudokuTinyRange.flatMap { i ->
sudokuTinyRange.map { j ->
Coordinate(i, j)
}
}
val sudokuTinyGroups = sudokuTinyRange.flatMap {
listOf(row(sudokuTinyRange, it), column(sudokuTinyRange, it), block(it, 3, 2))
}
val sudokuTinyPuzzleValues = (1..6).toSet()
class SudokuTiny(values: Map<Coordinate, Int>) : SudokuInput(values, sudokuTinyGroups, sudokuTinyCoordinates, sudokuTinyPuzzleValues) {
companion object {
fun readFromString(s: String): SudokuTiny {
return SudokuTiny(readValueMapFromString(s, sudokuTinyCoordinates))
}
}
}
open class SudokuInput(val values: Map<Coordinate, Int>, val groups: List<Set<Coordinate>>, val coordinates: List<Coordinate>, val puzzleValues: Set<Int>)
| 0 | Kotlin | 0 | 0 | bcf12c102f4ab77c5aa380dbf7c98a1cc3e585c0 | 6,244 | LogicSolver | MIT License |
src/test/kotlin/Day16.kt | christof-vollrath | 317,635,262 | false | null | import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
/*
--- Day 16: Ticket Translation ---
See https://adventofcode.com/2020/day/16
*/
fun List<List<Int>>.filterTicketsSatisfyingAnyRule(rules: List<TicketRule>): List<List<Int>> =
filter { ticket ->
ticket.all { value ->
rules.any { rule ->
rule.ranges.any { range ->
value in range
}
}
}
}
fun List<List<Int>>.filterValuesNotSatisfyingAllRules(rules: List<TicketRule>): List<List<Int>> =
map { ticket ->
ticket.filterValueInTicketNotSatisfyingAllRules(rules)
}
fun List<Int>.filterValueInTicketNotSatisfyingAllRules(ticketRules: List<TicketRule>) =
filter { value ->
val ranges = ticketRules.flatMap { it.ranges }
ranges.all { range ->
value !in range
}
}
fun parseTrainTicketNotes(inputString: String): TrainTicketNotes {
val lines = inputString.split("\n")
val ruleStrings = lines.takeWhile { ! it.startsWith("your ticket") }
val rules = ruleStrings.filter{ it.isNotEmpty() }.map { parseTicketRule(it)}
val myTicketString = lines.dropWhile { ! it.startsWith("your ticket")}.drop(1).first()
val myTicket = parseTicket(myTicketString)
val nearbyTicketsString = lines.dropWhile { ! it.startsWith("nearby ticket")}.drop(1)
val nearbyTickets = nearbyTicketsString.filter{ it.isNotEmpty() }.map { parseTicket(it) }
return TrainTicketNotes(rules, myTicket, nearbyTickets)
}
data class TrainTicketNotes(val rules: List<TicketRule>, val yourTicket: List<Int>, val nearbyTickets: List<List<Int>>)
fun parseTicket(ticketString: String): List<Int> = ticketString.split(",").map {
it.trim().toInt()
}
fun parseTicketRule(ticketRuleString: String): TicketRule {
val regex = """([a-z0-9 ]+): (\d+)-(\d+) or (\d+)-(\d+)""".toRegex()
val match = regex.find(ticketRuleString) ?: throw IllegalArgumentException("Can not parse input=$ticketRuleString")
if (match.groupValues.size != 6) throw IllegalArgumentException("Wrong number of elements parsed")
val name = match.groupValues[1]
val rules = sequence {
for (i in 2..5 step 2) {
val from = match.groupValues[i].toInt()
val to = match.groupValues[i+1].toInt()
yield(from..to)
}
}.toList()
return TicketRule(name, rules)
}
data class TicketRule(val name: String, val ranges: List<IntRange>)
fun findRuleForRows(yourTicket: List<Int>, tickets: List<List<Int>>, rules: List<TicketRule>): Map<String, Int> {
val ruleForColumnMap = mutableMapOf<TicketRule, Int>()
while (ruleForColumnMap.size < yourTicket.size) {
for (columnIndex in yourTicket.indices) {
val rulesForColumn = findRuleForColumn(tickets, rules, columnIndex)
val filteredRulesForColumn = rulesForColumn - ruleForColumnMap.keys // Ignore already found rules
if (filteredRulesForColumn.size == 1) { // Found a unique rule
val rule = filteredRulesForColumn.first()
ruleForColumnMap[rule] = columnIndex
}
}
}
return ruleForColumnMap.entries.map { (key, value) -> key.name to yourTicket[value] }.toMap()
}
fun findRuleForColumn(tickets: List<List<Int>>, rules: List<TicketRule>, columnIndex: Int): List<TicketRule> {
val column = tickets.map { it[columnIndex] }
return rules.filter { rule ->
column.all { value ->
rule.ranges.any { range -> value in range}
}
}
}
class Day16_Part1 : FunSpec({
val exampleString = """
class: 1-3 or 5-7
row: 6-11 or 33-44
seat: 13-40 or 45-50
your ticket:
7,1,14
nearby tickets:
7,3,47
40,4,50
55,2,20
38,6,12
""".trimIndent()
context("parse train tickets") {
context("parse ticket rule class") {
val ticketRuleString = "class: 1-3 or 5-7"
val ticketRule = parseTicketRule(ticketRuleString)
test("ticket rule is parsed correctly") {
ticketRule.name shouldBe "class"
ticketRule.ranges shouldBe listOf(1..3, 5..7)
}
}
context("parse ticket rule departure location") {
val ticketRuleString = "departure location: 27-374 or 395-974"
val ticketRule = parseTicketRule(ticketRuleString)
test("ticket rule is parsed correctly") {
ticketRule.name shouldBe "departure location"
ticketRule.ranges shouldBe listOf(27..374, 395..974)
}
}
context("parse ticket") {
val ticketString = "7,3,47"
val ticket = parseTicket(ticketString)
test("ticket is parsed correctly") {
ticket shouldBe listOf(7, 3, 47)
}
}
context("parse notes") {
val notes = parseTrainTicketNotes(exampleString)
test("notes should be parsed correctly") {
notes.rules.size shouldBe 3
notes.rules[1] shouldBe TicketRule("row", listOf(6..11, 33..44))
notes.yourTicket shouldBe listOf(7, 1, 14)
notes.nearbyTickets.size shouldBe 4
notes.nearbyTickets[1] shouldBe listOf(40, 4, 50)
}
}
}
context("filter valid tickets") {
val notes = parseTrainTicketNotes(exampleString)
val filtered = notes.nearbyTickets.filterTicketsSatisfyingAnyRule(notes.rules)
test("should have filtered values") {
filtered shouldBe listOf(
listOf(7, 3, 47)
)
}
}
context("filter invalid tickets") {
val notes = parseTrainTicketNotes(exampleString)
val filtered = notes.nearbyTickets.filterValuesNotSatisfyingAllRules(notes.rules)
test("should have filtered values") {
filtered.flatten() shouldBe listOf(4, 55, 12)
}
test("should have calculated correct sum") {
filtered.flatten().sum() shouldBe 71
}
}
})
class Day16_Part1_Exercise: FunSpec({
val input = readResource("day16Input.txt")!!
val notes = parseTrainTicketNotes(input)
val filtered = notes.nearbyTickets.filterValuesNotSatisfyingAllRules(notes.rules)
test("should have calculated correct sum") {
filtered.flatten().sum() shouldBe 26941
}
})
class Day16_Part2 : FunSpec({
val exampleString = """
class: 0-1 or 4-19
row: 0-5 or 8-19
seat: 0-13 or 16-19
your ticket:
11,12,13
nearby tickets:
3,9,18
15,1,5
5,14,9
""".trimIndent()
val notes = parseTrainTicketNotes(exampleString)
context("find rules for row") {
val rules = findRuleForColumn(notes.nearbyTickets, notes.rules, 0)
test("should have found rules") {
rules.first().name shouldBe "row"
}
}
context("find rules for rows") {
val columnMapping = findRuleForRows(notes.yourTicket, notes.nearbyTickets, notes.rules)
test("should have found mappings") {
columnMapping shouldBe mapOf(
"class" to 12,
"row" to 11,
"seat" to 13
)
}
}
})
class Day16_Part2_Exercise: FunSpec({
val input = readResource("day16Input.txt")!!
val notes = parseTrainTicketNotes(input)
val filteredTickets = notes.nearbyTickets.filterTicketsSatisfyingAnyRule(notes.rules)
val columnMapping = findRuleForRows(notes.yourTicket, filteredTickets, notes.rules)
val columnMappingDeparture = columnMapping.entries.filter { (key, _) -> key.startsWith("departure") }
println(columnMappingDeparture)
val solution = columnMappingDeparture.map { (_, value) -> value }.map { it.toLong() }.reduce { a, b -> a * b}
test("should have calculated correct solution") {
solution shouldBe 634796407951L
}
})
| 1 | Kotlin | 0 | 0 | 8ad08350aa4bd1a29b7e18765fc7a2d6de8021e8 | 7,954 | advent_of_code_2020 | Apache License 2.0 |
src/Day12.kt | tomoki1207 | 572,815,543 | false | {"Kotlin": 28654} | import java.util.*
data class Point(val row: Int, val col: Int, val mark: Char) {
val elevation = when (mark) {
'S' -> 'a'
'E' -> 'z'
else -> mark
}.code
fun climbable(other: Point): Boolean {
return elevation - other.elevation >= -1
}
}
fun main() {
fun solve(
input: List<String>,
determineStart: (Point) -> Boolean,
determineEnd: (Point) -> Boolean,
climbPredicate: (Point, Point) -> Boolean
): Int {
var start: Point? = null
val grid = input.mapIndexed { row, line ->
row to line.mapIndexed { col, c ->
val p = Point(row, col, c)
if (determineStart(p)) {
start = p
}
col to p
}.toMap()
}.toMap()
val closed = mutableSetOf<Point>()
var open = LinkedList<Point>().also { it.add(start!!) }
var step = 0
while (true) {
val tmp = LinkedList<Point>()
while (open.isNotEmpty()) {
val current = open.poll()
if (determineEnd(current)) {
return step
}
if (!closed.add(current)) {
continue
}
// up,down,right,left
grid[current.row - 1]?.get(current.col)?.let { up ->
if (climbPredicate(current, up)) {
tmp.add(up)
}
}
grid[current.row + 1]?.get(current.col)?.let { down ->
if (climbPredicate(current, down)) {
tmp.add(down)
}
}
grid[current.row]?.get(current.col - 1)?.let { left ->
if (climbPredicate(current, left)) {
tmp.add(left)
}
}
grid[current.row]?.get(current.col + 1)?.let { right ->
if (climbPredicate(current, right)) {
tmp.add(right)
}
}
}
open = tmp
step++
}
}
fun part1(input: List<String>) = solve(input, { p -> p.mark == 'S' }, { p -> p.mark == 'E' },
{ curr, aimTo -> curr.climbable(aimTo) })
fun part2(input: List<String>) = solve(input, { p -> p.mark == 'E' }, { p -> p.elevation == 'a'.code },
{ curr, aimTo -> aimTo.climbable(curr) })
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2ecd45f48d9d2504874f7ff40d7c21975bc074ec | 2,729 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day05.kt | juliantoledo | 570,579,626 | false | {"Kotlin": 34375} | fun main() {
fun processInput(input: List<String>, columns: Int): Pair<Array<MutableList<Char>>, MutableList<Triple<Int,Int, Int>>> {
var stacks = Array<MutableList<Char>>(columns){mutableListOf<Char>()}
var moves = mutableListOf<Triple<Int,Int, Int>>()
input.forEach { line ->
if (line.startsWith(" ") or line.startsWith("[")) {
for (i in 0..columns) {
var index = if (i==0) 1 else i*4+1
if (line.length > index) {
var letter = line[index]
if (letter.isLetter()) {
stacks[i].add(letter)
}
}
}
}
if (line.startsWith("m")) {
var temp = line.split("move ", " from ", " to ")
moves.add(Triple(temp[1].toInt(), temp[2].toInt(), temp[3].toInt()))
}
}
//println(stacks.toList())
//println(moves.toList())
return Pair(stacks, moves)
}
fun part1(stacks: Array<MutableList<Char>>, moves:MutableList<Triple<Int,Int, Int>>): String {
var topString = ""
moves.forEach { move ->
for (i in 1..move.first) {
stacks[move.third - 1].add(0, stacks[move.second - 1].removeFirst())
}
}
stacks.forEach { top ->
topString += top.first()
}
return topString
}
fun part2(stacks: Array<MutableList<Char>>, moves:MutableList<Triple<Int,Int, Int>>): String {
var topString = ""
moves.forEach { move ->
var temp = (mutableListOf <Char>())
for (i in 1..move.first) {
temp.add (stacks[move.second - 1].removeFirst())
}
stacks[move.third - 1].addAll(0, temp)
}
stacks.forEach { top ->
topString += top.first()
}
return topString
}
var input = readInput("Day05_test")
var items = processInput(input, 3)
var stacks = items.first
var moves = items.second
println(stacks.toList())
println(part1(stacks, moves))
input = readInput("Day05_test")
items = processInput(input, 3)
stacks = items.first
moves = items.second
println(part2(stacks, moves))
input = readInput("Day05_input")
items = processInput(input, 9)
stacks = items.first
moves = items.second
println(part1(stacks, moves))
input = readInput("Day05_input")
items = processInput(input, 9)
stacks = items.first
moves = items.second
println(part2(stacks, moves))
}
| 0 | Kotlin | 0 | 0 | 0b9af1c79b4ef14c64e9a949508af53358335f43 | 2,650 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/com/github/michaelbull/advent2023/iteration/Combinations.kt | michaelbull | 726,012,340 | false | {"Kotlin": 195941} | package com.github.michaelbull.advent2023.iteration
/* pair */
fun <T> List<T>.combinationPairs(): Sequence<Pair<T, T>> {
return combinations(
length = 2,
combination = ::combinationPair
)
}
private fun <T> List<T>.combinationPair(indices: IntArray, count: Int): Pair<T, T> {
require(count == 2)
return Pair(
first = get(indices[0]),
second = get(indices[1]),
)
}
/* triple */
fun <T> List<T>.combinationTriples(): Sequence<Triple<T, T, T>> {
return combinations(
length = 3,
combination = ::combinationTriple
)
}
private fun <T> List<T>.combinationTriple(indices: IntArray, count: Int): Triple<T, T, T> {
require(count == 3)
return Triple(
first = get(indices[0]),
second = get(indices[1]),
third = get(indices[2]),
)
}
/* list */
fun <T> List<T>.combinations(length: Int? = null): Sequence<List<T>> {
return combinations(
length = length,
combination = ::combinationList
)
}
inline fun <T, V> List<T>.combinations(
length: Int? = null,
crossinline combination: (indices: IntArray, count: Int) -> V,
): Sequence<V> = sequence {
val count = length ?: size
require(count >= 0) { "length must be non-negative but was $length" }
if (count in 1..size) {
val indices = IntArray(count) { it }
var searching = true
yield(combination(indices, count))
while (searching) {
var found = false
var index = count - 1
while (index >= 0 && !found) {
if (indices[index] == index + size - count) {
index--
} else {
indices[index]++
for (j in index + 1 until count) {
indices[j] = indices[j - 1] + 1
}
yield(combination(indices, count))
found = true
}
}
if (!found) {
searching = false
}
}
}
}
private fun <T> List<T>.combinationList(indices: IntArray, count: Int): List<T> {
require(count > 0)
return indices.map(this::get)
}
| 0 | Kotlin | 0 | 1 | ea0b10a9c6528d82ddb481b9cf627841f44184dd | 2,218 | advent-2023 | ISC License |
2021/src/main/kotlin/com/github/afranken/aoc/Day202105.kt | afranken | 434,026,010 | false | {"Kotlin": 28937} | package com.github.afranken.aoc
object Day202105 {
fun part1(inputs: Array<String>): Int {
val coordinates = getCoordinates(inputs)
val matrix = createMatrix(coordinates)
coordinates.forEach {
val from = Pair(it[0], it[1])
val to = Pair(it[2], it[3])
mark(matrix, from, to)
}
var count = 0
matrix.forEach { it.forEach { if (it >= 2) count++ } }
return count
}
fun part2(inputs: Array<String>): Int {
val coordinates = getCoordinates(inputs)
val matrix = createMatrix(coordinates)
coordinates.forEach {
val from = Pair(it[0], it[1])
val to = Pair(it[2], it[3])
mark(matrix, from, to, true)
}
var count = 0
matrix.forEach { it.forEach { if (it >= 2) count++ } }
return count
}
data class Pair(val x: Int, val y: Int)
private fun createMatrix(coordinates: List<List<Int>>): Array<IntArray> {
val size = coordinates[0][0].toString().length
var maxSizeString = ""
for (i in 0 until size) {
maxSizeString += "9"
}
val maxSize = Integer.valueOf(maxSizeString) + 1 //9->10, 99->100, 999->1000
return Array(maxSize) { IntArray(maxSize) { 0 } } //maxSize*maxSize array with '0's
}
private fun sort(from: Pair, to: Pair): List<Pair> {
return if (from.x < to.x || from.x == to.x && from.y < to.y) {
listOf(from, to)
} else {
listOf(to, from)
}
}
private fun mark(
matrix: Array<IntArray>,
from: Pair, to: Pair,
diagonals: Boolean = false
) {
val (lower, higher) = sort(from, to)
if (lower.x == higher.x) {
//vertical line.
(lower.y..higher.y).forEach {
matrix[it][lower.x]++
}
} else if (lower.y == higher.y) {
//horizontal line.
(lower.x..higher.x).forEach {
matrix[lower.y][it]++
}
} else if (diagonals) {
//diagonal line
val deltaX = higher.x - lower.x
val deltaY = higher.y - lower.y
val direction = when {
deltaY > 0 -> 1
deltaY < 0 -> -1
else -> 0
}
(0..deltaX).forEach { delta ->
matrix[lower.y + direction * delta][lower.x + delta]++
}
}
}
private fun getCoordinates(inputs: Array<String>): List<List<Int>> {
return inputs.map { it.split(",", " -> ") }.map { it.map { Integer.valueOf(it) } }
}
}
| 0 | Kotlin | 0 | 0 | 0140f68e60fa7b37eb7060ade689bb6634ba722b | 2,680 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/day5/day5.kt | aaronbush | 370,490,470 | false | null | package day5
import loadFile
fun F(num: Pair<Int, Int>): Pair<Int, Int> = num.first to num.second - (num.second - num.first) / 2 - 1
fun B(num: Pair<Int, Int>): Pair<Int, Int> = num.first + (num.second - num.first) / 2 + 1 to num.second
fun main() {
val data = "/day5/input.txt".loadFile()
part1(data)
part2(data)
}
private fun getSeatNumbers(data: List<String>): List<Int> {
val funMap = mapOf('F' to ::F, 'B' to ::B, 'L' to ::F, 'R' to ::B)
val seats = data.map { s ->
val row = s.take(7).fold(0 to 127) { acc, c -> funMap[c]?.invoke(acc) ?: acc }
val col = s.takeLast(3).fold(0 to 7) { acc, c -> funMap[c]?.invoke(acc) ?: acc }
Pair(row.first, col.first)
}
return seats.map { it.first * 8 + it.second }
}
fun part1(data: List<String>) {
val result = getSeatNumbers(data).maxOrNull()
println("part 1 is $result")
}
fun part2(data: List<String>) {
val sortedSeats = getSeatNumbers(data).sorted()
val result = sortedSeats.zipWithNext { a, b -> b - a }.indexOf(2)
println("part 2 is ${sortedSeats[result]} -*- ${sortedSeats[result + 1]}")
}
| 0 | Kotlin | 0 | 0 | 41d69ebef7cfeae4079e8311b1060b272c5f9a29 | 1,119 | aoc-2020-kotlin | MIT License |
advent-of-code-2023/src/main/kotlin/eu/janvdb/aoc2023/day16/day16.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2023.day16
import eu.janvdb.aocutil.kotlin.point2d.Direction
import eu.janvdb.aocutil.kotlin.point2d.Point2D
import eu.janvdb.aocutil.kotlin.readLines
import java.util.*
//const val FILENAME = "input16-test.txt"
const val FILENAME = "input16.txt"
fun main() {
val puzzle = Puzzle.parse(readLines(2023, FILENAME))
part1(puzzle)
part2(puzzle)
}
private fun part1(puzzle: Puzzle) {
val result = puzzle.followBeam(Pair(Point2D(0, 0), Direction.E)).getTilesHit()
println(result)
}
private fun part2(puzzle: Puzzle) {
val result = puzzle.entryPoints().map { puzzle.followBeam(it).getTilesHit() }.max()
println(result)
}
data class Puzzle(val size: Int, val tiles: List<Tile>, val directionsHit: List<Set<Direction>>) {
fun entryPoints(): Sequence<Pair<Point2D, Direction>> {
val fromLeft = (0 until size).asSequence().map { Point2D(0, it) to Direction.E }
val fromTop = (0 until size).asSequence().map { Point2D(it, 0) to Direction.S }
val fromRight = (0 until size).asSequence().map { Point2D(size - 1, it) to Direction.W }
val fromBottom = (0 until size).asSequence().map { Point2D(it, size - 1) to Direction.N }
return fromLeft + fromTop + fromRight + fromBottom
}
fun followBeam(start: Pair<Point2D, Direction>): Puzzle {
val toDo = LinkedList<Pair<Point2D, Direction>>()
toDo.add(start)
var current = this
while (!toDo.isEmpty()) {
val (point, direction) = toDo.removeFirst()
if (current.hasDirection(point, direction)) continue
current = current.addDirection(point, direction)
getTile(point)
.handleDirection(direction)
.map { Pair(point.move(it, 1), it) }
.filter { it.first.x in 0 until size && it.first.y in 0 until size }
.forEach { toDo.add(it) }
}
return current
}
private fun getIndex(point: Point2D) = point.y * size + point.x
private fun getTile(point: Point2D) = tiles[getIndex(point)]
private fun hasDirection(point: Point2D, direction: Direction) = directionsHit[getIndex(point)].contains(direction)
fun getTilesHit() = directionsHit.count { it.isNotEmpty() }
private fun addDirection(point: Point2D, direction: Direction): Puzzle {
val index = getIndex(point)
val newDirectionsHit = directionsHit.toMutableList()
newDirectionsHit[index] = newDirectionsHit[index] + direction
return Puzzle(size, tiles, newDirectionsHit)
}
companion object {
fun parse(lines: List<String>): Puzzle {
val size = lines.size
val tiles = lines.flatMap { line -> line.map { ch -> Tile.fromChar(ch) } }
val directionsHit = List(size * size) { mutableSetOf<Direction>() }
return Puzzle(size, tiles, directionsHit)
}
}
}
enum class Tile(val char: Char) {
EMPTY('.'),
MIRROR_SW('/'),
MIRROR_NW('\\'),
SPLITTER_HORIZONTAL('-'),
SPLITTER_VERTICAL('|');
fun handleDirection(direction: Direction): Sequence<Direction> {
return when (this) {
EMPTY -> sequenceOf(direction)
MIRROR_SW -> when (direction) {
Direction.W -> sequenceOf(Direction.S)
Direction.S -> sequenceOf(Direction.W)
Direction.E -> sequenceOf(Direction.N)
Direction.N -> sequenceOf(Direction.E)
}
MIRROR_NW -> when (direction) {
Direction.W -> sequenceOf(Direction.N)
Direction.N -> sequenceOf(Direction.W)
Direction.E -> sequenceOf(Direction.S)
Direction.S -> sequenceOf(Direction.E)
}
SPLITTER_HORIZONTAL -> when (direction) {
Direction.W, Direction.E -> sequenceOf(direction)
Direction.N, Direction.S -> sequenceOf(Direction.W, Direction.E)
}
SPLITTER_VERTICAL -> when (direction) {
Direction.N, Direction.S -> sequenceOf(direction)
Direction.W, Direction.E -> sequenceOf(Direction.N, Direction.S)
}
}
}
companion object {
fun fromChar(char: Char) = entries.first { it.char == char }
}
} | 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 3,764 | advent-of-code | Apache License 2.0 |
src/year2022/day18/Day18.kt | kingdongus | 573,014,376 | false | {"Kotlin": 100767} | package year2022.day18
import readInputFileByYearAndDay
import readTestFileByYearAndDay
fun main() {
val offsets = arrayOf(
Triple(1, 0, 0),
Triple(-1, 0, 0),
Triple(0, 1, 0),
Triple(0, -1, 0),
Triple(0, 0, 1),
Triple(0, 0, -1),
)
fun parseInput(input: List<String>) = input.map { it.split(",") }
.map { it.map { s -> s.toInt() } }
fun initStateAndCountExposed(
input: List<String>,
state: Array<Array<BooleanArray>>,
bound: Int
): Int {
var exposed = 0
parseInput(input).forEach {
exposed += 6
state[it[0]][it[1]][it[2]] = true
for (offset in offsets) {
val xn = it[0] + offset.first
val yn = it[1] + offset.second
val zn = it[2] + offset.third
if (xn < 0 || yn < 0 || zn < 0 || xn >= bound || yn >= bound || zn >= bound) continue
// placing a block next to a block reduces this block's surface and the other block's surface
if (state[xn][yn][zn]) exposed -= 2
}
}
return exposed
}
fun initStateAndDisplace(
input: List<String>,
state: Array<Array<BooleanArray>>,
) =
parseInput(input)
.forEach { state[it[0] + 1][it[1] + 1][it[2] + 1] = true } // move one away from any edge
fun part1(input: List<String>): Int {
val bound = parseInput(input).maxOf { it.max() } + 3 // leave some space to all sides
val state = Array(bound) { Array(bound) { BooleanArray(bound) } }
return initStateAndCountExposed(input, state, bound)
}
fun floodFill(blocks: Array<Array<BooleanArray>>): Int {
val visited = Array(blocks.size) { Array(blocks[0].size) { BooleanArray(blocks[0][0].size) } }
val toProcess = mutableSetOf(Triple(0, 0, 0))
var reachable = 0
while (toProcess.isNotEmpty()) {
val next = toProcess.first()
toProcess.remove(next)
visited[next.first][next.second][next.third] = true
for (offset in offsets) {
val x = next.first + offset.first
val y = next.second + offset.second
val z = next.third + offset.third
if (x < 0 || y < 0 || z < 0 || x > blocks.lastIndex || y > blocks[0].lastIndex || z > blocks[0][0].lastIndex) continue
if (blocks[x][y][z]) reachable++ // see if there is a surface in that direction
else if (!visited[x][y][z]) toProcess.add(Triple(x, y, z)) // calculate next places to check out
}
}
return reachable
}
fun part2(input: List<String>): Int {
val bound = parseInput(input).maxOf { it.max() } + 3 // leave some space to all sides
val state = Array(bound) { Array(bound) { BooleanArray(bound) } }
initStateAndDisplace(input, state)
return floodFill(state)
}
val testInput = readTestFileByYearAndDay(2022, 18)
check(part1(testInput) == 64)
check(part2(testInput) == 58)
val input = readInputFileByYearAndDay(2022, 18)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | aa8da2591310beb4a0d2eef81ad2417ff0341384 | 3,229 | advent-of-code-kotlin | Apache License 2.0 |
src/Day03.kt | guilherme | 574,434,377 | false | {"Kotlin": 7468} | import java.lang.RuntimeException
fun main() {
val PRIORITY_RANGE = concatenate(('a'.rangeTo('z'))
.toList(), ('A'.rangeTo('Z')).toList())
fun priority(item: Char): Int {
val priority = PRIORITY_RANGE.indexOf(item) + 1
if (priority == 0) {
throw RuntimeException("Invalid item ${item}")
} else {
return priority
}
}
fun repeatedItems(rucksack: String): List<Char> {
val middleIndex = rucksack.length / 2
val firstCompartment = rucksack.substring(0, middleIndex).toCharArray()
val secondCompartment = rucksack.substring(middleIndex , rucksack.length).toCharArray()
return firstCompartment.filter { secondCompartment.contains(it) }.distinct()
}
fun part1(input: List<String>): Int {
// find items that repeat on both compartments.
return input.map {
repeatedItems(it)
}
.flatten()
.sumOf { priority(it) }
}
// badge is the one that repeats on three lines
fun badge(elfItemGroup: List<String>): Char {
return elfItemGroup
// remove duplicates from same string
.map { it.toCharArray().distinct().joinToString("") }
.joinToString("")
.toCharArray()
.groupBy { it }
.filter { it.value.size == 3 } // find the one that repeats on three lines.
.keys
.first()
}
fun part2(input: List<String>): Int {
return input.withIndex().groupBy {
it.index / 3
}.map {
badge(it.value.map { it.value })
}
.sumOf { priority(it) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
val result1 = part1(testInput)
check(result1 == 157)
println("check 1 ok")
/* part 2 test */
val result2 = part2(testInput)
check(result2 == 70)
println("check 2 ok")
val input = readInput("Day03")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 3 | dfc0cee1d023be895f265623bec130386ed12f05 | 1,883 | advent-of-code | Apache License 2.0 |
src/Day05.kt | zhiqiyu | 573,221,845 | false | {"Kotlin": 20644} | import kotlin.math.max
import kotlin.math.abs
import java.util.LinkedList
import java.util.Queue
import java.util.Stack
class Stacks() {
var stacks: ArrayList<ArrayDeque<Char>>
init {
stacks = ArrayList<ArrayDeque<Char>>()
}
fun initialize(input: List<String>) {
var nums = (input.get(0).length + 1) / 4
for (i in 0..nums-1) stacks.add(ArrayDeque<Char>())
for (line in input) {
if (line == "\n") break
for (j in line.indices) {
if (line.get(j) == '[') {
stacks.get(j/4).add(line.get(j+1))
}
}
}
}
fun move(from: Int, to: Int, quant: Int) {
for (i in 0..quant-1) {
stacks.get(to-1).addFirst(stacks.get(from-1).removeFirst())
}
}
fun move2(from: Int, to: Int, quant: Int) {
var temp = ArrayDeque<Char>()
for (i in 0..quant-1) {
temp.addFirst(stacks.get(from-1).removeFirst())
}
for (i in 0..quant-1) {
stacks.get(to-1).addFirst(temp.removeFirst())
}
}
fun getTops(): String {
var tops = stacks.map {it -> it.get(0)}
return tops.joinToString(separator="")
}
}
fun main() {
/*
[G] [R] [P]
[H] [W] [T] [P] [H]
[F] [T] [P] [B] [D] [N]
[L] [T] [M] [Q] [L] [C] [Z]
[C] [C] [N] [V] [S] [H] [V] [G]
[G] [L] [F] [D] [M] [V] [T] [J] [H]
[M] [D] [J] [F] [F] [N] [C] [S] [F]
[Q] [R] [V] [J] [N] [R] [H] [G] [Z]
1 2 3 4 5 6 7 8 9
*/
fun part1(input: List<String>): String {
var stacks = Stacks()
stacks.initialize(input)
for (i in 0..(input.size-1)) {
if (!input.get(i).startsWith("move")) continue
var parts = input.get(i).split(" ")
var quant = parts.get(1).toInt()
var from = parts.get(3).toInt()
var to = parts.get(5).toInt()
stacks.move(from, to, quant)
}
return stacks.getTops()
}
fun part2(input: List<String>): String {
var stacks = Stacks()
stacks.initialize(input)
for (i in 0..(input.size-1)) {
if (!input.get(i).startsWith("move")) continue
var parts = input.get(i).split(" ")
var quant = parts.get(1).toInt()
var from = parts.get(3).toInt()
var to = parts.get(5).toInt()
stacks.move2(from, to, quant)
}
return stacks.getTops()
}
// 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("----------")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d3aa03b2ba2a8def927b94c2b7731663041ffd1d | 2,857 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/Day11.kt | akowal | 434,506,777 | false | {"Kotlin": 30540} | fun main() {
println(Day11.solvePart1())
println(Day11.solvePart2())
}
object Day11 {
private val input = readInput("day11")
fun solvePart1(): Int {
val levels = input.map { it.map(Char::digitToInt).toIntArray() }.toTypedArray()
var flashes = 0
repeat(100) {
flashes += runStep(levels)
}
return flashes
}
fun solvePart2(): Int {
val levels = input.map { it.map(Char::digitToInt).toIntArray() }.toTypedArray()
val flashAll = levels.size * levels.first().size
var steps = 1
while (runStep(levels) != flashAll) {
steps++
}
return steps
}
private fun runStep(levels: Array<IntArray>): Int {
var flashes = 0
val flashed = mutableSetOf<Point>()
val flash = ArrayDeque<Point>()
for (x in 0..levels.lastIndex) {
for (y in 0..levels.first().lastIndex) {
if (levels[x][y]++ >= 9) {
flash += Point(x, y)
}
}
}
while (flash.isNotEmpty()) {
val p = flash.removeFirst()
if (!flashed.add(p)) {
continue
}
flashes++
levels[p.x][p.y] = 0
flashed += p
p.neighors()
.filter { it !in flashed }
.filter { levels.getOrNull(it.x)?.getOrNull(it.y) != null }
.forEach {
if (levels[it.x][it.y]++ >= 9) {
flash += it
}
}
}
return flashes
}
private fun Point.neighors() = listOf(
Point(x, y + 1),
Point(x, y - 1),
Point(x + 1, y),
Point(x - 1, y),
Point(x - 1, y - 1),
Point(x + 1, y + 1),
Point(x + 1, y - 1),
Point(x - 1, y + 1),
)
}
| 0 | Kotlin | 0 | 0 | 08d4a07db82d2b6bac90affb52c639d0857dacd7 | 1,903 | advent-of-kode-2021 | Creative Commons Zero v1.0 Universal |
src/Day13.kt | risboo6909 | 572,912,116 | false | {"Kotlin": 66075} | sealed class Item {
class Value(val value: Int): Item()
class Nested(val value: List<Item>): Item()
}
fun main() {
fun parseNumber(line: String, startIdx: Int): Pair<Int, Int> {
val tmp = line.substring(startIdx).takeWhile { it.isDigit() }
return Pair(tmp.toInt(), tmp.length)
}
fun parseOne(line: String): List<Item> {
fun inner(startIdx: Int): Pair<List<Item>, Int> {
var idx = startIdx
val res: MutableList<Item> = mutableListOf()
while (idx < line.length) {
val s = line[idx]
if (s.isDigit()) {
val (n, toSkip) = parseNumber(line, idx)
res.add(Item.Value(n))
idx += toSkip
continue
} else if (s == '[') {
val (tmp, newIdx) = inner(idx+1)
idx = newIdx
res.add(Item.Nested(tmp))
} else if (s == ']') {
return Pair(res, idx)
}
idx++
}
return Pair(res, idx)
}
val (parsed, _) = inner(0)
return (parsed[0] as Item.Nested).value
}
fun compare(first: List<Item>, second: List<Item>): Int {
fun inner(a: List<Item>, b: List<Item>): Int {
for (idx in 0 until kotlin.math.min(a.size, b.size)) {
if (a[idx]::class == b[idx]::class) {
when(a[idx]) {
is Item.Nested -> {
val res = inner((a[idx] as Item.Nested).value, (b[idx] as Item.Nested).value)
if (res != 0) return res
}
is Item.Value -> {
if ((a[idx] as Item.Value).value > (b[idx] as Item.Value).value) {
return 1
} else if ((a[idx] as Item.Value).value < (b[idx] as Item.Value).value) {
return -1
}
}
}
} else {
when(a[idx]) {
is Item.Nested -> {
val res = inner((a[idx] as Item.Nested).value, listOf(b[idx]))
if (res != 0) return res
}
is Item.Value -> {
val res = inner(listOf(a[idx]), (b[idx] as Item.Nested).value)
if (res != 0) return res
}
}
}
}
if (b.size > a.size) {
return -1
} else if (b.size == a.size) {
return 0
}
return 1
}
return inner(first, second)
}
fun parse(input: List<String>): List<Pair<List<Item>, List<Item>>> {
val iter = input.iterator()
val res: MutableList<Pair<List<Item>, List<Item>>> = mutableListOf()
while (iter.hasNext()) {
val first = parseOne(iter.next())
val second = parseOne(iter.next())
res.add(Pair(first, second))
if (iter.hasNext()) {
iter.next()
}
}
return res
}
fun part1(input: List<String>): Int {
return parse(input).withIndex().sumOf { (i, pair) -> if (compare(pair.first, pair.second) == -1) i + 1 else 0 }
}
fun part2(input: List<String>): Int {
val dividers = parse(listOf("[[2]]", "[[6]]"))
val flatParsed = (parse(input) + dividers).flatMap { listOf(it.first, it.second) }.toMutableSet()
val res = flatParsed.sortedWith{o1, o2 -> compare(o1, o2)}
return ((res.indexOf(dividers.first().first)+1) *
(res.indexOf(dividers.first().second)+1))
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bd6f9b46d109a34978e92ab56287e94cc3e1c945 | 4,192 | aoc2022 | Apache License 2.0 |
src/day09/Day09.kt | gillyobeast | 574,413,213 | false | {"Kotlin": 27372} | package day09
import utils.appliedTo
import utils.readInput
import kotlin.math.abs
import kotlin.math.sign
enum class Move(val regex: Regex, val applyTo: (Point) -> Point) {
UP("U \\d+".toRegex(), { it.first to it.second + 1 }),
DOWN("D \\d+".toRegex(), { it.first to it.second - 1 }),
LEFT("L \\d+".toRegex(), { it.first - 1 to it.second }),
RIGHT("R \\d+".toRegex(), { it.first + 1 to it.second });
companion object {
private val digits = "(\\d+)".toRegex()
fun of(string: String): Pair<Move, Int> {
val direction = Move.values().first { it.regex.matches(string) }
return direction to digits.find(string)!!.value.toInt()
}
}
}
typealias Point = Pair<Int, Int>
fun part1(input: List<String>): Int {
val moves = input.map { Move.of(it) }
// println(moves)
var headPosition = 0 to 0 // x to y
var tailPosition = 0 to 0 // x to y
val tailVisitedPositions = mutableSetOf(tailPosition)
moves.forEach { (move, step): Pair<Move, Int> ->
repeat(step) { _ ->
headPosition = move.applyTo(headPosition)
// print("head = $headPosition ")
tailPosition = tailPosition.moveToward(headPosition)
// println("tail = $tailPosition")
tailVisitedPositions.add(tailPosition)
}
}
// println(tailVisitedPositions)
return tailVisitedPositions.size
}
fun part2(input: List<String>): Int {
val moves = input.map { Move.of(it) }
// println(moves)
// head, 1, 2, 3, 4, 5, 6, 7, 8, 9
val knots = mutableListOf<Point>()
repeat(10) { knots.add(0 to 0) }
val tailVisitedPositions = mutableSetOf(knots[9])
moves.forEach { (move, step): Pair<Move, Int> ->
repeat(step) { _ ->
knots[0] = move.applyTo(knots[0])
// print("head = ${knots[0]}, ")
for (i in 1..9) {
knots[i] = knots[i].moveToward(knots[i - 1])
// print("; $i = ${knots[i]}, ")
}
// println()
tailVisitedPositions.add(knots[9])
}
// for (i in 0..9)
// print("$i = ${knots[i]}, ")
// println()
}
// println(tailVisitedPositions)
return tailVisitedPositions.size
}
private fun Point.moveToward(other: Point): Point {
this.log("start ")
other.log(", towards ")
return if (this.isWithin1Of(other)) this
else {
(first.moveToward(other.first) to second.moveToward(other.second)).log(", moving to ")
}
}
private fun Int.moveToward(first1: Int) = this + (first1 - this).sign
private fun Point.isWithin1Of(headPosition: Point): Boolean {
return abs(first - headPosition.first).log(", x ") <= 1 && abs(second - headPosition.second).log(
", y "
) <= 1
}
private fun <T> T.log(s: String = ""): T = this//.also { print(s + it) }
fun main() {
val testInput = readInput("input_test")
val input = readInput("input")
// part 1
::part1.appliedTo(testInput, returns = 88)
println("Part 1: ${part1(input)}")
// part 2
::part2.appliedTo(testInput, returns = 36)
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 8cdbb20c1a544039b0e91101ec3ebd529c2b9062 | 3,170 | aoc-2022-kotlin | Apache License 2.0 |
2023/src/main/kotlin/day16.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Grid
import utils.Parser
import utils.Solution
import utils.Vec2i
import utils.createMutableGrid
import java.util.EnumSet
fun main() {
Day16.run()
}
object Day16 : Solution<Grid<Char>>() {
override val name = "day16"
override val parser = Parser.charGrid
data class Beam(
val location: Vec2i,
val direction: Direction,
)
enum class Direction(val delta: Vec2i) {
UP(Vec2i(0, -1)),
DOWN(Vec2i(0, 1)),
LEFT(Vec2i(-1, 0)),
RIGHT(Vec2i(1, 0));
companion object {
fun byVec(v: Vec2i): Direction {
return Direction.entries.first { it.delta == v }
}
}
}
private fun solve(start: Beam): Int {
val beams = mutableListOf(start)
val seen = createMutableGrid<Set<Direction>>(input.width, input.height) { EnumSet.noneOf(Direction::class.java) }
while (beams.isNotEmpty()) {
val beam = beams.removeLast()
val nextLocation = beam.location + beam.direction.delta
if (nextLocation.x !in 0 until input.width || nextLocation.y !in 0 until input.height) {
// out of bounds
continue
}
if (beam.direction in seen[nextLocation]) {
// already tracked a beam going that way
continue
}
seen[nextLocation] = seen[nextLocation] + beam.direction
val newBeams = when (input[nextLocation]) {
'.' -> listOf(Beam(nextLocation, beam.direction))
'-' -> if (beam.direction.delta.y == 0) {
listOf(Beam(nextLocation, beam.direction))
} else {
listOf(Beam(nextLocation, Direction.LEFT), Beam(nextLocation, Direction.RIGHT))
}
'|' -> if (beam.direction.delta.x == 0) {
listOf(Beam(nextLocation, beam.direction))
} else {
listOf(Beam(nextLocation, Direction.UP), Beam(nextLocation, Direction.DOWN))
}
'\\' -> if (beam.direction.delta.y == 0) {
listOf(Beam(nextLocation, Direction.byVec(beam.direction.delta.rotateCcw())))
} else {
listOf(Beam(nextLocation, Direction.byVec(beam.direction.delta.rotateCw())))
}
'/' -> if (beam.direction.delta.y == 0) {
listOf(Beam(nextLocation, Direction.byVec(beam.direction.delta.rotateCw())))
} else {
listOf(Beam(nextLocation, Direction.byVec(beam.direction.delta.rotateCcw())))
}
else -> throw IllegalStateException("Bad grid char ${input[beam.location]}")
}
beams.addAll(newBeams)
}
return seen.values.count { it.isNotEmpty() }
}
override fun part1(): Int {
return solve(Beam(Vec2i(-1, 0), Direction.RIGHT))
}
override fun part2(): Any? {
val entries = listOf(
(0 until input.height).flatMap {
listOf(
Beam(Vec2i(-1, it), Direction.RIGHT),
Beam(Vec2i(input.width, it), Direction.LEFT)
)
},
(0 until input.width).flatMap {
listOf(
Beam(Vec2i(it, -1), Direction.DOWN),
Beam(Vec2i(it, input.height), Direction.UP)
)
},
).flatten()
return entries.maxOf { solve(it) }
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 3,085 | aoc_kotlin | MIT License |
y2016/src/main/kotlin/adventofcode/y2016/Day17.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2016
import adventofcode.io.AdventSolution
import adventofcode.util.algorithm.IState
import adventofcode.util.algorithm.aStar
import adventofcode.util.algorithm.aStarExhaustive
import adventofcode.util.algorithm.md5
object Day17 : AdventSolution(2016, 17, "Two Steps Forward") {
override fun solvePartOne(input: String): String {
val res = aStar(Path(0, 0, "", input)) ?: throw IllegalStateException()
return (res.IState as Path).path
}
override fun solvePartTwo(input: String): String {
val res = aStarExhaustive(Path(0, 0, "", input))
return res.last().cost.toString()
}
}
private enum class Dir(val pos: Int, val ch: Char, val dx: Int, val dy: Int) {
UP(0, 'U', 0, -1),
DOWN(1, 'D', 0, 1),
LEFT(2, 'L', -1, 0),
RIGHT(3, 'R', 1, 0)
}
private fun open(hash: String, dir: Dir) = hash[dir.pos] in 'b'..'f'
class Path(
private val x: Int,
private val y: Int,
val path: String,
private val password: String) : IState {
override fun getNeighbors(): Sequence<IState> {
return Dir.values()
.asSequence()
.filter { open(md5(password + path), it) }
.map(this::copy)
.filter(Path::isValid)
}
private fun copy(dir: Dir) = Path(x + dir.dx, y + dir.dy, path + dir.ch, password)
private fun isValid() = x in 0..3 && y in 0..3
override val isGoal get() = x == 3 && y == 3
override val heuristic get() = 6 - (x + y)
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,386 | advent-of-code | MIT License |
dynamic_programming/LongestArithmeticSubsequence/kotlin/Solution.kt | YaroslavHavrylovych | 78,222,218 | false | {"Java": 284373, "Kotlin": 35978, "Shell": 2994} | import kotlin.math.sign
/**
* Given an array A of integers, return the length of the longest
* arithmetic subsequence in A.
* Recall that a subsequence of A is a
* list A[i_1], A[i_2], ..., A[i_k]
* with 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence
* B is arithmetic if B[i+1] - B[i] are all the same value
* (for 0 <= i < B.length - 1).
* <br>
* https://leetcode.com/problems/longest-arithmetic-subsequence/
*/
class Solution {
fun longestArithSeqLength(A: IntArray): Int {
if(A.size <= 2) return A.size
var max = 2
val diffs = Array<MutableMap<Int, Int>>(A.size) { HashMap() }
for(i in 1..A.indices.last) {
for(j in i-1 downTo 0) {
val diff = A[i] - A[j]
if(diffs[j][diff] == null) {
if(diffs[i][diff] == null) {
diffs[i][diff] = 2
}
} else {
if(diffs[i][diff] == null) {
diffs[i][diff] = diffs[j][diff]!! + 1
} else {
diffs[i][diff] = kotlin.math.max(
diffs[i][diff]!!, diffs[j][diff]!! + 1
)
}
if(max < diffs[i][diff]!!) {
max = diffs[i][diff]!!
}
}
}
}
return max
}
}
fun main() {
println("Longest Arithmetic Subsequence: test is not implemented")
}
| 0 | Java | 0 | 2 | cb8e6f7e30563e7ced7c3a253cb8e8bbe2bf19dd | 1,528 | codility | MIT License |
year2018/src/main/kotlin/net/olegg/aoc/year2018/day6/Day6.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2018.day6
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.year2018.DayOf2018
import kotlin.math.abs
/**
* See [Year 2018, Day 6](https://adventofcode.com/2018/day/6)
*/
object Day6 : DayOf2018(6) {
private val PATTERN = "(\\d+), (\\d+)".toRegex()
private const val TOTAL = 10000
override fun first(): Any? {
val points = lines
.mapNotNull { line ->
PATTERN.matchEntire(line)
?.destructured
?.toList()
?.map { it.toInt() }
?.let { it.first() to it.last() }
}
val left = points.minOf { it.first }
val top = points.minOf { it.second }
val right = points.maxOf { it.first }
val bottom = points.maxOf { it.second }
val area = (top..bottom)
.flatMap { y ->
(left..right).mapNotNull { x ->
val dist = points.map { abs(x - it.first) + abs(y - it.second) }
val best = dist.min()
if (dist.count { it == best } == 1) dist.indexOfFirst { it == best } else null
}
}
return area
.groupingBy { it }
.eachCount()
.filterKeys { key ->
points[key].first !in listOf(left, right) && points[key].second !in listOf(top, bottom)
}
.maxOf { it.value }
}
override fun second(): Any? {
val points = lines
.mapNotNull { line ->
PATTERN.matchEntire(line)
?.destructured
?.toList()
?.map { it.toInt() }
?.let { it.first() to it.last() }
}
val left = points.minOf { it.first }
val top = points.minOf { it.second }
val right = points.maxOf { it.first }
val bottom = points.maxOf { it.second }
val padding = TOTAL / points.size + 1
return (top - padding..bottom + padding)
.flatMap { y ->
(left - padding..right + padding).map { x ->
points.sumOf { abs(x - it.first) + abs(y - it.second) }
}
}
.count { it < TOTAL }
}
}
fun main() = SomeDay.mainify(Day6)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 2,000 | adventofcode | MIT License |
src/day3/main.kt | DonaldLika | 434,183,449 | false | {"Kotlin": 11805} | package day3
import assert
import readLines
import kotlin.math.absoluteValue
fun main() {
fun part1(input: List<String>): Int {
val gammaRate = input.toGamaRate()
val epsilonRate = gammaRate.invertBinaryString()
return gammaRate.toInt(2) * epsilonRate.toInt(2)
}
fun part2(input: List<String>): Int {
val oxygenGeneratorRating = input.oxygenGeneratorRating()
val co2ScrubberRating = input.co2ScrubberRating()
return oxygenGeneratorRating.toInt(2) * co2ScrubberRating.toInt(2)
}
// example
val testInput = readLines("day3/test")
assert(part1(testInput) == 198)
assert(part2(testInput) == 230)
val inputList = readLines("day3/input")
val part1Result = part1(inputList)
val part2Result = part2(inputList)
println("Result of part 1= $part1Result")
println("Result of part 2= $part2Result")
}
private fun List<String>.toGamaRate(): String = this.first()
.indices
.map { index ->
occurrenceCountPerBitOnIndex(index)
.maxByOrNull { it.value }?.key!!
}
.let { String(it.toCharArray()) }
private fun List<String>.occurrenceCountPerBitOnIndex(index: Int): Map<Char, Int> = this.groupingBy { it[index] }.eachCount()
private fun List<String>.oxygenGeneratorRating(): String {
return findRating {
val zeroes = it['0'] ?: 0
val ones = it['1'] ?: 0
if (zeroes > ones) '0' else '1'
}
}
private fun List<String>.co2ScrubberRating(): String {
return findRating {
val zeroes = it['0'] ?: 0
val ones = it['1'] ?: 0
if (zeroes > ones) '1' else '0'
}
}
private fun List<String>.findRating(genericRatingSupplier: (fetchedRatings: Map<Char, Int>) -> Char): String {
var filteredList = this
for (index in this.first().indices) {
val most = filteredList.occurrenceCountPerBitOnIndex(index)
filteredList = filteredList.filter { it[index] == genericRatingSupplier(most) }
if (filteredList.size == 1) {
return filteredList.single()
}
}
throw IllegalStateException("Rating couldn't be found")
}
private fun String.invertBinaryString() = this.map { it.digitToInt().minus(1).absoluteValue }.joinToString("") | 0 | Kotlin | 0 | 0 | b288f16ee862c0a685a3f9e4db34d71b16c3e457 | 2,253 | advent-of-code-2021 | MIT License |
src/day04/Day04.kt | Regiva | 573,089,637 | false | {"Kotlin": 29453} | package day04
import readLines
fun main() {
val id = "04"
fun readSections(fileName: String): Sequence<String> {
return readLines(fileName).asSequence()
}
// Time — O(), Memory — O()
fun part1(input: Sequence<String>): Int {
return input.map {
val sections = it.split(",")
val firstStart = sections.first().split("-").first().toInt()
val firstEnd = sections.first().split("-").last().toInt()
val secondStart = sections.last().split("-").first().toInt()
val secondEnd = sections.last().split("-").last().toInt()
firstStart..firstEnd to secondStart..secondEnd
}.count { pair ->
pair.first.all { pair.second.contains(it) } or pair.second.all { pair.first.contains(it) }
}
}
// Time — O(), Memory — O()
fun part2(input: Sequence<String>): Int {
return input.map {
val sections = it.split(",")
val firstStart = sections.first().split("-").first().toInt()
val firstEnd = sections.first().split("-").last().toInt()
val secondStart = sections.last().split("-").first().toInt()
val secondEnd = sections.last().split("-").last().toInt()
firstStart..firstEnd to secondStart..secondEnd
}.count { pair ->
pair.first.any { pair.second.contains(it) } or pair.second.any { pair.first.contains(it) }
}
}
val testInput = readSections("day$id/Day${id}_test")
println(part1(testInput))
check(part1(testInput) == 2)
val input = readSections("day$id/Day$id")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2d9de95ee18916327f28a3565e68999c061ba810 | 1,683 | advent-of-code-2022 | Apache License 2.0 |
gcj/y2022/kickstart_c/d.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package gcj.y2022.kickstart_c
const val M = 1000000007
private fun solve(): Int {
val n = readInt()
val s = readLn()
val a = List(n + 1) { List(n + 1) { IntArray(n + 1) } }
for (i in n downTo 0) for (j in i..n) for (k in 0..j - i) {
if (k == 0) {
a[i][j][k] = 1
continue
}
if (k == 1) {
a[i][j][k] = j - i
continue
}
a[i][j][k] = (a[i][j - 1][k].toModular() + a[i + 1][j][k].toModular() - a[i + 1][j - 1][k].toModular()).x
if (s[i] == s[j - 1]) {
a[i][j][k] = (a[i][j][k].toModular() + a[i + 1][j - 1][k - 2].toModular()).x
}
}
val cnk = List(n + 1) { IntArray(n + 1) }
for (i in cnk.indices) {
cnk[i][0] = 1
cnk[i][i] = 1
for (j in 1 until i) cnk[i][j] = (cnk[i - 1][j - 1].toModular() + cnk[i - 1][j].toModular()).x
}
var ans = 0.toModular()
for (i in 0 until n) {
ans += a[0][n][i].toModular().div(cnk[n][i].toModular())
}
return ans.x
}
fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun Int.toModular() = Modular(this)//toDouble()
private class Modular {
val x: Int
@Suppress("ConvertSecondaryConstructorToPrimary")
constructor(value: Int) { x = (value % M).let { if (it < 0) it + M else it } }
operator fun plus(that: Modular) = Modular((x + that.x) % M)
operator fun minus(that: Modular) = Modular((x + M - that.x) % M)
operator fun times(that: Modular) = (x.toLong() * that.x % M).toInt().toModular()
private fun modInverse() = Modular(x.toBigInteger().modInverse(M.toBigInteger()).toInt())
operator fun div(that: Modular) = times(that.modInverse())
override fun toString() = x.toString()
}
private operator fun Int.plus(that: Modular) = Modular(this) + that
private operator fun Int.minus(that: Modular) = Modular(this) - that
private operator fun Int.times(that: Modular) = Modular(this) * that
private operator fun Int.div(that: Modular) = Modular(this) / that
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,947 | competitions | The Unlicense |
kotlin/src/katas/kotlin/skiena/graphs/ShortestPath.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.skiena.graphs
import katas.kotlin.skiena.graphs.WeightedGraphs.diamondGraph
import katas.kotlin.skiena.graphs.WeightedGraphs.linearGraph
import katas.kotlin.skiena.graphs.WeightedGraphs.triangleGraph
import datsok.shouldEqual
import org.junit.Test
class ShortestPathTests {
@Test fun `Dijkstra shortest paths to all vertices in a graph`() {
linearGraph.dijkstraShortestPaths() shouldEqual Graph.readInts("1-2/10,2-3/20")
triangleGraph.dijkstraShortestPaths() shouldEqual Graph.readInts("1-2/20,1-3/20")
diamondGraph.dijkstraShortestPaths() shouldEqual Graph.readInts("1-2/10,1-4/20,2-3/30")
}
@Test fun `Floyd-Warshall shortest paths between all vertices in a graph`() {
// @formatter:off
linearGraph.floydWarshallShortestPaths() shouldEqual AllShortestPaths(
dist = listOf(
// 1 2 3
listOf(0, 10, 30), // 1
listOf(10, 0, 20), // 2
listOf(30, 20, 0) // 3
),
next = listOf(
// 1 2 3
listOf(-1, 2, 2), // 1
listOf( 1, -1, 3), // 2
listOf( 2, 2, -1) // 3
)
).also {
it.shortestPath(1, 1) shouldEqual listOf(1)
it.shortestPath(1, 2) shouldEqual listOf(1, 2)
it.shortestPath(1, 3) shouldEqual listOf(1, 2, 3)
it.shortestPath(3, 1) shouldEqual listOf(3, 2, 1)
it.shortestPath(2, 1) shouldEqual listOf(2, 1)
}
triangleGraph.floydWarshallShortestPaths() shouldEqual AllShortestPaths(
dist = listOf(
// 1 2 3
listOf( 0, 20, 20), // 1
listOf(20, 0, 10), // 2
listOf(20, 10, 0) // 3
),
next = listOf(
// 1 2 3
listOf(-1, 2, 3), // 1
listOf( 1, -1, 3), // 2
listOf( 1, 2, -1) // 3
)
)
diamondGraph.floydWarshallShortestPaths() shouldEqual AllShortestPaths(
dist = listOf(
// 1 2 3 4
listOf( 0, 10, 40, 20), // 1
listOf(10, 0, 30, 30), // 2
listOf(40, 30, 0, 40), // 3
listOf(20, 30, 40, 0) // 4
),
next = listOf(
// 1 2 3 4
listOf(-1, 2, 2, 4), // 1
listOf( 1, -1, 3, 1), // 2
listOf( 2, 2, -1, 4), // 3
listOf( 1, 1, 3, -1) // 4
)
).also {
it.shortestPath(1, 3) shouldEqual listOf(1, 2, 3)
it.shortestPath(3, 1) shouldEqual listOf(3, 2, 1)
}
// @formatter:on
}
}
private data class AllShortestPaths(val dist: List<List<Int>>, val next: List<List<Int>>) {
fun shortestPath(from: Int, to: Int): List<Int> {
if (from == to) return listOf(from)
return listOf(from) + shortestPath(next[from - 1][to - 1], to)
}
}
private fun Graph<Int>.floydWarshallShortestPaths(): AllShortestPaths {
val size = vertices.size + 1 // +1 to make lists indexed from 1
val dist = MutableList(size) { MutableList(size) { Int.MAX_VALUE / 2 } }
val next = MutableList(size) { MutableList(size) { -1 } }
edges.forEach { edge ->
dist[edge.from][edge.to] = edge.weight!!
next[edge.from][edge.to] = edge.to
}
vertices.forEach {
dist[it][it] = 0
}
vertices.forEach { k ->
vertices.forEach { i ->
vertices.forEach { j ->
if (dist[i][j] > dist[i][k] + dist[k][j]) {
dist[i][j] = dist[i][k] + dist[k][j]
next[i][j] = next[i][k]
}
}
}
}
// make result non-indexed from 1
dist.removeAt(0)
dist.forEach { it.removeAt(0) }
next.removeAt(0)
next.forEach { it.removeAt(0) }
return AllShortestPaths(dist, next)
}
private fun <T> Graph<T>.dijkstraShortestPaths(): Graph<T> {
val tree = Graph<T>()
val distance = HashMap<T, Int>()
tree.addVertex(vertices.first())
distance[vertices.first()] = 0
while (!tree.vertices.containsAll(vertices)) {
val minEdge = tree.vertices
.flatMap { vertex -> edgesByVertex[vertex]!! }
.filter { edge -> edge.to !in tree.vertices }
.minBy { edge -> distance.getOrPut(edge.to) { distance[edge.from]!! + edge.weight!! } }
tree.addEdge(minEdge)
}
return tree
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 4,618 | katas | The Unlicense |
src/main/kotlin/day7/Day07.kt | Avataw | 572,709,044 | false | {"Kotlin": 99761} | package day7
fun solveA(input: List<String>) = input.createFolderStructure().filter { it.getSize() < 100000L }.sumOf { it.getSize() }
fun solveB(input: List<String>): Long {
val folders = input.createFolderStructure()
val rootFolderSize = folders.find { it.name == "/" }!!.getSize()
return folders.findSmallestToDelete(totalUsedSpace = rootFolderSize, neededFreeSpace = 40000000L)
}
fun List<String>.createFolderStructure(): List<Folder> {
var currentFolder: Folder? = null
val folders = mutableListOf<Folder>()
this.map { it.split(" ") }.forEach { command ->
if (command.isChangeDirIn()) {
currentFolder = createNewFolder(name = command[2], parentFolder = currentFolder, folders)
}
if (command.isChangeDirOut()) currentFolder = currentFolder?.parentFolder
if (command.isFile()) currentFolder!!.files.add(File(command[1], command[0].toLong()))
}
return folders
}
fun List<String>.isFile() = this.first().toLongOrNull() != null
fun List<String>.isChangeDirIn() = this[1] == "cd" && this[2] != ".."
fun List<String>.isChangeDirOut() = this[1] == "cd" && this[2] == ".."
fun createNewFolder(name: String, parentFolder: Folder?, folders: MutableList<Folder>): Folder {
val newFolder = Folder(name, parentFolder, mutableListOf(), mutableListOf())
folders.add(newFolder)
parentFolder?.subFolder?.add(newFolder)
return newFolder
}
fun List<Folder>.findSmallestToDelete(totalUsedSpace: Long, neededFreeSpace: Long) = this.sortedBy { it.getSize() }
.first { totalUsedSpace - it.getSize() < neededFreeSpace }
.getSize()
data class File(val name: String, val size: Long)
data class Folder(
val name: String,
val parentFolder: Folder?,
val files: MutableList<File>,
val subFolder: MutableList<Folder>
) {
fun getSize(): Long = files.sumOf { it.size } + subFolder.sumOf { it.getSize() }
}
// first approach
////25:50
//fun solveA(input: List<String>): Long {
//
// val folders = mutableListOf<Folder>()
// var currentFolder: Folder? = null
//
// for (line in input) {
// println("CURRENT ${currentFolder?.name}")
// val command = line.split(" ")
// if (command[0] == "$" && command[1] == "cd") {
// currentFolder = if (command[2] != "..") {
// val newFolder = Folder(command[2], currentFolder, mutableListOf(), mutableListOf())
// println("ADDING NEW FOLDER: ${newFolder.name} to ${currentFolder?.name}")
// folders.add(newFolder)
// currentFolder?.subFolder?.add(newFolder)
// newFolder
// } else {
// currentFolder?.parentFolder
// }
// } else if (command[0].toLongOrNull() != null) {
// val newFile = File(command[1], command[0].toLong())
// currentFolder?.files?.add(newFile)
// }
// }
//
// println(folders.filter { it.getSize() < 100000L })
//
// return folders.filter { it.getSize() < 100000L }.sumOf { it.getSize() }
//}
//
////7:03
//fun solveB(input: List<String>): Long {
// val folders = mutableListOf<Folder>()
// var currentFolder: Folder? = null
//
// for (line in input) {
// println("CURRENT ${currentFolder?.name}")
// val command = line.split(" ")
// if (command[0] == "$" && command[1] == "cd") {
// currentFolder = if (command[2] != "..") {
// val newFolder = Folder(command[2], currentFolder, mutableListOf(), mutableListOf())
// println("ADDING NEW FOLDER: ${newFolder.name} to ${currentFolder?.name}")
// folders.add(newFolder)
// currentFolder?.subFolder?.add(newFolder)
// newFolder
// } else {
// currentFolder?.parentFolder
// }
// } else if (command[0].toLongOrNull() != null) {
// val newFile = File(command[1], command[0].toLong())
// currentFolder?.files?.add(newFile)
// }
// }
//
// val totalDiskSpace = 70000000L
// val totalUsed = folders.find { it.name == "/" }!!.getSize()
// val available = totalDiskSpace - totalUsed
//
// println("Available $available")
//
// val smallestToDelete = folders.filter { it.name != "/" }
// .sortedBy { it.getSize() }
// .first { totalUsed - it.getSize() < 40000000L }
//
// return smallestToDelete.getSize()
//}
| 0 | Kotlin | 2 | 0 | 769c4bf06ee5b9ad3220e92067d617f07519d2b7 | 4,430 | advent-of-code-2022 | Apache License 2.0 |
y2023/src/main/kotlin/adventofcode/y2023/Day16.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.Direction.*
import adventofcode.util.vector.Vec2
fun main() {
Day16.solve()
}
object Day16 : AdventSolution(2023, 16, "The Floor Will Be Lava") {
override fun solvePartOne(input: String): Int {
val parsed = parse(input)
return solve(parsed, Beam(Vec2(-1, 0), RIGHT))
}
override fun solvePartTwo(input: String): Int {
val parsed = parse(input)
val ys = input.lines().indices
val xs = input.lines().first().indices
val top = xs.map { Beam(Vec2(it, ys.first - 1), DOWN) }
val bottom = xs.map { Beam(Vec2(it, ys.last + 1), UP) }
val left = ys.map { Beam(Vec2(ys.first - 1, it), RIGHT) }
val right = ys.map { Beam(Vec2(xs.last + 1, it), LEFT) }
val initial = top + bottom + left + right
return initial.maxOf { solve(parsed, it) }
}
private val rays = mutableMapOf<Beam, Pair<List<Vec2>, Beam?>>()
private fun trace(parsed: Map<Vec2, Char>, beam: Beam) = rays.getOrPut(beam) {
var next = beam.position
val path = mutableListOf<Vec2>()
do {
next += beam.direction.vector
path += next
} while (parsed[next] == '.')
if (!parsed.containsKey(next)) {
path.removeAt(path.lastIndex)
path to null
} else
path to beam.copy(position = next)
}
private fun solve(parsed: Map<Vec2, Char>, initial: Beam): Int {
val energized = mutableSetOf<Vec2>()
val visited = mutableSetOf<Beam>()
val (path, next) = trace(parsed, initial)
energized += path
val open = listOfNotNull(next).toMutableList()
while (open.isNotEmpty()) {
val c = open.removeLast()
if (c in visited) continue
visited += c
val type = parsed[c.position]!!
require(type !='.')
bounces.getValue(type).getValue(c.direction).forEach {
val exit = c.copy(direction = it)
val (p2, n2) = trace(parsed, exit)
energized += p2
n2?.let(open::add)
}
energized += c.position
}
return energized.size
}
}
private data class Beam(val position: Vec2, val direction: Direction)
private fun parse(input: String): Map<Vec2, Char> = input.lines()
.flatMapIndexed { y, line ->
line.withIndex()
.map { (x, value) -> Vec2(x, y) to value }
}
.toMap()
private val bounces: Map<Char, Map<Direction, List<Direction>>> = mapOf(
'\\' to mapOf(
UP to LEFT,
RIGHT to DOWN,
DOWN to RIGHT,
LEFT to UP,
).mapValues { listOf(it.value) },
'/' to mapOf(
UP to RIGHT,
RIGHT to UP,
DOWN to LEFT,
LEFT to DOWN
).mapValues { listOf(it.value) },
'-' to mapOf(
UP to listOf(LEFT, RIGHT),
RIGHT to listOf(RIGHT),
DOWN to listOf(LEFT, RIGHT),
LEFT to listOf(LEFT)
),
'|' to mapOf(
UP to listOf(UP),
RIGHT to listOf(UP, DOWN),
DOWN to listOf(DOWN),
LEFT to listOf(UP, DOWN)
)
)
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 3,296 | advent-of-code | MIT License |
src/main/kotlin/Day14.kt | bent-lorentzen | 727,619,283 | false | {"Kotlin": 68153} | import java.time.LocalDateTime
import java.time.ZoneOffset
fun main() {
fun calculateWeight(grid: List<List<Char>>): Int {
return grid.mapIndexed { y, chars ->
chars.sumOf { c ->
if (c == 'O') grid.size - y else 0
}
}.sum()
}
fun tiltNorth(input: List<List<Char>>): List<List<Char>> {
val grid = input.map { it.toMutableList() }
val availablePositions = MutableList(grid.first.size) { mutableListOf<Int>() }
grid.forEachIndexed { y, chars ->
chars.forEachIndexed { x, c ->
when (c) {
'O' -> if (availablePositions[x].isNotEmpty()) {
grid[availablePositions[x].first][x] = 'O'
availablePositions[x].removeFirst()
grid[y][x] = '.'
availablePositions[x].add(y)
}
'.' -> availablePositions[x].add(y)
'#' -> availablePositions[x].clear()
}
}
}
return grid
}
fun tiltSouth(input: List<List<Char>>): List<List<Char>> {
return tiltNorth(input.reversed()).reversed()
}
fun tiltWest(input: List<List<Char>>): List<List<Char>> {
val grid = input.map { it.toMutableList() }
val availablePositions = MutableList(grid.size) { mutableListOf<Int>() }
grid.forEachIndexed { y, chars ->
chars.forEachIndexed { x, c ->
when (c) {
'O' -> if (availablePositions[y].isNotEmpty()) {
grid[y][availablePositions[y].first] = 'O'
availablePositions[y].removeFirst()
grid[y][x] = '.'
availablePositions[y].add(x)
}
'.' -> availablePositions[y].add(x)
'#' -> availablePositions[y].clear()
}
}
}
return grid
}
fun tiltEast(input: List<List<Char>>): List<List<Char>> {
return tiltWest(input.map { it.reversed() }).map { it.reversed() }
}
fun cycle(grid: List<List<Char>>): List<List<Char>> {
return tiltEast(tiltSouth(tiltWest(tiltNorth(grid))))
}
fun part1(input: List<String>): Int {
val grid = input.map { it.toList() }
return calculateWeight(tiltNorth(grid))
}
fun cycleUntilRepetition(grid: List<List<Char>>): MutableList<List<List<Char>>> {
val cycles = mutableListOf<List<List<Char>>>()
var lastCycle = grid
repeat(1_000_000_000) {
lastCycle = cycle(lastCycle)
if (cycles.contains(lastCycle)) {
cycles.add(lastCycle)
return cycles
}
cycles.add(lastCycle)
}
return cycles
}
fun findBillionthCycle(grid: List<List<Char>>): List<List<Char>> {
val cycles = cycleUntilRepetition(grid)
val firstIndex = cycles.indexOf(cycles.last)
val lastIndex = cycles.lastIndex
val indexInLoop = (1_000_000_000 - (firstIndex) - 1) % (lastIndex - firstIndex)
return cycles[firstIndex + indexInLoop]
}
fun part2(input: List<String>): Int {
val grid = input.map { it.toList() }
val cycled = findBillionthCycle(grid)
return calculateWeight(cycled)
}
val timer = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli()
val input = readLines("day14-input.txt")
val result1 = part1(input)
"Result1: $result1".println()
val result2 = part2(input)
"Result2: $result2".println()
println("${LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() - timer} ms")
}
| 0 | Kotlin | 0 | 0 | 41f376bd71a8449e05bbd5b9dd03b3019bde040b | 3,766 | aoc-2023-in-kotlin | Apache License 2.0 |
src/Day06.kt | asm0dey | 572,860,747 | false | {"Kotlin": 61384} | fun main() {
fun part1(input: String): Int {
val distinctCharCount = 4
return input
.windowed(distinctCharCount)
.mapIndexed { index, chunk -> index to (chunk.toSet().size == distinctCharCount) }
.filter { (_, a) -> a }
.map { (a, _) -> a + distinctCharCount }
.first()
}
fun part2(input: String): Int {
val distinctCharCount = 14
return input
.windowed(distinctCharCount)
.mapIndexed { index, chunk -> index to (chunk.toSet().size == distinctCharCount) }
.filter { (_, a) -> a }
.map { (a, _) -> a + distinctCharCount }
.first()
}
check(part1("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 7)
check(part1("bvwbjplbgvbhsrlpgdmjqwftvncz") == 5)
check(part1("nppdvjthqldpwncqszvftbrmjlhg") == 6)
check(part1("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 10)
val input = readInput("Day06")
println(part1(input[0]))
check(part2("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 19)
check(part2("bvwbjplbgvbhsrlpgdmjqwftvncz") == 23)
check(part2("nppdvjthqldpwncqszvftbrmjlhg") == 23)
check(part2("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 29)
println(part2(input[0]))
}
| 1 | Kotlin | 0 | 1 | f49aea1755c8b2d479d730d9653603421c355b60 | 1,250 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/aoc2022/Day04.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2022
import readInput
fun main() {
fun getBounds(section: String): IntRange {
val (lower, upper) = section.split("-", limit = 2).map { it.toInt() }
return IntRange(lower, upper)
}
fun part1(input: List<String>): Int {
return input.map {
val (section1, section2) = it.split(",", limit = 2)
val range1 = getBounds(section1)
val range2 = getBounds(section2)
if (range1.intersect(range2).size == range1.count() || range2.intersect(range1).size == range2.count()) 1
else 0
}.sum()
}
fun part2(input: List<String>): Int {
return input.map {
val (section1, section2) = it.split(",", limit = 2)
val range1 = getBounds(section1)
val range2 = getBounds(section2)
if (range1.intersect(range2).isNotEmpty() || range2.intersect(range1).isNotEmpty()) 1
else 0
}.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test", 2022)
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04", 2022)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 1,250 | adventOfCode | Apache License 2.0 |
src/day07/Day07.kt | GrzegorzBaczek93 | 572,128,118 | false | {"Kotlin": 44027} | package day07
import readInput
import utils.withStopwatch
fun main() {
val testInput = readInput("input07_test")
withStopwatch { println(part1(testInput)) }
// withStopwatch { println(part2(testInput)) }
val input = readInput("input07")
withStopwatch { println(part1(input)) }
// withStopwatch { println(part2(input)) }
}
private fun part1(input: List<String>) = input.parse()
private fun part2(input: List<String>) = input.parse()
fun List<String>.parse() {
val root = Node.Directory(parent = null, name = "/")
var currentNode: Node.Directory = root
fun parseCommand(line: String) {
line.split(" ").let {
when (it[1]) {
"cd" -> {
currentNode = if (it[2] == "..") {
currentNode.parent!!
} else {
currentNode.nodes.first { node -> node.name == it[2] } as Node.Directory
}
}
"ls" -> {}
else -> error("Unsupported operation!")
}
}
}
fun parseDirectory(line: String) {
line.split(" ").let { (_, name) -> currentNode.nodes.add(Node.Directory(currentNode, name)) }
}
fun parseFile(line: String) {
line.split(" ").let { (size, name) -> currentNode.nodes.add(Node.File(currentNode, name, size.toInt())) }
}
fun printTree(node: Node.Directory) {
println(node)
node.nodes.forEach {
when (it) {
is Node.Directory -> {
printTree(it)
}
is Node.File -> {}
}
}
}
fun calculateDirSize(node: Node.Directory): Int {
var size = 0
node.nodes.forEach {
size += when (it) {
is Node.Directory -> calculateDirSize(it)
is Node.File -> it.size
}
}
return size.also { node.size = size }
}
fun calcResultPart1(node: Node.Directory): Int {
var size = 0
if (node.size <= 100000) {
size += node.size
}
node.nodes.forEach {
if (it is Node.Directory) {
size += calcResultPart1(it)
}
}
return size
}
fun calcResultPart2(node: Node.Directory): Int {
val requiredSize = 6975962
var smallest = Int.MAX_VALUE
var smallestSize = Int.MAX_VALUE
node.nodes.forEach {
if (it is Node.Directory) {
val result = calcResultPart2(it)
if (result - requiredSize in 1 until smallest) {
smallest = result - requiredSize
smallestSize = result
}
}
}
if (node.size - requiredSize in 1 until smallest) {
smallest = node.size - requiredSize
smallestSize = node.size
}
return smallestSize
}
drop(1).forEach { line ->
when {
line.startsWith("$") -> parseCommand(line)
line.startsWith("dir") -> parseDirectory(line)
else -> parseFile(line)
}
}
println(calculateDirSize(root))
// printTree(root)
println(calcResultPart2(root))
}
sealed class Node(
open val parent: Directory?,
open val name: String,
) {
data class Directory(
override val parent: Directory?,
override val name: String,
val nodes: MutableList<Node> = mutableListOf(),
var size: Int = 0,
) : Node(parent, name) {
override fun toString(): String {
return "Directory(parent=${parent?.name}, name=$name, size=$size, nodes=$nodes"
}
}
data class File(override val parent: Directory?, override val name: String, val size: Int) : Node(parent, name) {
override fun toString(): String {
return "File(parent=${parent?.name}, name=$name, size=$size)"
}
}
}
/*
- / (dir)
- a (dir)
- e (dir)
- i (file, size=584)
- f (file, size=29116)
- g (file, size=2557)
- h.lst (file, size=62596)
- b.txt (file, size=14848514)
- c.dat (file, size=8504156)
- d (dir)
- j (file, size=4060174)
- d.log (file, size=8033020)
- d.ext (file, size=5626152)
- k (file, size=7214296)
*/
| 0 | Kotlin | 0 | 0 | 543e7cf0a2d706d23c3213d3737756b61ccbf94b | 4,331 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinimizeSumDifference.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.TreeSet
import kotlin.math.abs
import kotlin.math.min
/**
* 2035. Partition Array Into Two Arrays to Minimize Sum Difference
* @see <a href="https://leetcode.com/problems/partition-array-into-two-arrays-to-minimize-sum-difference">
* Source</a>
*/
fun interface MinimizeSumDifference {
operator fun invoke(nums: IntArray): Int
}
class MinimizeSumDifferenceSolution : MinimizeSumDifference {
override operator fun invoke(nums: IntArray): Int {
val n: Int = nums.size
if (n == 2) return abs(nums[1] - nums[0])
val lists1 = generate(nums.copyOfRange(0, n / 2))
val lists2 = generate(nums.copyOfRange(n / 2, n))
var ans = Int.MAX_VALUE
for (d in 0..n / 2) {
val arr1 = lists1[d]
val arr2 = lists2[d]
val k = arr1!!.size
var i1 = 0
var i2 = 0 // we use two pointers to find two elements in arr1, arr2 with minimum absolute difference
while (i1 < k && i2 < k) {
val diff = arr1[i1] - arr2!![i2]
ans = min(ans, abs(diff))
if (diff <= 0) i1++
if (diff >= 0) i2++
}
}
return ans
}
private fun generate(nums: IntArray): Array<IntArray?> {
val n = nums.size
var total = 0
for (num in nums) total += num
val ans = arrayOfNulls<IntArray>(n + 1)
val pos = IntArray(n + 1)
var i = 0
var binomial = 1
while (i <= n) {
ans[i] = IntArray(binomial) // number of ways to choose i from n = binomial(i,n)
binomial = binomial * (n - i) / (i + 1)
i++
}
val maxValue = 1 shl n
for (key in 0 until maxValue) {
var sum1 = 0
for (i0 in 0 until n) {
if (key shr i0 and 1 == 1) sum1 += nums[i0]
}
val sum2 = total - sum1
val bits = Integer.bitCount(key)
ans[bits]!![pos[bits]++] = sum1 - sum2
}
for (arr in ans) arr?.sort()
return ans
}
}
class MinimizeSumDifferenceTree : MinimizeSumDifference {
override operator fun invoke(nums: IntArray): Int {
val n: Int = nums.size
var sum = 0
for (i in nums) {
sum += i
}
val sets: Array<TreeSet<Int>?> = arrayOfNulls(n / 2 + 1)
for (i in 0 until (1 shl n) / 2) {
var curSum = 0
var m = 0
for (j in 0 until n / 2) {
if (i and (1 shl j) != 0) {
curSum += nums[j]
m++
}
}
if (sets[m] == null) sets[m] = TreeSet<Int>()
sets[m]?.add(curSum)
}
var res = Int.MAX_VALUE / 3
for (i in 0 until (1 shl n) / 2) {
var curSum = 0
var m = 0
for (j in 0 until n / 2) {
if (i and (1 shl j) != 0) {
curSum += nums[n / 2 + j]
m++
}
}
val target = (sum - 2 * curSum) / 2
val left: Int? = sets[n / 2 - m]?.floor(target)
val right: Int? = sets[n / 2 - m]?.ceiling(target)
if (left != null) {
res = min(res, abs(sum - 2 * (curSum + left)))
}
if (right != null) {
res = min(res, abs(sum - 2 * (curSum + right)))
}
if (res == 0) return 0
}
return res
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 4,184 | kotlab | Apache License 2.0 |
src/main/kotlin/day12.kt | gautemo | 433,582,833 | false | {"Kotlin": 91784} | import shared.getLines
fun String.isUppercase() = this.uppercase() == this
class CaveNavigate(lines: List<String>, private val allowTwice: Boolean = false) {
private val caveNodes = mutableListOf<CaveNode>()
private var options = mutableListOf<List<CaveNode>>()
private val reachedEnd = mutableListOf<List<CaveNode>>()
init {
for (line in lines) {
val (a, b) = line.split("-")
val existingA = caveNodes.find { it.name == a }
if (existingA == null) {
caveNodes.add(CaveNode(a, mutableListOf(b)))
} else {
existingA.connected.add(b)
}
val existingB = caveNodes.find { it.name == b }
if (existingB == null) {
caveNodes.add(CaveNode(b, mutableListOf(a)))
} else {
existingB.connected.add(a)
}
}
options.add(listOf(caveNodes.find { it.name == "start" }!!))
}
fun findDistinctPaths(): Int {
while (!searchCave()) {
reachedEnd.addAll(options.filter { it.last().name == "end" })
}
return reachedEnd.size
}
private fun canVisitCave(visited: List<CaveNode>, name: String): Boolean {
if (name.isUppercase()) return true
if (name == "start") return false
if (allowTwice) {
val usedUp = visited
.map { it.name }
.filter { !it.isUppercase() }
.groupingBy { it }
.eachCount()
.any { it.value == 2 }
if (!usedUp) return true
}
return visited.none { it.name == name }
}
private fun searchCave(): Boolean {
val newOptions = mutableListOf<List<CaveNode>>()
var isDone = true
for (option in options.filter { it.last().name != "end" }) {
val isAt = option.last()
val nextCaves = caveNodes
.filter { isAt.connected.contains(it.name) }
.filter { canVisitCave(option, it.name) }
nextCaves.forEach {
isDone = false
newOptions.add(option + it)
}
}
if (!isDone) {
options = newOptions
}
return isDone
}
}
data class CaveNode(val name: String, val connected: MutableList<String>)
fun main(){
val input = getLines("day12.txt")
val caveTask1 = CaveNavigate(input)
println(caveTask1.findDistinctPaths())
val caveTask2 = CaveNavigate(input, true)
println(caveTask2.findDistinctPaths())
} | 0 | Kotlin | 0 | 0 | c50d872601ba52474fcf9451a78e3e1bcfa476f7 | 2,583 | AdventOfCode2021 | MIT License |
src/day14/result.kt | davidcurrie | 437,645,413 | false | {"Kotlin": 37294} | package day14
import java.io.File
fun solve(rules: Map<Pair<Char, Char>, Char>, initialPairCounts: Map<Pair<Char, Char>, Long>, steps: Int): Long {
var pairCounts = initialPairCounts
for (step in 1..steps) {
pairCounts = pairCounts.entries.fold(emptyMap()) { acc, pairCount ->
val ch = rules[pairCount.key]
if (ch != null) {
acc + Pair(pairCount.key.first, ch).let { it to (acc[it] ?: 0L) + pairCount.value } +
Pair(ch, pairCount.key.second).let { it to (acc[it] ?: 0L) + pairCount.value }
} else {
acc + (pairCount.key to pairCount.value)
}
}
}
val counts = pairCounts.entries
.fold(emptyMap<Char, Long>()) { acc, pairCount ->
acc + (pairCount.key.first to (acc[pairCount.key.first] ?: 0L) + pairCount.value)
}
return counts.values.let { it.maxOrNull()!! - it.minOrNull()!! }
}
fun main() {
val lines = File("src/day14/input.txt").readLines()
val template = lines[0]
val rules = lines.drop(2).map { it.split(" -> ") }.associate { Pair(it[0][0], it[0][1]) to it[1][0] }
val pairCounts = "$template ".zipWithNext().groupingBy { it }.eachCount().map { (k, v) -> k to v.toLong() }.toMap()
println(solve(rules, pairCounts, 10))
println(solve(rules, pairCounts, 40))
} | 0 | Kotlin | 0 | 0 | dd37372420dc4b80066efd7250dd3711bc677f4c | 1,361 | advent-of-code-2021 | MIT License |
src/Day03.kt | phamobic | 572,925,492 | false | {"Kotlin": 12697} | fun main() {
val alphabetLetters = "abcdefghijklmnopqrstuvwxyz"
val alphabet = ("-$alphabetLetters${alphabetLetters.uppercase()}").toSet()
fun part1(input: List<String>): Int {
var sum = 0
input.forEach { line ->
val middleIndex = line.length / 2
val firstRucksack = line.substring(0, middleIndex).toSet()
val secondRucksack = line.substring(middleIndex).toSet()
val sharedChar = firstRucksack.intersect(secondRucksack).first()
sum += alphabet.indexOf(sharedChar)
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
val groups = input.chunked(3)
groups.forEach { rucksacks ->
val firstRucksack = rucksacks[0].toSet()
val secondRucksack = rucksacks[1].toSet()
val thirdRucksack = rucksacks[2].toSet()
val sharedChar = firstRucksack.intersect(secondRucksack).intersect(thirdRucksack).first()
sum += alphabet.indexOf(sharedChar)
}
return sum
}
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
}
| 1 | Kotlin | 0 | 0 | 34b2603470c8325d7cdf80cd5182378a4e822616 | 1,196 | aoc-2022 | Apache License 2.0 |
src/Day08.kt | mrugacz95 | 572,881,300 | false | {"Kotlin": 102751} | private data class Tree(
val height: Int,
var left: Boolean? = null,
var top: Boolean? = null,
var right: Boolean? = null,
var bottom: Boolean? = null,
val x: Int,
val y: Int,
) {
fun visible() = top == true ||
left == true ||
right == true ||
bottom == true
}
fun main() {
fun List<String>.parse(): List<List<Tree>> {
return mapIndexed { y, line ->
line.mapIndexed { x, tree ->
Tree(tree.toString().toInt(), x = x, y = y)
}
}
}
fun part1(input: List<String>): Int {
val forest = input.parse()
for (y in forest.indices) {
var highest = -1
for (x in forest[y].indices) {
val tree = forest[y][x]
if (tree.height <= highest) {
tree.left = false
} else {
tree.left = true
highest = tree.height
}
}
}
for (y in forest.indices) {
var highest = -1
for (x in forest[y].indices.reversed()) {
val tree = forest[y][x]
if (tree.height <= highest) {
tree.right = false
} else {
tree.right = true
highest = tree.height
}
}
}
for (x in forest.first().indices) {
var highest = -1
for (y in forest.indices) {
val tree = forest[y][x]
if (tree.height <= highest) {
tree.top = false
} else {
tree.top = true
highest = tree.height
}
}
}
for (x in forest.first().indices) {
var highest = -1
for (y in forest.indices.reversed()) {
val tree = forest[y][x]
if (tree.height <= highest) {
tree.bottom = false
} else {
tree.bottom = true
highest = tree.height
}
}
}
return forest.flatten().count {
it.visible()
}
}
fun part2(input: List<String>): Int {
val forest = input.parse()
return forest.flatten().map { tree ->
var left = 0
var right = 0
var top = 0
var bottom = 0
for (x in tree.x - 1 downTo 0) {
left += 1
if (forest[tree.y][x].height >= tree.height) {
break
}
}
for (x in tree.x + 1 until forest.size) {
right += 1
if (forest[tree.y][x].height >= tree.height) {
break
}
}
for (y in tree.y - 1 downTo 0) {
top += 1
if (forest[y][tree.x].height >= tree.height) {
break
}
}
for (y in tree.y + 1 until forest.size) {
bottom += 1
if (forest[y][tree.x].height >= tree.height) {
break
}
}
left * top * right * bottom
}.maxOf { it }
}
val testInput = readInput("Day08_test")
val input = readInput("Day08")
assert(part1(testInput), 21)
println(part1(input))
assert(part2(testInput), 8)
println(part2(input))
}
// Time: 01:00 | 0 | Kotlin | 0 | 0 | 29aa4f978f6507b182cb6697a0a2896292c83584 | 3,566 | advent-of-code-2022 | Apache License 2.0 |
2023/src/main/kotlin/de/skyrising/aoc2023/day24/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2023.day24
import com.microsoft.z3.Context
import com.microsoft.z3.Status
import de.skyrising.aoc.*
val test = TestInput("""
19, 13, 30 @ -2, 1, -2
18, 19, 22 @ -1, -1, -2
20, 25, 34 @ -2, -2, -4
12, 31, 28 @ -1, -2, -1
20, 19, 15 @ 1, -5, -3
""")
fun intersectRays(p1: Vec2l, v1: Vec2l, p2: Vec2l, v2: Vec2l): Vec2d? {
val dx = p2.x - p1.x
val dy = p2.y - p1.y
val det = v2.x * v1.y - v2.y * v1.x
if (det == 0L) return null
val t1 = (dy * v2.x - dx * v2.y) / det.toDouble()
val t2 = (dy * v1.x - dx * v1.y) / det.toDouble()
if (t1 < 0 || t2 < 0) return null
return Vec2d(t1, t2)
}
fun parse(input: PuzzleInput) = input.lines.map { val (x, y, z, vx, vy, vz) = it.longs(); Vec3l(x, y, z) to Vec3l(vx, vy, vz) }
@PuzzleName("Never Tell Me The Odds")
fun PuzzleInput.part1(): Any {
val hailstones = parse(this)
val area = 200000000000000.0..400000000000000.0 //7.0..27.0
return hailstones.unorderedPairs().count { (a, b) ->
val (p1, v1) = a
val (p2, v2) = b
val t = intersectRays(p1.xy(), v1.xy(), p2.xy(), v2.xy()) ?: return@count false
val p = p1.xy().toDouble() + v1.xy().toDouble() * t.x
//log("${a.first} @ ${a.second} ${b.first} @ ${b.second} t=$t $p")
(p.x in area && p.y in area)
}
}
fun PuzzleInput.part2(): Any {
val hailstones = parse(this)
val (rp, rv) = Context().run {
val solver = mkSolver()
val (x, y, z, vx, vy, vz) = mkRealConst("x", "y", "z", "vx", "vy", "vz")
for (i in 0..2) {
val (xi, yi, zi) = mkReal(hailstones[i].first)
val (vxi, vyi, vzi) = mkReal(hailstones[i].second)
val ti = mkRealConst("t$i")
solver += ti gt 0
solver += (xi + vxi * ti) eq (x + vx * ti)
solver += (yi + vyi * ti) eq (y + vy * ti)
solver += (zi + vzi * ti) eq (z + vz * ti)
}
if (solver.check() != Status.SATISFIABLE) error("Not satisfiable")
val m = solver.model
Vec3l(m[x].toLong(), m[y].toLong(), m[z].toLong()) to Vec3l(m[vx].toLong(), m[vy].toLong(), m[vz].toLong())
}
// val durations = hailstones.mapNotNull { (p, v) ->
// intersectRays(rp.xy(), rv.xy(), p.xy(), v.xy())?.x?.toDuration(DurationUnit.NANOSECONDS)
// }.sorted()
// log(durations)
return rp.x + rp.y + rp.z
}
| 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 2,397 | aoc | MIT License |
aoc-2023/src/main/kotlin/aoc/aoc9.kts | triathematician | 576,590,518 | false | {"Kotlin": 615974} | import aoc.AocParser.Companion.parselines
import aoc.*
import aoc.util.getDayInput
val testInput = """
0 3 6 9 12 15
1 3 6 10 15 21
10 13 16 21 30 45
""".parselines
// part 1
fun String.parse() = split(" ").map { it.toInt() }
fun List<Int>.diffs() = zipWithNext { a, b -> b - a }
fun List<Int>.extrapolate(): Long {
val diffs = mutableListOf<List<Int>>()
var cur = this
while (cur.any { it != 0 }) {
diffs.add(cur)
cur = cur.diffs()
}
val lastNums = diffs.map { it.last() }
val res = lastNums.sumOf { it.toLong() }
return res
}
fun List<Int>.extrapolateBack(): Long {
val diffs = mutableListOf<List<Int>>()
var cur = this
while (cur.any { it != 0 }) {
diffs.add(cur)
cur = cur.diffs()
}
val firstNums = diffs.map { it.first() }
val res = firstNums.mapIndexed { i, it ->
if (i % 2 == 0) it.toLong() else -it.toLong()
}.sum()
return res
}
fun List<String>.part1() = sumOf { it.parse().extrapolate() }
// part 2
fun List<String>.part2() = sumOf { it.parse().extrapolateBack() }
// calculate answers
val day = 9
val input = getDayInput(day, 2023)
val testResult = testInput.part1()
val testResult2 = testInput.part2()
val answer1 = input.part1().also { it.print }
val answer2 = input.part2().also { it.print }
// print results
AocRunner(day,
test = { "$testResult, $testResult2" },
part1 = { answer1 },
part2 = { answer2 }
).run()
| 0 | Kotlin | 0 | 0 | 7b1b1542c4bdcd4329289c06763ce50db7a75a2d | 1,455 | advent-of-code | Apache License 2.0 |
src/P14LongestCollatzSequence.kt | rhavran | 250,959,542 | false | null | fun main(args: Array<String>) {
println("Res: " + findSolution())
}
/**
The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.
*/
private fun findSolution(): Long {
val startingPoint = 999_999L
var maxChain = 0L
var startingPointWithMaxChain = 0L
for (x in startingPoint downTo 1L) {
val collatzSequence = collatzSequence(x)
if (collatzSequence > maxChain) {
maxChain = collatzSequence
startingPointWithMaxChain = x
}
}
return startingPointWithMaxChain
}
fun collatzSequence(startingPoint: Long): Long {
var result = 1L
var number = startingPoint
while (number != 1L) {
number = nextCollatzNumber(number)
result++
}
return result
}
fun nextCollatzNumber(n: Long): Long {
return if (n % 2 == 0L) n / 2 else (n * 3) + 1
}
| 0 | Kotlin | 0 | 0 | 11156745ef0512ab8aee625ac98cb6b7d74c7e92 | 1,401 | ProjectEuler | MIT License |
src/Day10.kt | buczebar | 572,864,830 | false | {"Kotlin": 39213} | import kotlin.math.abs
fun main() {
fun getValuesInEachCycle(input: List<String>): List<Int> {
val valuesInCycles = mutableListOf(1)
var valueAfterLastCycle = valuesInCycles.first()
input.forEach { instruction ->
when {
instruction.startsWith("noop") -> {
valuesInCycles.add(valueAfterLastCycle)
}
instruction.startsWith("addx") -> {
val (_, value) = instruction.splitWords()
repeat(2) { valuesInCycles.add((valueAfterLastCycle)) }
valueAfterLastCycle += value.toInt()
}
}
}
return valuesInCycles
}
fun part1(input: List<String>): Int {
val indexes = listOf(20, 60, 100, 140, 180, 220)
val cycles = getValuesInEachCycle(input)
return indexes.sumOf { if (it < cycles.size) cycles[it] * it else 0 }
}
fun part2(input: List<String>) {
getValuesInEachCycle(input)
.dropHead()
.chunked(40)
.map { row ->
row.forEachIndexed { index, x ->
print(
when {
abs(x - index) <= 1 -> "#"
else -> "."
}
)
}
println()
}
}
val testInput = readInput("Day10_test")
check(part1(testInput) == 13_140)
part2(testInput)
val input = readInput("Day10")
println(part1(input))
part2(input)
}
| 0 | Kotlin | 0 | 0 | cdb6fe3996ab8216e7a005e766490a2181cd4101 | 1,598 | advent-of-code | Apache License 2.0 |
src/Day05.kt | LesleySommerville-Ki | 577,718,331 | false | {"Kotlin": 9590} | fun main() {
data class Instructions(
val amount: Int,
val from: Int,
val to: Int
)
fun parseInstructions(input: List<String>): List<Instructions> =
input
.dropWhile { !it.startsWith("move") }
.map { row ->
row.split(" ").let { parts ->
Instructions(parts[1].toInt(), parts[3].toInt() - 1, parts[5].toInt() - 1)
}
}
fun readStacks(input: List<String>): List<MutableList<Char>> {
val stackRows = input.takeWhile { it.contains('[') }
return (1..stackRows.last().length step 4).map { index ->
stackRows
.mapNotNull { it.getOrNull(index) }
.filter { it.isUpperCase() }
.toMutableList()
}
}
fun parseInstructions(
instructions: List<Instructions>,
stacks: List<MutableList<Char>>,
reverse: Boolean
) {
instructions.forEach { (amount, source, destination) ->
val toBeMoved = stacks[source].take(amount)
repeat(amount) { stacks[source].removeFirst() }
stacks[destination].addAll(0, if (reverse) toBeMoved.reversed() else toBeMoved)
}
}
fun part1(input: List<String>): String {
val stacks: List<MutableList<Char>> = readStacks(input)
val instructions: List<Instructions> = parseInstructions(input)
parseInstructions(instructions, stacks, true)
return stacks.map { it.first() }.joinToString("")
}
fun part2(input: List<String>): String {
val stacks: List<MutableList<Char>> = readStacks(input)
val instructions: List<Instructions> = parseInstructions(input)
parseInstructions(instructions, stacks, false)
return stacks.map { it.first() }.joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
val input = readInput("Day05")
part1(input).println()
part2(input).println()
} | 0 | Kotlin | 0 | 0 | ea657777d8f084077df9a324093af9892c962200 | 2,093 | AoC | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem2477/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem2477
/**
* LeetCode page: [2477. Minimum Fuel Cost to Report to the Capital](https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital/);
*/
class Solution {
/* Complexity:
* Time O(n) and Space O(n) where n is the number of cities and equals roads.size + 1;
*/
fun minimumFuelCost(roads: Array<IntArray>, seats: Int): Long {
val edges = buildEdges(roads)
val argumentation = getNodeArgumentation(0, edges, seats, -1)
return argumentation.totalFuelSpent
}
private fun buildEdges(roads: Array<IntArray>): Map<Int, List<Int>> {
val edges = hashMapOf<Int, MutableList<Int>>()
for ((u, v) in roads) {
edges.computeIfAbsent(u) { mutableListOf() }.add(v)
edges.computeIfAbsent(v) { mutableListOf() }.add(u)
}
return edges
}
private fun getNodeArgumentation(
node: Int,
edges: Map<Int, List<Int>>,
seats: Int,
parentNode: Int
): NodeArgumentation {
val children = edges[node] ?: emptyList()
if (children.isEmpty()) {
return NodeArgumentation(0, 1, 1)
}
var totalFuelSpent = 0L
var numPassengersLeavingHere = 0
for (child in children) {
if (child == parentNode) continue
val argumentation = getNodeArgumentation(child, edges, seats, node)
numPassengersLeavingHere += argumentation.numPassengersLeavingHere
totalFuelSpent += argumentation.totalFuelSpent + argumentation.numCarsLeavingHere
}
numPassengersLeavingHere++
val numCarsLeavingHere = getMinRequiredCars(numPassengersLeavingHere, seats)
return NodeArgumentation(totalFuelSpent, numPassengersLeavingHere, numCarsLeavingHere)
}
private class NodeArgumentation(
val totalFuelSpent: Long,
val numPassengersLeavingHere: Int,
val numCarsLeavingHere: Int
)
private fun getMinRequiredCars(totalPassengers: Int, seats: Int): Int {
var minCars = totalPassengers / seats
if (minCars * seats < totalPassengers) minCars++
return minCars
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,200 | hj-leetcode-kotlin | Apache License 2.0 |
src/Day02.kt | emmanueljohn1 | 572,809,704 | false | {"Kotlin": 12720} |
fun main() {
val scoreChart = mapOf("A" to 1, "B" to 2, "C" to 3, "X" to 1, "Y" to 2, "Z" to 3)
val winPair = mapOf(3 to 1, 2 to 3, 1 to 2)
val losePair = winPair.entries.associateBy({ it.value }) { it.key }
fun roundScore (first: Int, second: Int): Int{
if( first == second) return 3
if(winPair[first] == second) {
return 6
}
return 0
}
fun part1(input: List<String>): Int {
return input.map { it.split(" ").map { shape -> scoreChart[shape.trim()]!! } }.sumOf { (first, second) ->
second + roundScore(first, second)
}
}
fun part2(input: List<String>): Int {
return input.map { it.split(" ").map { shape -> scoreChart[shape.trim()]!! } }.sumOf { (first, second) ->
when(second) {
1 -> losePair[first]!! + roundScore(first, losePair[first]!!) // lose
2 -> first + roundScore(first, first) // win
else -> winPair[first]!! + roundScore(first, winPair[first]!!) // draw
}
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("inputs/Day02_test")
println(part1(testInput))
println(part2(testInput))
println("----- Real input -------")
val input = readInput("inputs/Day02")
println(part1(input))
println(part2(input))
}
//15
//12
//----- Real input -------
//11063
//10349 | 0 | Kotlin | 0 | 0 | 154db2b1648c9d12f82aa00722209741b1de1e1b | 1,450 | advent22 | Apache License 2.0 |
src/aoc2022/Day04.kt | anitakar | 576,901,981 | false | {"Kotlin": 124382} | package aoc2022
import println
import readInput
fun main() {
fun part1(input: List<String>): Int {
var sum = 0
for (line in input) {
val ranges = line.split(",")
val range1 = ranges[0].split("-")
val range2 = ranges[1].split("-")
if ((range1[0].toInt() <= range2[0].toInt() && range1[1].toInt() >= range2[1].toInt()) ||
(range2[0].toInt() <= range1[0].toInt() && range2[1].toInt() >= range1[1].toInt())
) sum += 1
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
for (line in input) {
val ranges = line.split(",")
val range1 = ranges[0].split("-")
val range2 = ranges[1].split("-")
if (!(range1[1].toInt() < range2[0].toInt()) && !(range2[1].toInt() < range1[0].toInt())) sum += 1
}
return sum
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 1 | 50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf | 1,196 | advent-of-code-kotlin | Apache License 2.0 |
src/day03/Day03.kt | devEyosiyas | 576,863,541 | false | null | package day03
import println
import readInput
fun main() {
fun priority(c: Char): Int = when (val n = c.code) {
in 65..90 -> n - 65 + 27
in 97..122 -> n - 96
else -> n
}
fun processRucksack(rucksack: String, threeRucksacks: Boolean = false): Int {
val length = rucksack.length
val intersection: Set<Char>
if (threeRucksacks) rucksack.split("\n").let { (a, b, c) ->
intersection = a.toCharArray().toSet().intersect(b.toCharArray().toSet()).intersect(c.toCharArray().toSet())
} else {
val firstPart = rucksack.substring(0, length / 2).toCharArray().toSet()
val secondPart = rucksack.substring(length / 2, length).toCharArray().toSet()
intersection = firstPart.intersect(secondPart)
}
return intersection.sumOf { priority(it) }
}
fun rucksacks(rucksacks: List<String>): Int {
var sum = 0
rucksacks.forEach { rucksack ->
sum += processRucksack(rucksack)
}
return sum
}
fun threeRucksacks(rucksacks: List<String>): Int {
var sum = 0
rucksacks.chunked(3).forEach { rucksack ->
sum += processRucksack(rucksack.joinToString("\n"), true)
}
return sum
}
val testInput = readInput("day03", true)
val input = readInput("day03")
// part one
rucksacks(testInput).println()
rucksacks(input).println()
// part two
threeRucksacks(testInput).println()
threeRucksacks(input).println()
} | 0 | Kotlin | 0 | 0 | 91d94b50153bdab1a4d972f57108d6c0ea712b0e | 1,547 | advent_of_code_2022 | Apache License 2.0 |
src/main/kotlin/combinatorics/Permutations.kt | hastebrot | 62,413,557 | false | null | package combinatorics
import java.util.LinkedList
interface Circular<out T> : Iterable<T> {
fun state(): T
fun inc()
fun isZero(): Boolean // `true` in exactly one state
fun hasNext(): Boolean // `false` if the next state `isZero()`
override fun iterator() : Iterator<T> {
return object : Iterator<T> {
var started = false
override fun next(): T {
if(started) {
inc()
} else {
started = true
}
return state()
}
override fun hasNext() = this@Circular.hasNext()
}
}
}
class Ring(val size: Int) : Circular<Int> {
private var state = 0
override fun state() = state
override fun inc() {state = (1 + state) % size}
override fun isZero() = (state == 0)
override fun hasNext() = (state != size - 1)
init {
assert(size > 0)
}
}
abstract class CircularList<out E, out H: Circular<E>>(val size: Int) : Circular<List<E>> {
protected abstract val state: List<H> // state.size == size
override fun inc() {
state.forEach {
it.inc()
if(! it.isZero()) return
}
}
override fun isZero() = state.all {it.isZero()}
override fun hasNext() = state.any {it.hasNext()}
}
abstract class IntCombinations(size: Int) : CircularList<Int, Ring>(size)
class BinaryBits(N: Int) : IntCombinations(N) {
override val state = Array(N, {Ring(2)}).toList()
override fun state() = state.map {it.state()}.reversed()
}
class Permutations(N: Int) : IntCombinations(N) {
override val state = mutableListOf<Ring>()
init {
for(i in N downTo 1) {
state += Ring(i)
}
}
override fun state(): List<Int> {
val items = (0..size - 1).toCollection(LinkedList())
return state.map {ring -> items.removeAt(ring.state())}
}
}
fun main(args: Array<String>) {
val n = 100
val sumNumbers = Ring(n).sum()
println("In theory, the sum of numbers 0..${n - 1} is ${n * (n - 1) / 2}.")
println("Which is consistent with a practical result of $sumNumbers.\n")
BinaryBits(5).asSequence().filter {it.sum() == 2}.take(5).forEach { println(it) }
println("\npermutations of 3 elements:")
for(configuration in Permutations(3)) {
println(configuration)
}
}
| 7 | Kotlin | 4 | 2 | aea1a4d89e469e69568e77173231683687b4895d | 2,406 | kotlinx.math | Apache License 2.0 |
kotlin/src/katas/kotlin/leetcode/longest_string_of_vowels/LongestStringOfVowels.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.leetcode.longest_string_of_vowels
import datsok.shouldEqual
import org.junit.Test
/**
* https://leetcode.com/discuss/interview-question/233724/Amazon-online-assessment-Longest-string-made-up-of-only-vowels
*/
class LongestStringOfVowelsTests {
@Test fun examples() {
longestString("earthproblem") shouldEqual "eao"
longestString("letsgosomewhere") shouldEqual "ee"
longestString("XXXeeeXXX") shouldEqual "eee"
longestString("aaaXXXeeeXXXooo") shouldEqual "aaaeeeooo"
longestString("aaaXXiXeeeXiiXXooo") shouldEqual "aaaeeeooo"
}
}
private fun longestString(s: String): String {
val s1 = s.takeWhile { it.isVowel() }
val s3 = s.takeLastWhile { it.isVowel() }
val s2 = s.drop(s1.length).dropLast(s3.length).let { s2 ->
var from = 0
var max = ""
s2.forEachIndexed { i, char ->
if (!char.isVowel()) {
if (i - from > max.length) max = s2.substring(from, i)
from = i + 1
}
}
max
}
return s1 + s2 + s3
}
@Suppress("unused")
private fun longestString__(s: String): String {
var max = 0
var result = ""
s.length.allRanges().forEach { r1 ->
val s2 = s.removeRange(r1)
s2.length.allRanges().forEach { r2 ->
val s3 = s2.removeRange(r2)
if (s3.all { it.isVowel() } && s3.length > max) {
max = s3.length
result = s3
}
}
}
return result
}
private fun Int.allRanges() = sequence {
(0 until this@allRanges).forEach { i ->
(i until this@allRanges).forEach { j ->
yield(IntRange(i, j))
}
}
}
private fun Char.isVowel(): Boolean = setOf('a', 'e', 'i', 'o', 'u').contains(this)
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 1,799 | katas | The Unlicense |
src/day05/Day05.kt | sophiepoole | 573,708,897 | false | null | package day05
import readInputText
fun main() {
val testInput = readInputText("day05/input_test")
val input = readInputText("day05/input")
val day = Day05()
println("Part 1: ${day.part1(testInput)}")
println("Part 2: ${day.part2(testInput)}")
println("Part 1: ${day.part1(input)}")
println("Part 2: ${day.part2(input)}")
}
data class Move(val amount: Int, val from: Int, val to: Int) {
companion object {
private val regex = Regex("[0-9]+")
fun getFromString(move: String): Move {
val numbers = regex.findAll(move)
.map(MatchResult::value)
.toList()
return Move(numbers[0].toInt(), numbers[1].toInt(), numbers[2].toInt())
}
}
}
class Day05 {
private fun getMoves(input: String): List<Move> {
return input.split("\n\n")[1]
.split("\n")
.map { Move.getFromString(it) }
}
private fun getStacks(input: String): List<MutableList<Char>> {
val split = input.split("\n\n")
val numberOfCrates = split[0].last().digitToInt()
val stacks = List(numberOfCrates) { mutableListOf<Char>() }
val crates = split[0].split("\n").dropLast(1).asReversed()
crates.map { it.chunked(4) }.forEach { window ->
run {
window.forEachIndexed { index, element ->
val crateLabel = element.toList()[1]
if (crateLabel != ' ') {
stacks[index].add(crateLabel)
}
}
}
}
return stacks
}
fun part1(input: String): String {
val moves = getMoves(input)
val stacks = getStacks(input)
moves.forEach { move ->
for (i in 1..move.amount) {
val crate = stacks[move.from-1].removeLast()
stacks[move.to-1].add(crate)
}
}
var result = ""
for(stack in stacks) {
result += stack.last()
}
return stacks.fold("") { acc, string -> acc + string.last() }
}
fun part2(input: String): String {
val moves = getMoves(input)
val stacks = getStacks(input)
moves.forEach { move ->
val crates = stacks[move.from-1].takeLast(move.amount)
for (i in 1..move.amount) {
stacks[move.from-1].removeLast()
}
stacks[move.to-1].addAll(crates)
}
return stacks.fold("") { acc, string -> acc + string.last() }
}
} | 0 | Kotlin | 0 | 0 | 00ad7d82cfcac2cb8a902b310f01a6eedba985eb | 2,569 | advent-of-code-2022 | Apache License 2.0 |
src/Day07.kt | casslabath | 573,177,204 | false | {"Kotlin": 27085} | class Node (val dir: String, var value: Long, val parent: Node?) {
var children: MutableList<Node> = mutableListOf()
fun updateDirValues(newValue: Long) {
value += newValue
if(this.parent != null) {
this.parent.updateDirValues(newValue)
}
}
fun addChild(dir: String) {
children.add(Node(dir, 0, this))
}
fun getChild(dir: String): Node? {
return this.children.find {
it.dir == dir
}
}
}
operator fun List<Node>.contains(other: String): Boolean {
this.map {
if(it.dir == other) {
return true
}
}
return false
}
fun main() {
val maxSize = 100000
val totalSpace = 70000000
val spaceNeeded = 30000000
val rootNode = Node("/", 0, null)
fun part1(input: List<String>): Long {
var currentNode = rootNode
fun handleCd(dir: String) {
currentNode = when (dir) {
"/" -> {
rootNode
}
".." -> {
currentNode.parent!!
}
else -> {
if(!currentNode.children.contains(dir)) {
currentNode.addChild(dir)
}
currentNode.getChild(dir)!!
}
}
}
fun handleLine(line: List<String>) {
if(line[1] == "cd") {
handleCd(line[2])
} else if(line[0][0].isDigit()) {
currentNode.updateDirValues(line[0].toLong())
}
}
fun calculateTotal(node: Node): Long {
if(node.children.isEmpty()) {
return if(node.value <= maxSize) node.value else 0
}
if(node.value <= maxSize) {
return node.value + node.children.sumOf { calculateTotal(it) }
}
return node.children.sumOf { calculateTotal(it) }
}
input.map {handleLine(it.split(" ")) }
return calculateTotal(rootNode)
}
fun part2(): Long {
fun calculateSmallestRemoval(node: Node, removalSizeMin: Long): Long {
if(node.value >= removalSizeMin) {
return node.value.coerceAtMost(node.children.minOf { calculateSmallestRemoval(it, removalSizeMin) })
}
if(node.children.isEmpty()) {
return Long.MAX_VALUE
}
return node.children.minOf { calculateSmallestRemoval(it, removalSizeMin) }
}
val currentTotal = totalSpace - rootNode.value
if(currentTotal > spaceNeeded) {
return 0
}
val removalSizeMin = spaceNeeded - currentTotal
return calculateSmallestRemoval(rootNode, removalSizeMin)
}
val input = readInput("Day07")
println(part1(input))
println(part2())
}
| 0 | Kotlin | 0 | 0 | 5f7305e45f41a6893b6e12c8d92db7607723425e | 2,892 | KotlinAdvent2022 | Apache License 2.0 |
src/Day07.kt | dragere | 440,914,403 | false | {"Kotlin": 62581} | import kotlin.math.absoluteValue
import kotlin.math.pow
import kotlin.math.roundToInt
import kotlin.streams.toList
fun main() {
fun part1(input: List<Int>): Int {
val pos = input.sorted()[input.size / 2]
return input.sumOf { (it - pos).absoluteValue }
}
fun singleCost(from: Int, to: Int): Int {
val x = (from-to).absoluteValue.toFloat()
return (x + (x / 2.0 * (x-1))).roundToInt()
}
fun cost(l: List<Int>, to: Int): Int {
return l.sumOf { singleCost(it, to) }
}
fun part2(input: List<Int>): Int {
var pos = input.average().roundToInt()
var dir = if (cost(input, pos) > cost(input, pos - 1)) {
-1
} else if (cost(input, pos) > cost(input, pos + 1)) {
1
} else {
return cost(input, pos)
}
while (true) {
pos += dir
dir = if (cost(input, pos) > cost(input, pos - 1)) {
-1
} else if (cost(input, pos) > cost(input, pos + 1)) {
1
} else {
return cost(input, pos)
}
}
}
fun preprocessing(input: String): List<Int> {
return input.trim().split(",").stream().map { it.toInt() }.toList()
}
val realInp = read_testInput("real7")
val testInp = "16,1,2,0,4,2,7,1,2,14"
// println("Test 1: ${part1(preprocessing(testInp))}")
// println("Real 1: ${part1(preprocessing(realInp))}")
// println("-----------")
// println("Test 2: ${part2(preprocessing(testInp))}")
println("Real 2: ${part2(preprocessing(realInp))}")
}
| 0 | Kotlin | 0 | 0 | 3e33ab078f8f5413fa659ec6c169cd2f99d0b374 | 1,628 | advent_of_code21_kotlin | Apache License 2.0 |
src/Day04.kt | dominik003 | 573,083,805 | false | {"Kotlin": 9376} | fun main() {
fun part1(input: List<String>): Int {
var counter = 0
input.forEach {
val ranges = it.split(",")
val leftSide = ranges[0].split("-").map { cur -> Integer.parseInt(cur) }
val rightSide = ranges[1].split("-").map { cur -> Integer.parseInt(cur) }
counter += if (leftSide[0] < rightSide[0]) {
if (leftSide[1] >= rightSide[1]) 1 else 0
} else if (rightSide[0] < leftSide[0]) {
if (rightSide[1] >= leftSide[1]) 1 else 0
} else {
1
}
}
return counter
}
fun part2(input: List<String>): Int {
var counter = 0
input.forEach {
val ranges = it.split(",")
val leftSide = ranges[0].split("-").map { cur -> Integer.parseInt(cur) }
val rightSide = ranges[1].split("-").map { cur -> Integer.parseInt(cur) }
val overlaps = (leftSide[0]..leftSide[1]).toSet() intersect (rightSide[0]..rightSide[1]).toSet()
counter += if (overlaps.isNotEmpty()) 1 else 0
}
return counter
}
// test if implementation meets criteria from the description, like:
val testInput = readInput(4, true)
check(part1(testInput) == 2)
println(part2(testInput))
check(part2(testInput) == 4)
val input = readInput(4)
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | b64d1d4c96c3dd95235f604807030970a3f52bfa | 1,434 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | devLeitner | 572,272,654 | false | {"Kotlin": 6301} | import RPS.*
import RPSRESULT.*
fun main() {
fun part1() {
val input = readInput("./resources/day2source")
val list = arrayListOf<Array<String>>()
input.forEach {
list.add(arrayOf(it.split(" ")[0], it.split(" ")[1]))
}
val enumList = arrayListOf<List<RPS>>()
list.forEach {
enumList.add(it.map { it.toEnum() })
}
// print("$enumList\n")
var totalScore: Int = 0
enumList.forEach {
totalScore += it[0].vs(it[1])
}
print(totalScore)
}
fun part2() {
val input = readInput("resources/day2source")
val list = arrayListOf<Array<String>>()
input.forEach {
list.add(arrayOf(it.split(" ")[0], it.split(" ")[1]))
}
val enumList = arrayListOf<Part2>()
list.forEach {
enumList.add(Part2(it[0].toEnum(), it[1].toResult()))
}
var totalScore = 0
enumList.forEach {
val score = it.result.getScore(it.rps)
totalScore += score
print("$it with $score \n")
}
print(totalScore)
}
// part1()
part2()
}
internal data class Part2(val rps: RPS, val result: RPSRESULT)
internal fun String.toEnum(): RPS {
if (this == "A" || this == "X") return ROCK
if (this == "B" || this == "Y") return PAPER
if (this == "C" || this == "Z") return SCISSORS
throw Exception("wrong type for RPS")
}
internal fun String.toResult(): RPSRESULT {
if (this == "X") return LOSS
if (this == "Y") return DRAW
if (this == "Z") return WIN
throw Exception("wrong type for RPSResult")
}
internal fun RPS.vs(enemy: RPS): Int {
val score = enemy.calcFunc(this) + enemy.score
print("his: $this me: $enemy score for me: $score \n")
return score
}
internal enum class RPS(val score: Int, val calcFunc: (enemy: RPS) -> Int) {
ROCK(1, { enemy ->
when (enemy) {
SCISSORS -> 6
ROCK -> 3
PAPER -> 0
}
}),
PAPER(2, { enemy ->
when (enemy) {
SCISSORS -> 0
ROCK -> 6
PAPER -> 3
}
}),
SCISSORS(3, { enemy ->
when (enemy) {
SCISSORS -> 3
ROCK -> 0
PAPER -> 6
}
});
}
internal fun RPSRESULT.getScore(enemy: RPS) = when (this) {
WIN -> enemy.getWinner().score + 6
DRAW -> enemy.score + 3
LOSS -> enemy.getLoss().score + 0
}
internal fun RPS.getLoss() = when (this) {
ROCK -> SCISSORS
PAPER -> ROCK
SCISSORS -> PAPER
}
internal fun RPS.getWinner() = when (this) {
ROCK -> PAPER
PAPER -> SCISSORS
SCISSORS -> ROCK
}
internal enum class RPSRESULT() {
DRAW,
WIN,
LOSS
}
| 0 | Kotlin | 0 | 0 | 72b9d184fc58f790b393260fc6b1a0ed24028059 | 2,795 | AOC_2022 | Apache License 2.0 |
2021/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2021/day02/Day02.kt | sanderploegsma | 224,286,922 | false | {"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171} | package nl.sanderp.aoc.aoc2021.day02
import nl.sanderp.aoc.common.measureDuration
import nl.sanderp.aoc.common.prettyPrint
import nl.sanderp.aoc.common.readResource
fun main() {
val input = readResource("Day02.txt").lines().map { parse(it) }
val (answer1, duration1) = measureDuration<Int> { partOne(input) }
println("Part one: $answer1 (took ${duration1.prettyPrint()})")
val (answer2, duration2) = measureDuration<Long> { partTwo(input) }
println("Part two: $answer2 (took ${duration2.prettyPrint()})")
}
sealed class Command(val x: Int)
class Forward(x: Int) : Command(x)
class Up(x: Int) : Command(x)
class Down(x: Int) : Command(x)
private fun parse(line: String) = line.split(' ').let { (action, x) ->
when (action) {
"forward" -> Forward(x.toInt())
"up" -> Up(x.toInt())
"down" -> Down(x.toInt())
else -> throw IllegalArgumentException(action)
}
}
fun partOne(commands: List<Command>): Int {
data class State(val position: Int, val depth: Int)
val (position, depth) = commands.fold(State(0, 0)) { state, command ->
when (command) {
is Forward -> state.copy(position = state.position + command.x)
is Down -> state.copy(depth = state.depth + command.x)
is Up -> state.copy(depth = state.depth - command.x)
}
}
return position * depth
}
fun partTwo(commands: List<Command>): Long {
data class State(val position: Int, val depth: Int, val aim: Int)
val (position, depth) = commands.fold(State(0, 0, 0)) { state, command ->
when (command) {
is Forward -> state.copy(position = state.position + command.x, depth = state.depth + command.x * state.aim)
is Up -> state.copy(aim = state.aim - command.x)
is Down -> state.copy(aim = state.aim + command.x)
}
}
return position.toLong() * depth.toLong()
} | 0 | C# | 0 | 6 | 8e96dff21c23f08dcf665c68e9f3e60db821c1e5 | 1,907 | advent-of-code | MIT License |
dcp_kotlin/src/main/kotlin/dcp/day011/day011.kt | sraaphorst | 182,330,159 | false | {"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315} | package dcp.day011
// day011.kt
// By <NAME>, 2020.
typealias Word = String
// Use a trie to represent the dictionary.
class Trie private constructor(val char: Char, private val isWord: Boolean, val children: Map<Char, Trie>) {
constructor(words: List<String>): this('/', false, createTrieWords(words))
companion object {
private fun createTrieWords(words: List<Word>): Map<Char, Trie> {
if (words.isEmpty()) return emptyMap()
// This can be used at the first node or recursively at intermediate nodes.
// Group the words by first character. Filter out any empty entries as they have already been used to
// mark this node's isWord to true.
val wordsByString = words.filter(String::isNotEmpty).groupBy { it.first() }
return wordsByString.keys.map { ch ->
// If ch is the last word in a string, then the child node created has the isWord flag set.
ch to Trie(ch, wordsByString[ch]?.contains(ch.toString()) ?: false,
createTrieWords(wordsByString[ch]?.map { it.drop(1) } ?: emptyList()))
}.toMap()
}
}
// A trie can contain a word.
operator fun contains(word: String): Boolean =
isWord(word)
// Determine if the specified text is a word of this Trie.
fun isWord(word: Word): Boolean =
getNode(word)?.isWord ?: false
// Get the trie node associated with the partial or complete word, if it exists (null otherwise).
private fun getNode(word: Word): Trie? {
if (word.isEmpty())
return null
tailrec
fun aux(remainingWord: Word, node: Trie? = this): Trie? =
when {
node == null -> null
remainingWord.isEmpty() -> node
else -> aux(remainingWord.drop(1), node.children[remainingWord.first()])
}
// This seems redundantly repetitive, but since we're dealing with two data structures,
return aux(word)
}
fun autocomplete(partialWord: Word): List<Word> {
val baseNode = getNode(partialWord) ?: return emptyList()
// Now do a DFS of the tree rooted at node.
fun aux(wordSoFar: Word, words: List<Word>, nodeStack: List<Trie>): List<Word> {
if (nodeStack.isEmpty())
return words
val node: Trie = nodeStack.last()
val extensions = node.children.values.flatMap { trie -> aux(wordSoFar + trie.char, emptyList(), nodeStack + listOf(trie)) }
return if (node.isWord) listOf(wordSoFar) + extensions else extensions
}
return aux(partialWord, emptyList(), listOf(baseNode))
}
override fun toString(): String {
return "Trie(char=$char, isWord=$isWord, children=$children)"
}
}
| 0 | C++ | 1 | 0 | 5981e97106376186241f0fad81ee0e3a9b0270b5 | 2,840 | daily-coding-problem | MIT License |
src/Day05.kt | kipwoker | 572,884,607 | false | null | import java.util.Stack
class CrateStack(val crates: Stack<Char>)
class Move(val quantity: Int, val startIdx: Int, val endIdx: Int)
class State(val stacks: Array<CrateStack>, val moves: Array<Move>) {
fun applyMoves() {
for (move in moves) {
for (i in 1..move.quantity) {
val crate = stacks[move.startIdx].crates.pop()
stacks[move.endIdx].crates.push(crate)
}
}
}
fun applyMoves2() {
for (move in moves) {
val batch = mutableListOf<Char>()
for (i in 1..move.quantity) {
val crate = stacks[move.startIdx].crates.pop()
batch.add(crate)
}
batch.asReversed().forEach { crate ->
stacks[move.endIdx].crates.push(crate)
}
}
}
fun getTops(): String {
return String(stacks.map { it.crates.peek() }.toCharArray())
}
}
fun main() {
fun parseStacks(input: List<String>): Array<CrateStack> {
val idxs = mutableListOf<Int>()
val idxInput = input.last()
for ((index, item) in idxInput.toCharArray().withIndex()) {
if (item != ' ') {
idxs.add(index)
}
}
val result = Array(idxs.size) { _ -> CrateStack(Stack<Char>()) }
val cratesInput = input.asReversed().slice(1 until input.size)
for (line in cratesInput) {
for ((localIdx, idx) in idxs.withIndex()) {
if (line.length > idx && line[idx] != ' ') {
result[localIdx].crates.push(line[idx])
}
}
}
return result
}
fun parseMoves(input: List<String>): Array<Move> {
return input
.map { line ->
val parts = line.split(' ')
Move(parts[1].toInt(), parts[3].toInt() - 1, parts[5].toInt() - 1)
}.toTypedArray()
}
fun parse(input: List<String>): State {
val separatorIdx = input.lastIndexOf("")
val stacksInput = input.slice(0 until separatorIdx)
val movesInput = input.slice(separatorIdx + 1 until input.size)
return State(parseStacks(stacksInput), parseMoves(movesInput))
}
fun part1(input: List<String>): String {
val state = parse(input)
state.applyMoves()
return state.getTops()
}
fun part2(input: List<String>): String {
val state = parse(input)
state.applyMoves2()
return state.getTops()
}
val testInput = readInput("Day05_test")
assert(part1(testInput), "CMZ")
assert(part2(testInput), "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d8aeea88d1ab3dc4a07b2ff5b071df0715202af2 | 2,740 | aoc2022 | Apache License 2.0 |
src/2020/Day16_2.kts | Ozsie | 318,802,874 | false | {"Kotlin": 99344, "Python": 1723, "Shell": 975} | /**
* Now that you've identified which tickets contain invalid values, discard those tickets
* entirely. Use the remaining valid tickets to determine which field is which.
*
* Using the valid ranges for each field, determine what order the fields appear on the tickets.
* The order is consistent between all tickets: if seat is the third field, it is the third
* field on every ticket, including your ticket.
*
* For example, suppose you have the following notes:
*
* ```
* class: 0-1 or 4-19
* row: 0-5 or 8-19
* seat: 0-13 or 16-19
*
* your ticket:
* 11,12,13
*
* nearby tickets:
* 3,9,18
* 15,1,5
* 5,14,9
* ```
*
* Based on the nearby tickets in the above example, the first position must be row, the second
* position must be class, and the third position must be seat; you can conclude that in your
* ticket, class is 12, row is 11, and seat is 13.
*
* Once you work out which field is which, look for the six fields on your ticket that start
* with the word departure. What do you get if you multiply those six values together?
*/
import java.io.File
import java.math.BigInteger
import java.util.*
import kotlin.collections.HashMap
import kotlin.collections.component1
import kotlin.collections.component2
data class Rule(val name: String, val lowerRange: IntRange, val upperRange: IntRange, var order: Int = -1)
fun Rule.matches(num: Int) = num in lowerRange || num in upperRange
val f = File("input/2020/day16").readLines()
val rules = ArrayList<Rule>()
val ticket = ArrayList<Int>()
val nearby = ArrayList<List<Int>>()
var i = 0
while (i < f.size) {
val line = f[i++]
if (line.isEmpty()) continue
when (line) {
"your ticket:" -> {
val x = f[i++]
val t = x.split(",").map { it.toInt() }
ticket.addAll(t)
}
"nearby tickets:" -> {
while (i < f.size) {
val t = f[i++].split(",").map { it.toInt() }
nearby.add(t)
}
}
else -> {
val (name,ranges) = line.split(":")
val (a,b) = ranges.trim().split(" or ")
val (lA,hA) = a.split("-")
val (lB,hB) = b.split("-")
rules.add(Rule(name.trim(), (lA.toInt())..(hA.toInt()), (lB.toInt())..(hB.toInt())))
}
}
}
val valid = nearby.filter { t ->
t.filter { num ->
rules.filter { it.matches(num) }.isEmpty()
}.isEmpty()
}
var r = 1
while (rules.filter { it.order == -1 }.isNotEmpty()) {
println("Round ${r++}")
for (i in 0..rules.lastIndex) {
val candidates = valid.map { t ->
rules
.filter { it.order == -1 }
.filter { it.matches(t[i]) }
}
val notSetRules = rules.filter { rule ->
candidates.filter { it.contains(rule) }.size == valid.size
}
if (notSetRules.size == 1) {
notSetRules[0].order = i
println(" Matched Rule @ $i for ${notSetRules[0]}")
}
}
}
valid.forEach { t ->
val valid = t.forEachIndexed { i,n ->
var m = rules.filter { it.order == i }[0].matches(n)
if (!m) println(t)
}
}
val m = rules.filter { it.name.startsWith("departure") }.map {
println(ticket[it.order])
ticket[it.order]
}
if (m.isNotEmpty()) {
val mul = m.reduce(Int::times)
println(mul)
} | 0 | Kotlin | 0 | 0 | d938da57785d35fdaba62269cffc7487de67ac0a | 3,360 | adventofcode | MIT License |
MyLib_Kotlin/src/main/kotlin/algorithm/dp/LCS.kt | CWKSC | 420,659,931 | false | {"Kotlin": 29346} | package algorithm.dp
sealed class LCS {
companion object {
private fun longestOne(A: String, B: String): String {
return if (A.length >= B.length) A else B
}
fun recursionTopDown(A: String, B: String): String {
if (A.isEmpty() || B.isEmpty()) return "";
val aLast = A.last()
val bLast = B.last()
val subA = A.dropLast(1)
val subB = B.dropLast(1)
return if (aLast == bLast) {
recursionTopDown(subA, subB) + aLast
} else {
longestOne(
recursionTopDown(subA, B),
recursionTopDown(A, subB)
)
}
}
fun recursionBottomUp(LCS: String, remainA: String, remainB: String): String {
if (remainA.isEmpty() || remainB.isEmpty()) return LCS
val aFirst = remainA.first()
val bFirst = remainB.first()
val subA = remainA.drop(1)
val subB = remainB.drop(1)
return if (aFirst == bFirst) {
recursionBottomUp(LCS, subA, subB) + aFirst
} else {
longestOne(
recursionBottomUp(LCS, subA, remainB),
recursionBottomUp(LCS, remainA, subB)
)
}
}
fun recursionTopDownIndex(A: String, B: String, indexA: Int, indexB: Int): String {
if (indexA < 0 || indexB < 0) return "";
val a = A[indexA]
val b = B[indexB]
return if (a == b) {
recursionTopDownIndex(A, B, indexA - 1, indexB - 1) + a
} else {
longestOne(
recursionTopDownIndex(A, B, indexA - 1, indexB),
recursionTopDownIndex(A, B, indexA, indexB - 1),
)
}
}
fun dp(A: String, B: String): Array<IntArray> {
val aLength = A.length
val bLength = B.length
val dp = Array(aLength + 1) { IntArray(bLength + 1) { 0 } }
val direction = Array(aLength + 1) { CharArray(bLength + 1) { ' ' } }
for (row in 0 until aLength) {
for (col in 0 until bLength) {
if (A[row] == B[col]) {
dp[row + 1][col + 1] = dp[row][col] + 1
direction[row + 1][col + 1] = '\\';
} else if (dp[row][col + 1] >= dp[row + 1][col]) {
dp[row + 1][col + 1] = dp[row][col + 1]
direction[row + 1][col + 1] = '^';
} else {
dp[row + 1][col + 1] = dp[row + 1][col]
direction[row + 1][col + 1] = '<';
}
}
}
return dp
}
fun printDp(dp: Array<IntArray>, direction: Array<CharArray>) {
val aLength = dp.size
val bLength = dp[0].size
for (row in 0..aLength) {
for (col in 0..bLength) {
print("${dp[row][col]}${direction[row][col]} ")
}
println()
}
}
fun backtracking(dp: Array<IntArray>, direction: Array<CharArray>, A: String): String {
val aLength = dp.size
val bLength = dp[0].size
var LCS = ""
var row: Int = aLength
var col: Int = bLength
while (direction[row][col] != ' ') {
when (direction[row][col]) {
'\\' -> {
LCS += A.get(row - 1)
row -= 1
col -= 1
}
'<' -> col -= 1
'^' -> row -= 1
}
}
return LCS
}
}
} | 0 | Kotlin | 0 | 1 | 01c8453181012a82b1201ad0e9f896da80282bbf | 3,900 | MyLib_Kotlin | MIT License |
2022/kotlin/src/Day03.kt | tomek0123456789 | 573,389,936 | false | {"Kotlin": 5085} | fun main() {
val map = mutableMapOf<Char, Int>().apply {
var index = 1
('a'..'z').forEach {
this[it] = index
index++
}
('A'..'Z').forEach {
this[it] = index
index++
}
}
fun part1(input: List<String>): Int {
val pairs: MutableList<Pair<String, String>> = mutableListOf();
input.forEach {
val mid = it.length / 2
pairs.add(Pair(it.substring(0, mid), it.substring(mid)))
}
var sum = 0
for ((one, two) in pairs) {
val firstSet = one.toSet()
for (key in two.toSet()) {
if (key in firstSet) {
sum += map[key]!!
break
}
}
}
return sum
}
fun part2(input: List<String>): Int {
var i = 0
var sum = 0
while (i < input.size) {
val (one, two, three) = Triple(input[i].toSet(), input[i + 1].toSet(), input[i + 2].toSet())
for (c in one) {
if (c in two && c in three) {
sum += map[c]!!
break
}
}
i += 3
}
return sum
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5ee55448242ec79475057f43d34f19ae05933eba | 1,542 | aoc | Apache License 2.0 |
src/Day03.kt | psy667 | 571,468,780 | false | {"Kotlin": 23245} | fun main() {
val id = "03"
fun part1(input: List<String>): Int {
return input.sumOf { line ->
line
.chunked(line.length / 2)
.map { it.toSet() }
.reduce { acc, it -> acc.intersect(it) }
.first()
.let {
if (it.code > 96)
it.code - 96
else
it.code - 38
}
}
}
fun part2(input: List<String>): Int {
return input.windowed(3, 3).sumOf { line ->
line
.map { it.toSet() }
.reduce { acc, i -> acc.intersect(i) }
.let {
val i = it.first()
if (i.code > 96)
i.code - 96
else
i.code - 38
}
}
}
val testInput = readInput("Day${id}_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day${id}")
println("==== DAY $id ====")
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 73a795ed5e25bf99593c577cb77f3fcc31883d71 | 1,184 | advent-of-code-2022 | Apache License 2.0 |
2021/src/main/kotlin/sh/weller/aoc/Day03.kt | Guruth | 328,467,380 | false | {"Kotlin": 188298, "Rust": 13289, "Elixir": 1833} | package sh.weller.aoc
object Day03 : SomeDay<List<Char>, Int> {
override fun partOne(input: List<List<Char>>): Int {
val gamma = mutableListOf<Char>()
val epsilon = mutableListOf<Char>()
repeat(input.first().size) { index ->
val list = input.map { it[index] }
val count = list.groupingBy { it }.eachCount()
val numZero = count['0']!!
val numOne = count['1']!!
if (numZero > numOne) {
gamma.add('0')
epsilon.add('1')
} else {
gamma.add('1')
epsilon.add('0')
}
}
val gammaNumber = Integer.parseInt(gamma.joinToString(""), 2)
val epsilonNumber = Integer.parseInt(epsilon.joinToString(""), 2)
return gammaNumber * epsilonNumber
}
override fun partTwo(input: List<List<Char>>): Int {
var oxygen = input
var co2 = input
repeat(input.first().size) { index ->
if (oxygen.size != 1) {
val oxygenMostCommonValue = oxygen.findMostCommonValue(index)
oxygen = oxygen.findOxygen(oxygenMostCommonValue, index)
}
if (co2.size != 1) {
val oxygenMostCommonValue = co2.findMostCommonValue(index)
co2 = co2.findC02(oxygenMostCommonValue, index)
}
}
val oxygenNumber = Integer.parseInt(oxygen.first().joinToString(""), 2)
val co2Number = Integer.parseInt(co2.first().joinToString(""), 2)
return oxygenNumber * co2Number
}
private fun List<List<Char>>.findMostCommonValue(pos: Int): MostCommonValue {
val grouping = map { it[pos] }
.groupingBy { it }.eachCount()
return if (grouping['0']!! == grouping['1']!!) {
MostCommonValue.Equal
} else if (grouping['0']!! > grouping['1']!!) {
MostCommonValue.Zero
} else {
MostCommonValue.One
}
}
private fun List<List<Char>>.findOxygen(mostCommonValue: MostCommonValue, pos: Int): List<List<Char>> =
this.filter {
val currentBit = it[pos]
return@filter when (mostCommonValue) {
MostCommonValue.Equal -> currentBit == '1'
MostCommonValue.One -> currentBit == '1'
MostCommonValue.Zero -> currentBit == '0'
}
}
private fun List<List<Char>>.findC02(mostCommonValue: MostCommonValue, pos: Int): List<List<Char>> =
this.filter {
val currentBit = it[pos]
return@filter when (mostCommonValue) {
MostCommonValue.Equal -> currentBit == '0'
MostCommonValue.One -> currentBit == '0'
MostCommonValue.Zero -> currentBit == '1'
}
}
}
private sealed class MostCommonValue {
object One : MostCommonValue()
object Zero : MostCommonValue()
object Equal : MostCommonValue()
} | 0 | Kotlin | 0 | 0 | 69ac07025ce520cdf285b0faa5131ee5962bd69b | 2,992 | AdventOfCode | MIT License |
src/main/kotlin/endredeak/aoc2022/Day19.kt | edeak | 571,891,076 | false | {"Kotlin": 44975} | package endredeak.aoc2022
fun main() {
val pattern = Regex("Blueprint (\\d+): Each ore robot costs (\\d+) ore. " +
"Each clay robot costs (\\d+) ore. " +
"Each obsidian robot costs (\\d+) ore and (\\d+) clay. " +
"Each geode robot costs (\\d+) ore and (\\d+) obsidian.")
solve( "Not Enough Minerals") {
data class Blueprint(
val id: Int,
val oreCost: Int,
val clayCost: Int,
val obsidianCost: Pair<Int, Int>,
val geodeCost: Pair<Int, Int>) {
private val robots = listOf("ore", "clay", "obsidian", "geode")
.mapIndexed { i, r -> i to r }
.associate { it.second to if (it.first == 0) 1 else 0 }
.toMutableMap()
private val tokens = listOf("ore", "clay", "obsidian", "geode").associateWith { 0 }.toMutableMap()
fun shouldProduceClay() = tokens["ore"]!! >= clayCost && robots["clay"]!! < 3
fun shouldProduceObsidian() = tokens["ore"]!! >= obsidianCost.first && tokens["clay"]!! >= obsidianCost.second
fun shouldProduceGeode() = tokens["clay"]!! >= geodeCost.first && tokens["obsidian"]!! >= geodeCost.second
fun produceGeode(): String {
tokens["ore"] = tokens["ore"]!! - geodeCost.first
tokens["obsidian"] = tokens["obsidian"]!! - geodeCost.second
return "geode"
// robots["geode"] = robots["geode"]!! + 1
}
fun produceObsidian(): String {
tokens["ore"] = tokens["ore"]!! - obsidianCost.first
tokens["clay"] = tokens["clay"]!! - obsidianCost.second
// robots["obsidian"] = robots["obsidian"]!! + 1
return "obsidian"
}
fun produceClay(): String {
tokens["ore"] = tokens["ore"]!! - clayCost
// robots["clay"] = robots["clay"]!! + 1
return "clay"
}
fun simulate(rounds: Int): Int {
var i = 1
while(i <= rounds) {
val r = if (shouldProduceGeode()) {
produceGeode()
}
else if (shouldProduceObsidian()) {
produceObsidian()
}
else if (shouldProduceClay()) {
produceClay()
} else {
""
}
robots.forEach { (k, v) ->
tokens[k] = tokens[k]!! + v
}
if (robots.containsKey(r)) {
robots[r] = robots[r]!! + 1
}
i++
}
return tokens["geode"]!!
}
}
val input = lines
.map { l -> pattern.find(l)!!.destructured.toList().map { it.toInt()} }
.map { l -> Blueprint(l[0], l[1], l[2], l[3] to l[4], l[5] to l[6]) }
.onEach { println(it) }
part1 {
input.map { it.simulate(24) }
.onEach { println(it) }
-1
}
part2 {
}
}
} | 0 | Kotlin | 0 | 0 | e0b95e35c98b15d2b479b28f8548d8c8ac457e3a | 3,272 | AdventOfCode2022 | Do What The F*ck You Want To Public License |
src/Day09.kt | dmarcato | 576,511,169 | false | {"Kotlin": 36664} | import kotlin.math.absoluteValue
import kotlin.math.sign
data class Coords(val x: Int, val y: Int)
data class Snake(
var head: Coords = Coords(0, 0),
val knotsCount: Int = 1
) {
private val knots = mutableListOf<Coords>()
private val tailVisits = mutableSetOf<Coords>()
init {
repeat(knotsCount) { knots.add(head.copy()) }
tailVisits.add(knots.last())
}
fun move(direction: String, amount: Int) {
(0 until amount).forEach { _ ->
head = when (direction) {
"U" -> head.copy(y = head.y + 1)
"D" -> head.copy(y = head.y - 1)
"L" -> head.copy(x = head.x - 1)
"R" -> head.copy(x = head.x + 1)
else -> throw RuntimeException()
}
moveKnots()
}
}
private fun moveKnots() {
(0 until knotsCount).forEach { i ->
val knot = knots[i]
val previous = if (i > 0) knots[i - 1] else head
val diffX = previous.x - knot.x
val diffY = previous.y - knot.y
if (diffX.absoluteValue > 1) {
knots[i] = knot.copy(x = knot.x + diffX.sign, y = knot.y + diffY.sign)
} else if (diffY.absoluteValue > 1) {
knots[i] = knot.copy(x = knot.x + diffX.sign, y = knot.y + diffY.sign)
}
}
tailVisits.add(knots.last())
}
fun tailVisits(): Int = tailVisits.size
}
fun main() {
fun part1(input: List<String>): Int {
val snake = Snake()
input.forEach { cmd ->
val (direction, amountString) = cmd.split(" ")
val amount = amountString.toInt()
snake.move(direction, amount)
}
return snake.tailVisits()
}
fun part2(input: List<String>): Int {
val snake = Snake(knotsCount = 9)
input.forEach { cmd ->
val (direction, amountString) = cmd.split(" ")
val amount = amountString.toInt()
snake.move(direction, amount)
}
return snake.tailVisits()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
check(part1(testInput) == 13) { "part1 check failed" }
check(part2(testInput) == 1) { "part2 check failed" }
val input = readInput("Day09")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 6abd8ca89a1acce49ecc0ca8a51acd3969979464 | 2,414 | aoc2022 | Apache License 2.0 |
app/src/main/java/com/github/codingchili/dice30/model/Scoring.kt | codingchili | 276,671,690 | false | null | package com.github.codingchili.dice30.model
import java.util.*
import kotlin.math.max
/**
* Implements scoring for each dice roll and keeps a history
* of each scoring algorithm with its score.
*/
class Scoring {
val history = ArrayList<Pair<Algorithm, Int>>()
/**
* Records scoring for the given dice using the given algorithm.
* The algorithm can only be used once during a game of dice.
*
* @param dice the set of dice the user rolled, used to calculate the score.
* @param algorithm indicates how score is calculated for the given dice.
*/
fun commit(dice: ArrayList<Die>, algorithm: Algorithm) {
history.add(Pair(algorithm, score(dice, algorithm)))
}
/**
* @return the total score as recorded in the history.
*/
fun total(): Int {
return history.stream()
.map { it.second }
.reduce(0, Integer::sum)
}
/**
* @return a list of scoring algorithms that can still be used for this game.
* this list includes all possible scoring algorithms with the ones recorded in
* history removed.
*/
fun available(): List<Algorithm> {
val available = Algorithm.values().toMutableList()
available.removeAll { algorithm ->
history.stream().filter { entry -> entry.first == algorithm }
.findAny().isPresent
}
return available
}
/**
* Scores the given roll according to the given algorithm. This does not
* record the score in the history and can be used to check the score,
* before calling commit.
*
* @param dice a roll to calculate the score of.
* @param algorithm the algorithm to be used when calculating the score.
*/
fun score(dice: List<Die>, algorithm: Algorithm): Int {
return if (algorithm == Algorithm.LOW) {
dice.map { it.eyes.value() }.filter { it <= 3 }.sum()
} else {
permute(0, dice, null, algorithm)
}
}
/**
* The scoring algorithm does the following,
*
* 1) generate all possible permutations of the die set using recursion
* with depth first and backtracking. Reorder the dice, to make sure
* to get all permutations, not just combinations.
*
* 2) on each iteration, select one of each of the previously unselected dice and create
* new branches to test.
* 3) unmark the last chosen die after each of the currently possible branches are tested.
* 4) calculate the score of the permutation, keep if higher than the current maximum.
*
* The permutations (order) of the dice represents dice combinations.
* Call stack will never be deeper than the number of dice.
*/
private fun permute(score: Int, dice: List<Die>, chosen: Die?, algorithm: Algorithm): Int {
val sorted = dice.sortedBy { it.countOrder }
sorted.filter { !it.counted }.apply {
var high = score
forEach { high = max(permute(score, sorted, it.count(), algorithm), high) }
chosen?.counted = false
return max(high, selected(sorted, algorithm))
}
}
/**
* Calculates the score of the selected dice permutation. The order of the dice
* represents the matching of the groups, as an example
*
* Algorithm is; 8
* Permutation is; 4, 2, 2, 6, 3, 1 (supports any number of dice)
*
* The scoring algorithm creates the following pairs, from left to right
* [4], [2, 2]
*
* The rest of the dice are ignored, as the die after 4,2,2 is a 6 and cannot be used
* with itself or the next N dice to aggregate the sum of the algorithm target.
*
* The scoring algorithm goes from left to right, creating a combination of dice groups
* that matches the sum. Whenever the algorithm encounters a die which value
* when added to the running total exceeds the algorithm target - all other dice are
* ignored and won't be added to a combination.
*
* So for example, if the permutation produced the following instead
*
* Algorithm is; 8
* Permutation is; 4, 2, 2, 3, 1, 6 (same as before, different order)
*
* The following combinations are created
*
* [4], [2, 2], [3, 1]
*
* And the last 6 is ignored, this combination yields a higher score.
*/
private fun selected(dice: List<Die>, algorithm: Algorithm): Int {
var current = 0
var times = 0
dice.forEach {
current += it.eyes.value()
if (current == algorithm.sum) {
current = 0
times++
}
}
return times * algorithm.sum
}
/**
* The different algorithms which can be used to score a roll.
*/
enum class Algorithm(val sum: Int = -1) {
LOW,
FOUR(4),
FIVE(5),
SIX(6),
SEVEN(7),
EIGHT(8),
NINE(9),
TEN(10),
ELEVEN(11),
TWELVE(12);
}
} | 0 | Kotlin | 0 | 2 | 0212dbd0b2bb491239ad94e4997356c6c6c5c1d5 | 5,050 | android-dice | MIT License |
src/main/kotlin/dev/bogwalk/batch7/Problem74.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch7
import dev.bogwalk.util.combinatorics.permutationID
import dev.bogwalk.util.maths.factorial
/**
* Problem 74: Digit Factorial Chains
*
* https://projecteuler.net/problem=74
*
* Goal: For a given length L and limit N, return all integers <= N that start a digit factorial
* non-repeating chain of length L.
*
* Constraints: 10 <= N <= 1e6, 1 <= L <= 60
*
* Other than the factorions 145 & 40585 that loop with themselves (1! + 4! + 5! = 145), only 3
* loops exist:
*
* 169 -> 363601 -> 1454 -> 169
* 871 -> 45361 -> 871
* 872 -> 45362 -> 872
*
* Every starting number eventually becomes stuck in a loop, e.g:
*
* 69 -> 363600 -> 1454 -> 169 -> 363601 (-> 1454)
*
* The above chain is of length 5 and the longest non-repeating chain with a starting number <
* 1e6 has 60 terms.
*
* e.g.: N = 221, L = 7
* output = {24, 42, 104, 114, 140, 141}
*/
class DigitFactorialChains {
// pre-calculation of all digit factorials to increase performance
private val factorials = List(10) { it.factorial().intValueExact() }
// store all special case numbers that either loop to themselves (factorions) or to others
private val loopNums = listOf(145, 169, 871, 872, 1454, 40_585, 45_361, 45_362, 363_601)
// pre-generate the id of these special case numbers
private val loopPerms = loopNums.map { permutationID(it.toLong()) }
/**
* Solution based on the following:
*
* - 1! & 2! will cause an infinite loop with themselves. The only non-single digit factorions
* are: 145 and 40_585.
*
* - If a chain encounters an element in the 3 aforementioned loops or a factorion, it will
* become stuck & the search can be broken early without waiting for a repeated element to
* be found.
*
* - A starter will also be discarded early if it has not encountered a loop but has
* exceeded the requested [length].
*
* - A cache of permutationID(n) to chain length is created to reduce digit factorial sum
* calculations of every starter <= [limit].
*
* - Getting the permutation of a number & checking it against the class variables of
* special case numbers prevents wrong results caused by permutations that don't actually
* start loops. e.g. 27 -> 5042 -> 147 -> 5065 -> 961 -> {363_601 -> loop}. 961 has the same
* id as 169 but technically does not start the loop, so the count must be incremented.
*
* - All new chain elements (less than [limit] & up until a loop element is encountered) are
* stored so that they can be cached with a count using backtracking. e.g. 69 -> 363_600 ->
* loop element = count 5; so cache[id(363_600)] = 4 & cache[id(69)] = 5.
*
* SPEED (WORSE) 563.13ms for N = 1e6, L = 10
*/
fun digitFactorialChainStarters(limit: Int, length: Int): List<Int> {
val starters = mutableListOf<Int>()
val cache = mutableMapOf<String, Int>().apply {
this[permutationID(1L)] = 1
this[permutationID(2L)] = 1
this[loopPerms[0]] = 1
this[loopPerms[1]] = 3
this[loopPerms[2]] = 2
this[loopPerms[3]] = 2
this[loopPerms[4]] = 3
this[loopPerms[5]] = 1
this[loopPerms[6]] = 2
this[loopPerms[7]] = 2
this[loopPerms[8]] = 3
}
nextStarter@for (n in 0..limit) {
var permID = permutationID(n.toLong())
if (permID in cache.keys) {
var cachedLength = cache.getOrDefault(permID, 0)
if (permID in loopPerms && n !in loopNums) cachedLength++
if (cachedLength == length) starters.add(n)
continue@nextStarter
}
val chain = mutableListOf<String?>(permID)
var count = 1
var prev = n
while (true) {
prev = prev.toString().sumOf { ch -> factorials[ch.digitToInt()] }
permID = permutationID(prev.toLong())
if (permID in cache.keys) {
count += cache.getOrDefault(permID, 0)
if (permID in loopPerms && prev !in loopNums) count++
break
} else {
if (prev <= limit) chain.add(permID) else chain.add(null)
count++
if (count > length) continue@nextStarter
}
}
for ((i, element) in chain.withIndex()) {
element?.let {
cache[element] = count - i
}
}
if (count == length) starters.add(n)
}
return starters
}
/**
* Solution improved by not checking every chain element for a match with a special case loop
* starter. The search is instead stopped early if the element cannot be added to the chain
* set because it already exists.
*
* This forces the cache to have to store the special case number count values already falsely
* incremented & to catch these special cases again before checking final count length.
*
* SPEED (BETTER) 409.48ms for N = 1e6, L = 10
*/
fun digitFactorialChainStartersImproved(limit: Int, length: Int): List<Int> {
val starters = mutableListOf<Int>()
val cache = mutableMapOf<String, Int>().apply {
this[loopPerms[0]] = 2 // 145
this[loopPerms[1]] = 4 // 169
this[loopPerms[5]] = 2 // 40585
}
for (n in 0..limit) {
val permId = permutationID(n.toLong())
if (permId !in cache.keys) {
val chain = mutableSetOf<Int>()
var prev = n
while (chain.add(prev) && chain.size <= length) {
prev = prev.toString().sumOf { ch -> factorials[ch.digitToInt()] }
}
cache[permId] = chain.size
}
val valid = when (n) {
145, 40_585 -> length == 1
169, 1454, 363_601 -> length == 3
871, 872, 45_361, 45_362 -> length == 2
else -> cache[permId] == length
}
if (valid) starters.add(n)
}
return starters
}
/**
* Solution identical to the original except that it does not attempt to add all chain
* elements to the cache, only the starter element.
*
* Optimise this solution even further by creating an array of size 60 with each index
* representing [length] - 1 & storing a list of starters that produce this chain length. The
* array would be propagated in the main loop by not breaking the loop for a set length &
* adding each n to this array instead of the starters list. That way, the array can be made
* for all 1e6 starters & multiple test cases can be picked by simply filtering the list
* stored at index [length] - 1.
*
* SPEED (BETTER) 430.76ms for N = 1e6, L = 10
*/
fun digitFactorialChainStartersOptimised(limit: Int, length: Int): List<Int> {
val starters = mutableListOf<Int>()
val cache = mutableMapOf<String, Int>().apply {
this[permutationID(1L)] = 1
this[permutationID(2L)] = 1
this[loopPerms[0]] = 1
this[loopPerms[1]] = 3
this[loopPerms[2]] = 2
this[loopPerms[3]] = 2
this[loopPerms[4]] = 3
this[loopPerms[5]] = 1
this[loopPerms[6]] = 2
this[loopPerms[7]] = 2
this[loopPerms[8]] = 3
}
nextStarter@for (n in 0..limit) {
val nPermID = permutationID(n.toLong())
if (nPermID !in cache.keys) {
var count = 1
var prev = n
while (true) {
prev = prev.toString().sumOf { ch -> factorials[ch.digitToInt()] }
val permID = permutationID(prev.toLong())
if (permID in cache.keys) {
count += cache.getOrDefault(permID, 0)
if (permID in loopPerms && prev !in loopNums) count++
break
} else {
count++
if (count > length) continue@nextStarter
}
}
cache[nPermID] = count
}
var cachedLength = cache.getOrDefault(nPermID, 0)
if (nPermID in loopPerms && n !in loopNums) cachedLength++
if (cachedLength == length) starters.add(n)
}
return starters
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 8,699 | project-euler-kotlin | MIT License |
src/main/kotlin/day25/Day25.kt | qnox | 575,581,183 | false | {"Kotlin": 66677} | package day25
import readInput
import java.math.BigDecimal
fun toDec(snafu: String): Long {
var result = BigDecimal.ZERO
var multiplier = BigDecimal.ONE
for (c in snafu.reversed()) {
val n = when (c) {
'=' -> 0
'-' -> 1
'0' -> 2
'1' -> 3
'2' -> 4
else -> error("Unexpected char $c")
}
result += multiplier * BigDecimal.valueOf(n - 2L)
multiplier *= BigDecimal.valueOf(5L)
}
return result.toLong()
}
fun toSnafu(sumOf: Long): String {
val sb = StringBuilder()
var rest = sumOf
while (rest > 0) {
rest += 2
val n = rest % 5
rest /= 5
val c = when (n.toInt()) {
0 -> '='
1 -> '-'
2 -> '0'
3 -> '1'
4 -> '2'
else -> error("Unexpected num $n")
}
sb.append(c)
}
return sb.reversed().toString()
}
fun main() {
fun part1(input: List<String>): String {
return toSnafu(input.sumOf { toDec(it) })
}
fun part2(input: List<String>): Long {
return 1
}
val testInput = readInput("day25", "test")
val input = readInput("day25", "input")
val part1 = part1(testInput)
println(part1)
check(part1 == "2=-1=0")
println(part1(input))
val part2 = part2(testInput)
println(part2)
check(part2 == 54L)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 727ca335d32000c3de2b750d23248a1364ba03e4 | 1,448 | aoc2022 | Apache License 2.0 |
intstar-mcalculus/src/main/kotlin/intstar/mcalculus/Measurement.kt | vikaskushwaha9oct | 276,676,290 | false | null | package intstar.mcalculus
data class Measurement(
val left: DerivedMeasure,
val comparison: Comparison,
val right: Measure,
val confidence: List<ConfidenceValue>
) {
init {
require(confidence.sumsToOne { it.value }) { "Total confidence should be 1" }
require(confidence.isDisjoint { it.intervals }) { "Intervals should be disjoint" }
require(confidence.isSortedByStart { it.intervals }) { "Confidence values should be sorted by interval starts" }
}
}
data class ConfidenceValue(val intervals: List<Interval>, val value: Double) {
init {
require(value > 0 && value <= 1) { "Confidence value should be > 0 and <= 1" }
require(intervals.isNotEmpty()) { "Intervals within a confidence value should not be empty" }
require(intervals.isDisconnected()) { "Intervals within a confidence value should be disconnected" }
require(intervals.isSortedByStart()) { "Intervals within a confidence value should be sorted by their starts" }
}
}
enum class Comparison(val symbol: String) {
EQUALS("="),
LESS_THAN("<"),
GREATER_THAN(">"),
LESS_THAN_EQUALS("<="),
GREATER_THAN_EQUALS(">=")
}
sealed class Measure
data class ConstantMeasure(val value: Double) : Measure() {
init {
require(value.isDefined()) { "Constant measure should have a defined value" }
}
}
data class DerivedMeasure(val concept: Concept, val measurable: IdEntityConcept) : Measure()
sealed class Concept
data class RelationConcept(val left: EntityConcept, val right: EntityConcept) : Concept()
sealed class EntityConcept : Concept()
data class IdEntityConcept(val value: String) : EntityConcept()
data class ByteEntityConcept(val value: ByteString) : EntityConcept()
data class MeasurementEntityConcept(val value: List<Measurement>) : EntityConcept()
| 0 | Kotlin | 0 | 5 | 27ee78077690f2de1712a2b9f2ca6e4738162b56 | 1,854 | intstar | MIT License |
src/main/kotlin/com/github/michaelbull/advent2023/day6/Race.kt | michaelbull | 726,012,340 | false | {"Kotlin": 195941} | package com.github.michaelbull.advent2023.day6
fun Sequence<String>.toRaces(): Sequence<Race> {
val (times, distances) = raceData()
return times.findNumbers()
.zip(distances.findNumbers())
.map(Pair<Long, Long>::toRace)
}
fun Sequence<String>.toRace(): Race {
val (times, distances) = raceData()
return Race(
time = times.toMergedNumber(),
distance = distances.toMergedNumber()
)
}
data class Race(
val time: Long,
val distance: Long,
) {
fun winningCount(): Int {
val speeds = 1..<time
return speeds.count(::isWinningSpeed)
}
private fun isWinningSpeed(speed: Long): Boolean {
val remaining = time - speed
val travelled = speed * remaining
return travelled > distance
}
}
private val TIME_REGEX = "Time: (.*)".toRegex()
private val DISTANCE_REGEX = "Distance: (.*)".toRegex()
private val NUMBER_REGEX = "\\d+".toRegex()
private val WHITESPACE_REGEX = "\\s+".toRegex()
private fun String.findNumbers(): Sequence<Long> {
return NUMBER_REGEX
.findAll(this)
.map { it.value.toLong() }
}
private fun Sequence<String>.raceData(): Pair<String, String> {
val (timesLine, distancesLine) = chunked(2).single()
val timesResult = requireNotNull(TIME_REGEX.matchEntire(timesLine)) {
"$this must match $TIME_REGEX"
}
val distancesResult = requireNotNull(DISTANCE_REGEX.matchEntire(distancesLine)) {
"$this must match $DISTANCE_REGEX"
}
return timesResult.groupValues[1] to distancesResult.groupValues[1]
}
private fun String.toMergedNumber(): Long {
return replace(WHITESPACE_REGEX, "").toLong()
}
private fun Pair<Long, Long>.toRace(): Race {
return Race(first, second)
}
| 0 | Kotlin | 0 | 1 | ea0b10a9c6528d82ddb481b9cf627841f44184dd | 1,759 | advent-2023 | ISC License |
src/Day04.kt | dmarmelo | 573,485,455 | false | {"Kotlin": 28178} | fun main() {
fun String.toIntRange(): IntRange {
val (start, end) = split("-")
return start.toInt()..end.toInt()
}
fun List<String>.parseInput() = map {
val (range1, range2) = it.split(',')
range1.toIntRange() to range2.toIntRange()
}
operator fun IntRange.contains(other: IntRange) =
first <= other.first && last >= other.last
infix fun IntRange.overlaps(other: IntRange) =
first <= other.last && last >= other.first
fun part1(input: List<Pair<IntRange, IntRange>>): Int {
return input.count { (range1, range2) ->
range1 in range2 || range2 in range1
}
}
fun part2(input: List<Pair<IntRange, IntRange>>): Int {
return input.count { (range1, range2) ->
range1 overlaps range2
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test").parseInput()
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04").parseInput()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5d3cbd227f950693b813d2a5dc3220463ea9f0e4 | 1,129 | advent-of-code-2022 | Apache License 2.0 |
app/src/main/kotlin/day12/Day12.kt | W3D3 | 433,748,408 | false | {"Kotlin": 72893} | package day12
import common.InputRepo
import common.readSessionCookie
import common.solve
var foundPaths = ArrayList<List<Edge>>()
data class Edge(val source: String, val target: String) {
override fun toString(): String {
return "$source -> $target"
}
fun invert(): Edge {
return Edge(target, source)
}
}
private fun parseLine(line: String): Edge {
val split = line.split("-")
return Edge(split[0], split[1])
}
fun main(args: Array<String>) {
val day = 12
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay12Part1, ::solveDay12Part2)
}
fun solveDay12Part1(input: List<String>): Int {
foundPaths = ArrayList()
val normalEdges = input.map(::parseLine)
val inverted = normalEdges.map { it.invert() }
val edges = normalEdges + inverted
findPaths(emptyList(), edges)
println("start, $foundPaths")
return foundPaths.size
}
fun findPaths(previousPath: List<Edge>, edges: Collection<Edge>): List<Edge> {
val currentNode: String
if (previousPath.isEmpty()) {
currentNode = "start"
} else {
currentNode = previousPath.last().target
if (currentNode == "end") {
foundPaths.add(previousPath)
return previousPath
}
}
val notAllowed = previousPath.map { it.source }.filter { it == it.lowercase() }.toSet()
val reachable = edges
.filter { it.source == currentNode }
.filter { !notAllowed.contains(it.target) }
for (next in reachable) {
println(previousPath + next)
findPaths(previousPath + next, edges)
}
return emptyList()
}
fun solveDay12Part2(input: List<String>): Int {
foundPaths = ArrayList()
val normalEdges = input.map(::parseLine)
val inverted = normalEdges.map { it.invert() }
val edges = normalEdges + inverted
findPathsPart2(emptyList(), edges)
return foundPaths.size
}
fun findPathsPart2(previousPath: List<Edge>, edges: Collection<Edge>): List<Edge> {
val currentNode: String
if (previousPath.isEmpty()) {
currentNode = "start"
} else {
currentNode = previousPath.last().target
if (currentNode == "end") {
foundPaths.add(previousPath)
return previousPath
}
}
val notAllowed: Set<String>
val previousSmallCaves = previousPath.map { it.source }.plus(currentNode).filter { it == it.lowercase() }
if (previousSmallCaves.size == previousSmallCaves.distinct().size) {
// no duplicates, allow all small caves
notAllowed = setOf("start")
} else {
notAllowed = previousPath.map { it.source }.filter { it == it.lowercase() }.toSet()
}
val reachable = edges
.filter { it.source == currentNode }
.filter { !notAllowed.contains(it.target) }
for (next in reachable) {
println(previousPath + next)
findPathsPart2(previousPath + next, edges)
}
return emptyList()
} | 0 | Kotlin | 0 | 0 | df4f21cd99838150e703bcd0ffa4f8b5532c7b8c | 2,999 | AdventOfCode2021 | Apache License 2.0 |
src/Day08.kt | richardmartinsen | 572,910,850 | false | {"Kotlin": 14993} | fun main() {
fun part1(input: List<String>) {
val copyInput = input.map { it }
var trees = input.first().count() + input.last().count()
input.dropLast(1).drop(1).forEachIndexed { index, row ->
row.forEachIndexed { i, currentTree ->
// check trees to the left
if (row.substring(0, i).none { leftTree -> leftTree.code >= currentTree.code }) {
// println("adding 1 for tree $currentTree visible from the left")
trees += 1
return@forEachIndexed
}
// check trees to the right
if (row.substring(i+1).none { leftTree -> leftTree.code >= currentTree.code }) {
// println("adding 1 for tree $currentTree visible from the right")
trees += 1
return@forEachIndexed
}
// check trees to the top
if (copyInput.take(index+1).map { it[i]}.none{ topTree -> topTree.code >= currentTree.code}) {
// println("adding 1 for tree $currentTree visible from the top")
trees += 1
return@forEachIndexed
}
// check trees to the bottom
if (copyInput.drop(index+2).map { it[i]}.none{ bottomTree -> bottomTree.code >= currentTree.code}) {
// println("adding 1 for tree $currentTree visible from the bottom")
trees += 1
return@forEachIndexed
}
}
}
println("$trees trees visible from outside the grid")
return
}
fun part2(input: List<String>) {
val copyInput = input.map { it }
var bestScore = 0
var bestPosition = Pair(0, 0)
input.forEachIndexed { y, row ->
row.forEachIndexed { x, currentTree ->
var left = 0
var right = 0
var top = 0
var bottom = 0
row.substring(0, x).reversed().firstOrNull {
left += 1;
it.code >= currentTree.code
}
row.substring(x+1).firstOrNull {
right += 1;
it.code >= currentTree.code
}
copyInput.take(y).map { it[x]}.reversed().firstOrNull {
top += 1;
it.code >= currentTree.code
}
copyInput.drop(y+1).map { it[x]}.firstOrNull {
bottom += 1;
it.code >= currentTree.code
}
// println("tree $currentTree top: $top bottom: $bottom right: $right left: $left")
val scenicScore = top * bottom * left * right
if ( scenicScore > bestScore) {
bestScore = scenicScore
bestPosition = Pair(x+1, y+1)
}
}
}
println("Best scenicScore $bestScore in pos $bestPosition")
return
}
val input = readInput("Day08")
part1(input)
part2(input)
}
| 0 | Kotlin | 0 | 0 | bd71e11a2fe668d67d7ee2af5e75982c78cbe193 | 3,193 | adventKotlin | Apache License 2.0 |
src/Day02.kt | Cryosleeper | 572,977,188 | false | {"Kotlin": 43613} | fun main() {
fun part1(input: List<String>): Int {
val outcomes = mapOf(
"A X" to 3 + 1,
"A Y" to 6 + 2,
"A Z" to 0 + 3,
"B X" to 0 + 1,
"B Y" to 3 + 2,
"B Z" to 6 + 3,
"C X" to 6 + 1,
"C Y" to 0 + 2,
"C Z" to 3 + 3
)
var sum = 0
for (line in input) {
sum += outcomes.getValue(line)
}
return sum
}
fun part2(input: List<String>): Int {
val outcomes = mapOf(
"A X" to 0 + 3,
"A Y" to 3 + 1,
"A Z" to 6 + 2,
"B X" to 0 + 1,
"B Y" to 3 + 2,
"B Z" to 6 + 3,
"C X" to 0 + 2,
"C Y" to 3 + 3,
"C Z" to 6 + 1
)
var sum = 0
for (line in input) {
sum += outcomes.getValue(line)
}
return sum
}
// 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 | a638356cda864b9e1799d72fa07d3482a5f2128e | 1,212 | aoc-2022 | Apache License 2.0 |
src/Day02.kt | TrevorSStone | 573,205,379 | false | {"Kotlin": 9656} | private enum class Decoded {
WIN,
LOSE,
DRAW;
companion object {
fun fromChar(char: Char): Decoded? =
when (char) {
'X' -> LOSE
'Y' -> DRAW
'Z' -> WIN
else -> null
}
}
}
private sealed class RPS(val points: Int) {
fun totalPoints(other: RPS): Int = points + against(other)
abstract fun against(other: RPS): Int
abstract fun decode(other: Decoded): Int
object Rock : RPS(1) {
override fun against(other: RPS): Int =
when (other) {
Paper -> 0
Rock -> 3
Scissors -> 6
}
override fun decode(other: Decoded): Int =
when (other) {
Decoded.WIN -> Paper
Decoded.LOSE -> Scissors
Decoded.DRAW -> Rock
}.totalPoints(this)
}
object Paper : RPS(2) {
override fun against(other: RPS): Int =
when (other) {
Paper -> 3
Rock -> 6
Scissors -> 0
}
override fun decode(other: Decoded): Int =
when (other) {
Decoded.WIN -> Scissors
Decoded.LOSE -> Rock
Decoded.DRAW -> Paper
}.totalPoints(this)
}
object Scissors : RPS(3) {
override fun against(other: RPS): Int =
when (other) {
Paper -> 6
Rock -> 0
Scissors -> 3
}
override fun decode(other: Decoded): Int =
when (other) {
Decoded.WIN -> Rock
Decoded.LOSE -> Paper
Decoded.DRAW -> Scissors
}.totalPoints(this)
}
companion object {
fun fromChar(char: Char): RPS? =
when (char) {
'A',
'X' -> Rock
'B',
'Y' -> Paper
'C',
'Z' -> Scissors
else -> null
}
}
}
fun main() {
fun part1(input: List<String>): Int =
input.sumOf { line ->
val moves = line.mapNotNull { RPS.fromChar(it) }
check(moves.size == 2)
moves[1].totalPoints(moves[0])
}
fun part2(input: List<String>): Int =
input.sumOf { line ->
val moves = line.toCharArray().filter { it.isLetter() }
check(moves.size == 2)
val opponentMove = RPS.fromChar(moves[0]) ?: return@sumOf 0
val decoded = Decoded.fromChar(moves[1]) ?: return@sumOf 0
opponentMove.decode(decoded)
}
// 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 | 2a48776f8bc10fe1d7e2bbef171bf65be9939400 | 2,601 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/Day07.kt | er453r | 572,440,270 | false | {"Kotlin": 69456} | fun main() {
abstract class FileSystem {
abstract fun size(): Int
}
data class Directory(val path: String, val parent: Directory? = null) : FileSystem() {
val files = mutableMapOf<String, FileSystem>()
override fun size() = files.values.sumOf { it.size() }
}
data class File(val size: Int) : FileSystem() {
override fun size() = size
}
fun parseFileSystem(input: List<String>): Map<String, Directory> {
val directoryMap = mutableMapOf("/" to Directory("/"))
var currentDirectory = directoryMap.values.first()
for (cmd in input) {
if (cmd.startsWith("\$ cd")) {
val where = cmd.split("cd ").last().trim()
currentDirectory = when (where) {
"/" -> directoryMap["/"]!!
".." -> currentDirectory.parent!!
else -> directoryMap.getOrPut(currentDirectory.path + where + "/") {
Directory(currentDirectory.path + where + "/", currentDirectory)
}
}
} else if (cmd.startsWith("\$ ls")) {
// println("ls")
} else if (cmd.startsWith("dir")) {
val (_, name) = cmd.split(" ")
currentDirectory.files.putIfAbsent(name, directoryMap.getOrPut(currentDirectory.path + name + "/") {
Directory(currentDirectory.path + name + "/", currentDirectory)
})
} else if (cmd.first().isDigit()) {
val (size, file) = cmd.split(" ")
currentDirectory.files.putIfAbsent(file, File(size.toInt()))
} else
throw Exception("Unknown command $cmd")
}
return directoryMap
}
fun part1(input: List<String>) = parseFileSystem(input).values
.map { it.size() }
.filter { it <= 100000 }
.sum()
fun part2(input: List<String>): Int {
val fs = parseFileSystem(input)
val totalSize = 70000000
val required = 30000000
val currentUsed = fs["/"]!!.size()
val currentFree = totalSize - currentUsed
val missing = required - currentFree
return fs.values
.map { it.size() }
.filter { it >= missing }
.min()
}
test(
day = 7,
testTarget1 = 95437,
testTarget2 = 24933642,
part1 = ::part1,
part2 = ::part2,
)
}
| 0 | Kotlin | 0 | 0 | 9f98e24485cd7afda383c273ff2479ec4fa9c6dd | 2,481 | aoc2022 | Apache License 2.0 |
kotlin/1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.kt | neetcode-gh | 331,360,188 | false | {"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750} | class Solution {
class UnionFind(val n: Int) {
val par = IntArray (n) { it }
val rank = IntArray (n) { 1 }
fun find(x: Int): Int {
if (par[x] != x)
par[x] = find(par[x])
return par[x]
}
fun union(x: Int, y: Int): Boolean {
val px = find(x)
val py = find(y)
if (px == py) return false
if (rank[px] > rank[py]) {
par[py] = px
rank[px] += rank[py]
} else {
par[px] = py
rank[py] += rank[px]
}
return true
}
}
fun findCriticalAndPseudoCriticalEdges(n: Int, _edges: Array<IntArray>): List<List<Int>> {
val edges = _edges.mapIndexed { i, v ->
intArrayOf(v[0], v[1], v[2], i)
}.sortedWith(
Comparator { a, b ->
a[2] - b[2]
}
)
var mstWeight = 0
val uf = UnionFind (n)
for ((u, v, w, i) in edges) {
if (uf.union(u, v)) mstWeight += w
}
val crit = mutableListOf<Int>()
val pseudo = mutableListOf<Int>()
for ((u, v, w, i) in edges) {
val uf2 = UnionFind (n)
var mstWeightWithout = 0
for ((u2, v2, w2, i2) in edges) {
if (i != i2 && uf2.union(u2, v2)) mstWeightWithout += w2
}
if (uf2.rank.max()!! != n || mstWeightWithout > mstWeight) {
crit.add(i)
continue
}
val uf3 = UnionFind (n)
uf3.union(u, v)
var mstWeightWith = w
for ((u3, v3, w3, i3) in edges) {
if (uf3.union(u3, v3)) mstWeightWith += w3
}
if (mstWeightWith == mstWeight) pseudo.add(i)
}
return listOf(crit, pseudo)
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 1,917 | leetcode | MIT License |
src/Day08.kt | esp-er | 573,196,902 | false | {"Kotlin": 29675} | package patriker.day08
import patriker.utils.*
fun main() {
val testInput = readInput("Day08_test")
val testGrid = createGridArray(testInput)
val input = readInput("Day08_input")
val inputGrid = createGridArray(input)
println(solvePart1(testGrid))
println(solvePart1(inputGrid))
println("\nPart 2")
println(solvePart2(testGrid))
println(solvePart2(inputGrid))
}
fun createGridArray(input: List<String>): Array<IntArray>{
val grid = Array(input.size) {
IntArray(input.first().length)
}
input.forEachIndexed{ i, line ->
line.forEachIndexed{ j, c ->
grid[i][j] = c.digitToInt()
}
}
return grid
}
fun isVisible(row: Int, col: Int, grid: Array<IntArray>): Boolean{
if(row == 0 || row == grid.size-1)
return true
if(col == 0 || col == grid.first().size-1)
return true
val treeHeight = grid[row][col]
val northHidden = (0 until row).any{ grid[it][col] >= treeHeight }
if(!northHidden) return true
val southHidden = (row + 1 until grid.size).any{ grid[it][col] >= treeHeight }
if(!southHidden) return true
val westHidden = (0 until col).any{ grid[row][it] >= treeHeight }
if(!westHidden) return true
val eastHidden = (col + 1 until grid[0].size).any{ grid[row][it] >= treeHeight }
if(!eastHidden) return true
return false
}
fun scenicScore(row: Int, col: Int, grid: Array<IntArray>): Int{
val northRange = (row -1 downTo 0 )
val southRange = (row + 1 until grid.size)
val westRange = (col - 1 downTo 0)
val eastRange = (col+ 1 until grid[0].size)
val treeHeight = grid[row][col]
var northVisible = 0
for(i in northRange){
northVisible++
if(grid[i][col] >= treeHeight)
break
}
var southVisible = 0
for(i in southRange){
southVisible++
if(grid[i][col] >= treeHeight)
break
}
var westVisible = 0
for(j in westRange){
westVisible++
if(grid[row][j] >= treeHeight)
break
}
var eastVisible = 0
for(j in eastRange){
eastVisible++
if(grid[row][j] >= treeHeight)
break
}
return northVisible * southVisible * westVisible * eastVisible
}
fun solvePart1(input: Array<IntArray>): Int{
return input.indices.sumOf{ i ->
input[i].indices.count{ j ->
isVisible(i,j, input)
}
}
}
fun solvePart2(input: Array<IntArray>): Int{
return input.indices.maxOf{ i ->
input[i].indices.maxOf{ j ->
scenicScore(i,j, input)
}
}
} | 0 | Kotlin | 0 | 0 | f46d09934c33d6e5bbbe27faaf2cdf14c2ba0362 | 2,625 | aoc2022 | Apache License 2.0 |
advent-of-code-2021/src/main/kotlin/eu/janvdb/aoc2021/day18/Day18.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2021.day18
import eu.janvdb.aoc2021.day18.ExplodeResult.Companion.explosion
import eu.janvdb.aoc2021.day18.ExplodeResult.Companion.noExplosion
import eu.janvdb.aocutil.kotlin.readLines
const val FILENAME = "input18.txt"
fun main() {
val numbers = readLines(2021, FILENAME).map(Number::parse)
part1(numbers)
part2(numbers)
}
private fun part1(numbers: List<Number>) {
val result = numbers.reduce { a, b -> a + b }
println(result)
println(result.magnitude())
}
private fun part2(numbers: List<Number>) {
val result = numbers.asSequence()
.flatMap { number1 -> numbers.map { number2 -> Pair(number1, number2) } }
.map { it.first + it.second }
.maxOf { it.magnitude() }
println(result)
}
abstract class Number {
operator fun plus(other: Number): Number {
val result = NumberElement(this, other)
return result.simplify()
}
fun simplify(): Number {
val result = explode(0).number
if (result != this) return result.simplify()
val result2 = split()
if (result2 != this) return result2.simplify()
return result2
}
abstract fun explode(level: Int): ExplodeResult
abstract fun split(): Number
abstract fun distributeLeft(value: Int): Number
abstract fun distributeRight(value: Int): Number
abstract fun magnitude(): Int
companion object {
fun parse(s: String) = readNumber(TokenStream(s))
private fun readNumber(stream: TokenStream): Number {
val token = stream.nextToken()
if (token == "[") {
val left = readNumber(stream)
stream.nextToken() // ","
val right = readNumber(stream)
stream.nextToken() // "]"
return NumberElement(left, right)
}
return NumberLeaf(token.toInt())
}
}
}
class NumberLeaf(val value: Int) : Number() {
override fun explode(level: Int) = noExplosion(this)
override fun split(): Number {
return if (value > 9) NumberElement(NumberLeaf(value / 2), NumberLeaf((value + 1) / 2)) else this
}
override fun distributeLeft(value: Int) = NumberLeaf(this.value + value)
override fun distributeRight(value: Int) = NumberLeaf(this.value + value)
override fun magnitude() = value
override fun toString() = value.toString()
}
class NumberElement(val left: Number, val right: Number) : Number() {
override fun explode(level: Int): ExplodeResult {
// Check left
val resultLeft = left.explode(level + 1)
if (resultLeft.exploded) {
val newRight =
if (resultLeft.distributeRight != null) right.distributeLeft(resultLeft.distributeRight) else right
return explosion(NumberElement(resultLeft.number, newRight), resultLeft.distributeLeft, null)
}
// Check right
val resultRight = right.explode(level + 1)
if (resultRight.exploded) {
val newLeft =
if (resultRight.distributeLeft != null) left.distributeRight(resultRight.distributeLeft) else left
return explosion(NumberElement(newLeft, resultRight.number), null, resultRight.distributeRight)
}
// Only explode if level too high and numbers left and right
if (level > 3 && left is NumberLeaf && right is NumberLeaf) {
return explosion(NumberLeaf(0), left.value, right.value)
}
// No explosion
return noExplosion(this)
}
override fun split(): Number {
val splitLeft = left.split()
if (splitLeft != left) return NumberElement(splitLeft, right)
val splitRight = right.split()
if (splitRight != right) return NumberElement(left, splitRight)
return this
}
override fun distributeLeft(value: Int) = NumberElement(left.distributeLeft(value), right)
override fun distributeRight(value: Int) = NumberElement(left, right.distributeRight(value))
override fun magnitude() = 3 * left.magnitude() + 2 * right.magnitude()
override fun toString() = "[$left,$right]"
}
data class ExplodeResult(
val number: Number,
val distributeLeft: Int?,
val distributeRight: Int?,
val exploded: Boolean
) {
companion object {
fun noExplosion(number: Number) = ExplodeResult(number, null, null, false)
fun explosion(number: Number, distributeLeft: Int?, distributeRight: Int?) = ExplodeResult(
number, distributeLeft, distributeRight, true
)
}
}
class TokenStream(private val s: String) {
var index = 0
fun nextToken(): String {
val result: String = if (s[index] == '[' || s[index] == ']' || s[index] == ',') {
s.substring(index, index + 1)
} else {
var endIndex = index
while (s[endIndex].isDigit()) endIndex++
s.substring(index, endIndex)
}
index += result.length
return result
}
} | 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 4,436 | advent-of-code | Apache License 2.0 |
src/main/kotlin/com/jacobhyphenated/advent2023/day4/Day4.kt | jacobhyphenated | 725,928,124 | false | {"Kotlin": 121644} | package com.jacobhyphenated.advent2023.day4
import com.jacobhyphenated.advent2023.Day
import com.jacobhyphenated.advent2023.pow
/**
* Day 4: Scratchcards
*
* Scratch cards have lists of winning numbers and a list of your numbers
* You have a list of scratch cards as the puzzle input
*/
class Day4: Day<List<ScratchCard>> {
override fun getInput(): List<ScratchCard> {
return readInputFile("4").lines().map { parseInput(it) }
}
/**
* Part 1
* A puzzle score start at 1 for one matching number then doubles for each additional matching number
* (4 matching numbers = 8)
* Return the total score for all scratch cards
*
* Use set intersection to determine the number of matches. Then exponent math to quickly calculate score
*/
override fun part1(input: List<ScratchCard>): Int {
return input.sumOf { card ->
val matchCount = card.matchCount()
if(matchCount == 0) { 0 } else { 2 pow (matchCount - 1) }
}
}
/**
* Part 2
*
* Winning a scratch card only means you get additional cards. You get one additional card
* of each of the cards below the current card based on the number of matches.
* So if card 1 matches 4 numbers, you get an additional copy of 2,3,4,5
*
* How many cards do you have in total?
*/
override fun part2(input: List<ScratchCard>): Int {
// keep a list of the number of copies for each card type (using the puzzle input index for card id)
val cardCounts = MutableList(input.size) { 1 }
for (cardIndex in input.indices) {
val matchCount = input[cardIndex].matchCount()
// multiple copies of this card yield multiple additional copies of subsequent cards
val multiplier = cardCounts[cardIndex]
(cardIndex + 1 .. cardIndex + matchCount).forEach { cardCounts[it] += multiplier }
}
return cardCounts.sum()
}
fun parseInput(line: String): ScratchCard {
val (winningNumbers, yourNumbers) = line.split(":")[1].split("|").map { numberList ->
numberList.trim().split("\\s+".toRegex()).map { it.toInt() }
}
return ScratchCard(winningNumbers.toSet(), yourNumbers.toSet())
}
override fun warmup(input: List<ScratchCard>) {
part1(input)
}
}
data class ScratchCard(val winningNumbers: Set<Int>, val yourNumbers: Set<Int>) {
fun matchCount(): Int {
return winningNumbers.intersect(yourNumbers).size
}
}
fun main(@Suppress("UNUSED_PARAMETER") args: Array<String>) {
Day4().run()
} | 0 | Kotlin | 0 | 0 | 90d8a95bf35cae5a88e8daf2cfc062a104fe08c1 | 2,462 | advent2023 | The Unlicense |
src/Day08.kt | punx120 | 573,421,386 | false | {"Kotlin": 30825} | fun main() {
fun buildArray(input: List<String>): Array<IntArray> {
val n = input[0].length
val array = Array(n) { IntArray(n) }
for (i in 0 until n) {
for (j in 0 until n) {
array[i][j] = input[i][j].digitToInt()
}
}
return array
}
fun part1(array: Array<IntArray>): Int {
val n = array.size
val visibleTrees = BooleanArray(n * n)
var count = 0
for (r in array.indices) {
var max = -1
for (c in array.indices) {
if (array[r][c] > max) {
if (!visibleTrees[r * n + c]) {
visibleTrees[r * n + c] = true
++count
}
max = array[r][c]
}
}
max = -1
for (c in n - 1 downTo 0) {
if (array[r][c] > max) {
if (array[r][c] > max) {
if (!visibleTrees[r * n + c]) {
visibleTrees[r * n + c] = true
++count
}
max = array[r][c]
}
}
}
}
for (c in array.indices) {
var max = -1
for (r in array.indices) {
if (array[r][c] > max) {
if (!visibleTrees[r * n + c]) {
visibleTrees[r * n + c] = true
++count
}
max = array[r][c]
}
}
max = -1
for (r in n - 1 downTo 0) {
if (array[r][c] > max) {
if (!visibleTrees[r * n + c]) {
visibleTrees[r * n + c] = true
++count
}
max = array[r][c]
}
}
}
return count
}
fun computeScenicScore(array: Array<IntArray>, r: Int, c: Int): Int {
var left = 0
var right = 0
var top = 0
var bottom = 0
val h = array[r][c]
for (i in r-1 downTo 0) {
++left
if (array[i][c] >= h) {
break
}
}
for (i in r+1 until array.size) {
++right
if (array[i][c] >= h) {
break
}
}
for (i in c+1 until array.size) {
++bottom
if (array[r][i] >= h) {
break
}
}
for (i in c-1 downTo 0) {
++top
if (array[r][i] >= h) {
break
}
}
return left * right * top * bottom
}
fun part2(array: Array<IntArray>): Int {
var maxScenicScore = 0
for (r in array.indices) {
for (c in array.indices) {
val score = computeScenicScore(array, r, c)
if (score > maxScenicScore) {
maxScenicScore = score
}
}
}
return maxScenicScore
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
val testArray = buildArray(testInput)
println(part1(testArray))
println(part2(testArray))
val input = readInput("Day08")
val array = buildArray(input)
println(part1(array))
println(part2(array))
}
| 0 | Kotlin | 0 | 0 | eda0e2d6455dd8daa58ffc7292fc41d7411e1693 | 3,539 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/day13.kt | gautemo | 725,273,259 | false | {"Kotlin": 79259} | import shared.Input
import shared.toInts
fun main() {
val input = Input.day(13)
println(day13A(input))
println(day13B(input))
}
fun day13A(input: Input): Int {
return input.chunks.sumOf {
reflectsVertically(it) ?: (reflectsHorizontally(it)!! * 100)
}
}
fun day13B(input: Input): Int {
return input.chunks.sumOf {
val avoid = reflectsVertically(it) ?: (reflectsHorizontally(it)!! * 100)
for(x in 0 ..< it.lines()[0].length) {
for(y in 0 ..< it.lines().size) {
val replaceAt = x + (y * (it.lines()[0].length + 1))
val altered = it.replaceRange(replaceAt, replaceAt + 1, if(it[replaceAt] == '.') "x" else ".")
reflectsVertically(altered, avoid)?.let { found ->
return@sumOf found
}
reflectsHorizontally(altered, avoid)?.let { found ->
return@sumOf found * 100
}
}
}
throw Exception()
}
}
private fun reflectsVertically(patterns: String, avoid: Int? = null): Int? {
for(i in 1 ..< patterns.lines()[0].length) {
val reflected = patterns.lines().all {
val right = it.substring(i).take(i)
val left = it.take(i).takeLast(right.length)
left == right.reversed()
}
if(reflected && i != avoid) return i
}
return null
}
private fun reflectsHorizontally(patterns: String, avoid: Int? = null): Int? {
var flipped = ""
for(x in 0 ..< patterns.lines()[0].length) {
patterns.lines().forEach { flipped += it[x] }
flipped += "\n"
}
return reflectsVertically(flipped.trim(), avoid?.let { it / 100 })
} | 0 | Kotlin | 0 | 0 | 6862b6d7429b09f2a1d29aaf3c0cd544b779ed25 | 1,717 | AdventOfCode2023 | MIT License |
src/main/java/leetcode/kotlin/IntProblems.kt | Zhaoyy | 110,489,661 | false | {"Java": 248008, "Kotlin": 18188} | package leetcode.kotlin
import leetcode.easy.TreeNodeProblems.TreeNode
fun main(args: Array<String>) {
val intervals = ArrayList<Interval>()
intervals.add(Interval(1, 4))
intervals.add(Interval(0, 4))
println(merge(intervals))
}
class Interval(
var start: Int = 0,
var end: Int = 0
)
fun merge(intervals: List<Interval>): List<Interval> {
val ans = ArrayList<Interval>()
for (i in intervals.sortedBy {
it.start
}) {
if (ans.size > 0 && i.start <= ans.last().end) {
val last = ans.last()
last.end = Math.max(i.end, last.end)
} else {
ans.add(i)
}
}
return ans
}
class IntProblems {
/**
* https://leetcode.com/problems/longest-palindromic-substring/description/
*/
private var maxStart = 0
private var maxLen = 1
fun longestPalindrome(s: String): String {
for (i in 0..s.lastIndex) {
extend(s, i, i)
extend(s, i, i + 1)
}
return s.substring(maxStart, maxStart + maxLen)
}
private fun extend(s: String, l: Int, r: Int) {
var start = l
var end = r
while (start >= 0 && end < s.length && s[start] == s[end]) {
start--
end++
}
val len = end - start - 1
if (len > maxLen) {
maxStart = start + 1
maxLen = len
}
}
/**
* https://leetcode.com/problems/rotated-digits/description/
*/
fun rotatedDigits(N: Int): Int {
var count = 0
var i = 1
while (i <= N) {
if (isValid(i)) count++
i += 1 + extraStep(i)
}
return count
}
private fun extraStep(i: Int): Int {
var inc = 1
var t = i
while (t >= 10) {
inc *= 10
t /= 10
}
return if (t == 3 || t == 4 || t == 7) {
inc - 1
} else {
0
}
}
private fun isValid(n: Int): Boolean {
/*
Valid if N contains ATLEAST ONE 2, 5, 6, 9
AND NO 3, 4 or 7s
*/
var r = false
var t = n
while (t > 0) {
when (t % 10) {
2 -> r = true
5 -> r = true
6 -> r = true
9 -> r = true
3 -> return false
4 -> return false
7 -> return false
}
t /= 10
}
return r
}
/**
* https://leetcode.com/problems/valid-palindrome-ii/description/
*/
fun validPalindrome(s: String): Boolean {
if (s.length < 2) return true
val p = subValidPalindrome(s, 0, s.lastIndex)
return if (p.first < p.second) {
val p1 = subValidPalindrome(s, p.first + 1, p.second)
if (p1.first < p1.second) {
val p2 = subValidPalindrome(s, p.first, p.second - 1)
p2.first >= p2.second
} else {
true
}
} else {
true
}
}
private fun subValidPalindrome(s: String, l: Int, r: Int): Pair<Int, Int> {
var a = l
var b = r
while (a < b) {
if (s[a] != s[b]) {
break
}
a++
b--
}
return Pair(a, b)
}
/**
* https://leetcode.com/problems/two-sum-iv-input-is-a-bst/description/
*/
private val set = hashSetOf<Int>()
fun findTargetBetter(root: TreeNode?, k: Int): Boolean {
if (root == null) return false
val diff = k - root.`val`
if (set.contains(diff)) return true
set.add(root.`val`)
return findTargetBetter(root.left, k) || findTargetBetter(root.right, k)
}
private val list = arrayListOf<Int>()
fun findTarget(root: TreeNode?, k: Int): Boolean {
buildList(root)
if (list.size > 1 && (list[0] + list[1]) <= k && k <= (list[list.lastIndex] + list[list.lastIndex - 1])) {
for (v in list) {
val diff = k - v
if (diff != v && list.contains(diff)) {
return true
}
}
}
return false
}
private fun buildList(node: TreeNode?) {
node?.let {
node.left?.let {
buildList(node.left)
}
list.add(node.`val`)
node.right?.let {
buildList(node.right)
}
}
}
/**
* https://leetcode.com/problems/sum-of-square-numbers/description/
*/
fun judgeSquareSum(c: Int): Boolean {
var l = 0
var r = Math.sqrt(c.toDouble()).toInt()
while (l <= r) {
val t = l * l + r * r
if (t == c) return true
if (t > c) r--
if (t < c) l++
}
return false
}
/**
* https://leetcode.com/problems/average-of-levels-in-binary-tree/description/
*/
fun averageOfLevels(root: TreeNode?): DoubleArray {
return if (root == null) {
doubleArrayOf()
} else {
countNodeWithLevel(root, 0)
var index = 0
val result: MutableList<Double> = ArrayList()
while (levelCount.containsKey(index)) {
result.add(levelSum[index]!! / levelCount[index]!!)
index++
}
result.toDoubleArray()
}
}
private val levelSum: MutableMap<Int, Double> = HashMap()
private val levelCount: MutableMap<Int, Int> = HashMap()
private fun countNodeWithLevel(node: TreeNode, level: Int) {
levelSum.put(level, levelSum.getOrDefault(level, 0.toDouble()) + node.`val`)
levelCount[level] = levelCount.getOrDefault(level, 0) + 1
node.left?.apply {
countNodeWithLevel(node.left, level + 1)
}
node.right?.apply {
countNodeWithLevel(node.right, level + 1)
}
}
} | 0 | Java | 0 | 0 | 3f801c8f40b5bfe561c5944743a779dad2eca0d3 | 5,203 | leetcode | Apache License 2.0 |
src/Day03.kt | hufman | 573,586,479 | false | {"Kotlin": 29792} | import kotlin.streams.toList
fun main() {
fun score(char: Char): Int {
return if (('a' .. 'z').contains(char)) {
char - 'a' + 1
} else if (('A' .. 'Z').contains(char)) {
char - 'A' + 27
} else {
throw IllegalArgumentException(char.toString())
}
}
fun parse(input: List<String>): List<Pair<String, String>> {
return input.filter {it.length > 2}.map {
Pair(it.substring(0 until it.length/2), it.substring(it.length/2 until it.length))
}
}
fun part1(input: List<String>): Int {
val common = parse(input).map {
it.first.toCharArray().toSet().intersect(it.second.toCharArray().toSet()).first()
}
return common.map {
score(it)
}.sum()
}
fun part2(input: List<String>): Int {
val troops = input.chunked(3)
val badges = troops.map { sacks ->
sacks.fold(sacks[0].toCharArray().toSet()) { acc, sack ->
acc.intersect(sack.toCharArray().toSet())
}.first()
}
return badges.map {
score(it)
}.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 | 1bc08085295bdc410a4a1611ff486773fda7fcce | 1,212 | aoc2022-kt | Apache License 2.0 |
src/Day09.kt | Misano9699 | 572,108,457 | false | null | fun main() {
val head = 0
var tail = 1
var knots = MutableList(tail + 1) { Point(0, 0) }
var tailPoints = mutableSetOf(knots[tail])
fun reset() {
knots = MutableList(tail + 1) { Point(0, 0) }
tailPoints = mutableSetOf(knots[tail])
}
fun moveTailY(knot: Int) = when (knots[knot - 1].y - knots[knot].y) {
1, 2 -> knots[knot].up()
-1, -2 -> knots[knot].down()
else -> knots[knot]
}
fun moveTailX(knot: Int) = when (knots[knot - 1].x - knots[knot].x) {
1, 2 -> knots[knot].right()
-1, -2 -> knots[knot].left()
else -> knots[knot]
}
fun moveTail(knot: Int): Point {
var point = when (knots[knot - 1].x - knots[knot].x) {
2 -> moveTailY(knot).right()
-2 -> moveTailY(knot).left()
else -> knots[knot]
}
point = when (knots[knot - 1].y - knots[knot].y) {
2 -> moveTailX(knot).up()
-2 -> moveTailX(knot).down()
else -> point
}
return point
}
fun moveHead(direction: String) = when (direction) {
"R" -> knots[head].right()
"L" -> knots[head].left()
"U" -> knots[head].up()
"D" -> knots[head].down()
else -> knots[head]
}
fun moveKnots(direction: String, knot: Int) {
(1..knot).forEach { _ ->
knots[head] = moveHead(direction)
(1..tail).forEach {
knots[it] = moveTail(it)
}
tailPoints.add(knots[tail])
}
}
fun part1(input: List<String>): Int {
tail = 1
reset()
input.forEach { line ->
val move = line.split(" ")
moveKnots(move[0], move[1].toInt())
}
return tailPoints.count()
}
fun part2(input: List<String>): Int {
tail = 9
reset()
input.forEach { line ->
val move = line.split(" ")
moveKnots(move[0], move[1].toInt())
}
return tailPoints.count()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
val input = readInput("Day09")
println("---- PART 1 ----")
check(part1(testInput).also { println("Answer test input part1: $it") } == 13)
println("Answer part1: " + part1(input))
println("---- PART 2 ----")
check(part2(testInput).also { println("Answer test input part2: $it") } == 1)
println("Answer part2: " + part2(input))
}
data class Point(val x: Int, val y: Int) {
fun left(): Point = Point(this.x - 1, this.y)
fun right(): Point = Point(this.x + 1, this.y)
fun up(): Point = Point(this.x, this.y + 1)
fun down(): Point = Point(this.x, this.y - 1)
}
| 0 | Kotlin | 0 | 0 | adb8c5e5098fde01a4438eb2a437840922fb8ae6 | 2,774 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/dvdmunckhof/aoc/event2021/Day08.kt | dvdmunckhof | 318,829,531 | false | {"Kotlin": 195848, "PowerShell": 1266} | package com.dvdmunckhof.aoc.event2021
class Day08(private val input: List<String>) {
fun solvePart1(): Int {
val uniqueLengths = setOf(2, 3, 4, 7)
return input.asSequence()
.flatMap { it.split(" ").drop(11) }
.count { uniqueLengths.contains(it.length) }
}
fun solvePart2(): Int = input.sumOf { entry ->
val values = entry.split(" ")
val digit1 = values.first { it.length == 2 }.toSet()
val digit4 = values.first { it.length == 4 }.toSet()
values.subList(11, 15).fold(0) { acc, value ->
val digit = when (value.length) {
2 -> 1
3 -> 7
4 -> 4
5 -> when (commonChars(value, digit1, digit4)) {
1 to 2 -> 2
2 to 3 -> 3
1 to 3 -> 5
else -> error("Invalid digit")
}
6 -> when (commonChars(value, digit1, digit4)) {
2 to 3 -> 0
1 to 3 -> 6
2 to 4 -> 9
else -> error("Invalid digit")
}
7 -> 8
else -> error("Invalid digit")
}
acc * 10 + digit
}.toInt()
}
private fun commonChars(value: String, digit1: Set<Char>, digit4: Set<Char>): Pair<Int, Int> {
val chars = value.toCharArray()
val common1 = chars.count(digit1::contains)
val common4 = chars.count(digit4::contains)
return common1 to common4
}
}
| 0 | Kotlin | 0 | 0 | 025090211886c8520faa44b33460015b96578159 | 1,572 | advent-of-code | Apache License 2.0 |
src/day4/Day.kt | helbaroudy | 573,339,882 | false | null | package day4
import readInput
typealias Section = Pair<Int, Int>
fun main() {
fun Section.contains(elf: Section) = this.first >= elf.first && this.second <= elf.second
fun Section.overlaps(elf: Section) = this.first >= elf.first && this.first <= elf.second
fun parse(entry: String): Pair<Section, Section> {
val rawElf1 = entry.split(",")[0]
val rawElf2 = entry.split(",")[1]
val elf1 = Section(
rawElf1.split("-")[0].toInt(),
rawElf1.split("-")[1].toInt()
)
val elf2 = Section(
rawElf2.split("-")[0].toInt(),
rawElf2.split("-")[1].toInt()
)
return Pair(elf1, elf2)
}
fun day4(input: List<String>, fullyContains: Boolean): Int {
var total = 0
for (entry in input) {
val (elf1, elf2) = parse(entry)
if (fullyContains) {
if (elf1.contains(elf2) || elf2.contains(elf1)) total++
} else if (elf1.overlaps(elf2) || elf2.overlaps(elf1)) {
total++
}
}
return total
}
fun part1(input: List<String>) = day4(input, true)
fun part2(input: List<String>) = day4(input, false)
val input = readInput("Day04")
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | e9b98fc0eda739048e68f4e5472068d76ee50e89 | 1,333 | aoc22 | Apache License 2.0 |
src/main/kotlin/days/Day05.kt | Kebaan | 573,069,009 | false | null | package days
import utils.Day
import utils.splitBy
import java.util.*
import kotlin.collections.ArrayDeque
import kotlin.collections.component1
import kotlin.collections.component2
typealias Crate = Char
fun main() {
Day05.solve()
}
object Day05 : Day<String>(2022, 5) {
data class Move(val amount: Int, val from: Int, val to: Int)
private val MOVE_REGEX = """move (\d+) from (\d+) to (\d+)""".toRegex()
private fun parseInput(input: List<String>): Pair<TreeMap<Int, ArrayDeque<Crate>>, List<Move>> {
val (layerDescription, moveDescriptions) = input.splitBy { it.isEmpty() }
val stacks = TreeMap<Int, ArrayDeque<Crate>>()
layerDescription.forEach { layer ->
layer.forEachIndexed { index, spot ->
if (spot.isLetter()) {
val stackId = (index / 4 + 1)
stacks.getOrPut(stackId) { ArrayDeque() }.addFirst(spot)
}
}
}
val moves = moveDescriptions.map {
val (amount, from, to) = MOVE_REGEX.find(it)!!.destructured
Move(amount.toInt(), from.toInt(), to.toInt())
}
return stacks to moves
}
override fun part1(input: List<String>): String {
val (crateStacks, moves) = parseInput(input)
moves.forEach { move ->
repeat(move.amount) {
val crateToMove = crateStacks[move.from]!!.removeLast()
crateStacks[move.to]!!.addLast(crateToMove)
}
}
return crateStacks.extractTopCrates()
}
override fun part2(input: List<String>): String {
val (crateStacks, moves) = parseInput(input)
moves.forEach { move ->
val buffer = ArrayDeque<Crate>()
repeat(move.amount) {
val crateToMove = crateStacks[move.from]!!.removeLast()
buffer.addFirst(crateToMove)
}
crateStacks[move.to]!!.addAll(buffer)
}
return crateStacks.extractTopCrates()
}
private fun TreeMap<Int, ArrayDeque<Crate>>.extractTopCrates(): String {
return this.map { (_, stack) ->
stack.last()
}.joinToString("")
}
override fun doSolve() {
part1(input).let {
println(it)
check(it == "TBVFVDZPN")
}
part2(input).let {
println(it)
check(it == "VLCWHTDSZ")
}
}
override val testInput = """
[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""".trimIndent().lines()
}
| 0 | Kotlin | 0 | 0 | ef8bba36fedbcc93698f3335fbb5a69074b40da2 | 2,771 | Advent-of-Code-2022 | Apache License 2.0 |
dcp_kotlin/src/main/kotlin/dcp/day297/day297.kt | sraaphorst | 182,330,159 | false | {"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315} | package dcp.day297
// day297.kt
// By <NAME>, 2020.
private typealias Drink = Int
/**
* This is just a specific instance of a set covering problem in disguise.
* We want to cover the customers with the fewest number of drinks.
* We use the power set and iterate by size to find a minimal set of drinks required to satisfy all customers.
*/
/**
* Whittle down to nothing by repeatedly calling drop(1).powerset.
* Then add the current sets built up followed by the first element that we had dropped
*
* [] - whittled down to nothing
*
* - [] + [[]].map(_ + first()), where first is now the last element dropped, i.e. 3.
* [3]
*
* - [[],[3]] + [[],[3]]].map(_ + first()), where first is now the second-last element dropped, i.e. 2.
* [], [3] filtered out
* [2]
* [3, 2]
*
* - [[2],[3,2]]] + [[2],[3,2]].map(_ + first()), where first is now the third-last element ignored, i.e. 1
* [], [3], [2], [3,2] filtered out
* [1]
* [3, 1]
* [2, 1]
* [3, 2, 1]
*
* etc.
* [0]
* [3, 0]
* [2, 0]
* [3, 2, 0]
* [1, 0]
* [3, 1, 0]
* [2, 1, 0]
* [3, 2, 1, 0]
*/
private fun <T> Collection<T>.powerset(): Set<Set<T>> = when {
isEmpty() -> setOf(setOf())
else -> drop(1).powerset().let { setOfSets -> setOfSets + setOfSets.map { set -> set + first() } }
}
fun drinksToMemorize(customerPreferences: List<Set<Drink>>): Set<Drink>? {
// Get an entire list of the drinks.
val drinks = customerPreferences.flatten()
// Determine if a set of drinks satisfies all the customers.
fun satisfy(drinkSet: Set<Drink>): Boolean =
customerPreferences.all { preferences -> preferences.any { it in drinkSet } }
// Sort the power set by size to obtain a minimum set of drinks that the bartender should know.
return drinks.powerset().sortedBy { it.size }.find { satisfy(it) }
}
| 0 | C++ | 1 | 0 | 5981e97106376186241f0fad81ee0e3a9b0270b5 | 1,832 | daily-coding-problem | MIT License |
src/main/kotlin/dp/FindS.kt | yx-z | 106,589,674 | false | null | package dp
import util.*
// given X[1..k] and Y[1..n] : k <= n
// 1. determine if X is a subsequence of Y
// ex. PPAP is a subsequence of PenPineappleApplePie
infix fun IntArray.isSubsequenceOf(Y: IntArray): Boolean {
val X = this
val k = X.size
val n = Y.size
// isSub(i, j): whether X[1..i] is a subsequence of Y[1..j]
// memoization structure: 2d array dp[0..k, 0..n] : dp[i, j] = isSub(i, j)
val dp = Array(k + 1) { Array(n + 1) { false } }
// space complexity: O(k * n)
// base case:
// isSub(i, j) = true if i = 0 and j in 0..n
// = false if i > j >= 0 || i !in 0..k || j !in 0..n
for (j in 0..n) {
dp[0, j] = true
}
// recursive case:
// isSub(i, j) = isSub(i - 1, j - 1) if X[i] = Y[j]
// = isSub(i, j - 1) o/w
// dependency: isSub(i, j) depends on isSub(i, j - 1) and isSub(i - 1, j - 1)
// that is, entries to the left and to the upper-left
// evaluation order: outer loop for i from 1 to k (top down)
for (i in 1..k) {
// inner loop for j from 1 to n (left to right)
for (j in 1..n) {
dp[i, j] = if (X[i - 1] == Y[j - 1]) {
dp[i - 1, j - 1]
} else {
dp[i, j - 1]
}
}
}
// time complexity: O(k * n)
// we want isSub(k, n)
return dp[k, n]
}
// O(n) non-DP solution
infix fun IntArray.isSubseqOf(Y: IntArray): Boolean {
val X = this
val k = X.size
val n = Y.size
var i = 0
var j = 0
while (i < k && j < n) {
if (X[i] == Y[j]) {
i++
}
j++
}
return i == k
}
// 2. determine the minimum number of elements in Y : after removing those elements
// , X is no longer a subsequence of Y
// , you can also find the longest subsequence of Y that is not a supersequence of X
// let me find the length of such subsequence = l
// and we can know the minimum number of elements to be removed as n - l
fun OneArray<Int>.subseqNotSuperseq(X: OneArray<Int>): Int {
val Y = this
val k = X.size
val n = Y.size
// dp[i, j] = (len of longest subseq of Y[1..j] that only contains X[0..i] in the order but not X[i + 1 until k],
// last idx of subseq X[0..i])
// 2d array dp[0..k, 0..n] taking space O(kn)
// base case:
// when i = 0, every element is followed by an empty element
// so we keep updating the last index of seeing the empty element
val dp = Array(k + 1) { Array(n + 1) { 0 to it } }
// we want max_i{ dp[i, n]_1 }
var max = 0
for (i in 1..k) {
for (j in 1..n) {
dp[i, j] = if (Y[j] == X[i]) {
max(j - dp[i - 1, j - 1].second - 1, dp[i, j - 1].first) to j
} else {
1 + dp[i, j - 1].first to dp[i, j - 1].second
}
if (j == n) {
max = max(max, dp[i, n].first)
}
}
}
// time complexity: O(kn)
// dp.prettyPrintln(true)
return max
}
// 3. determine whether X occurs as two disjoint subsequence of Y
// ex. PPAP appears as two disjoint subsequences is [P]en[P]in[A](P)(P)le(A)[P](P)LEPIE
infix fun OneArray<Int>.occurAs2DisjointSubseq(Y: OneArray<Int>): Boolean {
val X = this
val k = size
val n = Y.size
// dp(i, j, l): idx of the last elements of 2 disjoint X[1..i] in Y[1..j] and Y[2..l]
// ex. dp(i, j, l) = (a, b) if Y[a] = Y[b] = X[i] and there are two disjoint subsequences
// Y[1..a] and Y[2..b] that equals X[1..i]
// a <= j, b <= l, 1 <= j < l <= n
// = [] o/w
val dp = OneArray<OneArray<OneArray<HashSet<Pair<Int, Int>>>>>(k)
for (i in 1..k) {
dp[i] = OneArray(n - 1)
for (j in 1 until n) {
dp[i][j] = OneArray(n)
for (l in 1..n) {
dp[i][j][l] = HashSet(0)
}
}
}
for (i in 1..k) {
for (j in 1 until n) {
for (l in j + 1..n) {
if (X[i] == Y[j] && Y[j] == Y[l]) {
if (i == 1 || dp[max(1, -1)][max(1, j - 1)][max(1, l - 1)].isNotEmpty()) {
dp[i][j][l].add(j to l)
}
} else {
dp[i][j][l].addAll(dp[i][max(1, j - 1)][max(1, l - 1)])
dp[i][j][l].addAll(dp[i][max(1, j - 1)][l])
dp[i][j][l].addAll(dp[i][j][max(1, l - 1)])
}
}
}
}
// for (i in 1..k) {
// for (j in 1 until n) {
// dp[i][j].prettyPrintln()
// }
// println()
// }
return dp[k][n - 1][n].isNotEmpty()
}
// 4. weighed subseq
// given X[1..k], Y[1..n], and C[1..n] as the cost of Y
fun OneArray<Int>.minWeighedSubseq(Y: OneArray<Int>, C: OneArray<Int>): Int {
val X = this
val k = X.size
val n = Y.size
// dp(i, j): minimum cost of a subseq in Y[1..j] that ends in Y[j] and equals to X[1..i]
// memoization structure: dp[1..k, 1..n] : dp[i, j] = dp(i, j)
val dp = OneArray<OneArray<Int>>(k)
// space complexity: O(k * n)
// we want min_j { dp(k, j) }
var min = Int.MAX_VALUE / 2
// base case:
// dp(i, j) = 0 if i !in 1..k or j !in 1..n
for (i in 1..k) {
dp[i] = OneArray(n)
for (j in 1..n) {
// assume +inf = Int.MAX_VALUE / 2 (so as to avoid overflow)
dp[i, j] = Int.MAX_VALUE / 2
}
}
// recursive case:
// assume util.min{ } = +inf
// dp(i, j) = min_l{ dp(i - 1, l) : l < j } + C[j] if X[i] = Y[j]
// = +inf o/w
// dependency: dp(i, j) depends on entries on the row above and to the left
// evaluation order: outer loop for i from 1 to k (top down)
for (i in 1..k) {
// inner loop for j from 1 to n (left to right)
for (j in 1..n) {
if (X[i] == Y[j]) {
dp[i, j] = if (i == 1) {
C[j]
} else {
(1 until j).map { dp[i - 1, it] + C[j] }.min()
?: (Int.MAX_VALUE / 2)
}
}
if (i == k) {
min = min(min, dp[i, j])
}
}
}
// time complexity: O(k * n)
// dp.prettyPrintTable(true)
return min
}
fun main(args: Array<String>) {
val test1X = intArrayOf(3, 5, 1, 2, 6)
val test1Ys = arrayOf(
intArrayOf(3, 5, 1, 2, 6), // true
intArrayOf(3, 5, 2, 1, 1, 2, 6), // true
intArrayOf(3, 5, 1, 6, 2, 2) // false
)
// test1Ys.forEach { println(test1X isSubsequenceOf it) }
// test1Ys.forEach { println(test1X isSubseqOf it) }
val test2X = "PPAP".toAlpha().toOneArray()
val test2Y = ("PEN" + "PINEAPPLE" + "APPLEPIE").toAlpha().toOneArray()
// println(test2Y.size - test2Y.subseqNotSuperseq(test2X))
// println(test2X occurAs2DisjointSubseq test2Y)
val test3X = arrayOf(1, 2, 3).toOneArray()
val test3Y = arrayOf(1, 2, 2, 1, 2, 3, 4, 2, 3).toOneArray()
// println(test3X occurAs2DisjointSubseq test3Y)
val test4X = oneArrayOf(1, 2)
val test4Y = oneArrayOf(1, 2, 3, 1, 1, 2)
val test4C = oneArrayOf(-10, 20, 0, 10, 20, 25)
println(test4X.minWeighedSubseq(test4Y, test4C))
}
fun String.toAlpha() = map { it - 'A' + 1 }.toIntArray()
| 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 6,428 | AlgoKt | MIT License |
src/Day08.kt | eo | 574,058,285 | false | {"Kotlin": 45178} | // https://adventofcode.com/2022/day/8
fun main() {
fun parseInput(input: List<String>): Array<IntArray> =
input.map { it.chunked(1).map(String::toInt).toIntArray() }.toTypedArray()
fun part1(input: List<String>): Int {
val grid = parseInput(input)
val leftMaxGrid = Grid(grid.rowCount, grid.colCount)
for (row in 0 until grid.rowCount) {
for (col in 0 until grid.colCount) {
leftMaxGrid[row, col] = if (col == 0) {
Int.MIN_VALUE
} else {
maxOf(leftMaxGrid[row, col - 1], grid[row, col - 1])
}
}
}
val rightMaxGrid = Grid(grid.rowCount, grid.colCount)
for (row in grid.rowCount - 1 downTo 0) {
for (col in grid.colCount - 1 downTo 0) {
rightMaxGrid[row, col] = if (col == grid.colCount - 1) {
Int.MIN_VALUE
} else {
maxOf(rightMaxGrid[row, col + 1], grid[row, col + 1])
}
}
}
val topMaxGrid = Grid(grid.rowCount, grid.colCount)
for (row in 0 until grid.rowCount) {
for (col in 0 until grid.colCount) {
topMaxGrid[row, col] = if (row == 0) {
Int.MIN_VALUE
} else {
maxOf(topMaxGrid[row - 1, col], grid[row - 1, col])
}
}
}
val bottomMaxGrid = Grid(grid.rowCount, grid.colCount)
for (row in grid.rowCount - 1 downTo 0) {
for (col in grid.colCount - 1 downTo 0) {
bottomMaxGrid[row, col] = if (row == grid.rowCount - 1) {
Int.MIN_VALUE
} else {
maxOf(bottomMaxGrid[row + 1, col], grid[row + 1, col])
}
}
}
return grid.count { row, col, treeHeight ->
treeHeight > leftMaxGrid[row, col] ||
treeHeight > rightMaxGrid[row, col] ||
treeHeight > topMaxGrid[row, col] ||
treeHeight > bottomMaxGrid[row, col]
}
}
fun scenicScore(grid: Grid, row: Int, col: Int): Int {
val treeHeight = grid[row, col]
var leftTrees = 0
for (c in col - 1 downTo 0) {
leftTrees++
if (grid[row, c] >= treeHeight) break
}
var rightTrees = 0
for (c in col + 1 until grid.colCount) {
rightTrees++
if (grid[row, c] >= treeHeight) break
}
var topTrees = 0
for (r in row - 1 downTo 0) {
topTrees++
if (grid[r, col] >= treeHeight) break
}
var bottomTrees = 0
for (r in row + 1 until grid.rowCount) {
bottomTrees++
if (grid[r, col] >= treeHeight) break
}
return leftTrees * rightTrees * topTrees * bottomTrees
}
fun part2(input: List<String>): Int {
val grid = parseInput(input)
var maxScenicScore = 0
for (row in 0 until grid.rowCount) {
for (col in 0 until grid.colCount) {
maxScenicScore = maxOf(
maxScenicScore,
scenicScore(grid, row, col)
)
}
}
return maxScenicScore
}
val input = readLines("Input08")
println("Part 1: " + part1(input))
println("Part 2: " + part2(input))
}
private typealias Grid = Array<IntArray>
private fun Grid(rowCount: Int, colCount: Int) = Array(rowCount) { IntArray(colCount) }
private val Grid.rowCount: Int get() = size
private val Grid.colCount: Int get() = first().size
private operator fun Grid.get(row: Int, col: Int): Int = this[row][col]
private operator fun Grid.set(row: Int, col: Int, value: Int){
this[row][col] = value
}
private fun Grid.count(predicate: (Int, Int, Int) -> Boolean) =
foldIndexed(0) { row, totalCount, rowValues ->
rowValues.foldIndexed(totalCount) { col, count, cellValue ->
count + if (predicate(row, col, cellValue)) 1 else 0
}
} | 0 | Kotlin | 0 | 0 | 8661e4c380b45c19e6ecd590d657c9c396f72a05 | 4,179 | aoc-2022-in-kotlin | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.