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/day24/Day24.kt | TheSench | 572,930,570 | false | {"Kotlin": 128505} | package day24
import runDay
import utils.Point
import java.lang.RuntimeException
fun main() {
fun part1(input: List<String>) = input.parse().let { (bounds, blizzards) ->
solve(bounds, blizzards, listOf(bounds.end))
}
fun part2(input: List<String>) = input.parse().let { (bounds, blizzards) ->
solve(bounds, blizzards, listOf(bounds.end, bounds.start, bounds.end))
}
(object {}).runDay(
part1 = ::part1,
part1Check = 18,
part2 = ::part2,
part2Check = 54,
)
}
fun solve(bounds: Bounds, blizzards: List<Blizzard>, goals: List<Point>): Int {
val startingStep = Step(bounds.start, 0)
var positions = listOf(startingStep)
var currentBlizzards = blizzards
val lcm = lcm(bounds.width, bounds.height)
val seen = mutableSetOf(0 to startingStep)
repeat(Int.MAX_VALUE) { turn ->
currentBlizzards = currentBlizzards.move(bounds)
val blizzardLocations = currentBlizzards.map { it.location }.toSet()
positions = positions.flatMap { (location, goal) ->
var targetGoal = goal
if (location == goals[targetGoal]) {
targetGoal++
if (targetGoal == goals.size) {
return turn + 1
}
}
location.getMoves().filter {
it in bounds && location !in blizzardLocations
}.map {
Step(it, targetGoal)
}.filter {
(turn % lcm) to it !in seen
}.onEach {
seen.add((turn % lcm) to it)
}
}.ifEmpty { throw RuntimeException("Got stuck") }
}
return Int.MAX_VALUE
}
data class Step(val location: Point, val goal: Int)
fun debug(turn: Int, bounds: Bounds, allBlizzards: List<Blizzard>) {
val blizzardLocations = allBlizzards.groupBy { it.location }
val map = (0..bounds.height).map { y ->
(0..bounds.width).map { x ->
val point = Point(x, y)
when {
x == 0 || y == 0 || x == bounds.width || y == bounds.height -> '#'
point in blizzardLocations -> {
val blizzards = blizzardLocations[point]!!
when (blizzards.size) {
1 -> blizzards[0].toString()
in (2..9) -> blizzards.size
else -> '@'
}
}
else -> ' '
}
}.joinToString("")
}.joinToString("\n")
println("After turn ${turn + 1}")
println(map)
println()
}
operator fun Bounds.contains(point: Point) =
(point.x in (1 until width) && point.y in (1 until height))
|| point == start
|| point == end
fun Point.getMoves() = listOf(
copy(x = x + 1),
copy(x = x - 1),
copy(y = y + 1),
copy(y = y - 1),
this,
)
fun List<String>.parse() = getBoundaries() to toBlizzards()
fun List<String>.getBoundaries() = Bounds(
width = this[0].length - 1,
height = this.size - 1,
)
fun List<String>.toBlizzards() = flatMapIndexed { y, row ->
row.mapIndexedNotNull { x, char ->
when (char) {
'^' -> Blizzard.up(x, y)
'v' -> Blizzard.down(x, y)
'<' -> Blizzard.left(x, y)
'>' -> Blizzard.right(x, y)
'#', '.' -> null
else -> throw IllegalArgumentException("$char")
}
}
}
data class Bounds(val width: Int, val height: Int) {
val start = Point(1, 0)
val end = Point(width - 1, height)
}
data class Blizzard(val location: Point, val velocity: Point) {
val x get() = location.x
val y get() = location.y
fun move() = copy(location = location + velocity)
override fun toString(): String = when {
velocity.x > 0 -> ">"
velocity.x < 0 -> "<"
velocity.y > 0 -> "v"
velocity.y < 0 -> "^"
else -> "A"
}
companion object {
fun up(x: Int, y: Int) = Blizzard(Point(x, y), Point(0, -1))
fun down(x: Int, y: Int) = Blizzard(Point(x, y), Point(0, 1))
fun left(x: Int, y: Int) = Blizzard(Point(x, y), Point(-1, 0))
fun right(x: Int, y: Int) = Blizzard(Point(x, y), Point(1, 0))
}
}
fun List<Blizzard>.move(bounds: Bounds) = map { it.move() }.map {
when {
it.x == 0 -> it.run { copy(location = Point(bounds.width - 1, y)) }
it.y == 0 -> it.run { copy(location = Point(x, bounds.height - 1)) }
it.x == bounds.width -> it.run { copy(location = Point(1, y)) }
it.y == bounds.height -> it.run { copy(location = Point(x, 1)) }
else -> it
}
}
private fun gcd(a: Int, b: Int): Int {
var a = a
var b = b
while (b > 0) {
val temp = b
b = a % b // % is remainder
a = temp
}
return a
}
private fun lcm(a: Int, b: Int): Int = a * (b / gcd(a, b))
| 0 | Kotlin | 0 | 0 | c3e421d75bc2cd7a4f55979fdfd317f08f6be4eb | 4,901 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/1.kt | torland-klev | 730,585,319 | false | {"Kotlin": 74157} | package klev
object `1` : Day {
override fun firstSolution(input: List<String>) =
input.sumOf { line ->
line.filter {
c ->
c.isDigit()
}.let { number -> "${number.first()}${number.last()}" }.toInt()
}.toString()
override fun secondSolution(input: List<String>) =
input.sumOf { line ->
line.replace("one", "one1one")
.replace("two", "two2two")
.replace("three", "three3three")
.replace("four", "four4four")
.replace("five", "five5five")
.replace("six", "six6six")
.replace("seven", "seven7seven")
.replace("eight", "eight8eight")
.replace("nine", "nine9nine")
.filter {
c ->
c.isDigit()
}.let { number -> "${number.first()}${number.last()}" }.toInt()
}.toString()
/**
* I gave this a solid attempt, but I cannot seem to find the missing case.
* If you can find a test that defeats this, please let me know.
*/
fun secondSolutionIncomplete(input: List<String>) =
input.sumOf { line ->
replaceAllTextWithNumber(line).filter {
c ->
c.isDigit()
}.let { number -> "${number.first()}${number.last()}" }.toInt()
}.toString()
private fun replaceAllTextWithNumber(
text: String,
substringStart: Int = 0,
substringEnd: Int = 2,
): String {
val shortestWordInList = itemsToFind.minOfOrNull { it.length } ?: 1
val longestWordInList = itemsToFind.maxOfOrNull { it.length } ?: 1
return if (longestWordInList < substringEnd - substringStart || text.length < substringEnd && substringStart - shortestWordInList <= text.length) {
val newStartIndex = substringStart + 1
replaceAllTextWithNumber(text, newStartIndex, newStartIndex + shortestWordInList)
} else if (text.length >= substringEnd && text.filterNot { it.isDigit() }.length > shortestWordInList) {
val preDigits = text.substring(0, substringStart).filter { it.isDigit() }
val currentText = text.substring(substringStart, substringEnd)
val remainderText = text.substring(substringStart + 1)
val match = currentText.findMatch()
if (match != null) {
replaceAllTextWithNumber(preDigits + match + remainderText, substringStart = 1, substringEnd = 1 + shortestWordInList)
} else {
replaceAllTextWithNumber(text, substringStart, substringEnd + 1)
}
} else {
text
}
}
private fun String.findMatch() =
when (this) {
"one" -> "1"
"two" -> "2"
"three" -> "3"
"four" -> "4"
"five" -> "5"
"six" -> "6"
"seven" -> "7"
"eight" -> "8"
"nine" -> "9"
else -> null
}
private fun String.replaceDigitStringWithDigitInt() =
this
.replace("one", "1")
.replace("two", "2")
.replace("three", "3")
.replace("four", "4")
.replace("five", "5")
.replace("six", "6")
.replace("seven", "7")
.replace("eight", "8")
.replace("nine", "9")
private val itemsToFind = listOf("one", "two", "three", "four", "five", "six", "seven", "eight", "nine")
private fun smallInput() =
"""pfnv2
eightwo
eighthree
sevenine
pfnv2
two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen"""
override fun input() =
"""threehqv2
sxoneightoneckk9ldctxxnffqnzmjqvj
1hggcqcstgpmg26lzxtltcgg
nrhoneightkmrjkd7fivesixklvvfnmhsldrc
zhlzhrkljonephkgdzsnlglmxvprlh6n
594chhplnzsxktjmkfpninefiveczfnvsctbxcfzfzjh
seven2tjf
five712
tzheightzlzmsqlnxfqzrlbhbdpbnbdjns6
ztwo1eight95
one25eightzptqnvvlnf
46brthree51bhvhtcnpcffoursix
five7bhsfdktxq33qtrmvqxfgone3
4f6six1skrmltxeight
onemhfbhrx99
five3eightjkdpxqtmbtwo
onebzp4seven4ft
5sxgjszzninembrtjptlfn24llbxrnm
sixninefivejpqgkcx3sixnine15
fourcmsndtdkrone75
68hnrkxbmvjzjzfk
2oneseventhreesixrbkkbhlx
five6npfmggbdkljqsixjnxgk1cqdmcneight
6eightfiveksmrbjgc
eight8zqjsixfivefrrbg4
2sixfhbnqbjv3krgqgfj
one56vhgnlxfjhrc6
8twothreelgbmx31
kfkjfckbhnv8threedpxhhfivepkcnfjmcpt
onenxqtvzvzph8nmtjgsjkone4btzxpkjfbthhsmqcqz
mdbsvbf8zbllzcsixclrjnfzf
knptlbzlffourfivetjzjpleightsix31
one6pbdfdtsqhjhqfourqqvkvksm
nxd3dkj1threeeightqxlfndjtglnxlqmb9
5three37tfnkz
57eight9fivefiveeight
2zd155
3lljdglhbfiveeight92
44lseven6
9xlv5gqgvpjvrhbbcrnmq2pt5
fiveeightslvzrvvgfsrvnsnhk1
twotsffgflt1two9four24three
2fourstszszgmxfive6fourzx
nine8bgh921seven
threevbvcrmqfivesix6fivenrxd22
zmdhdgfrr4przvs1
jpxt9
five6fivethree2three
qmz45cbtvx535
7eighttfbrsmvtpnsjcjpsjxcnine67two
nllgnjsdlkkng6ninesixjpjlmjg
two6615sixg2
7onetwoninemhjlqmlkkt
fourfffqcsmxc5nsixpncjnvpm5
rbbmltgpsixfive8nine4sevenfour
vfzmncfonexxkzlcstqhxvtwoplsglsix1kpkssfz
twojsrsixone39eight
three5nine
fcgx5pvnsxnhfd
9krnchzvnv8one
ninetwo1
eightrtvgkfjn1tfgxqeightseventwo
255five9
bxkg53
5vdr8
threetwomxbgqhzdq3
6dlg51p3
q53
8seven6594five
sixeightnpdsfdjljtwofiveqm7two2
qxsrbthree24four2
jbzeighteightpksq1twokcsvsr8
7kmmkdcmbl
twonvfhlseven7qksvksixqfz
8hbffjsbckqcscsevenbztnmvvg
one5kntjln21
2sevenlt7threesix49jkdtqqr
6drqlvfour1nine
6zmk8n
one279seven
65eightssvjkchfhrpdhlmrbrsevenkrpt7
dj87
sixsevendxvjjseight4two3tpvbcbf
4eightzz8three5
95gsfb5sevennhgmdc
plpn2threesix
seven22
8eightqqcgzd6ldh
4sixvsmhtlfcmbnmzgnsixfour
kmncbxcgmxmt1nine
4kb6one
threefivefivefourfive9npqtvvr3
cjkpsc5ninepkcqpvnkzcr
glzvgvpjvhsixbgdvzfive97mdbxtlvz7srhtpsfk
8three9dnzfgjzmzhh5seven
sevenfkqpshm6mx
9onedbvnnmfl15
sstcrnkkbzfsfcnkone8
xtqzchjspfdtsoneninethree4sixffsix
584ptgjtlqktk
kknpxzc26
pghjgrxh4135ttxr
2pjgp8one49
five3qjqsdstkq5ninevfzjgkpxphone82
fllgbdnbsztbfnjmhone7five
cgpqqcbfksnvppdqqsgh7twotzqglbvptmfive
2three6twozchrbnjsxdqtmfppzmr34
89kfjsix
3mpk7
3threekcgjfkk425
39zxtkntmxt
13ninevvrsxn436fivethree
nine5dphhllslr8nktvcd
7fourfourfivevbnlgzgxnpt
2hjvmsxfmfxtlljnqzr
6onepjqmjlsvfourfour2three
5kzsfrfmflp7twoqb4two3
three186threeone2
8four5hnineppprpkjhf
1qvtx1843
qblf36xsrdsvqhrmlrbthree
326sevenfivenseven1kctgmnqtwonefq
41sixfour
three4sevenone
4sevenptjmqgffivesix71pgpfcmc
14mndmdlsjhtprtxtskmdfive
6lrjglxqksevenkvsp5six37three
ljzfourjcclgcdgqcdnbhk9mrtnfrtwo
389six37threervldzxvlgr
2rtjhvsvrmtwo1hgzpeightdjkhxhmseven7
seven38fivepknvlmrjgbms7
27eightlccjptfm5rdthree4
cqpnjv58
2mbvkpzvfccrns8one52
three4seven7two
dfptdxdj8flxhqvfg8zljld
dm71two1hnggncbqkxsfkmq7
8blsrrqrjlckv7xszllqddzn5oneightfg
5fivej
fvx97jjfc63qbkpnqqqzbfmj
tgnzdkgfoureight9
37kc
1shthsfsdfmkmgxh2
6fdldj
sevenv79spttnzrrbvpmcf
ghpxgf3xk1zddlhfdnzthxmqqmzdpf
9f7ninethreeone
288vxrjxkjr78lsgbcssfdtsix
6vkckltsqvhsgvhtonezmrdfvn4
12bhseven6
three8bxfndbnine
4three14one
qs9twotkqgxthree
kbtwonesix2eight194four
nxjseven7
threejpzxfiveninet9fivetkxgzxd3
8fjjbghh9
nine8fourfourthreempcldmm
six24qkjpkqlrrqfiveninejnjbdld
zhsztjsgthreeeightone831
9threegpgtdm
8mnl31two7oneseven
gxdltwoonelzvbctwo91fourthree
lmgfive8
41six13kcvdsix
qsix9qlzjxfive8ninengxncsdpck
twoqmzfsrdq7
vqsgtzqmvslp1vnnjzvkjggn9fiveninesix
blrrckhs7tfpnssnpk76vkdsthree
znoneight925cnqsm79lplfpmzzh
twozqv3fourtwo
mscksglc3ql
fxf3four8dfmncxqseven
pdrfptqj3ndpmfiveonecz436
mtzzzjz23zhcbg1
74tflvhzjhvfivefour5bjhhkfvrfm7three
3246three
zzzzxptgsevenfoureight3sevenpq89
35sevenzgpptx8trrhb7seven8
onegfshppnb3vpvsbcvsg2qndxmpm
6ntfjnvdrmrzhdhgljq
eightlnmdkqb1
sevenseven2three
pjxvzpdtfcnine9five
sevenseven7
9rhdtwoninemclzzqhztxhljmjssevenfive3
6eightsthxqvfzgrlffsix7qxxdktsbseven
nine938zrsrhn3
two1fourthreetwotkvktvsspzfbfhrch27
29one7672
8zcdxmbfrhj3bqncflspd
bnplfntoneninesix6one
8one2six3one3nseven
seven31
kcfsnqz52nnkxrblnsndpqqjonesix97
825seventbpqbx
8348
4dreight53rmcjrrtpcmcslbkbvphvnp3
eightb3pvjcczsdkghdkvjkxfpjxkgqjqgkdd5
sp3onejffrxblxck5one4vbvseven
lpsrh6five3twovvthree6
skhpb21zptmbvccrfcs9eight
pqfphhcgxz8eightwohv
ftbmkdgtkvvbjgpclnhrlxphgrph52five
two7xkccqlcdcftzmnine6sgtt
bbdcstgccbfivefivesix7
xgzvtqbjngzk7sevenvmllqm4rldvmdvmtwotwo
one5four3eight2five6
cnfcdcv6onetwoseven24one9
cpgthkmbqd171ninedonetwosxvt
onemrrzcszddxcqvfive72drksvfcbpmseven
twothreetwo1
nmsrdffmhrjjhksix54five9eight
ftmjgrhlqxnine8two2ninefive8bxlhqv
twokjp3nine
6mzrgjbf51onefourthree
threenine89zlmh9fourff
threefourfivej6ptg
864dvsfvcvhtrqzgspsbvgvvmpgjsppsvsbxrr5
2sixzcnqbsixvcqnvnd
92lthree2
2onegmhhnljgrf9
847one3
sixeightseven2gbvgmmmlgbmkxdnkkfqj
bhxdczcbpfmhjprbrqqcfcdpeight1fbbtgnc9
two1npqxpbrhlrfourccsfrjggltslqlhjqthreezbc8
dgzm48
svhdzdtrctppcb6flhpvvnpsk3
s8fourrkrlhjsnsrddhrsxzseven
m4
8rctpll4ninefds64jxl2
two9seven36
vzrmfgtmjsixfourone4fourfrnr
7sixpzbdmvfddfhqspkninepxrcltthree4mjbh
6233q32
gzpmvphfl5six27one4eight
lclqftpzgqqbls83nine9seven
fzztdjhsixnine91
9five3
51seven2k
nine6vcssmvvld4fourff6
bjrplzdf9seveneight1
82rzzlqbr8ninesmfour39
kzgcnine24
815nine6mzjpkvfhdp5
84mclnine5
phhclzqllq581vhrsk7sixeight
8vccclqxdskgvgqoneseven
szm748dqvcxlbrqbzbdnqtqsnrcpcsqtgk6
686135
fzlvnbnfctseven6eighteightxkcstfv7qjsxpfxtfzpbcsm
vmsxmcmffourfour1
lbthreednlvv16fourxzhsix
eightfjtpfffour4eight9nine
8ksonefivefour
3sevenbcsfour52
7fourzflkvskjrcxxbdfz4nkjjbgnfour5three
nine9xnbjnnine2
onejzxkqt83twoxgltxrmztlfh5
jtkqjfourthreefour2seven897
8eightvvjdmfourgfmthreedgq5
89two79twokxfdsk
onesevenfour7gflgnsmpkjmlvntxhhqtqtwo2
three71eight3qq62xmkzfq
3mvn86
9mgsz
36ninehv62
vdtf7fxjgjz
sevenxlzdftxv87fourtwo
fivejgzhpfkths6four
52fourfour7sxzptgtnhsfour82
ddeightwohxxcninelzptfbxczrkhmxnvt2249mn
xlnbvzsxjfive94ninemsb3qvkvqk8
kfbvvpdxrrx1threecqhqxlqnts
two7nine
2jf
six71lzjldpjqssxhljslsrthreefour
5cqcdtpsqbplkdtbtbsevenseven1two
2threeseven
1zthreenblctql9nine5
eightmfive714foursix3
1hfbdtwo
3czdksdsjkvcstltsbjfour2
7four6
63pggqnfg9flspklblvxlg
oneeightnxdfsjgkbvxonetwonine2
674tdqqklvthreepnlschj39
jk5ninerpfdlfmpfmczg3
qggjm3pkbskbshjbztvzxllq8six8
plftsevenxxmfourone15
seven6eightsix86onenine
2spngskr19nine1sevensevenksz
bjqbjmcrbjdfnnnhmhsmdmdksevenninermlfive3
lfxj63three
qsnvrckf4mjnoneightlgt
tfqqh3ninegbcdnine8hv6xl
41fczmhgsixtwo
4qmnxhnhppjhptstwothreecmxxhhfflxpxb
ninejbjonexkfcm13
tgvkft8htone7
99dqllhxc
five7mxnhb216zkjmmnjmqrplgpg
76gfcvlzclzcnthdkkk532frtlllmsxbv
6bzrvlgdbkqktzjsdsjgqmfkzdckeightcsjsrrpcl
qnlk4sixlfqlm8
1sfxdrmonectrgngdnmbfglpr
2974rbfourfour2
98nine8three1qjftl4
1ninelqqnpfivefour8xgzbt
eighttwo1one
1threepxdnmpmtt
qqfcvv5zsgcpdgh
3ninegcnrtwotljnbkkftfourthreefour
vc1nhcmvvqsix6two
kmpfbntsix6jdgt8bdvbfptsbkjbbvnsbrjzzhqr
three3fourlxnn4
8ninetwofour2zxgrbhjxpgbjgtpn76
six8six
qsrxjhjrk5
eight7sxmmmghzpmclkcbqkxvkdfnrnmqhhkkt
nzrgxcfl9
4sixtwo2five
sevenrpbckzzxhcfour48two
pbmlptjqgcxcbpslkggvqgzdpqlvztwofour9ksmzpmshcctwo
811sqcbjrnpxbgv
one6bbml7dbmpfivepgrn
hmfive48onevbfxrlnck4gnb1
2threegklleightworcg
zoneightphzl6lksqsxklcqthreeeighttwonsnnrtqx
5crfbgsevensixdfour92
5eight122
six3gcjlxrr
1vbzx2onenvplbkmcfzmmbbqrone
oneninebctxhv78
6xpcdqcnxq
sixlhkqjgmlvcbjph6threetrlpnkg
nsxvf31ffqlx5four7tpnzqvllkn
onesix4dgskfddrfivefourtrzzxfjg
bprxxzdd1
three45shjhqtthreekmvx
sevenjpmjthreefive8eight9txtltqjm
zbqsnhfnkcccseven5vfiveonexvlfbkzbd
6kprj6eight4jhgdgcbcfg3lcfbgfsdkg
fourtwo217ljzlsevenznbmgd
jxpszskeight5rfourone2lxphhpone
five4zj5pz5qfoursix
vncrqcsix3fourxsnf7
636qbxtkzroneighttpv
1oneightgqx
two2fouronehcq
vbsmfthreethree7mhfsgnf
nklpxknvbbrjbmxtxplkldvspspvlq5tpbsxklqmndmxxn7
3four2684
3sixonethreegbjzfour2mmrk4
jzzrkn5five
ninesixsk1kphntgbmzlctjtzdmgzk
fourvjhkzqlqfour6c1
38xxrrgdrgxrninefive91
15seven8
nine4one5onenineone7
5mfknkone4cphtbrtj1eightwon
vgeightlvvxlkqzzgtg368nlmmhdmmqf
8threeeight29jhhqjpnbbp66mlb
mzzm4
sevenfive44xvxlrxzfk
82seven1twozdbpks143
eightckfbqfgz9gzkxqmzjkhsix7eight
tzl184two6four
fkdqzcj3three64seven1jrrdvcx
two6jq9ninenine
2three2three
7rsix73two
eightrmkhpvkdhd3four2twoseven
knhjndmbtwofive5
62three72xk
jxjzgqszseven2
8l4eightndnsssf
gpbqt882hsszgmsxc6two
ppeight9four
two9two96two3
fiveglpg41fourtwo7two
jtwonedjjninesvzc96
ztzgkneightdqpvgbnhlzhvchj65
757seven2tjzvtmbbgbxxrmtqvtp
25fivezdpdvgtlql8
sg2bktwo6fourfourtwo
1six6sevenjkpgbdqnrsvlbmq
honeight65five3
nine52kjhsrzxnp
five33
qtmcbxxjceightnmjxblsixonelhbspf5
twoltcsmtvmone1
1739one9
13ghnine8z
sixfive13twotkslfhxjfdqdhcj
vzjngqthreethreenmlshs89
sixjgnt1
onethree776gzsmt
4sixxxhnq
krnlpckgjv722threesxrcjkcznb6foursix
fkvmfourvkghfivesix3nine
sixmsrlzbdmnclztrhhtlbj9ndgccjq7d1
7hphone1
dlhdjjcpl443rsklgp
lljhthreesix53bzm8
4sixnine2four7threeone
237nine1three
lbplmntwobxpvcbslp6hpzpbmkvbqfour
onecgtqtbn787
one8threetwortvpqqspbgfour6nine
672twoone334
four4sixxghvzxm2
sevengcng8
eight9six5sixoneptdrglllzvsrtlc
sixxvdhxdlxdtdqjz24q
1gmkthree3kqgfdkmtppshvcjzqmstwo2
eightfourvkrzsqxq1sevennhnine5lmptlxl
sixckmdbd1mrncvrcntlvjcv
xptwone3xtgfourtwo2k5
4nineninetdl1fiverpfhsbvnbpzxbvhmqpqj
877tjrtdr
n286rkmsvkzcthreeqdxdccmcd
1979
254zhtrlvpfs
5njg
1nineqftrhzkxvgtwo
4five675zfjrhkdkbd
tzxrrzc8dljzcnmxmfourthree
fivezcgfdvrrf2sixseven2
74nine
387fourseven2twothree
9six5
threefnrqfkqtkxqlpt67
66rzpmsvztwonernf
9nlfsdtn8
89zbphtctxkfqpj6
eightksevenchjgvctdkfbhrxssfzcgssix21oneightrt
drmfmxpnptqt5lmdrnhzkfcknltj4
fourlvtkxjlheight3nine
kmbftcbrxpxqk9
mlgeightwo1rslfrhvfdgsprbmnqpp
ktwone98three
4hvxgtjdgldjfdnfiveeight
gmcsixthreenffhcbnc35six
xt8threefhgjrmpgh2
pj2sv77sqgjfhzx5
qccfftqjmv35
pnrsqpsgdlgzszldvtjrfive1two4seven74
4nbprtcnvpvcvdg5seven85bnvnrznnncbrsh
qmfmkqsix8fourhnfhqn69
threefpgk3seven
1rngbxkxqthkvonethree6seven
7three56qlqcrsljeight1five
18717fzdccbglhjmvkznqvfive
lprmxkdnrchs27sevenone6
four55sixjvhbkbpdjptnhcxpmlnfour
eightfvdccbgxrg4bplqrvvpjq59
one3rxm7eightxtg41
fourhxplrbq7mnvnlsdcfpkdknqdtdjrpfvkp
7mpmrgkqfzeight
three9cp
bk3eightt
4glcfxkptsixjfqdnscjv2xthree8
bdgxxxssthree4vfqzlvdk5
eighttwoonefsthree35
sflvqvvzcs271
cpflsnhjrmzqmfour3rhkdtqvskt
ncdgjdpdtpgpztj3
ninevlgzpcjsixthree49
fqfh7one2eight
vvzeight16three8kqvqzj
nineb4fdmtlhmjbsxzrkblxm2tpqkn
zdtghhxfbkkdnsix7sfj
eightfldsxvsvmdl6onenxfsz
threeprbbbcxhqone9jtqjone27six
pstg7
2threethreefive4nine
4fourthree
hgj1npvqhmkm
43twonine
58t2tvtstgs8tgmfbndr
9xdvnrzgnz6dkvnk5
one31nineeight
1eightgzzmrqjmxtdxmxcxn5txqvhdr
four1seven
sixz12cvqlmqqzvnnhfiveoneightm
three5fznzbvsqnxtqnsmjt7hrhjgvqxnr
gmbhone5fpxjlvksevenjgh
fjfskl4
tkjqkpjddlmvmmxtxf5mdzgjone42
onesflmvlhfvxlrbk68
gfive9zhtbkvn
xxhsvbjxhcnqsnvnineone489nft
ninetwo8fiveeight1ninennls
xdkbsfrfz65xgjftjfhnh4
4threeeightsevenjsltzglonesevenzhhhcdbjfive
one7nnxzvhmvl
dcmsrd4sevenfour51five2
qvrgbjkgfpdbndpdgdptjqdhqkcrjknfxbgn4
p2
3311dczzvrskxksevenpgxthreeeight
tworbzmdd45foursevenfive
5fivefive7trtdlnppfournine3
5sixvtbfcbfkvbvbv3986
six64sixltlpnvt77
1oneeighttwo
tjsgchgninexrszjtzseven86
3cnine18
gntwone89glp31oneseven
9twofrqprtrhklhq39fjdtnnnjconejrqbgrdhhj
twozvmhxrhjzlhfninerbhzjxrgnmjt7
6five6fivezsbjjtvxvd9sixfiveqnsr
2threevldkrspksbsixsixtdgzmjrs2
fourhlstxkvr74qnx
one83
kdpdcvjlcsevensevennzvfourpvmlgttbl5
93smjxjpgnp8
dfmjhmrconetbztgfgf8six3hlbqdzqqs
4twotktfive
7nine1fscqqcml2two1fhddkblmgrtkrn
6fivefoureightnineninefive
39fourlsnmh7one
3fhkbpdmmgkgf
eightone3qjpfddljjjpjjmcg2twonexh
4two2517
seven6sixvrhjm543ckq
four7ninethreeonevfqrkhtx4
jeightwo5
fnndfvpc3five3h5
xkqstv5jpfonetwogjlbx5
fiveone8eightfive
2twomjkthreetkxtht2one
seven65gbmjcsmkr3
3qtrdtwo52eightntlbdmqcvseven
4cghqgpsmjztwo
8tqjlbpjmtwolrxp
ggrxfxrx15
3vt8sevenfourbkgcbvll28
lmgzcd4sixslonetwo
ptstwone6mpspfsevenh765eight
jfgpcfrgrmfnine5
fivec1ninefivefour9kmthmtwo
5zscbtpbbbbkhjrlxtnf4cmbfhbtwo
2mmgv
zmhcsixeighttwonine5gvljrkvqh
4five3
1four8six2one
sevenseven26mnbd7nine
vmxrptvk964sevendmdsql5
sevenfivekllbkzrmpmeight2twothree4
one45kjlnmznt67bgpl
eight7gpc6vvzqone
hjdbghreightthreesixzphtmj81
5dqftptqnfthree2nine5
86sixqgmlbnpnsixbxnfhmcdt8threefklhnsmkz
5vjgqnvvlonevxjzh9vctwo7nine
63ffslvtvvtgkmhvf1ntjtseven
fivefivev5tbpkx2
fourrsb5eightsfqsblmkkeightbnpqkmxxc6five
79kddeight
j5qltpmnineseventwo5
54gbmmmrfour
6ctfvjtnvdfourxjkjseven
1frq
75xhz7one4xlb
onetvxfive221zj2
sevenvkxvmqd93
5nfnldqtxpb35seven8
twobxtrpdzvbktrh1seven2two8
qsixeighttwofrxbxfspqmktpj5
2twoseven29knktthzssnhhf
595eightfiveeight4
rzmktrreight6n5seveneight
fivesix9
kqc81one
t271fivefournine5
65threefiveqfsmone
brhlq1eight931fourtwo
nine7eight
68nsgrvk2six
419gsmxnmjfour5
jqrh848
2eight91
sfgzxpbhb1cxjpd5ninegvpfmhkfgjkgblseven
dmnrmp77qqnbpvzeighttwo
pmgjdtdfx6
prrzx4jfjzpcklsb5sevenfour7six
brsqmz38five5twonebp
seven4threefour
18gmfvqgteight
7oneeightfourseven
onepkfnnvjpkgbvt8
fourkj4onenlkjcrvl
1phb5
16thgsmdqbnfivethreehbmmninenine
9qfqhdgthreeqmdg9cjzkjckfttwo
dxsevenone1mxmcfkgtdsczbgsx8
9jmhxphrhrjqmnnine3rxfmhjjqt
fivevjrninethreeseven6eight4
gltmpctwopcbchlj9r91qbdvsz
nmskpljnffbtwo7ffive5kqr
hlceightwotwoctsix4kkppmcxh
7vdtbxbsdm9nine9mqbgzgb6
threethreeeight4lfshmkpsbrveightsix
s77eighttwo
kxgntkmxshkllhctzk14
eight9lks3574
66fourstxmfqzpseven8p
46nine1twocqcqzn
vvzmqcj5fiverrj3threepltjs
2blshrhbpsnqqgxtnlzthreefour
4bqcssvxmxtwoeight4threeonenine
onezphmrtxbtlczz5eight
qcvvlc92mhhqpfsrrfndgl
seventwo5
2eight5oneeighteighteight32
cbmbfsztjnine3ztzbk49lvvlknvrnn
4qbtglxjhzb
5qzrlv4nxlxzbcdjsevenseven2jphvkthb
seven56
fivejlpnftwo7nz4fiveone
53hszlseven
tzr5sevenone5
ninegmzppseven7
dhrcgzqctwoeight8qhtlpf5jhvbcl
98onetwo715tcg5
tlfoursix5gzbntsevenseven
eight7peightonetwo937
6djvpnxvgfvbzpbgh5fk
ktxcqsgjthreesevenjrsgddzrfour8
lqmvrqgtdcmtzprq9threefour11jjkffcd
kbnlmsixfivetwohxftxpmvfn7
1qhf239nine
125zdjtsdxmthreeeight22eight
37
five827
lzn25
cspdsgf41nsjlthreedpcmq1nine
flvgklrtwodpxk2twobg57
8seven5nine
82seventpqmczz28fiveone
854vtxbrr2
three6seven6sevenonejsqtjpt
sixzbsxxngxcninesix82
mrbsp8sevenjhsfxgvpbv8
nine9kh
6fhzkrxsxthreeone
tvpmseven3fthlkndskdgfhjrvcxcninetdlkgrnxpm
tbrgbllqffourfqthree2
1sixvtmjtwokb71bddxpv
twolsjbscrfjzjsnphgsbthsmch6two5
3fouroneeightvbxsixb2
41dbqvfthree
tjjtpjpg1
6rfmfouronethreezgjsprtmd1sixeight
six182tbjjx7
4ffsgbshfzq93five
4threecncqtdklqt
nrkkgxzlsevenrqhbvzfvn99oneqjlxld9
xchnxhmfhpfiveblccdzdnqbzbm8gjrbqdslbbhdxpbpm
hbfdlrxmkrbc9threeonefive1rrvlfgjrq4
1eightthreeclpnzrtfive2
4nine1lsmmjjhsbninehlfxbbmsjcone
four16seven3fhvhlhcrmone
qszfive3sixbcdkcmdqhj3six
eightonelmbjb1cfx
3three1sixsix7
1cnmrhxhzrkshqnpqmfour8fqlfzq
two9sixbcgpv2rnnkdpeightthreenine
vbzqpkmqtpbfourseven6bhzghsix6
fhtwone26sixtwothreeseven
jvoneight7eightdfvljxthreethreefoureightkvb6
6hrnfhcn2nlflcj
gqktqlbkbeightninehvfql3lbfllrnrblqchfmn6pknq
twosix4nine
36sevenzlzgftkzznxqpnrbhtwoeightfive
qxqckssnrd8sdprgknine
1seventwoseven
mnfhgnrlfzfive1
pghfiveeightseven4nfzlkgdcvk
jvcmsdlfeight4
dtmt1sixkgmvnfvqd1sjvslttcfmkgngkrmbsmd
gltskr21
vvqoneightmfkbp61qkdpsvlhqctfseventhree
qvggksmf1
xhmzv926sixlqtwoeight
647six51
5qbx5seven8oneeight
mmcktfzstwoblzthssjnine1
558
48threenine4hlfdjnxdpnine8
hsghqrmpzbqsl7flbcjqqmrxkkcghdzmthreesix
27tldnbdsixtwosevennjdjxz
sevensixsbphqrqtqs9983
7eightsixzrktkone
91npjhccblmpxtslz78kcvqtvqpmone
tnshjg21twothreeonesxkpgctcjdjpxt
six9twothreeqx4one6one
ninenine6npnszkvcgn
four5threenineone6
4twobgdhnbtcssevenmmzfgktwo4
three38
ndfplbcdsnrhgpq1two4
xhdfzl78twofivethree
zqcccjkgrdnr5cxmfhthreeskzcqkczp
vltlfh1qfdzgp8five
mqjnsx99ninetwo8
bnk7
dqk62ninegvhbmclnrfztmtfvrzjrv
85dnine3lkzmn
onesixthreekdrgmlnddsc7
sds6
9vkhr49sixxgqbgmsheightfive6
onetwoxrhzg1ninefourseven32
fsthreeczsqjcjlxqxgxrbfour8nine
threeseven576vrvj7d7eightwogc
6rfpeightfive4zsrnsvvbdd
3fiver6nnpmgmhzlhzfxb16jg
three9qhlpninethreethreemfr7
rx6dhk1sjrpmpjr
three4nhvkksevenxzbzbflnrcmmzg
eightvckzjgonetkcvjzdhnzfoursix6
onetwothreednktwoseight7jkpsgtdllf
nx6eight13nine
qzvnvsjnfjng99threesevenvc
seven2eightbpzsix
onefour8xccmksgfsckxkbcsqkgdgszxjgllh
8zfour
fiveeightrssqtwo992
8nbvcfjzpxnpfour4
zhqmxqlzv6onetwoeightkrfg25two
9tqbeightfmgqtdbl
three3nine97
vpcmmlctgc6
3two4fhnh2ninesixmtfbbvdkls6
171
lveightwofive8ninetwo3sixzp
3oneqhgonerjskld3eight5
zfxnkhrthreexllntwo1two9fivetwo
sixfivexmxxq7
xxhthqxnjq3tgjdvrnqtgts9
7226fiveqzbvgttlmv
884xxxt9
781
4dtpcdslmg9mdxsjksixnine
onesevenkqzg2
nine4nine
cdqmrvdkxtrqdsixnvqxs4fiveninefvdttbqkx
blcbcgbrnkpmlrdlj7fivedbnkkleightone94
1hgtmpdlpsfivethree8four5
vx93czsixkzkjpqbgzhthreetwo
zfbxmsjrmssixninebkvseventl69
jcnkdqmdvg392
pqkgqzgtwo245two9
1zzjc7onejdf5snc
25dhcpqbkzjxcxmxdgxftj
kzqsix8xblzlnjtvbfive5four35
ghfjjhphnftwo9five
jqstpxv5hcqfbh7twotwofive
jj66nsixhfsbgs6kmdpqdrpn
xfvc73snqtcpqcjlsix6526
tbpklzqjcz6fttcvqd
9pdrzfvrr9twolzgs
fiveseventhreeszxkxjx9ndvtlhqqqh7spfcvpzthree
68blhzlngj7
hznljt4eight8qfkhmqvpskcxknz9
eightjqlghmn76two5ggone
onesixmgbfjv41fhoneightvxl
jjlthreenine839
twotwo4xvlpcnpmtwo2jrzcjjlfteighteightwotv
t4
onefivefivefour94eightfour
6sixtj6threethree2sevenone
1eightkbsixrhhphnxmjlf
mlplpjkndlflk1nineninetndsqjnpmvzhkeight
jmkqqblqnxfivetwo8485eightone
five9565three3nineseven
bmfljlbbttxlvxzrfnnp319six
jb4one96
jqllbjqndlkbxkeightdrbhjjd3
8fiveggdtrfjvrpd7six7
24xrt3twosix2
rccf47zzmfshdtwosrsm
5jtqxkpshnbtwohtpbgtgsixone
seven77p
eightqgkmdvhdjssqfpfnk3sixthreesixthree
9ninetwoonelkrspqn3
4ttdgvkghzlninevkrxhclmstdq9mpmgtcvrlqvlqgtrxb
two7twojxzbrhtnpfrhpvsevenfive
4threetbkddx252tmspeight
five9xbcrfrxbdnb
threetwo6seven2foursix
onekeightxdgxjmthreeszrjhmk9
6q565cvdhbjldkb
two1three
dzrhvfktjninepfxvxmzmkeight1
xzbgjqfour5nphmrhlfdkk
38rfjeight5
848bfztdm
rldlk2zbmpsl8
gqgtrchtwoeight9eightone
27f
btgxvnm8seven2
sixmznpvvsbrslmtgfpvctz96hrjdlclnzmftjjdmp3
hsppfkeightsevenfive2
2two35kxssnjs21three
3ninefivemjslrzzsnl
9lzdmtdeightone3smfpmlvs5zkxmrssq
zrgsrbgcrllnjfrk9eightsevenlflnkxfgbzm
ninexsgvvslvvczfshvgfour6ngkkmcrkgbsngkzvcch
26six997
1zbsth
psdksevenone776
one8lzcrggjfrjssixkjtwo
sevenfour5three91six
brg3ninetwo5rvnpqsix
9seven9sixssnfourxsdbgbrpvxcmqh
6cmcheight8
onefive1sevenfournine1
threej3
lmzq27kkzxbtwo142
krhhmmsrklseven5pmjpthree8
lgplxpx7eighttlvqdmmlhz9gjfbxnlkkg
tfrpbxpsbghffsixrgm4
8fjnflxr2613
7onevzqcgqsevenrgs3twonex
8nine9brsnqlvtfivefour4fourtknbsm
grct7svvdbqtsrxsix9
544
bldknmxccsix4
xjdxzmhxqbfive36frtstwothree
4two7nine
8five99jddntnhjjsxjgfsqhljcrq
twotwofivethreeseven4tzgnqcq
sevenlvxjjrsjzvjxsltlfour2qmqtbklpkp
sixvrlseven1twothree
fivepcrhdtkrfour2snvjhhqzl8cbfkgghvb7
mhhfjmv4nine6rvdvhjlfgsixjzghsdf5
7fgmnvtfn94qbtrfb26
threeonejxjkcz2
1eighteightfour9xxdqnine
3threefour932
mtnp6onefour4oneseven3cjcm
fivetwo7four
sevenrtbx6trxfffsdlgztwo3
eight16fiveoneninejnpvnglzjd
7pqvfjeight
two87sbseven88
73678seven4three
pmxdvndvsixcvnntjcv4sevenhfmklmztwoeight
pdplkff87fouronefqrrbnine8djkgh
eight35vlllkzmnlpcgngjnt
897kqjhkfhfbone
ch6
5threefivehfnvsphfxqdltgtbjtwofour3
nine5fourfivejtrhmnbmx
eightqthree5gdpvnt2eightpbd
jbv34nine
lcqxvbhr1
4dpcbxj
seven3eight75
75ronenine4four
4ppfnkjpphppsjr4
2cjkjnvnjxtwolhmnrlcpzmbkhzjkcvknczjvcxj
tj5rgmvvhmc2
three7scghxlnbsmgtjgqqtmxrfnvtlvcpp16
fiveonefourxlqcttwosnine9
323hmpxbkpdvklcrnglmhdlcmmzdtwo
onevvbvctdqsvhqb9
4foursix3
56seveneight281five
5t1ldfbstvrvbks2sevengfndh
6four48
4fmgjxzxhq
sixkmltvqjv6qfpf235
three4djpcgvbone1bztqnhk
5fourfjtflgsixtwofourthree
4nine9gcdnfjm
xfcnmpbvmmhkfiveseven88v6
68sixtworztsbzvghjsmchmsxmdnine
seven1eight
3threesxjqxxx2threeeight2
twontnxvnjjtwocpxmrsix2x2nc
nineltgzzzzqg2sixnxdhcb36
623twohnmqptwo8
ntwonebtcqztrvninenine58glpkdpdghkbtrsz
rlnthmmdfsvmdfqhfivendptjfpx7hnbnkzlpntvglvdlfb4five
cmx6four6
81ninefourqbljfrbshsnmcqmzrhkznl
psixthree8jrmhcvpdgflsnnvdgmkxtxrl
2ggghpzxxlmrlftpqmsg
7four296nine
2xonesevenonenine39ctq
four915fdtcvcrv
fsssjgbncc8nine
qgpfveightdvtkhxxzrcmfivesix4
4436eightonefspnbptktv
rlmmlrhmjnfivetwo6sixmxs
443ninesixfour
fivexmcdmpxfcn8ddnrhbl9znqxtf
djtkclphr4ninesixfiveqgksrzj6nineeightwogz
eight494dd
klmmxtlvxsnineeightrxzzksjxcvgvznonevbnhxjlrxh85
vftdg4fvlseven9fnh
rglcjdkcsevenrvrkrrptx4mfbqb
767five9
eight1four3
fourfived84threethreeeight
two5foureight
seven43gzzmksixhmln2
bjknl46ninexrjbr5fourfour
2pns7fpjznxkponepfive
sixkqdhm1ninetwor7
threefive8
two8lhlphf
seven3seventwo
4psqnsmqgz25
eight33fiveg5oneeightwoh
sixsixxldfive8
qhljssjbsevengfh5seven
gjsqptqkjk3bhj6five
six6szlss9seven
nmzxrgthreemtckbvglb7six
ffxmfive392fivethreenineseven
sevenvvnssgvrq8ninedfvqzgrdtqnh
hbsgz8nineczksxzllx2five
9twonine
4fz
3fqjnpxnvseventhree7ninefive9
phlvsix123pszgrxvhjkk
3two4
klcbnvrfv31zbb236
eightseven1lkcv1six9
7four7fiveeight
lqninenmqmbsgk9
sevensixmczghz299six
49sixlcbtsbnineseven9five
rtwone36sblhninemflhd
8nineblqjzsddone24dnfdgph
jzlbhlhvfour4dlvctlrqsix
threeseventhreenlhcc8
2xgccjbmdlzlstjvqsknd
97ninedfcmx9359l
7sevenqzvlfqlfsdxsix
8682
2bhzhzpglp
sevenzbfvlpn7tkhmxtvgvfeightwobsb
npdfzsevenonezc1two
2hcmrldtn5
threeseven286fourfour
seventwo5eight
ninefourmqxjdthczlqp4xrxrptzvdllctwo
ninefour8
q52xzpxvkgsixctrjg
6four52qkvtqpqcfivevghjmltckgtjjf
qxxkgqqcggbjc85
lninelbzqtdbnvvmchxrpsbfivehtmqcc3
xbtlshzqtrtwo8sqffcsfivetwo3mvxsnkgseven
5pqlfrqqhpgtg6four
6lxjzthree14six4
three22fxrrdvk
sixztwoeightnine4seven1four
fivegbvrtkvldplfzrvxbmkmrcftxs4oneqhmxseventhree
threenine2vzdkxtz7
7mnmfkfq48
four66grzkq86six
four3threezdszkzkbhnsqpmsninebq
746
55fiveqhvtgfz
c2mjsrdzmtsevenfive6ncjrvzc4
ntwoneeight2five93jskvfcvn
fvzjvxtwozhnhnmqv3seventhree
2three5three
2sevenclone1
three9two4kqxq7four
eight8gzhcfbjxjnftxnnjl
mkz4two7fivefive9fivethree
eighttwo9seven6
eightkdpfprqdz6
9twofczb
sqmhjgzqvc3
525three9jnppn
eightkpfngjsx97twozmbdtxhh
snc6
two3dqpnps3pmdnbxdnlc8
pfnv2
four1sixeightm35
sixldzmvtfsthreeseven1ninethreeseveneight
7jrxgdjfh3xvlpfgckjp6fourfive
sktmpngljrrgvpqqkdnine14d
one79
1five7jmhtbnkvcg8vgrxdbnr5four
fvzcslpmgv174426
3nineccslpsrfdf35lqbfqbncs83
364twoqvqr4
79lfd2nineeight2ghrlbspvkzseven
nine1ztqbs
eightndxxqxtwo3cqz47
fiveeight792eightqskstrftdpccsrgskrhc
26fmrrhhpthree6b"""
}
| 0 | Kotlin | 0 | 0 | e18afa4a7c0c7b7e12744c38c1a57f42f055dcdf | 25,866 | advent-of-code-2023 | MIT License |
src/main/kotlin/aoc2023/Day17.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2023
import Point
import readInput
import to2dIntArray
import java.util.*
object Day17 {
private data class StraightCount(val horizontal: Int, val vertical: Int) {
val nextHorizontal by lazy { StraightCount(horizontal + 1, 0) }
val nextVertical by lazy { StraightCount(0, vertical + 1) }
}
private data class State(
val consecutiveStraight: StraightCount = StraightCount(0, 0),
val position: Point,
val distance: Int = 0,
val comingFrom: Point? = null
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as State
if (consecutiveStraight != other.consecutiveStraight) return false
if (position != other.position) return false
return true
}
override fun hashCode(): Int {
var result = consecutiveStraight.hashCode()
result = 31 * result + position.hashCode()
return result
}
}
private fun solve(input: List<String>, minConsecutive: Int = 0, maxConsecutive: Int): Int {
val map = input.to2dIntArray()
val maxX = input.size - 1
val maxY = input.first().length - 1
val start = Point(0, 0)
val end = Point(maxX, maxY)
val validGrid = start to end
val shortestDistances = mutableMapOf<Point, MutableList<State>>()
val queue: Queue<State> = PriorityQueue { o1, o2 -> o1.distance.compareTo(o2.distance) }
val startState = State(position = start)
queue.add(startState)
shortestDistances[start] = mutableListOf(startState)
while (queue.isNotEmpty()
&& shortestDistances[end]?.none { it.consecutiveStraight.horizontal >= minConsecutive || it.consecutiveStraight.vertical >= minConsecutive } != false
) {
val current = queue.poll()
current.position.getNeighbours(validGrid = validGrid).mapNotNull { nextPosition ->
val newDistance = current.distance + map[nextPosition.x][nextPosition.y]
if (current.comingFrom == nextPosition) {
null
} else if (current.position.x == nextPosition.x && current.consecutiveStraight.vertical < maxConsecutive
&& (current.comingFrom == null || current.comingFrom.x == current.position.x || current.consecutiveStraight.horizontal >= minConsecutive)
) {
State(current.consecutiveStraight.nextVertical, nextPosition, newDistance, current.position)
} else if (current.position.y == nextPosition.y && current.consecutiveStraight.horizontal < maxConsecutive
&& (current.comingFrom == null || current.comingFrom.y == current.position.y || current.consecutiveStraight.vertical >= minConsecutive)
) {
State(current.consecutiveStraight.nextHorizontal, nextPosition, newDistance, current.position)
} else {
null
}
}.forEach { nextState ->
val list = shortestDistances[nextState.position]
?: mutableListOf<State>().also { shortestDistances[nextState.position] = it }
if (!list.contains(nextState)) {
list.add(nextState)
queue.add(nextState)
}
}
}
return shortestDistances[end]
?.filter { it.consecutiveStraight.horizontal >= minConsecutive || it.consecutiveStraight.vertical >= minConsecutive }
?.minOfOrNull { it.distance }
?: throw IllegalStateException("Could not find any path to $end")
}
fun part1(input: List<String>) = solve(input, maxConsecutive = 3)
fun part2(input: List<String>) = solve(input, maxConsecutive = 10, minConsecutive = 4)
}
fun main() {
val testInput = readInput("Day17_test", 2023)
check(Day17.part1(testInput) == 102)
check(Day17.part2(testInput) == 94)
val input = readInput("Day17", 2023)
println(Day17.part1(input))
println(Day17.part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 4,208 | adventOfCode | Apache License 2.0 |
src/day13.kt | skuhtic | 572,645,300 | false | {"Kotlin": 36109} | fun main() {
day13.execute(forceBothParts = true)
}
val day13 = object : Day<Int>(13, 13, 140) {
override val testInput: InputData
get() = """
[1,1,3,1,1]
[1,1,5,1,1]
[[1],[2,3,4]]
[[1],4]
[9]
[[8,7,6]]
[[4,4],4,4]
[[4,4],4,4,4]
[7,7,7,7]
[7,7,7]
[]
[3]
[[[]]]
[[]]
[1,[2,[3,[4,[5,6,7]]]],8,9]
[1,[2,[3,[4,[5,6,0]]]],8,9]
""".trimIndent().lines()
override fun part1(input: InputData): Int = input.chunked(3).map { pair ->
pair.let { pair[0] to pair[1] }
}.mapIndexed { i, (f, s) -> (i + 1) * if (f.compare(s)) 1 else 0 }.sum()
override fun part2(input: InputData): Int {
val add1 = "[[2]]"
val add2 = "[[6]]"
return buildList {
input.forEach { line -> if (line.isNotEmpty()) add(line) }
add(add1)
add(add2)
}.sortedWith(comparator).reversed().let { (it.indexOf(add1) + 1) * (it.indexOf(add2) + 1) }
}
val comparator = Comparator<String> { a, b -> if (a.compare(b)) 1 else -1 }
fun String.compare(other: String): Boolean {
val f = get(0)
val s = other[0]
fun getNumber(str: String) = str.takeWhile { it.isDigit() }.let { it.toInt() to str.drop(it.length) }
fun putBracketsOnNumber(str: String): String = getNumber(str).let { (no, rest) -> "[$no]$rest" }
// log("$f - $s -> $this vs $other")
return when {
f == s -> drop(1).compare(other.drop(1))
f == '[' && s.isDigit() -> compare(putBracketsOnNumber(other))
f.isDigit() && s == '[' -> putBracketsOnNumber(this).compare(other)
f == ']' && s == ',' -> true
f == ',' && s == ']' -> false
f == ']' && s.isDigit() -> true
f.isDigit() && s == ']' -> false
f == ']' && s == '[' -> true
f == '[' && s == ']' -> false
f == ',' && s.isDigit() -> true
f.isDigit() && s == ',' -> false
f.isDigit() && s.isDigit() -> getNumber(this).let { fno ->
getNumber(other).let { sno ->
if (fno.first == sno.first) fno.second.compare(sno.second) else fno.first < sno.first
}
}
else -> error("$this vs $s")
}
}
}
| 0 | Kotlin | 0 | 0 | 8de2933df90259cf53c9cb190624d1fb18566868 | 2,446 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/aoc2021/day4.kt | sodaplayer | 434,841,315 | false | {"Kotlin": 31068} | package aoc2021
import aoc2021.utils.loadInput
data class Board(val marked: Set<Int>, val posMap: Map<String, Int>)
data class Round(val justCalled: String?, val nums: List<String>, val boards: List<Board>)
fun main() {
val lines = loadInput("/2021/day4")
.bufferedReader()
.readLines()
val nums = lines[0].split(",")
val boards = lines.drop(1)
.chunked(6)
.map{
it.joinToString( " ").split("\n", " ").filter(String::isNotBlank)
}
.map(::initBoard)
val playedRounds = generateSequence (Round(null as String?, nums, boards)) { (_, rounds, boards) ->
Round(
rounds.first(),
rounds.drop(1),
boards.map { markNum(it, rounds.first()) }
)
}
val firstBingo = playedRounds.filter { (_, _, boards) ->
boards.any(::bingo)
}.first()
val firstBoard = firstBingo.boards.find(::bingo)
println(sunUnmarked(firstBoard!!) * firstBingo.justCalled!!.toInt())
val (prev, final) = playedRounds.take(100)
.partition {
(_, _, boards) -> boards.count(::bingo) < 100
}
.let { it.first.last() to it.second.first() }
val worstBoard =
final.boards.toSet().filterNot { finalBoard ->
prev.boards
.filter(::bingo)
.map { it.posMap.keys }
.contains(finalBoard.posMap.keys)
}.first()
println(sunUnmarked(worstBoard) * final.justCalled!!.toInt())
}
fun initBoard(input: List<String>): Board {
return Board(
emptySet(),
input.mapIndexed { pos, num ->
num to pos
}.toMap()
)
}
fun markNum(board: Board, number: String): Board {
val pos = board.posMap[number]
return if (pos == null) board
else with(board) {
copy(
marked = marked + pos
)
}
}
val winningBoards = listOf(
/* Columns */
0 until 5,
5 until 10,
10 until 15,
15 until 20,
20 until 25,
/* Rows */
0 until 21 step 5,
1 until 22 step 5,
2 until 23 step 5,
3 until 24 step 5,
4 until 24 step 5,
)
fun bingo(board: Board) =
winningBoards.map { positions ->
positions.count {
board.marked.contains(it)
}
}.any { it == 5 }
fun sunUnmarked(board: Board) =
board.posMap.filterNot { (_, pos) ->
board.marked.contains(pos)
}.keys.sumOf(String::toInt)
| 0 | Kotlin | 0 | 0 | 2d72897e1202ee816aa0e4834690a13f5ce19747 | 2,456 | aoc-kotlin | Apache License 2.0 |
src/Day15.kt | dmarcato | 576,511,169 | false | {"Kotlin": 36664} | import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
data class PlanePos(val x: Int, val y: Int)
fun PlanePos.distance(x: Int, y: Int) = abs(this.x - x) + abs(this.y - y)
fun PlanePos.distance(pos: PlanePos) = distance(pos.x, pos.y)
enum class PlaneItem { Sensor, Beacon, NoBeacon }
fun PlaneItem?.symbol() = when (this) {
PlaneItem.Sensor -> "S"
PlaneItem.Beacon -> "B"
PlaneItem.NoBeacon -> "#"
else -> "."
}
class Plane {
private val grid = mutableMapOf<PlanePos, PlaneItem>()
private val distances = mutableMapOf<PlanePos, Int>()
private var rangeX: IntRange? = null
private var rangeY: IntRange? = null
fun addItems(input: List<String>) {
input.forEach { row ->
val (sensor, beacon) = row.split(":").map { item ->
"x=(-?\\d+), y=(-?\\d+)".toRegex().find(item)!!.groupValues.let { (_, x, y) ->
PlanePos(x.toInt(), y.toInt())
}
}
val distance = sensor.distance(beacon)
distances[sensor] = distance
listOf(sensor, beacon).forEach { pos ->
grid[pos] = when (pos) {
sensor -> PlaneItem.Sensor
else -> PlaneItem.Beacon
}
rangeX = min(pos.x - distance, rangeX?.first ?: Int.MAX_VALUE) .. max(pos.x + distance, rangeX?.last ?: Int.MIN_VALUE)
rangeY = min(pos.y - distance, rangeY?.first ?: Int.MAX_VALUE) .. max(pos.y + distance, rangeY?.last ?: Int.MIN_VALUE)
}
}
}
fun noBeaconPosition(rowNum: Int): Int {
return rangeX!!.count { x ->
val item = PlanePos(x, rowNum)
distances.any { (pos, distance) ->
grid[item] == null && pos.distance(item) <= distance
}
}
}
fun tuningFrequency(area: IntRange): Long {
val size = area.last - area.first
(0 .. size).forEach { y ->
var x = 0
while (x <= size) {
val sensorDistance = distances.firstNotNullOfOrNull { (pos, distance) ->
val itemDistance = pos.distance(x, y)
if (itemDistance <= distance) {
distance - itemDistance
} else {
null
}
} ?: return x * 4000000L + y
x += sensorDistance + 1
}
}
throw RuntimeException()
}
@Suppress("unused")
fun print() {
buildString {
rangeY!!.forEach { y ->
rangeX!!.forEach { x ->
if (x == 500 && y == 0) append("+")
else append(grid[PlanePos(x, y)].symbol())
}
append("\n")
}
}.println()
}
}
fun main() {
fun part1(input: List<String>, rowToCheck: Int): Int {
val plane = Plane()
plane.addItems(input)
return plane.noBeaconPosition(rowToCheck)
}
fun part2(input: List<String>, areaToCheck: Int): Long {
val plane = Plane()
plane.addItems(input)
return plane.tuningFrequency(0 .. areaToCheck)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day15_test")
check(part1(testInput, 10) == 26) { "part1 check failed" }
check(part2(testInput, 20) == 56000011L) { "part2 check failed" }
val input = readInput("Day15")
part1(input, 2000000).println()
part2(input, 4000000).println()
}
| 0 | Kotlin | 0 | 0 | 6abd8ca89a1acce49ecc0ca8a51acd3969979464 | 3,576 | aoc2022 | Apache License 2.0 |
src/Day07.kt | dannyrm | 573,100,803 | false | null | fun main() {
fun part1(input: List<String>): Long {
val tokens = input.map { parseLine(it) }
val tree = buildDirectoryTree(tokens)
return obtainDirectories(tree).filter { it.size() <= 100_000 }.sumOf { it.size() }
}
fun part2(input: List<String>): Long {
val totalDiskSpace = 70_000_000
val totalSpaceRequired = 30_000_000
val tokens = input.map { parseLine(it) }
val tree = buildDirectoryTree(tokens)
// Find the space used by the root directory
val totalSpaceUsed = obtainDirectories(tree).first { it.token.params[0] == "/" }.size()
val totalFreeSpace = totalDiskSpace - totalSpaceUsed
val totalSpaceToFree = totalSpaceRequired - totalFreeSpace
return obtainDirectories(tree).filter { it.size() >= totalSpaceToFree }.minOf { it.size() }
}
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
fun obtainDirectories(node: TreeNode): Set<TreeNode> {
val directories = mutableSetOf<TreeNode>()
if (node.token.tokenType == TokenType.DIR) {
directories.add(node)
}
node.children.forEach {
if (it.token.tokenType == TokenType.DIR) {
directories.add(node)
directories.addAll(obtainDirectories(it))
}
}
return directories
}
fun buildDirectoryTree(tokens: List<Token>): TreeNode {
val rootNode = TreeNode(Token(TokenType.DIR, listOf("/")), null)
var currentNode = rootNode
tokens.drop(1).forEach { token -> // Drop the first line as it's just CD'ing into the root dir
when (token.tokenType) {
TokenType.DIR -> {
val dirNode = TreeNode(token, currentNode)
if (!currentNode.children.contains(dirNode)) {
currentNode.addChild(dirNode)
}
}
TokenType.CD -> {
val dirNode = TreeNode(Token(TokenType.DIR, token.params), currentNode)
if (dirNode.token.params[0] == "..") {
currentNode = currentNode.parent!!
} else if (currentNode.children.contains(dirNode)) {
currentNode = currentNode.children.first { it == dirNode }
} else {
currentNode.addChild(dirNode)
}
}
TokenType.FILE -> {
val fileNode = TreeNode(Token(TokenType.FILE, token.params), currentNode)
if (!currentNode.children.contains(fileNode)) {
currentNode.addChild(fileNode)
}
}
else -> {}
}
}
return rootNode
}
fun parseLine(input: String): Token {
return if (input.startsWith("$")) { // A command
parseCommand(input)
} else {
parseOutputLine(input)
}
}
fun parseOutputLine(input: String): Token {
return if (input.startsWith("dir")) {
Token(TokenType.DIR, listOf(input.substring(4))) // Remove the "dir " at the beginning to get the dir name
} else {
val splitInput = input.split(" ")
val fileSize = splitInput[0]
val fileName = splitInput[1]
Token(TokenType.FILE, listOf(fileSize, fileName))
}
}
fun parseCommand(input: String): Token {
return input
.substring(2) // Remove the $ and space at the beginning of the String
.run {
when (this.substring(0, 2)) {
"cd" -> Token(TokenType.CD, listOf(this.substring(3))) // Remove the "cd ", leaving just the directory
"ls" -> Token(TokenType.LS)
else -> throw IllegalArgumentException("Unrecognised command: ${this.substring(0, 2)}")
}
}
}
data class Token(val tokenType: TokenType, val params: List<String> = listOf())
enum class TokenType {
CD,
LS,
DIR,
FILE
}
data class TreeNode(val token: Token, val parent: TreeNode?) {
val children = mutableListOf<TreeNode>()
fun addChild(child: TreeNode) {
children.add(child)
}
fun size(): Long = size(this)
private fun size(node: TreeNode): Long {
return when (node.token.tokenType) {
TokenType.FILE -> {
node.token.params[0].toLong()
}
TokenType.DIR -> {
node.children.sumOf { size(it) }
}
else -> {
0L
}
}
}
override fun toString(): String {
return "TreeNode(token=$token, parent=${parent?.token}, children=$children)"
}
}
| 0 | Kotlin | 0 | 0 | 9c89b27614acd268d0d620ac62245858b85ba92e | 4,583 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/github/dangerground/aoc2020/Day16.kt | dangerground | 317,439,198 | false | null | package com.github.dangerground.aoc2020
import com.github.dangerground.aoc2020.util.DayInput
fun main() {
val process = Day16(DayInput.batchesOfStringList(16))
println("result part 1: ${process.part1()}")
println("result part 2: ${process.part2()}")
}
class Day16(val batches: List<List<String>>) {
val fields = batches[0].map { Field(it) }
val nearbyTickets = batches[2].drop(1).map { it.split(",").map { it.toInt() } }
val myTicket = batches[1][1].split(",").map { it.toInt() }
fun part1(): Int {
var invalid = 0
nearbyTickets.forEach { ticket ->
for (value in ticket) {
invalid += isAllInvalid(value)
}
}
return invalid
}
private fun isAllInvalid(value: Int): Int {
fields.forEach { field ->
if (field.isValid(value)) {
return -1
}
}
return value
}
fun part2(): Long {
val remaining = nearbyTickets.filter { !it.any { isAllInvalid(it) > -1 } }.toMutableList()
remaining.add(myTicket)
val fieldResult = possibleFieldsForIndex(remaining)
return fieldResult.filter { (_, f) -> f[0].name.startsWith("departure") }
.map { (idx, _) -> myTicket[idx].toLong() }
.reduce { i1, i2 -> i1 * i2 }
}
private fun reduceByCanOnlyBeThisOneIndex(fieldResult: List<Pair<Int, MutableList<Field>>>) {
val lonely = mutableSetOf<Field>()
var changed: Boolean
do {
changed = false
fieldResult.forEach {
if (it.second.size == 1) {
lonely.add(it.second[0])
} else {
val removed = it.second.removeIf { lonely.contains(it) }
if (removed) {
changed = true
}
}
}
} while (changed)
}
private fun possibleFieldsForIndex(remaining: MutableList<List<Int>>): List<Pair<Int, MutableList<Field>>> {
val fieldResult = remaining[0].indices
.map { idx ->
remaining
.map { ticket -> allValid(ticket[idx]) }
.reduce { l1, l2 -> l1.intersect(l2).toList() }
.toMutableList()
}
.mapIndexed { idx, it -> idx to it }
reduceByCanOnlyBeThisOneIndex(fieldResult)
return fieldResult
}
private fun allValid(value: Int): List<Field> {
return fields.filter { it.isValid(value) }
}
}
class Field(input: String) {
val regex = Regex("([a-z ]+): (\\d+)-(\\d+) or (\\d+)-(\\d+)")
val name: String
val range1: IntRange
val range2: IntRange
init {
val groups = regex.matchEntire(input)!!.groupValues
name = groups[1]
range1 = IntRange(groups[2].toInt(), groups[3].toInt())
range2 = IntRange(groups[4].toInt(), groups[5].toInt())
}
fun isValid(value: Int): Boolean {
return range1.contains(value) || range2.contains(value)
}
override fun toString(): String {
return name
}
}
| 0 | Kotlin | 0 | 0 | c3667a2a8126d903d09176848b0e1d511d90fa79 | 3,155 | adventofcode-2020 | MIT License |
src/Day09.kt | weberchu | 573,107,187 | false | {"Kotlin": 91366} | import kotlin.math.abs
private fun ropeOffset(headPosition: Int, tailPosition: Int): Int {
return if (headPosition > tailPosition) {
1
} else if (headPosition < tailPosition) {
-1
} else {
0
}
}
private fun ropeSimulation(input: List<String>, ropeLength: Int): Int {
val visitedPositions = mutableSetOf<Pair<Int, Int>>()
val rope = MutableList(ropeLength) { Pair(0, 0) }
visitedPositions.add(rope[ropeLength - 1])
for (line in input) {
val motion = line.split(" ")
val direction = motion[0]
val magnitude = motion[1].toInt()
for (i in 0 until magnitude) {
rope[0] = when (direction) {
"U" -> Pair(rope[0].first, rope[0].second + 1)
"D" -> Pair(rope[0].first, rope[0].second - 1)
"L" -> Pair(rope[0].first - 1, rope[0].second)
"R" -> Pair(rope[0].first + 1, rope[0].second)
else -> throw IllegalArgumentException("Unknown motion $motion")
}
for (j in 1 until ropeLength) {
if (abs(rope[j - 1].first - rope[j].first) > 1 || abs(rope[j - 1].second - rope[j].second) > 1) {
rope[j] = Pair(
rope[j].first + ropeOffset(rope[j - 1].first, rope[j].first),
rope[j].second + ropeOffset(rope[j - 1].second, rope[j].second)
)
if (j == ropeLength - 1) {
visitedPositions.add(rope[j])
}
} else {
break
}
}
}
}
return visitedPositions.size
}
fun main() {
val input = readInput("Day09")
// val input = readInput("Test")
println("Part 1: " + ropeSimulation(input, 2))
println("Part 2: " + ropeSimulation(input, 10))
}
| 0 | Kotlin | 0 | 0 | 903ff33037e8dd6dd5504638a281cb4813763873 | 1,878 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/aoc23/Day13.kt | tahlers | 725,424,936 | false | {"Kotlin": 65626} | package aoc23
import kotlin.math.max
import kotlin.math.min
object Day13 {
data class Pos(val x: Int, val y: Int)
data class Pattern(val stones: Set<Pos> = emptySet()) {
fun vertical(index: Int): Set<Pos> = stones.filter { it.x == index }.toSet()
fun transpose() = Pattern(stones.map { Pos(it.y, it.x) }.toSet())
}
fun calculateOfReflectionPatterns(input: String, smudgeCount: Int = 0): Int {
val patterns = parseInput(input)
val patternCount = patterns.map { pattern ->
findVerticalReflection(pattern, smudgeCount) +
findVerticalReflection(pattern.transpose(), smudgeCount) * 100
}
return patternCount.sum()
}
private fun findVerticalReflection(pattern: Pattern, smudgeCount: Int): Int {
val maxX = pattern.stones.maxOf { it.x }
val reflectionColumn = (0..<maxX).singleOrNull { col ->
isReflectionAtCol(col, min(col + 1, maxX - col), pattern, smudgeCount)
} ?: -1
return reflectionColumn + 1
}
private fun isReflectionAtCol(col: Int, reflectionSize: Int, pattern: Pattern, smudgeCount: Int): Boolean {
val reflectionRange = 1..reflectionSize
val differenceCount = reflectionRange.sumOf {
val colLeft = col - (it - 1)
val colRight = col + it
countYDifferences(
pattern.vertical(colLeft),
pattern.vertical(colRight)
)
}
return differenceCount == smudgeCount
}
private fun countYDifferences(a: Set<Pos>, b: Set<Pos>): Int {
val aYs = a.map { it.y }
val bYs = b.map { it.y }
val maxY = max(aYs.max(), bYs.max())
return (0..maxY).count { (it in aYs) xor (it in bYs) }
}
private fun parseInput(input: String): List<Pattern> {
val blocks = input.trim().split("\n\n").map { it.trim() }
val pattern = blocks.map { block ->
val blockLines = block.lines()
val stones = blockLines.flatMapIndexed { y, line ->
line.mapIndexedNotNull { x, c ->
if (c == '#') Pos(x, y) else null
}
}
Pattern(stones.toSet())
}
return pattern
}
} | 0 | Kotlin | 0 | 0 | 0cd9676a7d1fec01858ede1ab0adf254d17380b0 | 2,273 | advent-of-code-23 | Apache License 2.0 |
src/main/kotlin/org/domnikl/algorithms/graphs/WeightedGraph.kt | domnikl | 231,452,742 | false | null | package org.domnikl.algorithms.graphs
import org.domnikl.data_structures.LinkedList
class WeightedGraph<T : Any> {
private val graph = mutableMapOf<T, LinkedList<Edge<T>>>()
fun addEdge(from: T, to: T, weight: Double) {
graph.getOrPut(from) { LinkedList() }.addFirst(Edge(to, weight))
graph.getOrPut(to) { LinkedList() }
}
private fun adjacentVertices(element: T): List<Edge<T>> {
return graph[element]?.toList() ?: emptyList()
}
fun dijkstra(from: T, destination: T): ShortestPath<T> {
var current = from
val unvisited = graph.keys
val distances = graph.map { it.key to Double.POSITIVE_INFINITY }.toMap().toMutableMap()
val paths = mutableMapOf<T, List<Edge<T>>>()
distances[from] = 0.0
while (unvisited.isNotEmpty() && unvisited.contains(destination)) {
adjacentVertices(current).forEach { edge ->
if (distances[current]!! + edge.weight < distances[edge.to]!!) {
distances[edge.to] = distances[current]!! + edge.weight
paths[edge.to] = paths.getOrDefault(current, listOf(Edge(current, 0.0))) + listOf(edge)
}
}
unvisited.remove(current)
if (current == destination || unvisited.all { distances[it]!!.isInfinite() }) {
break
}
if (unvisited.isNotEmpty()) {
current = unvisited.minBy { distances[it]!! }!!
}
}
val shortestPath = paths[destination]!!
return ShortestPath(
shortestPath.map { it.to },
shortestPath.sumBy { it.weight }
)
}
data class ShortestPath<T>(val nodes: List<T>, val weight: Double)
private data class Edge<T>(val to: T, val weight: Double)
private fun List<Edge<T>>.sumBy(selector: (Edge<T>) -> Double): Double {
return this.fold(0.0) { r, t -> r + selector(t) }
}
}
| 5 | Kotlin | 3 | 13 | 3b2c191876e58415d8221e511e6151a8747d15dc | 1,970 | algorithms-and-data-structures | Apache License 2.0 |
src/main/kotlin/day18/Day18.kt | Arch-vile | 317,641,541 | false | null | package day18
import readFile
fun main(args: Array<String>) {
val computations = readFile("./src/main/resources/day18Input.txt")
val sum = computations
.map { calculate(it) }
.sum()
println(sum)
}
fun calculate(originalCalculation: String): Long {
var calculation = originalCalculation.replace(" ", "")
while (hasParenthesis(calculation)) {
calculation = removeDeepestParenthesis(calculation)
}
return calculateSimple(calculation)
}
// Input be like "8 * 3 + 2 * 4"
fun calculateSimple(calculation: String): Long {
return calculation
.split("*")
.map { calculateSimpleSum(it) }
.reduce { acc, number -> acc * number }
}
// Input be like "3+3+1"
fun calculateSimpleSum(calculation: String): Long {
return calculation.split("+")
.map { it.toLong() }
.sum()
}
// Part be like "+3" or "*4"
fun combine(acc: Long, part: String): Long {
val operation = part.toCharArray()[0]
return when (operation) {
'+' -> acc + part.replace("+", "").toLong()
'*' -> acc * part.replace("*", "").toLong()
else -> part.toLong()
}
}
// "3 + 2 * 4" Will be like 3,+2,*4
fun split(calculation: String): List<String> {
return calculation
.replace("+", "%+")
.replace("*", "%*")
.split("%")
}
// Takes in "3 + ( 4 + (3 * 2))" and return "3 + (4 * 6)"
fun removeDeepestParenthesis(calculation: String): String {
val deepest =
"""\([^()]*\)""".toRegex()
.find(calculation)!!.value
val simpleCalculation = deepest
.replace("(", "")
.replace(")", "")
val value = calculateSimple(simpleCalculation)
return calculation.replace(deepest, value.toString())
}
fun hasParenthesis(calculation: String): Boolean {
return calculation.contains('(')
}
| 0 | Kotlin | 0 | 0 | 12070ef9156b25f725820fc327c2e768af1167c0 | 1,731 | adventOfCode2020 | Apache License 2.0 |
src/main/kotlin/Day2.kt | cbrentharris | 712,962,396 | false | {"Kotlin": 171464} | import kotlin.String
import kotlin.collections.List
object Day2 {
data class Cube(
val color: String,
val count: Int
)
data class Game(
val id: Int,
val cubePulls: List<List<Cube>>
) {
companion object {
fun parseGame(s: String): Game {
val (id, pulls) = s.split(":")
return Game(
id.trimStart(*"Game ".toCharArray()).toInt(),
pulls.split(";").map { cubeList ->
cubeList.split(",").map { cube ->
val (count, color) = cube.trimStart(' ').split(" ")
Cube(color, count.toInt())
}
}
)
}
}
}
fun part1(input: List<String>): String {
return sumOfGamesWithTarget(
input.map(Game::parseGame),
listOf(
Cube("red", 12), Cube("green", 13), Cube("blue", 14)
)
).toString()
}
private fun sumOfGamesWithTarget(input: List<Game>, targets: List<Cube>): Int {
val index = targets.associateBy { it.color }
return input.filter {
it.cubePulls.all {
it.all {
it.count <= index.getOrDefault(
it.color,
it
).count
}
}
}.sumOf { it.id }
}
fun part2(input: List<String>): String {
return sumOfPowersWithMinimums(input.map(Game::parseGame)).toString()
}
private fun sumOfPowersWithMinimums(games: List<Game>): Int {
return games.map {
val minimumCubesNeeded = it.cubePulls.flatten()
.groupBy { it.color }
.mapValues { it.value.maxBy { it.count } }
minimumCubesNeeded.map { it.value.count }.reduce { a, b -> a * b }
}.sum()
}
}
| 0 | Kotlin | 0 | 1 | f689f8bbbf1a63fecf66e5e03b382becac5d0025 | 1,959 | kotlin-kringle | Apache License 2.0 |
src/main/kotlin/year2022/Day11.kt | forketyfork | 572,832,465 | false | {"Kotlin": 142196} | package year2022
class Day11 {
data class Monkey(
val items: MutableList<Long>,
val operation: (Long) -> Long,
val divider: Long,
val trueThrow: Int,
val falseThrow: Int,
var inspections: Long = 0
)
private fun parseMonkeys(input: String) = input.split("\n\n")
.map { it.lines() }
.map { lines ->
Monkey(
ArrayDeque(lines[1]
.substringAfter("Starting items: ")
.split(", ")
.map { it.toLong() }),
lines[2]
.substringAfter("Operation: new = ")
.let {
if (it == "old * old") { a ->
a * a
} else if (it.startsWith("old * ")) { a ->
a * it.substringAfter("old * ").toLong()
} else { a ->
a + it.substringAfter("old + ").toLong()
}
},
lines[3].substringAfter("Test: divisible by ").toLong(),
lines[4].substringAfter("If true: throw to monkey ").toInt(),
lines[5].substringAfter("If false: throw to monkey ").toInt(),
)
}
private fun solution(monkeys: List<Monkey>, rounds: Int, worryReducer: (Long) -> Long): Long {
repeat(rounds) {
monkeys.forEach { monkey ->
while (monkey.items.isNotEmpty()) {
val item = monkey.items.removeFirst()
monkey.inspections++
val newItem = worryReducer(monkey.operation(item))
monkeys[if (newItem % monkey.divider == 0L) monkey.trueThrow else monkey.falseThrow]
.items.add(newItem)
}
}
}
return monkeys.sortedByDescending(Monkey::inspections).let { (first, second) ->
first.inspections * second.inspections
}
}
fun part1(input: String) = solution(parseMonkeys(input), 20) { it / 3 }
fun part2(input: String) = parseMonkeys(input).let { monkeys ->
val mod = monkeys.map { it.divider }.reduce(Long::times)
solution(monkeys, 10000) { it % mod }
}
}
| 0 | Kotlin | 0 | 0 | 5c5e6304b1758e04a119716b8de50a7525668112 | 2,305 | aoc-2022 | Apache License 2.0 |
src/Day04.kt | toninau | 729,811,683 | false | {"Kotlin": 8423} | fun main() {
data class Scratchcard(val index: Int, val winningNumbers: List<Int>, val guessedNumbers: List<Int>)
fun parse(input: List<String>): List<Scratchcard> {
return input.mapIndexed { index, line ->
val scratchcardNumbers = line.substringAfter(':').split('|').map { numbers ->
numbers.trim().split(' ')
.filter { it.isNotBlank() }
.map { it.toInt() }
}
Scratchcard(index = index, winningNumbers = scratchcardNumbers[0], guessedNumbers = scratchcardNumbers[1])
}
}
fun part1(scratchcards: List<Scratchcard>): Int {
return scratchcards.sumOf { scratchcard ->
scratchcard.winningNumbers.intersect(scratchcard.guessedNumbers.toSet())
.takeIf { it.isNotEmpty() }
?.fold(0.5) { sum, _ -> sum * 2 }?.toInt() ?: 0
}
}
fun part2(scratchcards: List<Scratchcard>): Int {
val deque = ArrayDeque(scratchcards)
deque.forEach {
val wonScratchcardsAmount = it.winningNumbers.intersect(it.guessedNumbers.toSet()).size
val wonScratchcards = scratchcards.slice(it.index + 1..it.index + wonScratchcardsAmount)
deque.addAll(wonScratchcards)
}
return deque.size
}
val input = readInput("Day04")
val scratchcards = parse(input)
println(part1(scratchcards))
println(part2(scratchcards))
}
| 0 | Kotlin | 0 | 0 | b3ce2cf2b4184beb2342dd62233b54351646722b | 1,457 | advent-of-code-2023 | Apache License 2.0 |
kotlin/src/main/kotlin/be/swsb/aoc2023/day3/Schematic.kt | Sch3lp | 724,797,927 | false | {"Kotlin": 44815, "Rust": 14075} | package be.swsb.aoc2023.day3
import be.swsb.aoc2023.Point
fun String.parse() =
Schematic(lines().flatMapIndexed { y, line ->
line.mapIndexed { x, char ->
Point(x, y) to char
}
}.toMap())
typealias Gear = Pair<Point, Set<Int>>
val Gear.ratio get() = this.second.map { it.toLong() }.reduce(Long::times)
class Schematic(private val points: Map<Point, Char>) {
fun allGears(): List<Gear> {
val numbersNextToAsterisks = allNumbersAdjacentToSymbol('*').toMap()
val allAsterisks = points.filterValues { it == '*' }.keys
return allAsterisks.map { asterisk ->
asterisk to numbersNextToAsterisks.filterValues { points -> points.any { point -> point in asterisk.neighbours } }.keys
}.filter { (_,numbers) -> numbers.size == 2 }
}
fun allNumbersAdjacentToSymbol(symbol: Char? = null): List<Pair<Int, List<Point>>> =
allNumbers().filter { (_, points) ->
points.any { point -> point.isAdjacentToASymbol(symbol) }
}
private fun Point.isAdjacentToASymbol(symbol: Char? = null) =
neighbours.any { neighbour ->
neighbour in this@Schematic.points.filterValues {
if (symbol == null) !it.isDigit() && it != '.'
else it == symbol
}.keys
}
fun allNumbers(): List<Pair<Int, List<Point>>> {
val maxX = points.maxOf { (k, _) -> k.x }
val maxY = points.maxOf { (k, _) -> k.y }
val numbers = mutableListOf<Pair<Int, List<Point>>>()
(0..maxY).forEach { y ->
(0..maxX).forEach { x ->
val point = Point(x, y)
if (point !in numbers.flatMap { it.second } && points[point]?.isDigit() == true) {
var curNumber = "${points[point]}"
val curPoints = mutableListOf(point)
var curPoint = point
while (curPoint.searchRight { p -> points[p]?.isDigit() == true } != null) {
val rightNeighbour = curPoint.searchRight { p -> points[p]?.isDigit() == true }
curNumber += "${points[rightNeighbour]}"
curPoints += rightNeighbour!!
curPoint = rightNeighbour!!
}
numbers += curNumber.toInt() to curPoints
}
}
}
return numbers
}
}
fun solve(string: String) = string.parse().allNumbersAdjacentToSymbol().sumOf { (n, _) -> n }
fun solve2(string: String) = string.parse().allGears().sumOf { it.ratio } | 0 | Kotlin | 0 | 1 | dec9331d3c0976b4de09ce16fb8f3462e6f54f6e | 2,596 | Advent-of-Code-2023 | MIT License |
src/Day03.kt | camina-apps | 572,935,546 | false | {"Kotlin": 7782} | import kotlin.math.floor
import kotlin.math.roundToInt
fun main() {
fun priorityOfItem(letter: Char): Int {
val offset = if (letter.isUpperCase()) 38 else 96
return letter.code - offset
}
fun findDuplicate(rucksack: String): Char {
val half = (rucksack.length / 2.0).roundToInt()
val firstCompartment = rucksack.slice(0 until half).toList()
val secondCompartment = rucksack.slice(half until rucksack.length).toList()
val duplicate = firstCompartment.intersect(secondCompartment)
return duplicate.first()
}
fun findDuplicateBetweenElves(elvesRucksacks: List<String>): Char {
val firstRucksack = elvesRucksacks.first().map { it.toChar() }
val secondRucksack = elvesRucksacks[1].map { it.toChar() }
val thirdRucksack = elvesRucksacks.last().map { it.toChar() }
val intersection = firstRucksack.intersect(secondRucksack)
val secondIntersection = thirdRucksack.intersect(intersection)
return secondIntersection.first()
}
fun part1(input: List<String>): Int {
return input.sumOf {
val item = findDuplicate(it)
priorityOfItem(item)
}
}
fun part2(input: List<String>): Int {
return input
.chunked(3)
.sumOf {
val badge = findDuplicateBetweenElves(it)
priorityOfItem(badge)
}
}
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 | fb6c6176f8c127e9d36aa0b7ae1f0e32b5c31171 | 1,639 | aoc_2022 | Apache License 2.0 |
y2023/src/main/kotlin/adventofcode/y2023/Day15.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2023
import adventofcode.io.AdventSolution
fun main() {
Day15.solve()
}
object Day15 : AdventSolution(2023, 15, " Lens Library") {
override fun solvePartOne(input: String) = input.splitToSequence(",").sumOf(::hash)
override fun solvePartTwo(input: String): Int {
val hashmap = List(256) { mutableListOf<Lens>() }
input.splitToSequence(",").forEach { instruction ->
val label = instruction.dropLast(if (instruction.last() == '-') 1 else 2)
val focalLength = instruction.last().digitToIntOrNull()
val box = hashmap[hash(label)]
val index = box.indexOfFirst { it.label == label }
when {
focalLength != null && index >= 0 -> box[index] = Lens(label, focalLength)
focalLength != null -> box += Lens(label, focalLength)
index >= 0 -> box.removeAt(index)
}
}
return hashmap.flatMapIndexed { box, content ->
content.mapIndexed { index, lens -> (box + 1) * (index + 1) * lens.focalLength }
}.sum()
}
}
private fun hash(label: String) = label.fold(0) { acc, ch -> (acc + ch.code) * 17 % 256 }
private data class Lens(val label: String, val focalLength: Int)
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,271 | advent-of-code | MIT License |
src/main/day04/Day04.kt | rolf-rosenbaum | 543,501,223 | false | {"Kotlin": 17211} | package day04
import readInput
import second
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
fun part1(input: List<String>): Int {
val guards = input.guards()
val mostAsleepGuard = guards.maxByOrNull {
it.sleepIntervals.sumOf { range -> range.second - range.first }
}!!
val sleepiestMinute = (0..59).maxByOrNull { minute ->
mostAsleepGuard.sleepIntervals.map { it.toIntRange() }.count { minute in it }
}!!
return mostAsleepGuard.id.toInt() * sleepiestMinute
}
fun part2(input: List<String>): Int {
val guards = input.guards()
val sleepiestMinuteList = guards.flatMap { guard ->
(0..59).map { minute ->
guard.id to guard.sleepIntervals.count { minute in it.toIntRange() }
}
}
val foo = sleepiestMinuteList.maxByOrNull { it.second }!!
val minute = sleepiestMinuteList.indexOf(foo) % 60
return foo.first.toInt() * minute
}
private fun List<String>.guards(): MutableList<Guard> {
val guards: MutableList<Guard> = mutableListOf()
var currentId = ""
var sleepStart = -1
map {
it.toTimedInput()
}.sortedBy { it.time }.forEach { line ->
if (line.action.contains("Guard")) {
val pattern = """ #(\d+) """.toRegex()
pattern.find(line.action)?.let {
currentId = it.value.substring(2).trim()
}
} else if (line.action.contains("asleep")) {
sleepStart = line.time.minute
} else if (line.action.contains("wakes")) {
val guard = guards.find { it.id == currentId }
if (guard == null) {
guards.add(Guard(currentId).addSleepInterval(sleepStart to line.time.minute))
} else {
guards.add(guard.addSleepInterval(sleepStart to line.time.minute))
guards.remove(guard)
}
}
}
return guards
}
fun main() {
val input = readInput("main/day04/Day04")
println(part1(input))
println(part2(input))
}
data class TimedInput(
val time: LocalDateTime,
val action: String
)
data class Guard(
val id: String,
val sleepIntervals: List<Pair<Int, Int>> = emptyList()
) {
fun addSleepInterval(interval: Pair<Int, Int>): Guard {
return copy(sleepIntervals = this.sleepIntervals + interval)
}
}
fun Pair<Int, Int>.toIntRange() = first until second
fun String.toTimedInput(): TimedInput {
val split = split("] ")
return TimedInput(
time = LocalDateTime.parse(split.first().substring(1), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")),
action = split.second()
)
} | 0 | Kotlin | 0 | 0 | dfd7c57afa91dac42362683291c20e0c2784e38e | 2,652 | aoc-2018 | Apache License 2.0 |
kotlin/src/main/kotlin/year2023/Day23.kt | adrisalas | 725,641,735 | false | {"Kotlin": 130217, "Python": 1548} | package year2023
fun main() {
val input = readInput("Day23")
Day23.part1(input).println()
Day23.part2(input).println()
}
object Day23 {
fun part1(trails: List<String>): Int {
val visited = List(trails.size) {
MutableList(trails[0].length) {
false
}
}
return trails.longestHike(
from = Point(0, 1),
target = Point(trails.size - 1, trails[0].length - 2),
visited = visited,
pathGenerator = pathGeneratorPart1(trails)
)
}
fun part2(trails: List<String>): Int {
val visited = List(trails.size) {
MutableList(trails[0].length) {
false
}
}
val from = Point(0, 1)
val target = Point(trails.size - 1, trails[0].length - 2)
return trails.longestHike(
from = Point(0, 1),
target = Point(trails.size - 1, trails[0].length - 2),
visited = visited,
pathGenerator = pathGeneratorPart2(trails, from, target)
)
}
private data class Point(val row: Int, val column: Int)
private fun List<String>.longestHike(
from: Point,
target: Point,
distance: Int = 0,
visited: List<MutableList<Boolean>>,
pathGenerator: (Point) -> List<Pair<Point, Int>>
): Int {
if (from == target) {
return distance
}
visited[from.row][from.column] = true
val max = pathGenerator(from)
.filter { (path, _) -> !visited[path.row][path.column] }
.maxOfOrNull { (neighbour, weight) ->
this.longestHike(
from = neighbour,
target = target,
visited = visited,
distance = distance + weight,
pathGenerator = pathGenerator
)
}
visited[from.row][from.column] = false
return max ?: 0
}
private fun pathGeneratorPart1(trails: List<String>): (Point) -> List<Pair<Point, Int>> {
return { point ->
val (row, column) = point
when (trails[row][column]) {
'>' -> listOf(Point(row, column + 1) to 1)
'<' -> listOf(Point(row, column - 1) to 1)
'v' -> listOf(Point(row + 1, column) to 1)
'^' -> listOf(Point(row - 1, column) to 1)
else -> {
trails.validPathsFrom(point).map { it to 1 }
}
}
}
}
private fun List<String>.validPathsFrom(point: Point): List<Point> {
val trails = this
val (row, column) = point
val paths = mutableListOf<Point>()
val canGoUp = (row - 1 >= 0) && trails[row - 1][column] != '#'
if (canGoUp) paths.add(Point(row - 1, column))
val canGoDown = (row + 1 < trails.size) && trails[row + 1][column] != '#'
if (canGoDown) paths.add(Point(row + 1, column))
val canGoLeft = (column - 1 >= 0) && trails[row][column - 1] != '#'
if (canGoLeft) paths.add(Point(row, column - 1))
val canGoRight = (column + 1 < trails[0].length) && trails[row][column + 1] != '#'
if (canGoRight) paths.add(Point(row, column + 1))
return paths
}
private fun pathGeneratorPart2(
trails: List<String>,
from: Point,
target: Point
): (Point) -> List<Pair<Point, Int>> {
val junctions = mutableMapOf(
from to mutableListOf<Pair<Point, Int>>(),
target to mutableListOf(),
)
for (row in trails.indices) {
for (column in trails[row].indices) {
if (trails[row][column] == '.') {
val point = Point(row, column)
if (trails.validPathsFrom(point).size > 2) {
junctions[point] = mutableListOf()
}
}
}
}
for (junctionEdge in junctions.keys) {
var edges = setOf(junctionEdge)
val visited = mutableSetOf(junctionEdge)
var distance = 0
while (edges.isNotEmpty()) {
distance++
edges = buildSet {
for (point in edges) {
trails.validPathsFrom(point)
.filter { it !in visited }
.forEach {
if (it in junctions) {
val next = junctions.getValue(junctionEdge)
next.add(it to distance)
} else {
add(it)
visited.add(it)
}
}
}
}
}
}
return { point -> junctions.getValue(point) }
}
}
| 0 | Kotlin | 0 | 2 | 6733e3a270781ad0d0c383f7996be9f027c56c0e | 5,004 | advent-of-code | MIT License |
src/algorithmdesignmanualbook/sorting/FastMedian.kt | realpacific | 234,499,820 | false | null | package algorithmdesignmanualbook.sorting
import utils.shouldBe
/**
* NO need to sort all the items.
* Just find the sort the items before the median index
* Using quicksort, find the partition.
* Then throw away the left partition if the median index lies in the right portion
* while calibrating the new median index.
*
* Similar to finding the kth smallest item in the unsorted list
*/
private fun fastMedian(array: IntArray, low: Int, high: Int, medianIndex: Int): Int {
val j = partition(array, low, high)
return if (j - low == medianIndex) {
array[j]
} else if (j - low > medianIndex) {
fastMedian(array, low, j - 1, medianIndex)
} else {
fastMedian(array, j + 1, high, medianIndex - j - 1 + low)
}
}
private fun quickSort(array: IntArray, low: Int, high: Int) {
if (low < high) {
val j = partition(array, low, high)
quickSort(array, low, j)
quickSort(array, j + 1, high)
}
}
private fun partition(array: IntArray, low: Int, high: Int): Int {
fun swap(index1: Int, index2: Int) {
val temp = array[index1]
array[index1] = array[index2]
array[index2] = temp
}
val pivot = array[low]
var i = low
var j = high
do {
while (array[i] <= pivot) i++
while (array[j] > pivot) j--
if (i < j) swap(i, j)
} while (i < j)
swap(low, j)
return j
}
fun midpointIndex(array: IntArray): Int {
return (array.size / 2)
}
fun main() {
run {
val original = intArrayOf(9, 1, 0, 2, 3, 4, 6, 8, 7, 10, 5)
val expected = original.sorted().toIntArray()
val quickSortInput = original.clone()
quickSort(quickSortInput, 0, original.lastIndex)
quickSortInput shouldBe expected
fastMedian(original, 0, original.lastIndex, midpointIndex(original)) shouldBe 5
}
run {
val original = intArrayOf(-90, 11, 30, 44, 20, 12, 22, -10, 1, 8, 90, 7, 10)
fastMedian(original, 0, original.lastIndex, midpointIndex(original)) shouldBe 11
}
}
| 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 2,063 | algorithms | MIT License |
solutions/aockt/y2023/Y2023D04.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2023
import aockt.util.parse
import io.github.jadarma.aockt.core.Solution
import kotlin.math.pow
object Y2023D04 : Solution {
/**
* Information about an elven scratchcard.
*
* @property id The ID.
* @property winningNumbers The winning numbers, written on the left of the pipe.
* @property cardNumbers The numbers you have, written on the right of the pipe.
* @property matchingCount How many [cardNumbers] are also [winningNumbers].
* @property value The estimated numerical value of the card based on its [matchingCount].
* @property prizeCards The IDs of the cards that can be claimed for this card based on its [matchingCount].
*/
private data class Scratchcard(val id: Int, val winningNumbers: Set<Int>, val cardNumbers: Set<Int>) {
val matchingCount = cardNumbers.intersect(winningNumbers).size
val value: Int = when (matchingCount) {
0 -> 0
else -> 2.0.pow(matchingCount - 1).toInt()
}
val prizeCards: Set<Int> = when (matchingCount) {
0 -> emptySet()
else -> List(size = matchingCount) { id + 1 + it }.toSet()
}
}
/** Parses the [input] and returns the scratchcards. */
private fun parseInput(input: String): Set<Scratchcard> = parse {
val cardRegex = Regex("""^Card\s+(\d+): ([\d ]+) \| ([\d ]+)$""")
fun parseNumberSet(input: String): Set<Int> =
input.split(' ').filter(String::isNotBlank).map(String::toInt).toSet()
input
.lineSequence()
.map { line -> cardRegex.matchEntire(line.also(::println))!!.destructured }
.map { (id, left, right) -> Scratchcard(id.toInt(), parseNumberSet(left), parseNumberSet(right)) }
.toSet()
}
/**
* Takes a set of [Scratchcard]s and collects other cards as prises until all cards cave been claimed.
* Assumes the set contains cards of consecutive IDs without gaps.
* Returns pairs of scratchcards and their total count, indexed by id.
*/
private fun Set<Scratchcard>.tradeIn(): Map<Int, Pair<Scratchcard, Int>> = buildMap {
this@tradeIn.forEach { put(it.id, it to 1) }
val maxLevel = keys.maxOf { it }
for (id in 1..maxLevel) {
require(id in keys) { "Invalid input. Missing info for card #$id/$maxLevel." }
}
for (id in 1..maxLevel) {
val (card, copies) = getValue(id)
for (prizeId in card.prizeCards.filter { it <= maxLevel }) {
put(prizeId, getValue(prizeId).run { copy(second = second + copies) })
}
}
}
override fun partOne(input: String) = parseInput(input).sumOf(Scratchcard::value)
override fun partTwo(input: String) = parseInput(input).tradeIn().values.sumOf { it.second }
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 2,863 | advent-of-code-kotlin-solutions | The Unlicense |
src/Day22.kt | sabercon | 648,989,596 | false | null | typealias Deck = List<Int>
typealias Decks = Pair<Deck, Deck>
private fun win1(card1: Int, card2: Int, deck1: Deck, deck2: Deck): Boolean {
return card1 > card2
}
private fun win2(card1: Int, card2: Int, deck1: Deck, deck2: Deck): Boolean {
return if (deck1.size < card1 || deck2.size < card2) card1 > card2
else playToEnd(::win2, deck1.take(card1) to deck2.take(card2)).first
}
private fun play(winFn: (Int, Int, Deck, Deck) -> Boolean, decks: Decks): Decks {
val card1 = decks.first[0]
val card2 = decks.second[0]
val deck1 = decks.first.drop(1)
val deck2 = decks.second.drop(1)
return if (winFn(card1, card2, deck1, deck2)) {
deck1 + card1 + card2 to deck2
} else {
deck1 to deck2 + card2 + card1
}
}
private fun playToEnd(winFn: (Int, Int, Deck, Deck) -> Boolean, decks: Decks, seen: MutableSet<Decks> = mutableSetOf())
: Pair<Boolean, Deck> {
val (deck1, deck2) = decks
if (decks in seen || deck2.isEmpty()) return true to deck1
if (deck1.isEmpty()) return false to deck2
seen.add(decks)
return playToEnd(winFn, play(winFn, decks), seen)
}
fun main() {
val (deck1, deck2) = readText("Day22").split("\n\n")
.map { deck -> deck.lines().drop(1).map { it.toInt() } }
playToEnd(::win1, deck1 to deck2).second
.reversed().mapIndexed { index, card -> (index + 1) * card }.sum().println()
playToEnd(::win2, deck1 to deck2).second
.reversed().mapIndexed { index, card -> (index + 1) * card }.sum().println()
}
| 0 | Kotlin | 0 | 0 | 81b51f3779940dde46f3811b4d8a32a5bb4534c8 | 1,536 | advent-of-code-2020 | MIT License |
src/day02/Day02.kt | skempy | 572,602,725 | false | {"Kotlin": 13581} | package day02
import day02.Result.DRAW
import day02.Result.LOSE
import day02.Result.WIN
import day02.TournamentOptions.Paper
import day02.TournamentOptions.Rock
import day02.TournamentOptions.Scissors
import readInputAsPairs
enum class Result(val points: Int) {
WIN(6),
DRAW(3),
LOSE(0)
}
sealed class TournamentOptions {
abstract fun versus(option: TournamentOptions): Int
abstract fun shapePoints(): Int
abstract fun roundEnd(result: Result): TournamentOptions
object Rock : TournamentOptions() {
private val outcomes = mapOf(
Rock to DRAW,
Paper to WIN,
Scissors to LOSE
)
override fun versus(option: TournamentOptions): Int = outcomes[option]!!.points.plus(option.shapePoints())
override fun shapePoints(): Int = 1
override fun roundEnd(result: Result): TournamentOptions {
val reversed = outcomes.entries.associate { (k, v) -> v to k }
return reversed[result]!!
}
}
object Paper : TournamentOptions() {
private val outcomes = mapOf(
Rock to LOSE,
Paper to DRAW,
Scissors to WIN
)
override fun versus(option: TournamentOptions): Int = outcomes[option]!!.points.plus(option.shapePoints())
override fun shapePoints(): Int = 2
override fun roundEnd(result: Result): TournamentOptions {
val reversed = outcomes.entries.associate { (k, v) -> v to k }
return reversed[result]!!
}
}
object Scissors : TournamentOptions() {
private val outcomes = mapOf(
Rock to WIN,
Paper to LOSE,
Scissors to DRAW
)
override fun versus(option: TournamentOptions): Int = outcomes[option]!!.points.plus(option.shapePoints())
override fun shapePoints(): Int = 3
override fun roundEnd(result: Result): TournamentOptions {
val reversed = outcomes.entries.associate { (k, v) -> v to k }
return reversed[result]!!
}
}
}
fun main() {
val rock = Pair("A", "X").toList()
val paper = Pair("B", "Y").toList()
val scissor = Pair("C", "Z").toList()
fun mapToTournamentOptions(option: String): TournamentOptions = when {
rock.contains(option) -> Rock
paper.contains(option) -> Paper
scissor.contains(option) -> Scissors
else -> TODO("YOU SELECTED THE WRONG OPTION YOU SILLY ELF")
}
fun mapToResultOptions(option: String): Result = when (option) {
"Z" -> WIN
"Y" -> DRAW
"X" -> LOSE
else -> TODO("YOU SELECTED THE WRONG OPTION YOU SILLY ELF")
}
fun part1(input: List<Pair<String, String>>): Int {
return input
.map { Pair(mapToTournamentOptions(it.first), mapToTournamentOptions(it.second)) }
.sumOf { round -> round.first.versus(round.second) }
}
fun part2(input: List<Pair<String, String>>): Int {
return input
.map { Pair(mapToTournamentOptions(it.first), mapToResultOptions(it.second)) }
.sumOf { round -> round.first.versus(round.first.roundEnd(round.second)) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInputAsPairs("Day02", "_test", ' ')
println("Test Part1: ${part1(testInput)}")
println("Test Part2: ${part2(testInput)}")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInputAsPairs("Day02", breakPoint = ' ')
println("Actual Part1: ${part1(input)}")
println("Actual Part2: ${part2(input)}")
check(part1(input) == 11841)
check(part2(input) == 13022)
}
| 0 | Kotlin | 0 | 0 | 9b6997b976ea007735898083fdae7d48e0453d7f | 3,712 | AdventOfCode2022 | Apache License 2.0 |
Advent-of-Code-2023/src/Day17.kt | Radnar9 | 726,180,837 | false | {"Kotlin": 93593} | import java.util.PriorityQueue
private const val AOC_DAY = "Day17"
private const val TEST_FILE = "${AOC_DAY}_test"
private const val INPUT_FILE = AOC_DAY
private data class Block(val row: Int, val col: Int, val dirRow: Int, val dirCol: Int, val heatLoss: Int, val dirCounter: Int, val path: List<Position> = listOf(Position(0, 0)))
private fun Block.withoutHeatLoss() = Block(row, col, dirRow, dirCol, 0, dirCounter)
/**
* Finds the shortest path from the top-left corner to the bottom-right corner of the city using Dijkstra's algorithm
* and the established rules.
*/
private fun part1(input: List<String>): Int {
val city = input.map { it.map { num -> num.digitToInt() } }
val pQueue = PriorityQueue<Block>(compareBy { it.heatLoss }).apply { add(Block(0, 0, 0, 0, 0, 0)) }
val seen = mutableSetOf<Block>()
var result = Block(0, 0, 0, 0, 0, 0)
while (pQueue.isNotEmpty()) {
val block = pQueue.poll()
if (block.row == city.size - 1 && block.col == city[0].size - 1) {
result = block
break
}
if (block.withoutHeatLoss() in seen) continue
seen.add(block.withoutHeatLoss())
// If the maximum of 3 consecutive blocks in the same direction is not reached, continue in the same direction
if (block.dirCounter < 3 && Pair(block.dirRow, block.dirCol) != Pair(0, 0)) {
val nextRow = block.row + block.dirRow
val nextCol = block.col + block.dirCol
if (nextRow in city.indices && nextCol in city[0].indices) {
val nextHeatLoss = block.heatLoss + city[nextRow][nextCol]
val path = mutableListOf<Position>().apply { addAll(block.path); add(Position(nextRow, nextCol)) }
pQueue.add(Block(nextRow, nextCol, block.dirRow, block.dirCol, nextHeatLoss, block.dirCounter + 1, path))
}
}
// Test all directions, unless the direction that goes to the back position and the one that's the same as the current one
for (dir in listOf(Pair(1, 0), Pair(-1, 0), Pair(0, 1), Pair(0, -1))) {
if (dir == Pair(-block.dirRow, -block.dirCol) || dir == Pair(block.dirRow, block.dirCol)) continue
val nextRow = block.row + dir.first
val nextCol = block.col + dir.second
if (nextRow in city.indices && nextCol in city[0].indices) {
val nextHeatLoss = block.heatLoss + city[nextRow][nextCol]
val path = mutableListOf<Position>().apply { addAll(block.path); add(Position(nextRow, nextCol)) }
pQueue.add(Block(nextRow, nextCol, dir.first, dir.second, nextHeatLoss, 1, path))
}
}
}
// Debug
if (false) {
val observePath = input.toMutableList()
for (pos in result.path) {
observePath[pos.row] = observePath[pos.row].replaceRange(pos.col, pos.col + 1, "#")
}
observePath.forEach { println(it) }
}
return result.heatLoss
}
/**
* Same as part1, but now it needs to move a minimum of four blocks in the same direction before it can turn
* (or even before it can stop at the end), and can move in the same direction for a maximum of 10 consecutive blocks.
*/
private fun part2(input: List<String>): Int {
val city = input.map { it.map { num -> num.digitToInt() } }
val pQueue = PriorityQueue<Block>(compareBy { it.heatLoss }).apply { add(Block(0, 0, 0, 0, 0, 0)) }
val seen = mutableSetOf<Block>()
while (pQueue.isNotEmpty()) {
val block = pQueue.poll()
if (block.row == city.size - 1 && block.col == city[0].size - 1 && block.dirCounter >= 4) {
return block.heatLoss
}
if (block.withoutHeatLoss() in seen) continue
seen.add(block.withoutHeatLoss())
if (block.dirCounter < 10 && Pair(block.dirRow, block.dirCol) != Pair(0, 0)) {
val nextRow = block.row + block.dirRow
val nextCol = block.col + block.dirCol
if (nextRow in city.indices && nextCol in city[0].indices) {
val nextHeatLoss = block.heatLoss + city[nextRow][nextCol]
pQueue.add(Block(nextRow, nextCol, block.dirRow, block.dirCol, nextHeatLoss, block.dirCounter + 1))
}
}
if (block.dirCounter < 4 && Pair(block.dirRow, block.dirCol) != Pair(0, 0)) continue
for (dir in listOf(Pair(1, 0), Pair(-1, 0), Pair(0, 1), Pair(0, -1))) {
if (dir == Pair(-block.dirRow, -block.dirCol) || dir == Pair(block.dirRow, block.dirCol)) continue
val nextRow = block.row + dir.first
val nextCol = block.col + dir.second
if (nextRow in city.indices && nextCol in city[0].indices) {
val nextHeatLoss = block.heatLoss + city[nextRow][nextCol]
pQueue.add(Block(nextRow, nextCol, dir.first, dir.second, nextHeatLoss, 1))
}
}
}
return 0
}
fun main() {
createTestFiles(AOC_DAY)
val testInput = readInputToList(TEST_FILE)
val part1ExpectedRes = 102
println("---| TEST INPUT |---")
println("* PART 1: ${part1(testInput)}\t== $part1ExpectedRes")
val part2ExpectedRes = 94
println("* PART 2: ${part2(testInput)}\t== $part2ExpectedRes\n")
val input = readInputToList(INPUT_FILE)
val improving = true
println("---| FINAL INPUT |---")
println("* PART 1: ${part1(input)}${if (improving) "\t== 767" else ""}")
println("* PART 2: ${part2(input)}${if (improving) "\t== 904" else ""}")
}
| 0 | Kotlin | 0 | 0 | e6b1caa25bcab4cb5eded12c35231c7c795c5506 | 5,536 | Advent-of-Code-2023 | Apache License 2.0 |
src/Day23.kt | mjossdev | 574,439,750 | false | {"Kotlin": 81859} | private enum class MoveDirection {
NORTH, SOUTH, WEST, EAST;
}
fun main() {
data class Point(val row: Int, val col: Int)
fun Point.next(direction: MoveDirection) = when (direction) {
MoveDirection.NORTH -> copy(row = row - 1)
MoveDirection.SOUTH -> copy(row = row + 1)
MoveDirection.WEST -> copy(col = col - 1)
MoveDirection.EAST -> copy(col = col + 1)
}
data class Move(val from: Point, val to: Point)
fun readElfPositions(input: List<String>) = buildSet {
input.forEachIndexed { rowIndex, row ->
row.forEachIndexed { colIndex, cell ->
if (cell == '#') add(Point(rowIndex, colIndex))
}
}
}
fun getProposedMoves(elfPositions: Set<Point>, directions: Iterable<MoveDirection>): List<Move> =
elfPositions.map { position ->
val stays = position.let {
val north = position.next(MoveDirection.NORTH)
val northWest = north.next(MoveDirection.WEST)
val northEast = north.next(MoveDirection.EAST)
val south = position.next(MoveDirection.SOUTH)
val southWest = south.next(MoveDirection.WEST)
val southEast = south.next(MoveDirection.EAST)
val west = position.next(MoveDirection.WEST)
val east = position.next(MoveDirection.EAST)
arrayOf(
north,
northWest,
northEast,
south,
southWest,
southEast,
west,
east
).none { it in elfPositions }
}
if (stays) return@map Move(position, position)
val direction = directions.firstOrNull {
val newPosition = position.next(it)
when (it) {
MoveDirection.NORTH, MoveDirection.SOUTH -> arrayOf(
newPosition,
newPosition.next(MoveDirection.WEST),
newPosition.next(MoveDirection.EAST)
).none { p -> p in elfPositions }
MoveDirection.WEST, MoveDirection.EAST -> arrayOf(
newPosition,
newPosition.next(MoveDirection.NORTH),
newPosition.next(MoveDirection.SOUTH)
).none { p -> p in elfPositions }
}
}
if (direction == null) Move(position, position) else Move(position, position.next(direction))
}
fun part1(input: List<String>): Int {
var elfPositions = readElfPositions(input)
val directions = ArrayDeque(MoveDirection.values().toList())
repeat(10) {
elfPositions = getProposedMoves(elfPositions, directions).groupBy { it.to }.asSequence()
.flatMap { (destination, moves) ->
if (moves.size == 1) listOf(destination) else moves.map { it.from }
}.toSet()
directions.addLast(directions.removeFirst())
}
return elfPositions.let {
(it.maxOf { p -> p.row } - it.minOf { p -> p.row } + 1) * (it.maxOf { p -> p.col } - it.minOf { p -> p.col } + 1) - it.size
}
}
fun part2(input: List<String>): Int {
var elfPositions = readElfPositions(input)
val directions = ArrayDeque(MoveDirection.values().toList())
var round = 0
while (true) {
++round
val moves = getProposedMoves(elfPositions, directions)
if (moves.all { (from, to) -> from == to }) return round
elfPositions = moves.groupBy { it.to }.asSequence()
.flatMap { (destination, moves) ->
if (moves.size == 1) listOf(destination) else moves.map { it.from }
}.toSet()
directions.addLast(directions.removeFirst())
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day23_test")
check(part1(testInput) == 110)
check(part2(testInput) == 20)
val input = readInput("Day23")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | afbcec6a05b8df34ebd8543ac04394baa10216f0 | 4,270 | advent-of-code-22 | Apache License 2.0 |
src/Day12.kt | rifkinni | 573,123,064 | false | {"Kotlin": 33155, "Shell": 125} | class Grid(val rows: List<List<Coordinate>>,
val start: Coordinate,
val end: Coordinate) {
private val nodes: MutableSet<Coordinate> = mutableSetOf(start)
fun run(): Int {
start.distanceFromStart = 0
nodes.removeAll(nodes)
nodes.add(start)
while (end.distanceFromStart == Integer.MAX_VALUE) {
val node = nodes.first()
val neighbors = getNeighbors(node)
.filter { it.value - node.value <= 1 } // the neighbor is no more than 1 character greater than the current
searchNeighbors(node, neighbors)
}
return end.distanceFromStart
}
fun run2(): Int {
end.distanceFromStart = 0
nodes.removeAll(nodes)
nodes.add(end)
while (nodes.isNotEmpty()) {
val node = nodes.first()
val neighbors = getNeighbors(node)
.filter { node.value - it.value <= 1 } // the neighbor is no more than 1 character greater than the current
searchNeighbors(node, neighbors)
}
return rows.flatten().filter { it.value == 'a' }.minOf { it.distanceFromStart }
}
private fun getNeighbors(coordinate: Coordinate): List<Coordinate> {
val neighbors: MutableList<Coordinate> = ArrayList()
if (coordinate.y - 1 >= 0) {
neighbors.add(rows[coordinate.y - 1][coordinate.x])
}
if (coordinate.y + 1 < rows.size) {
neighbors.add(rows[coordinate.y + 1][coordinate.x])
}
if (coordinate.x - 1 >= 0) {
neighbors.add(rows[coordinate.y][coordinate.x - 1])
}
if (coordinate.x + 1 < rows[0].size) {
neighbors.add(rows[coordinate.y][coordinate.x + 1])
}
return neighbors
}
private fun searchNeighbors(node: Coordinate, neighbors: List<Coordinate>) {
for (neighbor in neighbors) {
if (neighbor.distanceFromStart == Integer.MAX_VALUE) { // we have not yet visited this node
nodes.add(neighbor)
}
// update if there is a new shortest path
if (node.distanceFromStart + 1 < neighbor.distanceFromStart) {
neighbor.distanceFromStart = node.distanceFromStart + 1
}
}
nodes.remove(node)
}
}
data class Coordinate(val x: Int, val y: Int, val value: Char) {
var distanceFromStart = Int.MAX_VALUE
}
fun main() {
fun buildGrid(input: List<String>): Grid {
val rows: MutableList<List<Coordinate>> = ArrayList()
var start: Coordinate? = null
var end: Coordinate? = null
for (y in input.indices) {
val row: MutableList<Coordinate> = ArrayList()
for (x in input[y].indices) {
val coordinate: Coordinate
val value = input[y][x]
when(value) {
'S' -> {
coordinate = Coordinate(x, y, 'a')
start = coordinate
}
'E' -> {
coordinate = Coordinate(x, y, 'z')
end = coordinate
}
else -> {
coordinate = Coordinate(x, y, value)
}
}
row.add(coordinate)
}
rows.add(row)
}
return Grid(rows, start!!, end!!)
}
fun part1(input: List<String>): Int {
return buildGrid(input).run()
}
fun part2(input: List<String>): Int {
return buildGrid(input).run2()
}
// test if implementation meets criteria from the description, like:
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 | c2f8ca8447c9663c0ce3efbec8e57070d90a8996 | 3,909 | 2022-advent | Apache License 2.0 |
src/main/kotlin/day16.kt | gautemo | 433,582,833 | false | {"Kotlin": 91784} | import shared.getText
fun toBits(input: String): Bits{
return Bits(input.map { it.digitToInt(16).toString(2).padStart(4, '0') }.joinToString(""))
}
fun versionSum(packets: List<Packet>): Int{
return packets.sumOf { it.version + versionSum(it.subPackets) }
}
fun evaluatePackets(packet: Packet): Long{
return when(packet.typeID){
4 -> packet.literalValue!!
0 -> packet.subPackets.sumOf { evaluatePackets(it) }
1 -> packet.subPackets.fold(1) { sum, p -> sum * evaluatePackets(p) }
2 -> packet.subPackets.minOf { evaluatePackets(it) }
3 -> packet.subPackets.maxOf { evaluatePackets(it) }
5 -> if(evaluatePackets(packet.subPackets.first()) > evaluatePackets(packet.subPackets.last())) 1 else 0
6 -> if(evaluatePackets(packet.subPackets.first()) < evaluatePackets(packet.subPackets.last())) 1 else 0
7 -> if(evaluatePackets(packet.subPackets.first()) == evaluatePackets(packet.subPackets.last())) 1 else 0
else -> throw Exception("should match on type")
}
}
fun toPackets(bits: Bits, maxPackets: Int? = null): List<Packet>{
val packets = mutableListOf<Packet>()
while(!bits.isEmpty()){
if(maxPackets != null && packets.size == maxPackets) break
packets.add(toPacket(bits))
}
return packets
}
private fun toPacket(bits: Bits): Packet {
val version = bits.take(3).toInt(2)
val typeID = bits.take(3).toInt(2)
if(typeID == 4) {
var literalValue = ""
for (group in bits.value.chunked(5)) {
bits.drop(5)
literalValue += group.drop(1)
if (group.startsWith('0')) break
}
return Packet(version, typeID, literalValue.toLong(2))
}else{
val lengthType = bits.take(1)
return if(lengthType == "0"){
val L = bits.take(15).toInt(2)
val subpackets = toPackets(Bits(bits.take(L)))
Packet(version, typeID, subPackets = subpackets)
}else{
val L = bits.take(11).toInt(2)
val subpackets = toPackets(bits, L)
Packet(version, typeID, subPackets = subpackets)
}
}
}
data class Packet(val version: Int, val typeID: Int, val literalValue: Long? = null, val subPackets: List<Packet> = listOf())
data class Bits(var value: String){
fun take(n: Int): String {
val taken = value.take(n)
value = value.drop(n)
return taken
}
fun drop(n: Int){
value = value.drop(n)
}
fun isEmpty() = value.isEmpty() || value.all { it == '0' }
}
fun main(){
val input = getText("day16.txt")
val bits = toBits(input)
val packets = toPackets(bits)
val task1 = versionSum(packets)
println(task1)
val task2 = evaluatePackets(packets.first())
println(task2)
} | 0 | Kotlin | 0 | 0 | c50d872601ba52474fcf9451a78e3e1bcfa476f7 | 2,801 | AdventOfCode2021 | MIT License |
src/main/kotlin/days/y2023/day17/Day17.kt | jewell-lgtm | 569,792,185 | false | {"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123} | package days.y2023.day17
import util.InputReader
import java.util.PriorityQueue
import kotlin.math.abs
typealias PuzzleLine = String
typealias PuzzleInput = List<PuzzleLine>
class Day17(val input: PuzzleInput) {
val grid = input.toGrid()
fun partOne(): Int {
val queue =
makeQueue(
grid, listOf(
GameState(0, Direction.X, grid.start),
GameState(0, Direction.Y, grid.start)
)
)
var endState: GameState? = null
while (queue.isNotEmpty() && endState == null) {
val currBest = queue.poll()
if (currBest.position == grid.end) {
endState = currBest
continue
}
val direction = currBest.nextDirection
val toVisit = when (direction) {
Direction.X -> listOf(-3, -2, -1, 1, 2, 3).map { currBest.position.copy(x = currBest.position.x + it) }
Direction.Y -> listOf(-3, -2, -1, 1, 2, 3).map { currBest.position.copy(y = currBest.position.y + it) }
}
val nextStates = toVisit.mapNotNull { nextPosition ->
if (grid.positionIsValid(nextPosition) && nextPosition !in currBest.visited) {
val positionsBetween = currBest.position.positionsBetween(nextPosition)
val heatLost = currBest.heatLost + positionsBetween.sumOf { grid.heatLoss[it.y][it.x] }
val visited = currBest.visited + positionsBetween
GameState(heatLost, direction.other(), nextPosition, visited)
} else null
}
queue.addAll(nextStates)
}
requireNotNull(endState)
return endState.heatLost
}
}
// up to and including
private fun Position.positionsBetween(position: Position): Set<Position> {
val result = mutableSetOf<Position>()
require(position.y == this.y || position.x == this.x)
for (y in minOf(position.y, y)..maxOf(position.y, y)) {
result.add(Position(y, position.x))
}
for (x in minOf(position.x, x)..maxOf(position.x, x)) {
result.add(Position(this.y, x))
}
return result - this
}
private fun Grid2d.positionIsValid(position: Position): Boolean {
return position.y in heatLoss.indices && position.x in heatLoss[position.y].indices
}
data class Position(val y: Int, val x: Int)
fun Position.distanceTo(other: Position): Int {
return abs(y - other.y) + abs(x - other.x)
}
data class Grid2d(val heatLoss: List<List<Int>>)
enum class Direction {
X, Y
}
fun Direction.other(): Direction = when (this) {
Direction.X -> Direction.Y
Direction.Y -> Direction.X
}
data class GameState(
val heatLost: Int,
val nextDirection: Direction,
val position: Position,
val visited: Set<Position> = setOf(position),
)
private fun GameState.heuristic(end: Position, heatLossPerSquare: Float): Float {
// val heatLost = if (heatLost == 0) 1f else 1f / heatLost.toFloat()
val distance = if (position.distanceTo(end) == 0) 1f else 1f / position.distanceTo(end).toFloat()
// return (heatLost + distance) / 2f
return distance
}
val Grid2d.start: Position
get() = Position(y = 0, x = 0)
val Grid2d.end: Position
get() = Position(y = heatLoss.size - 1, x = heatLoss[0].size - 1)
val Grid2d.weights: List<List<Int>>
get() = heatLoss.map { line -> line.map { 10 - it } }
fun Grid2d.goalDistance(a: Position): Int {
return a.distanceTo(end)
}
fun PuzzleInput.toGrid(): Grid2d {
return Grid2d(map { line -> line.map { it.toString().toInt() } })
}
fun makeQueue(grid2d: Grid2d, startingValues: List<GameState> = emptyList()): PriorityQueue<GameState> {
val end = grid2d.end
val averageHeatLoss = grid2d.heatLoss.flatten().average()
val distances: MutableMap<Position, Double> = mutableMapOf()
fun MutableMap<Position, Double>.distance(position: Position) =
getOrPut(position) { averageHeatLoss * position.distanceTo(end).toDouble() }
return PriorityQueue<GameState> { a, b ->
val aCost = a.heatLost + ( distances.distance(a.position))
val bCost = b.heatLost + ( distances.distance(b.position))
aCost.compareTo(bCost)
}.also { it.addAll(startingValues) }
}
fun main() {
val year = 2023
val day = 17
val exampleInput: PuzzleInput = InputReader.getExampleLines(year, day)
val puzzleInput: PuzzleInput = InputReader.getPuzzleLines(year, day)
fun partOne(input: PuzzleInput) = Day17(input).partOne()
println("Example 1: ${partOne(InputReader.getExampleLines(year, day, "example1s"))}")
println("Example 1: ${partOne(exampleInput)}")
println("Part 1: ${partOne(puzzleInput)}")
}
| 0 | Kotlin | 0 | 0 | b274e43441b4ddb163c509ed14944902c2b011ab | 4,772 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/main/kotlin/day10/Day10.kt | alxgarcia | 435,549,527 | false | {"Kotlin": 91398} | package day10
import java.io.File
import java.util.LinkedList
// Poor man's Either -> Pair<A?, B?>
fun findMissingSequenceOrOffendingChar(line: String): Pair<Char?, String?> {
val missingSequence = LinkedList<Char>()
line.forEach { c ->
when (c) {
'(' -> missingSequence.addFirst(')')
'[' -> missingSequence.addFirst(']')
'{' -> missingSequence.addFirst('}')
'<' -> missingSequence.addFirst('>')
')', ']', '}', '>' -> if (missingSequence.firstOrNull() == c) missingSequence.removeFirst() else return (c to null)
}
}
return null to missingSequence.joinToString("")
}
private val syntaxCheckerScoreMap = mutableMapOf(
')' to 3,
']' to 57,
'}' to 1197,
'>' to 25137,
)
fun sumScoreOfCorruptedLines(lines: List<String>): Int =
lines
.map { findMissingSequenceOrOffendingChar(it).first }
.sumOf { maybeChar -> maybeChar?.let { c -> syntaxCheckerScoreMap[c] } ?: 0 }
private val autocompleteScoreMap = mapOf(
')' to 1,
']' to 2,
'}' to 3,
'>' to 4,
)
fun computeMiddleScoreOfIncompleteLinesMissingChars(lines: List<String>): Long {
fun computeScoreOfAutocomplete(sequence: String): Long =
sequence.map { autocompleteScoreMap[it]!! }.fold(0L) { acc, score -> (acc * 5L) + score }
val scores =
lines
.map { findMissingSequenceOrOffendingChar(it).second }
.filterNot { it.isNullOrBlank() }
.map { computeScoreOfAutocomplete(it!!) }
.sorted()
return scores[scores.size / 2]
}
fun main() {
File("./input/day10.txt").useLines { lines ->
val input = lines.toList()
println(sumScoreOfCorruptedLines(input))
println(computeMiddleScoreOfIncompleteLinesMissingChars(input))
}
}
| 0 | Kotlin | 0 | 0 | d6b10093dc6f4a5fc21254f42146af04709f6e30 | 1,698 | advent-of-code-2021 | MIT License |
app/src/main/kotlin/com/jamjaws/adventofcode/xxiii/day/Day09.kt | JamJaws | 725,792,497 | false | {"Kotlin": 30656} | package com.jamjaws.adventofcode.xxiii.day
import com.jamjaws.adventofcode.xxiii.readInput
class Day09 {
fun part1(text: List<String>): Int =
text.asSequence()
.map { line -> line.split(' ').map(String::toInt) }
.map { values -> getDifferenceSequences(values) }
.map { differences -> differences.reversed().map(List<Int>::last) }
.sumOf { lasts -> lasts.sum() }
fun part2(text: List<String>): Int =
text.asSequence()
.map { line -> line.split(' ').map(String::toInt) }
.map { values -> getDifferenceSequences(values) }
.map { differences -> differences.reversed() }
.map { differences -> differences.map(List<Int>::first) }
.map { firsts -> firsts.reduce { acc, value -> value - acc } }
.sum()
private tailrec fun getDifferenceSequences(
values: List<Int>,
accumulator: List<List<Int>> = emptyList(),
): List<List<Int>> =
if (values.all { it == 0 }) {
accumulator + listOf(values)
} else {
val diffValues = values.windowed(2, 1) { (a, b) -> b - a }
getDifferenceSequences(diffValues, accumulator + listOf(values))
}
}
fun main() {
val answer1 = Day09().part1(readInput("Day09"))
println(answer1)
val answer2 = Day09().part2(readInput("Day09"))
println(answer2)
}
| 0 | Kotlin | 0 | 0 | e2683305d762e3d96500d7268e617891fa397e9b | 1,415 | advent-of-code-2023 | MIT License |
2022/src/Day14.kt | Saydemr | 573,086,273 | false | {"Kotlin": 35583, "Python": 3913} | package src
fun main() {
val walls = mutableSetOf<Pair<Int,Int>>()
val sands = mutableSetOf<Pair<Int,Int>>()
readInput("input14")
.map { it.trim().split("->") }
.map { it.map { nane -> nane.trim().split(",") }
.map { list -> list.map { str -> str.toInt() } } }
.map { it.windowed(2)
.forEach { pairs ->
if (pairs[0][0] == pairs[1][0]) {
val min = if (pairs[0][1] < pairs[1][1]) pairs[0][1] else pairs[1][1]
val max = if (pairs[0][1] < pairs[1][1]) pairs[1][1] else pairs[0][1]
walls.addAll(List(max - min + 1) { pairs[0][0] }.zip((min..max)))
}
else {
val min = if (pairs[0][0] < pairs[1][0]) pairs[0][0] else pairs[1][0]
val max = if (pairs[0][0] < pairs[1][0]) pairs[1][0] else pairs[0][0]
walls.addAll((min..max).zip(List(max - min + 1) { pairs[0][1] }))
}
}
}
val height = walls.maxBy { it.second }.second + 2
val minWidth = walls.minBy { it.first }.first - height - 2
val maxWidth = walls.maxBy { it.first }.first + height + 2
// part 2
walls.addAll((minWidth..maxWidth).zip(List(maxWidth - minWidth + 1) { height }))
var dfs = false
val startPos = Pair(500, 0)
fun dfs(pos: Pair<Int,Int>): Boolean {
dfs = dfs || pos.second > height || sands.contains(Pair(500,0)) // remove last `or` to get part 1
if (dfs || sands.contains(pos) || walls.contains(pos))
return dfs
if (!(dfs(Pair(pos.first, pos.second + 1))
|| dfs(Pair(pos.first - 1, pos.second + 1))
|| dfs(Pair(pos.first + 1, pos.second + 1)))
)
sands.add(pos)
return true
}
while (!dfs)
dfs(startPos)
println(sands.size)
}
| 0 | Kotlin | 0 | 1 | 25b287d90d70951093391e7dcd148ab5174a6fbc | 1,915 | AoC | Apache License 2.0 |
src/Day5.kt | sitamshrijal | 574,036,004 | false | {"Kotlin": 34366} | import java.util.Stack
fun main() {
fun parse(input: List<String>): Pair<List<Stack<Char>>, List<CrateMove>> {
val stacks = input.filterNot {
it.startsWith("move") || it.isEmpty()
}
val map = mutableMapOf<Int, Stack<Char>>()
(stacks.lastIndex - 1 downTo 0).forEach {
val crates = stacks[it]
val splits = crates.split(" ")
var stackNumber = 1
var spaceCount = 0
splits.forEach { split ->
if (split.isEmpty()) {
spaceCount++
} else {
val value = map.getOrDefault(stackNumber, Stack<Char>())
value.push(split[1])
map[stackNumber++] = value
}
if (spaceCount == 4) {
stackNumber++
// Reset
spaceCount = 0
}
}
}
val regex = """move (\d+) from (\d) to (\d)""".toRegex()
val moves = input.filter { it.startsWith("move") }.map {
val (match1, match2, match3) = regex.matchEntire(it)!!.destructured
val count = match1.toInt()
val start = match2.toInt()
val end = match3.toInt()
CrateMove(map[start]!!, map[end]!!, count)
}
return map.values.toList() to moves
}
fun part1(input: List<String>): String {
val (stacks, moves) = parse(input)
moves.forEach { (start, end, count) ->
repeat(count) {
end.push(start.pop())
}
}
return stacks.map { it.peek() }.joinToString(separator = "")
}
fun part2(input: List<String>): String {
val (stacks, moves) = parse(input)
moves.forEach { (start, end, count) ->
val toAdd = buildList {
repeat(count) {
add(start.pop())
}
}
toAdd.reversed().forEach {
end.push(it)
}
}
return stacks.map { it.peek() }.joinToString(separator = "")
}
val input = readInput("input5")
println(part1(input))
println(part2(input))
}
/**
* Move [count] crates from the [start] stack to the [end] stack.
*/
data class CrateMove(val start: Stack<Char>, val end: Stack<Char>, val count: Int)
| 0 | Kotlin | 0 | 0 | fd55a6aa31ba5e3340be3ea0c9ef57d3fe9fd72d | 2,392 | advent-of-code-2022 | Apache License 2.0 |
src/Day20.kt | mikrise2 | 573,939,318 | false | {"Kotlin": 62406} | fun mix(list: List<Pair<Long, Long>>): List<Pair<Long, Long>> {
val mixedList = list.toMutableList()
val size = list.size
repeat(size) { index ->
val currentIndex = mixedList.indexOfFirst { it.first == index.toLong() }
val elem = mixedList.removeAt(currentIndex)
val newIndex = (currentIndex + elem.second) % (size - 1)
mixedList.add((newIndex + if (newIndex <= 0) (size - 1) else 0).toInt(), elem)
}
return mixedList
}
fun main() {
fun part1(input: List<String>): Long {
val list = mix(input.mapIndexed { index, it ->
Pair(index.toLong(), it.toLong())
}.toList())
val zeroIndex = list.indexOfFirst { it.second == 0L }.toLong()
val size = list.size.toLong()
return listOf(1000L, 2000L, 3000L).sumOf { list[((zeroIndex + it) % size).toInt()].second }
}
fun part2(input: List<String>): Long {
var list = input.mapIndexed { index, it ->
Pair(index.toLong(), it.toLong())
}.toList().map { Pair(it.first, it.second * 811589153L) }
repeat(10) {
list = mix(list)
}
val zeroIndex = list.indexOfFirst { it.second == 0L }.toLong()
val size = list.size.toLong()
return listOf(1000L, 2000L, 3000L).sumOf { list[((zeroIndex + it) % size).toInt()].second }
}
val input = readInput("Day20")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d5d180eaf367a93bc038abbc4dc3920c8cbbd3b8 | 1,437 | Advent-of-code | Apache License 2.0 |
src/main/kotlin/de/pgebert/aoc/days/Day02.kt | pgebert | 724,032,034 | false | {"Kotlin": 65831} | package de.pgebert.aoc.days
import de.pgebert.aoc.Day
class Day02(input: String? = null) : Day(2, "Cube Conundrum", input) {
override fun partOne() =
inputList.mapNotNull(::getGameIdOfValidInputLine).sum()
private fun parseGameId(game: String): Int {
return game.filter { it.isDigit() }.toInt()
}
private fun parseSubsets(indicators: String): List<Pair<String, Int>> {
return indicators.split(";", ",").map {
it.filter { it.isLetter() } to it.filter { it.isDigit() }.toInt()
}
}
private fun isValidSubset(subset: Pair<String, Int>): Boolean {
val (color, count) = subset
return when {
color == "red" && count <= 12 -> true
color == "green" && count <= 13 -> true
color == "blue" && count <= 14 -> true
else -> false
}
}
private fun getGameIdOfValidInputLine(line: String): Int? {
val (game, indicators) = line.split(":")
val gameId = parseGameId(game)
val subsets = parseSubsets(indicators)
val valid = subsets.all(::isValidSubset)
return if (valid) gameId else null
}
override fun partTwo() = inputList.mapNotNull { line ->
val indicators = line.split(":").last()
val subsets = parseSubsets(indicators)
var (minRed, minGreen, minBlue) = getMinSetOfCubes(subsets)
minRed * minGreen * minBlue
}.sum()
private fun getMinSetOfCubes(subsets: List<Pair<String, Int>>): Triple<Int, Int, Int> {
var countMap = mutableMapOf("red" to 0, "green" to 0, "blue" to 0)
subsets.forEach { (color, count) ->
if (count > countMap[color]!!) countMap[color] = count
}
return Triple(countMap["red"]!!, countMap["green"]!!, countMap["blue"]!!)
}
}
| 0 | Kotlin | 1 | 0 | a30d3987f1976889b8d143f0843bbf95ff51bad2 | 1,833 | advent-of-code-2023 | MIT License |
src/Day07.kt | Excape | 572,551,865 | false | {"Kotlin": 36421} | class Dir {
var size = 0
val children = mutableSetOf<Dir>()
fun parseLs(input: String) {
this.size = input.split("\n").drop(1)
.filterNot { it.startsWith("dir") }
.fold(0) { totalSize, line -> totalSize + line.split(" ").first().toInt() }
}
fun addChild() = Dir().also { children.add(it) }
val totalSize: Int
get() = size + children.sumOf { it.totalSize }
}
fun main() {
fun parseDirectories(input: String): List<Dir> {
val rootDir = Dir()
val workingDirs = ArrayDeque<Dir>()
val dirs = mutableListOf(rootDir)
workingDirs.addFirst(rootDir)
input.split("\n$ ").drop(1).forEach { cmd ->
when {
cmd.startsWith("ls") -> {
workingDirs.first().parseLs(cmd)
}
cmd.startsWith("cd") -> {
when (cmd.split(" ")[1]) {
".." -> {
workingDirs.removeFirst()
}
else -> {
val newDir = workingDirs.first().addChild()
dirs.add(newDir)
workingDirs.addFirst(newDir)
}
}
}
}
}
return dirs
}
fun part1(input: String): Int {
val dirs = parseDirectories(input)
return dirs.map { it.totalSize }.filter { it <= 100000 }.sum()
}
fun part2(input: String): Int {
val dirs = parseDirectories(input)
val capacity = 70000000
val requiredSpace = 30000000
val rootDir = dirs[0]
val unusedSize = capacity - rootDir.totalSize
val minSize = requiredSpace - unusedSize
return dirs.map { it.totalSize }.sorted().first { it >= minSize }
}
val testInput = readInputAsString("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInputAsString("Day07")
println("part 1: ${part1(input)}")
println("part 2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | a9d7fa1e463306ad9ea211f9c037c6637c168e2f | 2,134 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/net/wrony/aoc2023/a5/Main.kt | kopernic-pl | 727,133,267 | false | {"Kotlin": 52043} | package net.wrony.aoc2023.a5
import kotlin.io.path.Path
import kotlin.io.path.readText
data class MappingRange(val destStart: Long, val sourceStart: Long, val length: Long) {
fun mapsValue(l: Long): Boolean = l in sourceStart..<sourceStart + length
fun mapSourceToDestVal(l: Long): Long {
return destStart + (l - sourceStart)
}
}
fun main() {
fun listMappings(groups: List<List<String>>): List<List<MappingRange>> =
groups.drop(1).map { map ->
map.drop(1).map { mapping -> mapping.split(" ").map { it.toLong() } }
.map { (a, b, c) -> MappingRange(a, b, c) }
}
Path("src/main/resources/5.txt").readText().let { input ->
input.lines()[0]
input.lines().mapIndexed { idx, l -> idx to l.isEmpty() }.filter { (idx, empty) -> !empty }
.map { (idx, _) -> idx }
var counter = 0
input.lines().groupBy {
if (it.isBlank()) counter++
counter
}.values.map { group -> group.filter { it.isNotBlank() && it.isNotEmpty() } }
.also { groups ->
val seeds = groups[0][0].removePrefix("seeds: ").split(" ").map { it.toLong() }
val maps = listMappings(groups)
seeds.minOfOrNull { seed ->
maps.fold(seed) { acc, ranges ->
ranges.find { it.mapsValue(acc) }?.mapSourceToDestVal(acc) ?: acc
}
}.let { println(it) }
}.also { groups ->
val seedRanges =
groups[0][0].removePrefix("seeds: ").split(" ").map { it.toLong() }.asSequence()
.chunked(2).map { (nb, size) -> nb..<(nb + size) }.sortedBy { r -> r.last - r.first }.toList()
val maps = listMappings(groups)
var minLoc = Long.MAX_VALUE
println()
println(seedRanges.toList())
seedRanges
.asSequence()
.forEachIndexed { rangeIdx, seedRange ->
println("Range $seedRange")
seedRange.forEach { seed ->
when (rangeIdx) {
0 -> {
val loc = maps.fold(seed) { acc, ranges ->
ranges.find { it.mapsValue(acc) }?.mapSourceToDestVal(acc)
?: acc
}
if (loc < minLoc) {
minLoc = loc; println("Min seed $seed")
}
}
else -> {
if (!(seedRanges.subList(0, rangeIdx - 1)
.any { it.contains(seed) })
) {
val loc = maps.fold(seed) { acc, ranges ->
ranges.find { it.mapsValue(acc) }
?.mapSourceToDestVal(acc) ?: acc
}
if (loc < minLoc) {
minLoc = loc; println("Min seed $seed, loc $loc")
}
}
}
}
}
}
println(minLoc)
}
//194601276 -- too high
//108956227 OK
}
} | 0 | Kotlin | 0 | 0 | 1719de979ac3e8862264ac105eb038a51aa0ddfb | 3,671 | aoc-2023-kotlin | MIT License |
src/main/kotlin/day2/Day2.kt | stoerti | 726,442,865 | false | {"Kotlin": 19680} | package io.github.stoerti.aoc.day2
import io.github.stoerti.aoc.IOUtils
fun main(args: Array<String>) {
val redLimit = 12
val greenLimit = 13
val blueLimit = 14
val games = IOUtils.readInput("day_2_input")
.map { Game.fromString(it) }
val result1 = games
.filter {
it.maxRed() <= redLimit && it.maxBlue() <= blueLimit && it.maxGreen() <= greenLimit
}
.onEach { println("${it.gameId} - maxRed: ${it.maxRed()}, maxBlue: ${it.maxBlue()}, maxGreen: ${it.maxGreen()}, ") }
.sumOf { it.gameId }
val result2 = games
.onEach { println("${it.gameId} - maxRed: ${it.maxRed()}, maxBlue: ${it.maxBlue()}, maxGreen: ${it.maxGreen()}, ") }
.map {
it.maxRed() * it.maxBlue() * it.maxGreen()
}
.sumOf { it }
println("Result Puzzle 1: $result1")
println("Result Puzzle 2: $result2")
}
data class Game(
val gameId: Int,
val rounds: List<GameRound>,
) {
companion object {
fun fromString(inputLine: String): Game {
val gameId = inputLine.split(":")[0].removePrefix("Game ").toInt()
val gameRounds = inputLine.split(":")[1].split(";").map { it.trim() }.map { GameRound.fromString(it) }
return Game(gameId, gameRounds)
}
}
fun maxRed(): Int = rounds.maxOf { it.red }
fun maxBlue(): Int = rounds.maxOf { it.blue }
fun maxGreen(): Int = rounds.maxOf { it.green }
}
data class GameRound(
val red: Int,
val blue: Int,
val green: Int,
) {
companion object {
fun fromString(input: String): GameRound {
val result = input.split(",").map { it.trim() }
return GameRound(
red = result.find { it.contains("red") }?.let { it.substring(0, it.indexOf(" ")).toInt() } ?: 0,
blue = result.find { it.contains("blue") }?.let { it.substring(0, it.indexOf(" ")).toInt() } ?: 0,
green = result.find { it.contains("green") }?.let { it.substring(0, it.indexOf(" ")).toInt() } ?: 0,
)
}
}
}
| 0 | Kotlin | 0 | 0 | 05668206293c4c51138bfa61ac64073de174e1b0 | 1,923 | advent-of-code | Apache License 2.0 |
src/main/kotlin/aoc/year2023/Day07.kt | SackCastellon | 573,157,155 | false | {"Kotlin": 62581} | package aoc.year2023
import aoc.Puzzle
/**
* [Day 7 - Advent of Code 2023](https://adventofcode.com/2023/day/7)
*/
object Day07 : Puzzle<Int, Int> {
override fun solvePartOne(input: String): Int = input.lineSequence()
.map { it.split(' ').let { (a, b) -> a.toHand() to b.toInt() } }
.sortedByDescending { (hand, _) -> hand }
.mapIndexed { index, (_, bid) -> bid * (index + 1) }
.sum()
override fun solvePartTwo(input: String): Int = TODO()
private fun String.toHand() = map(Card.labelCache::getValue).let(::Hand)
private fun typeOf(cards: List<Card>): Type {
val matchingCount = cards.groupingBy { it }.eachCount().values.sortedDescending()
return Type.entries.first { type -> matchingCount.zip(type.matchingCount).all { (a, b) -> a == b } }
}
private enum class Card(val label: Char) {
A('A'),
K('K'),
Q('Q'),
J('J'),
T('T'),
NINE('9'),
EIGHT('8'),
SEVEN('7'),
SIX('6'),
FIVE('5'),
FOUR('4'),
THREE('3'),
TWO('2');
override fun toString(): String = label.toString()
companion object {
internal val labelCache = entries.associateBy { it.label }
}
}
private class Hand(private val cards: List<Card>) : Comparable<Hand> {
private val type: Type = typeOf(cards)
override fun compareTo(other: Hand): Int = COMPARATOR.compare(this, other)
override fun toString(): String = "Hand(cards=$cards, type=$type)"
companion object {
private val COMPARATOR = compareBy(Hand::type)
.thenComparing<Card> { it.cards[0] }
.thenComparing<Card> { it.cards[1] }
.thenComparing<Card> { it.cards[2] }
.thenComparing<Card> { it.cards[3] }
.thenComparing<Card> { it.cards[4] }
}
}
private enum class Type(val matchingCount: List<Int>) {
FIVE_KIND(listOf(5)),
FOUR_KIND(listOf(4, 1)),
FULL_HOUSE(listOf(3, 2)),
THREE_KIND(listOf(3)),
TWO_PAIR(listOf(2, 2)),
ONE_PAIR(listOf(2)),
HIGH_CARD(listOf(1)),
}
}
| 0 | Kotlin | 0 | 0 | 75b0430f14d62bb99c7251a642db61f3c6874a9e | 2,214 | advent-of-code | Apache License 2.0 |
src/2022/Day13.kt | ttypic | 572,859,357 | false | {"Kotlin": 94821} | package `2022`
import readInput
import splitBy
fun main() {
fun part1(input: List<String>): Int {
return input.splitBy { it.isEmpty() }.mapIndexed { index, (left, right) ->
val leftPacket = Packet.parsePacket(left)
val rightPacket = Packet.parsePacket(right)
if (leftPacket <= rightPacket) {
index + 1
} else {
0
}
}.sum()
}
fun part2(input: List<String>): Int {
val packets = input.filter { it.isNotBlank() }.map { Packet.parsePacket(it) }
val signal1 = ListPacket(mutableListOf(ListPacket(mutableListOf(IntPacket(2)))))
val signal2 = ListPacket(mutableListOf(ListPacket(mutableListOf(IntPacket(6)))))
val sorted = (packets + signal1 + signal2).sorted()
return (sorted.indexOf(signal1) + 1) * (sorted.indexOf(signal2) + 1)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test")
println(part1(testInput))
println(part2(testInput))
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
sealed interface Packet: Comparable<Packet> {
companion object {
fun parsePacket(packetPresentation: String): Packet {
val tokens = "\\d+|]|\\[".toRegex().findAll(packetPresentation).map { it.value }
if (tokens.first() != "[") {
return IntPacket(tokens.first().toInt())
}
val listPacket = ListPacket(mutableListOf())
val stack = ArrayDeque<ListPacket>()
stack.addFirst(listPacket)
tokens.drop(1).forEach {
when(it) {
"[" -> {
stack.addFirst(ListPacket(mutableListOf()))
}
"]" -> {
val currentPacket = stack.removeFirst()
stack.firstOrNull()?.value?.add(currentPacket)
}
else -> {
stack.first().value.add(IntPacket(it.toInt()))
}
}
}
return listPacket
}
}
}
data class IntPacket(val value: Int): Packet {
override fun compareTo(other: Packet): Int {
return when(other) {
is IntPacket -> {
value - other.value
}
is ListPacket -> {
ListPacket(mutableListOf(this)).compareTo(other)
}
}
}
override fun toString(): String {
return value.toString()
}
}
data class ListPacket(val value: MutableList<Packet>): Packet {
override fun compareTo(other: Packet): Int {
when(other) {
is IntPacket -> {
return this.compareTo(ListPacket(mutableListOf(other)))
}
is ListPacket -> {
value.forEachIndexed { index, packet ->
if (index >= other.value.size) return 1
val compare = packet.compareTo(other.value[index])
if (compare < 0) return -1
if (compare > 0) return 1
}
return value.size - other.value.size
}
}
}
override fun toString(): String {
return value.joinToString(separator = ",", prefix = "[", postfix = "]")
}
}
| 0 | Kotlin | 0 | 0 | b3e718d122e04a7322ed160b4c02029c33fbad78 | 3,491 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day03.kt | orirabi | 574,124,632 | false | {"Kotlin": 14153} | val priorities = generateSequence('a' to 1) {
when (it.first) {
'z' -> 'A' to it.second + 1
'Z' -> null
else -> it.first + 1 to it.second + 1
}
}
.toMap()
fun main() {
fun getDuplicate(pack: String): Char {
val compartments = pack.chunked(pack.length / 2)
check(compartments.size == 2)
check(compartments[0].length == compartments[1].length)
val chars = compartments[0].toSet()
return compartments[1].asSequence()
.filter { it in chars }
.first()
}
fun getPriority(pack: String): Int {
return priorities[getDuplicate(pack)]!!
}
fun getPriorities(input: List<String>): Int {
return input.asSequence().map { getPriority(it) }.sum()
}
fun findBadge(group: List<String>): Char {
check(group.size == 3)
return group.map { it.toSet() }
.reduce { a: Set<Char>, b: Set<Char> -> a.intersect(b) }
.single()
}
fun getBadgePriority(group: List<String>): Int {
return priorities[findBadge(group)]!!
}
fun getBadges(input: List<String>): Int {
return input.asSequence().chunked(3)
.map { getBadgePriority(it) }
.sum()
}
val packs = readInput("Day03")
println(getPriorities(packs))
println(getBadges(packs))
}
| 0 | Kotlin | 0 | 0 | 41cb10eac3234ae77ed7f3c7a1f39c2f9d8c777a | 1,360 | AoC-2022 | Apache License 2.0 |
src/aoc23/Day02.kt | mihassan | 575,356,150 | false | {"Kotlin": 123343} | @file:Suppress("PackageDirectoryMismatch")
package aoc23.day02
import java.lang.Integer.max
import lib.Solution
enum class Cube {
RED, GREEN, BLUE;
companion object {
fun parse(cubeStr: String) = Cube.valueOf(cubeStr.uppercase())
}
}
data class Cubes(val cubes: Map<Cube, Int>) {
fun isPossible(maxCubes: Cubes) = cubes.all { (cube, count) ->
count <= (maxCubes.cubes[cube] ?: Int.MIN_VALUE)
}
fun power() = Cube.values().fold(1) { acc, cube -> acc * (cubes[cube] ?: 0) }
companion object {
fun parse(cubesStr: String) = cubesStr.split(", ").associate {
val (countPart, cubePart) = it.split(" ")
Cube.parse(cubePart) to countPart.toInt()
}.let {
Cubes(it)
}
}
}
data class Game(val id: Int, val cubesList: List<Cubes>) {
fun isPossible(maxCubes: Cubes) = cubesList.all { it.isPossible(maxCubes) }
fun power() = cubesList
.flatMap { it.cubes.entries }
.groupingBy { it.key }
.fold(0) { acc, (_, count) -> max(acc, count) }
.let { Cubes(it) }
.power()
companion object {
fun parse(gameStr: String): Game {
val (idPart, rest) = gameStr.split(": ")
val id = idPart.substringAfter("Game ").toInt()
val cubesList = rest.split("; ").map { Cubes.parse(it) }
return Game(id, cubesList)
}
}
}
typealias Input = List<Game>
typealias Output = Int
private val solution = object : Solution<Input, Output>(2023, "Day02") {
override fun parse(input: String): Input = input.lines().map { Game.parse(it) }
override fun format(output: Output): String = "$output"
override fun part1(input: Input): Output =
input.filter { it.isPossible(MAX_CUBES) }.sumOf { it.id }
override fun part2(input: Input): Output = input.sumOf { it.power() }
val MAX_CUBES = Cubes(mapOf(Cube.RED to 12, Cube.GREEN to 13, Cube.BLUE to 14))
}
fun main() = solution.run()
| 0 | Kotlin | 0 | 0 | 698316da8c38311366ee6990dd5b3e68b486b62d | 1,873 | aoc-kotlin | Apache License 2.0 |
day07/kotlin/corneil/src/main/kotlin/solution.kt | timgrossmann | 224,991,491 | true | {"HTML": 2739009, "Python": 169603, "Java": 157274, "Jupyter Notebook": 116902, "TypeScript": 113866, "Kotlin": 89503, "Groovy": 73664, "Dart": 47763, "C++": 43677, "CSS": 34994, "Ruby": 27091, "Haskell": 26727, "Scala": 11409, "Dockerfile": 10370, "JavaScript": 6496, "PHP": 4152, "Go": 2838, "Shell": 2493, "Rust": 2082, "Clojure": 567, "Tcl": 46} | package com.github.corneil.aoc2019.day7
import com.github.corneil.aoc2019.intcode.Program
import com.github.corneil.aoc2019.intcode.readProgram
import java.io.File
fun phaseAmplifierTest(code: List<Long>, sequence: LongArray): Long {
val program = Program(code)
var amplifierInput = 0L
sequence.forEach { phase ->
val result = program.executeProgram(listOf(phase, amplifierInput))
amplifierInput = result.outputs().first()
}
return amplifierInput
}
fun phaseAmplifierFeedback(code: List<Long>, sequence: LongArray): Long {
val program = Program(code)
var lastOutput = 0L
var amplifierInput = listOf(0L)
val amplifiers = sequence.map { phase -> program.createProgram(listOf(phase)) }
do {
amplifiers.forEach { amp ->
if (!amp.isHalted()) {
val result = amp.executeUntilOutput(amplifierInput)
if (result.isNotEmpty()) {
lastOutput = result.last()
amplifierInput = result
}
}
}
} while (amplifiers.count { !it.isHalted() } == amplifiers.size)
return lastOutput
}
// found on https://rosettacode.org/wiki/Permutations#Kotlin
fun <T> permute(input: List<T>): List<List<T>> {
if (input.size == 1) return listOf(input)
val perms = mutableListOf<List<T>>()
val toInsert = input[0]
for (perm in permute(input.drop(1))) {
for (i in 0..perm.size) {
val newPerm = perm.toMutableList()
newPerm.add(i, toInsert)
perms.add(newPerm)
}
}
return perms
}
fun permutationGeneration(start: Long, end: Long): List<LongArray> {
return permute((start..end).toList()).map { it.toLongArray() }
}
fun main(args: Array<String>) {
val fileName = if (args.size > 1) args[0] else "input.txt"
val code = readProgram(File(fileName))
val maxOutput = permutationGeneration(0L, 4L).map { seq -> phaseAmplifierTest(code, seq) }.max()
println("Max Output = $maxOutput")
val maxOutput2 = permutationGeneration(5L, 9L).map { seq -> phaseAmplifierFeedback(code, seq) }.max()
println("Max Output = $maxOutput2")
}
| 0 | HTML | 0 | 1 | bb19fda33ac6e91a27dfaea27f9c77c7f1745b9b | 2,174 | aoc-2019 | MIT License |
src/hongwei/leetcode/playground/leetcode_2021/M39_CombinationSum.kt | hongwei-bai | 201,601,468 | false | {"Java": 143669, "Kotlin": 38875} | package hongwei.leetcode.playground.leetcode_2021
import hongwei.leetcode.playground.common.Log
class M39_CombinationSum {
fun test() {
val listOfCandidates = listOf(
listOf(2, 3, 6, 7),
listOf(2, 3, 5),
listOf(2),
listOf(1),
listOf(1),
)
val listOfTarget = listOf(
7,
8,
1,
1,
2,
)
val expectedResultList = listOf(
setOf(listOf(2, 2, 3), listOf(7)),
setOf(listOf(2, 2, 2, 2), listOf(2, 3, 3), listOf(3, 5)),
emptySet(),
setOf(listOf(1)),
setOf(listOf(1, 1)),
)
listOfCandidates.forEachIndexed { i, list ->
val actualResult = combinationSum(list.toIntArray(), listOfTarget[i])
if (actualResult.toSet() == expectedResultList[i]) {
Log.pass("Test[$i] passed.")
} else {
Log.fail("Test[$i] FAILED!\ninput1: $list\ninput2: ${listOfTarget[i]}\nexpected: ${expectedResultList[i]}\nactual: $actualResult")
}
}
}
fun combinationSum(candidates: IntArray, target: Int): List<List<Int>> {
val list = foo(candidates.size - 1, candidates, target)
return list.filter { it.sum() == target }
}
fun foo(n: Int, candidates: IntArray, target: Int): List<List<Int>> {
val fPrevious = if (n > 0) {
foo(n - 1, candidates, target)
} else {
emptyList()
}
val list = mutableListOf<List<Int>>()
fPrevious.forEach { prevList ->
val prevSum = prevList.sum()
var i = 0
while (true) {
if (prevSum + candidates[n] * i <= target) {
val lvl2List = mutableListOf<Int>()
prevList.forEach {
lvl2List.add(it)
}
for (j in 0 until i) {
lvl2List.add(candidates[n])
}
list.add(lvl2List)
} else {
break
}
i++
}
}
var i = 1
while (true) {
if (candidates[n] * i <= target) {
val lvl2List = mutableListOf<Int>()
for (j in 0 until i) {
lvl2List.add(candidates[n])
}
list.add(lvl2List)
} else {
break
}
i++
}
return list
}
}
/*
39. Combination Sum
Medium
7604
180
Add to List
Share
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.
The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.
Example 1:
Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation:
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.
Example 2:
Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]
Example 3:
Input: candidates = [2], target = 1
Output: []
Example 4:
Input: candidates = [1], target = 1
Output: [[1]]
Example 5:
Input: candidates = [1], target = 2
Output: [[1,1]]
Constraints:
1 <= candidates.length <= 30
1 <= candidates[i] <= 200
All elements of candidates are distinct.
1 <= target <= 500
Accepted
848,346
Submissions
1,363,625
*/ | 0 | Java | 0 | 1 | 9d871de96e6b19292582b0df2d60bbba0c9a895c | 3,866 | leetcode-exercise-playground | Apache License 2.0 |
advent-of-code2015/src/main/kotlin/day2/Advent2.kt | REDNBLACK | 128,669,137 | false | null | package day2
import mul
import parseInput
import splitToLines
/**
--- Day 2: I Was Told There Would Be No Math ---
The elves are running low on wrapping paper, and so they need to submit an order for more. They have a list of the dimensions (length l, width w, and height h) of each present, and only want to order exactly as much as they need.
Fortunately, every present is a box (a perfect right rectangular prism), which makes calculating the required wrapping paper for each gift a little easier: find the surface area of the box, which is 2*l*w + 2*w*h + 2*h*l. The elves also need a little extra paper for each present: the area of the smallest side.
For example:
A present with dimensions 2x3x4 requires 2*6 + 2*12 + 2*8 = 52 square feet of wrapping paper plus 6 square feet of slack, for a total of 58 square feet.
A present with dimensions 1x1x10 requires 2*1 + 2*10 + 2*10 = 42 square feet of wrapping paper plus 1 square foot of slack, for a total of 43 square feet.
All numbers in the elves' list are in feet. How many total square feet of wrapping paper should they order?
Your puzzle answer was 1606483.
The first half of this puzzle is complete! It provides one gold star: *
--- Part Two ---
The elves are also running low on ribbon. Ribbon is all the same width, so they only have to worry about the length they need to order, which they would again like to be exact.
The ribbon required to wrap a present is the shortest distance around its sides, or the smallest perimeter of any one face. Each present also requires a bow made out of ribbon as well; the feet of ribbon required for the perfect bow is equal to the cubic feet of volume of the present. Don't ask how they tie the bow, though; they'll never tell.
For example:
A present with dimensions 2x3x4 requires 2+2+3+3 = 10 feet of ribbon to wrap the present plus 2*3*4 = 24 feet of ribbon for the bow, for a total of 34 feet.
A present with dimensions 1x1x10 requires 1+1+1+1 = 4 feet of ribbon to wrap the present plus 1*1*10 = 10 feet of ribbon for the bow, for a total of 14 feet.
How many total feet of ribbon should they order?
*/
fun main(args: Array<String>) {
println(Present(2, 3, 4).calcPaper() == 58)
println(Present(1, 1, 10).calcPaper() == 43)
println(Present(2, 3, 4).calcRibbon() == 34)
println(Present(1, 1, 10).calcRibbon() == 14)
val input = parseInput("day2-input.txt")
println(total(input))
}
fun total(input: String) = parsePresents(input)
.map { it.calcPaper() to it.calcRibbon() }
.let { mapOf("paper" to it.sumBy { it.first }, "ribbon" to it.sumBy { it.second }) }
data class Present(val h: Int, val w: Int, val l: Int) {
val dimensions = listOf(h, w, l)
val maxDimension = dimensions.let { it.indexOf(it.max()) }
fun calcPaper(): Int {
fun wrappingPaperArea() = 2 * l * w + 2 * w * h + 2 * h * l
fun slackArea() = dimensions
.filterIndexed { i, v -> i != maxDimension }
.mul()
return wrappingPaperArea() + slackArea()
}
fun calcRibbon(): Int {
fun presentRibbon() = dimensions
.filterIndexed { i, v -> i != maxDimension }
.map { it * 2 }
.sum()
fun bowRibbon() = dimensions.mul()
return presentRibbon() + bowRibbon()
}
}
private fun parsePresents(input: String) = input.splitToLines()
.map {
val (h, w, l) = it.split('x')
.map(String::toInt)
.toList()
Present(h, w, l)
}
| 0 | Kotlin | 0 | 0 | e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7 | 3,568 | courses | MIT License |
2022/src/Day08.kt | Saydemr | 573,086,273 | false | {"Kotlin": 35583, "Python": 3913} | package src
fun main() {
val visibility = mutableListOf<MutableList<Boolean>>()
val scenicScores = mutableListOf<Int>()
val input = readInput("input8")
.map { it.trim() }
.map { it.chunked(1)
.map { it2 -> it2.toInt() } }
fun isVisibleFromDirection(x: Int, y: Int, direction: String): Boolean {
return if (direction == "left") input[x].take(y).map { it < input[x][y] }.filter { it }.count { true } == y
else if (direction == "right") input[x].drop(y+1).map { it < input[x][y] }.filter { it }.count { true } == input[x].size - y - 1
else {
val column = input.map { it[y] }
if (direction == "up") column.take(x).map { it < input[x][y] }.filter { it }.count { true } == x
else column.drop(x+1).map { it < input[x][y] }.filter { it }.count { true } == column.size - x - 1
}
}
fun scenicScore(x: Int, y: Int): Int {
val left = if (input[x].take(y).indexOfLast { it >= input[x][y] } < 0) y else input[x].take(y).reversed().indexOfFirst { it >= input[x][y] } + 1
val right = if (input[x].drop(y+1).indexOfFirst { it >= input[x][y] } < 0) input[x].size - y - 1 else input[x].drop(y+1).indexOfFirst { it >= input[x][y] } + 1
val column = input.map { it[y] }
val up = if(column.take(x).indexOfLast { it >= input[x][y] } < 0) x else column.take(x).reversed().indexOfFirst { it >= input[x][y] } + 1
val down = if (column.drop(x+1).indexOfFirst { it >= input[x][y] } < 0) column.size - x - 1 else column.drop(x+1).indexOfFirst { it >= input[x][y] } + 1
return left * right * up * down
}
fun isVisible(x: Int, y: Int): Boolean {
return if (x <= 0 || y <= 0 || y >= input[0].size - 1 || x >= input.size - 1) true
else (isVisibleFromDirection(x,y,"up") ||
isVisibleFromDirection(x,y,"down") ||
isVisibleFromDirection(x,y,"left") ||
isVisibleFromDirection(x,y,"right"))
}
fun part1(input: List<List<Int>>): Int {
for (i in input.indices)
{
visibility.add(mutableListOf())
for (j in 0 until input[i].size)
visibility[i].add(isVisible(i,j))
}
return visibility.flatten().count{ it }
}
fun part2 (input: List<List<Int>>): Int {
for (i in input.indices) {
for (j in 0 until input[i].size)
scenicScores.add(scenicScore(i, j))
}
return scenicScores.max()
}
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 25b287d90d70951093391e7dcd148ab5174a6fbc | 2,581 | AoC | Apache License 2.0 |
src/day08/Day08.kt | shiddarthbista | 572,833,784 | false | {"Kotlin": 9985} | package day08
import readInput
fun main() {
fun part1(input: List<String>): Int {
return input.indices.sumOf { i ->
input[0].indices.count { j ->
val left = (j - 1 downTo 0).map { i to it }
val right = (j + 1 until input[0].length).map { i to it }
val up = (i - 1 downTo 0).map { it to j }
val down = (i + 1 until input.size).map { it to j }
listOf(left, right, up, down).any { trees ->
trees.all { (x, y) -> input[x][y] < input[i][j] }
}
}
}
}
fun part2(input: List<String>): Int {
return input.indices.maxOf { i ->
input[0].indices.maxOf { j ->
val left = (j - 1 downTo 0).map { i to it }
val right = (j + 1 until input[0].length).map { i to it }
val up = (i - 1 downTo 0).map { it to j }
val down = (i + 1 until input.size).map { it to j }
listOf(left, right, up, down).map { trees ->
minOf(trees.takeWhile { (x, y) -> input[x][y] < input[i][j] }.size + 1, trees.size)
}.reduce(Int::times)
}
}
}
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | ed1b6a132e201e98ab46c8df67d4e9dd074801fe | 1,432 | aoc-2022-kotlin | Apache License 2.0 |
src/Day14.kt | Cryosleeper | 572,977,188 | false | {"Kotlin": 43613} | fun main() {
fun part1(input: List<String>): Int {
val parsedInput = input.parseToStone().map { it.points }
val stones = parsedInput.flatten().toSet()
val maxDepth = stones.maxByOrNull { it.y }!!.y
println("Cave is $stones with max depth of $maxDepth")
val sand = mutableSetOf<Point>()
var activeSand = Point(500, 0)
run sand@{
while (sand.contains(Point(500, 0)).not()) {
while (activeSand.canFall(stones + sand)) {
activeSand.fall(stones + sand)
if (activeSand.y > maxDepth) {
println("Sand falls off at $activeSand")
return@sand
}
}
println("Sand stopped at $activeSand")
sand.add(activeSand)
activeSand = Point(500, 0)
}
}
return sand.size
}
fun part2(input: List<String>): Int {
val parsedInput = input.parseToStone().map { it.points }
val stones = parsedInput.flatten().toSet()
val maxDepth = stones.maxByOrNull { it.y }!!.y
println("Cave is $stones with max depth of $maxDepth")
val sand = mutableSetOf<Point>()
var activeSand = Point(500, 0)
run sand@{
while (sand.contains(Point(500, 0)).not()) {
while (activeSand.canFall(stones + sand, maxDepth+2)) {
activeSand.fall(stones + sand, maxDepth+2)
}
println("Sand stopped at $activeSand")
sand.add(activeSand)
activeSand = Point(500, 0)
}
}
return sand.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14")
//println(part1(input))
println(part2(input))
}
private fun List<String>.parseToStone(): List<Stone> {
val result = mutableListOf<Stone>()
this.forEach {line ->
result.add(Stone(line.split(" -> ").map { point -> point.split(",").let { Point(it[0].toInt(), it[1].toInt()) } }))
}
return result
}
private data class Stone(private val turnPoints: List<Point>) {
val points: Set<Point> = turnPoints.convertToPoints()
private fun List<Point>.convertToPoints(): Set<Point> {
val result = mutableSetOf<Point>()
repeat(this.size - 1) { index ->
range(this[index].x, this[index+1].x).forEach { x ->
range(this[index].y, this[index+1].y).forEach { y ->
//println("Adding stone to $x, $y")
result.add(Point(x, y))
}
}
}
return result
}
private fun range(from: Int, to: Int) = if (from <= to) from..to else to..from
}
private data class Point(var x: Int, var y: Int) {
override fun toString(): String {
return "($x,$y)"
}
fun canFall(objects: Set<Point>, limit: Int = Int.MAX_VALUE): Boolean {
return (limit > y+1) && (objects.contains(Point(x, y+1)).not() || objects.contains(Point(x-1, y+1)).not() || objects.contains(Point(x+1, y+1)).not())
}
fun fall(objects: Set<Point>, limit: Int = Int.MAX_VALUE): Boolean {
if (y+1 == limit) {
return false
} else if (objects.contains(Point(x, y+1)).not()) {
y += 1
return true
} else if (objects.contains(Point(x-1, y+1)).not()) {
x -= 1
y += 1
return true
} else if (objects.contains(Point(x+1, y+1)).not()) {
x += 1
y += 1
return true
} else {
return false
}
}
} | 0 | Kotlin | 0 | 0 | a638356cda864b9e1799d72fa07d3482a5f2128e | 3,821 | aoc-2022 | Apache License 2.0 |
src/aoc2021/day03/Code.kt | ldickmanns | 572,675,185 | false | {"Kotlin": 48227} | package aoc2021.day03
import readInput
fun main() {
val input = readInput("aoc2021/day03/input")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Int {
val nColumns = input.first().length
val oneCounters = IntArray(nColumns)
input.forEach { line: String ->
line.forEachIndexed { index: Int, c: Char ->
if (c == '1') oneCounters[index] += 1
}
}
val gammaRateString = buildString {
oneCounters.forEach {
if (it > 500) append("1") else append("0")
}
}
val epsilonRateString = buildString {
oneCounters.forEach {
if (it > 500) append("0") else append("1")
}
}
val gammaRate = Integer.parseInt(gammaRateString, 2)
val epsilonRate = Integer.parseInt(epsilonRateString, 2)
return gammaRate * epsilonRate
}
fun part2(input: List<String>): Int {
val nColumns = input.first().length
val zeroCounter = IntArray(nColumns)
val oneCounter = IntArray(nColumns)
input.forEach { line ->
line.forEachIndexed { index: Int, c: Char ->
if (c == '0') zeroCounter[index] += 1 else oneCounter[index] += 1
}
}
var oxygenArray = input
var co2Array = input
for (i in 0 until nColumns) {
val nZerosOxygen = oxygenArray.map { it[i] }.filter { it == '0' }.size
val nOnesOxygen = oxygenArray.size - nZerosOxygen
val nZerosCO2 = co2Array.map { it[i] }.filter { it == '0' }.size
val nOnesCO2 = co2Array.size - nZerosCO2
val hasMoreOrEqualOnes = nOnesOxygen >= nZerosOxygen
oxygenArray = if (oxygenArray.size > 1) oxygenArray.filter {
if (hasMoreOrEqualOnes) it[i] == '1' else it[i] == '0'
} else oxygenArray
val hasLessOrEqualZeros = nZerosCO2 <= nOnesCO2
co2Array = if (co2Array.size > 1) co2Array.filter {
if (hasLessOrEqualZeros) it[i] == '0' else it[i] == '1'
} else co2Array
}
println(oxygenArray.size)
println(co2Array.size)
val oxygenRating = Integer.parseInt(oxygenArray.first(), 2)
val co2Rating = Integer.parseInt(co2Array.first(), 2)
return oxygenRating * co2Rating
}
| 0 | Kotlin | 0 | 0 | 2654ca36ee6e5442a4235868db8174a2b0ac2523 | 2,216 | aoc-kotlin-2022 | Apache License 2.0 |
solutions/qualifications/cheating-detection/src/main/kotlin/solutions.cheating.detection/CheatingDetectionSolution.kt | Lysoun | 351,224,145 | false | null | import kotlin.math.exp
import kotlin.math.ln
fun main(args: Array<String>) {
val casesNumber = readLine()!!.toInt()
// Ignore required percentage to success
readLine()
for (i in 1..casesNumber) {
println("Case #$i: ${findCheater(List(100) { 0 }.map { readLine()!! })}")
}
}
fun numberOfGoodAnswersToSkillOrDifficulty(numberOfGoodAnswers: Int, totalNumber: Int): Double {
return (6.0 * numberOfGoodAnswers / totalNumber) - 3
}
fun computeQuestionsDifficulties(players: List<Player>): List<Double> = List(10000) { it }
.map { questionNumber -> players.map { it.answers[questionNumber] } }
.map { it.sum() }
.map { numberOfGoodAnswersToSkillOrDifficulty(it, 100) }
data class Player(val number: Int, val answers: List<Int>, val numberOfGoodAnswers: Int, val skill: Double) {
companion object {
fun from(number: Int, playerAnswers: String): Player {
val playersAnswersAsShorts = playerAnswers.toList()
.map { answer -> Character.getNumericValue(answer) }
val numberOfGoodAnswers = playersAnswersAsShorts.sum()
val skill = numberOfGoodAnswersToSkillOrDifficulty(numberOfGoodAnswers, 10000)
return Player(number, playersAnswersAsShorts, numberOfGoodAnswers, skill)
}
}
}
fun probabilityFunctionPrimitive(skill: Double, difficulty: Double): Double = -ln(1 + exp(skill - difficulty))
fun computeProbabilityMean(skill: Double): Double =
(probabilityFunctionPrimitive(skill, 3.0) - probabilityFunctionPrimitive(skill, -3.0))/ 6.0
fun computeMean(numbers: Sequence<Double>, size: Int): Double = numbers.sum().div(size)
fun computeVariance(mean: Double, numbers: Sequence<Double>, size: Int): Double =
numbers.map { it * it }.sum().div(size).minus(mean * mean)
fun findCheater(playersAnswers: List<String>): Int {
val players = playersAnswers.mapIndexed { index, answers -> Player.from(index + 1, answers) }
val questionsDifficulties = computeQuestionsDifficulties(players)
return players.filter { it.skill >= 0.0 }
.map { player ->
val questionsAnsweredCorrectlyDifficulties = player.answers
.asSequence()
.mapIndexed { index, answer -> index to answer }
.filter { it.second == 1 }
.map { it.first }
.map { questionsDifficulties[it] }
val mean = computeMean(questionsAnsweredCorrectlyDifficulties, player.numberOfGoodAnswers)
player.number to computeVariance(mean, questionsAnsweredCorrectlyDifficulties, player.numberOfGoodAnswers)
}
.maxByOrNull { it.second }!!
.first
} | 0 | Kotlin | 0 | 0 | 98d39fcab3c8898bfdc2c6875006edcf759feddd | 2,707 | google-code-jam-2021 | MIT License |
src/main/de/ddkfm/Day4.kt | DDKFM | 433,861,159 | false | {"Kotlin": 13522} | package de.ddkfm
data class Board(
val board : List<List<Int>> = emptyList(),
val marked : List<MutableList<Boolean>> = board.map { it.map { false }.toMutableList() }
) {
fun find(number : Int) : Int {
var find = -1
board.indices.map { i ->
board[i].indices.map { j ->
if(board[i][j] == number && !marked[i][j]) {
marked[i][j] = true
find = number
}
}
}
return find
}
fun hasWon() : Boolean {
val row = marked.any { it.all { it } }
val columns = (0 until 5)
.map { i -> marked.map { it[i] } }
.any { it.all { it } }
return row || columns
}
fun unmarkedSum() : Int {
val markedList = marked.flatten().toList()
return board.flatten()
.filterIndexed { index, i -> !markedList[index] }
.sum()
}
fun print() {
board.forEachIndexed { i, list ->
list.forEachIndexed { j, number ->
val num = if(number < 10) " $number" else "$number"
val mark = if(marked[i][j])
"[$num]"
else
" $num "
print("$mark ")
}
print("\n")
}
}
}
class Day4 : DayInterface<List<String>, Int> {
override fun part1(input: List<String>): Int {
val inputs = input.first().split(",").map { it.toInt() }
val boards = input.getBoards()
inputs.forEach { input ->
boards.forEach { board ->
val find = board.find(input)
if(find != -1) {
//println("find $find on board $board")
if(board.hasWon()) {
println("NICE: $find")
val unmarked = board.unmarkedSum()
return unmarked * find
}
}
}
}
return -1
}
fun List<String>.getBoards(): List<Board> {
return this.drop(1)
.filterNot { it.isEmpty() }
.chunked(5)
.map { chunk ->
val board = chunk
.map {
it.split(" ")
.filter { it.isNotEmpty() }
.map { it.toInt() }
}
return@map Board(board)
}
}
override fun part2(input: List<String>): Int {
val inputs = input.first().split(",").map { it.toInt() }
val boards = input.getBoards()
val winningBoards = mutableListOf<Int>()
inputs.forEach { input ->
boards.forEachIndexed { index, board ->
val find = board.find(input)
if(find != -1) {
//println("find $find on board $board")
if(board.hasWon()) {
println("Board $index has won:")
board.print()
if(!winningBoards.contains(index))
winningBoards.add(index)
if(winningBoards.size == boards.size) {
val unmarked = board.unmarkedSum()
return unmarked * find
}
}
}
}
}
return -1
}
}
| 0 | Kotlin | 0 | 0 | 6e147b526414ab5d11732dc32c18ad760f97ff59 | 3,467 | AdventOfCode21 | MIT License |
day9/src/Program.kt | DaveTCode | 433,797,148 | false | null | package org.davetcode.aoc2021.day9
import java.io.File
fun main() {
val testData = processFile("c:\\code\\home\\aoc2021day9\\test.txt")
val inputData = processFile("c:\\code\\home\\aoc2021day9\\input.txt")
println(part1(testData))
println(part1(inputData))
println(part2(testData))
println(part2(inputData))
}
fun processFile(file: String): Array<Array<Int>> {
return File(file)
.readLines()
.map { line -> line.toCharArray().map { it - '0' }.toTypedArray() }
.toTypedArray()
}
data class Point(val x: Int, val y: Int)
fun getLowPoints(data: Array<Array<Int>>): List<Point> {
val lowPoints = mutableListOf<Point>()
for (y in data.indices) {
for (x in data[0].indices) {
val dataPoint = data[y][x]
if (x > 0 && data[y][x - 1] <= dataPoint) continue
if (x < data[0].size - 1 && data[y][x + 1] <= dataPoint) continue
if (y > 0 && data[y - 1][x] <= dataPoint) continue
if (y < data.size - 1 && data[y + 1][x] <= dataPoint) continue
lowPoints.add(Point(x, y))
}
}
return lowPoints
}
fun calculateBasinSize(data: Array<Array<Int>>, startPoint: Point): Int {
fun inner(currentPoint: Point, basinPoints: MutableSet<Point>) {
val (x, y) = currentPoint
// Up
if (y > 0 && data[y][x] < data[y - 1][x] && data[y - 1][x] != 9) {
basinPoints.add(Point(x, y - 1))
inner(Point(currentPoint.x, currentPoint.y - 1), basinPoints)
}
// Down
if (y < (data.size - 1) && data[y][x] < data[y + 1][x] && data[y + 1][x] != 9) {
basinPoints.add(Point(x, y + 1))
inner(Point(currentPoint.x, currentPoint.y + 1), basinPoints)
}
// Left
if (x > 0 && data[y][x] < data[y][x - 1] && data[y][x - 1] != 9) {
basinPoints.add(Point(x - 1, y))
inner(Point(currentPoint.x - 1, currentPoint.y), basinPoints)
}
// Right
if (x < (data[y].size - 1) && data[y][x] < data[y][x + 1] && data[y][x + 1] != 9) {
basinPoints.add(Point(x + 1, y))
inner(Point(currentPoint.x + 1, currentPoint.y), basinPoints)
}
}
val basinPoints = mutableSetOf(startPoint)
inner(startPoint, basinPoints)
return basinPoints.size
}
fun part2(data: Array<Array<Int>>): Int {
val lowPoints = getLowPoints(data)
val basins = lowPoints
.map { calculateBasinSize(data, it) }
.sortedDescending()
println(basins)
// Assume that all low points are in their own basin, no saddles
return lowPoints
.map { calculateBasinSize(data, it) }
.sortedDescending()
.take(3)
.reduce { acc, i -> acc * i }
}
fun part1(data: Array<Array<Int>>): Int {
val lowPoints = getLowPoints(data)
return lowPoints.sumOf { data[it.y][it.x] + 1 }
} | 0 | Rust | 1 | 0 | 2e3132403133529ef5d13ac098599a0ee8c584f2 | 3,003 | aoc2021 | MIT License |
src/day7/Day07.kt | MatthewWaanders | 573,356,006 | false | null | package day7
import day7.tree.Directory
import day7.tree.File
import day7.tree.Node
import day7.tree.Root
import utils.readInput
const val part1Limit = 100000
const val requiredSpace = 30000000
const val totalSpace = 70000000
fun main() {
val testInput = readInput("Day07_test", "day7")
check(part1(testInput) == 95437)
val input = readInput("Day07", "day7")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>) = calculateChildDirectorySizes(
buildTreeFromInput(input)
).sumOf { if (it <= part1Limit) it else 0 }
fun part2(input: List<String>): Int {
val directorySizes = calculateChildDirectorySizes(
buildTreeFromInput(input)
).sorted()
return directorySizes.first { it >= (requiredSpace - (totalSpace - directorySizes.last())) }
}
fun buildTreeFromInput(input: List<String>) = buildSubtreeFromInput(Root(), input, 1).first
fun buildSubtreeFromInput(parent: Node, input: List<String>, start: Int): Pair<Node, Int> {
var i = start
while (i < input.size) {
val line = input[i]
if (line.startsWith("$")) {
val parts = line.split(" ")
val (_, command) = parts
if (command == "ls") {
i++
continue
}
val (_, _, target) = parts
if (target == "..") {
return Pair(parent, i)
}
val (child, endIndex) = buildSubtreeFromInput(
Node(Directory, emptyList(), 0),
input,
i + 1,
)
parent.addChild(child)
i = endIndex + 1
} else {
if (line.startsWith("dir")) {
i++
continue
}
val (size, _) = line.split(" ")
parent.addChild(Node(File, emptyList(), size.toInt()))
i++
}
}
return Pair(parent, i)
}
fun calculateChildDirectorySizes(parent: Node): List<Int> = parent.children.fold(listOf(parent.totalSize)) { acc, it ->
if (it.type == Directory) {
if (it.children.isNotEmpty()) {
acc + calculateChildDirectorySizes(it)
} else {
acc + it.totalSize
}
} else {
acc
}
} | 0 | Kotlin | 0 | 0 | f58c9377edbe6fc5d777fba55d07873aa7775f9f | 2,272 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/aoc2022/Day19.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2022
import utils.InputUtils
private val bluePrintRegex = "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.".toRegex()
data class BluePrint(
val id: Int,
val oreCost: Int,
val clayCost: Int,
val obsidianOreCost: Int,
val obsidianClayCost: Int,
val geodeOreCost: Int,
val geodeObsidianCost: Int
) {
override fun toString(): String = "Blueprint $id: Each ore robot costs $oreCost ore. Each clay robot costs $clayCost ore. Each obsidian robot costs $obsidianOreCost ore and $obsidianClayCost clay. Each geode robot costs $geodeOreCost ore and $geodeObsidianCost obsidian."
val geodeRobot = Resources(ore = geodeOreCost, obsidian = geodeObsidianCost)
val obsidianRobot = Resources(ore = obsidianOreCost, clay = obsidianClayCost)
val robots = mapOf(
Resources(ore = oreCost) to Resources(ore = 1),
Resources(ore = clayCost) to Resources(clay = 1),
obsidianRobot to Resources(obsidian = 1),
geodeRobot to Resources(geode = 1),
Resources() to Resources() // Do nothing
)
fun run(mine: Mine, turns: Int) : Sequence<Mine> {
if (turns == 0) return sequenceOf(mine)
var possibleRobots = robots
.filter { (cost, _) -> mine.goods.canAfford(cost) }
.filter { (_, generates) -> turns > 5 || !(generates.ore > 0 || generates.clay > 0) }
if (geodeRobot in possibleRobots) { possibleRobots = possibleRobots.filterKeys { it == geodeRobot } }
if (obsidianRobot in possibleRobots) {possibleRobots = possibleRobots.filterKeys { it == obsidianRobot }}
return possibleRobots.asSequence().flatMap { (cost, generates) ->
val goods = mine.goods + mine.robots - cost
run(Mine(robots = mine.robots + generates, goods = goods), turns - 1)
}
}
}
fun createBluePrint(matchResult: MatchResult): BluePrint {
val values = matchResult.groupValues.drop(1).map { it.toInt() }
val (id, oreCost, clayCost, obsidianOreCost, obsidianClayCost) = values
val (geodeOreCost, geodeObsidianCost) = values.drop(5)
return BluePrint(id, oreCost, clayCost, obsidianOreCost, obsidianClayCost, geodeOreCost, geodeObsidianCost)
}
data class Resources(
val ore: Int = 0,
val clay: Int = 0,
val obsidian: Int = 0,
val geode: Int = 0,
) {
operator fun plus(other: Resources): Resources = Resources(ore + other.ore, clay + other.clay, obsidian + other.obsidian, geode + other.geode)
operator fun minus(other: Resources): Resources = Resources(ore - other.ore, clay - other.clay, obsidian - other.obsidian, geode - other.geode)
fun canAfford(cost: Resources): Boolean {
return ore >= cost.ore && clay >= cost.clay && obsidian >= cost.obsidian && geode >= cost.geode
}
}
data class Mine(
val robots: Resources,
val goods: Resources,
)
fun main() {
val testInput = """Blueprint 1: Each ore robot costs 4 ore. Each clay robot costs 2 ore. Each obsidian robot costs 3 ore and 14 clay. Each geode robot costs 2 ore and 7 obsidian.
Blueprint 2: Each ore robot costs 2 ore. Each clay robot costs 3 ore. Each obsidian robot costs 3 ore and 8 clay. Each geode robot costs 3 ore and 12 obsidian.""".split("\n")
fun runBluePrint(bluePrint: BluePrint, turns: Int): Int {
val initialMine = Mine(robots = Resources(ore = 1), goods = Resources())
return bluePrint.run(initialMine, turns).map { it.goods.geode }.max() * bluePrint.id
}
fun part1(input: List<String>): Int {
return input.parsedBy(bluePrintRegex).map(::createBluePrint).map {
runBluePrint(it, 24)
}.onEach { println(it) }.sum()
}
fun part2(input: List<String>): Int {
return -1
}
val testValue = part1(testInput)
println(testValue)
check(testValue == 33)
val puzzleInput = InputUtils.downloadAndGetLines(2022, 19).toList()
println(part1(puzzleInput))
println(part2(testInput))
println(part2(puzzleInput))
}
| 0 | Kotlin | 0 | 0 | 5abc9e479bed21ae58c093c8efbe4d343eee7714 | 4,138 | aoc-2022-kotlin | Apache License 2.0 |
src/Day11/Day11.kt | tomashavlicek | 571,148,715 | false | {"Kotlin": 23780} | package Day11
import readInput
import java.math.BigInteger
import java.util.LinkedList
import java.util.Queue
fun main() {
class Monkey(
val items: Queue<Long>,
val operation: (old: Long) -> Long,
val testDivisible: Int,
val ifTrue: Int,
val ifFalse: Int,
var inspectedItems: Int = 0
)
fun parseOperation(input: String): (old: Long) -> Long {
val operationInput = input.substringAfter("Operation: new = old ")
if (operationInput.first() == '+') {
val number = operationInput.drop(2).toInt()
return { old -> old + number }
} else {
if (operationInput == "* old") {
return { old -> old * old }
} else {
val number = operationInput.drop(2).toInt()
return { old -> old * number }
}
}
}
fun parseInput(input: List<String>): List<Monkey> {
val monkeysInput = input.windowed(size = 6, step = 7)
val monkeys = mutableListOf<Monkey>()
for (monkeyInput in monkeysInput) {
monkeys.add(
Monkey(
items = LinkedList(monkeyInput[1].substringAfter("Starting items: ").filter { !it.isWhitespace() }.split(',').map { it.toLong() }),
operation = parseOperation(monkeyInput[2]),
testDivisible = monkeyInput[3].substringAfter("Test: divisible by ").toInt(),
ifTrue = monkeyInput[4].substringAfter("If true: throw to monkey ").toInt(),
ifFalse = monkeyInput[5].substringAfter("If false: throw to monkey ").toInt()
)
)
}
return monkeys
}
fun part1(input: List<String>): Int {
val monkeys = parseInput(input)
repeat(times = 20) {
for (monkey in monkeys) {
while (monkey.items.isNotEmpty()) {
var item = monkey.items.remove()
// inspect the item
item = monkey.operation(item)
monkey.inspectedItems++
// monkey gets bored with the item
item /= 3
// test worry level
if (item % monkey.testDivisible == 0L) {
monkeys[monkey.ifTrue].items.add(item)
} else {
monkeys[monkey.ifFalse].items.add(item)
}
}
}
}
return monkeys.map { it.inspectedItems }.sortedDescending().take(2).reduce { acc, i -> acc * i }
}
fun part2(input: List<String>): Long {
val monkeys = parseInput(input)
val commonWorryLevel = monkeys.map { it.testDivisible }.reduce { acc, i -> acc * i }
repeat(times = 10000) {
monkeys.forEach { monkey ->
while (monkey.items.isNotEmpty()) {
var item = monkey.items.remove()
// inspect the item
item = monkey.operation(item) % commonWorryLevel
monkey.inspectedItems++
// test worry level
if (item % monkey.testDivisible == 0L) {
monkeys[monkey.ifTrue].items.add(item)
} else {
monkeys[monkey.ifFalse].items.add(item)
}
}
}
}
val (first, second) = monkeys.map { it.inspectedItems }.sortedDescending().take(2)
return first.toLong() * second.toLong()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11/Day11_test")
part1(testInput).also {
println("Test input part1: $it")
check(it == 10605)
}
part2(testInput).also {
println("Test input part2: $it")
check(it == 2713310158)
}
val input = readInput("Day11/Day11")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 899d30e241070903fe6ef8c4bf03dbe678310267 | 4,040 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day04.kt | euphonie | 571,665,044 | false | {"Kotlin": 23344} | interface OverlapValidator {
fun checks(range: IntRange, otherRange: IntRange) : Boolean
}
class FullOverlapValidator: OverlapValidator {
override fun checks(range: IntRange, otherRange: IntRange): Boolean {
val firstInSecond =
range.first in otherRange &&
range.last in otherRange
val secondInFirst =
otherRange.first in range.first..range.last &&
otherRange.last in range.first..range.last
return firstInSecond || secondInFirst
}
}
class PartialOverlapValidator : OverlapValidator {
override fun checks(range: IntRange, otherRange: IntRange): Boolean {
val firstInSecond =
range.first in otherRange ||
range.last in otherRange
val secondInFirst =
otherRange.first in range.first..range.last ||
otherRange.last in range.first..range.last
return firstInSecond || secondInFirst
}
}
fun main() {
fun existsFullIntersection(assignment: String) : Int {
val ranges = assignment.split(",", "-")
val validator = FullOverlapValidator()
val isContained = validator.checks(
ranges[0].toInt()..ranges[1].toInt(),
ranges[2].toInt()..ranges[3].toInt())
return if (isContained) 1 else 0
}
fun existsPartialIntersection(assignment: String) : Int {
val ranges = assignment.split(",", "-")
val validator = PartialOverlapValidator()
val isContained = validator.checks(
ranges[0].toInt()..ranges[1].toInt(),
ranges[2].toInt()..ranges[3].toInt())
return if (isContained) 1 else 0
}
fun part1(input: List<String>) : Int {
return input.sumOf { existsFullIntersection(it) }
}
fun part2(input: List<String>) : Int {
return input.sumOf { existsPartialIntersection(it) }
}
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
check(part1(input) == 475)
check(part2(input) == 825)
} | 0 | Kotlin | 0 | 0 | 82e167e5a7e9f4b17f0fbdfd01854c071d3fd105 | 2,131 | advent-of-code-kotlin | Apache License 2.0 |
src/Day04.kt | pmellaaho | 573,136,030 | false | {"Kotlin": 22024} | fun main() {
fun stringToRanges(row: String): Pair<IntRange, IntRange> {
return row.split(",").map {
val nbrs = it.split("-")
nbrs.first().toInt()..nbrs.last().toInt()
}.let {
Pair(it.first(), it.last())
}
}
fun part1(input: List<String>): Int {
return input.map { row ->
val (r1, r2) = stringToRanges(row)
val common = r1.toSet() intersect r2.toSet()
if (common.size == r1.toSet().size || common.size == r2.toSet().size) 1
else 0
}.sumOf { it }
}
fun part2(input: List<String>): Int {
return input.map { row ->
val (r1, r2) = stringToRanges(row)
val common = r1.toSet() intersect r2.toSet()
if (common.isNotEmpty()) 1
else 0
}.sumOf { it }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
// val res = part1(testInput)
// check(res == 2)
// val res = part2(testInput)
// check(res == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | cd13824d9bbae3b9debee1a59d05a3ab66565727 | 1,175 | AoC_22 | Apache License 2.0 |
src/y2015/Day13.kt | gaetjen | 572,857,330 | false | {"Kotlin": 325874, "Mermaid": 571} | package y2015
import util.readInput
object Day13 {
private fun parse(input: List<String>): Pair<Set<String>, Map<Pair<String, String>, Int>> {
val names = mutableSetOf<String>()
val happiness = input.associate {
val elements = it.split(' ')
val p1 = elements.first()
val p2 = elements.last().dropLast(1)
names.add(p1)
names.add(p2)
val amount = elements[3].toInt()
(p1 to p2) to if (elements[2] == "gain") {
amount
} else {
-amount
}
}
return names to happiness
}
fun part1(input: List<String>): Int {
val (names, happiness) = parse(input)
return maxHappiness(
happiness,
names.first(),
names - names.first(),
0,
names.first()
)
}
private fun maxHappiness(
edges: Map<Pair<String, String>, Int>,
latest: String,
remaining: Set<String>,
happiness: Int,
start: String
): Int {
if (remaining.isEmpty()) {
return happiness + edges[latest to start]!! + edges[start to latest]!!
}
return remaining.maxOf {
maxHappiness(
edges,
it,
remaining - it,
happiness + edges[latest to it]!! + edges[it to latest]!!,
start
)
}
}
fun part2(input: List<String>): Int {
val (names, happiness) = parse(input)
val extraEdges = happiness + names.associate {
(it to "Me") to 0
} + names.associate {
("Me" to it) to 0
}
return maxHappiness(
extraEdges,
"Me",
names,
0,
"Me"
)
}
}
fun main() {
val testInput = """
Alice would gain 54 happiness units by sitting next to Bob.
Alice would lose 79 happiness units by sitting next to Carol.
Alice would lose 2 happiness units by sitting next to David.
Bob would gain 83 happiness units by sitting next to Alice.
Bob would lose 7 happiness units by sitting next to Carol.
Bob would lose 63 happiness units by sitting next to David.
Carol would lose 62 happiness units by sitting next to Alice.
Carol would gain 60 happiness units by sitting next to Bob.
Carol would gain 55 happiness units by sitting next to David.
David would gain 46 happiness units by sitting next to Alice.
David would lose 7 happiness units by sitting next to Bob.
David would gain 41 happiness units by sitting next to Carol.
""".trimIndent().split("\n")
println("------Tests------")
println(Day13.part1(testInput))
println(Day13.part2(testInput))
println("------Real------")
val input = readInput("resources/2015/day13")
println(Day13.part1(input))
println(Day13.part2(input))
}
| 0 | Kotlin | 0 | 0 | d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a | 3,023 | advent-of-code | Apache License 2.0 |
src/Day03.kt | rmyhal | 573,210,876 | false | {"Kotlin": 17741} | fun main() {
fun part1(input: List<String>): Int {
return priorities(input)
}
fun part2(input: List<String>): Int {
return groupPriorities(input)
}
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
private fun priorities(input: List<String>) = input.sumOf { findPriorityChar(it).toPriorityNumber() }
private fun groupPriorities(input: List<String>): Int {
return input
.chunked(3)
.sumOf { group ->
group
.map { it.toSet() }
.reduce { acc, chars -> acc.intersect(chars) }
.first()
.toPriorityNumber()
}
}
private fun Char.toPriorityNumber(): Int {
return if (this.isLowerCase()) {
this - 'a' + 1
} else {
this - 'A' + 27
}
}
private fun findPriorityChar(rucksack: String): Char {
val (first, second) = rucksack.chunked(rucksack.length / 2).map { it.toSet() }
return first.intersect(second).first()
}
| 0 | Kotlin | 0 | 0 | e08b65e632ace32b494716c7908ad4a0f5c6d7ef | 925 | AoC22 | Apache License 2.0 |
src/Day05.kt | rod41732 | 728,131,475 | false | {"Kotlin": 26028} | /**
* You can edit, run, and share this code.
* play.kotlinlang.org
*/
fun main() {
val testInput = readInput("Day05_test")
val input = readInput("Day05")
data class MapRule(val destStart: Long, val srcStart: Long, val length: Long) {
fun mapOrNull(number: Long): Long? {
return if (srcStart <= number && number <= srcStart + length - 1) {
number + destStart - srcStart
} else {
null
}
}
fun inverse(): MapRule {
return MapRule(srcStart, destStart, length)
}
}
fun List<MapRule>.map(value: Long): Long {
return this.firstNotNullOfOrNull { it.mapOrNull(value) } ?: value
}
fun List<List<MapRule>>.map(value: Long): Long {
return this.fold(value) { acc, layer -> layer.map(acc) }
}
fun parseInput(input: List<String>): Pair<List<Long>, List<List<MapRule>>> {
val chunks = input.windowWhen { it == "" }
val seedLine = chunks.first().first()
val seeds = seedLine.substringAfter(": ").split(" ").map { it.toLong() }
// layer of maps, i.e. listOf(seed-to-soil, soil-to-fertilizer, ...)
val mapLayers = chunks.drop(1).map {
val mapLines = it.drop(1)
val mapData = mapLines.map { it.split(" ").map { it.toLong() }.let { (a, b, c) -> MapRule(a, b, c) } }
mapData
}
return Pair(seeds, mapLayers)
}
fun part1(input: List<String>): Long {
val (seeds, mapLayers) = parseInput(input)
return seeds.minOf { mapLayers.map(it) }
}
fun part2(input: List<String>): Long {
val (seeds, mapLayers) = parseInput(input)
val boundaryPoints = buildSet {
val inverseMapLayers = mapLayers.reversed().map { layer -> layer.map { it.inverse() } }
// calculate boundary point for all layers
inverseMapLayers.forEachIndexed { index, currentLayer ->
val restLayers = inverseMapLayers.drop(index + 1)
// calculate boundary point for each layer
currentLayer.forEach {
val src = it.destStart
val origToAchieve = restLayers.map(src)
add(origToAchieve)
}
}
}
val seedsToCheck = seeds.chunked(2).flatMap { (start, length) ->
val seedRange = start..(start + length - 1)
boundaryPoints.filter { seedRange.contains(it) } + seedRange.start
}
return seedsToCheck.minOf { mapLayers.map(it) }
}
assertEqual(part1(testInput), 35)
assertEqual(part2(testInput), 46)
println("Part1: ${part1(input)}")
println("Part2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 05a308a539c8a3f2683b11a3a0d97a7a78c4ffac | 2,760 | aoc-23 | Apache License 2.0 |
src/main/kotlin/y2022/day13/Day13.kt | TimWestmark | 571,510,211 | false | {"Kotlin": 97942, "Shell": 1067} | package y2022.day13
fun main() {
AoCGenerics.printAndMeasureResults(
part1 = { part1() },
part2 = { part2() }
)
}
var index = 0
fun initParseData(line: String): List<Any> {
index = 0
return parseData(line)
}
fun parseData(line: String): List<Any> {
val list: MutableList<Any> = mutableListOf()
while (index < line.length) {
when (line[index]) {
'[' -> {
index++
list.add(parseData(line))
}
']' -> {
index++
break
}
',' -> index++
else -> {
var numberString: String = line[index].toString() // this is a digit
do {
index++
if (line[index].isDigit()) {
numberString += line[index]
}
} while (line[index].isDigit())
list.add(numberString.toInt())
}
}
}
return list
}
fun input(): List<Pair<List<Any>, List<Any>>> {
return AoCGenerics.getInputLines("/y2022/day13/input.txt")
.chunked(3)
.map {
index = 0
val firstData = it[0]
val secondData = it[1]
Pair(initParseData(firstData), initParseData(secondData))
}
}
fun compareTo(a: List<Any>, b: List<Any>): Int {
return inOrder(Pair(a,b))
}
fun inOrder(pair: Pair<List<Any>, List<Any>>): Int {
val left = pair.first
val right = pair.second
for (i in 0 until maxOf(left.size, right.size)) {
when {
left.size <= i -> return 1
right.size <= i -> return -1
left[i] is Int && right[i] is Int -> {
return if ((left[i] as Int) < (right[i] as Int)) {
1
} else if ((left[i] as Int) > (right[i] as Int)) {
-1
} else continue
}
left[i] is List<*> && right[i] is List<*> -> {
val x = inOrder(Pair(left[i] as List<Any>, right[i] as List<Any> ))
if (x != 0) return x else continue
}
left[i] is List<*> && right[i] is Int -> {
return inOrder(Pair(left[i] as List<Any>, listOf(right[i])))
}
left[i] is Int && right[i] is List<*> -> {
return inOrder(Pair(listOf(left[i]), right[i] as List<Any> ))
}
}
}
return 0
}
fun part1(): Int {
val input = input()
return input.mapIndexedNotNull { index, pair ->
if (inOrder(pair) > 0) {
index + 1
} else {
null
}
}.sum()
}
fun part2(): Int {
val test = input().map { pair ->
listOf(pair.first, pair.second)
}.flatten().toMutableList()
val add1 = listOf(listOf(2))
val add2 = listOf(listOf(6))
test.add(add1)
test.add(add2)
val myComparator = Comparator<List<Any>> { element1, element2 ->
inOrder(Pair(element1, element2))
}
val sorted = test.sortedWith(myComparator).reversed()
val index1 = sorted.indexOf(add1) + 1
val index2 = sorted.indexOf(add2) + 1
return index1 * index2
}
| 0 | Kotlin | 0 | 0 | 23b3edf887e31bef5eed3f00c1826261b9a4bd30 | 3,248 | AdventOfCode | MIT License |
src/AoC1.kt | Pi143 | 317,631,443 | false | null | import java.io.File
fun main() {
println("Starting Day 1 A Test 1")
calculateDay1PartA(2020, "Input/2020_1_A_test1")
println("Starting Day 1 A Real")
calculateDay1PartA(2020, "Input/2020_1_A")
println("Starting Day 1 B Test 1")
calculateDay1PartB(2020, "Input/2020_1_A_test1")
println("Starting Day 1 B Real")
calculateDay1PartB(2020, "Input/2020_1_A")
}
fun calculateDay1PartA(targetNum: Int, File: String, start: Int = 0): Information2D {
val readData = readDay1Data(File)
val sorted = readData.sorted()
var lowIndex = start
var highIndex = sorted.size - 1
while (sorted[lowIndex] + sorted[highIndex] != targetNum && highIndex > lowIndex) {
if (sorted[lowIndex] + sorted[highIndex] < targetNum) {
lowIndex++
}
if (sorted[lowIndex] + sorted[highIndex] > targetNum) {
highIndex--
}
}
println("lowIndex : $lowIndex")
println("highIndex : $highIndex")
println("low : ${sorted[lowIndex]}")
println("high : ${sorted[highIndex]}")
println("Product : ${sorted[lowIndex] * sorted[highIndex]}")
return Information2D(lowIndex, highIndex)
}
fun calculateDay1PartB(targetNum: Int, File: String): Information2D {
val readData = readDay1Data(File)
val sorted = readData.sorted()
var lowIndex = 0
var middleIndex = 1
var highIndex = sorted.size - 1
while (sorted[lowIndex] + sorted[middleIndex] + sorted[highIndex] != targetNum) {
val missingSum = targetNum - sorted[lowIndex]
val calculatePartA = calculateDay1PartA(missingSum, File, lowIndex)
if(calculatePartA.highIndex > calculatePartA.lowIndex){
middleIndex = calculatePartA.lowIndex
highIndex = calculatePartA.highIndex
break
} else {
lowIndex++
}
}
println("lowIndex : $lowIndex")
println("middleIndex : $middleIndex")
println("highIndex : $highIndex")
println("low : ${sorted[lowIndex]}")
println("middle : ${sorted[middleIndex]}")
println("high : ${sorted[highIndex]}")
println("Product : ${sorted[lowIndex] * sorted[middleIndex] * sorted[highIndex]}")
return Information2D(lowIndex, highIndex)
}
fun readDay1Data(input: String): List<Int> {
val myList = mutableListOf<Int>()
File(localdir + input).forEachLine { myList.add(it.toInt()) }
return myList
}
class Information2D(
var lowIndex: Int,
var highIndex: Int
) {
}
| 0 | Kotlin | 0 | 1 | fa21b7f0bd284319e60f964a48a60e1611ccd2c3 | 2,484 | AdventOfCode2020 | MIT License |
solutions/qualifications/reverse-sort-engineering/src/main/kotlin/solutions.reverse.sort.engineering/ReverseSortEngineeringSolution.kt | Lysoun | 351,224,145 | false | null | fun main(args: Array<String>) {
val casesNumber = readLine()!!.toInt()
for (i in 1..casesNumber) {
val lineInput = readLine()!!.split(" ")
println("Case #$i: ${findListMatchingConstraints(ProblemInput(lineInput[0].toInt(), lineInput[1].toInt()))}")
}
}
const val IMPOSSIBLE = "IMPOSSIBLE"
fun buildSmallestNumberPositionPerIteration(problemInput: ProblemInput): List<Int> {
val smallestNumberPositionPerIteration = MutableList(problemInput.listSize - 1) { 1 }
var cost = problemInput.cost - problemInput.listSize + 1
var i = problemInput.listSize - 1
while(cost > 0 && i > 0) {
if (cost >= i) {
cost -= i
smallestNumberPositionPerIteration[problemInput.listSize - i - 1] = i + 1
}
--i
}
return smallestNumberPositionPerIteration
}
fun reverseSubList(list: List<Int>, startingIndex: Int, endingIndex: Int): List<Int> {
return list.subList(0, startingIndex) +
list.subList(startingIndex, endingIndex).reversed() +
list.subList(endingIndex, list.size)
}
fun buildListMatchingConstraints(problemInput: ProblemInput): List<Int> {
val smallestNumberPositionPerIteration = buildSmallestNumberPositionPerIteration(problemInput).reversed()
var listMatchingConstraints = List(problemInput.listSize) { it + 1 }
var index = problemInput.listSize - 2
for(i in smallestNumberPositionPerIteration) {
if (i > 1) {
listMatchingConstraints = reverseSubList(listMatchingConstraints, index, index + i)
}
--index
}
return listMatchingConstraints
}
fun findListMatchingConstraints(problemInput: ProblemInput): String {
// Having a cost inferior to listSize - 1 is impossible because there will be listSize - 1 iterations
// and each iteration has a minimum cost of 1
if (problemInput.cost < problemInput.listSize - 1) {
return IMPOSSIBLE
}
// Having a cost superior to listSize(listSize + 1)/2 - 1 is impossible because
// there will be listSize - 1 iterations and each iteration i has a maximum cost of listSize - i
if (problemInput.cost > problemInput.listSize * (problemInput.listSize + 1) / 2 - 1) {
return IMPOSSIBLE
}
return buildListMatchingConstraints(problemInput).joinToString(" ")
}
data class ProblemInput(val listSize: Int, val cost: Int) | 0 | Kotlin | 0 | 0 | 98d39fcab3c8898bfdc2c6875006edcf759feddd | 2,385 | google-code-jam-2021 | MIT License |
src/Day09.kt | l8nite | 573,298,097 | false | {"Kotlin": 105683} | import kotlin.math.abs
class Vector(val x: Int, val y: Int)
enum class Direction(val vector: Vector) {
R(Vector(+1, 0)),
L(Vector(-1, 0)),
U(Vector(0, -1)),
D(Vector(0, +1))
}
class Knot(var x: Int, var y: Int) {
val history = mutableSetOf<Pair<Int, Int>>()
init {
history.add(Pair(x, y))
}
fun move(v: Vector) {
x += v.x
y += v.y
history.add(Pair(x, y))
}
fun follow(k: Knot) {
if (abs(k.x-x) >= 2 || abs(k.y-y) >=2) {
x += k.x.compareTo(x)
y += k.y.compareTo(y)
history.add(Pair(x, y))
}
}
override fun toString(): String {
return "($x, $y): History: $history"
}
}
fun main() {
fun move(knots: List<Knot>, d: Direction, n: Int) {
repeat(n) {
knots[0].move(d.vector)
knots.drop(1).forEachIndexed { index, knot ->
knot.follow(knots[index])
}
}
}
fun parse(input: List<String>): List<Pair<Direction, Int>> = input.map { line ->
line.split(" ").let {
Pair(Direction.valueOf(it[0]), it[1].toInt())
}
}
fun part1(input: List<String>): Int {
val knots = mutableListOf<Knot>(Knot(0,0), Knot(0,0))
parse(input).forEach { (d, n) -> move(knots, d, n) }
return knots.last().history.size
}
fun part2(input: List<String>): Int {
val knots = mutableListOf<Knot>()
repeat(10) { knots.add(Knot(0, 0)) }
parse(input).forEach { (d, n) -> move(knots, d, n) }
return knots.last().history.size
}
// test if implementation meets criteria from the description, like:
val testInput1 = readInput("Day09_test_1")
check(part1(testInput1) == 13)
val testInput2 = readInput("Day09_test_2")
check(part2(testInput1) == 1)
check(part2(testInput2) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f74331778fdd5a563ee43cf7fff042e69de72272 | 1,977 | advent-of-code-2022 | Apache License 2.0 |
src/day2/Day02.kt | HGilman | 572,891,570 | false | {"Kotlin": 109639, "C++": 5375, "Python": 400} | package day2
import day2.Chain.getFightPoints
import day2.Chain.getSignForResult
import readInput
sealed class Result {
companion object {
fun fromSymbol(s: Char): Result {
return when(s) {
'X' -> Lose
'Y' -> Draw
else -> Win
}
}
}
}
object Win : Result()
object Lose : Result()
object Draw : Result()
sealed class Sign(val id: Int, val points: Int) {
companion object {
fun fromSymbol(s: Char): Sign {
return when (s) {
'A', 'X' -> {
Rock
}
'B', 'Y' -> {
Paper
}
else -> {
Scissors
}
}
}
}
}
object Paper : Sign(0, 2)
object Rock : Sign(1, 1)
object Scissors : Sign(2, 3)
object Chain {
private val chain = listOf(Paper, Rock, Scissors)
fun Sign.beatSign(): Sign {
return chain[(id + 1) % chain.size]
}
fun Sign.isBeatenBySign(): Sign {
val newId = id - 1
return if (newId < 0) chain[chain.size - 1] else chain[newId]
}
fun Sign.getFightPoints(opponent: Sign): Int {
return when (opponent) {
this -> {
3
}
beatSign() -> {
6
}
isBeatenBySign() -> {
0
}
else -> 0
}
}
fun Sign.getSignForResult(wantedResult: Result): Sign {
return when (wantedResult) {
Draw -> this
Win -> isBeatenBySign()
Lose -> beatSign()
}
}
}
fun main() {
fun getSymbols(input: List<String>): List<Pair<Char, Char>> {
return input.map {
val (first, second) = it.split(" ").map { s -> s.first() }
Pair(first, second)
}
}
fun getPoints(signs: List<Pair<Sign, Sign>>): Int {
return signs.fold(0) { points, pair ->
val (opponent, me) = pair
points + me.points + me.getFightPoints(opponent)
}
}
fun part1(input: List<String>): Int {
val signs = getSymbols(input).map {
val opponent = Sign.fromSymbol(it.first)
val me = Sign.fromSymbol(it.second)
Pair(opponent, me)
}
return getPoints(signs)
}
fun part2(input: List<String>): Int {
val signs = getSymbols(input).map {
val opponent = Sign.fromSymbol(it.first)
val wantedResult = Result.fromSymbol(it.second)
val me = opponent.getSignForResult(wantedResult)
Pair(opponent, me)
}
return getPoints(signs)
}
val testInput = readInput("day2/Day02_test")
println(part1(testInput))
check(part1(testInput) == 15)
val input = readInput("day2/Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | d05a53f84cb74bbb6136f9baf3711af16004ed12 | 2,953 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/year_2023/Day04.kt | krllus | 572,617,904 | false | {"Kotlin": 97314} | package year_2023
import Day
import solve
class Day04 : Day(day = 4, year = 2023, "Scratchcards") {
private fun getCards(): List<Card> {
val cards = mutableListOf<Card>()
for (entry in input) {
val data = entry.split(":")
val id = data.first().split(" ").last().toInt()
val numbers = data.last().split("| ")
val winningNumbers = numbers.first().split(" ").mapNotNull { it.toIntOrNull() }
val myNumbers = numbers.last().split(" ").mapNotNull { it.toIntOrNull() }
val card = Card(id = id, winningNumbers = winningNumbers, myNumbers = myNumbers)
cards.add(card)
}
return cards
}
override fun part1(): Int {
return getCards().sumOf { it.calculatePoints() }
}
override fun part2(): Int {
val cards = getCards().sortedBy { it.id }
val cardMap = mutableMapOf<Int, Int>()
val visited = mutableSetOf<Int>()
cards.forEach { card -> cardMap[card.id - 1] = 1 }
var selectedId = cards.first().id - 1
while (!visited.contains(selectedId) && selectedId < cards.size) {
visited.add(selectedId)
val count = cardMap[selectedId]
val card = cards[selectedId]
val matchingNumbers = card.calculateMatchingNumbers()
for (i in selectedId + 1..selectedId + matchingNumbers) {
cardMap[i] = (cardMap[i] ?: 1) + (count ?: 0)
}
selectedId++
}
return cardMap.values.sum()
}
}
data class Card(
val id: Int, val winningNumbers: List<Int>, val myNumbers: List<Int>
) {
fun calculatePoints(): Int {
var points = 0
for (number in myNumbers) {
if (winningNumbers.contains(number)) {
if (points == 0) points = 1
else points *= 2
}
}
return points
}
fun calculateMatchingNumbers(): Int {
return myNumbers.count { winningNumbers.contains(it) }
}
}
fun main() {
solve<Day04>(offerSubmit = true) {
"""
Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53
Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19
Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1
Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83
Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36
Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11
""".trimIndent()(part1 = 13, part2 = 30)
}
} | 0 | Kotlin | 0 | 0 | b5280f3592ba3a0fbe04da72d4b77fcc9754597e | 2,465 | advent-of-code | Apache License 2.0 |
lib/src/main/kotlin/com/bloidonia/advent/day13/Day13.kt | timyates | 433,372,884 | false | {"Kotlin": 48604, "Groovy": 33934} | package com.bloidonia.advent.day13
import com.bloidonia.advent.readText
data class Point(val x: Int, val y: Int) {
fun reflect(axis: String, pos: Int) = when (axis) {
"x" -> if (x < pos) this else Point(pos - (x - pos), y)
else -> if (y < pos) this else Point(x, pos - (y - pos))
}
}
class Fold(private val axis: String, private val pos: Int) {
fun fold(points: List<Point>): List<Point> = points.map { it.reflect(axis, pos) }.distinct()
}
class Day13(val points: List<Point>, val folds: List<Fold>) {
fun fold() = Day13(folds.first().fold(points), folds.drop(1))
override fun toString() = (0..points.maxOf { it.y }).joinToString("\n") { y ->
(0..points.maxOf { it.x }).joinToString("") { x ->
if (points.contains(Point(x, y))) "🟧" else "🟫"
}
}
}
fun String.toDay13() = this.split("\n\n".toPattern(), limit = 2).let { (points, folds) ->
Day13(
points.split("\n").map { it.toPoint() },
folds.split("\n").map { it.toFold() }
)
}
fun String.toPoint() = this.split(",", limit = 2).let { (x, y) -> Point(x.toInt(), y.toInt()) }
fun String.toFold() = this.split(" ").last().split("=", limit = 2).let { (axis, pos) -> Fold(axis, pos.toInt()) }
fun main() {
println(readText("/day13input.txt").toDay13().fold().points.size)
println(
generateSequence(readText("/day13input.txt").toDay13()) { it.fold() }
.dropWhile { it.folds.isNotEmpty() }
.first()
)
} | 0 | Kotlin | 0 | 1 | 9714e5b2c6a57db1b06e5ee6526eb30d587b94b4 | 1,493 | advent-of-kotlin-2021 | MIT License |
src/Day03.kt | uekemp | 575,483,293 | false | {"Kotlin": 69253} |
val Char.priority: Int
get() {
return when (this) {
in 'a'..'z' -> this - 'a' + 1
in 'A'..'Z' -> this - 'A' + 27
else -> error("Unknown priority for $this")
}
}
fun findDuplicatesIn(rucksack: String): Char {
val half = rucksack.length / 2
for (index in 0 until half) {
if (rucksack.indexOf(rucksack[index], half) > 0) {
return rucksack[index]
}
}
error("Couldn't find duplicate in $rucksack")
}
fun findBadge(rucksack: String, vararg rucksacks: String): Char {
val badges = rucksack.toCharArray().toMutableSet()
for (r in rucksacks) {
badges.retainAll(r.toCharArray().toSet())
}
if (badges.size != 1) {
error("Too many/too few badges: $badges")
}
return badges.first()
}
fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { line ->
findDuplicatesIn(line).priority
}
}
fun part2(input: List<String>): Int {
return input.chunked(3).sumOf { chunk ->
if (chunk.size != 3) {
error("Invalid input data")
}
findBadge(chunk[0], chunk[1], chunk[2]).priority
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
val input = readInput("Day03")
check(part1(input) == 7746)
check(part2(input) == 2604)
}
| 0 | Kotlin | 0 | 0 | bc32522d49516f561fb8484c8958107c50819f49 | 1,489 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/at/mpichler/aoc/lib/Vector.kt | mpichler94 | 656,873,940 | false | {"Kotlin": 196457} | package at.mpichler.aoc.lib
import kotlin.math.*
abstract class VectorI(val data: List<Int>) {
fun norm(ord: Order): Int {
return when (ord) {
Order.L1 -> data.sumOf { it.absoluteValue }
Order.L2 -> sqrt(data.sumOf { it * it }.toDouble()).roundToInt()
Order.Linf -> data.maxOf { it.absoluteValue }
}
}
fun dnorm(ord: Order): Double {
return when (ord) {
Order.L1 -> data.sumOf { it.absoluteValue }.toDouble()
Order.L2 -> sqrt(data.sumOf { it * it }.toDouble())
Order.Linf -> data.maxOf { it.absoluteValue }.toDouble()
}
}
fun distanceTo(other: VectorI): Int {
return data.zip(other.data).sumOf { (it.first - it.second).absoluteValue }
}
}
data class Vector2i(val x: Int, val y: Int) : VectorI(listOf(x, y)) {
constructor() : this(0, 0)
operator fun plus(other: Vector2i) = Vector2i(x + other.x, y + other.y)
operator fun minus(other: Vector2i) = Vector2i(x - other.x, y - other.y)
operator fun plus(value: Int) = Vector2i(x + value, y + value)
operator fun minus(value: Int) = Vector2i(x - value, y - value)
operator fun times(factor: Int) = Vector2i(x * factor, y * factor)
fun neighbors(moves: Iterable<Vector2i>): List<Vector2i> {
return moves.map { it + this }
}
fun sign(): Vector2i {
return Vector2i(x.sign, y.sign)
}
fun withX(newX: Int): Vector2i {
return Vector2i(newX, y)
}
fun withY(newY: Int): Vector2i {
return Vector2i(x, newY)
}
fun neighbors(moves: Iterable<Vector2i>, limits: Pair<Vector2i, Vector2i>): Iterable<Vector2i> {
return moves.map { it + this }
.filter { it.x >= limits.first.x && it.x <= limits.second.x && it.y >= limits.first.y && it.y <= limits.second.y }
}
}
data class Vector3i(val x: Int, val y: Int, val z: Int) : VectorI(listOf(x, y, z)) {
constructor() : this(0, 0, 0)
operator fun plus(other: Vector3i) = Vector3i(x + other.x, y + other.y, z + other.z)
operator fun minus(other: Vector3i) = Vector3i(x - other.x, y - other.y, z - other.z)
operator fun plus(other: Int) = Vector3i(x + other, y + other, z + other)
operator fun minus(other: Int) = Vector3i(x - other, y - other, z - other)
}
enum class Order { L1, L2, Linf, }
fun min(first: Vector2i, second: Vector2i): Vector2i {
return Vector2i(
min(first.x, second.x),
min(first.y, second.y)
)
}
fun min(first: Vector3i, second: Vector3i): Vector3i {
return Vector3i(
min(first.x, second.x),
min(first.y, second.y),
min(first.z, second.z)
)
}
fun max(first: Vector3i, second: Vector3i): Vector3i {
return Vector3i(
max(first.x, second.x),
max(first.y, second.y),
max(first.z, second.z)
)
}
fun max(first: Vector2i, second: Vector2i): Vector2i {
return Vector2i(
max(first.x, second.x),
max(first.y, second.y)
)
}
fun moves(distance: Int = 1, diagonals: Boolean = false, zeroMove: Boolean = false): List<Vector2i> {
require(distance >= 1) { "distance must be >= 1" }
return buildList {
if (zeroMove) {
add(Vector2i(0, 0))
}
for (d in 1..distance) {
add(Vector2i(0, -d))
if (diagonals) {
add(Vector2i(d, -d))
}
add(Vector2i(d, 0))
if (diagonals) {
add(Vector2i(d, d))
}
add(Vector2i(0, d))
if (diagonals) {
add(Vector2i(-d, d))
}
add(Vector2i(-d, 0))
if (diagonals) {
add(Vector2i(-d, -d))
}
}
}
}
| 0 | Kotlin | 0 | 0 | 69a0748ed640cf80301d8d93f25fb23cc367819c | 3,756 | advent-of-code-kotlin | MIT License |
src/main/kotlin/day11.kt | gautemo | 572,204,209 | false | {"Kotlin": 78294} | import shared.chunks
import shared.getText
import shared.lcm
fun main() {
val input = getText("day11.txt")
println(day11A(input))
println(day11B(input))
}
fun day11A(input: String): Long {
return findMonkeyBusiness(input, 20)
}
fun day11B(input: String): Long {
return findMonkeyBusiness(input, 10000, true)
}
private fun findMonkeyBusiness(input: String, rounds: Int, worryFree: Boolean = false): Long {
val divideByList = mutableListOf<Long>()
val monkeys = input.chunks().map { monkeyInput ->
val lines = monkeyInput.lines()
val items = lines[1].split(":")[1].split(",").map { it.trim().toLong() }
val operation = fun(old: Long): Long {
val toCalculate = lines[2].split("=")[1].replace("old", old.toString())
return if(toCalculate.contains('+')) {
val (a, b) = toCalculate.split('+').map { it.trim().toLong() }
a + b
} else {
val (a, b) = toCalculate.split('*').map { it.trim().toLong()}
a * b
}
}
val divideBy = lines[3].split(" ").last().toInt()
divideByList.add(divideBy.toLong())
val toMonkeyTrue = lines[4].split(" ").last().toInt()
val toMonkeyFalse = lines[5].split(" ").last().toInt()
val test = fun(value: Long): Int {
return if(value % divideBy == 0L) toMonkeyTrue else toMonkeyFalse
}
Monkey(items.toMutableList(), operation, test)
}
val leastCommonMultiplier = divideByList.reduce { acc, i -> lcm(acc, i) }
repeat(rounds) {
monkeys.forEach { monkey ->
while (monkey.items.isNotEmpty()) {
val item = monkey.items.removeAt(0)
var newItemValue = monkey.operation(item) % leastCommonMultiplier
if(!worryFree) newItemValue /= 3
val toMonkey = monkey.test(newItemValue)
monkeys[toMonkey].items.add(newItemValue)
monkey.inspectedItems++
}
}
}
return monkeys.map { it.inspectedItems }.sortedDescending().take(2).let { it[0] * it[1] }
}
private class Monkey(val items: MutableList<Long>, val operation: (old: Long) -> Long, val test: (value: Long) -> Int) {
var inspectedItems = 0L
} | 0 | Kotlin | 0 | 0 | bce9feec3923a1bac1843a6e34598c7b81679726 | 2,295 | AdventOfCode2022 | MIT License |
src/day7/day7.kt | bienenjakob | 573,125,960 | false | {"Kotlin": 53763} | package day7
import inputTextOfDay
import testTextOfDay
fun part1(input: String): Int {
val maxSize = 100_000
return scanDirectorySizes(input)
.toList()
.filter { it <= maxSize }
.sumOf { it }
}
fun part2(input: String): Int {
val dirSizes = scanDirectorySizes(input)
val total = 70_000_000
val required = 30_000_000
val used = dirSizes.first()
val freeSpace = total - used
val additional = required - freeSpace
return dirSizes
.filter { it > additional }
.minOf { it }
}
fun scanDirectorySizes(input: String): List<Int> {
val path = mutableListOf<String>()
val dirSizes = mutableMapOf<String, Int>()
input.lines().forEach {
val command = it.split(" ")
when (command[0]) {
"$" -> when (command[1]) {
"cd" -> when (command[2]) {
".." -> path.removeLast()
else -> path.add(command[2])
}
}
"dir" -> {}
else -> path.forEachIndexed { index, _ ->
val currentPath = path.take(index + 1).joinToString("")
dirSizes[currentPath] = dirSizes.getOrDefault(currentPath,0) + command[0].toInt()
}
}
}
return dirSizes.map { (_, size) -> size }
}
fun main() {
val day = 7
val testInput = testTextOfDay(day)
println("Test1: " + part1(testInput))
println("Test2: " + part2(testInput))
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = inputTextOfDay(day)
println("Part1: " + part1(input))
println("Part2: " + part2(input))
check(part1(input) == 1845346)
check(part2(input) == 3636703)
}
| 0 | Kotlin | 0 | 0 | 6ff34edab6f7b4b0630fb2760120725bed725daa | 1,740 | aoc-2022-in-kotlin | Apache License 2.0 |
app/src/main/java/com/betulnecanli/kotlindatastructuresalgorithms/CodingPatterns/TwoHeaps.kt | betulnecanli | 568,477,911 | false | {"Kotlin": 167849} | // The "Two Heaps" coding pattern involves using two heaps (usually a max heap and a min heap) to efficiently solve problems
//where you need to find the median or maintain order statistics in a stream of numbers.
/*
Usage: In many problems, we are given a set of elements that can be divided into two parts.
We are interested in knowing the smallest element in one part and the biggest element in the other part.
As the name suggests, this technique uses a Min-Heap to find the smallest element and a Max-Heap to find the biggest element.
*/
//1. Find the Median of a Number Stream
import java.util.PriorityQueue
class MedianFinder {
private val maxHeap = PriorityQueue<Int>(kotlin.Comparator.reverseOrder())
private val minHeap = PriorityQueue<Int>()
fun addNum(num: Int) {
if (maxHeap.isEmpty() || num <= maxHeap.peek()) {
maxHeap.offer(num)
} else {
minHeap.offer(num)
}
// Balance the heaps
if (maxHeap.size > minHeap.size + 1) {
minHeap.offer(maxHeap.poll())
} else if (minHeap.size > maxHeap.size) {
maxHeap.offer(minHeap.poll())
}
}
fun findMedian(): Double {
return if (maxHeap.size == minHeap.size) {
(maxHeap.peek() + minHeap.peek()) / 2.0
} else {
maxHeap.peek().toDouble()
}
}
}
fun main() {
val medianFinder = MedianFinder()
medianFinder.addNum(1)
println("Median: ${medianFinder.findMedian()}") // Output: 1.0
medianFinder.addNum(2)
println("Median: ${medianFinder.findMedian()}") // Output: 1.5
medianFinder.addNum(3)
println("Median: ${medianFinder.findMedian()}") // Output: 2.0
}
//2. Next Interval for a Sum
import java.util.PriorityQueue
data class Interval(val start: Int, val end: Int)
fun findNextInterval(intervals: List<Interval>, targets: List<Int>): List<Interval?> {
val result = mutableListOf<Interval?>()
val maxHeap = PriorityQueue<Interval>(compareBy { it.start })
for ((i, interval) in intervals.withIndex()) {
maxHeap.offer(interval)
}
for (target in targets) {
var found = false
while (maxHeap.isNotEmpty()) {
val interval = maxHeap.poll()
if (interval.start >= target) {
result.add(interval)
found = true
break
}
}
if (!found) {
result.add(null)
}
maxHeap.addAll(intervals.subList(i + 1, intervals.size))
}
return result
}
fun main() {
val intervals = listOf(
Interval(1, 3),
Interval(2, 4),
Interval(5, 7)
)
val targets = listOf(2, 4, 8)
val result = findNextInterval(intervals, targets)
println("Next Intervals: ${result.joinToString(", ")}")
}
/*
Find the Median of a Number Stream:
The MedianFinder class uses two heaps to maintain the balance of numbers and efficiently find the median of a stream of numbers.
The max heap stores the smaller half of the numbers, and the min heap stores the larger half.
Next Interval for a Sum:
The findNextInterval function uses a max heap to efficiently find the next interval for a given target sum.
It iterates through the intervals and maintains a max heap of intervals starting before the target.
*/
| 2 | Kotlin | 2 | 40 | 70a4a311f0c57928a32d7b4d795f98db3bdbeb02 | 3,339 | Kotlin-Data-Structures-Algorithms | Apache License 2.0 |
src/day05/day05.kt | LostMekka | 574,697,945 | false | {"Kotlin": 92218} | package day05
import util.extractIntGroups
import util.readInput
import util.shouldBe
import java.util.LinkedList
fun main() {
val day = 5
val testInput = readInput(day, testInput = true).parseInput()
part1(testInput) shouldBe "CMZ"
part2(testInput) shouldBe "MCD"
val input = readInput(day).parseInput()
println("output for part1: ${part1(input)}")
println("output for part2: ${part2(input)}")
}
private class Input(
val stacks: List<List<Char>>,
val rules: List<Rule>,
)
private data class Rule(
val amount: Int,
val source: Int,
val target: Int,
)
private val stackNumberRegex = Regex("""\d+""")
private val ruleRegex = Regex("""^move (\d+) from (\d+) to (\d+)$""")
private fun List<String>.parseInput(): Input {
val (stackLineCount, stackNumberLine) = withIndex().first { '[' !in it.value }
val stackCount = stackNumberRegex.findAll(stackNumberLine).count()
val stacks = List<MutableList<Char>>(stackCount) { mutableListOf() }
for (line in subList(0, stackLineCount)) {
for ((i, block) in line.chunked(4).withIndex()) {
val letter = block[1]
if (letter != ' ') stacks[i] += letter
}
}
val rules = subList(stackLineCount + 2, size).map { line ->
val (a, b, c) = line.extractIntGroups(ruleRegex)
Rule(
amount = a,
source = b - 1,
target = c - 1,
)
}
return Input(stacks, rules)
}
private fun part1(input: Input): String {
val state = input.stacks.map { LinkedList(it.reversed()) }
for ((amount, source, target) in input.rules) {
repeat(amount) {
state[target] += state[source].removeLast()
}
}
return state.joinToString("") { it.last.toString() }
}
private fun part2(input: Input): String {
val state = input.stacks.map { LinkedList(it.reversed()) }
for ((amount, source, target) in input.rules) {
state[target] += state[source].takeLast(amount)
repeat(amount) {
state[source].removeLast()
}
}
return state.joinToString("") { it.last.toString() }
}
| 0 | Kotlin | 0 | 0 | 58d92387825cf6b3d6b7567a9e6578684963b578 | 2,137 | advent-of-code-2022 | Apache License 2.0 |
src/Day14.kt | iProdigy | 572,297,795 | false | {"Kotlin": 33616} | import kotlin.math.max
import kotlin.math.min
fun main() {
fun part1(input: List<String>): Int {
val (grid, xRange) = parse(input)
return simulate(grid, xRange.first, xRange.second)
}
fun part2(input: List<String>): Int {
val (grid, x, maxY) = parse(input)
grid[maxY + 2].run {
indices.forEach { this[it] = true }
}
return simulate(grid, x.first, x.second, false)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14")
println(part1(input)) // 638
println(part2(input)) // 31722
}
private fun simulate(grid: Array<BooleanArray>, minX: Int, maxX: Int, constrainX: Boolean = true): Int {
var dropped = 0
while (true) {
// attempt to drop sand
val (x, y) = drop(grid) ?: break
// ensure placement is within bounds
if (constrainX && (x < minX || x > maxX)) break
// if so, indicate placed
grid[y][x] = true
dropped++
}
return dropped
}
private fun drop(grid: Array<BooleanArray>, sourceX: Int = 500, sourceY: Int = 0): Pair<Int, Int>? {
var x = sourceX
var y = sourceY
if (grid[y][x] && grid[y + 1][x - 1] && grid[y + 1][x + 1]) return null
while (y + 1 < grid.size && (!grid[y + 1][x] || !grid[y + 1][x - 1] || !grid[y + 1][x + 1])) {
while (!(grid.getOrNull(y + 1) ?: return null)[x]) {
y++
}
if (!grid[y + 1][x - 1]) {
y++
x--
} else if (!grid[y + 1][x + 1]) {
y++
x++
} else {
break
}
}
return x to y
}
private fun parse(input: List<String>): Triple<Array<BooleanArray>, Pair<Int, Int>, Int> {
val grid = Array(200) { BooleanArray(1000) }
var minX = Int.MAX_VALUE
var maxX = Int.MIN_VALUE
var maxY = 0
input.map { it.split(" -> ").map { coordinate -> coordinate.split(',').map { num -> num.toInt() }.let { (a, b) -> a to b } } }
.map { it.windowed(2) }
.flatten()
.forEach { (a, b) ->
val xRange = min(a.first, b.first)..max(a.first, b.first)
val yRange = min(a.second, b.second)..max(a.second, b.second)
for (x in xRange) {
for (y in yRange) {
grid[y][x] = true
}
}
minX = min(minX, xRange.first)
maxX = max(maxX, xRange.last)
maxY = max(maxY, yRange.last)
}
return Triple(grid, minX to maxX, maxY)
}
| 0 | Kotlin | 0 | 1 | 784fc926735fc01f4cf18d2ec105956c50a0d663 | 2,681 | advent-of-code-2022 | Apache License 2.0 |
src/Day14.kt | mrugacz95 | 572,881,300 | false | {"Kotlin": 102751} | import kotlin.math.max
import kotlin.math.min
private fun List<List<Char>>.print() {
println(joinToString("\n") { it.joinToString("") })
}
fun main() {
fun List<String>.parse(): Triple<MutableList<MutableList<Char>>, Pair<Int, Int>, Pair<Int, Int>> {
val lines = map {
it.split(" -> ").map { line ->
val (x, y) = line.split(",")
y.toInt() to x.toInt()
}
}
var xPos = Pair(Int.MAX_VALUE, -Int.MAX_VALUE)
var yPos = Pair(Int.MAX_VALUE, -Int.MAX_VALUE)
lines.flatten().map {
yPos = Pair(min(it.first, yPos.first), max(it.first, yPos.second))
xPos = Pair(min(it.second, xPos.first), max(it.second, xPos.second))
}
yPos = Pair(min(0, yPos.first), yPos.second + 1)
xPos = Pair(0, 1000)
val cave = MutableList(yPos.second - yPos.first + 1) {
MutableList(xPos.second - xPos.first + 1) { ' ' }
}
for (line in lines) {
for ((start, end) in line.zipWithNext()) {
for (y in min(start.first, end.first)..max(start.first, end.first)) {
for (x in min(start.second, end.second)..max(start.second, end.second)) {
cave[y - yPos.first][x - xPos.first] = 'x'
}
}
}
}
return Triple(cave, yPos, xPos)
}
fun simulate(
cave: MutableList<MutableList<Char>>,
xPos: Pair<Int, Int>,
yPos: Pair<Int, Int>,
finishCondition: (Pos) -> Boolean
): Int {
var units = 0
while (true) {
var sand = Pos(0, 500)
units += 1
while (true) {
if (finishCondition(sand)) {
return units - 1
}
if (sand.y == yPos.second) {
break
}
if (cave[sand.y + 1 - yPos.first][sand.x - xPos.first] == ' ') {
sand += Pos(1, 0)
continue
}
if (cave[sand.y + 1 - yPos.first][sand.x - 1 - xPos.first] == ' ') {
sand += Pos(1, -1)
continue
}
if (cave[sand.y + 1 - yPos.first][sand.x + 1 - xPos.first] == ' ') {
sand += Pos(1,1)
continue
}
break
}
cave[sand.y - yPos.first][sand.x - xPos.first] = 'o'
// cave.print()
}
}
fun part1(input: List<String>): Int {
val (cave, yPos, xPos) = input.parse()
return simulate(cave, xPos, yPos) { sand ->
sand.y >= yPos.second
}
}
fun part2(input: List<String>): Int {
val (cave, yPos, xPos) = input.parse()
return simulate(cave, xPos, yPos) { sand ->
cave[0 - yPos.first][500 - xPos.first] == 'o'
}
}
val testInput = readInput("Day14_test")
val input = readInput("Day14")
assert(part1(testInput), 24)
println(part1(input))
assert(part2(testInput), 93)
println(part2(input))
}
// Time: 01:00 | 0 | Kotlin | 0 | 0 | 29aa4f978f6507b182cb6697a0a2896292c83584 | 3,183 | advent-of-code-2022 | Apache License 2.0 |
codeforces/kotlinheroes6/e.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.kotlinheroes6
private fun solve() {
readLn()
val a = readInts()
val st = SegmentsTreeMax(a.size)
val seen = IntArray(a.size + 1) { -1 }
for (i in a.indices) {
val x = a[i]
val prev = seen[x]
if (prev == -1) {
seen[x] = i
continue
}
val best = maxOf(st.get(prev, i), if (prev + 1 == i) 0 else 1)
st.set(prev, best + 2)
}
println(maxOf(st.get(0, a.size), 1))
}
fun main() = repeat(readInt()) { solve() }
private class SegmentsTreeMax(size: Int) {
val two: Int
val a: Array<Int>
init {
var t = 1
while (t < size) {
t *= 2
}
two = t
a = Array<Int>(2 * two, {_ -> 0})
}
fun get(from: Int, to: Int): Int {
var res = Integer.MIN_VALUE
var x = two + from
var y = two + to
while (x < y) {
if (x % 2 == 1) {
res = Math.max(res, a[x])
x++
}
if (y % 2 == 1) {
y--
res = Math.max(res, a[y])
}
x /= 2
y /= 2
}
return res
}
fun set(pos: Int, v: Int) {
var x = two + pos
a[x] = v
while (x >= 2) {
x /= 2
a[x] = Math.max(a[2 * x], a[2 * x + 1])
}
}
}
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,250 | competitions | The Unlicense |
src/main/kotlin/days/Day21.kt | sicruse | 315,469,617 | false | null | package days
class Day21 : Day(21) {
private val recipies: Map<Set<String>, Set<String>> by lazy {
inputList.map { text ->
val ingredients = text.split(" (").first().split(" ").toSet()
val allergens = text.split("(contains ").last().dropLast(1).split(", ").toSet()
ingredients to allergens
}.toMap()
}
private val allIngredients: Set<String> by lazy { recipies.keys.flatten().toSet() }
private val allAllergens: Set<String> by lazy { recipies.values.flatten().toSet() }
private val safeIngredients: Set<String> by lazy { allIngredients subtract unsafeIngredients }
private val unsafeIngredients by lazy {
allAllergens.flatMap { allergen ->
recipies
.mapNotNull { (ingredients, allergens) ->
if (allergen in allergens) ingredients else null
}
.reduce { remainingIngredients, ingredients -> ingredients intersect remainingIngredients }
}.toSet()
}
override fun partOne(): Any {
val allRecipies = recipies.keys
return allRecipies.sumOf { ingredients ->
ingredients.count { ingredient -> ingredient in safeIngredients }
}
}
override fun partTwo(): Any {
// Build the map of Allergens to Ingredients
val dangerousIngredientList: MutableMap<String, String> = mutableMapOf()
// First construct a mutable map of allergens to possible ingredients
val allergensToIngredients =
allAllergens.map { allergen ->
val possibleIngredients =
recipies
.mapNotNull{ (ingredients, allergens) ->
if (allergen in allergens) ingredients - safeIngredients else null
}
.reduce { remainingIngredients, ingredients -> ingredients intersect remainingIngredients }
.toMutableSet()
allergen to possibleIngredients
}.toMap().toMutableMap()
// Iterate through the map of allergens to possible ingredients
// identify allergens which match a single ingredient
while (allergensToIngredients.isNotEmpty()) {
val match = allergensToIngredients
.mapNotNull { (allergen, ingredients) ->
if (ingredients.size == 1) allergen to ingredients.first() else null
}
.toMap()
// remove the matched allergens from the search set
val matchedAllergens = match.keys
allergensToIngredients.keys.removeAll(matchedAllergens)
// remove the matched ingredients from the possible ingredients search sets
val matchedIngredients = match.values
val possibleIngredients = allergensToIngredients.values
possibleIngredients.forEach { ingredientSet -> ingredientSet.removeAll(matchedIngredients) }
// update our result set with the match data
dangerousIngredientList += match
}
return dangerousIngredientList
.entries
.sortedBy { (allergen, _) -> allergen }
.joinToString(",") { (_, ingredient) -> ingredient }
}
}
| 0 | Kotlin | 0 | 0 | 9a07af4879a6eca534c5dd7eb9fc60b71bfa2f0f | 3,284 | aoc-kotlin-2020 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/ru/timakden/aoc/year2022/Day02.kt | timakden | 76,895,831 | false | {"Kotlin": 321649} | package ru.timakden.aoc.year2022
import ru.timakden.aoc.util.measure
import ru.timakden.aoc.util.readInput
import ru.timakden.aoc.year2022.Day02.Outcome.*
import ru.timakden.aoc.year2022.Day02.Shape.Companion.canDefeat
import ru.timakden.aoc.year2022.Day02.Shape.Companion.getShapeByCondition
import ru.timakden.aoc.year2022.Day02.Shape.Companion.toShape
/**
* [Day 2: Rock Paper Scissors](https://adventofcode.com/2022/day/2).
*/
object Day02 {
@JvmStatic
fun main(args: Array<String>) {
measure {
val input = readInput("year2022/Day02")
println("Part One: ${part1(input)}")
println("Part Two: ${part2(input)}")
}
}
fun part1(input: List<String>): Int {
return input.sumOf { round ->
val (opponent, player) = round.split("\\s+".toRegex()).let { it.first().toShape() to it.last().toShape() }
player.score + when {
opponent == player -> DRAW.score
player.canDefeat(opponent) -> WIN.score
else -> DEFEAT.score
}
}
}
fun part2(input: List<String>): Int {
return input.sumOf { round ->
val (opponent, player) = round.split("\\s+".toRegex()).let {
val shape = it.first().toShape()
shape to shape.getShapeByCondition(it.last())
}
player.score + when {
opponent == player -> DRAW.score
player.canDefeat(opponent) -> WIN.score
else -> DEFEAT.score
}
}
}
private enum class Shape(val score: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3);
companion object {
fun String.toShape(): Shape {
return when (this) {
"A" -> ROCK
"B" -> PAPER
"C" -> SCISSORS
"X" -> ROCK
"Y" -> PAPER
"Z" -> SCISSORS
else -> error("Unsupported shape")
}
}
fun Shape.canDefeat(other: Shape) = this == ROCK && other == SCISSORS ||
this == PAPER && other == ROCK ||
this == SCISSORS && other == PAPER
fun Shape.getShapeByCondition(condition: String) = when (condition) {
"X" -> this.getLosingShape()
"Y" -> this
"Z" -> this.getWinningShape()
else -> error("Unsupported shape")
}
private fun Shape.getWinningShape() = when (this) {
ROCK -> PAPER
PAPER -> SCISSORS
SCISSORS -> ROCK
}
private fun Shape.getLosingShape() = when (this) {
ROCK -> SCISSORS
PAPER -> ROCK
SCISSORS -> PAPER
}
}
}
private enum class Outcome(val score: Int) {
DEFEAT(0),
DRAW(3),
WIN(6)
}
}
| 0 | Kotlin | 0 | 3 | acc4dceb69350c04f6ae42fc50315745f728cce1 | 3,016 | advent-of-code | MIT License |
src/Day07.kt | Sagolbah | 573,032,320 | false | {"Kotlin": 14528} | fun main() {
fun buildTree(input: List<String>): Node {
val root: Node.Dir = Node.Dir(mutableListOf(), null, "/")
var curr = root
for (line in input) {
val arr = line.split(" ")
if (arr.size == 3 && arr[1] == "cd") {
curr = when (val dest = arr[2]) {
".." -> {
curr.parent!!
}
"/" -> {
root
}
else -> {
curr.children.first { node -> node is Node.Dir && node.name == dest } as Node.Dir
}
}
} else if (arr[0] != "$") { // skip cd
val toAdd = when (arr[0]) {
"dir" -> Node.Dir(mutableListOf(), curr, arr[1])
else -> Node.File(arr[0].toInt(), arr[1])
}
curr.children.add(toAdd)
}
}
return root
}
fun dfs(node: Node, ans: MutableList<Int>): Int {
return when (node) {
is Node.File -> node.size
is Node.Dir -> {
var sum = 0
for (child in node.children) {
sum += dfs(child, ans)
}
ans.add(sum)
sum
}
}
}
fun part1(input: List<String>): Int {
val root = buildTree(input)
val ans = mutableListOf<Int>()
dfs(root, ans)
return ans.filter { x -> x <= 100000 }.sum()
}
fun part2(input: List<String>): Int {
val root = buildTree(input)
val ans = mutableListOf<Int>()
dfs(root, ans)
val available = 70000000 - ans.max() // it will be root
val need = 30000000 - available
return ans.filter { x -> x >= need }.min()
}
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
sealed class Node {
data class Dir(val children: MutableList<Node>, val parent: Dir?, val name: String) : Node()
data class File(val size: Int, val name: String) : Node()
} | 0 | Kotlin | 0 | 0 | 893c1797f3995c14e094b3baca66e23014e37d92 | 2,145 | advent-of-code-kt | Apache License 2.0 |
src/main/kotlin/16.kts | reitzig | 318,492,753 | false | null | import java.io.File
data class Rule(val name: String, val ranges: List<IntRange>) {
fun admits(value: Int): Boolean =
ranges.any { it.contains(value) }
companion object {
operator fun invoke(ruleLine: String): Rule {
val (name, rangesString) = ruleLine.split(":")
val ranges = rangesString
.split("or")
.map { rangeString ->
rangeString.split("-")
.map { it.trim().toInt() }
.let { IntRange(it[0], it[1]) }
}
return Rule(name, ranges)
}
}
}
data class Ticket(val fields: List<Int>) {
companion object {
operator fun invoke(ticketLine: String): Ticket =
ticketLine
.split(",")
.map { it.toInt() }
.let { Ticket(it) }
}
}
fun possibleRulesForField(fieldIndex: Int, tickets: List<Ticket>, rules: List<Rule>): List<Rule> =
rules.filter { rule ->
tickets.all { ticket ->
rule.admits(ticket.fields[fieldIndex])
}
}
fun disambiguateRuleAssignments(possibleRules: List<Pair<Int, List<Rule>>>): Map<Int, Rule> {
fun disambiguate(possibleAssignments: List<Pair<Int, List<Rule>>>): List<Pair<Int, List<Rule>>> =
when (possibleAssignments.size) {
0 -> listOf()
else -> {
val agreedAssignments = possibleAssignments
.filter { (_, rules) -> rules.size == 1 }
val agreedRules = agreedAssignments
.flatMap { it.second }
.distinct()
agreedAssignments +
possibleAssignments.subtract(agreedAssignments)
.map { (fieldIndex, rules) ->
Pair(fieldIndex, rules.subtract(agreedRules).toList())
}
.let { disambiguate(it) }
}
}
return disambiguate(possibleRules)
.map { (fieldIndex, rules) ->
Pair(fieldIndex, rules.first())
}
.toMap()
}
val input = File(args[0]).readLines()
val rules = input
.takeWhile { it.isNotBlank() }
.map { Rule(it) }
val myTicket = input
.dropWhile { it.trim() != "your ticket:" }
.drop(1)
.first()
.let { Ticket(it) }
val nearbyTickets = input
.dropWhile { it.trim() != "nearby tickets:" }
.drop(1)
.map { Ticket(it) }
// Part 1:
nearbyTickets
.flatMap { ticket ->
ticket.fields.filterNot { value ->
rules.any { it.admits(value) }
}
}
.sum()
.let { println(it) }
// Part 2:
val validTickets = nearbyTickets
.filter { ticket ->
ticket.fields.all { value ->
rules.any { it.admits(value) }
}
}
(0..validTickets.first().fields.lastIndex)
.map { Pair(it, possibleRulesForField(it, validTickets, rules)) }
.let { disambiguateRuleAssignments(it) }
.filter { (_, rule) -> rule.name.startsWith("departure") }
.map { (fieldIndex, _) -> myTicket.fields[fieldIndex] }
.fold(1L, Long::times)
.let { println(it) } | 0 | Kotlin | 0 | 0 | f17184fe55dfe06ac8897c2ecfe329a1efbf6a09 | 3,194 | advent-of-code-2020 | The Unlicense |
calendar/day15/Day15.kt | maartenh | 572,433,648 | false | {"Kotlin": 50914} | package day15
import Day
import Lines
import tools.*
import java.lang.Integer.max
import kotlin.math.abs
class Day15 : Day() {
override fun part1(input: Lines): Any {
val sensors = input.map { runParser(sensor(), it) }
val mergedRanges = rowCoverage(sensors, 2_000_000)
return mergedRanges.sumOf { it.last - it.first + 1 } -
sensors.map { it.nearestBeacon }.filter { it.y == 2_000_000 }.distinct().count()
}
private fun rowCoverage(
sensors: List<Sensor>,
targetRow: Int
): List<IntRange> {
val coverageRanges = sensors
.map {
val verticalDistance = abs(it.location.y - targetRow)
val extend = it.beaconDistance - verticalDistance
it.location.x - extend..it.location.x + extend
}
.filter { !it.isEmpty() }
.sortedBy { it.first }
val mergedRanges =
coverageRanges.drop(1).fold(listOf(coverageRanges.first())) { acc: List<IntRange>, range: IntRange ->
if (acc.last().last + 1 >= range.first) {
val mergedRange = acc.last().first..max(acc.last().last, range.last)
acc.dropLast(1).plusElement(mergedRange)
} else {
acc.plusElement(range)
}
}
return mergedRanges
}
override fun part2(input: Lines): Any {
val sensors = input.map { runParser(sensor(), it) }
val maxCoordinate = 4_000_000
val range = 0..maxCoordinate
val distressRowCoverage = range.asSequence()
.map { row -> row to rowCoverage(sensors, row) }
.first { it.second.size > 1 }
val distressLocation = Point(distressRowCoverage.second[0].last + 1, distressRowCoverage.first)
return distressLocation.x.toBigInteger() * 4000000.toBigInteger() + distressLocation.y.toBigInteger()
}
data class Point(val x: Int, val y: Int) {
fun distanceTo(target: Point): Int =
abs(x - target.x) + abs(y - target.y)
}
data class Sensor(val location: Point, val nearestBeacon: Point) {
val beaconDistance = location.distanceTo(nearestBeacon)
override fun toString(): String {
return "Sensor(location=$location, nearestBeacon=$nearestBeacon, beaconDistance=$beaconDistance)"
}
}
private fun point(): Parser<Point> =
(string("x=") seq int() seq string(", y=") seq int()).map {
Point(it.first.first.second, it.second)
}
private fun sensor(): Parser<Sensor> =
(string("Sensor at ") seq point() seq string(": closest beacon is at ") seq point()).map {
Sensor(it.first.first.second, it.second)
}
} | 0 | Kotlin | 0 | 0 | 4297aa0d7addcdc9077f86ad572f72d8e1f90fe8 | 2,784 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/be/tabs_spaces/advent2021/days/Day17.kt | janvryck | 433,393,768 | false | {"Kotlin": 58803} | package be.tabs_spaces.advent2021.days
import be.tabs_spaces.advent2021.util.sumToNFromOne
import kotlin.math.abs
class Day17 : Day(17) {
private val trajectoryControl = TargetArea.from(inputString).let { targetArea -> TrajectoryControl(targetArea) }
override fun partOne() = trajectoryControl.maxVerticalSpeed().sumToNFromOne()
override fun partTwo() = trajectoryControl.targetTrajectories().size
data class TrajectoryControl(val targetArea: TargetArea) {
fun targetTrajectories() = launchVelocityCandidates().filter { it.hits(targetArea) }
private fun launchVelocityCandidates() = (1..maxHorizontalSpeed()).flatMap { x ->
(minVerticalSpeed()..maxVerticalSpeed()).map { y -> Velocity(x, y) }
}
private fun minVerticalSpeed() = minSpeed(Point::y)
fun maxVerticalSpeed() = maxSpeed(Point::y) { abs(it + 1) }
private fun maxHorizontalSpeed() = maxSpeed(Point::x)
private fun maxSpeed(axis: (Point) -> Int, transform: ((Int) -> Int) = { it }): Int {
return listOf(
axis(targetArea.bottomRight),
axis(targetArea.upperLeft),
).maxOf(transform)
}
private fun minSpeed(axis: (Point) -> Int, transform: ((Int) -> Int) = { it }): Int {
return listOf(
axis(targetArea.bottomRight),
axis(targetArea.upperLeft),
).minOf(transform)
}
}
data class TargetArea(val upperLeft: Point, val bottomRight: Point) {
companion object {
fun from(rawInput: String): TargetArea {
val (x, y) = rawInput.drop("target area: ".length).split(", ")
val (xMin, xMax) = x.drop("x=".length).split("..").map { it.toInt() }
val (yMin, yMax) = y.drop("y=".length).split("..").map { it.toInt() }
return TargetArea(Point(xMin, yMax), Point(xMax, yMin))
}
}
fun contains(point: Point) = point.let { (x, y) ->
x in upperLeft.x..bottomRight.x && y in bottomRight.y..upperLeft.y
}
fun overshot(point: Point) = point.let { (x, y) -> x > bottomRight.x || y < bottomRight.y }
}
data class Velocity(val dX: Int, val dY: Int) {
fun hits(targetArea: TargetArea): Boolean {
var currentHorizontalSpeed = dX
var currentVerticalSpeed = dY
var point = Point(0, 0)
do {
point = point.let { (x, y) -> Point(x + currentHorizontalSpeed, y + currentVerticalSpeed) }
if (targetArea.contains(point)) return true
currentHorizontalSpeed = maxOf(0, currentHorizontalSpeed - 1)
currentVerticalSpeed -= 1
} while (!targetArea.overshot(point))
return false
}
}
data class Point(val x: Int, val y: Int)
}
| 0 | Kotlin | 0 | 0 | f6c8dc0cf28abfa7f610ffb69ffe837ba14bafa9 | 2,891 | advent-2021 | Creative Commons Zero v1.0 Universal |
src/Day13.kt | oleksandrbalan | 572,863,834 | false | {"Kotlin": 27338} | fun main() {
val input = readInput("Day13")
.filterNot { it.isEmpty() }
.map { it.parseRoot() }
val part1 = input
.chunked(2)
.mapIndexed { index, (left, right) -> if (left < right) index + 1 else -0 }
.sum()
println("Part1: $part1")
val divider1 = "[[2]]".parseRoot()
val divider2 = "[[6]]".parseRoot()
val list = (input + divider1 + divider2).sorted()
val part2 = (list.indexOf(divider1) + 1) * (list.indexOf(divider2) + 1)
println("Part2: $part2")
}
private fun String.parseRoot(): Item {
var index = 0
fun String.parseItem(): Item {
if (get(index).isDigit()) {
var number = ""
while (get(index).isDigit()) {
number += get(index)
index += 1
}
return Number(number.toInt())
}
if (get(index) == '[') {
index += 1
val items = mutableListOf<Item>()
while (get(index) != ']') {
val a = parseItem()
items.add(a)
if (get(index) == ',') {
index += 1
}
}
index += 1
return ItemList(items)
}
return ItemList(emptyList())
}
return parseItem()
}
private sealed interface Item : Comparable<Item>
private data class Number(val value: Int) : Item {
override fun compareTo(other: Item): Int =
when (other) {
is Number -> value.compareTo(other.value)
is ItemList -> ItemList(listOf(this)).compareTo(other)
}
}
private data class ItemList(val items: List<Item>) : Item {
override fun compareTo(other: Item): Int =
when (other) {
is Number -> this.compareTo(ItemList(listOf(other)))
is ItemList -> {
val zip = items.zip(other.items)
val zipCompare = zip
.map { it.first.compareTo(it.second) }
.firstOrNull { it != 0 }
?: 0
if (zipCompare != 0) {
zipCompare
} else {
items.size.compareTo(other.items.size)
}
}
}
}
| 0 | Kotlin | 0 | 2 | 1493b9752ea4e3db8164edc2dc899f73146eeb50 | 2,252 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/Day15.kt | jcornaz | 573,137,552 | false | {"Kotlin": 76776} | import kotlin.math.abs
object Day15 {
fun part1(input: String): Long = numberOfNonBeacon(input, 2000000).toLong()
fun part2(input: String, searchScope: Int): Long {
val scan = Scan.parse(input)
val beacon = (0..searchScope)
.asSequence()
.map { y -> y to scan.uncoveredRange(y, 0..searchScope) }
.first { (_, range) -> range.size > 0 }
.let { (y, range) -> range.asSequence().map { Position(it, y) } }
.first()
return beacon.x.toLong() * 4_000_000 + beacon.y.toLong()
}
private val LINE_REGEX = Regex("Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)")
fun numberOfNonBeacon(input: String, y: Int): Int {
val scan = Scan.parse(input)
val searchRange = scan.minX..scan.maxX
val uncovered = scan.uncoveredRange(y, scan.minX..scan.maxX)
return searchRange.size - uncovered.size - scan.beacons.count { it.y == y }
}
private class Scan private constructor(val beacons: Set<Position>, private val sensors: List<Sensor>) {
val minX get() = sensors.minOf { it.minX }
val maxX get() = sensors.maxOf { it.maxX }
fun uncoveredRange(y: Int, initialRange: IntRange): SearchRange =
sensors.fold(SearchRange(initialRange)) { range, sensor ->
sensor.coverage(y)?.let(range::remove) ?: range
}
companion object {
fun parse(input: String): Scan {
val beacons = mutableSetOf<Position>()
val sensors = mutableListOf<Sensor>()
input.lineSequence()
.forEach { line ->
val (sensorPosition, beaconPosition) = parseLine(line)
beacons.add(beaconPosition)
sensors.add(Sensor(sensorPosition, sensorPosition.distanceTo(beaconPosition)))
}
return Scan(beacons, sensors)
}
}
}
private fun parseLine(line: String): Pair<Position, Position> {
val (_, sx, sy, bx, by) = LINE_REGEX.find(line)!!.groupValues
return Position(sx.toInt(), sy.toInt()) to Position(bx.toInt(), by.toInt())
}
private data class Position(val x: Int, val y: Int) {
fun distanceTo(other: Position): Int {
return abs(x - other.x) + abs(y - other.y)
}
}
private data class Sensor(val position: Position, val range: Int) {
val minX = position.x - range
val maxX = position.x + range
operator fun contains(otherPosition: Position) =
coverage(otherPosition.y)?.let { otherPosition.x in it } ?: false
fun coverage(y: Int): IntRange? {
val vDist = abs(y - position.y)
if (vDist > range) return null
val extent = range - vDist
return (position.x - extent)..(position.x + extent)
}
}
private class SearchRange private constructor(val ranges: List<IntRange>) {
constructor(range: IntRange) : this(listOf(range))
val size: Int get() = ranges.sumOf { it.size }
fun asSequence() = ranges.asSequence().flatMap { it.asSequence() }
fun remove(range: IntRange): SearchRange {
if (ranges.isEmpty()) return this
return SearchRange(ranges.flatMap { it.remove(range) })
}
private fun IntRange.remove(other: IntRange): List<IntRange> = buildList {
(first .. minOf(other.first - 1, last))
.takeUnless { it.isEmpty() }
?.let(::add)
(maxOf(other.last + 1, first)..endInclusive)
.takeUnless { it.isEmpty() }
?.let(::add)
}
}
val IntRange.size: Int get() = last - first + 1
}
| 1 | Kotlin | 0 | 0 | 979c00c4a51567b341d6936761bd43c39d314510 | 3,812 | aoc-kotlin-2022 | The Unlicense |
src/Day04.kt | iartemiev | 573,038,071 | false | {"Kotlin": 21075} | class SectionRange(private val start: Int, private val end: Int) {
fun partiallyOverlapsWith(range2: SectionRange): Boolean {
return end >= range2.start && start <= range2.end
}
fun fullyOverlapsWith(range2: SectionRange): Boolean {
return (start <= range2.start && end >= range2.end)
|| (range2.start <= start && range2.end >= end)
}
}
fun rangePairFromLine(line: String): Pair<SectionRange, SectionRange> {
val (range1, range2) = line.split(",").map{
val (start, end) = it.split("-")
SectionRange(start.toInt(), end.toInt())
}
return Pair(range1, range2)
}
fun main() {
fun part1(input: List<String>): Int {
return input.count {
val (range1, range2) = rangePairFromLine(it)
range1.fullyOverlapsWith(range2)
}
}
fun part2(input: List<String>): Int {
return input.count {
val (range1, range2) = rangePairFromLine(it)
range1.partiallyOverlapsWith(range2)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8d2b7a974c2736903a9def65282be91fbb104ffd | 1,212 | advent-of-code | Apache License 2.0 |
src/Day03.kt | fonglh | 573,269,990 | false | {"Kotlin": 48950, "Ruby": 1701} | fun main() {
fun getPriority(input: Char): Int {
return if (input.isUpperCase()) {
input.code - 64 + 26
} else {
input.code - 96
}
}
fun part1(input: List<String>): Int {
var prioritySum = 0
input.forEach {
val midIndex = it.length / 2
val firstCompartment = it.substring(0, midIndex)
val secondCompartment = it.substring(midIndex)
val firstSet = firstCompartment.toCharArray().toSet()
val secondSet = secondCompartment.toCharArray().toSet()
val commonChar = firstSet.intersect(secondSet).elementAt(0)
prioritySum += getPriority(commonChar)
}
return prioritySum
}
fun part2(input: List<String>): Int {
var prioritySum = 0
var commonCharSet: Set<Char> = emptySet()
input.forEachIndexed { index, it ->
if (index % 3 == 0) {
commonCharSet = it.toCharArray().toSet()
}
commonCharSet = commonCharSet.intersect(it.toCharArray().toSet())
if ((index+1) % 3 == 0) {
val commonChar = commonCharSet.elementAt(0)
prioritySum += getPriority(commonChar)
}
}
return prioritySum
}
// 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 | ef41300d53c604fcd0f4d4c1783cc16916ef879b | 1,583 | advent-of-code-2022 | Apache License 2.0 |
src/day-6.kt | drademacher | 160,820,401 | false | null | import java.io.File
import kotlin.math.abs
fun main(args: Array<String>) {
println("part 1: " + partOne())
println("part 2: " + partTwo())
}
private data class Point(val x: Int, val y: Int) {
fun distance(other: Point): Int = abs(x - other.x) + abs(y - other.y)
}
private fun partOne(): Int? {
val points = parseFile()
val areaOfPoint = HashMap<Point, Int>()
val minX = points.map { it.x }.min()!!
val maxX = points.map { it.x }.max()!!
val minY = points.map { it.y }.min()!!
val maxY = points.map { it.y }.max()!!
val pointsToIgnore = computerOuterPoints(minX, maxX, minY, maxY, points)
for (x in minX..maxX) {
for (y in minY..maxY) {
val closest = points.map { Pair(it, Point(x, y).distance(it)) }.sortedBy { it.second }
val (p, d) = closest[0]
if (d == closest[1].second || p in pointsToIgnore) {
continue
}
val count = areaOfPoint.getOrDefault(p, 0)
areaOfPoint[p] = count + 1
}
}
return areaOfPoint.values.max()
}
private fun partTwo(): Int {
val points = parseFile()
var numberOfValidPoints = 0
val minX = points.map { it.x }.min()!!
val maxX = points.map { it.x }.max()!!
val minY = points.map { it.y }.min()!!
val maxY = points.map { it.y }.max()!!
for (x in minX..maxX) {
for (y in minY..maxY) {
val sumOfDistances = points.map { Point(x, y).distance(it) }.sum()
if (sumOfDistances < 10000) {
numberOfValidPoints += 1
}
}
}
return numberOfValidPoints
}
private fun parseFile(): List<Point> {
val rawFile = File("res/day-6.txt").readText()
val points = rawFile
.split("\n")
.filter { it != "" }
.map { it.split(", ").map(String::toInt) }
.map { Point(it[0], it[1]) }
return points
}
private fun computerOuterPoints(minX: Int, maxX: Int, minY: Int, maxY: Int, points: List<Point>): MutableSet<Point> {
val pointsToIgnore = mutableSetOf<Point>()
for (x in listOf(minX, maxX)) {
for (y in minY..maxY) {
val closest = points.minBy { Point(x, y).distance(it) }!!
pointsToIgnore.add(closest)
}
}
for (x in minX..maxX) {
for (y in listOf(minY, maxY)) {
val closest = points.minBy { Point(x, y).distance(it) }!!
pointsToIgnore.add(closest)
}
}
return pointsToIgnore
}
| 0 | Kotlin | 0 | 0 | a7f04450406a08a5d9320271148e0ae226f34ac3 | 2,510 | advent-of-code-2018 | MIT License |
src/year2022/day02/Day02.kt | TheSunshinator | 572,121,335 | false | {"Kotlin": 144661} | package year2022.day02
import io.kotest.matchers.shouldBe
import utils.readInput
fun main() {
val testInput = readInput("02", "test_input")
val realInput = readInput("02", "input")
testInput.part1().also(::println) shouldBe 15
realInput.part1().let(::println)
testInput.part2().also(::println) shouldBe 12
realInput.part2().let(::println)
}
private fun <T> List<String>.totalScore(
parseSecondInput: (Char) -> T,
computeScore: (opponent: GameChoice, T) -> Int,
): Int {
return asSequence()
.map { GameChoice.parse(it[0]) to parseSecondInput(it[2]) }
.map { (opponent, t) -> computeScore(opponent, t) }
.sum()
}
private fun List<String>.part1() = totalScore(
parseSecondInput = GameChoice::parse,
computeScore = { opponent, self -> self.score + (self * opponent).score }
)
private fun List<String>.part2() = totalScore(
parseSecondInput = Outcome::parse,
computeScore = { opponent, outcome -> (outcome / opponent).score + outcome.score }
)
private enum class GameChoice(
val score: Int,
) {
ROCK(1) {
override fun times(opponent: GameChoice) = when (opponent) {
ROCK -> Outcome.DRAW
PAPER -> Outcome.DEFEAT
SCISSORS -> Outcome.WIN
}
},
PAPER(2) {
override fun times(opponent: GameChoice) = when (opponent) {
ROCK -> Outcome.WIN
PAPER -> Outcome.DRAW
SCISSORS -> Outcome.DEFEAT
}
},
SCISSORS(3) {
override fun times(opponent: GameChoice) = when (opponent) {
ROCK -> Outcome.DEFEAT
PAPER -> Outcome.WIN
SCISSORS -> Outcome.DRAW
}
};
abstract operator fun times(opponent: GameChoice): Outcome
companion object {
internal fun parse(choice: Char): GameChoice = when (choice) {
'A', 'X' -> ROCK
'B', 'Y' -> PAPER
else -> SCISSORS
}
}
}
private enum class Outcome(val score: Int) {
WIN(6) {
override fun div(opponent: GameChoice) = when (opponent) {
GameChoice.ROCK -> GameChoice.PAPER
GameChoice.PAPER -> GameChoice.SCISSORS
GameChoice.SCISSORS -> GameChoice.ROCK
}
},
DRAW(3) {
override fun div(opponent: GameChoice) = opponent
},
DEFEAT(0) {
override fun div(opponent: GameChoice) = when (opponent) {
GameChoice.ROCK -> GameChoice.SCISSORS
GameChoice.PAPER -> GameChoice.ROCK
GameChoice.SCISSORS -> GameChoice.PAPER
}
};
abstract operator fun div(opponent: GameChoice): GameChoice
companion object {
internal fun parse(choice: Char): Outcome = when (choice) {
'X' -> DEFEAT
'Y' -> DRAW
else -> WIN
}
}
}
| 0 | Kotlin | 0 | 0 | d050e86fa5591447f4dd38816877b475fba512d0 | 2,836 | Advent-of-Code | Apache License 2.0 |
src/day09/Day09.kt | schrami8 | 572,631,109 | false | {"Kotlin": 18696} | package day09
import readInput
import java.util.*
import kotlin.collections.ArrayList
import kotlin.math.abs
data class Location(var x: Int, var y: Int) {
fun isTouching(location: Location): Boolean {
return abs(x - location.x) <= 1 && abs(y - location.y) <= 1
}
}
fun move(direction: String, location: Location) {
when (direction) {
"R" -> location.x++
"L" -> location.x--
"U" -> location.y++
"D" -> location.y--
}
}
fun trackMovement(head: Location, tail: Location) {
if (!head.isTouching(tail)) {
if (head.x > tail.x) tail.x++
if (head.y > tail.y) tail.y++
if (head.x < tail.x) tail.x--
if (head.y < tail.y) tail.y--
}
}
fun createMotions(input: List<String>): List<Pair<String, Int>> {
return input.map { it ->
it.split(" ").let { Pair(it[0], it[1].toInt()) }}
}
fun main() {
fun part1(input: List<Pair<String, Int>>): Int {
val head = Location(0, 0)
val tail = Location(0, 0)
val visited = mutableSetOf<Location>()
input.forEach { pair ->
repeat(pair.second) {
move(pair.first, head)
trackMovement(head, tail)
visited.add(tail.copy())
}
}
return visited.size
}
fun part2(input: List<Pair<String, Int>>): Int {
val locations = mutableListOf<Location>()
for (i in 0..9) {
val location = Location(0, 0)
locations.add(location)
}
val visited = mutableSetOf<Location>()
input.forEach { pair ->
repeat(pair.second) { index ->
move(pair.first, locations[0]) // head
for (i in 0..locations.size - 2)
trackMovement(locations[i], locations[i + 1])
visited.add(locations.last().copy())
}
}
return visited.size
}
// test if implementation meets criteria from the description, like:
val testInput = createMotions(readInput("day09/Day09_test"))
check(part1(testInput) == 13)
val input = createMotions(readInput("day09/Day09"))
println(part1(input))
check(part2(testInput) == 1)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 215f89d7cd894ce58244f27e8f756af28420fc94 | 2,252 | advent-of-code-kotlin | Apache License 2.0 |
day-05/src/main/kotlin/HydrothermalVenture.kt | diogomr | 433,940,168 | false | {"Kotlin": 92651} | fun main() {
println("Part One Solution: ${partOne()}")
println("Part Two Solution: ${partTwo()}")
}
private fun partOne(): Int {
val field = Array(1000) {
IntArray(1000)
}
readLines().forEach {
val linePoints = it.getLinePoints(diagonals = false)
linePoints.forEach { p ->
field[p.x][p.y] = ++field[p.x][p.y]
}
}
return countOverlappedPoints(field)
}
private fun partTwo(): Int {
val field = Array(1000) {
IntArray(1000)
}
readLines().forEach {
val linePoints = it.getLinePoints(diagonals = true)
linePoints.forEach { p ->
field[p.x][p.y] = ++field[p.x][p.y]
}
}
return countOverlappedPoints(field)
}
private fun countOverlappedPoints(field: Array<IntArray>) =
field.iterator().asSequence().flatMap { it.asIterable() }.count { it > 1 }
private fun readLines(): List<Line> {
return readInputLines()
.map {
val coordinates = it.split(" -> ")
val from = coordinates[0].split(",")
val to = coordinates[1].split(",")
Line(
from = Point(from[0].toInt(), from[1].toInt()),
to = Point(to[0].toInt(), to[1].toInt())
)
}
}
data class Point(val x: Int, val y: Int)
data class Line(val from: Point, val to: Point) {
fun getLinePoints(diagonals: Boolean = false): Collection<Point> {
return if (to.x == from.x) {
val start = if (to.y > from.y) from.y else to.y
val end = if (to.y > from.y) to.y else from.y
IntRange(start, end)
.map { Point(from.x, it) }
} else if (to.y == from.y) {
val start = if (to.x > from.x) from.x else to.x
val end = if (to.x > from.x) to.x else from.x
IntRange(start, end)
.map { Point(it, from.y) }
} else {
if (!diagonals) {
return emptyList()
}
val xStep = if (to.x > from.x) 1 else -1
val yStep = if (to.y > from.y) 1 else -1
val diagonalPoints = mutableListOf<Point>()
diagonalPoints.add(from)
do {
val last = diagonalPoints.last()
val currentPoint = last.copy(x = last.x + xStep, y = last.y + yStep)
diagonalPoints.add(currentPoint)
} while (currentPoint != to)
diagonalPoints
}
}
}
private fun readInputLines(): List<String> {
return {}::class.java.classLoader.getResource("input.txt")
.readText()
.split("\n")
.filter { it.isNotBlank() }
}
| 0 | Kotlin | 0 | 0 | 17af21b269739e04480cc2595f706254bc455008 | 2,675 | aoc-2021 | MIT License |
src/main/kotlin/de/pgebert/aoc/days/Day03.kt | pgebert | 724,032,034 | false | {"Kotlin": 65831} | package de.pgebert.aoc.days
import de.pgebert.aoc.Day
import kotlin.math.max
import kotlin.math.min
class Day03(input: String? = null) : Day(3, "Gear Ratios", input) {
private val numberRegex = "\\d+".toRegex()
private val specialCharacterRegex = "[^\\d.]".toRegex()
private val gearRegex = "\\*".toRegex()
override fun partOne() = inputList.mapIndexed { row, line ->
numberRegex.findAll(line).sumOf { match ->
val rangeStart = max(match.range.first - 1, 0)
val rangeEnd = min(match.range.last + 1, inputList.first().length - 1)
val isSpecialCharacterAdjacent = isSpecialCharacterMatch(row, IntRange(rangeStart, rangeEnd))
if (isSpecialCharacterAdjacent) match.value.toInt() else 0
}
}.sum()
private fun isSpecialCharacterMatch(rowIndex: Int, range: IntRange): Boolean {
val previousRow = inputList.getOrNull(rowIndex - 1)?.slice(range)?.contains(specialCharacterRegex)
val nextRow = inputList.getOrNull(rowIndex + 1)?.slice(range)?.contains(specialCharacterRegex)
val currentRowLeft = inputList[rowIndex].getOrNull(range.first)?.toString()?.matches(specialCharacterRegex)
val currentRowRight = inputList[rowIndex].getOrNull(range.last)?.toString()?.matches(specialCharacterRegex)
return listOf(previousRow, nextRow, currentRowLeft, currentRowRight).contains(true)
}
override fun partTwo() = inputList.mapIndexed { row, line ->
if (0 < row && row < inputList.size - 1) 0
gearRegex.findAll(line).sumOf { match ->
val rangeStart = max(match.range.first - 1, 0)
val rangeEnd = min(match.range.last + 1, inputList.first().length - 1)
val numbers = findMatchingNumbers(row, IntRange(rangeStart, rangeEnd))
if (numbers.size == 2) numbers.first() * numbers.last() else 0
}
}.sum()
private fun findMatchingNumbers(rowIndex: Int, range: IntRange): List<Int> {
val previousRow = numberRegex.findAll(inputList[rowIndex - 1]).filter { it.range.intersect(range).isNotEmpty() }
val currentRow = numberRegex.findAll(inputList[rowIndex]).filter { it.range.intersect(range).isNotEmpty() }
val nextRow = numberRegex.findAll(inputList[rowIndex + 1]).filter { it.range.intersect(range).isNotEmpty() }
return (previousRow + currentRow + nextRow).map { it.value.toInt() }.toList()
}
}
| 0 | Kotlin | 1 | 0 | a30d3987f1976889b8d143f0843bbf95ff51bad2 | 2,435 | advent-of-code-2023 | MIT License |
src/Day18.kt | er453r | 572,440,270 | false | {"Kotlin": 69456} | fun main() {
fun part1(input: List<String>): Int {
val occupied = input.map { it.ints() }.map { (x, y, z) -> Vector3d(x, y, z) }.toSet()
return occupied.sumOf { cube -> 6 - Vector3d.DIRECTIONS.count { dir -> cube + dir in occupied } }
}
fun part2(input: List<String>): Int {
val occupied = input.map { it.ints() }.map { (x, y, z) -> Vector3d(x, y, z) }.toMutableSet()
val minX = occupied.minOf { it.x } - 1
val minY = occupied.minOf { it.y } - 1
val minZ = occupied.minOf { it.z } - 1
val maxX = occupied.maxOf { it.x } + 1
val maxY = occupied.maxOf { it.y } + 1
val maxZ = occupied.maxOf { it.z } + 1
val xRange = minX..maxX
val yRange = minY..maxY
val zRange = minZ..maxZ
val all = xRange.map { x -> yRange.map { y -> zRange.map { z -> Vector3d(x, y, z) } } }.flatten().flatten().toSet()
val airOutside = mutableSetOf<Vector3d>()
val visitQueue = mutableListOf(Vector3d(minX, minY, minZ))
while (visitQueue.isNotEmpty()) { // fill the outside with air!
val candidate = visitQueue.removeLast()
airOutside += candidate
for (direction in Vector3d.DIRECTIONS) {
val next = candidate + direction
if (next in airOutside || next in occupied || next.x !in xRange || next.y !in yRange || next.z !in zRange)
continue
visitQueue += next
}
}
val airPockets = all - airOutside - occupied
occupied += airPockets
return occupied.sumOf { cube -> 6 - Vector3d.DIRECTIONS.count { dir -> cube + dir in occupied } }
}
test(
day = 18,
testTarget1 = 64,
testTarget2 = 58,
part1 = ::part1,
part2 = ::part2,
)
}
| 0 | Kotlin | 0 | 0 | 9f98e24485cd7afda383c273ff2479ec4fa9c6dd | 1,844 | aoc2022 | Apache License 2.0 |
src/Day03.kt | wooodenleg | 572,658,318 | false | {"Kotlin": 30668} | val smallLetters = buildList {
var character = 'a'.also(::add)
while (character != 'z') add(++character)
}
val allLetters = smallLetters + smallLetters.map(Char::uppercaseChar)
fun main() {
fun part1(input: List<String>): Int {
var sum = 0
for (line in input) {
val firstCompartment = line.subSequence(0, line.length / 2).asIterable()
val secondCompartment = line.subSequence(line.length / 2, line.length).asIterable()
val sharedItem = (firstCompartment intersect secondCompartment.toSet()).first()
sum += allLetters.indexOf(sharedItem) + 1 // +1 because priorities are indexed from 1
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
for (group in input.chunked(3)) {
val (first, second, third) = group.map(String::asIterable).map(Iterable<Char>::toSet)
val sharedItem = (first intersect second intersect third).first()
sum += allLetters.indexOf(sharedItem) + 1
}
return sum
}
val testInput = readInputLines("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInputLines("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | ff1f3198f42d1880e067e97f884c66c515c8eb87 | 1,283 | advent-of-code-2022 | Apache License 2.0 |
rl-algo/src/main/kotlin/wumo/sim/algorithm/drl/common/SegmentTree.kt | wumo | 305,330,037 | false | null | package wumo.sim.algorithm.drl.common
open class SegmentTree<T>(val capacity: Int,
inline val operation: (T, T) -> T,
neutral_element: T) {
init {
assert(capacity > 0 && (capacity and (capacity - 1)) == 0) {
"capacity must be positive and a power of 2."
}
}
val value = MutableList(2 * capacity) { neutral_element }
fun reduce_helper(start: Int, end: Int, node: Int, node_start: Int, node_end: Int): T {
if (start == node_start && end == node_end)
return value[node]
val mid = (node_start + node_end) / 2
return when {
end <= mid -> reduce_helper(start, end, 2 * node, node_start, mid)
mid + 1 <= start -> reduce_helper(start, end, 2 * node + 1, mid + 1, node_end)
else -> operation(
reduce_helper(start, mid, 2 * node, node_start, mid),
reduce_helper(mid + 1, end, 2 * node + 1, mid + 1, node_end)
)
}
}
fun reduce(start: Int = 0, end: Int? = null): T {
var end = end ?: capacity
if (end < 0)
end += capacity
end -= 1
return reduce_helper(start, end, 1, 0, capacity - 1)
}
operator fun set(idx: Int, v: T) {
//index of the leaf
var idx = idx + capacity
value[idx] = v
idx /= 2
while (idx >= 1) {
value[idx] = operation(
value[2 * idx],
value[2 * idx + 1]
)
idx /= 2
}
}
operator fun get(idx: Int): T {
assert(idx in 0 until capacity)
return value[capacity + idx]
}
}
class SumSegmentTree(capacity: Int) : SegmentTree<Float>(
capacity = capacity,
operation = { a, b -> a + b },
neutral_element = 0f) {
fun sum(start: Int = 0, end: Int? = null): Float =
reduce(start, end)
fun find_prefixsum_idx(prefixsum: Float): Int {
assert(prefixsum in 0f..(sum() + 1e-5f))
var prefixsum = prefixsum
var idx = 1
while (idx < capacity)//while non-leaf
if (value[2 * idx] > prefixsum)
idx *= 2
else {
prefixsum -= value[2 * idx]
idx = 2 * idx + 1
}
return idx - capacity
}
}
class MinSegmentTree(capacity: Int) : SegmentTree<Float>(
capacity = capacity,
operation = { a, b -> minOf(a, b) },
neutral_element = Float.POSITIVE_INFINITY) {
fun min(start: Int = 0, end: Int? = null): Float =
reduce(start, end)
} | 0 | null | 0 | 0 | 2a3a5118239b27eeb268cd1e7bdbfe5f5604dab6 | 2,374 | sim-world | MIT License |
src/main/kotlin/be/seppevolkaerts/day7/Day7.kt | Cybermaxke | 727,453,020 | false | {"Kotlin": 35118} | package be.seppevolkaerts.day7
data class Hand(
val cards: String,
val bid: Int,
)
fun parseHands(iterable: Iterable<String>) =
iterable.map { line ->
val split = line.split(' ')
Hand(split[0], split[1].toInt())
}
private fun Hand.type(jokerChar: Char? = null): Int {
val groupsByChar = cards.groupBy { it }.mapValues { it.value.size }
val jokers = if (jokerChar != null) groupsByChar[jokerChar] ?: 0 else 0
fun match(vararg sizes: Int): Boolean {
val remainingGroupsByChar = groupsByChar.toMutableMap()
val remainingSizes = sizes.toMutableList()
// first match without joker
remainingSizes.removeIf { size ->
val itr = remainingGroupsByChar.entries.iterator()
while (itr.hasNext()) {
val group = itr.next()
if (group.value == size && group.key != jokerChar) {
itr.remove()
return@removeIf true
}
}
false
}
if (jokerChar != null && jokers > 0 && remainingSizes.isNotEmpty()) {
var remainingJokers = jokers
remainingSizes.removeIf { size ->
if (remainingJokers == 0)
return@removeIf false
val itr = remainingGroupsByChar.entries.iterator()
while (itr.hasNext()) {
val group = itr.next()
val jokersToUse = size - group.value
if (remainingJokers >= jokersToUse && group.key != jokerChar) {
itr.remove()
remainingJokers -= jokersToUse
return@removeIf true
}
}
false
}
remainingSizes.removeIf { size ->
if (size == remainingJokers) {
remainingJokers = 0
return@removeIf true
}
false
}
}
return remainingSizes.isEmpty()
}
return when {
// Five of a kind
match(5) -> 6
// Four of a kind
match(4) -> 5
// Full house
match(2, 3) -> 4
// Three of a kind
match(3) -> 3
// Two pairs
match(2, 2) -> 2
// One pair
match(2) -> 1
// High card
else -> 0
}
}
private fun List<Hand>.sort(cardToScore: String, jokerChar: Char? = null): List<Hand> {
fun Char.score() = cardToScore.indexOf(this)
val comparator = compareBy<Hand> { it.type(jokerChar) }
.then { hand1, hand2 ->
hand1.cards.zip(hand2.cards).forEach { (card1, card2) ->
if (card1 != card2)
return@then card1.score().compareTo(card2.score())
}
0
}
return sortedWith(comparator)
}
fun List<Hand>.partOneSort(): List<Hand> = sort(cardToScore = "23456789TJQKA")
fun List<Hand>.partOneTotalWinnings() = partOneSort()
.mapIndexed { index, hand -> (index + 1) * hand.bid }.sum()
fun List<Hand>.partTwoSort(): List<Hand> = sort(cardToScore = "J23456789TQKA", jokerChar = 'J')
fun List<Hand>.partTwoTotalWinnings() = partTwoSort()
.mapIndexed { index, hand -> (index + 1) * hand.bid }.sum()
| 0 | Kotlin | 0 | 1 | 56ed086f8493b9f5ff1b688e2f128c69e3e1962c | 2,869 | advent-2023 | MIT License |
src/main/java/com/ncorti/aoc2021/Exercise15.kt | cortinico | 433,486,684 | false | {"Kotlin": 36975} | package com.ncorti.aoc2021
import java.util.PriorityQueue
object Exercise15 {
private fun getInput() =
getInputAsTest("15") { split("\n") }
.map { line -> line.toCharArray().map { it.digitToInt() }.toTypedArray() }
.toTypedArray()
// Not the most elegant solution but it does the job :)
private fun getBiggerInput() =
getInput().let {
Array(it.size * 5) { i ->
Array(it.size * 5) { j ->
val modi = i % it.size
val divi = i / it.size
val modj = j % it.size
val divj = j / it.size
val partial = it[modi][modj] + divi + divj
partial % 10 + partial / 10
}
}
}
private fun findShortestPath(world: Array<Array<Int>>): Int {
val queue =
PriorityQueue<Triple<Int, Int, Int>> { (_, _, cost1), (_, _, cost2) -> cost1 - cost2 }
val dist =
Array(world.size) { i ->
IntArray(world[0].size) { j ->
if (i == 0 && j == 0) {
queue.add(Triple(i, j, 0))
0
} else {
queue.add(Triple(i, j, Int.MAX_VALUE))
Int.MAX_VALUE
}
}
}
while (queue.isNotEmpty()) {
val (curri, currj, currd) = queue.remove()
steps.forEach { (stepi, stepj) ->
val (newi, newj) = curri + stepi to currj + stepj
if (newi >= 0 && newj >= 0 && newi < world.size && newj < world.size) {
val newDist = currd + world[curri + stepi][currj + stepj]
if (newDist < dist[newi][newj]) {
dist[newi][newj] = newDist
queue.removeIf { (i, j, _) -> i == newi && j == newj }
queue.add(Triple(newi, newj, newDist))
if (newi == world.size - 1 && newj == world.size - 1) {
return newDist
}
}
}
}
}
return dist[world.size - 1][world.size - 1]
}
private val steps = listOf(-1 to 0, 0 to -1, 1 to 0, 0 to 1)
fun part1() = findShortestPath(getInput())
fun part2() = findShortestPath(getBiggerInput())
}
fun main() {
println(Exercise15.part1())
println(Exercise15.part2())
}
| 0 | Kotlin | 0 | 4 | af3df72d31b74857201c85f923a96f563c450996 | 2,529 | adventofcode-2021 | MIT License |
src/main/kotlin/day18/Day18.kt | TheSench | 572,930,570 | false | {"Kotlin": 128505} | package day18
import runDay
import stackOf
import kotlin.math.max
import kotlin.math.min
fun main() {
fun part1(input: List<String>): Long {
val grid = mutableSetOf<Point3D>()
var sides = 0L
input.map { it.toPoint() }
.forEach {
grid.add(it)
sides += 6 - it.neighbors()
.filter { neighbor -> neighbor in grid }
.sumOf { 2L }
}
return sides
}
fun part2(input: List<String>): Long {
val grid = mutableSetOf<Point3D>()
var sides = 0L
var min = Point3D(Int.MAX_VALUE, Int.MAX_VALUE, Int.MAX_VALUE)
var max = Point3D(Int.MIN_VALUE, Int.MIN_VALUE, Int.MIN_VALUE)
input.map { it.toPoint() }
.forEach {
grid.add(it)
min = Point3D(min(it.x, min.x), min(it.y, min.y), min(it.z, min.z))
max = Point3D(max(it.x, max.x), max(it.y, max.y), max(it.z, max.z))
sides += 6 - it.neighbors()
.filter { neighbor -> neighbor in grid }
.sumOf { 2L }
}
grid.print(min, max)
val touchesOutside = mutableSetOf<Point3D>()
val xBounds = min.x+1 until max.x
val yBounds = min.y+1 until max.y
val zBounds = min.z+1 until max.z
// 2528 .. 2540
(xBounds).forEach { x ->
(yBounds).forEach { y ->
(zBounds).forEach { z ->
val point = Point3D(x, y, z)
if (point !in grid && point !in touchesOutside) {
val stack = stackOf(point)
val bubble = mutableSetOf(point)
while (stack.size > 0) {
val next = stack.removeFirst()
next.neighbors().filter { it !in grid && it !in bubble }.forEach {
stack.addFirst(it)
bubble.add(it)
}
if (next in touchesOutside || next.x !in xBounds || next.y !in yBounds || next.z !in zBounds) {
touchesOutside.add(point)
break
}
}
if (point !in touchesOutside) {
bubble.forEach { pointInBubble ->
grid.add(pointInBubble)
sides += 6 - pointInBubble.neighbors()
.filter { neighbor -> neighbor in grid }
.sumOf { 2L }
}
} else {
bubble.forEach { pointInBubble ->
touchesOutside.add(pointInBubble)
}
}
}
}
}
}
// grid.print(min, max)
return sides
}
(object {}).runDay(
part1 = ::part1,
part1Check = 64L,
part2 = ::part2,
part2Check = 58L,
)
}
fun Grid.print(min: Point3D, max: Point3D) =
List(max.x - min.x + 1) { x ->
List(max.y - min.y + 1) { y ->
List(max.z - min.z + 1) { z ->
val point = Point3D(x + min.x, y + min.y, z + min.z)
point in this
}
}
}.print()
fun List<List<List<Boolean>>>.print() = forEach { square ->
square.forEach { row ->
println(row.map { if (it) '#' else '.' }.joinToString(""))
}
println()
}
fun String.toPoint() = split(",")
.map { it.toInt() }
.let {
Point3D(
it[0],
it[1],
it[2],
)
}
data class Point3D(
val x: Int,
val y: Int,
val z: Int,
) {
operator fun plus(other: Point3D) = Point3D(
x = this.x + other.x,
y = this.y + other.y,
z = this.z + other.z,
)
}
fun Point3D.neighbors() = listOf(
copy(x = x - 1),
copy(x = x + 1),
copy(y = y - 1),
copy(y = y + 1),
copy(z = z - 1),
copy(z = z + 1),
)
typealias Grid = MutableSet<Point3D> | 0 | Kotlin | 0 | 0 | c3e421d75bc2cd7a4f55979fdfd317f08f6be4eb | 4,254 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/Day04.kt | michaeljwood | 572,560,528 | false | {"Kotlin": 5391} | fun main() {
fun part1(input: List<String>) = inputLinesToRangePairs(input).count { it.first.overlapsFully(it.second) }
fun part2(input: List<String>) = inputLinesToRangePairs(input).count { it.first.overlaps(it.second) }
// test if implementation meets criteria from the description, like:
val testInput = readInputLines("day4/test")
check(part1(testInput) == 2)
val input = readInputLines("day4/input")
println(part1(input))
println(part2(input))
}
private fun inputLinesToRangePairs(input: List<String>) = input.filter { it.isNotBlank() }
.map {
it.split(",")
.map { section -> section.split("-").map { bound -> bound.toInt() } }
.let { sections ->
Pair(
IntRange(sections[0][0], sections[0][1]),
IntRange(sections[1][0], sections[1][1])
)
}
}
private fun IntRange.overlapsFully(other: IntRange) =
(this.contains(other.first) && this.contains(other.last)) || (other.contains(this.first) && other.contains(this.last))
private fun IntRange.overlaps(other: IntRange) =
this.contains(other.first) || this.contains(other.last) || other.contains(this.first) || other.contains(this.last)
| 0 | Kotlin | 0 | 0 | 8df2121f12a5a967b25ce34bce6678ab9afe4aa7 | 1,254 | advent-of-code-2022 | Apache License 2.0 |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions47.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.round1
import kotlin.math.max
fun test47() {
printlnResult(arrayOf(
intArrayOf(1, 10, 3, 8),
intArrayOf(12, 2, 9, 6),
intArrayOf(5, 7, 4, 11),
intArrayOf(3, 7, 16, 5),
))
printlnResult(arrayOf(
intArrayOf(1, 2, 3, 4, 5),
))
printlnResult(arrayOf(
intArrayOf(1),
intArrayOf(2),
intArrayOf(3),
intArrayOf(4),
intArrayOf(5),
))
printlnResult(arrayOf(intArrayOf(99)))
}
/**
* Questions 47: Give a matrix with m * n, different number(more than 0) in different lattice, you can start in left-top,
* and you can move a lattice toward bottom or right, until to right-bottom,
* find the best way to get the sum of numbers on the path
*/
private fun getBiggestNumber(matrix: Array<IntArray>): Int {
require(matrix.isNotEmpty() && matrix.first().isNotEmpty()) { "The matrix can't be empty" }
val first = matrix.first().first()
return when {
matrix.size == 1 && matrix.first().size == 1 -> matrix.first().first()
matrix.size > 1 && matrix.first().size == 1 -> matrix.getBiggestNumber(1, 0, first)
matrix.size == 1 && matrix.first().size > 1 -> matrix.getBiggestNumber(0, 1, first)
else -> max(
matrix.getBiggestNumber(0, 1, first),
matrix.getBiggestNumber(1, 0, first),
)
}
}
/**
* Recursion
*/
private fun Array<IntArray>.getBiggestNumber(i: Int, j: Int, sum: Int): Int {
val firstSize = first().size
val newSum = sum + this[i][j]
val newI = i + 1
val newJ = j + 1
return when {
newI < size && newJ < firstSize -> max(
getBiggestNumber(i, newJ, newSum),
getBiggestNumber(newI, j, newSum),
)
newI < size && newJ >= firstSize -> getBiggestNumber(newI, j, newSum)
newI >= size && newJ < firstSize -> getBiggestNumber(i, newJ, newSum)
else -> newSum
}
}
/**
* Loop
*/
private fun getBiggestNumberForLoop(matrix: Array<IntArray>): Int {
val maxJ = matrix.first().size
val maxValues = IntArray(maxJ)
for (i in matrix.indices)
for (j in matrix.first().indices) {
val left = if (j > 0) maxValues[j - 1] else 0
val up = if (i > 0) maxValues[j] else 0
maxValues[j] = max(left, up) + matrix[i][j]
}
return maxValues.last()
}
private fun printlnResult(matrix: Array<IntArray>) =
println("The biggest number on the path is: ${getBiggestNumber(matrix)}, ${getBiggestNumberForLoop(matrix)}")
| 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 2,560 | Algorithm | Apache License 2.0 |
src/main/kotlin/dp/SCS.kt | yx-z | 106,589,674 | false | null | package dp
import util.*
// shortest common supersequence
// given A[1..m] and B[1..n], their common supersequence is a sequence that
// contains both A and B as subsequences
// find the minimum length of such supersequence
fun main(args: Array<String>) {
val A = intArrayOf(5, 6, 2)
val B = intArrayOf(1, 5, 2, 5)
// println(A scs B) // [1, 5, 6, 2, 5] -> 5
val X = "AxxBxxCDxEF".toCharOneArray()
val Y = "yyABCDyEyFy".toCharOneArray()
val Z = "zAzzBCDzEFz".toCharOneArray()
println(scs(X, Y, Z)) // 21
}
infix fun IntArray.scs(that: IntArray): Int {
// dp(i, j): length of shortest common supersequence for A[1..i] and B[1..j]
// dp(i, j) = j if i = 0
// = i if j = 0
// = min{ 1 + dp(i - 1, j - 1), 1 + dp(i, j - 1), 1 + dp(i - 1, j) } if A[i] = B[j]
// = min{ 2 + dp(i - 1, j - 1), 1 + dp(i, j - 1), 1 + dp(i - 1, j) } o/w
// memoization structure: 2d array dp[1..m][1..n]
// space complexity: O(mn)
val dp = Array(size + 1) { IntArray(that.size + 1) }
// dependencies: dp[i, j] depends on dp[i - 1, j], dp[i, j - 1] and dp[i - 1, j - 1]
// evaluation order: i from 0..m, j from 0..n
// time complexity: O(n^2)
for (i in 1..size) {
for (j in 1..that.size) {
dp[i, j] = when {
i - 1 == 0 -> j - 1
j - 1 == 0 -> i - 1
this[i - 1] == that[j - 1] -> min(1 + dp[i - 1, j - 1], dp[i, j - 1], 1 + dp[i - 1, j])
else -> min(2 + dp[i - 1, j - 1], 1 + dp[i, j - 1], 1 + dp[i - 1, j])
}
}
}
// we want dp(m, n)
return dp[size, that.size]
}
// another version of scs of two sequences merely served as the
// pre-process stage for solving the three sequences version
private infix fun OneArray<Char>.scs(B: OneArray<Char>): Array<Array<Int>> {
val A = this
val n = size
val dp = Array(n + 1) { Array(n + 1) { 0 } }
for (i in 1..n) {
dp[i, 0] = i
dp[0, i] = i
}
for (i in 1..n) {
for (j in 1..n) {
dp[i, j] = if (A[i] == B[j]) {
min(1 + dp[i - 1, j - 1], 1 + dp[i, j - 1], 1 + dp[i - 1, j])
} else {
min(2 + dp[i - 1, j - 1], 1 + dp[i, j - 1], 1 + dp[i - 1, j])
}
}
}
return dp
}
// what if we are given three strings X[1..n], Y[1..n], Z[1..n]
fun scs(X: OneArray<Char>, Y: OneArray<Char>, Z: OneArray<Char>): Int {
val n = X.size // == Y.size == Z.size by assumption
// dp(i, j, k): len of scs among X[0..i], Y[0..j], Z[0..k]
// where X[0], Y[0], Z[0] represents the empty character
// memoization structure: 3d arr dp[0..n, 0..n, 0..n]
val dp = Array(n + 1) { Array(n + 1) { Array(n + 1) { 0 } } }
// space: O(n^3)
// base case:
val xy = X scs Y
val yz = Y scs Z
val xz = X scs Z
for (i in 0..n) {
for (j in 0..n) {
dp[i, j, 0] = xy[i, j]
dp[0, i, j] = yz[i, j]
dp[i, 0, j] = xz[i, j]
}
}
// time: O(n^2)
// recursive case:
// { too many cases... see below in code }
// dependency: dp(i, j, k) depends on dp(i - 1, j - 1, k - 1),
// dp(i, j - 1, k),
// dp(i - 1, j, k - 1),
// dp(i - 1, j - 1, k)
// imagine dp as tables indexed by i, each having row idx j and col idx k
// then dp[i, j, k] depends on entries in the previous table, and entries
// in the current table that is above or to the left of the current entry
// eval order: outermost loop for i increasing from 1 to n
for (i in 1..n) {
// middle loop for j increasing from 1 to n
for (j in 1..n) {
// innermost loop for k increasing from 1 to n
for (k in 1..n) {
dp[i, j, k] = when {
X[i] == Y[j] && Y[j] == Z[k] ->
min(
dp[i - 1, j - 1, k - 1] + 1,
dp[i, j - 1, k - 1] + 1,
dp[i - 1, j, k - 1] + 1,
dp[i - 1, j - 1, k] + 1,
dp[i - 1, j, k] + 1,
dp[i, j - 1, k] + 1,
dp[i, j, k - 1] + 1)
X[i] == Y[j] && Y[j] != Z[k] ->
min(
dp[i - 1, j - 1, k - 1] + 2,
dp[i, j - 1, k - 1] + 2,
dp[i - 1, j, k - 1] + 2,
dp[i - 1, j - 1, k] + 1,
dp[i - 1, j, k] + 1,
dp[i, j - 1, k] + 1,
dp[i, j, k - 1] + 1)
X[i] != Y[j] && Y[j] == Z[k] ->
min(
dp[i - 1, j - 1, k - 1] + 2,
dp[i, j - 1, k - 1] + 1,
dp[i - 1, j, k - 1] + 2,
dp[i - 1, j - 1, k] + 2,
dp[i - 1, j, k] + 1,
dp[i, j - 1, k] + 1,
dp[i, j, k - 1] + 1)
X[i] == Z[k] && Z[k] != Y[j] ->
min(
dp[i - 1, j - 1, k - 1] + 2,
dp[i, j - 1, k - 1] + 2,
dp[i - 1, j, k - 1] + 1,
dp[i - 1, j - 1, k] + 2,
dp[i - 1, j, k] + 1,
dp[i, j - 1, k] + 1,
dp[i, j, k - 1] + 1)
else -> // X[i] != Y[j] != Z[k]
min(
dp[i - 1, j - 1, k - 1] + 3,
dp[i, j - 1, k - 1] + 2,
dp[i - 1, j, k - 1] + 2,
dp[i - 1, j - 1, k] + 2,
dp[i - 1, j, k] + 1,
dp[i, j - 1, k] + 1,
dp[i, j, k - 1] + 1)
}
}
}
}
// time: O(n^3)
// we want the len of scs among X[0..n], Y[0..n], Z[0..n]
return dp[n, n, n]
} | 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 4,988 | AlgoKt | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.