path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/Day03.kt | arturradiuk | 571,954,377 | false | {"Kotlin": 6340} | fun findRepeatedChar(first: String, second: String): Int {
first.toCharArray().map { char ->
if (second.find { it == char } != null) return char.mapToPoints()
}
throw Error()
}
fun findRepeatedChar(first: String, second: String, third: String): Int {
first.toCharArray().map { char ->
val foundS = second.find { it == char }
val thirdT = third.find { it == char }
if (foundS == thirdT && foundS == char) {
return char.mapToPoints()
}
}
throw Error()
}
private fun Char.mapToPoints(): Int = when (this) {
in 'a'..'z' -> this.code - 96
in 'A'..'Z' -> this.code - 38
else -> throw Error()
}
fun partOne(rucksacks: List<String>): Int = rucksacks.sumOf {
val (first, second) = it.chunked(it.length / 2)
findRepeatedChar(first, second)
}
fun partTwo(rucksacks: List<String>): Int = rucksacks.windowed(3, 3).sumOf {
val (first, second, third) = it
findRepeatedChar(first, second, third)
}
fun main() {
val rucksacks = readInput("Day03")
println(partOne(rucksacks))
println(partTwo(rucksacks))
} | 0 | Kotlin | 0 | 0 | 85ef357643e5e4bd2ba0d9a09f4a2d45653a8e28 | 1,114 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/at/mpichler/aoc/solutions/year2023/Day01.kt | mpichler94 | 656,873,940 | false | {"Kotlin": 196457} | package at.mpichler.aoc.solutions.year2023
import at.mpichler.aoc.lib.Day
import at.mpichler.aoc.lib.PartSolution
open class Part1A : PartSolution() {
internal lateinit var texts: List<String>
override fun parseInput(text: String) {
texts = text.trim().split("\n")
}
override fun getExampleAnswer() = 142
internal fun getNumber(nums: String) = ("" + nums.first() + nums.last()).toInt()
override fun compute(): Int {
return texts.sumOf { it.filter(Char::isDigit).let(this::getNumber) }
}
}
class Part1B : Part1A() {
private val digits = mapOf(
"one" to "1",
"two" to "2",
"three" to "3",
"four" to "4",
"five" to "5",
"six" to "6",
"seven" to "7",
"eight" to "8",
"nine" to "9"
)
override fun getExampleInput() = """
two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen
""".trimIndent()
override fun getExampleAnswer() = 281
override fun compute(): Int {
var sum = 0
for (text in texts) {
var nums = text
while (true) {
val changed = replaceNumbers(nums)
if (changed == nums) {
nums = changed
break
}
nums = changed
}
nums = nums.filter { it.isDigit() }
sum += getNumber(nums)
}
return sum
}
private fun replaceNumbers(text: String): String {
var nums = text
for (i in nums.indices) {
for ((k, v) in digits) {
if (nums.substring(i).startsWith(k)) {
nums = nums.replaceFirst(k, v)
return nums
}
if (nums.substring(0, nums.length - i).endsWith(k)) {
nums = nums.replace(k, v)
return nums
}
}
}
return text
}
}
fun main() {
Day(2023, 1, Part1A(), Part1B())
}
| 0 | Kotlin | 0 | 0 | 69a0748ed640cf80301d8d93f25fb23cc367819c | 2,117 | advent-of-code-kotlin | MIT License |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2017/2017-07.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2017
fun main() {
println("Part1+2:")
println(solve(testInput1))
println(solve(input))
}
private fun solve(input: String): Pair<String, Int> {
val programs = input.lines().map {
val (name, weight, above) = regex.matchEntire(it)!!.destructured
TowerProgram(name, weight.toInt(), if (above.isEmpty()) emptyList() else above.split(", "))
}.associateBy { it.name }
val parentMap = programs.flatMap { (_, parent) -> parent.above.map { it to parent } }.toMap()
val root = programs.values.single { it.name !in parentMap }
return root.name to findWrongWeight(root.name, 0, programs)
}
private fun findWrongWeight(from: String, expectedSum: Int, programs: Map<String, TowerProgram>, ): Int {
val program = programs[from]!!
return if (!program.areAboveInBalance(programs)) {
val (wrongName, correctWeight) = program.findWrong(programs)
findWrongWeight(wrongName, correctWeight, programs)
} else {
val diff = expectedSum - totalWeight(from, programs)
program.weight + diff
}
}
private fun TowerProgram.areAboveInBalance(programs: Map<String, TowerProgram>): Boolean {
return above.map { totalWeight(it, programs) }.distinct().size == 1
}
private fun TowerProgram.findWrong(programs: Map<String, TowerProgram>): Pair<String, Int> {
val totals = above.map { totalWeight(it, programs) }
val min = totals.minOrNull()!!
val max = totals.maxOrNull()!!
return if (totals.count { it == min } == 1) {
above[totals.indexOf(min)] to max
} else {
above[totals.indexOf(max)] to min
}
}
private fun totalWeight(name: String, programs: Map<String, TowerProgram>): Int {
val program = programs[name]!!
return program.weight + program.above.sumOf { totalWeight(it, programs) }
}
private data class TowerProgram(val name: String, val weight: Int, val above: List<String>)
private val regex = """(\w+) \((\d+)\)(?: -> ([\w, ]+))?""".toRegex()
private const val testInput1 = """pbga (66)
xhth (57)
ebii (61)
havc (66)
ktlj (57)
fwft (72) -> ktlj, cntj, xhth
qoyq (66)
padx (45) -> pbga, havc, qoyq
tknk (41) -> ugml, padx, fwft
jptl (61)
ugml (68) -> gyxo, ebii, jptl
gyxo (61)
cntj (57)"""
private const val input = """suvtxzq (242) -> tdoxrnb, oanxgk
smjsfux (7)
oanxgk (68)
tvvfszm (66)
xprwsaf (266) -> uynuje, hhxlqcl
imkbcte (256) -> aeoojsr, muxff
uyxvzt (1046) -> uemmhd, ctdjc, gxqkboz, nvudb, dadueoc
ancik (61)
oysettw (152) -> fjojctd, eiiis, eilacwy
chfkzye (88)
maytl (149) -> uprsewo, obkvvy
qdyxf (95)
ssqhzgo (183) -> idwscr, jwmobb
hmtesft (62)
prayxh (377) -> bybrtqt, ftlxelc
rxlcg (16) -> soscup, gvqhsi
vhrxv (76)
bpmgs (81)
tngrxak (82)
odlmlp (19)
uocgh (78)
qdiuck (203) -> opxgy, evfob
hmpgq (86)
agrorp (98)
fnubw (7991) -> uyxvzt, xzzbz, zqbno, fxftvvi
pjdwe (71)
agmcum (9)
plxbhxv (91) -> pburz, crbuu, ancik, oglzi
tjvdz (68)
fwjrt (93)
smubum (79)
yojgof (34)
obkvvy (46)
lbhigx (32)
yixnd (10)
uysrm (255) -> vjzzaxi, mnegwoy
ggfpru (99)
pffjr (75)
bzoui (45) -> qzzuio, dzkcq
vrpls (22)
umrlyk (196) -> eygeo, xmhogfl
nkjocfh (81)
dzkcq (24)
ffpmvco (95)
fdlcwg (78)
gbvlb (214) -> sdjtpgj, ijhxyp
idhmz (17)
jouimd (55)
jnetreq (185)
xejdjnu (87)
gyeakaj (84)
gcdvju (22)
dadueoc (54) -> ywbagad, amkkd
ebpdat (63)
jcyop (522) -> qzegoz, rjbsi, fbbhkn, fafmv, pgiscip, fvzlw, etyllx
ozyiajn (137) -> iotjdfw, ulqoxr
pomtfpc (46)
baukd (52)
xgrkt (77)
mvbiu (37)
xhgxlcb (31)
xwmmdbs (48)
kxrwmdo (35)
kmmaqz (93)
vuoipf (1917) -> hgzal, evjtjkw, qstxfxv, yqzlm, agwseuk
zaoep (284) -> ffsrpnc, cvddep, mqlmpi
jnkjy (150) -> tdfetjs, gcpjvg, ztfmse
xjjge (142) -> yeavyk, cxfsjtx
xxcmska (51)
vjqrn (95) -> pnfmax, uhdvcqk, tetvxtx, ypjre
ffanqao (86)
evcrg (88)
htzab (142) -> douazak, wrqgf
xnvjeq (71)
oamdc (98)
goxkdq (343) -> vxbul, yfapady
evjtjkw (61) -> linzo, fzrps
ctmsdh (80)
apijq (57) -> ggbavjl, kvyvm, yfjodsp, dtiqmg, ehqjjsl, eggrxn, eaxgw
ctdjc (156)
jfagd (35)
ciwaqy (49)
fcydda (279)
nzkxl (10) -> wruuxfs, zviebo, fdxmq
kwlrqf (46) -> ngzhx, jnmwff, yacsqd, zbredd, gsabtz, gaodhdn, daziob
tgctm (2340) -> gtolwfw, zrjkvhs, jvrfyh
weasj (213) -> gzzmpmt, btmauhd, dvdfe, wqswycq
nbpifq (19) -> iujht, evacloi, geevgr
sjjfw (250) -> jpbod, xxcmska, hqkqg
mcltn (23)
tjqces (74)
epxsima (142) -> rpcpu, uyqja
uprsewo (46)
ikufikz (18)
oxtcw (60)
ftjsi (52)
cksrupl (216) -> bcqrh, bqcpk, smjsfux
iwrxh (793) -> wkrunp, ciwaqy
jgemyt (395) -> spzcts, zxdwxi
sdjtpgj (27)
tkbvq (229) -> vtvrufl, vmask, qzdgae, ltxdrag
fmxgjyi (67)
doioysi (37)
kvyvm (231) -> cfofvmk, mrfxp, aiifb
ahxab (11)
csjgde (313) -> ixqosm, ziclyc
trkehb (234) -> qhivkhk, odnxu
gaepxdo (10) -> dssmkge, dcfod, mnzrs
xneou (37) -> qdmwhp, ykuovbf, nnrup, kmmaqz
wcsvv (125) -> xlcwwh, wkpcmj
ynabij (365) -> guenoww, hyupti
vyksxor (74)
jajnukt (141) -> jzsuszj, kypvxgj, prpur, bbvcyqt
qvvfdz (235) -> mzxzvj, ayhtq
qwuwet (44)
wsnnpt (93)
kchxaz (50)
excue (94) -> vbklmbl, cvebrdn, tsejpo, auvkftn, odgaq, mikabr, plafq
inpzr (283) -> bttuf, mtpjiqv
ceahs (149) -> iywmq, ednoc, opoav
oxokip (59)
bjhbaeq (15) -> jbeccla, yghmpm
fafmv (164) -> pmcxf, sgcszn
kfdlwmd (76)
wezrbzw (90)
mjfmma (80)
unwxho (93) -> ycbensb, dqqvw, xggqps, wopctnz
xddneql (98)
ugaao (293) -> igxnbx, iuwfcfn
idwscr (27)
hkifor (56)
wvamomg (66)
fzrps (64)
oqatq (34)
cjlll (25)
fusrhst (85)
lglzu (65) -> tgoxupv, aqcvcmu
jicds (19)
dlorovb (88)
tjpyzok (48)
ewetx (18) -> aivthrm, dehctx, xejdjnu
ohjpwlf (89)
ayrmt (6)
drfiyc (208) -> ajvtod, mbsom, svgsp
llbrfnj (35)
ojvela (47) -> pfdhuej, eftexh, dlorovb, ihxxanb
mzdorez (75)
feecvjl (68)
bhjgta (936) -> jtemqlc, ztqfg, zaoep, knfjqwi
wrqgf (50)
cchsvcu (2393) -> vbahlkz, nsaunto, iidrfg
ehqjjsl (225) -> iiihrc, cmlrqjx
uwqgz (59) -> juadxcz, doulax
hlbyzqi (98)
dqwfuzn (785) -> utecy, smpbfj
sabrmjw (539) -> ynabij, yorve, tdfla, xneou, urxki, caaul
szvvmv (59)
nwvfcq (8)
olnfb (95)
gcgai (217) -> hmgnq, doioysi
rzyceeb (75) -> cpvmv, vyqeu
eaxgw (359) -> sumkuu, qyxyyfe
xezfgjm (386) -> lfmshq, btunou, fnkvv, jcetf
xgwbi (34)
hhxlqcl (69)
jjutz (85) -> ppmtmra, lrhov, gahmpi
aeede (82)
vhpqug (48)
gwcznw (78)
iiihrc (84)
ponhl (56)
xkljy (165) -> qeaafc, luobrd
sgdqadb (365) -> gzbpbzh, semuybr
vlstbi (265)
doulax (35)
awgit (71)
ukgraro (27)
itqxypr (40)
tqjnarz (86) -> ulgusti, tngrxak, jpchi
cjcnjv (22)
upalmon (65)
mybgqcz (34)
ensbsjj (10194) -> zjdlixd, enpvalm, bhjgta
jbexqrg (43)
odvadyf (28)
yhkvwfh (14) -> efnhbg, lfgtisg
aeuhflj (20)
lxugv (93)
qxubf (223) -> woauuj, etlyn
woauuj (72)
lhldwh (35)
ehxoyp (6)
svhudk (55)
jtlqjwb (90)
bhgjfjp (43)
wojfh (76)
cxhplek (28)
eiiis (60)
lfmshq (86) -> jgjis, tezrxeh, kfdlwmd
qhoznbt (52)
ifcvuo (305) -> dyimr, zjybiy
zelat (1852) -> dtovks, jkjkxjo, etihx, xwukld
ptkhfgv (76)
yfwlsm (40) -> diodh, wqwuh, xddneql, oamdc
udnuwf (44)
topay (77)
rpqtlka (10)
uclzd (258)
uqcsmi (138) -> orfvwfh, mvvdw, wxqcjau
jkjkxjo (97)
sjizhzd (385)
awhtxfi (67)
mfkyyn (22)
khxovd (70) -> pnednw, oxtcw, zculjs
btuuf (36)
tbmtw (7374) -> jcyop, gnpvu, qokpqcj, dpulvm
dyimr (47)
ktiqs (60)
uqrmg (38) -> xgwbi, mybgqcz, yojgof, qssip
kypvxgj (37)
ymmmd (119) -> posqxf, xnvjeq, rmuwew
mazuw (20)
ahxil (180) -> ayrmt, ehxoyp
ytjvi (30)
gfrjfp (10456) -> vglmk, ncewylf, ofqyppk, lrrznr, krvxpc
sumkuu (17)
sogmnn (1837) -> hmpgq, ffanqao
ulqoxr (77)
dnzvald (12)
fhsmv (87)
cgoclfi (44)
qeaafc (36)
ovsdyv (241)
hrykmkz (59)
dpqsx (224) -> topay, ioinp
ihrnca (85)
bpndvbp (22)
fbtzaic (11651) -> nzkxl, mdbtyw, dqwfuzn
smpbfj (64)
krnlmf (22)
mqlmpi (12)
cmlrqjx (84)
yorve (285) -> yhwiyr, hmtesft
katupgz (23)
prpur (37)
iidrfg (133)
iofnddc (65)
houiwqu (64)
exzvkxu (26)
topcav (93) -> zmuxeo, glmtq
uoowx (48)
xkvgp (17)
paplmio (91)
igxnbx (46)
ftbzlvu (93)
bucdl (107)
bydph (90) -> bhyawz, etgphv
fqoary (30) -> ldcqple, gfrjfp, uvfrdrm, flnwg, dzihru, kyjva, ncuauw
soiwb (22)
iqgctux (839) -> vjqrn, hfbyx, kfibzch, fctrumt, oraqucr, ewetx, fpmlwfh
zxdwxi (39)
gzzmpmt (43)
pujxta (22)
cvebrdn (192) -> hyblgwq, dafsjnc
tpdpnu (63)
glmtq (74)
fdxmq (28) -> lisgic, mpsbosw, hykydhr
kloyc (30)
tfrrlt (27)
lwbtd (39)
xykzz (93)
ppoiun (196) -> glton, rscybf
gimfzpl (98)
adjeeo (66) -> svlzb, grluwcw, bqytirn, lzovhs
mbsom (14)
dvcdvss (76)
ypjre (46)
micrqvl (15)
ezzme (89)
dnkuuf (237) -> fitxh, iofnddc
rjbsi (176)
qdhlpqn (54) -> jrnzibg, urdzsm, pxzxws, eounhdc, goxkdq
zatst (36) -> udjinl, hwssapq
ismlzl (8)
uyqja (34)
zxuzl (808) -> lvheqh, syjwi, usqget, gowyxis
pbwqe (166) -> dbwnqzs, swzwgb, eeufykm
bzpuxrk (52)
qzzuio (24)
dtpnpq (104) -> lowahta, obidwky
lhumvsh (23)
ntintc (19)
bvytf (157) -> unjnjhh, xuhgu, aeede
gitpug (56)
vtvrufl (9)
duwrtfc (16)
uahwv (40)
fjojctd (60)
pburz (61)
btunou (210) -> qhoznbt, ftjsi
ieacu (179) -> fetmzid, cnzqk
gwzoe (72)
eplazoz (77)
uxppyj (83)
dvdfe (43)
dkorpg (39)
ipgte (85)
spzcts (39)
lwxoin (169) -> yvbxww, fmgdkun
iatnsa (34)
daziob (265) -> pikkduj, qjxczyx
knvtk (26)
qjxczyx (78)
gtolwfw (96) -> mbfhki, uftzqia
ussukc (8)
fsaitmn (425) -> ckeqik, lmqhg, zfkliql, ahhtyrn
dczlybu (17)
fcqyuld (69)
ibrkwsx (81)
mroyq (17)
bboim (1467) -> bydph, ppzdpud, lfmuqxa
dochk (175) -> ichsx, xyorm, oxhcne
grluwcw (78)
vkzmdxf (23) -> lwxoin, qdiuck, qjqmpw, kfjckfy
gmcrj (69) -> polkn, gejdtfw, cfuudsk, fqoary
lisgic (91)
nhkfwk (48)
eeufykm (25)
ytvur (98)
pikkduj (78)
hkstlva (19) -> stzau, zpaybpo, ibrkwsx
xmhogfl (31)
wqimeek (93)
eycqvhz (95)
xzufzqj (35)
iohhnkq (78)
ftlxelc (13)
jfknc (97) -> sjizhzd, efhdsgs, weasj, hrxzek, ugaao, sgdqadb, xxljznv
fmgdkun (24)
vwjspf (7)
vvyffam (13) -> nwecq, buodib, ypujb, ndjueqb
dqjepow (1158) -> waikg, ljyobyk, xbnecm, pssff, cqoxq, uokpbvj
piyyydu (250) -> lodjokj, oakblco, rlgru, aawuak
uxfcrt (240) -> ahxab, pbsabz
lmteo (50) -> coleqoq, ohseo
jprrnd (76)
juadxcz (35)
bubuic (62)
cqzhj (23)
nvudb (62) -> uebysc, cjxuwe
rantzzr (7)
tyddsz (261)
ixqosm (75)
dtrdb (264) -> bhgjfjp, jbexqrg
aqljjk (60)
gcpjvg (35)
xdrpbh (75)
yfapady (24)
gwlskzx (445) -> tqcdt, agmcum
xxljznv (29) -> ezzme, xvxezl, zjzldd, rfigs
ztqfg (71) -> xdfwfmo, lugxki, uxppyj
fnkvv (152) -> dfdawtk, mxpnyo
aeoojsr (15)
uymdisn (31)
jnkqo (49) -> tvcul, stfsit
otsbf (98)
lwgppcz (67)
ecuhckx (806) -> ddnfy, tzseb, mbxffzk
hqkqg (51)
nsaunto (13) -> uahwv, fveuo, bihjuos
mdbtyw (396) -> zqcrxm, lfbocy, uqrmg
bnlxpgs (41)
dafsjnc (53)
ofeqif (87)
plafq (112) -> wqimeek, fgeakc
oazne (238) -> pddmke, cugsuk, vyvwpp
unjnjhh (82)
hlxglt (97)
oglzi (61)
rmzdg (90) -> gfxra, oqxprqa, jfknc, mwmyxd, iqgctux, cchsvcu
aszlk (6)
xkzympi (80)
fcajmx (79)
iygrvcq (84)
xvxezl (89)
wqswycq (43)
wkpcmj (30)
gydhlh (67) -> igeuou, ggfpru
yhjbr (15)
blmrnzv (75)
guenoww (22)
ibygguq (75)
uaouhj (50)
kmvtp (80) -> ztcoo, evcrg, seqpyc, awkci
pnptpzb (18) -> qvvfdz, fgbkh, jnkjy, uprknk, uqcsmi, mwixu
rxeesk (97)
puiuyvv (64) -> hydsxwk, tjqces, sfkznca
oxtuf (84)
rhomwvz (72)
zoeyj (230) -> rznjgnj, ztocqs, itqxypr
xdfwfmo (83)
mzxzvj (10)
uyauqa (476) -> gbvlb, inbnp, nbpifq, kxbgcn
eggrxn (13) -> bfuell, oqkcc, qpshatb, ffpmvco
bcqrh (7)
bulumce (106) -> xeeor, lqyjcz, lsnyoe
dvqaks (35) -> mkzpyhk, excue, zxuzl, ukdun, xoxpsax, opyyn, unvguy
zbredd (391) -> micrqvl, yhjbr
rwulpg (106) -> uymdisn, xhgxlcb
rfigs (89)
xoxpsax (970) -> lmteo, htzab, vllceh, zotuf, xjjge
ygfdkew (34)
ahhtyrn (12)
ckeqik (12)
lqyjcz (87)
gaodhdn (421)
moqjbf (23)
wcjly (254) -> kunjdjs, bubuic
urdzsm (347) -> mfkyyn, pujxta
ipbtx (94)
ichsx (38)
cfofvmk (54)
slavm (402)
oakblco (32)
pbsabz (11)
ffsrpnc (12)
kfabmu (85)
gsabtz (357) -> lbhigx, jklgnxw
tfjnjpk (63) -> jgcpvo, qppcrmh, gwzoe
nmzgz (91)
uante (22)
ruann (26)
tezrxeh (76)
usqget (73) -> jtlqjwb, uzqerzq, fadrtgp
rpwxt (50)
evacloi (83)
cqoxq (275)
pnfmax (46)
pdqytmz (99)
hidxzy (50)
zrjkvhs (70) -> yxqgha, tlghvt
kaahj (67)
qkoobj (784) -> puiuyvv, imkbcte, zroqzf
uynuje (69)
wgrjyq (285) -> iwajq, adqhyes
etgphv (31)
tdfla (393) -> ussukc, ismlzl
qzdgae (9)
aivthrm (87)
kfjckfy (217)
nxydw (159) -> hrykmkz, mkidiho
bkxeyq (72)
inbnp (180) -> ueadckf, udnuwf
bdvlgx (543) -> psrozz, efjmuv, plxbhxv
pfdhuej (88)
ekojj (148) -> oeuror, ajhda
srvqwf (112) -> rbjjv, duhoci
hvyklmf (9)
bvpxgrf (80) -> mnryxre, orjnwip, qaznr
reyxj (84)
yqzlm (37) -> ptkhfgv, ikmdjtw
yhwiyr (62)
ygdeams (32) -> rhomwvz, gwnlt
jvrfyh (100) -> mvbiu, druuhf
zlwjs (81)
oogzvyg (23)
rkauf (32)
hfbyx (247) -> wldfv, xmufd
jtokzu (35)
hyeteeg (367) -> xwmmdbs, vhpqug
gowyxis (313) -> vtazp, opdzu
riszb (81)
hgzal (59) -> imslgj, bktvx
lvxmqy (90) -> lyyqnt, gwcznw, fdlcwg, nifsnge
bihjuos (40)
mnryxre (36)
nkaejjm (32)
wxgwp (88) -> ofeqif, dxdioa
oqxprqa (1180) -> ntigfy, mnfrudu, uknimmc, qnljlu
jbeccla (46)
tlikogo (25) -> lldzrv, qkcqxgk, wpypfwm, hbwuw
easqs (41)
jtemqlc (320)
wldfv (16)
gcepcso (498) -> ekojj, owexd, fypjed, epxsima, ppoiun
vtbkd (123)
cfwrezj (254) -> tjpyzok, uoowx
bqcpk (7)
wkrunp (49)
lsnyoe (87)
diodh (98)
etidy (167) -> hqpzd, ponhl
qucjvpl (6)
xzzbz (629) -> ifcvuo, ojvela, vdmezfc
lfbocy (174)
mgqrq (95)
hykydhr (91)
ohseo (96)
udjinl (78)
yeoia (5411) -> kwlrqf, sabrmjw, whvre
tvcul (96)
hqept (94)
ljyobyk (77) -> zvmbtmg, pdqytmz
mwixu (117) -> fcqyuld, cssuc
qssip (34)
zmuxeo (74)
uvfrdrm (12966) -> kvqdnuq, zelat, bheam
duhoci (69)
ccvnkwy (92) -> dpbwe, zsflxau
lfgtisg (39)
exgjf (50)
uivov (22)
cvvewfi (13)
mkzpyhk (1136) -> podrlpj, tyddsz, tkxpetn, pnmuf
sxeywx (84)
cbezt (388) -> cjcnjv, gcdvju
dvpfc (28)
eounhdc (97) -> otsbf, ytvur, lilwts
gxflenw (73)
ncewylf (1774) -> btuuf, omzdv
uftzqia (39)
ulxsfq (340) -> hmphp, ivrypwl, duwrtfc, vpcawb
uebysc (47)
tkxpetn (93) -> oxtuf, ytrmqx
qgjpqt (48)
dmrvdna (27)
qrfqnq (81)
ykuovbf (93)
hdiot (14)
oraqucr (279)
wruuxfs (58) -> zlwjs, pfahvas, mtrumh
odnxu (12)
bttuf (42)
cpvmv (83)
huxkort (327) -> dczlybu, cdeyujt, idhmz
prtbd (38) -> ipgte, tkjlunx, fusrhst, btnvmr
krvxpc (424) -> ssqhzgo, xkljy, pjflk, lfkqyf, cksrupl, qivrvv
pcjppf (203) -> hcyhv, cedao
vdmezfc (399)
gvqhsi (88)
sjrlj (66)
lotiapl (90)
xtprb (52)
ofqyppk (186) -> ymmmd, oysettw, ceahs, tqjnarz, vyoxvhv
umwyc (78)
etyllx (53) -> rclzxhh, qoybzxh, easqs
yeogm (76)
iujht (83)
bfvriie (48)
cfqpega (94)
mikabr (170) -> zmksfeg, houiwqu
aawuak (32)
zbizc (99) -> ygivo, fmxgjyi, lwgppcz, kaahj
nwyys (50)
ztcoo (88)
linzo (64)
gfdnli (84)
gahmpi (52)
waikg (275)
ednoc (61)
namjj (29) -> umwyc, uocgh
mbfhki (39)
gnbmemw (123)
wamfc (48)
geevgr (83)
gnpvu (20) -> mmvft, pcjppf, jajnukt, dochk, hngooro, gaepxdo
ffmjzxx (28)
aiifb (54)
hcyhv (43)
zmksfeg (64)
eilacwy (60)
yxqgha (52)
posqxf (71)
rujthq (92)
fppes (65)
fmtsssj (75)
nnrup (93)
agwseuk (132) -> jicds, ntintc, odlmlp
vxbul (24)
wqwuh (98)
vgfqulp (199) -> mzdorez, ibygguq
idbcgs (175) -> xkvgp, buzeugv
hrxzek (184) -> skdiibp, lgjtrj, awhtxfi
tzseb (23) -> legxh, kfabmu, ihrnca
mnzrs (93)
hqvgt (129)
stfsit (96)
fetmzid (15)
hydsxwk (74)
orysz (40) -> xjkgmv, knvtk
snblhv (99)
ivrypwl (16)
vyvwpp (13)
opxgy (7)
xeeor (87)
zsflxau (50)
bheam (2222) -> iitdq, aszlk, qucjvpl
wygvotv (16)
ixukvkp (92) -> uaouhj, yotjazk
ltxdrag (9)
pfvxd (89)
dpulvm (1175) -> xuuft, xwblt, invrcvf
oyatv (57)
atwpqc (35)
brbzgkm (16)
ijvmnd (12)
wqqqxn (18) -> aqivm, ozyiajn, gcgai
fbbhkn (84) -> pomtfpc, rjqihtl
xuuft (41) -> kjxwxam, dvcdvss
zohacp (1362) -> ovsdyv, yuwdebl, jnkqo, topcav, jsbcdkn, azgii
tsejpo (90) -> bzpuxrk, goyce, rwbqd, mfrcmg
ioinp (77)
zjdlixd (831) -> mpfrdzc, oazne, zwyrvyj, vebkntv, nxydw
sfkznca (74)
cvddep (12)
mnegwoy (47)
mkidiho (59)
xyorm (38)
rpcpu (34)
akqzb (79)
rmuwew (71)
glton (7)
hpvsz (57)
oauxbtz (23)
gvibwl (52)
hwssapq (78)
ecyyqsp (80) -> qwuwet, cgoclfi
pzxhj (145) -> qhwwv, ktiqs
rbjjv (69)
twsfo (151) -> namjj, jnetreq, wcsvv, lglzu
dzihru (11994) -> bwvmae, kpfjraq, ztxlw, bboim
rybeva (11)
imslgj (65)
odgaq (172) -> tpdpnu, ebpdat
rutvyr (9470) -> ecuhckx, morwid, daziqx
yacsqd (33) -> hlxglt, cbxczib, rxeesk, kgepl
adqhyes (89)
uprknk (65) -> ccezie, eycqvhz
wpypfwm (81)
oxhcne (38)
xggqps (95)
lojhip (66)
qivrvv (61) -> gqwepeb, chfkzye
rlgru (32)
cqiexk (154) -> pjdwe, awgit, kqxvtvy
fctrumt (259) -> yixnd, rpqtlka
vwfoi (34)
xxrxf (84)
ayhtq (10)
whvre (2803) -> olnfb, mgqrq
cbxczib (97)
zusipm (188)
kdsrjc (142) -> ytjvi, kloyc, oghvi, hbdmcdc
cxfsjtx (50)
unvguy (761) -> unwxho, jgemyt, fsaitmn
qtwwe (14)
zjybiy (47)
nygkk (857) -> zatst, ixukvkp, rxlcg, wqcsaan, ccvnkwy, ahxil
lowahta (36)
rscybf (7)
ytrmqx (84)
odkjk (108) -> nwvfh, xquwlv, hghuq, dsozgr
cedao (43)
ehfoqf (66)
knfjqwi (280) -> mazuw, mtjcvaf
obidwky (36)
pclycj (13)
vhlpr (17)
vjzzaxi (47)
coleqoq (96)
yeavyk (50)
idvkl (29)
rwbqd (52)
sppbe (23)
rjqihtl (46)
wqcsaan (114) -> dkorpg, lwbtd
lugxki (83)
gnmkuj (75)
tyfoz (94)
ubhvop (89)
fpmomi (94)
nzdilp (99)
uoybmh (349)
tdfetjs (35)
ziclyc (75)
zpaybpo (81)
mbqewjq (250)
jrnzibg (370) -> rantzzr, vwjspf, iguatq
bjllzfr (10)
pbvmk (125) -> xzufzqj, jtokzu, jfagd, atwpqc
cnzqk (15)
btnvmr (85)
xlhbak (14779) -> hqvgt, zhxqgb, vvyffam, uwqgz
qpshatb (95)
otzkp (92)
stzau (81)
pxheyj (16)
zakeqj (7554) -> ltmvmwe, pnptpzb, gcepcso, bdvlgx, yhwegl, uyauqa
jkeqz (34)
ckkcgp (180) -> nzdilp, snblhv
vyeryld (9)
wxqcjau (39)
cssuc (69)
gicuckw (80)
fxftvvi (989) -> fcydda, tfjnjpk, etidy
ltmvmwe (756) -> qavfiun, yqcaue, ybppeq
kyjva (16122) -> wqqqxn, vkzmdxf, twsfo, iwrxh
jflahw (84) -> tjiqr, csjgde, wgrjyq, hyeteeg, gwlskzx, fuohb
cbxgol (42)
xwblt (193)
podrlpj (261)
kfibzch (54) -> dpnlf, mcjbnfk, blmrnzv
bdvlhq (21) -> akqzb, fcajmx, smubum
qhwwv (60)
ubsmxso (78)
mtpjiqv (42)
ccezie (95)
fgeakc (93)
jyppp (57)
sqvfg (56)
ycbensb (95)
rznjgnj (40)
luobrd (36)
uknimmc (235) -> gyeakaj, sxeywx
zzsqh (78)
lvheqh (261) -> jtviekh, kyeul
koeufzg (84)
ggbavjl (21) -> iojwg, xykzz, pjvsofk, lxugv
crbuu (61)
ubpoy (68)
opdzu (15)
dfdawtk (81)
edafmn (27)
rndpfmx (300) -> pgxiavo, cjlll
iuzmx (16)
dsozgr (81)
ygivo (67)
tqytfku (79) -> krnlmf, dxyhphf
pmiwkyg (41)
bwvmae (33) -> piyyydu, ckkcgp, mqzkogj, adjeeo, uztqohr
xlcwwh (30)
auvkftn (282) -> nwvfcq, ophcgq
qdmwhp (93)
ztfmse (35)
ppzdpud (68) -> cbxgol, goohdry
ibnunt (56)
qdwhkl (72)
bktvx (65)
eftexh (88)
jwmobb (27)
dgjtv (29)
cjxuwe (47)
mbxffzk (210) -> vwfoi, oqatq
omzdv (36)
jsbcdkn (61) -> eumtjne, venip, aqljjk
qnljlu (83) -> ctmsdh, arxafnu, ximwl, xkzympi
uhdvcqk (46)
ncuauw (14760) -> xezfgjm, tjtrq, qkoobj
morwid (92) -> trkehb, uclzd, umrlyk, axrrydf, tjqdup, bdvlhq
intews (29)
lterpwd (34) -> bwmlg, intews
kunjdjs (62)
jlxwojc (7)
buodib (29)
qzegoz (28) -> wiprvsa, vyksxor
bwjrqs (56) -> wvamomg, sjrlj
opoav (61)
dpbwe (50)
dssmkge (93)
ajhda (31)
qjnow (217) -> rpwxt, exgjf, nwyys
efjmuv (195) -> lhldwh, bcyndtf, llbrfnj, kxrwmdo
eeozf (11)
vpcawb (16)
jpbod (51)
qavfiun (114) -> fmtsssj, pffjr
ywbagad (51)
tetvxtx (46)
ukdun (568) -> bvytf, prayxh, sjjfw, lxwaq
qhivkhk (12)
ndjueqb (29)
swzwgb (25)
mrfxp (54)
qkcqxgk (81)
lfmuqxa (98) -> dmrvdna, tfrrlt
tkjlunx (85)
avcwghu (94)
jgcpvo (72)
uzqerzq (90)
qoybzxh (41)
ldghw (48)
lrjdbp (23)
hfejf (13)
invrcvf (49) -> bkxeyq, qdwhkl
opyyn (1428) -> zusipm, bvpxgrf, wdvmvhe, bwjrqs
amkkd (51)
vnxmgtu (91)
pnednw (60)
eumtjne (60)
siknup (52)
xwukld (97)
mxpnyo (81)
iojwg (93)
daziqx (1364) -> orysz, lterpwd, yhkvwfh
nlusd (23)
zviebo (213) -> bpndvbp, vrpls, zeauw, uante
ntigfy (376) -> vyeryld, jgzpdx, hvyklmf
atzunin (78)
bcyndtf (35)
iitdq (6)
azgii (241)
qmkyl (12)
dlzrs (18)
zqcrxm (135) -> pclycj, hfejf, hpcvu
vbklmbl (298)
jlmbjs (52)
yrbypdv (89)
vyoxvhv (24) -> eplazoz, ftkqwci, xgrkt, nedbp
eadmwtp (22)
kqxvtvy (71)
hpcvu (13)
yuwdebl (67) -> fhsmv, eifgc
tucqq (80) -> vpywo, vuoipf, jflahw, fgpgrxr, tgctm
yfjodsp (373) -> bjllzfr, ldjeual
ulgusti (82)
yvbxww (24)
ihbybvd (84) -> eptpjci, gicuckw, mjfmma, ayismka
ciygx (23)
iwajq (89)
bncdukb (79) -> fwjrt, ftbzlvu
zhxqgb (115) -> tdvopw, jlxwojc
efnhbg (39)
pgiscip (30) -> gxflenw, bpaelk
jnmwff (233) -> tyfoz, hqept
gwnlt (72)
bybrtqt (13)
buzeugv (17)
jzsuszj (37)
dbwnqzs (25)
illkoi (56)
tlghvt (52)
vglmk (96) -> iygpmov, dtrdb, rndpfmx, cfwrezj, zoeyj
xquwlv (81)
lilwts (98)
aqivm (67) -> illkoi, gitpug, ibnunt, sqvfg
vsprxrs (175) -> fpxda, dyyccwq
ihxxanb (88)
semuybr (10)
cdeyujt (17)
xufnd (90)
etihx (97)
mnfrudu (207) -> agrorp, hlbyzqi
bfwgsag (27)
xjkgmv (26)
pnmuf (173) -> soiwb, htinuz, eadmwtp, uivov
rfxyb (48)
igeuou (99)
aqcvcmu (60)
ewomrs (84)
cugsuk (13)
weeom (20)
mpsbosw (91)
mmvft (275) -> zyxbmy, gdftnih
nifsnge (78)
lrhov (52)
psrozz (223) -> adccmtd, hkifor
enpvalm (14) -> dnkuuf, qjzipyw, znoap, bulumce, qxubf, nnktssm
jpxtrww (23)
zroqzf (264) -> rybeva, eeozf
nfcrpf (22)
jgjis (76)
zqbno (81) -> tlikogo, uoybmh, vgfqulp, mstjkgi, uysrm
fvzlw (76) -> kchxaz, hidxzy
legxh (85)
iomsug (78)
skdiibp (67)
dyyccwq (96)
kjxwxam (76)
oeuror (31)
lodjokj (32)
mvvdw (39)
exadxz (41) -> xxrxf, koeufzg
pmcxf (6)
oqkcc (95)
mbfvaw (22)
xbnecm (227) -> brbzgkm, iuzmx, wygvotv
kpfjraq (923) -> srvqwf, drfiyc, khxovd, mbqewjq
pfahvas (81)
dehctx (87)
bpaelk (73)
jndcfc (90)
axrrydf (190) -> tsqfitq, ffqzxf, dviucr, mroyq
ukcqez (129) -> paplmio, nmzgz, vnxmgtu
jklgnxw (32)
fypjed (98) -> cxhplek, ffmjzxx, dvpfc, odvadyf
uwxvsjd (313) -> edafmn, bfwgsag
iguatq (7)
flnwg (30) -> ghdzwq, kziosg, apijq, zohacp, dkspw, zmzmna, dqjepow
soscup (88)
lrrznr (536) -> ymmun, uxfcrt, wxgwp, kdsrjc, hkstlva
dkspw (918) -> prtbd, huxkort, suvtxzq, dpqsx, wcjly
goyce (52)
ueadckf (44)
zikbees (13)
uwfkgbm (98)
gdftnih (7)
zvmbtmg (99)
pfjaob (78)
gzbpbzh (10)
znoap (205) -> bpmgs, riszb
btmauhd (43)
eptpjci (80)
gejdtfw (65882) -> yeoia, fbtzaic, tbmtw, rutvyr, tucqq
ypujb (29)
hqpzd (56)
dtiqmg (301) -> katupgz, lrjdbp, oauxbtz, sppbe
yqcaue (60) -> ubpoy, feecvjl, tjvdz
goohdry (42)
glcfzs (27)
vllceh (173) -> cqzhj, jpxtrww, lhumvsh
utecy (64)
kzmsh (38) -> upalmon, fppes
iotjdfw (77)
vyqeu (83)
vmask (9)
ftkqwci (77)
tjiqr (87) -> avcwghu, cfqpega, ipbtx, fpmomi
polkn (91947) -> dvqaks, fnubw, xlhbak
xmufd (16)
mtrumh (81)
vebkntv (87) -> qdyxf, xqkov
ffqzxf (17)
mstjkgi (178) -> jyppp, oyatv, hpvsz
awkci (88)
kziosg (2380) -> pbscvh, bjhbaeq, hhvng, bucdl
fpuaei (23)
ngzhx (334) -> idvkl, dgjtv, uptfdfp
zfkliql (12)
pssff (95) -> lotiapl, jndcfc
bqytirn (78)
caaul (211) -> ehfoqf, tvvfszm, lojhip
wiprvsa (74)
lmqhg (12)
hhvng (73) -> vhlpr, nxalp
arxafnu (80)
svlzb (78)
lldzrv (81)
bfuell (95)
yhwegl (584) -> jjutz, maytl, pbwqe, rzyceeb
xqkov (95)
orfvwfh (39)
tqcdt (9)
oghvi (30)
qjqmpw (37) -> wezrbzw, xufnd
ikmdjtw (76)
gxqkboz (88) -> ygfdkew, etvxdqn
ajvtod (14)
efhdsgs (385)
iuwfcfn (46)
orjnwip (36)
kyeul (41)
qppcrmh (72)
hbdmcdc (30)
jcetf (126) -> lvrzba, xxieckm
xxieckm (94)
uokpbvj (223) -> exzvkxu, ruann
evfob (7)
rclzxhh (41)
rjkehq (163) -> fpuaei, oogzvyg
ximwl (80)
zeauw (22)
ophcgq (8)
jtviekh (41)
druuhf (37)
nedbp (77)
vbahlkz (133)
ymmun (198) -> rkauf, nkaejjm
mcjbnfk (75)
mpfrdzc (251) -> cvvewfi, zikbees
uemmhd (124) -> pxheyj, cwxvww
qyxyyfe (17)
qjzipyw (11) -> yrbypdv, ubhvop, ohjpwlf, pfvxd
fgpgrxr (2583) -> wsnnpt, vlcrv, bzoui
etvxdqn (34)
tdoxrnb (68)
bwmlg (29)
nwvfh (81)
dqqvw (95)
venip (60)
dxdioa (87)
ybppeq (224) -> weeom, aeuhflj
fpmlwfh (231) -> qmkyl, pfvnpy, ijvmnd, dnzvald
pfvnpy (12)
owexd (48) -> nkjocfh, qrfqnq
douazak (50)
mwmyxd (2288) -> ecyyqsp, kzmsh, rwulpg
fgbkh (163) -> moqjbf, mcltn, nlusd, ciygx
qokpqcj (542) -> ulxsfq, xprwsaf, ihbybvd
pgxiavo (25)
adccmtd (56)
zwyrvyj (173) -> xtprb, gvibwl
yghmpm (46)
dtovks (97)
ayismka (80)
wehkpx (90) -> zzsqh, iohhnkq, iomsug, atzunin
ldcqple (13659) -> qdhlpqn, nygkk, sogmnn
kgepl (97)
cnstz (176)
vlcrv (27) -> rtdffxh, mbfvaw, nfcrpf
tjqdup (258)
syjwi (289) -> ukgraro, glcfzs
fveuo (40)
vtazp (15)
fpxda (96)
dviucr (17)
fitxh (65)
ztocqs (40)
fuohb (367) -> nhkfwk, rfxyb
nwecq (29)
fadrtgp (90)
rtdffxh (22)
bbvcyqt (37)
gqwepeb (88)
xuhgu (82)
ghdzwq (1763) -> idbcgs, fkjnhd, ieacu, exadxz, rjkehq
eygeo (31)
qaznr (36)
muxff (15)
hmphp (16)
dpnlf (75)
zyxbmy (7)
tsqfitq (17)
nzrhyzx (432)
hghuq (81)
yotjazk (50)
ztxlw (1431) -> aoxyn, gnbmemw, vtbkd, tqytfku
lvrzba (94)
uptfdfp (29)
uztqohr (296) -> bnlxpgs, pmiwkyg
dcfod (93)
svgsp (14)
zculjs (60)
mfrcmg (52)
aoxyn (19) -> jlmbjs, siknup
pjvsofk (93)
zjzldd (89)
hngooro (139) -> xdrpbh, gnmkuj
wopctnz (95)
pbscvh (107)
seqpyc (88)
vpywo (2334) -> dtpnpq, ygdeams, cnstz
ldjeual (10)
cwxvww (16)
kvqdnuq (38) -> qjnow, zbizc, uwxvsjd, vsprxrs, inpzr, cqiexk
zotuf (132) -> jouimd, svhudk
iywmq (61)
fkjnhd (141) -> iatnsa, jkeqz
nnktssm (271) -> wamfc, qgjpqt
jpchi (82)
ijhxyp (27)
tgoxupv (60)
lxwaq (67) -> reyxj, iygrvcq, gfdnli, ewomrs
hbwuw (81)
pddmke (13)
kxbgcn (150) -> szvvmv, oxokip
lyyqnt (78)
ddnfy (82) -> gimfzpl, uwfkgbm
tjtrq (52) -> bncdukb, gydhlh, pzxhj, tkbvq, vlstbi, pbvmk
dxyhphf (22)
sgcszn (6)
nxalp (17)
gobaplu (52)
pjflk (53) -> otzkp, rujthq
ovyifn (298) -> baukd, gobaplu
lgjtrj (67)
qstxfxv (161) -> hdiot, qtwwe
pxzxws (235) -> pfjaob, ubsmxso
cfuudsk (87306) -> ensbsjj, zakeqj, rmzdg
jgzpdx (9)
eifgc (87)
tdvopw (7)
bhyawz (31)
ppmtmra (52)
hyupti (22)
hmgnq (37)
mqzkogj (342) -> dlzrs, ikufikz
htinuz (22)
hyblgwq (53)
wdvmvhe (44) -> bfvriie, ldghw, nnmsru
etlyn (72)
zmzmna (648) -> kmvtp, cbezt, nzrhyzx, yfwlsm, odkjk
lzovhs (78)
nnmsru (48)
gfxra (782) -> lvxmqy, ukcqez, wehkpx, slavm, ovyifn
mtjcvaf (20)
urxki (409)
iygpmov (46) -> jprrnd, wojfh, vhrxv, yeogm
lfkqyf (237)"""
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 25,297 | advent-of-code | MIT License |
2021/src/day18/Solution.kt | vadimsemenov | 437,677,116 | false | {"Kotlin": 56211, "Rust": 37295} | package day18
import java.nio.file.Files
import java.nio.file.Paths
fun main() {
fun part1(input: Input): Int {
return input.reduce { acc, snailfish ->
SnailfishPair(acc, snailfish).reduce()
}.magnitude()
}
fun part2(input: Input): Int {
return input.maxOf { lhs ->
input.maxOf { rhs ->
if (lhs != rhs) SnailfishPair(lhs, rhs).reduce().magnitude()
else Int.MIN_VALUE
}
}
}
check(part1(readInput("test-input.txt")) == 4140)
check(part2(readInput("test-input.txt")) == 3993)
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
private fun Snailfish.reduce(): Snailfish =
reduceExplode(0)?.first?.reduce()
?: reduceSplit()?.reduce()
?: this
private fun Snailfish.reduceExplode(depth: Int): Triple<Snailfish, Int, Int>? {
fun propagateRight(snailfish: Snailfish, add: Int): Snailfish = if (add == 0) snailfish else
when (snailfish) {
is SnailfishNumber -> SnailfishNumber(snailfish.value + add)
is SnailfishPair -> SnailfishPair(snailfish.lhs, propagateRight(snailfish.rhs, add))
}
fun propagateLeft(snailfish: Snailfish, add: Int): Snailfish = if (add == 0) snailfish else
when (snailfish) {
is SnailfishNumber -> SnailfishNumber(snailfish.value + add)
is SnailfishPair -> SnailfishPair(propagateLeft(snailfish.lhs, add), snailfish.rhs)
}
return when (this) {
is SnailfishNumber -> null
is SnailfishPair -> if (depth == 4) {
check(lhs is SnailfishNumber && rhs is SnailfishNumber)
Triple(SnailfishNumber(0), lhs.value, rhs.value)
} else {
lhs.reduceExplode(depth + 1)
?.let { (snailfish, left, right) ->
Triple(SnailfishPair(snailfish, propagateLeft(rhs, right)), left, 0)
}
?: rhs.reduceExplode(depth + 1)
?.let { (snailfish, left, right) ->
Triple(SnailfishPair(propagateRight(lhs, left), snailfish), 0, right)
}
}
}
}
private fun Snailfish.reduceSplit(): SnailfishPair? = when(this) {
is SnailfishNumber -> if (value < 10) null else
SnailfishPair(SnailfishNumber(value / 2), SnailfishNumber((value + 1) / 2))
is SnailfishPair ->
lhs.reduceSplit()?.let { SnailfishPair(it, rhs) } ?:
rhs.reduceSplit()?.let { SnailfishPair(lhs, it) }
}
private fun Snailfish.magnitude(): Int = when(this) {
is SnailfishNumber -> value
is SnailfishPair -> 3 * lhs.magnitude() + 2 * rhs.magnitude()
}
private sealed interface Snailfish
private data class SnailfishPair(
val lhs: Snailfish,
val rhs: Snailfish,
) : Snailfish
private data class SnailfishNumber(
val value: Int,
) : Snailfish
private class Parser(private val input: String) : AutoCloseable {
private var ptr = 0
fun parseSnailfish(): Snailfish = if (input[ptr] == '[') {
parsePair()
} else {
parseNumber()
}
private fun parseNumber(): SnailfishNumber {
check(input[ptr] in '0'..'9')
var res = 0
while (ptr < input.length && input[ptr].isDigit()) {
res = 10 * res + input[ptr++].code - '0'.code
}
return SnailfishNumber(res)
}
private fun parsePair(): SnailfishPair {
check(input[ptr++] == '[')
val lhs = parseSnailfish()
check(input[ptr++] == ',')
val rhs = parseSnailfish()
check(input[ptr++] == ']')
return SnailfishPair(lhs, rhs)
}
override fun close() {
check(ptr == input.length)
}
}
private fun readInput(s: String): Input {
return Files.newBufferedReader(Paths.get("src/day18/$s")).readLines().map { line ->
Parser(line).use { it.parseSnailfish() }
}
}
private typealias Input = List<Snailfish> | 0 | Kotlin | 0 | 0 | 8f31d39d1a94c862f88278f22430e620b424bd68 | 3,633 | advent-of-code | Apache License 2.0 |
src/Day09.kt | jordan-thirus | 573,476,470 | false | {"Kotlin": 41711} | import kotlin.math.sign
fun main() {
fun Point.isAdjacent(other: Point): Boolean =
x - other.x in -1..1 && y - other.y in -1..1
fun Point.move(direction: String): Point = when (direction) {
"L" -> left()
"R" -> right()
"U" -> up()
"D" -> down()
else -> throw IllegalArgumentException("Bad move")
}
fun moveToNewPosition(prev: Point, point: Point): Point {
return if (!prev.isAdjacent(point)) {
val x = (prev.x - point.x).sign + point.x
val y = (prev.y - point.y).sign + point.y
Point(y, x)
} else {
point
}
}
fun part1(input: List<String>): Int {
var head = Point(0, 0)
var tail = Point(0, 0)
val visited = mutableSetOf(tail)
for (line in input) {
val move = line.split(" ")
val distance = move[1].toInt()
val direction = move[0]
repeat(distance) {
head = head.move(direction)
tail = moveToNewPosition(head, tail)
visited.add(tail)
}
}
return visited.size
}
fun part2(input: List<String>): Int {
var snake = Array(10) { Point(0,0)}.toList().toMutableList()
val visited = mutableSetOf(snake.last())
for (line in input) {
val move = line.split(" ")
val distance = move[1].toInt()
val direction = move[0]
repeat(distance) {
snake[0] = snake[0].move(direction)
snake = snake.runningReduce { acc, point -> moveToNewPosition(acc, point) }.toMutableList()
visited.add(snake.last())
}
}
return visited.size
}
// test if implementation meets criteria from the description, like:
check(part1(readInput("Day09_test1")) == 13)
check(part2(readInput("Day09_test2")) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 59b0054fe4d3a9aecb1c9ccebd7d5daa7a98362e | 2,036 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | ajesh-n | 573,125,760 | false | {"Kotlin": 8882} | fun main() {
fun stakes(stakesString: String): MutableList<MutableList<String>> {
val stakes = mutableListOf<MutableList<String>>()
val crates = stakesString.lines().map {
it.windowed(3, 4).map { line -> line.filter { char -> char.isLetter() } }
}.dropLast(1).reversed()
for (line in crates) {
for ((j, char) in line.withIndex()) {
if (char.isNotBlank()) {
stakes.getOrNull(j)?.add(char) ?: run {
stakes.add(j, mutableListOf())
stakes[j].add(char)
}
}
}
}
return stakes
}
fun part1(input: String): String {
val (stakesString, instructions) = input.split("\n\n")
val stakes = stakes(stakesString)
instructions.split("\n").forEach {
val stakesToMove = it.split("from")[0].split(" ")[1].toInt()
val (from, to) = it.split("from")[1].split("to").map { n -> n.trim().toInt() }
repeat(stakesToMove) {
stakes[to - 1].add(stakes[from - 1].last())
stakes[from - 1].removeLast()
}
}
return stakes.joinToString("") { it.last() }
}
fun part2(input: String): String {
val (stakesString, instructions) = input.split("\n\n")
val stakes = stakes(stakesString)
instructions.split("\n").forEach {
val stakesToMove = it.split("from")[0].split(" ")[1].toInt()
val (from, to) = it.split("from")[1].split("to").map { n -> n.trim().toInt() }
stakes[from - 1].takeLast(stakesToMove).let { toMove ->
stakes[to - 1].addAll(toMove)
}
repeat(stakesToMove) {
stakes[from - 1].removeLast()
}
}
return stakes.joinToString("") { it.last() }
}
val testInput = readText("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readText("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2545773d7118da20abbc4243c4ccbf9330c4a187 | 2,111 | kotlin-aoc-2022 | Apache License 2.0 |
2021/src/Day12.kt | Bajena | 433,856,664 | false | {"Kotlin": 65121, "Ruby": 14942, "Rust": 1698, "Makefile": 454} | import java.util.*
// https://adventofcode.com/2021/day/12
fun main() {
class Graph(vertexes: Set<String>, edges: List<Pair<String, String>>) {
val edges = edges
val bigCaves = vertexes.filter { isBigCave(it) }
val smallCaves = vertexes.filter { !isBigCave(it) }
val START = "start"
val END = "end"
val paths = mutableListOf<List<String>>()
fun isBigCave(v : String) : Boolean {
return v.first().isUpperCase()
}
fun findPaths(currentPath: List<String> = listOf(START)) {
if (currentPath.contains(END)) {
paths.add(currentPath)
return
}
allowedVertexes(currentPath.last()).filter { bigCaves.contains(it) || !currentPath.contains(it) }.forEach {
val path = currentPath.toMutableList()
path.add(it)
findPaths(path)
}
}
fun findPathsPart2(currentPath: List<String> = listOf(START)) {
if (currentPath.contains(END)) {
paths.add(currentPath)
return
}
allowedVertexes(currentPath.last()).filter { av ->
av != START && (isBigCave(av) || !currentPath.contains(av) || currentPath.filter { !isBigCave(it) && it != START }.groupingBy { it }.eachCount().filterValues { it > 1 }.isEmpty())
}.forEach {
val path = currentPath.toMutableList()
path.add(it)
findPathsPart2(path)
}
}
fun allowedVertexes(vertex: String) : List<String> {
return edges.mapNotNull {
if (it.first == vertex) {
it.second
} else if (it.second == vertex) {
it.first
} else {
null
}
}
}
}
fun buildGraph() : Graph {
var edges = mutableListOf<Pair<String, String>>()
var vertexes = mutableSetOf<String>()
for (edge in readInput("Day12")) {
var verts = edge.split("-")
edges.add(Pair(verts.first(), verts.last()))
vertexes.addAll(verts)
}
return Graph(vertexes, edges)
}
fun part1() {
val g = buildGraph()
g.findPaths()
println(g.paths.size)
}
fun part2() {
val g = buildGraph()
g.findPathsPart2()
for (p in g.paths) {
println("${p.joinToString(",")}")
}
println(g.paths.size)
}
// part1()
part2()
}
| 0 | Kotlin | 0 | 0 | a5ca56b7ac8d9d48f82dc079c8ea0cf06d17109a | 2,244 | advent-of-code | Apache License 2.0 |
src/Day03.kt | ben-dent | 572,931,260 | false | {"Kotlin": 10265} | fun getIntersection(input: String): Set<Char> {
val mid = input.length / 2
val first = input.substring(0, mid).toSet()
val second = input.substring(mid).toSet()
return first.intersect(second)
}
fun getIntersection(input: List<String>): Set<Char> {
val first = input[0].toSet()
val second = input[1].toSet()
val third = input[2].toSet()
return first.intersect(second).intersect(third)
}
fun getPriority(n: Int): Int {
if (n in 65..90) {
return n - 38
}
return n - 96
}
fun getGroups(input: List<String>): List<List<String>> {
val groups = ArrayList<List<String>>()
var current = ArrayList<String>()
var count = 0
input.forEach {
current.add(it)
if (count == 2) {
groups.add(current)
current = ArrayList()
count = 0
} else {
++count
}
}
return groups
}
fun main() {
fun part1(input: List<String>): Long {
return input.sumOf { getIntersection(it).sumOf { i -> getPriority(i.code) } }.toLong()
}
fun part2(input: List<String>): Long {
val groups = getGroups(input)
return groups.sumOf { getIntersection(it).sumOf { i -> getPriority(i.code) } }.toLong()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157L)
check(part2(testInput) == 70L)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 2c3589047945f578b57ceab9b975aef8ddde4878 | 1,539 | AdventOfCode2022Kotlin | Apache License 2.0 |
leetcode2/src/leetcode/palindrome-partitioning.kt | hewking | 68,515,222 | false | null | package leetcode
/**
* 131. 分割回文串
* https://leetcode-cn.com/problems/palindrome-partitioning/
* 给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。
返回 s 所有可能的分割方案。
示例:
输入: "aab"
输出:
[
["aa","b"],
["a","a","b"]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-partitioning
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
**/
object PalindromeParitioning {
class Solution {
/**
* 思路: 回溯法
* 通用框架
* https://leetcode-cn.com/problems/palindrome-partitioning/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-3-7/
* res = []
* backTrack(路径,选择集) {
* if 终止条件
* res.add(path)
* return
* for 选择 in 选择集
* 选择
* backTrack(路径,选择集)
* 取消选择
* }
*/
fun partition(s: String): List<List<String>> {
val ans = mutableListOf<MutableList<String>>()
backTrack(ans,s,0, mutableListOf())
return ans
}
/**
* https://leetcode-cn.com/problems/palindrome-partitioning/solution/hui-su-you-hua-jia-liao-dong-tai-gui-hua-by-liweiw/
*/
fun backTrack(res: MutableList<MutableList<String>> ,s:String,index: Int,path: MutableList<String>) {
if (index == s.length) {
res.add(path.toMutableList())
return
}
for (i in index until s.length) {
val subStr = s.substring(index,i + 1)
if (!checkPalindrome(subStr)) {
continue
}
path.add(subStr)
backTrack(res,s,i + 1,path)
path.removeAt(path.size - 1)
}
}
fun checkPalindrome(s: String) : Boolean {
if (s.length == 1) return true
val len = s.length
var flag = true
for (i in 0 until len / 2) {
if (s[i] != s[len - 1 - i]) {
flag = false
}
}
return flag
}
}
@JvmStatic
fun main(args: Array<String>) {
print(Solution().partition("aab"))
}
} | 0 | Kotlin | 0 | 0 | a00a7aeff74e6beb67483d9a8ece9c1deae0267d | 2,463 | leetcode | MIT License |
src/main/kotlin/com/ginsberg/advent2018/Day15.kt | tginsberg | 155,878,142 | false | null | /*
* Copyright (c) 2018 by <NAME>
*/
/**
* Advent of Code 2018, Day 15 - Beverage Bandits
*
* Problem Description: http://adventofcode.com/2018/day/15
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2018/day15/
*/
package com.ginsberg.advent2018
import java.util.ArrayDeque
import java.util.Deque
typealias Caves = Array<CharArray>
typealias Path = List<Point>
class Day15(private val rawInput: List<String>) {
private var caves: Caves = parseCaves()
private var fighters: List<Fighter> = Fighter.findFighters(caves)
fun solvePart1(): Int {
val result = goFightGoblins()
return result.second.filterNot { it.dead }.sumBy { it.hp } * result.first
}
fun solvePart2(): Int =
generateSequence(4, Int::inc).map { ap ->
// Reset
caves = parseCaves()
fighters = Fighter.findFighters(caves)
val result = goFightGoblins(ap)
if (result.second.filter { it.team == Team.Elf }.none { it.dead }) {
result.second.filterNot { it.dead }.sumBy { it.hp } * result.first
} else {
null
}
}
.filterNotNull()
.first()
private fun goFightGoblins(elfAttackPoints: Int = 3): Pair<Int, List<Fighter>> {
fighters.filter { it.team == Team.Elf }.forEach { it.ap = elfAttackPoints }
var rounds = 0
while (round()) {
rounds++
}
return Pair(rounds, fighters)
}
private fun round(): Boolean {
// Fighters need to be in order at the start of the round.
// This is a sequence because we can lazily remove dead fighers before their turn,
// otherwise we have to manually check.
fighters.sorted().asSequence().filterNot { it.dead }.forEach { fighter ->
// Check for premature end of the round - nobody left to fight
if (!keepFighting()) {
return false
}
// If we are already in range, stop moving.
var target: Fighter? = fighter.inRange(fighters).firstOrNull()
if (target == null) {
// Movement
val path = fighter.findPathToBestEnemyAdjacentSpot(fighters, caves)
if (path.isNotEmpty()) {
fighter.moveTo(path.first(), caves)
}
// Find target
target = fighter.inRange(fighters).firstOrNull()
}
// Fight if we have a target
target?.let {
fighter.attack(it, caves)
}
}
return true // Round ended at its natural end
}
private fun keepFighting(): Boolean =
fighters.filterNot { it.dead }.distinctBy { it.team }.count() > 1
private fun parseCaves(): Caves =
rawInput.map { it.toCharArray() }.toTypedArray()
}
private enum class Team(val logo: Char) {
Elf('E'),
Goblin('G');
companion object {
fun byLogo(logo: Char): Team? =
values().firstOrNull { logo == it.logo }
}
}
private data class Fighter(
val team: Team,
var location: Point,
var hp: Int = 200,
var ap: Int = 3,
var dead: Boolean = false
) : Comparable<Fighter> {
// Enemies are in range if they are not me, neither of us is dead,
// we are not on the same team, and only 1 square away
fun inRange(others: List<Fighter>): List<Fighter> =
others.filter {
it != this &&
!this.dead &&
!it.dead &&
it.team != this.team &&
this.location.distanceTo(it.location) == 1
}
.sortedWith(compareBy({ it.hp }, { it.location }))
fun attack(target: Fighter, caves: Caves) {
target.hp -= this.ap
if (target.hp <= 0) {
// Mark enemy as dead and clean up the corpse
target.dead = true
caves[target.location.y][target.location.x] = '.'
}
}
fun moveTo(place: Point, caves: Caves) {
// We need to alter the caves because we use it for pathfinding
caves[location.y][location.x] = '.'
location = place
caves[location.y][location.x] = team.logo
}
// Bad real estate descriptions - Enemy Adjacent
fun findPathToBestEnemyAdjacentSpot(
fighters: List<Fighter>,
caves: Caves
): Path =
pathToAnyEnemy(
enemyAdjacentOpenSpots(fighters, caves),
caves
)
private fun enemyAdjacentOpenSpots(fighters: List<Fighter>, caves: Caves): Set<Point> =
fighters
.filterNot { it.dead }
.filterNot { it.team == team }
.flatMap { it.location.cardinalNeighbors().filter { neighbor -> caves[neighbor.y][neighbor.x] == '.' } }
.toSet()
private fun pathToAnyEnemy(
enemies: Set<Point>,
caves: Caves
): Path {
val seen: MutableSet<Point> = mutableSetOf(location)
val paths: Deque<Path> = ArrayDeque()
// Seed the queue with each of our neighbors, in reading order (that's important)
location.cardinalNeighbors()
.filter { caves[it.y][it.x] == '.' }
.forEach { paths.add(listOf(it)) }
// While we still have paths to examine, and haven't found the answer yet...
while (paths.isNotEmpty()) {
val path: Path = paths.removeFirst()
val pathEnd: Point = path.last()
// If this is one of our destinations, return it
if (pathEnd in enemies) {
return path
}
// If this is a new path, create a set of new paths from it for each of its
// cardinal direction (again, in reader order), and add them all back
// to the queue.
if (pathEnd !in seen) {
seen.add(pathEnd)
pathEnd.cardinalNeighbors()
.filter { caves[it.y][it.x] == '.' }
.filterNot { it in seen }
.forEach { paths.add(path + it) }
}
}
return emptyList()
}
override fun compareTo(other: Fighter): Int =
location.compareTo(other.location)
companion object {
fun findFighters(caves: Caves): List<Fighter> =
caves.mapIndexed { y, row ->
row.mapIndexed { x, spot ->
Team.byLogo(spot)?.let {
Fighter(it, Point(x, y))
}
}
}
.flatten()
.filterNotNull()
}
}
| 0 | Kotlin | 1 | 18 | f33ff59cff3d5895ee8c4de8b9e2f470647af714 | 6,658 | advent-2018-kotlin | MIT License |
src/Day02.kt | jimmymorales | 572,156,554 | false | {"Kotlin": 33914} | fun main() {
fun part1(input: List<String>): Int = input.sumOf {
val s1 = it.first() - 'A' + 1
val s2 = it.last() - 'X' + 1
when {
s2 == s1 -> 3 + s2
(s2 == 3 && s1 == 2) ||
(s2 == 2 && s1 == 1) ||
(s2 == 1 && s1 == 3) -> 6 + s2
else -> s2
}
}
fun part2(input: List<String>): Int = input.sumOf { round ->
val s1 = round.first() - 'A' + 1
when (round.last()) {
'Y' -> 3 + s1
'X' -> (s1 - 1).let { if (it == 0) 3 else it }
else -> 6 + (s1 + 1).let { if (it == 4) 1 else it }
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
val input = readInput("Day02")
println(part1(input))
// part 2
check(part2(testInput) == 12)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | fb72806e163055c2a562702d10a19028cab43188 | 938 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | fercarcedo | 573,142,185 | false | {"Kotlin": 60181} | data class Move(
val numCrates: Int,
val fromStack: Int,
val toStack: Int
)
fun main() {
fun parseStacks(input: List<String>): List<ArrayDeque<Char>> {
val stackNumbersLineRegex = "(\\d|\\s)+".toRegex()
val stackNumbersLineIndex = input.indexOfFirst { stackNumbersLineRegex.matches(it) }
val lineIndexToStackNumberMap = "\\d+".toRegex().findAll(input[stackNumbersLineIndex]).flatMap {
it.groups
}.associate { it!!.range.first to it.value.toInt() }
val numStacks = lineIndexToStackNumberMap.maxBy { it.value }.value
val stacks = mutableListOf<ArrayDeque<Char>>()
repeat(numStacks) { stacks.add(ArrayDeque()) }
val regex = "\\[(?<crate>[A-Z])\\]".toRegex()
for (i in stackNumbersLineIndex - 1 downTo 0) {
val line = input[i]
regex.findAll(line).forEach {
val crateGroup = it.groups["crate"]
val crateIndex = crateGroup!!.range.first
val crate = crateGroup.value
val stackNumber = lineIndexToStackNumberMap[crateIndex]!!
stacks[stackNumber - 1].addFirst(crate.first())
}
}
return stacks
}
fun parseMovements(input: List<String>): List<Move> {
val moves = mutableListOf<Move>()
val regexMove = "move (?<numCrates>\\d+) from (?<fromStack>\\d+) to (?<toStack>\\d+)".toRegex()
val firstMoveLine = input.indexOfFirst { regexMove.matches(it) }
for (i in firstMoveLine until input.size) {
val matchGroups = regexMove.matchEntire(input[i])!!.groups
moves.add(Move(matchGroups["numCrates"]!!.value.toInt(), matchGroups["fromStack"]!!.value.toInt() - 1, matchGroups["toStack"]!!.value.toInt() - 1))
}
return moves
}
fun executeMovements(stacks: List<ArrayDeque<Char>>,
movements: List<Move>,
allowMovingMultipleCratesAtOnce: Boolean) {
movements.forEach { move ->
val crates = mutableListOf<Char>()
repeat(move.numCrates) {
crates.add(stacks[move.fromStack].removeFirst())
}
if (move.numCrates > 1 && allowMovingMultipleCratesAtOnce) {
crates.reverse()
}
crates.forEach { stacks[move.toStack].addFirst(it) }
}
}
fun play(input: List<String>,
allowMovingMultipleCratesAtOnce: Boolean = false): String {
val stacks = parseStacks(input)
val movements = parseMovements(input)
executeMovements(stacks, movements, allowMovingMultipleCratesAtOnce)
return stacks.map { it.first() }.joinToString("")
}
fun part1(input: List<String>) = play(input)
fun part2(input: List<String>) = play(input, true)
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input)) // ZRLJGSCTR
println(part2(input)) // PRTTGRFPB
}
| 0 | Kotlin | 0 | 0 | e34bc66389cd8f261ef4f1e2b7f7b664fa13f778 | 3,075 | Advent-of-Code-2022-Kotlin | Apache License 2.0 |
src/main/kotlin/day14/Day14.kt | Arch-vile | 317,641,541 | false | null | package day14
import readFile
import utils.subsets
import java.lang.Long.parseLong
import kotlin.math.pow
interface Command
data class MaskCommand(val mask: String) : Command
data class MemoryCommand(val address: Long, val value: Long) : Command
data class Memory(val data: MutableMap<Long, Long> = mutableMapOf()) {
private lateinit var mask: String
fun process(command: Command) {
when (command) {
is MaskCommand -> mask = command.mask
is MemoryCommand -> store(command.address, command.value)
}
}
private fun store(address: Long, value: Long) {
val floatingAddresses = applyFloating(mask, address)
floatingAddresses
.forEach {
data[applyMask(mask, address + it)] = value
}
}
fun values(): Set<Map.Entry<Long, Long>> {
return data.toMap().entries
}
}
fun main(args: Array<String>) {
val maskRegex = """mask = ([01X]*)""".toRegex()
val memoryRegex = """mem\[(\d*)\] = (\d*)""".toRegex()
val input = readFile("./src/main/resources/day14Input.txt")
val commands = input
.map {
if (maskRegex.matches(it)) {
MaskCommand(maskRegex.find(it)!!.groupValues[1])
} else {
var groupValues = memoryRegex.find(it)!!.groupValues
MemoryCommand(groupValues[1].toLong(), groupValues[2].toLong())
}
}
val memory = Memory()
commands.forEach { memory.process(it) }
println(memory.values().map { it.value }.sum())
}
private fun applyMask(mask: String, value: Long): Long {
val orMaskS = mask.replace('X', '0')
val orMask = parseLong(orMaskS, 2)
return value or orMask
}
private fun applyFloating(mask: String, address: Long): List<Long> {
var alterations = mask.reversed()
.mapIndexedNotNull { index, char ->
if (char == 'X') {
var thebit = getBit(address, index)
if (thebit == '0')
2L.toDouble().pow(index)
else
-1 * 2L.toDouble().pow(index)
} else
null
}
return subsets(alterations)
.map { it.sum() }
.map { it.toLong() }
.plus(0)
}
fun getBit(address: Long, index: Int): Char {
// LOL, too tired with this puzzle 🤪
val asBinary = "000000000000000000000000000000000000000" + address.toString(2)
return asBinary[asBinary.length - index - 1]
}
| 0 | Kotlin | 0 | 0 | 12070ef9156b25f725820fc327c2e768af1167c0 | 2,269 | adventOfCode2020 | Apache License 2.0 |
src/Day04.kt | Venkat-juju | 572,834,602 | false | {"Kotlin": 27944} | import kotlin.system.measureNanoTime
data class SectionRange(
val startSection : Int,
val endSection: Int
)
fun SectionRange.isFullyContained(other: SectionRange): Boolean {
return (this.startSection >= other.startSection && this.endSection <= other.endSection) ||
(this.startSection <= other.startSection && this.endSection >= other.endSection)
}
fun SectionRange.isAtleastSingleSectionOverlap(other: SectionRange): Boolean {
return ((this.startSection..this.endSection) intersect (other.startSection .. other.endSection)).isNotEmpty()
}
fun String.toSectionRange(): List<SectionRange> {
return this.split(",").map { it.split("-") }.map { SectionRange(it.first().toInt(), it.last().toInt()) }
}
fun main() {
fun part1(input: List<String>): Int {
return input.map(String::toSectionRange).count { it.first().isFullyContained(it.last()) }
}
fun part2(input: List<String>): Int {
return input.map(String::toSectionRange).count { it.first().isAtleastSingleSectionOverlap(it.last()) }
}
// 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")
val timeTaken = measureNanoTime {
println(part1(input))
println(part2(input))
}
println("Time taken: $timeTaken ns")
}
| 0 | Kotlin | 0 | 0 | 785a737b3dd0d2259ccdcc7de1bb705e302b298f | 1,421 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/days/Solution10.kt | Verulean | 725,878,707 | false | {"Kotlin": 62395} | package days
import adventOfCode.InputHandler
import adventOfCode.Solution
import adventOfCode.util.PairOf
import adventOfCode.util.Point2D
import adventOfCode.util.plus
import kotlin.math.abs
typealias CharGrid = Array<CharArray>
private operator fun CharGrid.get(point: Point2D) = this[point.first][point.second]
private operator fun CharGrid.set(point: Point2D, value: Char) {
this[point.first][point.second] = value
}
object Solution10 : Solution<CharGrid>(AOC_YEAR, 10) {
override fun getInput(handler: InputHandler) = handler.getInput("\n").map(String::toCharArray).toTypedArray()
private enum class Direction(val vector: Point2D) {
NORTH(-1 to 0),
EAST(0 to 1),
SOUTH(1 to 0),
WEST(0 to -1)
}
private operator fun Direction.unaryMinus() = mapOf(
Direction.NORTH to Direction.SOUTH,
Direction.SOUTH to Direction.NORTH,
Direction.EAST to Direction.WEST,
Direction.WEST to Direction.EAST
).getValue(this)
private val pipeBends = setOf('L', 'J', '7', 'F')
private val pipeOpenings = mapOf(
'|' to setOf(Direction.NORTH, Direction.SOUTH),
'-' to setOf(Direction.EAST, Direction.WEST),
'L' to setOf(Direction.NORTH, Direction.EAST),
'J' to setOf(Direction.NORTH, Direction.WEST),
'7' to setOf(Direction.SOUTH, Direction.WEST),
'F' to setOf(Direction.SOUTH, Direction.EAST),
'.' to setOf()
)
private fun findStart(grid: CharGrid): Point2D {
grid.forEachIndexed { i, row ->
val j = row.indexOf('S')
if (j >= 0) return i to j
}
return -1 to -1
}
private fun traversePath(grid: CharGrid, position: Point2D, direction: Direction): Pair<List<Point2D>, Int> {
val vertices = mutableListOf<Point2D>()
var boundaryPoints = 0
var p = position
var d = direction
do {
p += d.vector
val tile = grid[p]
d = pipeOpenings.getValue(tile).first { it != -d }
if (tile in pipeBends) vertices.add(p)
boundaryPoints++
} while (p != position)
return vertices to boundaryPoints
}
override fun solve(input: CharGrid): PairOf<Int> {
val startPosition = findStart(input)
val startOpenings = Direction.entries.filter { d ->
val adj = startPosition + d.vector
if (adj.first !in input.indices || adj.second !in input[0].indices) false
else -d in pipeOpenings.getValue(input[adj])
}
input[startPosition] = pipeOpenings.entries.first { (_, openings) -> (startOpenings - openings).isEmpty() }.key
val (vertices, boundaryPoints) = traversePath(input, startPosition, startOpenings.first())
// Shoelace Formula + Pick's Theorem
val area = abs(vertices.zip(vertices.drop(1) + vertices.take(1)).sumOf { (p1, p2) ->
p1.first * p2.second - p1.second * p2.first
}) / 2
return boundaryPoints / 2 to area - boundaryPoints / 2 + 1
}
}
| 0 | Kotlin | 0 | 1 | 99d95ec6810f5a8574afd4df64eee8d6bfe7c78b | 3,067 | Advent-of-Code-2023 | MIT License |
src/Day03.kt | TheGreatJakester | 573,222,328 | false | {"Kotlin": 47612} | import utils.readInputAsLines
fun String.firstHalf(): String {
return this.substring(0, this.length / 2)
}
fun String.secondHalf(): String {
return this.substring(this.length / 2, this.length)
}
fun scoreLetter(letter: Char): Int {
if (letter in 'A'..'Z') {
return letter.code - 'A'.code + 27
} else if (letter in 'a'..'z') {
return letter.code - 'a'.code + 1
} else {
throw Exception("Missed")
}
}
fun main() {
fun part1(input: List<String>): Int {
val letters = input.mapNotNull {
val first = it.firstHalf()
val last = it.secondHalf()
first.firstOrNull { letter -> last.contains(letter) }
}
val scroes = letters.map(::scoreLetter)
return scroes.sum()
}
fun part2(input: List<String>): Int {
val mutableInput = mutableListOf<String>().apply {
addAll(input)
}
var sum = 0
while (mutableInput.isNotEmpty()) {
val (elf1, elf2, elf3) = mutableInput.take(3)
repeat(3) {
mutableInput.removeAt(0)
}
val shared = elf1.filter { elf2.contains(it) }.first { elf3.contains(it) }
sum += scoreLetter(shared)
}
return sum
}
// test if implementation meets criteria from the description, like:
val testInput = readInputAsLines("Day03_test")
check(part1(testInput) == 157)
val input = readInputAsLines("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | c76c213006eb8dfb44b26822a44324b66600f933 | 1,550 | 2022-AOC-Kotlin | Apache License 2.0 |
src/Day12.kt | freszu | 573,122,040 | false | {"Kotlin": 32507} | import java.util.*
private const val START = 'S'
private const val END = 'E'
fun main() {
fun Matrix<Char>.dijkstraShortestPathLength(
start: Position,
end: Position
): Int? {
val toBeEvaluated = PriorityQueue<Pair<Position, Int>>(compareBy { (_, distance) -> distance })
toBeEvaluated.add(start to 0)
val visited = mutableSetOf<Position>()
while (toBeEvaluated.isNotEmpty()) {
val (position, distance) = toBeEvaluated.poll()
if (position !in visited) {
if (position == end) return distance
visited.add(position)
neighbors(position)
.filter { get(position).code + 1 >= get(it).code }
.filter { it !in visited }
.forEach { neighbor -> toBeEvaluated.add(neighbor to distance + 1) }
}
}
return null
}
fun part1(lines: List<String>): Int {
val terrainMap = lines.map { it.toList() }
val start = terrainMap.positionOf(START)
val end = terrainMap.positionOf(END)
return terrainMap
.replace(start, 'a')
.replace(end, 'z')
.dijkstraShortestPathLength(start, end)
.let(::requireNotNull)
}
fun part2(lines: List<String>): Int {
val terrainMap = lines.map { it.toList() }
val start = terrainMap.positionOf(START)
val end = terrainMap.positionOf(END)
val terrainWithoutMarkings = terrainMap.replace(start, 'a').replace(end, 'z')
return terrainWithoutMarkings.findAll('a')
.map { terrainWithoutMarkings.dijkstraShortestPathLength(it, end) }
.filterNotNull()
.min()
}
val testInput = readInput("Day12_test")
val input = readInput("Day12")
check(part1(testInput) == 31)
println(part1(input))
check(part2(testInput) == 29)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2f50262ce2dc5024c6da5e470c0214c584992ddb | 1,962 | aoc2022 | Apache License 2.0 |
src/Day18.kt | joy32812 | 573,132,774 | false | {"Kotlin": 62766} | import java.util.*
import kotlin.math.abs
data class Cube(val x: Int, val y: Int, val z: Int)
fun main() {
fun String.toCube(): Cube {
val (x, y, z) = this.split(",").map { it.toInt() }
return Cube(x + 1, y + 1, z + 1)
}
fun nextTo(a: Cube, b: Cube): Boolean {
return abs(a.x - b.x) + abs(a.y - b.y) + abs(a.z - b.z) == 1
}
fun part1(input: List<String>): Int {
val cubes = input.map { it.toCube() }
var total = cubes.size * 6
for (i in cubes.indices) {
for (j in i + 1 until cubes.size) {
if (nextTo(cubes[i], cubes[j])) total -= 2
}
}
return total
}
fun toKey(cube: Cube): Int {
return cube.x * 1000000 + cube.y * 1000 + cube.z
}
fun toXYZ(key: Int): List<Int> {
val x = key / 1000000
val y = (key % 1000000) / 1000
val z = key % 1000
return listOf(x, y, z)
}
/**
* BFS
*/
fun part2(input: List<String>): Int {
val n = 50
val grid = Array(n) { Array(n) { Array(n) { false } } }
val visited = Array(n) { Array(n) { Array(n) { false } } }
val cubes = input.map { it.toCube() }
for (cube in cubes) grid[cube.x][cube.y][cube.z] = true
visited[0][0][0] = true
val Q = LinkedList<Int>()
val key = toKey(Cube(0, 0, 0))
Q.add(key)
while (Q.isNotEmpty()) {
val key = Q.poll()
val (x, y, z) = toXYZ(key)
for (dx in -1..1) {
for (dy in -1..1) {
for (dz in -1..1) {
val nx = x + dx
val ny = y + dy
val nz = z + dz
if (nx < 0 || nx >= n || ny < 0 || ny >= n || nz < 0 || nz >= n) continue
if (!nextTo(Cube(x, y, z), Cube(nx, ny, nz))) continue
if (visited[nx][ny][nz]) continue
if (grid[nx][ny][nz]) continue
visited[nx][ny][nz] = true
val nkey = toKey(Cube(nx, ny, nz))
Q.add(nkey)
}
}
}
}
var ans = 0
for (x in 0 until n) {
for (y in 0 until n) {
for (z in 0 until n) {
if (!visited[x][y][z]) continue
for (dx in -1..1) {
for (dy in -1..1) {
for (dz in -1..1) {
val nx = x + dx
val ny = y + dy
val nz = z + dz
if (nx < 0 || nx >= n || ny < 0 || ny >= n || nz < 0 || nz >= n) continue
if (!nextTo(Cube(x, y, z), Cube(nx, ny, nz))) continue
if (grid[nx][ny][nz]) ans++
}
}
}
}
}
}
return ans
}
println(part1(readInput("data/day18_test")))
println(part1(readInput("data/day18")))
println(part2(readInput("data/day18_test")))
println(part2(readInput("data/day18")))
}
| 0 | Kotlin | 0 | 0 | 5e87958ebb415083801b4d03ceb6465f7ae56002 | 3,293 | aoc-2022-in-kotlin | Apache License 2.0 |
src/day09/Day09.kt | TheJosean | 573,113,380 | false | {"Kotlin": 20611} | package day09
import readInput
import kotlin.math.absoluteValue
import kotlin.math.min
fun main() {
data class Coordinate(var x: Int, var y: Int)
fun getMotions(direction: String, amount: Int): List<Coordinate> {
val motions = when (direction) {
"R" -> (1..amount).map { Coordinate(1, 0) }
"L" -> (-amount..-1).map { Coordinate(-1, 0) }
"U" -> (1..amount).map { Coordinate(0, 1) }
"D" -> (-amount..-1).map { Coordinate(0, -1) }
else -> listOf()
}
return motions
}
fun getPosition(target: Coordinate, knots: List<Coordinate>): Coordinate? {
var next = target
knots.forEach { coordinate ->
val distance = Coordinate(next.x - coordinate.x, next.y - coordinate.y)
if (distance.x.absoluteValue > 1 || distance.y.absoluteValue > 1) {
val x = min(distance.x.absoluteValue, 1)
val y = min(distance.y.absoluteValue, 1)
coordinate.x += if (distance.x > 0) x else -x
coordinate.y += if (distance.y > 0) y else -y
} else {
return null
}
next = coordinate
}
return knots.last().copy()
}
fun execute(input: List<String>, knotsCount: Int): Int {
val head = Coordinate(0, 0)
val elements = List(knotsCount) { Coordinate(0, 0) }
return 1 + input.map {
val (direction, amount) = it.split(' ')
getMotions(direction, amount.toInt())
}.flatten().mapNotNull {
head.x += it.x; head.y += it.y
getPosition(head, elements)
}.toSet().size
}
fun part1(input: List<String>): Int {
return execute(input, 1)
}
fun part2(input: List<String>): Int {
return execute(input, 9)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("/day09/Day09_test")
check(part1(testInput) == 13)
val testInput2 = readInput("/day09/Day09_test2")
check(part2(testInput2) == 36)
val input = readInput("/day09/Day09")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 798d5e9b1ce446ba3bac86f70b7888335e1a242b | 2,200 | advent-of-code | Apache License 2.0 |
src/main/kotlin/Day03.kt | N-Silbernagel | 573,145,327 | false | {"Kotlin": 118156} | fun main() {
fun findCommonChar(firstCompartment: CharSequence, secondCompartment: CharSequence): Char {
for (cFirst in firstCompartment) {
for (cSecond in secondCompartment) {
if (cFirst == cSecond) {
return cFirst
}
}
}
throw RuntimeException()
}
fun getPriority(commonChar: Char): Int {
val ascii = commonChar.code
if (commonChar.isLowerCase()) {
return ascii - 96
}
return ascii - 38
}
fun compare(firstCompartment: CharSequence, secondCompartment: CharSequence, value: Int): Int {
val commonChar = findCommonChar(firstCompartment, secondCompartment)
return value + getPriority(commonChar)
}
fun part1(input: List<String>): Int {
var value = 0
for (rucksack in input) {
val compartmentSize = rucksack.length / 2
val firstCompartment = rucksack.subSequence(0, compartmentSize)
val secondCompartment = rucksack.subSequence(compartmentSize, rucksack.length)
value = compare(firstCompartment, secondCompartment, value)
}
return value
}
fun calculatePriorityOfGroup(
chunk: List<String>,
): Int {
for (char in chunk[0]) {
val secondRucksackHas = chunk[1].indexOf(char) != -1
val thirdRucksackHas = chunk[2].indexOf(char) != -1
if (secondRucksackHas && thirdRucksackHas) {
return getPriority(char)
}
}
return 0
}
fun part2(input: List<String>): Int {
val chunkedInput: List<List<String>> = input.chunked(3)
var sumOfPriorities = 0
for (chunk in chunkedInput) {
sumOfPriorities += calculatePriorityOfGroup(chunk)
}
return sumOfPriorities
}
val input = readFileAsList("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b0d61ba950a4278a69ac1751d33bdc1263233d81 | 1,989 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/days/Solution12.kt | Verulean | 725,878,707 | false | {"Kotlin": 62395} | package days
import adventOfCode.InputHandler
import adventOfCode.Solution
import adventOfCode.util.PairOf
import adventOfCode.util.TripleOf
import adventOfCode.util.ints
typealias Hotspring = Pair<String, List<Int>>
object Solution12 : Solution<List<Hotspring>>(AOC_YEAR, 12) {
override fun getInput(handler: InputHandler) = handler.getInput("\n")
.map { it.split(' ') }
.map { it.first() to it.last().ints() }
private fun getArrangements(hotspring: Hotspring): Long {
val (line, groupLengths) = hotspring
val dp = mutableMapOf<TripleOf<Int>, Long>()
fun f(i: Int, j: Int, l: Int): Long {
val k = Triple(i, j, l)
if (k in dp) return dp.getValue(k)
if (i == line.length) {
return when {
j == groupLengths.size && l == 0 -> 1
j == groupLengths.size - 1 && l == groupLengths.last() -> 1
else -> 0
}
}
var ret = 0L
when (line[i]) {
'.' -> {
if (l == 0) ret += f(i + 1, j, 0)
if (j < groupLengths.size && l == groupLengths[j]) ret += f(i + 1, j + 1, 0)
}
'#' -> ret += f(i + 1, j, l + 1)
else -> {
if (l == 0) ret += f(i + 1, j, 0)
if (j < groupLengths.size && l == groupLengths[j]) ret += f(i + 1, j + 1, 0)
ret += f(i + 1, j, l + 1)
}
}
dp[k] = ret
return ret
}
return f(0, 0, 0)
}
override fun solve(input: List<Hotspring>): PairOf<Long> {
val ans1 = input.sumOf(::getArrangements)
val ans2 =
input.map { (line, groupLengths) -> List(5) { line }.joinToString("?") to (1..5).flatMap { groupLengths } }
.sumOf(::getArrangements)
return ans1 to ans2
}
}
| 0 | Kotlin | 0 | 1 | 99d95ec6810f5a8574afd4df64eee8d6bfe7c78b | 1,964 | Advent-of-Code-2023 | MIT License |
src/main/kotlin/days/model/Almanac.kt | errob37 | 726,532,024 | false | {"Kotlin": 29748, "Shell": 408} | package days.model
data class Almanac(
val input: List<String>,
val seedMode: SeedMode,
) {
private val seeds = extractSeed()
private val resourceMaps = extractResourceMaps()
private var chainMap: List<ResourceMap>? = null
fun getMinimumLocation(): Long {
ensureChainMap()
return if (seedMode == SeedMode.UNIT) {
seeds.minOf {
chainMap!!.fold(it) { acc, resourcesMap ->
resourcesMap.map(acc)
}
}
} else {
var min = Long.MAX_VALUE
seeds.forEach {
val converted = chainMap!!.fold(it) { toConvert, resourcesMap -> resourcesMap.map(toConvert) }
if (converted < min) {
min = converted
}
}
min
}
}
private fun extractSeed(): List<Long> {
val seedList = input
.first()
.split(":")[1]
.trim()
.split(" ")
.filter { it.isNotBlank() }
.map { it.toLong() }
if (seedMode == SeedMode.UNIT) return seedList
return seedList
.chunked(2)
.map {
val start = it.first()
val range = it[1]
val end = start + range
val longRange = LongRange(start, end - 1)
longRange
}
.toList()
.flatten()
}
private fun extractResourceMaps() =
input
.drop(2)
.splitOnEmptyLine()
.map { extractResourceMap(it) }
private fun extractResourceMap(input: List<String>): ResourceMap {
val (from, to) = mapNameToResourceType(input.first())
val rawRange = input.drop(1)
return ResourceMap(from, to, rawRange.map { extractRange(it) })
}
private fun mapNameToResourceType(input: String): Pair<Resource, Resource> {
val (resourceTypes, _) = input.split(" ")
val (fromType, _, toType) = resourceTypes.split("-")
return Pair(
Resource.valueOf(fromType.uppercase()),
Resource.valueOf(toType.uppercase())
)
}
private fun extractRange(input: String): Mapper {
val (destinationRangeStart, sourceRangeStart, rangeLength) =
input.split(" ").map { it.trim() }
return Mapper(sourceRangeStart.toLong(), destinationRangeStart.toLong(), rangeLength.toLong())
}
private fun ensureChainMap() {
if (chainMap == null) {
chainMap = mutableListOf<ResourceMap>().apply {
var nextMap = search(Resource.SEED)
while (nextMap != null) {
add(nextMap)
nextMap = search(nextMap.toResource)
}
}
}
}
private fun search(resource: Resource): ResourceMap? {
return resourceMaps.firstOrNull { it.fromResource == resource }
}
}
data class ResourceMap(
val fromResource: Resource,
val toResource: Resource,
val mapper: List<Mapper>
) {
fun map(l: Long): Long {
return mapper.firstOrNull { it.toLongRange().contains(l) }?.map(l) ?: l
}
}
data class Mapper(
val sourceStart: Long,
val destinationStart: Long,
val rangeLength: Long
) {
fun map(l: Long): Long {
val offset = l - sourceStart
return destinationStart + offset
}
fun toLongRange() = LongRange(sourceStart, sourceStart + rangeLength - 1)
}
enum class Resource {
FERTILIZER,
LIGHT,
LOCATION,
SEED,
SOIL,
WATER,
TEMPERATURE,
HUMIDITY,
}
enum class SeedMode {
UNIT,
RANGE
}
fun List<String>.splitOnEmptyLine(): List<List<String>> {
val index = this.indexOfFirst(String::isNullOrBlank)
return if (index == -1) {
listOf(this)
} else {
return listOf(this.take(index)) + this.drop(index + 1).splitOnEmptyLine()
}
}
| 0 | Kotlin | 0 | 0 | 79db6f0f56d207b68fb89425ad6c91667a84d60f | 3,976 | adventofcode-2023 | Apache License 2.0 |
src/main/kotlin/day20/Day20.kt | Jessevanbekkum | 112,612,571 | false | null | package day20
import util.readLines
import java.lang.Math.abs
fun day20_1(input: String): Int {
val particles = readLines(input).mapIndexed { i, s -> Particle(i, s) }.toMutableList()
(0..1_000).forEach {
particles.forEach { it.step() }
}
return particles.minBy { p -> p.sum() }!!.nr
}
fun day20_2(input: String): Int {
val particles = readLines(input).mapIndexed { i, s -> Particle(i, s) }.toMutableList()
(0..10_000).forEach {
particles.forEach { it.step() }
particles.sort()
var i = 0;
var j = 1;
val booms = mutableListOf<Particle>()
var currentSum = particles[0].sum()
while (i < particles.size - 1) {
if (boom(particles[i], particles[j])) {
booms.add(particles[i])
booms.add(particles[j])
}
j++
if (j >= particles.size || particles[j].sum() != currentSum) {
i++
currentSum = particles[i].sum()
j = i + 1
}
}
particles.removeAll(booms)
}
return particles.size
}
fun boom(p1: Particle, p2: Particle): Boolean {
return p1.pX == p2.pX && p1.pY == p2.pY && p1.pZ == p2.pZ
}
data class Particle(val nr: Int, val line: String) : Comparable<Particle> {
override fun compareTo(other: Particle): Int {
return this.sum() - other.sum()
}
var pX: Int
var pY: Int
var pZ: Int
var vX: Int
var vY: Int
var vZ: Int
val aX: Int
val aY: Int
val aZ: Int
val lp = Regex("p=<(-?\\d*),(-?\\d*),(-?\\d*)>, v=<(-?\\d*),(-?\\d*),(-?\\d*)>, a=<(-?\\d*),(-?\\d*),(-?\\d*)>")
init {
val match = lp.matchEntire(line)
pX = match!!.groupValues[1].toInt()
pY = match.groupValues[2].toInt()
pZ = match.groupValues[3].toInt()
vX = match.groupValues[4].toInt()
vY = match.groupValues[5].toInt()
vZ = match.groupValues[6].toInt()
aX = match.groupValues[7].toInt()
aY = match.groupValues[8].toInt()
aZ = match.groupValues[9].toInt()
}
fun sum(): Int {
return abs(pX) + abs(pY) + abs(pZ)
}
fun step() {
vX += aX
vY += aY
vZ += aZ
pX += vX
pY += vY
pZ += vZ
}
override fun toString(): String {
return nr.toString() + "-(" + pX + "," + pY + "," + pZ + ")"
}
} | 0 | Kotlin | 0 | 0 | 1340efd354c61cd070c621cdf1eadecfc23a7cc5 | 2,432 | aoc-2017 | Apache License 2.0 |
2022/src/main/kotlin/com/github/akowal/aoc/Day09.kt | akowal | 573,170,341 | false | {"Kotlin": 36572} | package com.github.akowal.aoc
import com.github.akowal.aoc.Direction.D
import com.github.akowal.aoc.Direction.L
import com.github.akowal.aoc.Direction.R
import com.github.akowal.aoc.Direction.U
import kotlin.math.abs
import kotlin.math.sign
class Day09 {
private val headRoute = inputFile("day09").readLines().flatMap { line ->
val (dir, dist) = line.split(' ').let { it[0] to it[1].toInt() }
List(dist) { Direction.valueOf(dir) }
}.scan(Point(0, 0)) { prev, move ->
prev.run {
when (move) {
L -> copy(x = x - 1)
R -> copy(x = x + 1)
U -> copy(y = y + 1)
D -> copy(y = y - 1)
}
}
}
fun solvePart1(): Int {
val tailRoute = follow(headRoute)
return tailRoute.toSet().size
}
fun solvePart2(): Int {
var knotRoute = headRoute
repeat(9) {
knotRoute = follow(knotRoute)
}
return knotRoute.toSet().size
}
private fun follow(route: List<Point>) = route.scan(Point(0, 0)) { tail, head ->
val dx = tail.x - head.x
val dy = tail.y - head.y
when {
abs(dx) < 2 && abs(dy) < 2 -> tail// no pull
abs(dx) > abs(dy) -> head.copy(x = head.x + dx.sign)// horizontal pull
abs(dy) > abs(dx) -> head.copy(y = head.y + dy.sign)// vertical pull
else -> Point(x = head.x + dx.sign, y = head.y + dy.sign) // diagonal pull
}
}
}
enum class Direction {
L, R, U, D
}
fun main() {
val solution = Day09()
println(solution.solvePart1())
println(solution.solvePart2())
}
| 0 | Kotlin | 0 | 0 | 02e52625c1c8bd00f8251eb9427828fb5c439fb5 | 1,657 | advent-of-kode | Creative Commons Zero v1.0 Universal |
src/main/kotlin/ru/timakden/aoc/year2022/Day18.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.Day18.VoxelWorld.Voxel
/**
* [Day 18: Boiling Boulders](https://adventofcode.com/2022/day/18).
*/
object Day18 {
@JvmStatic
fun main(args: Array<String>) {
measure {
val input = readInput("year2022/Day18")
println("Part One: ${part1(input)}")
println("Part Two: ${part2(input)}")
}
}
fun part1(input: List<String>): Int {
val world = generateWorld(input)
return world.solidVoxels.sumOf { cur -> 6 - cur.neighbors.mapNotNull(world.voxels::get).count { it } }
}
fun part2(input: List<String>): Int {
val world = generateWorld(input)
val hollowInside = world.hollowGroups().filterNot { it.value }.flatMap { it.key }.toSet()
val solids = world.solidVoxels.toSet()
return solids.sumOf { it.neighbors.filterNot(hollowInside::contains).filterNot(solids::contains).count() }
}
private fun generateWorld(input: List<String>): VoxelWorld {
val w = input.map { line ->
val (x, y, z) = line.split(',').map { it.toInt() }
Voxel(x, y, z)
}.associateWith { true }.let { VoxelWorld().apply { voxels.putAll(it) } }
for (x in w.voxels.keys.minOf(Voxel::x)..w.voxels.keys.maxOf(Voxel::x)) {
for (y in w.voxels.keys.minOf(Voxel::y)..w.voxels.keys.maxOf(Voxel::y)) {
for (z in w.voxels.keys.minOf(Voxel::z)..w.voxels.keys.maxOf(Voxel::z)) {
if (Voxel(x, y, z) !in w.voxels) w.voxels[Voxel(x, y, z)] = false
}
}
}
return w
}
class VoxelWorld {
data class Voxel(val x: Int, val y: Int, val z: Int) {
private val left: Voxel get() = copy(x = x - 1)
private val right: Voxel get() = copy(x = x + 1)
private val up: Voxel get() = copy(y = y + 1)
private val down: Voxel get() = copy(y = y - 1)
private val front: Voxel get() = copy(z = z + 1)
private val behind: Voxel get() = copy(z = z - 1)
val neighbors get() = sequenceOf(left, right, up, down, front, behind)
}
val voxels = hashMapOf<Voxel, Boolean>()
fun hollowGroups(): Map<Set<Voxel>, Boolean> {
val hollowGroups = hashMapOf<Set<Voxel>, Boolean>()
val globalQueue = hollowVoxels.toHashSet()
while (globalQueue.isNotEmpty()) {
val group = hashSetOf<Voxel>()
val fst = globalQueue.first()
globalQueue.remove(fst)
group.add(fst)
val localQueue = ArrayDeque(group)
var outside = false
while (localQueue.isNotEmpty()) {
for (neighbor in localQueue.removeFirst().neighbors) {
if (voxels[neighbor] == null) outside = true
else if (voxels[neighbor] == false && !group.contains(neighbor)) {
group.add(neighbor)
globalQueue.remove(neighbor)
localQueue.add(neighbor)
}
}
}
hollowGroups[group] = outside
}
return hollowGroups
}
val solidVoxels
get() = voxels
.filter { (_, solid) -> solid }
.map { (voxel, _) -> voxel }
private val hollowVoxels
get() = voxels
.filter { (_, solid) -> !solid }
.map { (voxel, _) -> voxel }
}
}
| 0 | Kotlin | 0 | 3 | acc4dceb69350c04f6ae42fc50315745f728cce1 | 3,709 | advent-of-code | MIT License |
src/main/kotlin/dp/LBSubstring.kt | yx-z | 106,589,674 | false | null | package dp
import util.*
// given A[1..n] composed of '[', ']', '(', ')', ex. A = ([]])()
// find the length of
// longest balanced subsequence of A, i.e. matching parenthesis/brackets
// ex. ([] )() -> 6 in the example above
fun main(args: Array<String>) {
val A = "([]])()".toCharOneArray()
println(A.lbs()) // 6
}
fun OneArray<Char>.lbs(): Int {
val A = this
val n = size
// dp(i, j): len of lbs of A[i..j]
// memoization structure: 2d arr dp[1..n, 1..n]
val dp = OneArray(n) { OneArray(n) { 0 } }
// space: O(n^2)
// base case:
// dp(i, j) = 0 if i, j !in indices or i >= j
// recursive case:
// dp(i, j) = max_k { 2 + dp(i + 1, j - 1), dp(i, k) + dp(k + 1, j) }
// where k in i + 1..j - 1 if A[i] matches A[j]
// = max_k { dp(i, k) + dp(k + 1, j) } same k as above o/w
// dependency: dp(i, j) depends on dp(i + 1, j - 1), dp(i, k), and dp(k + 1, j)
// , that is entries below, to the left, and to the lower-left
// eval order: outer loop for i decreasing from n - 1 down to 1
for (i in n - 1 downTo 1) {
// inner loop for j increasing from i + 1 to n
for (j in i + 1..n) {
// loop for k doesn't matter, say increasing from i + 1 to j - 1
dp[i, j] = (i + 1 until j)
.map { k -> dp[i, k] + dp[k + 1, j] }
.max() ?: 0
if (A[i] match A[j]) {
dp[i, j] = max(dp[i, j], 2 + dp[i + 1, j - 1])
}
}
}
// time: O(n^3)
// dp.prettyPrintTable()
return dp[1, n]
}
infix fun Char.match(that: Char) = when (this) {
'(' -> that == ')'
'[' -> that == ']'
else -> false
}
| 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 1,555 | AlgoKt | MIT License |
src/main/kotlin/dev/bogwalk/batch0/Problem1.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch0
import dev.bogwalk.util.maths.gaussSum
import dev.bogwalk.util.maths.lcm
/**
* Problem 1: Multiples of 3 or 5
*
* https://projecteuler.net/problem=1
*
* Goal: Find the sum of all natural numbers less than N that are multiples of either of the
* provided factors K1 or K2.
*
* Constraints: 1 <= N <= 1e9, 1 <= K < N
*
* e.g.: N = 10, K1 = 3, K2 = 5
* multiples of K1 || K2 < N = {3, 5, 6, 9}
* sum = 23
*/
class MultiplesOf3Or5 {
/**
* Brute iteration through all numbers < [n] that checks for selector predicate.
*
* SPEED (WORSE): 3.2e+05ns for N = 1e3, K1 = 3, K2 = 5
* SPEED (WORSE): 22.35ms for N = 1e6, K1 = 3, K2 = 5
* SPEED (WORSE): 263.28ms for N = 1e7, K1 = 3, K2 = 5
*
* @throws OutOfMemoryError for the occasional upper test constraints > N = 1e7.
*/
fun sumOfMultiplesBrute(n: Int, factor1: Int, factor2: Int): Long {
val minNum = minOf(factor1, factor2).toLong()
return (minNum until n.toLong()).sumOf { num ->
if (num % factor1 == 0L || num % factor2 == 0L) num else 0L
}
}
/**
* Calculates the sum of multiples of both factors minus the sum of duplicates found via the
* least common multiple of the given factors.
*
* SPEED (BETTER): 2400ns for N = 1e3, K1 = 3, K2 = 5
* SPEED (BETTER): 3030ns for N = 1e6, K1 = 3, K2 = 5
* SPEED (BETTER): 4930ns for N = 1e7, K1 = 3, K2 = 5
* SPEED (BETTER): 3200ns for N = 1e9, K1 = 3, K2 = 5
*/
fun sumOfMultiples(n: Int, factor1: Int, factor2: Int): Long {
val maxTerm = n - 1 // n not inclusive
return if (factor1 == factor2) {
sumOfArithProgression(maxTerm, factor1)
} else {
val sumOfDuplicates = sumOfArithProgression(
maxTerm,
lcm(factor1.toLong(), factor2.toLong()).toInt()
)
sumOfArithProgression(maxTerm, factor1)
.plus(sumOfArithProgression(maxTerm, factor2))
.minus(sumOfDuplicates)
}
}
/**
* Calculates the sum of an arithmetic progression sequence.
*
* Solution based on the formula:
*
* S_n = {n}Sigma{k=1} a + (k-1)d = n(2a + (n - 1)d)/2,
*
* where a is the 1st term, d is the delta, and n is the amount of terms to add.
*
* a and d are the same in this case, so the formula becomes:
*
* S_n = (n(n + 1)d)/2
*
* Note that this is an adapted Gaussian sum (triangular number) formula, where n is replaced
* with the amount of terms that are evenly divisible by d, then the original formula is
* multiplied by d.
*/
private fun sumOfArithProgression(maxTerm: Int, delta: Int): Long {
val terms = maxTerm / delta
return terms.gaussSum() * delta.toLong()
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 2,879 | project-euler-kotlin | MIT License |
src/Day03.kt | atsvetkov | 572,711,515 | false | {"Kotlin": 10892} | fun main() {
fun Char.priority() = when (this) {
in 'a'..'z' -> this - 'a' + 1
in 'A'..'Z' -> this - 'A' + 27
else -> 0
}
fun part1(input: List<String>): Int {
return input.sumOf { line ->
val size = line.length
val wrongItems = line.substring(0, size/2).toCharArray().intersect(line.substring(size/2).toList().toSet())
check(wrongItems.size == 1) { "Only one wrong item is expected" }
wrongItems.first().priority()
}
}
fun part2(input: List<String>): Int {
return input
.chunked(3)
.sumOf { sacks ->
val commonItems = sacks[0].toSet().intersect(sacks[1].toSet()).intersect(sacks[2].toSet())
check(commonItems.size == 1) { "Only one common item is expected" }
commonItems.first().priority()
}
}
val input = readInput("Day03")
println("Part 1: " + part1(input))
println("Part 2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | 01c3bb6afd658a2e30f0aee549b9a3ac4da69a91 | 1,019 | advent-of-code-2022 | Apache License 2.0 |
Array/huangxinyu/kotlin/src/MergeSortedArray.kt | JessonYue | 268,215,243 | false | null | package com.ryujin.algorithm
/**
* 给定两个排序后的数组 A 和 B,其中 A 的末端有足够的缓冲空间容纳 B。 编写一个方法,将 B 合并入 A 并排序。
初始化 A 和 B 的元素数量分别为 m 和 n。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sorted-merge-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
class MergeSortedArray {
companion object {
/**
* a[0]<b[0]
*/
fun test1() {
val a = intArrayOf(1, 2, 3, 0, 0, 0)
val b = intArrayOf(2, 5, 6)
merge1(a, 3, b, 3)
a.forEach { print(it) }
}
/**
* a[0]>b[0]
*/
fun test2() {
val a = intArrayOf(2, 3, 4, 0, 0, 0)
val b = intArrayOf(1, 3, 5)
merge1(a, 3, b, 3)
a.forEach { print(it) }
}
/**
* b数组开始位置有多个小于a[0]
*/
fun test3() {
val a = intArrayOf(5, 6, 7, 0, 0, 0)
val b = intArrayOf(1, 3, 4)
merge1(a, 3, b, 3)
a.forEach { print(it) }
}
/**
* 方法1:借助一个m+n长度的数组c,两个指针分别指向两个数组的起始位置,每次将较小的数填充进c数组中,
* 然后将剩余数据的后面的数据全部拷贝进去,最后再将c数组数据复制给A数组
*/
fun merge(A: IntArray, m: Int, B: IntArray, n: Int) {
val c = IntArray(m + n)
var i = 0
var j = 0
var index = 0
while (i < m && j < n) {
if (A[i] <= B[j]) {
c[index] = A[i]
++i
} else {
c[index] = B[j]
++j
}
++index
}
//将剩余的部分依次放入数组中
if (i < m) {
System.arraycopy(A, i, c, index, m - i)
}
if (j < n) {
System.arraycopy(B, j, c, index, n - j)
}
c.forEachIndexed { index, i ->
A[index] = i;
}
}
/**
* 方法2:同方法1的思路差不多,不过用到三个指针,cur指针指向A数组的m+n-1位置,ida指针指向A数组有效数据的末尾,idb指向B数组
* 有效数据的末尾,一次比较ida和idb指向的数据,将大的那个数据赋值给cur指针指向的位置,然后cur--,较大的那个指针--
*/
fun merge1(A: IntArray, m: Int, B: IntArray, n: Int) {
var cur = m + n - 1
var ida = m - 1
var idb = n - 1
while (idb >= 0 && ida >= 0) {
A[cur--] = if (A[ida] >= B[idb]) A[ida--] else B[idb--]
}
while (idb >= 0) {
A[cur--] = B[idb--]
}
}
}
}
| 0 | C | 19 | 39 | 3c22a4fcdfe8b47f9f64b939c8b27742c4e30b79 | 3,044 | LeetCodeLearning | MIT License |
src/aoc22/Day02.kt | mihassan | 575,356,150 | false | {"Kotlin": 123343} | @file:Suppress("PackageDirectoryMismatch")
package aoc22.day02
import aoc22.day02.GameResult.DRAW
import aoc22.day02.GameResult.LOSS
import aoc22.day02.GameResult.WIN
import aoc22.day02.Hand.PAPER
import aoc22.day02.Hand.ROCK
import aoc22.day02.Hand.SCISSOR
import lib.Solution
import lib.Solution.Part
import lib.Solution.Part.PART1
import lib.Solution.Part.PART2
enum class Hand(val score: Int) {
ROCK(1), PAPER(2), SCISSOR(3);
fun beats(): Hand = when (this) {
ROCK -> SCISSOR
PAPER -> ROCK
SCISSOR -> PAPER
}
fun beatenBy(): Hand = when (this) {
ROCK -> PAPER
PAPER -> SCISSOR
SCISSOR -> ROCK
}
companion object {
fun of(hand: String): Hand = when (hand) {
"A" -> ROCK
"B" -> PAPER
"C" -> SCISSOR
else -> error("Bad input for a hand: $hand")
}
}
}
enum class Strategy {
X, Y, Z;
fun handToPlay(part: Part, opponent: Hand): Hand = when (part) {
PART1 -> handToPlayForPart1()
PART2 -> handToPlayForPart2(opponent)
}
private fun handToPlayForPart1(): Hand = when (this) {
X -> ROCK
Y -> PAPER
Z -> SCISSOR
}
private fun handToPlayForPart2(opponent: Hand): Hand = when (this) {
X -> opponent.beats() // Loss
Y -> opponent // Draw
Z -> opponent.beatenBy() // Win
}
companion object {
fun of(strategy: String): Strategy = when (strategy) {
"X" -> X
"Y" -> Y
"Z" -> Z
else -> error("Bad input for a strategy: $strategy")
}
}
}
enum class GameResult(val score: Int) {
WIN(6), LOSS(0), DRAW(3)
}
fun Hand.play(other: Hand): GameResult = when (other) {
beats() -> WIN
beatenBy() -> LOSS
else -> DRAW
}
data class Game(val opponent: Hand, val strategy: Strategy) {
fun totalScore(part: Part): Int {
val myHand = strategy.handToPlay(part, opponent)
return myHand.score + myHand.play(opponent).score
}
companion object {
fun of(game: String): Game {
val (hand, strategy) = game.split(" ")
return Game(Hand.of(hand), Strategy.of(strategy))
}
}
}
private val solution = object : Solution<List<Game>, Int>(2022, "Day02") {
override fun parse(input: String): List<Game> =
input.lines().filter { it.isNotBlank() }.map { Game.of(it) }
override fun format(output: Int): String = output.toString()
override fun solve(part: Part, input: List<Game>): Int = input.sumOf { game ->
game.totalScore(part)
}
}
fun main() = solution.run()
| 0 | Kotlin | 0 | 0 | 698316da8c38311366ee6990dd5b3e68b486b62d | 2,447 | aoc-kotlin | Apache License 2.0 |
day-18/src/main/kotlin/Snailfish.kt | diogomr | 433,940,168 | false | {"Kotlin": 92651} | import kotlin.system.measureTimeMillis
fun main() {
val partOneMillis = measureTimeMillis {
println("Part One Solution: ${partOne()}")
}
println("Part One Solved in: $partOneMillis ms")
val partTwoMillis = measureTimeMillis {
println("Part Two Solution: ${partTwo()}")
}
println("Part Two Solved in: $partTwoMillis ms")
}
private fun partOne(): Int {
var result: SnailfishNumber? = null
readInputLines().forEach {
val number = SnailfishNumber()
readNumber(it.substring(1), number)
result = if (result == null) number else sum(result!!, number)
}
return result!!.getMagnitude()
}
private fun partTwo(): Int {
var magnitude = Int.MIN_VALUE
val lines = readInputLines()
for (i in lines.indices) {
for (j in lines.indices) {
if (i == j) {
continue
}
val first = SnailfishNumber()
readNumber(lines[i].substring(1), first)
val second = SnailfishNumber()
readNumber(lines[j].substring(1), second)
val result = sum(first, second)
if (result.getMagnitude() > magnitude) {
magnitude = result.getMagnitude()
}
}
}
return magnitude
}
data class SnailfishNumber(
var leftValue: Int? = null,
var rightValue: Int? = null,
var leftPair: SnailfishNumber? = null,
var rightPair: SnailfishNumber? = null,
) {
override fun toString(): String {
val left = if (leftValue != null) leftValue.toString() else leftPair.toString()
val right = if (rightValue != null) rightValue.toString() else rightPair.toString()
return "[$left,$right]"
}
fun getMagnitude(): Int {
val left = if (leftValue != null) leftValue!! else leftPair!!.getMagnitude()
val right = if (rightValue != null) rightValue!! else rightPair!!.getMagnitude()
return (left * 3) + (right * 2)
}
}
private fun sum(left: SnailfishNumber, right: SnailfishNumber): SnailfishNumber {
val sum = SnailfishNumber(null, null, left, right)
reduce(sum)
return sum
}
private fun reduce(number: SnailfishNumber) {
if (explode(number, number, 0)) {
reduce(number)
} else if (split(number, number)) {
reduce(number)
}
}
private fun split(number: SnailfishNumber, root: SnailfishNumber): Boolean {
if (number.leftPair != null && split(number.leftPair!!, root)) return true
if (number.leftValue != null && number.leftValue!! >= 10) {
number.leftPair = splitInteger(number.leftValue!!)
number.leftValue = null
return true
}
if (number.rightPair != null && split(number.rightPair!!, root)) return true
if (number.rightValue != null && number.rightValue!! >= 10) {
number.rightPair = splitInteger(number.rightValue!!)
number.rightValue = null
return true
}
return false
}
private fun splitInteger(number: Int): SnailfishNumber {
val result = number / 2
return if (number % 2 == 0) SnailfishNumber(result, result) else SnailfishNumber(result, result + 1)
}
private fun explode(root: SnailfishNumber, number: SnailfishNumber, level: Int): Boolean {
if (level > 3 && number.leftPair == null && number.rightPair == null) {
explodeNumber(root, number)
return true
} else {
if (number.leftValue != null && number.rightValue != null) return false
if (number.leftValue == null && explode(root, number.leftPair!!, level + 1)) return true
if (number.rightValue == null && explode(root, number.rightPair!!, level + 1)) return true
return false
}
}
private fun explodeNumber(root: SnailfishNumber, number: SnailfishNumber) {
val parent = findParent(root, number)
if (parent!!.leftPair !== number) { // Pair is rightPair of parent
parent!!.rightPair = null
parent.rightValue = 0
if (parent.leftValue != null) {
parent.leftValue = parent.leftValue!! + number.leftValue!!
} else {
val rightmostLeft = findRightmostLeft(parent)
rightmostLeft.rightValue = rightmostLeft.rightValue!! + number.leftValue!!
}
var grandparent = findParent(root, parent)
var parentCopy = parent
while (true) {
// Find leftmost right
if (grandparent?.rightPair === parentCopy) {
parentCopy = grandparent
grandparent = findParent(root, grandparent!!)
if (grandparent == null) return else continue
} else {
if (grandparent!!.rightValue != null) {
grandparent.rightValue = grandparent.rightValue!! + number.rightValue!!
} else {
val leftmostRight = findLeftmostRight(grandparent)
leftmostRight.leftValue = leftmostRight.leftValue!! + number.rightValue!!
}
return
}
}
} else { // Pair is leftPair of parent
parent!!.leftPair = null
parent.leftValue = 0
if (parent.rightValue != null) {
parent.rightValue = parent.rightValue!! + number.rightValue!!
} else {
val leftmostRight = findLeftmostRight(parent)
leftmostRight.leftValue = leftmostRight.leftValue!! + number.rightValue!!
}
var grandparent = findParent(root, parent)
var parentCopy = parent
while (true) {
// Find rightmost left
if (grandparent?.leftPair === parentCopy) {
parentCopy = grandparent
grandparent = findParent(root, grandparent!!)
if (grandparent == null) return else continue
} else {
if (grandparent!!.leftValue != null) {
grandparent.leftValue = grandparent.leftValue!! + number.leftValue!!
} else {
val rightmostLeft = findRightmostLeft(grandparent)
rightmostLeft.rightValue = rightmostLeft.rightValue!! + number.leftValue!!
}
return
}
}
}
}
private fun findRightmostLeft(number: SnailfishNumber): SnailfishNumber {
if (number.leftValue != null) return number
return findDeepRight(number.leftPair!!)
}
private fun findLeftmostRight(number: SnailfishNumber): SnailfishNumber {
if (number.rightValue != null) return number
return findDeepLeft(number.rightPair!!)
}
private fun findDeepLeft(number: SnailfishNumber): SnailfishNumber {
if (number.leftValue != null) return number
return findDeepLeft(number.leftPair!!)
}
private fun findDeepRight(number: SnailfishNumber): SnailfishNumber {
if (number.rightValue != null) return number
return findDeepRight(number.rightPair!!)
}
private fun findParent(root: SnailfishNumber, child: SnailfishNumber): SnailfishNumber? {
if (root === child) return null
if (root.leftValue != null && root.rightValue != null) return null
if (root.leftPair === child) return root
if (root.rightPair === child) return root
root.leftPair?.let {
findParent(it, child)?.let { p -> return p }
}
root.rightPair?.let {
findParent(it, child)?.let { p -> return p }
}
return null
}
const val OPEN = '['
const val CLOSE = ']'
const val COMMA = ','
private fun readNumber(input: String, number: SnailfishNumber): String {
var inputCopy = input
while (true) {
val i = inputCopy[0]
if (i == COMMA) {
inputCopy = inputCopy.substring(1)
continue
} else if (i == OPEN) {
val child = SnailfishNumber(null, null, null, null)
inputCopy = readNumber(inputCopy.substring(1), child)
if (number.leftPair == null && number.leftValue == null) {
number.leftPair = child
} else if (number.rightPair == null && number.rightValue == null) {
number.rightPair = child
} else {
throw RuntimeException("Impossible state")
}
} else if (i == CLOSE) {
return inputCopy.substring(1)
} else {
if (number.leftPair == null && number.leftValue == null) {
number.leftValue = i.digitToInt()
} else {
number.rightValue = i.digitToInt()
}
inputCopy = inputCopy.substring(1)
}
}
}
private fun readInputLines(): List<String> {
return {}::class.java.classLoader.getResource("input.txt")!!
.readText()
.split("\n")
.filter { it.isNotBlank() }
}
| 0 | Kotlin | 0 | 0 | 17af21b269739e04480cc2595f706254bc455008 | 8,695 | aoc-2021 | MIT License |
src/main/kotlin/Day02.kt | jcornaz | 573,137,552 | false | {"Kotlin": 76776} | object Day02 {
private val plays = Play.values().asSequence()
private val results = Result.values().asSequence()
enum class Play(val symbol: String, val score: Int) {
Rock("A", 1),
Paper("B", 2),
Scissors("C", 3),
}
enum class Result(val symbol: String, val score: Int) {
Lose("X", 0),
Draw("Y", 3),
Win("Z", 6),
}
fun part1(input: String): Int =
input.lines().sumOf(::part1ScoreOf)
fun part2(input: String): Int =
input.lineSequence().sumOf(::part2ScoreOf)
private fun parsePlay(input: String): Play = plays.first { it.symbol == input }
private fun parseResult(input: String): Result = results.first { it.symbol == input }
private fun part1ScoreOf(line: String): Int {
val (opponent, me) = line.split(' ')
return score(
parsePlay(opponent),
when (me) {
"X" -> Play.Rock
"Y" -> Play.Paper
else -> Play.Scissors
}
)
}
private fun part2ScoreOf(line: String): Int {
val (opponent, wanted) = line.split(' ')
.let { (op, wanted) -> parsePlay(op) to parseResult(wanted) }
val me = whatToPlay(opponent, wanted)
return wanted.score + me.score
}
private fun score(opponent: Play, me: Play): Int =
resultOf(opponent, me).score + me.score
private fun resultOf(opponent: Play, me: Play): Result =
results.first { whatToPlay(opponent, it) == me }
fun whatToPlay(opponent: Play, wantedResult: Result): Play = when (wantedResult) {
Result.Draw -> opponent
Result.Win -> when (opponent) {
Play.Rock -> Play.Paper
Play.Paper -> Play.Scissors
Play.Scissors -> Play.Rock
}
Result.Lose -> plays.first { whatToPlay(it, Result.Win) == opponent }
}
}
| 1 | Kotlin | 0 | 0 | 979c00c4a51567b341d6936761bd43c39d314510 | 1,903 | aoc-kotlin-2022 | The Unlicense |
src/ad/kata/aoc2021/day11/Octopuses.kt | andrej-dyck | 433,401,789 | false | {"Kotlin": 161613} | package ad.kata.aoc2021.day11
import ad.kata.aoc2021.PuzzleInput
import ad.kata.aoc2021.types.*
class Octopuses(val energyLevels: Matrix<EnergyLevel>) {
fun countFlashes() =
energyLevels.flatten().count(EnergyLevel::hasFlashed)
fun timeProjection() =
generateSequence(this) { it.increaseEnergyLevels() }.drop(1)
private fun increaseEnergyLevels() = Octopuses(
energyLevels.map { e -> e.raiseBy(1) }.propagateFlashes()
)
private tailrec fun Matrix<EnergyLevel>.propagateFlashes(
flashed: Set<Coordinate> = emptySet()
): Matrix<EnergyLevel> {
val newFlashes = filterIndexed { c, e -> e.hasFlashed() && c !in flashed }.keys
return if (newFlashes.none()) this
else mapIndexed { c, e -> e.raiseByIf(!e.hasFlashed()) { adjacentFlashes(c, newFlashes) } }
.propagateFlashes(flashed + newFlashes)
}
private fun EnergyLevel.raiseByIf(condition: Boolean, value: () -> Int) =
if (condition) raiseBy(value()) else this
private fun Matrix<EnergyLevel>.adjacentFlashes(c: Coordinate, newFlashed: Set<Coordinate>) =
adjacentItemsOf(c)
.filterValues(EnergyLevel::hasFlashed).keys
.intersect(newFlashed).size
}
fun Octopuses.totalFlashesAfter(steps: Int) =
timeProjection().take(steps).sumOf { it.countFlashes() }
fun Octopuses.firstFlashSync() =
timeProjection().indexOfFirst(Octopuses::allFlash) + 1
fun Octopuses.allFlash() = energyLevels.all { it.hasFlashed() }
fun octopusesFromInput(filename: String) = Octopuses(
PuzzleInput(filename).lines()
.map { it.toCharArray().map(Char::digitToInt) }
.map { it.map { e -> EnergyLevel(e) } }
.toMatrix()
)
| 0 | Kotlin | 0 | 0 | 28d374fee4178e5944cb51114c1804d0c55d1052 | 1,729 | advent-of-code-2021 | MIT License |
src/Day05.kt | eo | 574,058,285 | false | {"Kotlin": 45178} | // https://adventofcode.com/2022/day/5
fun main() {
fun parseInput(input: String): Pair<CrateStacks, List<Move>> {
val (drawingStr, movesStr) = input.split("\n\n")
val crateStacks = CrateStacks.fromDrawing(drawingStr)
val moves = movesStr.lines().map(Move::fromString)
return crateStacks to moves
}
fun part1(input: String): String {
val (crateStacks, moves) = parseInput(input)
moves.forEach { crateStacks.performSingleCrateMove(it) }
return crateStacks.topCrates()
}
fun part2(input: String): String {
val (crateStacks, moves) = parseInput(input)
moves.forEach { crateStacks.performMultiCratesMove(it) }
return crateStacks.topCrates()
}
val input = readText("Input05")
println("Part 1: " + part1(input))
println("Part 2: " + part2(input))
}
private class Move(val quantity: Int, val from: Int, val to: Int) {
companion object {
private val REGEX = "move (\\d+) from (\\d+) to (\\d+)".toRegex()
fun fromString(str: String): Move = REGEX.matchEntire(str)?.let {
val (quantity, from, to) = it.destructured
Move(quantity.toInt(), from.toInt(), to.toInt())
} ?: error("Invalid move string: $str")
}
}
private class CrateStacks
private constructor(private val stackIds: List<Int>, private val stacks: Map<Int, ArrayDeque<Char>>) {
fun performSingleCrateMove(move: Move) {
repeat(move.quantity) {
stacks[move.from]?.removeLast()?.let { crate ->
stacks[move.to]?.add(crate)
}
}
}
fun performMultiCratesMove(move: Move) {
stacks[move.to]?.addAll(
Array(move.quantity) {
stacks[move.from]?.removeLast()
}.filterNotNull().reversed()
)
}
fun topCrates() = buildString {
stackIds.forEach { stackId ->
stacks[stackId]?.let { stack ->
if (stack.isEmpty()) append(" ") else append(stack.last())
}
}
}
companion object {
fun fromDrawing(drawingStr: String): CrateStacks {
val stackLinesReversed = drawingStr.lines().reversed()
val stackIds = "\\d+".toRegex().findAll(stackLinesReversed.first())
.map { it.value.toInt() }
.toList()
val stacks = stackIds.associateWith { ArrayDeque<Char>() }
stackLinesReversed.drop(1)
.forEach { line ->
line.chunked(4).forEachIndexed { stackIndex, crate ->
if (crate.startsWith('[')) {
stacks[stackIds[stackIndex]]?.add(crate[1])
}
}
}
return CrateStacks(stackIds, stacks)
}
}
}
| 0 | Kotlin | 0 | 0 | 8661e4c380b45c19e6ecd590d657c9c396f72a05 | 2,885 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day02.kt | remidu | 573,452,090 | false | {"Kotlin": 22113} | import Result.*
import Shape.*
enum class Shape(val code1: String, val code2: String, val points: Int) {
ROCK("A", "X", 1),
PAPER("B", "Y", 2),
SCISSORS("C", "Z", 3);
companion object {
infix fun of(code: String): Shape {
return values().first { it.code1 == code || it.code2 == code }
}
}
}
enum class Result(val code: String, val points: Int) {
WIN("Z", 6),
DRAW("Y", 3),
FAIL("X", 0);
companion object {
infix fun of(code: String): Result {
return values().first { it.code == code }
}
}
}
fun main() {
fun play(yourShape: Shape, myShape: Shape): Int {
if (yourShape == ROCK && myShape == PAPER) return 6
if (yourShape == ROCK && myShape == SCISSORS) return 0
if (yourShape == PAPER && myShape == SCISSORS) return 6
if (yourShape == PAPER && myShape == ROCK) return 0
if (yourShape == SCISSORS && myShape == ROCK) return 6
if (yourShape == SCISSORS && myShape == PAPER) return 0
return 3 // draw
}
fun part1(input: List<String>): Int {
var total = 0
for (line in input) {
val codes = line.split(" ")
val yourShape = Shape.of(codes[0])
val myShape = Shape.of(codes[1])
total += play(yourShape, myShape) + myShape.points
}
return total
}
fun myShape(yourShape: Shape, result: Result): Shape {
if (yourShape == ROCK && result == WIN) return PAPER
if (yourShape == PAPER && result == WIN) return SCISSORS
if (yourShape == SCISSORS && result == WIN) return ROCK
if (yourShape == ROCK && result == FAIL) return SCISSORS
if (yourShape == PAPER && result == FAIL) return ROCK
if (yourShape == SCISSORS && result == FAIL) return PAPER
return yourShape // draw
}
fun part2(input: List<String>): Int {
var total = 0
for (line in input) {
val codes = line.split(" ")
val yourShape = Shape.of(codes[0])
val result = Result.of(codes[1])
total += myShape(yourShape, result).points + result.points
}
return total
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ecda4e162ab8f1d46be1ce4b1b9a75bb901bc106 | 2,451 | advent-of-code-2022 | Apache License 2.0 |
src/Day09.kt | ekgame | 573,100,811 | false | {"Kotlin": 20661} | import kotlin.math.abs
fun main() {
data class Point(val x: Int, val y: Int) {
fun isTouching(other: Point) = other.x in (x-1)..(x+1) && other.y in (y-1)..(y+1)
fun add(other: Point) = Point(other.x + x, other.y + y)
}
data class MoveInstruction(val vector: Point, val magnitude: Int)
class ChainSimulation(pieces: Int) {
val pieces = Array(pieces) { Point(0, 0) }
val head: Point
get() = pieces.first()
val tail: Point
get() = pieces.last()
fun moveHead(vector: Point) {
pieces[0] = head.add(vector)
moveChain(1)
}
fun moveChain(index: Int) {
if (index >= pieces.size) {
return
}
val head = pieces[index - 1]
val tail = pieces[index]
if (head.isTouching(tail)) {
return
}
pieces[index] = when {
head.x == tail.x -> Point(tail.x, (head.y + tail.y)/2)
head.y == tail.y -> Point((head.x + tail.x)/2, tail.y)
abs(head.x - tail.x) == abs(head.y - tail.y) -> Point((head.x + tail.x)/2, (head.y + tail.y)/2)
abs(head.x - tail.x) > 1 -> Point((head.x + tail.x)/2, head.y)
abs(head.y - tail.y) > 1 -> Point(head.x, (head.y + tail.y)/2)
else -> error("Invalid state")
}
moveChain(index + 1)
}
fun dump() {
val x1 = -11//pieces.minOf { it.x }
val y1 = -5//pieces.minOf { it.y }
val x2 = 15//pieces.maxOf { it.x }
val y2 = 15//pieces.maxOf { it.y }
(y1..y2).reversed().forEach { y ->
(x1..x2).forEach { x ->
val index = pieces.indexOfFirst { it.x == x && it.y == y } + 1
print(when (index) {
0 -> "."
1 -> "H"
else -> index - 1
})
}
print("\n")
}
println("--------------")
}
}
fun parseInstructions(input: List<String>) = input.map {
val (direction, magnitude) = it.split(" ")
when (direction) {
"L" -> MoveInstruction(Point(-1, 0), magnitude.toInt())
"R" -> MoveInstruction(Point(1, 0), magnitude.toInt())
"U" -> MoveInstruction(Point(0, 1), magnitude.toInt())
"D" -> MoveInstruction(Point(0, -1), magnitude.toInt())
else -> error("invalid direction")
}
}
fun solve(input: List<String>, parts: Int): Int {
val simulation = ChainSimulation(parts)
val visited = mutableSetOf(simulation.tail)
parseInstructions(input).forEach { move ->
repeat(move.magnitude) {
simulation.moveHead(move.vector)
visited.add(simulation.tail)
}
// simulation.dump()
}
return visited.size
}
fun part1(input: List<String>) = solve(input, 2)
fun part2(input: List<String>) = solve(input, 10)
val testInput = readInput("09.test")
val testInput2 = readInput("09.2.test")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
check(part2(testInput2) == 36)
val input = readInput("09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | 0c2a68cedfa5a0579292248aba8c73ad779430cd | 3,417 | advent-of-code-2022 | Apache License 2.0 |
kotlin/strings/SuffixArray.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package strings
import java.util.stream.IntStream
// https://en.wikipedia.org/wiki/Suffix_array
object SuffixArray {
// build suffix array in O(n*log(n))
fun suffixArray(S: CharSequence): IntArray {
val n: Int = S.length()
// Stable sort of characters.
// Same characters are sorted by their position in descending order.
// E.g. last character which represents suffix of length 1 should be ordered first among same characters.
val sa: IntArray = IntStream.range(0, n)
.mapToObj { i -> n - 1 - i }
.sorted(Comparator.comparingInt(S::charAt))
.mapToInt(Integer::intValue)
.toArray()
val classes: IntArray = S.chars().toArray()
// sa[i] - suffix on i'th position after sorting by first len characters
// classes[i] - equivalence class of the i'th suffix after sorting by first len characters
var len = 1
while (len < n) {
// Calculate classes for suffixes of length len * 2
val c: IntArray = classes.clone()
for (i in 0 until n) {
// Condition sa[i - 1] + len < n emulates 0-symbol at the end of the string.
// A separate class is created for each suffix followed by emulated 0-symbol.
classes[sa[i]] =
if (i > 0 && c[sa[i - 1]] == c[sa[i]] && sa[i - 1] + len < n && c[sa[i - 1] + len / 2] == c[sa[i] + len / 2]) classes[sa[i - 1]] else i
}
// Suffixes are already sorted by first len characters
// Now sort suffixes by first len * 2 characters
val cnt: IntArray = IntStream.range(0, n).toArray()
val s: IntArray = sa.clone()
for (i in 0 until n) {
// s[i] - order of suffixes sorted by first len characters
// (s[i] - len) - order of suffixes sorted only by second len characters
val s1 = s[i] - len
// sort only suffixes of length > len, others are already sorted
if (s1 >= 0) sa[cnt[classes[s1]]++] = s1
}
len *= 2
}
return sa
}
// sort rotations of a string in O(n*log(n))
fun rotationArray(S: CharSequence): IntArray {
val n: Int = S.length()
val sa: IntArray = IntStream.range(0, n)
.boxed()
.sorted(Comparator.comparingInt(S::charAt))
.mapToInt(Integer::intValue)
.toArray()
val classes: IntArray = S.chars().toArray()
var len = 1
while (len < n) {
val c: IntArray = classes.clone()
for (i in 0 until n) classes[sa[i]] =
if (i > 0 && c[sa[i - 1]] == c[sa[i]] && c[(sa[i - 1] + len / 2) % n] == c[(sa[i] + len / 2) % n]) classes[sa[i - 1]] else i
val cnt: IntArray = IntStream.range(0, n).toArray()
val s: IntArray = sa.clone()
for (i in 0 until n) {
val s1 = (s[i] - len + n) % n
sa[cnt[classes[s1]]++] = s1
}
len *= 2
}
return sa
}
// longest common prefixes array in O(n)
fun lcp(sa: IntArray, s: CharSequence): IntArray {
val n = sa.size
val rank = IntArray(n)
for (i in 0 until n) rank[sa[i]] = i
val lcp = IntArray(n - 1)
var i = 0
var h = 0
while (i < n) {
if (rank[i] < n - 1) {
val j = sa[rank[i] + 1]
while (Math.max(i, j) + h < s.length() && s.charAt(i + h) === s.charAt(j + h)) {
++h
}
lcp[rank[i]] = h
if (h > 0) --h
}
i++
}
return lcp
}
// Usage example
fun main(args: Array<String?>?) {
val s1 = "abcab"
val sa1 = suffixArray(s1)
// print suffixes in lexicographic order
for (p in sa1) System.out.println(s1.substring(p))
System.out.println("lcp = " + Arrays.toString(lcp(sa1, s1)))
// random test
val rnd = Random(1)
for (step in 0..99999) {
val n: Int = rnd.nextInt(100) + 1
val s: StringBuilder = rnd.ints(n, 0, 10)
.collect({ StringBuilder() }, { sb, i -> sb.append(('a' + i)) }, StringBuilder::append)
val sa = suffixArray(s)
val ra = rotationArray(s.toString() + '\u0000')
val lcp = lcp(sa, s)
var i = 0
while (i + 1 < n) {
val a: String = s.substring(sa[i])
val b: String = s.substring(sa[i + 1])
if (a.compareTo(b) >= 0 || !a.substring(0, lcp[i]).equals(b.substring(0, lcp[i]))
|| "$a ".charAt(lcp[i]) === (b.toString() + " ").charAt(lcp.get(i)) || sa[i] != ra[i + 1]
) throw RuntimeException()
i++
}
}
System.out.println("Test passed")
}
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 4,985 | codelibrary | The Unlicense |
src/year2022/day20/Day20.kt | kingdongus | 573,014,376 | false | {"Kotlin": 100767} | package year2022.day20
import readInputFileByYearAndDay
import readTestFileByYearAndDay
fun main() {
data class Node(var value: Long, var previous: Node? = null, var next: Node? = null) {
override fun toString(): String = "$value, previous:${previous?.value}, next:${next?.value}"
}
fun mix(nodes: List<Node>) {
nodes.forEach {
var delta = it.value % (nodes.size - 1)
if (delta != 0L) {
it.next!!.previous = it.previous
it.previous!!.next = it.next
var newPreviousNode = it.previous
while (delta > 0) {
newPreviousNode = newPreviousNode?.next
delta--
}
while (delta < 0) {
newPreviousNode = newPreviousNode?.previous
delta++
}
it.previous = newPreviousNode
it.next = newPreviousNode?.next
newPreviousNode?.next = it
it.next?.previous = it
}
}
}
fun initializeDoubleLinkedList(input: List<String>): List<Node> {
val nodes = input.map { it.toLong() }.toLongArray().map { Node(it) }
for (i in 0 until nodes.lastIndex) nodes[i].next = nodes[i + 1]
for (i in 1..nodes.lastIndex) nodes[i].previous = nodes[i - 1]
nodes.last().next = nodes.first()
nodes.first().previous = nodes.last()
return nodes
}
fun calculateCoordinates(nodes: List<Node>): Long {
val nullNode = nodes.first { it.value == 0L }
return listOf(1000L, 2000L, 3000L).map { it % nodes.size }.sumOf {
var node = nullNode
repeat(it.toInt()) { node = node.next!! }
node.value
}
}
fun part1(input: List<String>): Long = initializeDoubleLinkedList(input).let {
mix(it)
return calculateCoordinates(it)
}
fun part2(input: List<String>): Long = initializeDoubleLinkedList(input)
.onEach { node -> node.value *= 811589153 }
.let {
repeat(10) { _ -> mix(it) }
return calculateCoordinates(it)
}
val testInput = readTestFileByYearAndDay(2022, 20)
check(part1(testInput) == 3L)
check(part2(testInput) == 1623178306L)
val input = readInputFileByYearAndDay(2022, 20)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | aa8da2591310beb4a0d2eef81ad2417ff0341384 | 2,424 | advent-of-code-kotlin | Apache License 2.0 |
src/UselessStuff.kt | isaiahhyun | 574,590,804 | false | {"Kotlin": 11744} | fun main() {
val input = readInput("sentences")
println("Pairs: ${findThingy(input)}")
}
fun sumAllNums(input: List<String>): Int {
// var total = 0
// for(num in input){
// total+= num.toInt()
// }
// return total
return input.map { it.toInt() }.sum()
}
fun findMin(input: List<String>): Int {
//for(inti = 0; i < input.size; i++) java
// for(i in 0..input.size-1) kotlin
// for(i in 0 until input.size) kotlin
return input.map { it.toInt() }.min()
}
fun findTwoSmallest(input: List<String>): Int {
val sorted = input.map { it.toInt() }.sorted()
sorted.take(2)
return input.map { it.toInt() }.sorted().take(2).sum()
//return sorted[0] + sorted[1]
}
fun countWords(input: List<String>): Int {
var wordCount = 0
for (line in input) {
wordCount += line.split(" ").size
}
return wordCount
}
fun countHWords(input: List<String>): Int {
var count = 0
return count
}
fun findBiggestSum(input: List<String>): Int {
var total = 0
var biggest = 0
for (i in input.indices) {
if (input[i] == "") {
if (total > biggest && total < 68996) {
biggest = total
}
total = 0
} else {
total += input[i].toInt()
}
}
return biggest
}
fun countPriorities(input: List<String>): Int {
var countScore = 0
var hasBeenFound = false
var storedValue = ""
for (i in input.indices) {
var b = input[i].toCharArray()
var h = (input[i].length) / 2
var secondHalf = input[i].substring(h)
//println(secondHalf)
for (x in 0 until h) {
if (b[x].toString() != storedValue) {
if (secondHalf.contains(b[x].toString())) {
storedValue = b[x].toString()
if (b[x].toString().lowercase() == b[x].toString()) {
var y = (b[x].code - 96)
countScore += y
} else {
var y = (b[x].code - 38)
countScore += y
}
}
}
}
storedValue = ""
}
return countScore
}
fun findBadge(input: List<String>): Int {
var count = 0
var countScore = 0
var string1 = ""
var string2 = ""
var string3 = ""
var storedValue = ""
for (i in input.indices) {
if (count == 0) {
string1 = input[i]
count++
} else if (count == 1) {
string2 = input[i]
count++
} else if (count == 2) {
string3 = input[i]
count++
var x = string2
var y = string1.toCharArray()
var z = string3
var h = string1.length
for (m in 0 until h) {
if (y[m].toString() != storedValue)
if ((x.contains(y[m].toString())) && (z.contains(y[m].toString()))) {
storedValue = y[m].toString()
if (y[m].toString().lowercase() == y[m].toString()) {
var j = (y[m].code - 96)
countScore += j
} else {
var j = (y[m].code - 38)
countScore += j
}
}
}
storedValue = ""
} else if (count == 3) {
string1 = input[i]
count = 1
}
}
return countScore
}
fun findPairs(input: List<String>): Int {
var countPairs = 0
for (i in input.indices) {
var first = input[i].substring(0, input[i].indexOf(","))
var second = input[i].substring(input[i].indexOf(",") + 1)
var startFirst = first.substring(0, first.indexOf("-"))
var startSecond = second.substring(0, second.indexOf("-"))
var endFirst = first.substring(first.indexOf("-") + 1)
var endSecond = second.substring(second.indexOf("-") + 1)
if (startFirst == startSecond && endSecond == endFirst) {
countPairs++
} else if (startFirst == startSecond || endSecond == endFirst || endFirst == startSecond || startFirst == endSecond) {
countPairs++
} else if (startSecond.toInt() > startFirst.toInt() && startSecond.toInt() < endFirst.toInt()) {
countPairs++
} else if (startFirst.toInt() > startSecond.toInt() && startFirst.toInt() < endSecond.toInt()) {
countPairs++
} else if (endSecond.toInt() > startFirst.toInt() && endSecond.toInt() < endFirst.toInt()) {
countPairs++
} else if (endFirst.toInt() > startSecond.toInt() && endFirst.toInt() < endSecond.toInt()) {
countPairs++
} else if ((endFirst.toInt() - startFirst.toInt()) > (endSecond.toInt() - startSecond.toInt())) {
if ((endSecond.toInt() <= endFirst.toInt()) && startSecond.toInt() >= startFirst.toInt()) {
countPairs++
}
} else if ((endFirst.toInt() - startFirst.toInt()) < (endSecond.toInt() - startSecond.toInt())) {
if ((endSecond.toInt() >= endFirst.toInt()) && startSecond.toInt() <= startFirst.toInt()) {
countPairs++
}
}
}
return countPairs
}
fun secretMessage(input: List<String>): String {
var first = mutableListOf("F", "T", "C", "L", "R", "P", "G", "Q")
var two = mutableListOf("N", "Q", "H", "W", "R", "F", "S", "J")
var three = mutableListOf("F", "B", "H", "W", "P", "M", "Q")
var four = mutableListOf("V", "S", "T", "D", "F")
var five = mutableListOf("Q", "L", "D", "W", "V", "F", "Z")
var six = mutableListOf("Z", "C", "L", "S")
var seven = mutableListOf("Z", "B", "M", "V", "D", "F")
var eight = mutableListOf("T", "J", "B")
var nine = mutableListOf("Q", "N", "B", "G", "L", "S", "P", "H")
for (i in input.indices) {
var x = input[i].substring(5)
var y = input[i].substring(12)
var z = input[i].substring(0)
if (x.length == 14) {
x = x.substring(0, 2)
y = y.substring(1, 2)
z = input[i].substring(18)
} else {
x = x.substring(0, 1)
y = y.substring(0, 1)
z = input[i].substring(17)
}
//println(y)
var hold = mutableListOf("")
for (h in 0 until x.toInt()) {
if (y.toInt() == 1) {
hold += first[first.size - 1]
first.removeAt(first.size - 1)
}
if (y.toInt() == 2) {
hold += two[two.size - 1]
two.removeAt(two.size - 1)
}
if (y.toInt() == 3) {
hold += three[three.size - 1]
three.removeAt(three.size - 1)
}
if (y.toInt() == 4) {
hold += four[four.size - 1]
four.removeAt(four.size - 1)
}
if (y.toInt() == 5) {
hold += five[five.size - 1]
five.removeAt(five.size - 1)
}
if (y.toInt() == 6) {
hold += six[six.size - 1]
six.removeAt(six.size - 1)
}
if (y.toInt() == 7) {
hold += seven[seven.size - 1]
seven.removeAt(seven.size - 1)
}
if (y.toInt() == 8) {
hold += eight[eight.size - 1]
eight.removeAt(eight.size - 1)
}
if (y.toInt() == 9) {
hold += nine[nine.size - 1]
nine.removeAt(nine.size - 1)
}
}
for (j in 0 until x.toInt()) {
if (z.toInt() == 1) {
first += hold[hold.size - 1]
hold.removeAt(hold.size - 1)
}
if (z.toInt() == 2) {
two += hold[hold.size - 1]
hold.removeAt(hold.size - 1)
}
if (z.toInt() == 3) {
three += hold[hold.size - 1]
hold.removeAt(hold.size - 1)
}
if (z.toInt() == 4) {
four += hold[hold.size - 1]
hold.removeAt(hold.size - 1)
}
if (z.toInt() == 5) {
five += hold[hold.size - 1]
hold.removeAt(hold.size - 1)
}
if (z.toInt() == 6) {
six += hold[hold.size - 1]
hold.removeAt(hold.size - 1)
}
if (z.toInt() == 7) {
seven += hold[hold.size - 1]
hold.removeAt(hold.size - 1)
}
if (z.toInt() == 8) {
eight += hold[hold.size - 1]
hold.removeAt(hold.size - 1)
}
if (z.toInt() == 9) {
nine += hold[hold.size - 1]
hold.removeAt(hold.size - 1)
}
}/*
for(j in 0 until x.toInt() ) {
if(z.toInt() == 1){
first += hold[1]
hold.removeAt(1) }
if(z.toInt() == 2){
two += hold[1]
hold.removeAt(1)}
if(z.toInt() == 3){
three += hold[1]
hold.removeAt(1)}
if(z.toInt() == 4){
four += hold[1]
hold.removeAt(1)}
if(z.toInt() == 5){
five += hold[1]
hold.removeAt(1)}
if(z.toInt() == 6){
six += hold[1]
hold.removeAt(1)}
if(z.toInt() == 7){
seven += hold[1]
hold.removeAt(1)}
if(z.toInt() == 8){
eight += hold[1]
hold.removeAt(1)}
if(z.toInt() == 9){
nine += hold[1]
hold.removeAt(1)}
gives you the first part
}*/
}
println(first)
println(two)
println(three)
println(four)
println(five)
println(six)
println(seven)
println(eight)
println(nine)
return ""
}
fun findThingy(input: List<String>): Int {
var count = 1
var groups = input[0].windowed(4)
println(groups)
// println(input)
//val map = groups.map{it.chars()}
for(i in groups.indices)
{
for(x in groups.indices)
{
for(m in 0 until groups[x].length -1)
{
var y = groups[x].substring(m,m+1)
if(groups[x].indexOf(y, m+1) != groups[x].indexOf(y))
{
count+=3
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | b6092180cd202f5bf24efb0fa97c7a20b1b934c3 | 10,663 | AdventOfCode2022IH | Apache License 2.0 |
src/main/kotlin/day16/Code.kt | fcolasuonno | 317,324,330 | false | null | package day16
import isDebug
import java.io.File
fun main() {
val name = if (isDebug()) "test.txt" else "input.txt"
System.err.println(name)
val dir = ::main::class.java.`package`.name
val input = File("src/main/kotlin/$dir/$name").readLines()
val parsed = parse(input)
part1(parsed)
part2(parsed)
}
data class Rule(val name: String, val range1: IntRange, val range2: IntRange) {
override fun toString() = name
operator fun contains(value: Int) = value in range1 || value in range2
}
private val ruleStructure = """([^:]+): (\d+)-(\d+) or (\d+)-(\d+)""".toRegex()
fun parse(input: List<String>): Triple<List<Rule>, List<Int>, List<List<Int>>> {
val (rules, mine, others) = input.joinToString(separator = "\n").split("\n\n")
return Triple(rules.split("\n").map {
ruleStructure.matchEntire(it)?.destructured?.let {
val (rule, range1Start, range1End, range2Start, range2End) = it.toList()
Rule(rule, range1Start.toInt()..range1End.toInt(), range2Start.toInt()..range2End.toInt())
}
}.requireNoNulls(),
mine.split("\n").drop(1).single().split(",").map { it.toInt() },
others.split("\n").drop(1).map { it.split(",").map { it.toInt() } })
}
fun part1(input: Triple<List<Rule>, List<Int>, List<List<Int>>>) {
val (rules, _, others) = input
val res = others.flatMap { it.filterNot { field -> rules.any { rule -> field in rule } } }.sum()
println("Part 1 = $res")
}
fun part2(input: Triple<List<Rule>, List<Int>, List<List<Int>>>) {
val (rules, mine, others) = input
val valid = others.filter { it.all { field -> rules.any { rule -> field in rule } } }
val foundRules = mutableMapOf<Rule, Int>()
val unknownRules = rules.toMutableSet()
while (unknownRules.isNotEmpty()) {
val unknownIndices = mine.indices - foundRules.values
foundRules += unknownIndices.mapNotNull { index ->
unknownRules.singleOrNull { rule -> valid.all { it[index] in rule } }?.let { it to index }
}
unknownRules -= foundRules.keys
}
val res = foundRules
.filterKeys { if (!isDebug()) it.name.startsWith("departure") else true }
.values
.fold(1L) { acc, i -> acc * mine[i] }
println("Part 2 = $res")
} | 0 | Kotlin | 0 | 0 | e7408e9d513315ea3b48dbcd31209d3dc068462d | 2,286 | AOC2020 | MIT License |
src/day07/Day07.kt | Harvindsokhal | 572,911,840 | false | {"Kotlin": 11823} | package day07
import readInput
private data class Directory(
val name: String,
val parent: Directory? = null,
val dirs: MutableList<Directory> = mutableListOf(),
val files: MutableList<File> = mutableListOf()
) {
fun allDirs(): List<Directory> = dirs + dirs.flatMap { it.allDirs() }
fun size(): Int = files.sumOf { it.size } + dirs.sumOf { it.size() }
}
private data class File(val size: Int)
fun main() {
val data = readInput("day07/day07_data")
fun prepareTree(): Directory {
val outermost = Directory("/")
var current = outermost
data.drop(1).forEach { line ->
when {
line.startsWith("$ cd ..") -> current = current.parent!!
line.startsWith("$ cd") -> current = current.dirs.first { it.name == line.substringAfter("cd ") }
line.startsWith("dir") -> current.dirs.add(Directory(line.substringAfter("dir "), current))
!line.contains("$") -> current.files.add(File(line.substringBefore(" ").toInt()))
}
}
return outermost
}
val outermostDirectory = prepareTree()
fun solvePart1() = outermostDirectory.allDirs().map { it.size() }.filter { it < 100_000 }.sum()
fun solvePart2(): Int {
val spaceToFree = 30_000_000 - (70_000_000 - outermostDirectory.size())
return outermostDirectory.allDirs().map { it.size() }.sorted().first { it >= spaceToFree }
}
println(solvePart1())
println(solvePart2())
}
| 0 | Kotlin | 0 | 0 | 7ebaee4887ea41aca4663390d4eadff9dc604f69 | 1,503 | aoc-2022-kotlin | Apache License 2.0 |
leetcode/src/daily/hard/Q927.kt | zhangweizhe | 387,808,774 | false | null | package daily.hard
fun main() {
// 927. 三等分
// https://leetcode.cn/problems/three-equal-parts/
println(threeEqualParts(intArrayOf(0,0,0,0,0)).contentToString())
}
fun threeEqualParts(arr: IntArray): IntArray {
// 一个满足题意的数组,1 的数量应该是 3 的整数倍,且每一份中,1的数量是一样的
// 所以可以先计算数组的和,如果不能被 3 整数,那肯定不符合题意
val sum = arr.sum()
if (sum % 3 != 0) {
return intArrayOf(-1, -1)
}
// 如果和为0,说明每个元素都是0,也是符合题意的数组
if (sum == 0) {
return intArrayOf(0, arr.size - 1)
}
// 分成3份,计算每一份中,1的数量
val partial = sum / 3
// 找到每一份中,第一个1的下标
var first = 0
var second = 0
var third = 0
// cur: 1 的下标
var cur = 0
for (i in arr.indices) {
if (arr[i] == 1) {
if (cur == 0) {
first = i
}else if (cur == partial) {
second = i
}else if (cur == partial * 2) {
third = i
}
cur++
}
}
// [third, arr.size) 构成了最后一个数,计算二进制数的长度
val len = arr.size - third
val firstEnd/**exclude**/ = first + len
val secondEnd/**exclude**/ = second + len
if (firstEnd > second || secondEnd > third) {
// 三个数的二进制数有重合
// 如:11011110,len = arr.size - third = 8 - 5 = 3
// first = 0, firstEnd = 3, second = 3, secondEnd = 6, secondEnd > third,第二段和第三段重合了
return intArrayOf(-1, -1)
}
for (i in 0 until len) {
if (arr[first+i] == arr[second+i] && arr[second+i] == arr[third+i]) {
if (i == len - 1) {
// 每一份的最后一个数都一样了,那就是满足题意的
return intArrayOf(firstEnd-1, secondEnd)
}
continue
}else {
return intArrayOf(-1, -1)
}
}
return intArrayOf(-1, -1)
} | 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 2,125 | kotlin-study | MIT License |
src/Day18.kt | jinie | 572,223,871 | false | {"Kotlin": 76283} | class Day18 {
fun part1(input: Set<Point3D>): Int {
return input.sumOf {
6 - it.neighbors().count { neighbor ->
neighbor in input
}
}
}
private fun Set<Point3D>.rangeOf(function: (Point3D) -> Int): IntRange =
this.minOf(function) - 1..this.maxOf(function) + 1
fun part2(input: Set<Point3D>): Int {
val xRange = input.rangeOf { it.x }
val yRange = input.rangeOf { it.y }
val zRange = input.rangeOf { it.z }
val queue = ArrayDeque<Point3D>().apply { add(Point3D(xRange.first, yRange.first, zRange.first)) }
val seen = mutableSetOf<Point3D>()
var ret = 0
queue.forEach { lookNext ->
if (lookNext !in seen) {
lookNext.neighbors()
.filter { it.x in xRange && it.y in yRange && it.z in zRange }
.forEach { neighbor ->
seen += lookNext
if (neighbor in input) ret++
else queue.add(neighbor)
}
}
}
return ret
}
}
fun main() {
val testInput = readInput("Day18_test").map { it.split(",").toList() }
.map { Point3D(it[0].toInt(), it[1].toInt(), it[2].toInt()) }.toSet()
check(Day18().part1(testInput) == 64)
measureTimeMillisPrint {
val input = readInput("Day18").map { it.split(",").toList() }
.map { Point3D(it[0].toInt(), it[1].toInt(), it[2].toInt()) }.toSet()
println(Day18().part1(input))
println(Day18().part2(input))
}
} | 0 | Kotlin | 0 | 0 | 4b994515004705505ac63152835249b4bc7b601a | 1,611 | aoc-22-kotlin | Apache License 2.0 |
app/src/main/java/com/example/arknightsautoclicker/processing/tasks/recruitment/TagAnalyzer.kt | qwerttyuiiop1 | 684,537,002 | false | {"Kotlin": 142059} | package com.example.arknightsautoclicker.processing.tasks.recruitment
import com.example.arknightsautoclicker.processing.ext.norm
class TagAnalyzer(
private val data: Set<CharTag> = TagData().characters
) {
val availableTagsNorm: Set<String>
= data.flatMapTo(mutableSetOf()) { it.tags_norm }
data class TagCombination(
val tags: List<String>,
val characters: List<CharTag>
) {
val minRarity = characters.minOf { it.rarity }
val minProprity = characters.minOf { it.priority }
val minRarityCount = characters.count { it.rarity == minRarity }
// maximize minRarity first, then minimize minRarityCount
// if equal, minimize number of tags
private val score
get() = minProprity * minRarity * 10000 - minRarityCount * 100 - tags.size
fun max(a: TagCombination) =
if (score >= a.score) this else a
}
private fun getBestCombination(
tags_norm: List<String>,
comb: TagCombination,
ind: Int = 0
): TagCombination {
if (comb.tags.size >= 3) return comb
var best = comb
for (i in ind until tags_norm.size) {
val tag = tags_norm[i]
val newChars = comb.characters.filter { it.tags_norm.contains(tag) }
if (newChars.isEmpty()) continue
var newComb = TagCombination(
comb.tags + tag,
newChars
)
newComb = getBestCombination(tags_norm, newComb, i + 1)
best = best.max(newComb)
}
return best
}
/**
* @return the best combination of tags
* @return null if a tag combination guarantees 5* + operator
* where the user should manually select the operator with a calculator
*/
fun getBestCombination(inputTag: List<String>): TagCombination {
val tags = inputTag.map { it.norm }
val comb = if (tags.any { it == "Top Operator".norm }) {
val chars = data.filter { it.rarity == 6 }
val comb = TagCombination(listOf("Top Operator".norm), chars)
getBestCombination(tags, comb)
} else {
val chars = data.filter { it.rarity in 3..5 }
getBestCombination(tags, TagCombination(listOf(), chars))
}
val origTags = comb.tags.map { tag ->
inputTag.find { it.norm == tag } ?: throw Exception("Should not happen")
}
return TagCombination(origTags, comb.characters)
}
}
| 1 | Kotlin | 0 | 1 | 4c7ca55be02c08d1784bac57b3eff15decd07389 | 2,510 | Arknights-Autoclicker | MIT License |
src/Day03.kt | eps90 | 574,098,235 | false | {"Kotlin": 9738} | import kotlin.math.ceil
fun String.splitInHalf(): List<String> = chunked(ceil(length.toDouble() / 2).toInt())
private val priorities = (('a'..'z') + ('A'..'Z')).withIndex().associateBy({ it.value }) { it.index + 1 }
fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { line ->
val (one, two) = line.splitInHalf().map { it.toSortedSet() }
one.intersect(two).first().let { priorities[it] ?: 0 }
}
}
fun part2(input: List<String>): Int {
return input.chunked(3).sumOf { group ->
group.map { it.toSet() }.reduce { acc, chars ->
acc.intersect(chars)
}.first().let { priorities[it] ?: 0 }
}
}
val testInput = readInput("Day03_test")
println(part1(testInput))
check(part1(testInput) == 157)
println(part2(testInput))
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bbf58c512fddc0ef1112c3bee5e5c6d43f5aabc0 | 985 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/solutions/constantTime/iteration5/MinBracketTaxCalculator.kt | daniel-rusu | 669,564,782 | false | {"Kotlin": 70755} | package solutions.constantTime.iteration5
import dataModel.v3.AccumulatedTaxBracketV2
import dataModel.v3.AccumulatedTaxBracketV2.Companion.toAccumulatedBracketsV2
import dataModel.base.Money
import dataModel.base.Money.Companion.cents
import dataModel.base.TaxBracket
import dataModel.base.TaxCalculator
import solutions.constantTime.iteration4.GCDTaxCalculator
/**
* Similar to [GCDTaxCalculator] but uses the smallest bracket instead of the GCD along with a constant-time
* correction. This is much more efficient as the GCD can be 1 whereas the smallest bracket is usually much larger
* resulting in significantly fewer chunks.
*/
class MinBracketTaxCalculator(taxBrackets: List<TaxBracket>) : TaxCalculator {
private val chunkSize = getNarrowestBracketSize(taxBrackets)
private val highestBracket: AccumulatedTaxBracketV2
private val roundedDownIncomeToBracket: Map<Money, AccumulatedTaxBracketV2>
init {
val accumulatedBrackets = taxBrackets.toAccumulatedBracketsV2()
highestBracket = accumulatedBrackets.last()
roundedDownIncomeToBracket = associateChunkMultiplesToTaxBrackets(accumulatedBrackets)
}
override fun computeTax(income: Money): Money {
return getTaxBracket(income).computeTotalTax(income)
}
private fun getTaxBracket(income: Money): AccumulatedTaxBracketV2 {
if (income >= highestBracket.from) return highestBracket
val roundedDownIncome = income / chunkSize * chunkSize
val approximateBracket = roundedDownIncomeToBracket[roundedDownIncome]!!
return when {
approximateBracket.to == null || income < approximateBracket.to!! -> approximateBracket
else -> approximateBracket.next!! // boundary scenario
}
}
/** Create a map associating each multiple of the chunk size with its corresponding tax bracket */
private fun associateChunkMultiplesToTaxBrackets(
accumulatedBrackets: List<AccumulatedTaxBracketV2>,
): Map<Money, AccumulatedTaxBracketV2> {
val chunkAmount = Money.ofCents(chunkSize)
var bracketIndex = 0
return generateSequence(0.cents) { it + chunkAmount }
.takeWhile { it < accumulatedBrackets.last().from }
// create a hashMap as "associateWith" creates a LinkedHashMap by default which uses more memory
.associateWithTo(HashMap()) { income ->
if (income >= accumulatedBrackets[bracketIndex].to!!) {
bracketIndex++
}
accumulatedBrackets[bracketIndex]
}
}
}
private fun getNarrowestBracketSize(brackets: List<TaxBracket>): Long {
return brackets.asSequence()
.filter { it.to != null }
.minOfOrNull { (it.to!! - it.from).cents }
?: 1L
}
| 0 | Kotlin | 0 | 1 | 166d8bc05c355929ffc5b216755702a77bb05c54 | 2,801 | tax-calculator | MIT License |
src/main/kotlin/it/battagliandrea/advent/of/code/day3/models.kt | battagliandrea | 726,559,484 | false | {"Kotlin": 20889} | package it.battagliandrea.advent.of.code.day3
import it.battagliandrea.advent.of.code.utils.readLines
import kotlin.math.abs
data class Cell(val x: Int, val y: Int)
fun Cell.neighbours(other: Cell) =
abs(x - other.x) <= 1 && abs(y - other.y) <= 1
sealed class Entity(val cells: List<Cell>)
fun Entity.neighbours(other: Entity) =
cells.any { cell -> other.cells.any { cell.neighbours(it) } }
fun Entity.neighboursAny(others: List<Entity>) =
others.any { it.neighbours(this) }
class Symbol(x: Int, y: Int, val value: Char) : Entity(listOf(Cell(x, y)))
class Number(x: Int, y: Int, val value: String) : Entity(List(value.length) { i -> Cell(x + i, y) })
data class Engine(
private val numbers: List<Number>,
private val symbols: List<Symbol>
) {
fun getPartNumbers() = numbers
.filter { number -> number.neighboursAny(symbols) }
fun getGearRatio() = symbols
.filter { it.value == '*' }
.map { symbol ->
val neighbours = numbers.filter { it.neighbours(symbol) }
if (neighbours.size == 2) {
val (a, b) = neighbours
a.value.toInt() * b.value.toInt()
} else {
0
}
}
companion object {
fun createFromFileName(fileName: String) : Engine {
val input = fileName.readLines()
val numbers = mutableListOf<Number>()
val symbols = mutableListOf<Symbol>()
input.forEachIndexed { y, row ->
var currentNumber = ""
row.forEachIndexed { x, char ->
when (char) {
'.' -> Unit
in '0'..'9' -> currentNumber += char
else -> symbols += (Symbol(x, y, char))
}
if (char !in '0'..'9' && currentNumber.isNotEmpty()) {
numbers += (Number(x - currentNumber.length, y, currentNumber))
currentNumber = ""
}
numbers.forEach{ it.value }
}
if (currentNumber.isNotEmpty()) {
numbers += (Number(row.length - currentNumber.length, y, currentNumber))
}
}
return Engine(numbers = numbers, symbols = symbols)
}
}
}
| 0 | Kotlin | 0 | 0 | 588e3da810e2b0ff62a70cbb4c33604e37a18b88 | 2,361 | AdventOfCode2023 | Apache License 2.0 |
2015/src/main/kotlin/day16.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parse
import utils.Parser
import utils.Solution
import utils.mapItems
fun main() {
Day16.run()
}
object Day16 : Solution<List<Day16.Sue>>() {
override val name = "day16"
override val parser = Parser.lines.mapItems { parseSue(it) }
@Parse("Sue {id}: {r ', ' items}")
data class Sue(
val id: Int,
@Parse("{key}: {value}")
val items: Map<ItemKind, Int>
) {
fun matches(blueprint: Map<ItemKind, IntRange>): Boolean {
return blueprint.all { (k, v) ->
val mine = items[k]
mine == null || mine in v
}
}
}
enum class ItemKind {
children,
cats,
samoyeds,
pomeranians,
akitas,
vizslas,
goldfish,
trees,
cars,
perfumes;
}
override fun part1(input: List<Sue>): Int {
val blueprint = mapOf(
ItemKind.children to 3 .. 3,
ItemKind.cats to 7 .. 7,
ItemKind.samoyeds to 2 .. 2,
ItemKind.pomeranians to 3 .. 3,
ItemKind.akitas to 0 .. 0,
ItemKind.vizslas to 0 .. 0,
ItemKind.goldfish to 5 .. 5,
ItemKind.trees to 3 .. 3,
ItemKind.cars to 2 .. 2,
ItemKind.perfumes to 1 .. 1,
)
return input.first { it.matches(blueprint) }.id
}
override fun part2(input: List<Sue>): Int {
val blueprint = mapOf(
ItemKind.children to 3 .. 3,
ItemKind.cats to 8 .. Integer.MAX_VALUE,
ItemKind.samoyeds to 2 .. 2,
ItemKind.pomeranians to (0 until 3),
ItemKind.akitas to 0 .. 0,
ItemKind.vizslas to 0 .. 0,
ItemKind.goldfish to (0 until 5),
ItemKind.trees to 4 .. Integer.MAX_VALUE,
ItemKind.cars to 2 .. 2,
ItemKind.perfumes to 1 .. 1,
)
return input.first { it.matches(blueprint) }.id
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 1,730 | aoc_kotlin | MIT License |
src/day23/day.kt | LostMekka | 574,697,945 | false | {"Kotlin": 92218} | package day23
import util.Point
import util.boundingRect
import util.readInput
import util.shouldBe
import java.util.LinkedList
fun main() {
val testInput = readInput(Input::class, testInput = true).parseInput()
testInput.part1() shouldBe 110
testInput.part2() shouldBe 20
val input = readInput(Input::class).parseInput()
println("output for part1: ${input.part1()}")
println("output for part2: ${input.part2()}")
}
private class Input(
val startingPositions: Set<Point>,
)
private fun List<String>.parseInput(): Input {
val elves = buildSet {
for ((y, line) in this@parseInput.withIndex()) {
for ((x, char) in line.withIndex()) {
if (char == '#') add(Point(x, y))
}
}
}
return Input(elves)
}
private data class State(
var positions: Set<Point>,
val strategies: LinkedList<(List<Point>, Set<Point>) -> Point?>,
var isMoving: Boolean = true,
)
private fun Input.startingState() = State(
startingPositions,
LinkedList<(List<Point>, Set<Point>) -> Point?>().apply {
add { n, p -> n[2].takeIf { n[1] !in p && n[2] !in p && n[3] !in p } }
add { n, p -> n[6].takeIf { n[5] !in p && n[6] !in p && n[7] !in p } }
add { n, p -> n[4].takeIf { n[3] !in p && n[4] !in p && n[5] !in p } }
add { n, p -> n[0].takeIf { n[7] !in p && n[0] !in p && n[1] !in p } }
},
)
private fun State.simulateRound() {
val proposalsByTarget = positions.groupBy { currPos ->
val neighbours = currPos.neighboursIncludingDiagonals()
when {
neighbours.none { it in positions } -> null
else -> strategies
.asSequence()
.mapNotNull { it(neighbours, positions) }
.firstOrNull()
}
}
isMoving = false
positions = buildSet {
for ((target, sources) in proposalsByTarget) {
when {
sources.size > 1 || target == null -> addAll(sources)
else -> {
add(target)
isMoving = true
}
}
}
}
strategies += strategies.removeFirst()
}
private fun Input.part1(): Long {
val state = startingState()
repeat(10) { state.simulateRound() }
return state.positions.boundingRect().size() - state.positions.size
}
private fun Input.part2(): Int {
val state = startingState()
var i = 0
while (state.isMoving) {
state.simulateRound()
i++
}
return i
}
| 0 | Kotlin | 0 | 0 | 58d92387825cf6b3d6b7567a9e6578684963b578 | 2,542 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | roxspring | 573,123,316 | false | {"Kotlin": 9291} | fun main() {
fun Char.priority(): Int = when (this) {
in 'a'..'z' -> code - 'a'.code + 1
in 'A'..'Z' -> code - 'A'.code + 26 + 1
else -> throw Exception("WTF? $this")
}
fun String.uniqueCharactersInCommonWith(other: String): String =
toCharArray().filter { other.contains(it) }.distinct().joinToString()
fun part1(lines: List<String>): Int = lines.asSequence()
.map { line -> Pair(line.substring(0 until line.length / 2), line.substring(line.length / 2)) }
.map { (left, right) ->
left.uniqueCharactersInCommonWith(right).first()
}
.sumOf { it.priority() }
fun part2(lines: List<String>): Int = lines.asSequence()
.chunked(3)
.map { group -> group[0].uniqueCharactersInCommonWith(group[1]).uniqueCharactersInCommonWith(group[2]).first() }
.sumOf { it.priority() }
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
val input = readInput("Day03")
println(part1(input))
check(part2(testInput) == 70)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 535beea93bf84e650d8640f1c635a430b38c169b | 1,166 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/ru/timakden/aoc/year2023/Day13.kt | timakden | 76,895,831 | false | {"Kotlin": 321649} | package ru.timakden.aoc.year2023
import ru.timakden.aoc.util.measure
import ru.timakden.aoc.util.readInput
import kotlin.math.absoluteValue
/**
* [Day 13: Point of Incidence](https://adventofcode.com/2023/day/13).
*/
object Day13 {
@JvmStatic
fun main(args: Array<String>) {
measure {
val input = readInput("year2023/Day13")
println("Part One: ${part1(input)}")
println("Part Two: ${part2(input)}")
}
}
fun part1(input: List<String>): Int =
parseInput(input).sumOf { findMirror(it, 0) }
fun part2(input: List<String>): Int =
parseInput(input).sumOf { findMirror(it, 1) }
private fun findMirror(pattern: List<String>, goalTotal: Int): Int =
findHorizontalMirror(pattern, goalTotal) ?: findVerticalMirror(pattern, goalTotal)
?: error("Pattern does not mirror")
private fun findHorizontalMirror(pattern: List<String>, goalTotal: Int): Int? =
(0 until pattern.lastIndex).firstNotNullOfOrNull { start ->
if (createMirrorRanges(start, pattern.lastIndex)
.sumOf { (up, down) ->
pattern[up] diff pattern[down]
} == goalTotal
) (start + 1) * 100
else null
}
private fun findVerticalMirror(pattern: List<String>, goalTotal: Int): Int? =
(0 until pattern.first().lastIndex).firstNotNullOfOrNull { start ->
if (createMirrorRanges(start, pattern.first().lastIndex)
.sumOf { (left, right) ->
pattern.columnToString(left) diff pattern.columnToString(right)
} == goalTotal
) start + 1
else null
}
private infix fun String.diff(other: String): Int =
indices.count { this[it] != other[it] } + (length - other.length).absoluteValue
private fun createMirrorRanges(start: Int, max: Int): List<Pair<Int, Int>> =
(start downTo 0).zip(start + 1..max)
private fun List<String>.columnToString(column: Int): String =
this.map { it[column] }.joinToString("")
private fun parseInput(input: List<String>): List<List<String>> =
input.joinToString("\n").split("\n\n").map { it.lines() }
}
| 0 | Kotlin | 0 | 3 | acc4dceb69350c04f6ae42fc50315745f728cce1 | 2,266 | advent-of-code | MIT License |
src/Day07.kt | robinpokorny | 572,434,148 | false | {"Kotlin": 38009} | data class Directory(
val name: String,
val parent: Directory?,
var size: Int? = null,
val dirs: MutableList<Directory> = mutableListOf(),
val files: MutableMap<String, Int> = mutableMapOf()
)
sealed class TerminalOutput {
class CD(val path: String) : TerminalOutput()
class File(val name: String, val size: Int) : TerminalOutput()
}
private fun parseToOutput(input: List<String>): List<TerminalOutput> = input
.mapNotNull {
if (it[0] == '$')
if (it[2] == 'c')
TerminalOutput.CD(it.substring(5))
else
null
else
if (it[0] == 'd')
null
else
it.split(' ')
.let { (size, name) ->
TerminalOutput.File(name, size.toInt())
}
}
private fun countSizes(root: Directory): Unit {
if (root.size != null) return
root.dirs.forEach(::countSizes)
root.size = root.files.values.sum() +
root.dirs.sumOf { it.size ?: 0 }
}
private fun parseToTree(input: List<String>): Directory {
val output = parseToOutput(input)
val root = Directory("/", null)
output.fold(root) { dir, line ->
when (line) {
is TerminalOutput.CD -> when (line.path) {
".." -> dir.parent!!
"/" -> root
else -> Directory(line.path, dir)
.also { dir.dirs.add(it) }
}
is TerminalOutput.File -> dir.also {
it.files.set(line.name, line.size)
}
}
}
countSizes(root)
return root
}
private fun sumDirsUnder100k(root: Directory): Int {
val x = root.size?.takeIf { it < 100_000 } ?: 0
return x + root.dirs.sumOf(::sumDirsUnder100k)
}
private fun findDirsLargerThan(root: Directory, limit: Int): List<Directory> {
if (root.size!! < limit) return listOf()
return root.dirs.flatMap { findDirsLargerThan(it, limit) }.plus(root)
}
private fun smallestToDelete(root: Directory): Int =
findDirsLargerThan(root, root.size!! - 40000000).minOf { it.size ?: 0 }
fun main() {
val input = parseToTree(readDayInput(7))
val testInput = parseToTree(rawTestInput)
// PART 1
assertEquals(sumDirsUnder100k(testInput), 95437)
println("Part1: ${sumDirsUnder100k(input)}")
// PART 2
assertEquals(smallestToDelete(testInput), 24933642)
println("Part2: ${smallestToDelete(input)}")
}
private val rawTestInput = """
${'$'} cd /
${'$'} ls
dir a
14848514 b.txt
8504156 c.dat
dir d
${'$'} cd a
${'$'} ls
dir e
29116 f
2557 g
62596 h.lst
${'$'} cd e
${'$'} ls
584 i
${'$'} cd ..
${'$'} cd ..
${'$'} cd d
${'$'} ls
4060174 j
8033020 d.log
5626152 d.ext
7214296 k
""".trimIndent().lines() | 0 | Kotlin | 0 | 2 | 56a108aaf90b98030a7d7165d55d74d2aff22ecc | 2,885 | advent-of-code-2022 | MIT License |
src/day16/Day16.kt | spyroid | 433,555,350 | false | null | package day16
import com.github.ajalt.mordant.terminal.Terminal
import readInput
import kotlin.system.measureTimeMillis
class Decoder(input: String) {
data class Packet(val version: Int, val type: Int) {
val packets = mutableListOf<Packet>()
var value = 0L
fun getAllVersions(): List<Int> = buildList {
add(version)
packets.forEach { addAll(it.getAllVersions()) }
}
fun value(): Long {
return when (type) {
0 -> packets.sumOf { it.value() }
1 -> packets.map { it.value() }.reduce { a, b -> a * b }
2 -> packets.minOf { it.value() }
3 -> packets.maxOf { it.value() }
4 -> value
5 -> if (packets.first().value() > packets.last().value()) 1 else 0
6 -> if (packets.first().value() < packets.last().value()) 1 else 0
7 -> if (packets.first().value() == packets.last().value()) 1 else 0
else -> -1
}
}
}
private val binData = buildString {
input.asSequence()
.map { it.digitToInt(16).toString(2) }
.forEach { append(it.padStart(4, '0')) }
}
val root = decodePacket(binData).first
private fun decodePacket(data: String): Pair<Packet, String> {
var local = data
val version = local.take(3).toInt(2).also { local = local.drop(3) }
val type = local.take(3).toInt(2).also { local = local.drop(3) }
val packet = Packet(version, type)
if (type == 4) {
packet.value = buildString {
while (local.first() == '1') {
append(local.drop(1).take(4))
local = local.drop(5)
}
append(local.drop(1).take(4))
local = local.drop(5)
}.toLong(2)
} else {
val lenType = local.take(1).toInt(2).also { local = local.drop(1) }
if (lenType == 0) {
val totalLength = local.take(15).toInt(2).also { local = local.drop(15) }
var subData = local.take(totalLength).also { local = local.drop(totalLength) }
while (subData.isNotEmpty()) {
val (pkt, remaining) = decodePacket(subData)
packet.packets.add(pkt)
subData = remaining
}
} else {
val subPacketCount = local.take(11).toInt(2).also { local = local.drop(11) }
while (packet.packets.size < subPacketCount) {
val (pkt, remaining) = decodePacket(local)
local = remaining
packet.packets.add(pkt)
}
}
}
return Pair(packet, local)
}
}
fun main() {
fun part1(input: List<String>): Int {
return Decoder(input.first()).root.getAllVersions().sum()
}
fun part2(input: List<String>): Long {
return Decoder(input.first()).root.value()
}
val testData = readInput("day16/test")
val inputData = readInput("day16/input")
val term = Terminal()
var res1 = part1(testData)
check(res1 == 31) { "Expected 31 but got $res1" }
var time = measureTimeMillis { res1 = part1(inputData) }
term.success("⭐️ Part1: $res1 in $time ms")
var res2 = 0L
time = measureTimeMillis { res2 = part2(inputData) }
term.success("⭐️ Part2: $res2 in $time ms")
}
| 0 | Kotlin | 0 | 0 | 939c77c47e6337138a277b5e6e883a7a3a92f5c7 | 3,505 | Advent-of-Code-2021 | Apache License 2.0 |
src/main/kotlin/PartitionArrayForMaximumSum.kt | Codextor | 453,514,033 | false | {"Kotlin": 26975} | /**
* Given an integer array arr, partition the array into (contiguous) subarrays of length at most k.
* After partitioning, each subarray has their values changed to become the maximum value of that subarray.
*
* Return the largest sum of the given array after partitioning.
* Test cases are generated so that the answer fits in a 32-bit integer.
*
*
*
* Example 1:
*
* Input: arr = [1,15,7,9,2,5,10], k = 3
* Output: 84
* Explanation: arr becomes [15,15,15,9,10,10,10]
* Example 2:
*
* Input: arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4
* Output: 83
* Example 3:
*
* Input: arr = [1], k = 1
* Output: 1
*
*
* Constraints:
*
* 1 <= arr.length <= 500
* 0 <= arr[i] <= 10^9
* 1 <= k <= arr.length
* @see <a https://leetcode.com/problems/partition-array-for-maximum-sum/">LeetCode</a>
*/
fun maxSumAfterPartitioning(arr: IntArray, k: Int): Int {
val arraySize = arr.size
// memoryArray[i] will hold the maximum sum we can get for the first i elements of arr, with memoryArray[0] = 0
val memoryArray = IntArray(arraySize + 1)
for (index in 1..arraySize) {
var subarrayMaxElement = 0
for (subarraySize in 1..minOf(k, index)) {
subarrayMaxElement = subarrayMaxElement.coerceAtLeast(arr[index - subarraySize])
val sum = memoryArray[index - subarraySize] + subarraySize * subarrayMaxElement
memoryArray[index] = memoryArray[index].coerceAtLeast(sum)
}
}
return memoryArray[arraySize]
}
| 0 | Kotlin | 1 | 0 | 68b75a7ef8338c805824dfc24d666ac204c5931f | 1,487 | kotlin-codes | Apache License 2.0 |
src/Day08.kt | jmorozov | 573,077,620 | false | {"Kotlin": 31919} | fun main() {
val inputData = readInput("Day08")
part1(inputData)
part2(inputData)
}
private fun part1(inputData: List<String>) {
var visibleTrees = 0
val (rows, cols) = buildGrid(inputData)
for ((rowIdx, row) in rows.withIndex()) {
if (rowIdx == 0 || rowIdx == rows.lastIndex) {
visibleTrees += row.size
continue
}
for ((colIdx, treeHigh) in row.withIndex()) {
val isVisible = colIdx == 0 ||
colIdx == row.lastIndex ||
isVisibleFromLeft(row, colIdx, treeHigh) ||
isVisibleFromRight(row, colIdx, treeHigh) ||
isVisibleFromLeft(cols[colIdx], rowIdx, treeHigh) ||
isVisibleFromRight(cols[colIdx], rowIdx, treeHigh)
if (isVisible) {
visibleTrees++
}
}
}
println("Trees are visible from outside the grid: $visibleTrees")
}
private fun buildGrid(inputData: List<String>): Pair<Array<IntArray>, Array<IntArray>> {
val rows = Array(inputData.size) { IntArray(0) }
val cols = Array(inputData.first().length) { IntArray(inputData.size) }
for ((rowIdx, line) in inputData.withIndex()) {
val row = line.trim().toCharArray().map { it.digitToInt() }.toIntArray()
rows[rowIdx] = row
for ((colIdx, col) in row.withIndex()) {
cols[colIdx][rowIdx] = col
}
}
return Pair(rows, cols)
}
private fun isVisibleFromLeft(row: IntArray, colIdx: Int, treeHigh: Int): Boolean =
row.sliceArray(0 until colIdx).all { it < treeHigh }
private fun isVisibleFromRight(row: IntArray, colIdx: Int, treeHigh: Int): Boolean =
row.sliceArray(colIdx + 1 .. row.lastIndex).all { it < treeHigh }
private fun part2(inputData: List<String>) {
var highestScenicScore = 0
val (rows, cols) = buildGrid(inputData)
for ((rowIdx, row) in rows.withIndex()) {
if (rowIdx == 0 || rowIdx == rows.lastIndex) {
continue
}
for ((colIdx, treeHigh) in row.withIndex()) {
if (colIdx == 0 || colIdx == row.lastIndex) {
continue
}
val scenicScore = leftScenicScore(row, colIdx, treeHigh) *
rightScenicScore(row, colIdx, treeHigh) *
leftScenicScore(cols[colIdx], rowIdx, treeHigh) *
rightScenicScore(cols[colIdx], rowIdx, treeHigh)
if (scenicScore > highestScenicScore) {
highestScenicScore = scenicScore
}
}
}
println("The highest scenic score possible for any tree: $highestScenicScore")
}
private fun leftScenicScore(row: IntArray, colIdx: Int, treeHigh: Int): Int {
var visibleTrees = 0
for (idx in colIdx - 1 downTo 0) {
visibleTrees++
if (row[idx] >= treeHigh) {
break
}
}
return visibleTrees
}
private fun rightScenicScore(row: IntArray, colIdx: Int, treeHigh: Int): Int {
var visibleTrees = 0
for (idx in colIdx + 1 .. row.lastIndex) {
visibleTrees++
if (row[idx] >= treeHigh) {
break
}
}
return visibleTrees
}
| 0 | Kotlin | 0 | 0 | 480a98838949dbc7b5b7e84acf24f30db644f7b7 | 3,219 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/day20/Day20.kt | jakubgwozdz | 571,298,326 | false | {"Kotlin": 85100} | package day20
import execute
import readAllText
private class Elem(val v: Long) {
override fun toString() = v.toString()
}
private fun List<Elem>.process(e: Elem): List<Elem> {
val oldIdx = withIndex().single { it.value == e }.index
val newResult = subList(oldIdx + 1, size) + subList(0, oldIdx) + subList(oldIdx + 1, size) + subList(0, oldIdx)
var delta = (e.v % (size - 1)).toInt()
// while (delta >= 0) delta -= size - 1
if (delta < 0) delta += size - 1
return newResult.subList(delta, delta + size - 1) + e
}
fun part1(input: String) = solve(input, 1, 1)
fun part2(input: String) = solve(input, 811589153, 10)
private fun solve(input: String, multiplier: Long, times: Int) = input.lineSequence().mapNotNull { it.toIntOrNull() }
.toList()
.map { Elem(it * multiplier) }
.let { initial ->
var result = initial
repeat(times) { initial.forEach { result = result.process(it) } }
val offset = result.withIndex().single { it.value.v == 0L }.index
listOf(1000, 2000, 3000).sumOf { result[(offset + it) % result.size].v }
}
fun main() {
val input = readAllText("local/day20_input.txt")
val test = """
1
2
-3
3
-2
0
4
""".trimIndent()
execute(::part1, test, 3)
execute(::part1, input, 8764)
execute(::part2, test, 1623178306)
execute(::part2, input, 535648840980)
}
| 0 | Kotlin | 0 | 0 | 7589942906f9f524018c130b0be8976c824c4c2a | 1,429 | advent-of-code-2022 | MIT License |
kotlin/src/com/leetcode/222_CountCompleteTreeNodes.kt | programmerr47 | 248,502,040 | false | null | package com.leetcode
import com.leetcode.data.TreeNode
import com.leetcode.data.treeNode
import com.sun.source.tree.Tree
import java.util.*
/**
* In leetcode there is much more concise and elegant solution.
* So beware of my big, but still fast one :)
*
* The algorithm is next:
*
* 1. find the max possible depth of the tree. This is achievable
* by iterating only through the left children (by definition of
* complete tree)
*
* 2. Calculate max amount of children in the lowest level of the tree.
* For example: for depth 2 it is 2, for depth 4 it is 8 and etc
*
* 3. This step is very similar to binary search. We have the last child
* somewhere between 0 and max amount of children in the lowest level.
* So we take the avg of 0 and max_amount and check if this child is presented or not
*
* 4. If the child is presented, then we need to take right window [avg + 1, max_amout]
* if the child is not presented, then we need to take left window [0, avg - 1]
*
* 5. Repeat 3-4 until the window will be 1 or less values.
*
* Estimation consists of several parts:
*
* 1. finding max depth. Since we have complete binary tree,
* it will never have more than [log(n)] + 1 depth. Means O(logN)
*
* 2. then we have a window [0 ... max_count_low_level]. The last variable
* is no more than n/2 by definition of binary tree. And we will have
* something like binary search around that window, which is log(n/2).
* Means O(logN)
*
* 3. On each iteration of "binary search". We need to calculate depth of
* respective path in the tree. Since the 1. is valid, the respective path
* will have depth no more than max depth. Means O(logN)
*
* So, Time: O(logN) + O(logN) * O(logN) = O((logN)^2)
*/
private class Solution222 {
fun countNodes(root: TreeNode?): Int {
if (root == null) return 0
val maxDepth = root.depth()
val maxCount = (1 shl maxDepth) - 1
var left = 0
var right = maxCount / 2
var maxDepthLast = 0
while (left <= right) {
val avg = (left + right) / 2
if (root.depth(maxDepth, avg) == maxDepth) {
maxDepthLast = avg
left = avg + 1
} else {
right = avg - 1
}
}
return maxCount - maxCount / 2 + maxDepthLast
}
private fun TreeNode.depth(max: Int = 0, shift: Int = 0): Int {
var ptr: TreeNode? = this
var depth = 0
while (ptr != null) {
depth++
ptr = if (shift.bit(max - depth - 1) == 0) ptr.left else ptr.right
}
return depth
}
private fun Int.bit(i: Int): Int = ((1 shl i) and this) shr i
}
fun main() {
val solution = Solution222()
println(solution.countNodes(null))
println(solution.countNodes(
treeNode(1) {
left = treeNode(2) {
left = treeNode(4) {
left = treeNode(8)
right = treeNode(9)
}
right = treeNode(5) {
left = treeNode(10)
}
}
right = treeNode(3) {
left = treeNode(6)
right = treeNode(7)
}
}
))
println(solution.countNodes(
treeNode(1) {
left = treeNode(2) {
left = treeNode(4) {
left = treeNode(8)
right = treeNode(9)
}
right = treeNode(5) {
left = treeNode(10)
right = treeNode(11)
}
}
right = treeNode(3) {
left = treeNode(6) {
left = treeNode(12)
right = treeNode(13)
}
right = treeNode(7) {
left = treeNode(14)
right = treeNode(15)
}
}
}
))
println(solution.countNodes(
treeNode(1) {
left = treeNode(2) {
left = treeNode(4) {
left = treeNode(8) {
left = treeNode(16)
}
right = treeNode(9)
}
right = treeNode(5) {
left = treeNode(10)
right = treeNode(11)
}
}
right = treeNode(3) {
left = treeNode(6) {
left = treeNode(12)
right = treeNode(13)
}
right = treeNode(7) {
left = treeNode(14)
right = treeNode(15)
}
}
}
))
}
private fun buildCompleteTree(count: Int): TreeNode? {
if (count == 0) return null
var value = 1
val root = TreeNode(value)
val queue = LinkedList<TreeNode>()
queue.add(root)
var remain = count - 1
while (remain > 0) {
val node = queue.pollFirst()
value++
node.left = TreeNode(value)
queue.addLast(node.left)
remain--
if (remain <= 0) return root
value++
node.right = TreeNode(value)
queue.addLast(node.right)
remain--
}
return root
} | 0 | Kotlin | 0 | 0 | 0b5fbb3143ece02bb60d7c61fea56021fcc0f069 | 5,294 | problemsolving | Apache License 2.0 |
src/Day03.kt | epishkin | 572,788,077 | false | {"Kotlin": 6572} | fun main() {
fun priority(element: Char): Int {
val offset =
if (element.isUpperCase()) 'A'.code - 27
else 'a'.code - 1
return element.code - offset
}
fun part1(input: List<String>): Int {
return input
.map {
val half = it.length / 2
Pair(it.take(half), it.takeLast(half))
}
.map { (one, two) ->
one.find { two.contains(it) }
}
.sumOf { priority(it!!) }
}
fun part2(input: List<String>): Int {
return input
.chunked(3)
.map { (one, two, three) ->
one
.toSet()
.intersect(two.toSet())
.intersect(three.toSet())
.first()
}
.sumOf { priority(it) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e5e5755c2d77f75750bde01ec5aad70652ef4dbf | 1,228 | advent-of-code-2022 | Apache License 2.0 |
src/Day21.kt | StephenVinouze | 572,377,941 | false | {"Kotlin": 55719} | data class YellingMonkey(
val name: String,
val number: Long?,
val operator: Operator?,
val waitingForMonkeys: List<String>,
)
enum class Operator(val value: Char) {
Add('+'),
Substract('-'),
Multiply('*'),
Divide('/'),
}
fun main() {
fun List<String>.toYellingMonkeys(): List<YellingMonkey> =
map { line ->
val name = line.substringBefore(":")
val operation = line.substringAfter(":").trim()
val isYellingNumber = operation.first().isDigit()
val number = if (isYellingNumber) operation.toLong() else null
val (operator, waitingForMonkeys) = operation.split(" ").let {
val operator = if (isYellingNumber) null else Operator.values().first { operator -> operator.value == it[1].first() }
val waitingForMonkeys = if (isYellingNumber) emptyList() else listOf(it[0], it[2])
operator to waitingForMonkeys
}
YellingMonkey(
name = name,
number = number,
operator = operator,
waitingForMonkeys = waitingForMonkeys
)
}
fun part1(input: List<String>): Long {
val monkeys = input.toYellingMonkeys().toMutableList()
while (monkeys.first { it.name == "root" }.number == null) {
monkeys.forEachIndexed { index, monkey ->
if (monkey.waitingForMonkeys.isNotEmpty()) {
val waitingForMonkeys = monkey.waitingForMonkeys.map { name -> monkeys.first { it.name == name } }
val firstMonkeyNumber = waitingForMonkeys.first().number
val secondMonkeyNumber = waitingForMonkeys.last().number
val updatedMonkey = if (firstMonkeyNumber != null && secondMonkeyNumber != null) {
val number = when (monkey.operator) {
Operator.Add -> firstMonkeyNumber + secondMonkeyNumber
Operator.Substract -> firstMonkeyNumber - secondMonkeyNumber
Operator.Multiply -> firstMonkeyNumber * secondMonkeyNumber
Operator.Divide -> firstMonkeyNumber / secondMonkeyNumber
null -> throw IllegalStateException("Monkey should have an operator at this point!")
}
monkey.copy(number = number, waitingForMonkeys = emptyList())
} else monkey
monkeys[index] = updatedMonkey
}
}
}
return monkeys.first { it.name == "root" }.number!!
}
fun part2(input: List<String>): Long {
val monkeys = input.toYellingMonkeys().toMutableList()
return 0L
}
check(part1(readInput("Day21_test")) == 152L)
//check(part2(readInput("Day21_test")) == 301L)
val input = readInput("Day21")
println(part1(input))
//println(part2(input))
} | 0 | Kotlin | 0 | 0 | 11b9c8816ded366aed1a5282a0eb30af20fff0c5 | 2,993 | AdventOfCode2022 | Apache License 2.0 |
src/Day14.kt | zsmb13 | 572,719,881 | false | {"Kotlin": 32865} | data class Position(val x: Int, val y: Int)
fun Position.below() = Position(x, y + 1)
fun Position.left() = Position(x - 1, y + 1)
fun Position.right() = Position(x + 1, y + 1)
fun createOccupiedSet(paths: List<List<Position>>): MutableSet<Position> {
return buildSet {
paths.forEach { path ->
path.zipWithNext().forEach { (p1, p2) ->
val (x1, y1) = p1
val (x2, y2) = p2
(minOf(y1, y2)..maxOf(y1, y2)).forEach { y ->
(minOf(x1, x2)..maxOf(x1, x2)).forEach { x ->
add(Position(x, y))
}
}
}
}
}.toMutableSet()
}
fun Position.computeNext(occupied: MutableSet<Position>) = sequence {
yield(below())
yield(left())
yield(right())
}.firstOrNull { it !in occupied }
inline fun runSimulation(
testInput: List<String>,
drop: (MutableSet<Position>, Int, Position, Position?) -> Position?
): Int {
val paths: List<List<Position>> = testInput.map { line ->
line.split(" -> ").map { coordinates ->
val (x, y) = coordinates.split(',').map(String::toInt)
Position(x, y)
}
}
val yMax = paths.maxOf { path -> path.maxOf(Position::y) }
val occupied = createOccupiedSet(paths)
val initialSize = occupied.size
runCatching {
while (true) {
var s = Position(500, 0)
while (true) {
val proposedNext = s.computeNext(occupied)
val next = drop(occupied, yMax, s, proposedNext)
if (next == null) {
occupied += s
break
}
s = next
}
}
}
return occupied.size - initialSize
}
fun main() {
fun part1(testInput: List<String>): Int {
return runSimulation(testInput) { _, yMax, s, next ->
// Run until sand doesn't fall past yMax
check(s.y <= yMax)
next
}
}
fun part2(testInput: List<String>): Int {
return runSimulation(testInput) { occupied, yMax, s, next ->
// Hit the floor - override next value
if (s.y == yMax + 1) {
occupied += s
return@runSimulation null
}
// Run until we're NOT stuck in the starting position
check((next == null && s == Position(500, 0)).not()) {
// Mark starting position occupied before wrapping up
occupied.add(s)
}
next
}
}
val testInput = readInput("Day14_test")
check(part1(testInput).also(::println) == 24)
check(part2(testInput).also(::println) == 93)
val input = readInput("Day14")
check(part1(input).also(::println) == 692)
check(part2(input).also(::println) == 31706)
}
| 0 | Kotlin | 0 | 6 | 32f79b3998d4dfeb4d5ea59f1f7f40f7bf0c1f35 | 2,881 | advent-of-code-2022 | Apache License 2.0 |
src/year2022/day07/Day07.kt | kingdongus | 573,014,376 | false | {"Kotlin": 100767} | package year2022.day07
import readInputFileByYearAndDay
import readTestFileByYearAndDay
import java.util.*
operator fun Regex.contains(text: CharSequence): Boolean = this.matches(text)
fun main() {
data class File(val name: String, val size: Int)
class Folder(val name: String = "/", val parent: Folder? = null) {
val subFolders = mutableListOf<Folder>()
val files = mutableListOf<File>()
fun size(): Int = subFolders.sumOf { it.size() } + files.sumOf { it.size }
}
fun parseFileSystem(input: List<String>): Folder {
val root = Folder()
var currentFolder = root
input.forEach {
when (it) {
"$ cd /" -> currentFolder = root
"$ cd .." -> currentFolder = currentFolder.parent!!
in Regex(""". cd [a-zA-Z]+""") -> {
val name = it.split(" ").last()
currentFolder = currentFolder.subFolders.first { folder -> folder.name == name }
}
in Regex("""dir [a-zA-Z]+""") -> {
val name = it.split(" ").last()
currentFolder.subFolders.add(Folder(name, currentFolder))
}
in Regex("""[0-9]+ [a-zA-Z/.]+""") -> {
val name = it.split(" ").last()
val size = it.split(" ").first().toInt()
currentFolder.files.add(File(name, size))
}
else -> {
// do nothing on ls and unrecognized commands
}
}
}
return root
}
fun part1(input: List<String>): Int {
val root = parseFileSystem(input)
val toProcess = Stack<Folder>()
toProcess.push(root)
var sub100kSum = 0
while (toProcess.isNotEmpty()) {
val next = toProcess.pop()
val size = next.size()
if (size < 100000) sub100kSum += size
next.subFolders.forEach { toProcess.push(it) }
}
return sub100kSum
}
fun part2(input: List<String>): Int {
val root = parseFileSystem(input)
val toFreeUp = 30_000_000 - (70_000_000 - root.size())
val toProcess = Stack<Folder>()
toProcess.push(root)
var bestMatch = root
while (toProcess.isNotEmpty()) {
val next = toProcess.pop()
val size = next.size()
if (size < toFreeUp) continue
next.subFolders.forEach { toProcess.push(it) }
if (size < bestMatch.size()) bestMatch = next
}
return bestMatch.size()
}
val testInput = readTestFileByYearAndDay(2022, 7)
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInputFileByYearAndDay(2022, 7)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | aa8da2591310beb4a0d2eef81ad2417ff0341384 | 2,885 | advent-of-code-kotlin | Apache License 2.0 |
src/Day12.kt | dmarcato | 576,511,169 | false | {"Kotlin": 36664} | import java.util.*
import kotlin.time.ExperimentalTime
data class StepPos(val x: Int, val y: Int)
fun StepPos.linearPos(input: List<String>): Int = y * input.first().length + x
data class StepAndCost(val step: StepPos, val cost: Long) : Comparable<StepAndCost> {
override fun compareTo(other: StepAndCost): Int {
return cost.compareTo(other.cost)
}
}
fun StepPos.createStepPosFor(x: Int, y: Int, input: List<String>, visited: Array<Boolean>): StepPos? {
val rowSize = input[0].length
val realX = x.coerceIn(0, rowSize - 1)
val realY = y.coerceIn(0, input.size - 1)
val thisValue = input.valueOf(this.x, this.y)
val value = input.valueOf(realX, realY)
val linearPos = realY * input.first().length + realX
return if ((this.x != realX || this.y != realY) && !visited[linearPos] && value.code <= thisValue.code + 1) {
StepPos(realX, realY)
} else {
null
}
}
fun StepPos.availableDirections(input: List<String>, visited: Array<Boolean>, currentCost: Long): List<StepAndCost> {
return buildList {
createStepPosFor(x - 1, y, input, visited)?.let {
add(StepAndCost(it, currentCost + 1))
}
createStepPosFor(x, y - 1, input, visited)?.let {
add(StepAndCost(it, currentCost + 1))
}
createStepPosFor(x + 1, y, input, visited)?.let {
add(StepAndCost(it, currentCost + 1))
}
createStepPosFor(x, y + 1, input, visited)?.let {
add(StepAndCost(it, currentCost + 1))
}
}
}
fun findStarts(input: List<String>, chars: List<Char>): List<StepPos> {
return input.flatMapIndexed { y: Int, row: String ->
row.withIndex().filter { it.value in chars }.map { StepPos(it.index, y) }
}
}
fun List<String>.valueOf(x: Int, y: Int, mapStartEnd: Boolean = true): Char {
val value = this[y][x]
return if (mapStartEnd) {
when (value) {
'S' -> 'a'
'E' -> 'z'
else -> value
}
} else {
value
}
}
class OrderedLinkedList<T : Comparable<T>> : LinkedList<T>() {
override fun add(element: T): Boolean {
val itr = listIterator()
while (true) {
if (!itr.hasNext()) {
itr.add(element)
return true
}
if (itr.next() > element) {
itr.previous()
itr.add(element)
return true
}
}
}
override fun addAll(elements: Collection<T>): Boolean {
elements.forEach { add(it) }
return true
}
}
fun stepsToEnd(input: List<String>, pos: StepPos): Long {
val linearSize = input.size * input.first().length
val paths = OrderedLinkedList<StepAndCost>()
val visited = Array(linearSize) { false }
val shortest = mutableMapOf<StepPos, StepAndCost>()
paths.add(StepAndCost(pos, 0))
shortest[pos] = StepAndCost(pos, 0)
while (true) {
val current = paths.poll() ?: return Long.MAX_VALUE
val value = input.valueOf(current.step.x, current.step.y, false)
if (value == 'E') {
return current.cost
} else {
current.step.availableDirections(input, visited, current.cost).forEach {
if (it.cost < (shortest[it.step]?.cost ?: Long.MAX_VALUE)) {
shortest[it.step] = it
paths.add(it)
}
}
}
visited[current.step.linearPos(input)] = true
}
}
@OptIn(ExperimentalTime::class)
fun main() {
fun part1(input: List<String>): Long {
return findStarts(input, listOf('S')).minOf { stepsToEnd(input, it) }
}
fun part2(input: List<String>): Long {
return findStarts(input, listOf('S', 'a')).minOf { stepsToEnd(input, it) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
check(part1(testInput) == 31L) { "part1 check failed" }
check(part2(testInput) == 29L) { "part2 check failed" }
val input = readInput("Day12")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 6abd8ca89a1acce49ecc0ca8a51acd3969979464 | 4,155 | aoc2022 | Apache License 2.0 |
src/main/kotlin/aoc2019/TheNBodyProblem.kt | komu | 113,825,414 | false | {"Kotlin": 395919} | package komu.adventofcode.aoc2019
import komu.adventofcode.utils.choosePairs
import komu.adventofcode.utils.lcm3
import kotlin.math.abs
fun nBodyProblem(moons: List<Moon>, steps: Int): Int {
val pairs = moons.choosePairs()
repeat(steps) {
for ((m1, m2) in pairs) {
m1.applyGravity(m2)
m2.applyGravity(m1)
}
for (m in moons)
m.applyVelocity()
}
return moons.sumBy { it.energy }
}
fun nBodyProblem2(moons: List<Moon>) = lcm3(
period(moons.map { it.x.position }),
period(moons.map { it.y.position }),
period(moons.map { it.z.position })
)
fun period(xs: List<Int>): Long {
val states = xs.map { AxisState(it) }
val pairs = states.choosePairs()
val seen = mutableSetOf<List<AxisState>>()
var steps = 0L
while (seen.add(states.map { it.copy() })) {
for ((m1, m2) in pairs) {
m1.applyGravity(m2)
m2.applyGravity(m1)
}
for (m in states)
m.applyVelocity()
steps++
}
return steps
}
data class AxisState(var position: Int, var velocity: Int = 0) {
fun applyGravity(s: AxisState) {
velocity += gravity(position, s.position)
}
fun applyVelocity() {
position += velocity
}
companion object {
private fun gravity(a: Int, b: Int) = when {
a < b -> 1
a > b -> -1
else -> 0
}
}
}
class Moon(x: Int, y: Int, z: Int) {
val x = AxisState(x)
val y = AxisState(y)
val z = AxisState(z)
fun applyGravity(m: Moon) {
x.applyGravity(m.x)
y.applyGravity(m.y)
z.applyGravity(m.z)
}
fun applyVelocity() {
x.applyVelocity()
y.applyVelocity()
z.applyVelocity()
}
val energy: Int
get() = (abs(x.position) + abs(y.position) + abs(z.position)) * (abs(x.velocity) + abs(y.velocity) + abs(z.velocity))
}
| 0 | Kotlin | 0 | 0 | 8e135f80d65d15dbbee5d2749cccbe098a1bc5d8 | 1,950 | advent-of-code | MIT License |
src/day_11/kotlin/Day11.kt | Nxllpointer | 573,051,992 | false | {"Kotlin": 41751} | data class Monkey(
val itemWrorryLevels: MutableList<Long>,
val wrorryOperation: (Long) -> Long,
val testDivisor: Int,
val throwToTestSuccess: Int,
val throwToTestFailed: Int
) {
fun inspectItem() {
itemWrorryLevels[0] = wrorryOperation(itemWrorryLevels[0])
}
fun throwItem(monkeys: List<Monkey>) {
val testSucceeded = itemWrorryLevels[0] % testDivisor == 0L
val throwTo = if (testSucceeded) throwToTestSuccess else throwToTestFailed
monkeys[throwTo].itemWrorryLevels += itemWrorryLevels.removeAt(0)
}
}
fun playKeepAway(monkeys: List<Monkey>, rounds: Int, afterInspection: Monkey.() -> Unit): Long {
val inspectionCounts = MutableList(monkeys.size) { 0 }
repeat(rounds) {
monkeys.forEachIndexed { monkeyIndex, monkey ->
while (monkey.itemWrorryLevels.isNotEmpty()) {
monkey.inspectItem()
inspectionCounts[monkeyIndex]++
monkey.afterInspection()
monkey.throwItem(monkeys)
}
}
}
return inspectionCounts.sortedDescending().take(2).product()
}
fun part1(monkeys: List<Monkey>) {
val monkeyBusinessLevel = playKeepAway(monkeys, rounds = 20, afterInspection = {
// Calm down
itemWrorryLevels[0] /= 3L
})
println("Part 1: The level of monkey business is $monkeyBusinessLevel")
}
fun part2(monkeys: List<Monkey>) {
// By calculating the product of all divisors we get a number that is divisible by all divisors.
// This means that any number that is divisible by our product is a multiple of each divisor.
// We can use this to keep the wrorry level in a computable range while also being able to get correct test results.
val divisorsProduct = monkeys.map { it.testDivisor }.product()
val monkeyBusinessLevel = playKeepAway(monkeys, rounds = 10000, afterInspection = {
itemWrorryLevels[0] %= divisorsProduct
})
println("Part 2: The level of monkey business is $monkeyBusinessLevel")
}
fun Collection<Monkey>.deepCopy() = map { monkey ->
monkey.copy(itemWrorryLevels = monkey.itemWrorryLevels.toMutableList())
}
fun main() {
val monkeys = getAOCInput { rawInput ->
rawInput.trim()
.split("\n\n")
.map { it.split("\n") }
.map { monkeyLines ->
val itemWrorryLevels = monkeyLines[1]
.splitInTwo(": ")
.second
.split(", ")
.map { it.toLong() }
.toMutableList()
val operation: (Long) -> Long = monkeyLines[2]
.splitInTwo("= old ")
.second
.splitInTwo(" ")
.let { (operator, other) ->
{ old ->
val number = if (other == "old") old else other.toLong()
when (operator) {
"+" -> old + number
"*" -> old * number
else -> throw IllegalArgumentException("Unknown operator $operator")
}
}
}
fun String.lastInt() = split(" ").last().toInt()
val testDivisor = monkeyLines[3].lastInt()
val throwToTestSuccess = monkeyLines[4].lastInt()
val throwToTestFailure = monkeyLines[5].lastInt()
Monkey(itemWrorryLevels, operation, testDivisor, throwToTestSuccess, throwToTestFailure)
}
}
part1(monkeys.deepCopy())
part2(monkeys.deepCopy())
}
| 0 | Kotlin | 0 | 0 | b6d7ef06de41ad01a8d64ef19ca7ca2610754151 | 3,693 | AdventOfCode2022 | MIT License |
src/Day25.kt | mrugacz95 | 572,881,300 | false | {"Kotlin": 102751} | import java.math.BigInteger
fun snafuToDecimal(snafu: String): BigInteger {
var base = 1.toBigInteger()
var sum = 0.toBigInteger()
for (digit in snafu.reversed()) {
val number = when (digit) {
'=' -> -2
'-' -> -1
'1' -> 1
'0' -> 0
'2' -> 2
else -> error("Unknown number")
}.toBigInteger()
sum += (number * base)
base *= 5.toBigInteger()
}
return sum
}
fun decimalToSNAFU(decimalNumber: BigInteger): String {
var number = decimalNumber
val base5 = mutableListOf<Int>()
while (number != 0.toBigInteger()) {
val digit = number % 5.toBigInteger()
number /= 5.toBigInteger()
base5.add(digit.toInt())
}
val snafu = (base5 + listOf(0)).toMutableList()
for (i in base5.indices) {
while (snafu[i].toString().toInt() > 2) {
snafu[i + 1] += 1
snafu[i] -= 5
}
while (snafu[i].toString().toInt() < -2) {
snafu[i + 1] -= 1
snafu[i] += 5
}
}
val result = snafu.reversed().map {
when (it) {
1 -> '1'
2 -> '2'
0 -> '0'
-1 -> '-'
-2 -> '='
else -> error("unknown digit $it in $decimalNumber")
}
}.joinToString("").let {
if (it.first() == '0') {
it.drop(1)
} else {
it
}
}
return result
}
fun main() {
val decimalNumbers = listOf(
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 2022, 12345, 314159265,
1747, 906, 198
).map { it.toBigInteger() }
val snafuNumbers = listOf(
"1", "2", "1=", "1-", "10", "11", "12", "2=", "2-", "20", "1=0", "1-0", "1=11-2", "1-0---0", "1121-1110-1=0",
"1=-0-2", "12111", "2=0="
)
for ((dec, snafu) in decimalNumbers.zip(snafuNumbers)) {
assert(decimalToSNAFU(dec) == snafu)
assert(snafuToDecimal(snafu) == dec)
}
fun part1(input: List<String>): String {
return input.map { snafuToDecimal(it) }.reduce { acc, it -> acc + it }.let {
decimalToSNAFU(it)
}
}
val testInput = readInput("Day25_test")
val input = readInput("Day25")
assert(part1(testInput), "2=-1=0")
println(part1(input))
}
// Time: 01:00 | 0 | Kotlin | 0 | 0 | 29aa4f978f6507b182cb6697a0a2896292c83584 | 2,341 | advent-of-code-2022 | Apache License 2.0 |
gcj/y2020/round1a/c_small.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package gcj.y2020.round1a
private fun solve(): Long {
val (hei, wid) = readInts()
val a = List(hei) { readInts().toIntArray() }
var ans = 0L
while (true) {
val eliminated = mutableListOf<Pair<Int, Int>>()
for (x in 0 until hei) for (y in 0 until wid) if (a[x][y] > 0) {
fun nei(d: Int): Int? {
var xx = x; var yy = y
while (true) {
xx += DX[d]; yy += DY[d]
val v = a.getOrNull(xx)?.getOrNull(yy) ?: return null
if (v > 0) return v
}
}
val found: List<Int> = DX.indices.mapNotNull { nei(it) }
if (a[x][y] * found.size < found.sum()) eliminated.add(x to y)
}
ans += a.sumBy { it.sum() }
eliminated.forEach { (x, y) -> a[x][y] = 0 }
if (eliminated.isEmpty()) break
}
return ans
}
private val DX = intArrayOf(1, 0, -1, 0)
private val DY = intArrayOf(0, 1, 0, -1)
fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,077 | competitions | The Unlicense |
src/poyea/aoc/mmxxii/day19/Day19.kt | poyea | 572,895,010 | false | {"Kotlin": 68491} | package poyea.aoc.mmxxii.day19
import java.util.PriorityQueue
import kotlin.math.ceil
import kotlin.math.max
import poyea.aoc.utils.readInput
class Factory(val blueprint: Blueprint, val minutes: Int) {
fun search(): Int {
var max = 0
val queue = PriorityQueue<State>()
queue.add(State(minutes = minutes))
while (queue.isNotEmpty()) {
val state = queue.poll()
if (state.betterThan(max)) {
queue.addAll(state.nextStates())
}
max = max(max, state.geode + state.geodeRobots * (state.minutes - 1))
}
return max
}
private fun State.nextStates() = buildList {
if (blueprint.maxOreCost > oreRobots) {
add(next(blueprint.oreRobot))
}
if (blueprint.maxClayCost > clayRobots) {
add(next(blueprint.clayRobot))
}
if (clayRobots > 0 && blueprint.maxObsidianCost > obsidianRobots) {
add(next(blueprint.obsidianRobot))
}
if (obsidianRobots > 0) {
add(next(blueprint.geodeRobot))
}
}.filter { it.minutes > 0 }
}
data class State(
val ore: Int = 1,
val oreRobots: Int = 1,
val clay: Int = 0,
val clayRobots: Int = 0,
val obsidian: Int = 0,
val obsidianRobots: Int = 0,
val geode: Int = 0,
val geodeRobots: Int = 0,
val minutes: Int
) : Comparable<State> {
override fun compareTo(other: State) = other.geode.compareTo(geode)
fun next(robot: Robot): State {
val minutes = findTime(robot)
return copy(
ore = ore + oreRobots * minutes - robot.oreCost,
oreRobots = oreRobots + robot.oreRobotsBuilt,
clay = clay + clayRobots * minutes - robot.clayCost,
clayRobots = clayRobots + robot.clayRobotsBuilt,
obsidian = obsidian + obsidianRobots * minutes - robot.obsidianCost,
obsidianRobots = obsidianRobots + robot.obsidianRobotsBuilt,
geode = geode + geodeRobots * minutes,
geodeRobots = geodeRobots + robot.geodeRobotsBuilt,
minutes = this.minutes - minutes
)
}
fun betterThan(best: Int): Boolean {
val potential = (0..(minutes - 1)).sumOf { it + geodeRobots }
return geode + potential > best
}
private fun findTime(robot: Robot): Int {
val remainingOre = (robot.oreCost - ore).coerceAtLeast(0)
val remainingClay = (robot.clayCost - clay).coerceAtLeast(0)
val remainingObsidian = (robot.obsidianCost - obsidian).coerceAtLeast(0)
return maxOf(
ceil(remainingOre / oreRobots.toFloat()).toInt(),
ceil(remainingClay / clayRobots.toFloat()).toInt(),
ceil(remainingObsidian / obsidianRobots.toFloat()).toInt(),
) + 1
}
}
data class Blueprint(
val id: Int,
val oreRobot: Robot,
val clayRobot: Robot,
val obsidianRobot: Robot,
val geodeRobot: Robot
) {
val maxOreCost = maxOf(oreRobot.oreCost, clayRobot.oreCost, obsidianRobot.oreCost, geodeRobot.oreCost)
val maxClayCost = obsidianRobot.clayCost
val maxObsidianCost = geodeRobot.obsidianCost
companion object {
fun from(line: String): Blueprint {
val numbers = "\\d+".toRegex().findAll(line).map { it.value.toInt() }.toList()
return Blueprint(
id = numbers[0],
oreRobot = Robot(oreCost = numbers[1], oreRobotsBuilt = 1),
clayRobot = Robot(oreCost = numbers[2], clayRobotsBuilt = 1),
obsidianRobot = Robot(oreCost = numbers[3], clayCost = numbers[4], obsidianRobotsBuilt = 1),
geodeRobot = Robot(oreCost = numbers[5], obsidianCost = numbers[6], geodeRobotsBuilt = 1)
)
}
}
}
data class Robot(
val oreCost: Int = 0,
val clayCost: Int = 0,
val obsidianCost: Int = 0,
val oreRobotsBuilt: Int = 0,
val clayRobotsBuilt: Int = 0,
val obsidianRobotsBuilt: Int = 0,
val geodeRobotsBuilt: Int = 0,
)
fun part1(input: String): Int {
return input.split("\n")
.map(Blueprint::from)
.sumOf { it.id * Factory(it, minutes = 24).search() }
}
fun part2(input: String): Int {
return input.split("\n")
.map(Blueprint::from)
.take(3)
.map { Factory(it, minutes = 32).search() }
.reduce(Int::times)
}
fun main() {
println(part1(readInput("Day19")))
println(part2(readInput("Day19")))
}
| 0 | Kotlin | 0 | 1 | fd3c96e99e3e786d358d807368c2a4a6085edb2e | 4,536 | aoc-mmxxii | MIT License |
src/Day04/Day04.kt | rooksoto | 573,602,435 | false | {"Kotlin": 16098} | package Day04
import profile
import readInputActual
import readInputTest
private const val DAY = "Day04"
fun main() {
fun part1(input: List<String>): Int =
toFormattedSectionLists(input)
.count {
it.first.containsAll(it.second) || it.second.containsAll(it.first)
}
fun part2(input: List<String>): Int =
toFormattedSectionLists(input)
.count {
it.first.intersect(it.second.toSet()).isNotEmpty()
}
val testInput = readInputTest(DAY)
val input = readInputActual(DAY)
check(part1(testInput) == 2)
profile(shouldLog = true) {
println("Part 1: ${part1(input)}")
} // Answer: 450 @ 39ms
check(part2(testInput) == 4)
profile(shouldLog = true) {
println("Part 2: ${part2(input)}")
} // Answer: 837 @ 46ms
}
private fun toFormattedSectionLists(
input: List<String>
): List<Pair<List<Int>, List<Int>>> =
input.map(::toSectionStringPairs)
.map(::toIntRangePairs)
.map(::toSectionListPairs)
private fun toSectionStringPairs(
input: String
): Pair<String, String> =
with(input.split(",")) {
Pair(first(), last())
}
private fun toIntRangePairs(
stringPair: Pair<String, String>
): Pair<IntRange, IntRange> {
val (firstRangeStart, firstRangeEnd) = stringPair.first.split("-")
val (secondRangeStart, secondRangeEnd) = stringPair.second.split("-")
return Pair(
firstRangeStart.toInt()..firstRangeEnd.toInt(),
secondRangeStart.toInt()..secondRangeEnd.toInt()
)
}
private fun toSectionListPairs(
intRangePair: Pair<IntRange, IntRange>
): Pair<List<Int>, List<Int>> =
with(intRangePair) {
Pair(first.toList(), second.toList())
}
| 0 | Kotlin | 0 | 1 | 52093dbf0dc2f5f62f44a57aa3064d9b0b458583 | 1,772 | AoC-2022 | Apache License 2.0 |
src/Day02.kt | JIghtuse | 572,807,913 | false | {"Kotlin": 46764} | import java.lang.IllegalStateException
enum class Shape {
Rock,
Paper,
Scissors
}
fun opponentInputToShape(s: String): Shape =
when (s) {
"A" -> Shape.Rock
"B" -> Shape.Paper
"C" -> Shape.Scissors
else -> throw IllegalStateException("invalid opponent input $s")
}
fun ourInputToShape(s: String): Shape =
when (s) {
"X" -> Shape.Rock
"Y" -> Shape.Paper
"Z" -> Shape.Scissors
else -> throw IllegalStateException("invalid our input $s")
}
fun scoreForShape(shape: Shape) =
when (shape) {
Shape.Rock -> 1
Shape.Paper -> 2
Shape.Scissors -> 3
}
fun scoreForRound(me: Shape, opponent: Shape): Int {
if (me == opponent) {
return 3 // draw
}
return when (me to opponent) {
(Shape.Rock to Shape.Scissors) -> 6 // win
(Shape.Scissors to Shape.Paper) -> 6 // win
(Shape.Paper to Shape.Rock) -> 6 // win
else -> 0 // lost
}
}
fun main() {
fun scoreForTwoShapes(me: Shape, opponent: Shape) =
scoreForShape(me) + scoreForRound(me, opponent)
fun part1(input: List<String>): Int =
input.sumOf {
val (s, t) = it.split(" ")
val ourShape = ourInputToShape(t)
val opponentShape = opponentInputToShape(s)
scoreForTwoShapes(ourShape, opponentShape)
}
fun determineShape(opponent: Shape, expectedOutcome: String) =
when (opponent to expectedOutcome) {
Shape.Rock to "Z" -> Shape.Paper
Shape.Scissors to "Z" -> Shape.Rock
Shape.Paper to "Z" -> Shape.Scissors
Shape.Rock to "X" -> Shape.Scissors
Shape.Scissors to "X" -> Shape.Paper
Shape.Paper to "X" -> Shape.Rock
else -> opponent
}
fun part2(input: List<String>): Int =
input.sumOf {
val (s, t) = it.split(" ")
val opponentShape = opponentInputToShape(s)
val ourShape = determineShape(opponentShape, t)
scoreForTwoShapes(ourShape, opponentShape)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8f33c74e14f30d476267ab3b046b5788a91c642b | 2,358 | aoc-2022-in-kotlin | Apache License 2.0 |
leetcode/src/offer/Offer61.kt | zhangweizhe | 387,808,774 | false | null | package offer
fun main() {
// 剑指 Offer 61. 扑克牌中的顺子
// https://leetcode-cn.com/problems/bu-ke-pai-zhong-de-shun-zi-lcof/
println(isStraight2(intArrayOf(1,2,5,0,3)))
}
/**
* 排序,遍历排序后的数组
* 计算 0 的数量 zeroCount
* 遍历到非0元素时:1)如果 nums[i] == nums[i+1],则 return false
* 2)如果 nums[i+1] - nums[i] > 1,
* 说明相邻的两个数不是连续的,中间的间隙需要 zeroCount 来补,所以执行 zeroCount -= (nums[i+1] - nums[i] - 1)
* 最后如果 zeroCount >= 0,表示 0 的个数足够补充间隙,return true,否则 return false
*/
fun isStraight(nums: IntArray): Boolean {
nums.sort()
var zeroCount = 0
for (i in 0 until (nums.size - 1)) {
if (nums[i] == 0) {
zeroCount++
}else if (nums[i+1] - nums[i] > 1){
zeroCount -= (nums[i+1] - nums[i] - 1)
}else if (nums[i+1] == nums[i]) {
return false
}
}
return zeroCount >= 0
}
/**
* 组成顺子的充分条件是:
* 1)nums 中没有重复的数字(非0)
* 2)数组最大值 - 最小值 < 5
*/
fun isStraight1(nums: IntArray): Boolean {
nums.sort()
// 第一个非0元素的下标,即是非0的最小元素
var firstNoZeroIndex = 0
for (i in 0 until (nums.size - 1)) {
if (nums[i] == 0) {
firstNoZeroIndex++
}else {
if (nums[i] == nums[i+1]) {
// 非0的重复元素
return false
}
}
}
return nums[4] - nums[firstNoZeroIndex] < 5
}
fun isStraight2(nums: IntArray): Boolean {
var max = Int.MIN_VALUE
var min = Int.MAX_VALUE
var zeroCount = 0
for (i in nums) {
if (i == 0) {
zeroCount++
}else{
if (i == max || i == min) {
return false
}
if (i > max) {
max = i
}
if (i < min) {
min = i
}
}
}
return max - min < 5
} | 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 2,073 | kotlin-study | MIT License |
src/main/kotlin/io/github/mikaojk/day3/part2/day3Part2.kt | MikAoJk | 573,000,620 | false | {"Kotlin": 15562} | package io.github.mikaojk.day3.part2
import io.github.mikaojk.common.getFileAsString
import java.util.Locale
fun day3Part2(): Int {
val rucksacksItems = getFileAsString("src/main/resources/day3/rucksacksItems.txt")
val rucksacks = rucksacksItems.split("\\n".toRegex()).mapIndexed { index, rucksacksItems ->
Rucksack(
number = index,
firstCompartment = Items(items = rucksacksItems.slice(0 until (rucksacksItems.length / 2))),
secoundCompartment = Items(items = rucksacksItems.slice((rucksacksItems.length / 2) until (rucksacksItems.length)))
)
}
val groupedRucksacks = rucksacks.chunked(3)
val sameItemsInGroup = groupedRucksacks.map {
findSameItem(it)
}
val sumForEachRucksack = sameItemsInGroup.flatMap { charList ->
charList.map { char ->
findPriorityValueForItem(char)
}
}
return sumForEachRucksack.sum()
}
fun findPriorityValueForItem(item: Char): Int {
return if (item.isUpperCase()) {
PriorityUpperCase.values().find { it.name == item.toString() }!!.value
} else {
(PriorityUpperCase.values().find { it.name == (item.uppercase(Locale.getDefault())) }!!.value) - 26
}
}
fun findSameItem(rucksacks: List<Rucksack>): List<Char> {
val rucksacksItem = rucksacks.map { rucksack ->
rucksack.firstCompartment.items + rucksack.secoundCompartment.items
}
return findSameItem(rucksacksItem[0], rucksacksItem[1], rucksacksItem[2])
}
fun findSameItem(items1: String, items2: String, items3: String): List<Char> {
val items1CharArray = items1.toCharArray()
val distinctSameItem =
items1CharArray.filter { item -> (items2.contains(item) && items3.contains(item)) }.toSet().toList();
return distinctSameItem
}
enum class PriorityUpperCase(val value: Int) {
A(27),
B(28),
C(29),
D(30),
E(31),
F(32),
G(33),
H(34),
I(35),
J(36),
K(37),
L(38),
M(39),
N(40),
O(41),
P(42),
Q(43),
R(44),
S(45),
T(46),
U(47),
V(48),
W(49),
X(50),
Y(51),
Z(52)
}
data class Rucksack(
val number: Int,
val firstCompartment: Items,
val secoundCompartment: Items
)
data class Items(
val items: String
) | 0 | Kotlin | 0 | 0 | eaa90abc6f64fd42291ab42a03478a3758568ecf | 2,297 | aoc2022 | MIT License |
src/main/kotlin/days/Day8Solution.kt | yigitozgumus | 434,108,608 | false | {"Kotlin": 17835} | package days
import BaseSolution
class Day8Solution(inputList: List<String>) : BaseSolution(inputList) {
val signals = inputList.map { it.split("|").first().split(" ").filterNot { it == "" }.map { it.trim() } }
private val output = inputList.map {
it.split("|")[1].split(" ").filterNot { it == "" }.map { it.trim() }
}
override fun part1() {
println(output.flatten().count { listOf(2, 3, 4, 7).contains(it.length) })
}
override fun part2() {
signals.mapIndexed { index, signal ->
val numberMap = MutableList<String>(10) { "" }.apply { this[8] = "abcdefg" } // add 8
with(signal) {
find { it.length == 2 }?.let { numberMap[1] = it } // add 1
find { it.length == 4 }?.let { numberMap[4] = it } // add 4
find { it.length == 3 }?.let { numberMap[7] = it } // add 7
filter { it.length == 6 }.forEach {
if (it.toSet().containsAll(numberMap[7].toSet()).not()) {
numberMap[6] = it // find 6
}
}
filter { it.length == 5 }.forEach {
if (it.toSet().containsAll(numberMap[1].toSet())) {
numberMap[3] = it // find 3
}
}
filter { it.length == 6 && it != numberMap[6] }.forEach {
if (it.toSet().containsAll(numberMap[3].toSet())) {
numberMap[9] = it // find 9
}
}
filter { it.length == 5 && it != numberMap[3] }.forEach {
if (numberMap[6].toSet().containsAll(it.toSet())) {
numberMap[5] = it// find 5
}
}
find { it.length == 5 && it != numberMap[3] && it != numberMap[5] }?.let {
numberMap[2] = it
}
find { it.length == 6 && it != numberMap[6] && it != numberMap[9] }?.let {
numberMap[0] = it
}
}
val outputString = output[index].map { output ->
val key = numberMap.find {
it.toSet().containsAll(output.toSet()) && output.toSet().containsAll(it.toSet())
}
numberMap.indexOf(key)
}
outputString.joinToString("").toInt()
}.sum().also {
println(it)
}
}
}
| 0 | Kotlin | 0 | 0 | c0f6fc83fd4dac8f24dbd0d581563daf88fe166a | 2,501 | AdventOfCode2021 | MIT License |
src/Day09.kt | iam-afk | 572,941,009 | false | {"Kotlin": 33272} | import kotlin.math.abs
import kotlin.math.max
import kotlin.math.sign
fun main() {
fun follow(t: Pair<Int, Int>, h: Pair<Int, Int>) =
t.first + (h.first - t.first).sign to t.second + (h.second - t.second).sign
fun List<String>.simulate(n: Int): Int {
val rope = Array(n) { 0 to 0 }
val visited = mutableSetOf(0 to 0)
for (move in this) {
val args = move.split(' ')
val (dx, dy) = when (args[0]) {
"U" -> 0 to 1
"D" -> 0 to -1
"L" -> -1 to 0
"R" -> 1 to 0
else -> error("unknown direction ${args[0]}")
}
repeat(args[1].toInt()) {
rope[0] = rope[0].first + dx to rope[0].second + dy
for (i in 1 until n) {
if (max(abs(rope[i - 1].first - rope[i].first), abs(rope[i - 1].second - rope[i].second)) > 1) {
rope[i] = follow(rope[i], rope[i - 1])
}
}
visited.add(rope.last())
}
}
return visited.size
}
fun part1(input: List<String>): Int = input.simulate(2)
fun part2(input: List<String>): Int = input.simulate(10)
// test if implementation meets criteria from the description, like:
val testInput1 = readInput("Day09_test1")
check(part1(testInput1) == 13)
val testInput2 = readInput("Day09_test2")
check(part2(testInput2) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b30c48f7941eedd4a820d8e1ee5f83598789667b | 1,575 | aockt | Apache License 2.0 |
src/main/kotlin/aoc2023/Day19.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2023
import utils.InputUtils
val parseRule = "(([xmas])([><])(\\d+):)?([a-zAR]+)".toRegex()
val parseWorkflow = "([a-z]+)\\{(($parseRule,?)+)}".toRegex()
val parsePresent = "\\{x=(\\d+),m=(\\d+),a=(\\d+),s=(\\d+)}".toRegex()
private data class Rule(val field: Char?, val test: Char?, val comparison: Int?, val target: String, val inverted:Boolean=false) {
val testFn: (Int) -> Boolean = when(test) {
'<' -> {{ it < (comparison ?: Int.MAX_VALUE)}}
'>' -> {{ it > (comparison ?: 0)}}
else -> {{true}}
}
val matcher: (Present) -> Boolean = when(field) {
'x' -> {{ testFn(it.x) }}
'm' -> {{ testFn(it.m) }}
'a' -> {{ testFn(it.a) }}
's' -> {{ testFn(it.s) }}
null -> {{true}}
else -> throw IllegalStateException("Bad rule $field")
}
fun match(present: Present): Boolean = matcher(present)
fun inRange(i: Int): Boolean {
val ret = testFn(i)
return if (inverted) !ret else ret
}
override fun toString(): String {
return (if (field != null) { "$field$test$comparison" }
else { "true" }) + "${if(inverted) "!" else ""}:$target"
}
}
private data class Workflow(val label:String, val rules: List<Rule>) {
fun applyTo(present: Present): String =
rules.first { it.match(present)}.target
}
private data class Present(val x: Int, val m: Int, val a: Int, val s: Int) {
fun score(): Int {
return x+m+a+s
}
}
private fun createRule(matcher: MatchResult): Rule {
val (_, field, test, comp, target) = matcher.destructured
return Rule(field.getOrNull(0),
test.getOrNull(0),
if (comp.isNotBlank()) comp.toInt() else null,
target)
}
private enum class Action { ACCEPT, REJECT}
private fun createWorkflow(matcher: MatchResult): Workflow {
val (label, rules) = matcher.destructured
val parsedRules = rules.split(",").parsedBy(parseRule, ::createRule).toList()
return Workflow(label, parsedRules)
}
private fun parsePresent(matcher: MatchResult): Present {
val (x,m,a,s) = matcher.destructured.toList().map { it.toInt() }
return Present(x,m,a,s)
}
private val codeResult = mapOf("R" to Action.REJECT, "A" to Action.ACCEPT)
private fun processPresent(present: Present, sorters: Map<String, Workflow>): Action {
return generateSequence("in") {
sorters[it]?.applyTo(present)
}.takeWhilePlusOne { it !in codeResult }
.last().let { codeResult[it] ?: throw IllegalStateException("Bad result $it") }
}
private data class Workflows(val workflows: Map<String, Workflow>) {
fun combinations(rules: List<Rule>): Long {
//println(rules)
val valid = "xmas".map { ch ->
val r = rules.filter { it.field == ch }
(1..4000).count { x -> r.all { it.inRange(x) } }.toLong()
}
//println("$valid (${valid.product()})")
return valid.product()
}
fun dfs() = dfs("in", listOf())
fun dfs( flow: String, soFar: List<Rule>): Long {
val tests = mutableListOf<Rule>()
return workflows[flow]?.rules?.map { rule ->
val ret = when(rule.target) {
"R" -> 0L
"A" -> combinations(soFar + tests + listOf(rule))
else -> dfs(rule.target, soFar + tests + listOf(rule))
}
tests.addLast(rule.copy(inverted = true))
ret
}?.sum() ?: 0
}
}
fun main() {
val testInput = """px{a<2006:qkq,m>2090:A,rfg}
pv{a>1716:R,A}
lnx{m>1548:A,A}
rfg{s<537:gd,x>2440:R,A}
qs{s>3448:A,lnx}
qkq{x<1416:A,crn}
crn{x>2662:A,R}
in{s<1351:px,qqz}
qqz{s>2770:qs,m<1801:hdj,R}
gd{a>3333:R,R}
hdj{m>838:A,pv}
{x=787,m=2655,a=1222,s=2876}
{x=1679,m=44,a=2067,s=496}
{x=2036,m=264,a=79,s=2244}
{x=2461,m=1339,a=466,s=291}
{x=2127,m=1623,a=2188,s=1013}""".trimIndent().split("\n")
fun part1(input: List<String>): Int {
val (listOfInstructions, parts) = input.toBlocksOfLines().toList()
val sorters = listOfInstructions.parsedBy(parseWorkflow, ::createWorkflow)
.associateBy { it.label }
val presents = parts.parsedBy(parsePresent, ::parsePresent)
return presents.filter {
processPresent(it, sorters) == Action.ACCEPT
}
.map { it.score() }
.sum()
}
fun part2(input: List<String>): Long {
val listOfInstructions = input.toBlocksOfLines().first()
val workflows = listOfInstructions.parsedBy(parseWorkflow, ::createWorkflow)
.associateBy { it.label }
return Workflows(workflows).dfs()
}
// test if implementation meets criteria from the description, like:
val testValue = part1(testInput)
println(testValue)
check(testValue == 19114)
println(part2(testInput))
val puzzleInput = InputUtils.downloadAndGetLines(2023, 19)
val input = puzzleInput.toList()
println(part1(input))
val start = System.currentTimeMillis()
println(part2(input))
println("Time: ${System.currentTimeMillis() - start}")
}
| 0 | Kotlin | 0 | 0 | 5abc9e479bed21ae58c093c8efbe4d343eee7714 | 5,062 | aoc-2022-kotlin | Apache License 2.0 |
src/day03/Day03.kt | tobihein | 569,448,315 | false | {"Kotlin": 58721} | package day03
import readInput
class Day03 {
fun part1(): Int {
val readInput = readInput("day03/input")
return part1(readInput)
}
fun part2(): Int {
val readInput = readInput("day03/input")
return part2(readInput)
}
fun part1(input: List<String>): Int = input.map { toPair(it) }.map { intersect(it) }.map { toValue(it) }.sum()
private fun intersect(pair: Pair<String, String>): Set<Char> {
val left = pair.first.toCharArray().toSet()
val right = pair.second.toCharArray().toSet()
val intersect = left.intersect(right)
return intersect
}
private fun toValue(set: Set<Char>): Int {
val char = set.first().code
return toValue(char)
}
private fun toValue(char: Int): Int {
if ('a'.code <= char && char <= 'z'.code) {
return char - 'a'.code + 1
}
if ('A'.code <= char && char <= 'Z'.code) {
return char - 'A'.code + 27
}
return 0
}
private fun toPair(s: String): Pair<String, String> {
val middle = s.length / 2
val left = s.substring(0, middle)
val right = s.substring(middle)
return Pair(left, right)
}
fun part2(input: List<String>): Int {
val groups = input.chunked(3)
var sum = 0
groups.forEach {
sum += it.map { it.toCharArray().toSet() }
.reduce { accumulator, chars -> accumulator.intersect(chars) }
.map { toValue(it.code) }.first()
}
return sum
}
}
| 0 | Kotlin | 0 | 0 | af8d851702e633eb8ff4020011f762156bfc136b | 1,586 | adventofcode-2022 | Apache License 2.0 |
src/Day09.kt | mathijs81 | 572,837,783 | false | {"Kotlin": 167658, "Python": 725, "Shell": 57} | private const val EXPECTED_1 = 114
private const val EXPECTED_2 = 2
private class Day09(isTest: Boolean) : Solver(isTest) {
fun part1() = readAsLines().sumOf { line ->
val numbers = line.splitInts()
val lineLists = mutableListOf(numbers)
while (true) {
val newLine = lineLists.last().windowed(2).map { it[1] - it[0] }
lineLists.add(newLine)
if (newLine.all { it == 0 }) {
break
}
}
var value = 0
for (i in lineLists.indices.reversed()) {
value = value + lineLists[i].last()
}
value
}
fun part2() = readAsLines().sumOf { line ->
val numbers = line.splitInts()
val lineLists = mutableListOf(numbers)
while (true) {
val newLine = lineLists.last().windowed(2).map { it[1] - it[0] }
lineLists.add(newLine)
if (newLine.all { it == 0 }) {
break
}
}
var value = 0
for (i in lineLists.indices.reversed()) {
value = lineLists[i].first() - value
}
value
}
}
fun main() {
val testInstance = Day09(true)
val instance = Day09(false)
testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } }
println("part1 ANSWER: ${instance.part1()}")
testInstance.part2().let {
check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" }
println("part2 ANSWER: ${instance.part2()}")
}
}
| 0 | Kotlin | 0 | 2 | 92f2e803b83c3d9303d853b6c68291ac1568a2ba | 1,523 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/eu/michalchomo/adventofcode/year2023/Day11.kt | MichalChomo | 572,214,942 | false | {"Kotlin": 56758} | package eu.michalchomo.adventofcode.year2023
import eu.michalchomo.adventofcode.Day
import eu.michalchomo.adventofcode.main
import eu.michalchomo.adventofcode.toCharMatrix
import kotlin.math.max
import kotlin.math.min
object Day11 : Day {
override val number: Int = 11
override fun part1(input: List<String>): String = solve(input)
override fun part2(input: List<String>): String = solve(input, emptySpaceExpansionFactor = 1_000_000)
private fun solve(input: List<String>, emptySpaceExpansionFactor: Int = 2): String =
input.toCharMatrix().let { matrix ->
val emptyRowsIndices = matrix.asSequence()
.mapIndexedNotNull { i, row -> if (row.toSet().size == 1) i else null }
.toList()
val emptyColsIndices = (0..<matrix[0].size).asSequence()
.mapNotNull { j -> if (matrix.indices.all { row -> matrix[row][j] == '.' }) j else null }
.toList()
val galaxies = matrix.asSequence()
.flatMapIndexed { i, row ->
val rowOffset = emptyRowsIndices.count { it < i } * (emptySpaceExpansionFactor - 1)
row.asSequence().mapIndexedNotNull { j, c ->
if (c == '#') {
val colOffset = emptyColsIndices.count { it < j } * (emptySpaceExpansionFactor - 1)
(i + rowOffset).toLong() to (j + colOffset).toLong()
} else null
}.toList()
}
.mapIndexed { index, list -> index to list }
.toMap()
galaxies.values.indices.sumOf { i ->
((i + 1)..<galaxies.size).sumOf { j -> galaxies[i]!!.distanceTo(galaxies[j]!!) }
}
}.toString()
private fun Pair<Long, Long>.distanceTo(other: Pair<Long, Long>) =
(max(this.first, other.first) - min(this.first, other.first)) +
(max(this.second, other.second) - min(this.second, other.second))
}
fun main() {
main(Day11)
}
| 0 | Kotlin | 0 | 0 | a95d478aee72034321fdf37930722c23b246dd6b | 2,062 | advent-of-code | Apache License 2.0 |
src/main/kotlin/Day07.kt | goblindegook | 319,372,062 | false | null | package com.goblindegook.adventofcode2020
import com.goblindegook.adventofcode2020.extension.toIntOr
import com.goblindegook.adventofcode2020.input.load
fun main() {
val rules = load("/day07-input.txt")
println(containerTypeCount(rules, "shiny gold"))
println(bagCount(rules, "shiny gold"))
}
fun containerTypeCount(rules: String, bag: String): Int = rules
.lines()
.map { rule -> rule.split(" bags contain ").let { it[0] to it[1] } }
.containers(bag, emptySet())
.count()
private fun List<Pair<String, String>>.containers(type: String, previous: Set<String>): Set<String> =
partition { (_, contents) -> (previous + type).any { it in contents } }
.let { (found, remaining) ->
if (found.isEmpty()) previous
else remaining.containers(type, previous + found.map { (container) -> container })
}
fun bagCount(rules: String, bag: String): Int = rules
.lines()
.recursiveBagCount(0, listOf(bag to 1)) - 1
private fun List<String>.recursiveBagCount(total: Int, queue: List<Pair<String, Int>>): Int =
if (queue.isEmpty()) total
else queue[0].let { (type, quantity) ->
find { it.startsWith(type) }.orEmpty()
.split("bags contain", ",").drop(1)
.map(::parseContents)
.let { contents ->
recursiveBagCount(
total + quantity,
queue.drop(1) + contents.map { it.first to it.second * quantity }
)
}
}
private fun parseContents(line: String): Pair<String, Int> = line
.trim()
.split(" ")
.let { "${it[1]} ${it[2]}" to (it[0].toIntOr(0)) } | 0 | Kotlin | 0 | 0 | 85a2ff73899dbb0e563029754e336cbac33cb69b | 1,659 | adventofcode2020 | MIT License |
src/main/kotlin/be/tabs_spaces/advent2021/days/Day08.kt | janvryck | 433,393,768 | false | {"Kotlin": 58803} | package be.tabs_spaces.advent2021.days
import be.tabs_spaces.advent2021.days.Day08.SevenSegmentNumber.*
class Day08 : Day(8) {
companion object {
val uniqueSegments = listOf(ONE, FOUR, SEVEN, EIGHT)
val uniqueSegmentLengths = uniqueSegments.map { it.segments }
}
override fun partOne() = inputList
.map { it.split(" | ")[1] }
.flatMap { it.split(" ") }.map { it.length }
.count { it in uniqueSegmentLengths }
override fun partTwo() = inputList
.map {
val (patterns, displays) = it.split(" | ")
SignalPatterns(patterns.split(" ")) to ScrambledDisplays(displays.split(" "))
}.sumOf {
it.first.deduceMappings().valueFor(it.second)
}
enum class SevenSegmentNumber(val segments: Int, val stringRepresentation: String) {
ZERO(6, "0"),
ONE(2, "1"),
TWO(5, "2"),
THREE(5, "3"),
FOUR(4, "4"),
FIVE(5, "5"),
SIX(6, "6"),
SEVEN(3, "7"),
EIGHT(7, "8"),
NINE(6, "9")
}
data class SignalPatterns(val patterns: List<String>) {
private val frequencies = patterns.flatMap { it.toList() }
.groupingBy { it }
.eachCount()
.toList()
.sortedBy { it.second }
private val deducedMappings: MutableMap<String, SevenSegmentNumber> = mutableMapOf()
fun deduceMappings(): DeducedMappings {
deduceMappingsForUniqueLengths()
deduceTwo()
deduceThree()
deduceFive()
deduceZero()
deduceNine()
deduceSix()
return deducedMappings.toMap()
}
private fun deduceMappingsForUniqueLengths() = uniqueSegments.forEach { matchPatternByLength(it) }
private fun deduceTwo() = unmappedPatterns().first { !it.contains(frequencies.last().first) }.apply { deducedMappings[this] = TWO }
private fun deduceThree() = unmappedPatterns().first { it.length == 5 && it.hasAllCharsOf(SEVEN) }.apply { deducedMappings[this] = THREE }
private fun deduceFive() = matchPatternByLength(FIVE)
private fun deduceZero() = unmappedPatterns().first { !it.hasAllCharsOf(FIVE) }.apply { deducedMappings[this] = ZERO }
private fun deduceNine() = unmappedPatterns().first { it.hasAllCharsOf(SEVEN) }.apply { deducedMappings[this] = NINE }
private fun deduceSix() = unmappedPatterns().first().apply { deducedMappings[this] = SIX }
private fun unmappedPatterns() = patterns.filterNot { deducedMappings.containsKey(it) }
private fun matchPatternByLength(number: SevenSegmentNumber) = unmappedPatterns()
.first { it.length == number.segments }
.apply { deducedMappings[this] = number }
private fun String.hasAllCharsOf(number: SevenSegmentNumber) = deducedMappings.entries.first { it.value == number }.key.all { c -> c in this }
}
data class ScrambledDisplays(val displays: List<String>)
}
typealias DeducedMappings = Map<String, Day08.SevenSegmentNumber>
fun DeducedMappings.valueFor(displays: Day08.ScrambledDisplays): Int = displays.displays.joinToString("") { display ->
this.entries.first { display.length == it.key.length && it.key.all { c -> c in display } }.value.stringRepresentation
}.toInt() | 0 | Kotlin | 0 | 0 | f6c8dc0cf28abfa7f610ffb69ffe837ba14bafa9 | 3,347 | advent-2021 | Creative Commons Zero v1.0 Universal |
src/Day09.kt | karlwalsh | 573,854,263 | false | {"Kotlin": 32685} | import Direction.*
fun main() {
fun part1(input: List<String>): Int {
val motions = input.toMotions()
var head = Position(0, 0)
var tail = head
//Unique positions, containing the starting position
val uniquePositions: MutableSet<Position> = mutableSetOf(tail)
motions.forEach { (direction, steps) ->
repeat(steps) {
head = when (direction) {
UP -> head.copy(y = head.y + 1)
DOWN -> head.copy(y = head.y - 1)
LEFT -> head.copy(x = head.x - 1)
RIGHT -> head.copy(x = head.x + 1)
}
if (tail.isNotAdjacentTo(head)) {
while (tail.isNotAdjacentTo(head)) {
tail = tail.oneStepTowards(head)
}
uniquePositions.add(tail)
}
}
}
return uniquePositions.size
}
fun part2(input: List<String>): Int {
val motions = input.toMotions()
//Unique positions, containing the starting position
val uniquePositions: MutableSet<Position> = mutableSetOf(Position(0, 0))
//0 is the head, 9 is the tail
val rope = Array(10) { Position(0, 0) }
motions.forEach { (direction, steps) ->
repeat(steps) {
rope[0] = when (direction) {
UP -> rope[0].copy(y = rope[0].y + 1)
DOWN -> rope[0].copy(y = rope[0].y - 1)
LEFT -> rope[0].copy(x = rope[0].x - 1)
RIGHT -> rope[0].copy(x = rope[0].x + 1)
}
//Only consider moving knots if head and first knot are not adjacent
if (rope[1].isNotAdjacentTo(rope[0])) {
1.until(10).forEach { knot ->
while (rope[knot].isNotAdjacentTo(rope[knot - 1])) {
rope[knot] = rope[knot].oneStepTowards(rope[knot - 1])
}
}
}
uniquePositions.add(rope[9])
}
}
return uniquePositions.size
}
val input = readInput("Day09")
with(::part1) {
val exampleResult = this(example())
check(exampleResult == 13) { "Part 1 result was $exampleResult" }
println("Part 1: ${this(input)}")
}
with(::part2) {
val exampleResult = this(example())
check(exampleResult == 1) { "Part 2 result was $exampleResult" }
println("Part 2: ${this(input)}")
}
}
private fun List<String>.toMotions(): List<Motion> = this
.map { Motion(Direction.parse(it.substringBefore(' ')), it.substringAfter(' ').toInt()) }
private data class Position(val y: Int, val x: Int) {
fun isNotAdjacentTo(other: Position): Boolean = !isAdjacentTo(other)
fun isAdjacentTo(other: Position): Boolean =
(this.x == other.x || this.x == other.x - 1 || this.x == other.x + 1) &&
(this.y == other.y || this.y == other.y - 1 || this.y == other.y + 1)
fun oneStepTowards(other: Position): Position {
val nextY = if (this.y < other.y) this.y + 1 else if (this.y > other.y) this.y - 1 else this.y
val nextX = if (this.x < other.x) this.x + 1 else if (this.x > other.x) this.x - 1 else this.x
return Position(nextY, nextX)
}
}
private data class Motion(val direction: Direction, val steps: Int)
private enum class Direction {
UP, DOWN, LEFT, RIGHT;
companion object {
fun parse(direction: String): Direction = when (direction) {
"U" -> UP
"D" -> DOWN
"L" -> LEFT
"R" -> RIGHT
else -> throw IllegalArgumentException("Unknown direction $direction")
}
}
}
private fun example() = """
R 4
U 4
L 3
D 1
R 4
D 1
L 5
R 2
""".trimIndent().lines() | 0 | Kotlin | 0 | 0 | f5ff9432f1908575cd23df192a7cb1afdd507cee | 3,987 | advent-of-code-2022 | Apache License 2.0 |
src/day7/Day07.kt | dean95 | 571,923,107 | false | {"Kotlin": 21240} | package day7
import readInput
import kotlin.math.min
private fun main() {
fun extractDirectories(input: List<String>): Directory {
val rootDir = Directory("/")
val dirs = ArrayDeque<Directory>()
input.forEach { line ->
if (line.first() == '$') {
val parts = line.split(" ")
if (parts[1] == "cd") {
val (_, _, dirName) = parts
when (dirName) {
"/" -> {
dirs.clear()
dirs.add(rootDir)
}
".." -> {
dirs.removeLast()
}
else -> {
dirs.add(dirs.last().directories.find { it.name == dirName }!!)
}
}
}
} else {
val (first, second) = line.split(" ")
if (first == "dir") {
dirs.last().directories.add(Directory(second))
} else {
dirs.last().files.add(File(second, first.toLong()))
}
}
}
return rootDir
}
fun part1(input: List<String>): Long {
val rootDir = extractDirectories(input)
var totalSum = 0L
fun sums(rootDir: Directory): Long {
if (rootDir.directories.isEmpty()) {
val sum = rootDir.files.sumOf(File::size)
if (sum <= 100000) totalSum += sum
return sum
}
var directoriesSum = 0L
rootDir.directories.forEach {
val filesSize = sums(it)
directoriesSum += filesSize
}
val filesSize = rootDir.files.sumOf(File::size)
if (filesSize + directoriesSum <= 100000) totalSum += (filesSize + directoriesSum)
return directoriesSum + filesSize
}
sums(rootDir)
return totalSum
}
fun part2(input: List<String>): Long {
val rootDir = extractDirectories(input)
val dirSizes = mutableListOf<Long>()
fun sums(rootDir: Directory): Long {
if (rootDir.directories.isEmpty()) {
val filesSize = rootDir.files.sumOf(File::size)
dirSizes.add(filesSize)
return filesSize
}
var directoriesSum = 0L
rootDir.directories.forEach {
val filesSize = sums(it)
directoriesSum += filesSize
}
val filesSize = rootDir.files.sumOf(File::size)
dirSizes.add(directoriesSum + filesSize)
return directoriesSum + filesSize
}
val totalSpaceUsed = sums(rootDir)
val unusedSpaceSize = 70000000 - totalSpaceUsed
val sizeToBeDeleted = 30000000 - unusedSpaceSize
var currentMin = Long.MAX_VALUE
dirSizes.forEach {
if (it >= sizeToBeDeleted) {
currentMin = min(currentMin, it)
}
}
return currentMin
}
val testInput = readInput("day7/Day07_test")
check(part1(testInput) == 95437L)
check(part2(testInput) == 24933642L)
val input = readInput("day7/Day07")
println(part1(input))
println(part2(input))
}
private data class Directory(
val name: String,
val directories: MutableList<Directory> = mutableListOf(),
val files: MutableList<File> = mutableListOf()
)
private data class File(
val name: String,
val size: Long
) | 0 | Kotlin | 0 | 0 | 0ddf1bdaf9bcbb45116c70d7328b606c2a75e5a5 | 3,623 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | maquirag | 576,698,073 | false | {"Kotlin": 3883} | fun main() {
val day = "02"
fun moveScore(move: Char): Int =
mapOf('A' to 1, 'B' to 2, 'C' to 3)[move]!!
fun gameScore(p1: Char, p2: Char) = when (p2 - p1) {
0 -> 3
1, -2 -> 6
else -> 0
}
fun determineMove(p1: Char, strategy: Char): Char = when (strategy) {
'X' -> mapOf('A' to 'C', 'B' to 'A', 'C' to 'B')[p1]!!
'Z' -> mapOf('A' to 'B', 'B' to 'C', 'C' to 'A')[p1]!!
else -> p1
}
fun part1(input: List<String>): Int =
input.map { it.split(" ")}
.map { (p1, p2) ->
val move1 = p1.first()
val move2 = p2.first() - ('X' - 'A')
moveScore(move2) + gameScore(move1, move2) }
.sum()
fun part2(input: List<String>): Int =
input.map { it.split(" ")}
.map { (p1, p2) ->
val move1 = p1.first()
val move2 = p2.first().let { determineMove(move1, it) }
moveScore(move2) + gameScore(move1, move2) }
.sum()
val testInput = readInput("Day${day}_Test")
val input = readInput("Day${day}")
val test1 = part1(testInput)
check(test1 == 15)
println("Part 1 => ${part1(input)}")
val test2 = part2(testInput)
check(test2 == 12)
println("Part 2 => ${part2(input)}")
} | 0 | Kotlin | 0 | 0 | 23403172e909f8fb0c87e953d06fc0921c75fc32 | 1,371 | aoc2022-kotlin | Apache License 2.0 |
src/Day09.kt | jvmusin | 572,685,421 | false | {"Kotlin": 86453} | import kotlin.math.abs
fun main() {
val dx = mapOf(
'U' to 0,
'D' to 0,
'L' to -1,
'R' to 1
)
val dy = mapOf(
'U' to 1,
'D' to -1,
'L' to 0,
'R' to 0
)
fun part1(input: List<String>): Int {
var curHead = 0 to 0
var curTail = 0 to 0
val visited = LinkedHashSet<Pair<Int, Int>>().apply { add(0 to 0) }
for ((dir, times) in input.map { it.split(" ") }.map { it[0][0] to it[1].toInt() }) {
repeat(times) {
curHead = (curHead.first + dx[dir]!!) to (curHead.second + dy[dir]!!)
if (maxOf(abs(curHead.first - curTail.first), abs(curHead.second - curTail.second)) > 1) {
val moveX = curHead.first.compareTo(curTail.first)
val moveY = curHead.second.compareTo(curTail.second)
curTail = (curTail.first + moveX) to (curTail.second + moveY)
visited += curTail
}
}
}
return visited.size
}
fun part2(input: List<String>): Int {
val positions = mutableListOf<Pair<Int, Int>>().apply {
repeat(10) {
add(0 to 0)
}
}
val visited = LinkedHashSet<Pair<Int, Int>>().apply { add(0 to 0) }
for ((dir, times) in input.map { it.split(" ") }.map { it[0][0] to it[1].toInt() }) {
repeat(times) {
positions[0] = (positions[0].first + dx[dir]!!) to (positions[0].second + dy[dir]!!)
for (i in 1 until positions.size) {
val curHead = positions[i - 1]
val curTail = positions[i]
if (maxOf(abs(curHead.first - curTail.first), abs(curHead.second - curTail.second)) > 1) {
val moveX = curHead.first.compareTo(curTail.first)
val moveY = curHead.second.compareTo(curTail.second)
positions[i] = (curTail.first + moveX) to (curTail.second + moveY)
} else break
}
visited.add(positions.last())
}
}
return visited.size
}
@Suppress("DuplicatedCode")
run {
val day = String.format("%02d", 9)
val testInput = readInput("Day${day}_test")
val input = readInput("Day$day")
println("Part 1 test - " + part1(testInput))
println("Part 1 real - " + part1(input))
println("---")
println("Part 2 test - " + part2(testInput))
println("Part 2 real - " + part2(input))
}
}
| 1 | Kotlin | 0 | 0 | 4dd83724103617aa0e77eb145744bc3e8c988959 | 2,626 | advent-of-code-2022 | Apache License 2.0 |
src/day05/Day05.kt | zoricbruno | 573,440,038 | false | {"Kotlin": 13739} | package day05
import readInput
import java.util.*
import kotlin.collections.HashMap
fun findSpacer(input: List<String>): Int {
var blank_index = 0
while (input[blank_index] != "")
blank_index++
return blank_index
}
fun extractNumbersFromString(input: String): List<Int> {
return Regex("[0-9]+")
.findAll(input)
.map(MatchResult::value)
.map { it.toInt() }
.toList()
}
fun extractStacks(input: List<String>): HashMap<Int, Stack<Char>> {
val split_index = findSpacer(input)
val stack_names = extractNumbersFromString(input[split_index - 1])
val stacks = hashMapOf<Int, Stack<Char>>()
for (stack_name in stack_names) {
val stack = Stack<Char>()
for (i in split_index - 2 downTo 0) {
val value_index = 1 + (stack_name - 1) * 4
if (value_index >= input[i].length || input[i][value_index] == ' ')
break
stack.push(input[i][value_index])
}
stacks[stack_name] = stack
}
return stacks
}
fun extractMove(input: String): Triple<Int, Int, Int> {
val numbers = extractNumbersFromString(input)
return Triple(numbers[0], numbers[1], numbers[2])
}
fun performMove(repetition: Int, from: Stack<Char>, to: Stack<Char>) = repeat(repetition) { to.push(from.pop()) }
fun performBulkMove(repetition: Int, from: Stack<Char>, to: Stack<Char>) {
val bulkChars = mutableListOf<Char>()
repeat(repetition) {
bulkChars.add(from.pop())
}
for (char in bulkChars.asReversed())
to.push(char)
}
fun extractTops(stacks: HashMap<Int, Stack<Char>>) = stacks.map { it.value.pop() }.joinToString("")
fun part1(input: List<String>): String {
val moves_index = findSpacer(input) + 1
val stacks = extractStacks(input)
for (i in moves_index until input.size) {
val (repetitions, from_name, to_name) = extractMove(input[i])
performMove(repetitions, stacks[from_name]!!, stacks[to_name]!!)
}
return extractTops(stacks)
}
fun part2(input: List<String>): String {
val moves_index = findSpacer(input) + 1
val stacks = extractStacks(input)
for (i in moves_index until input.size) {
val (repetitions, from_name, to_name) = extractMove(input[i])
performBulkMove(repetitions, stacks[from_name]!!, stacks[to_name]!!)
}
return extractTops(stacks)
}
fun main() {
val day = "Day05"
val test = "${day}_test"
val testInput = readInput(day, test)
val input = readInput(day, day)
val testFirst = part1(testInput)
println(testFirst)
check(testFirst == "CMZ")
println(part1(input))
val testSecond = part2(testInput)
println(testSecond)
check(testSecond == "MCD")
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 16afa06aff0b6e988cbea8081885236e4b7e0555 | 2,766 | kotlin_aoc_2022 | Apache License 2.0 |
src/main/java/com/barneyb/aoc/aoc2022/day11/MonkeyInTheMiddle.kt | barneyb | 553,291,150 | false | {"Kotlin": 184395, "Java": 104225, "HTML": 6307, "JavaScript": 5601, "Shell": 3219, "CSS": 1020} | package com.barneyb.aoc.aoc2022.day11
import com.barneyb.aoc.util.*
import com.barneyb.util.IntPair
import com.barneyb.util.Queue
import kotlin.text.toLong
fun main() {
Solver.execute(
::parse,
::partOne,
::partTwo, // 15310845153
)
}
data class Monkey(
val items: Queue<Long>,
val op: (Long) -> Long,
val modulus: Long,
val targets: IntPair,
) {
var inspectionCount = 0L
private set
fun hasItems() =
items.isNotEmpty()
fun inspect(): Long {
inspectionCount++
return items.dequeue()
}
fun addItem(item: Long) {
items.enqueue(item)
}
fun target(level: Long) =
if (level % modulus == 0L)
targets.first
else
targets.second
}
/*
Monkey 0:
Starting items: 79, 98
Operation: new = old * 19
Test: divisible by 23
If true: throw to monkey 2
If false: throw to monkey 3
*/
internal fun parse(input: String) =
input.toSlice()
.trim()
.split("\n\n")
internal fun parseMonkey(str: Slice): Monkey {
val lines = str.trim()
.lines()
val items = Queue<Long>().apply {
val l = lines[1]
l.drop(l.indexOf(':') + 1)
.split(',')
.map { it.trim().toLong() }
.forEach(this::enqueue)
}
val op = lines[2].trim().split(' ').drop(4).let { (op, str) ->
val operand = if (str[0] == 'o') null else str.toLong()
if (op[0] == '+') {
fun(a: Long) =
a + (operand ?: a)
} else if (op[0] == '*') {
fun(a: Long) =
a * (operand ?: a)
} else {
throw IllegalArgumentException("Unknown '$op $str' operation")
}
}
val modulus = lines[3].split(' ').last().toLong()
val targets = IntPair(
lines[4].trim().split(' ').last().toInt(),
lines[5].trim().split(' ').last().toInt(),
)
return Monkey(items, op, modulus, targets)
}
internal fun partOne(blocks: List<Slice>) =
part(blocks.map(::parseMonkey), 20) { it / 3 }
internal fun partTwo(blocks: List<Slice>) =
blocks.map(::parseMonkey).let { monkeys ->
monkeys.map(Monkey::modulus)
.fold(1, Long::times)
.let { modulus ->
part(monkeys, 10000) { it % modulus }
}
}
private fun part(
monkeys: List<Monkey>,
rounds: Int,
transform: (Long) -> Long
): Long {
repeat(rounds) {
monkeys.forEach { m ->
while (m.hasItems()) {
var level = m.inspect()
level = m.op(level)
level = transform(level)
monkeys[m.target(level)].addItem(level)
}
}
}
return monkeys
.map(Monkey::inspectionCount)
.sortedDescending()
.take(2)
.fold(1, Long::times)
}
| 0 | Kotlin | 0 | 0 | 8b5956164ff0be79a27f68ef09a9e7171cc91995 | 2,894 | aoc-2022 | MIT License |
advent-of-code-2023/src/Day21.kt | osipxd | 572,825,805 | false | {"Kotlin": 141640, "Shell": 4083, "Scala": 693} | import lib.matrix.Matrix
import lib.matrix.Position
import lib.matrix.contains
import lib.matrix.get
private const val DAY = "Day21"
fun main() {
fun testInput() = readInput("${DAY}_test")
fun input() = readInput(DAY)
"Part 1" {
part1(testInput(), steps = 6) shouldBe 16
measureAnswer { part1(input(), steps = 64) }
}
"Part 2" {
measureAnswer { part2(input()) }
}
}
private fun part1(input: Matrix<Char>, steps: Int): Int {
val start = Position(input.rowCount / 2, input.columnCount / 2)
var pots = setOf(start)
repeat(steps) {
pots = pots.flatMap { it.neighbors() }.filter { it in input && input[it] != '#' }.toSet()
}
return pots.size
}
private fun part2(input: Matrix<Char>): Long {
val patternSize = input.columnCount
val patternHalfSize = patternSize / 2
val start = Position(patternHalfSize, patternHalfSize)
var evenPlots = 0
var oddPlots = 0
val seen = mutableSetOf<Position>()
val queue = ArrayDeque<Pair<Int, Position>>()
val steps = patternSize + patternHalfSize
fun addNextStep(step: Int, position: Position) {
if (position !in seen && input.getInfinite(position) != '#') {
seen += position
if (step < steps) queue.addLast(step to position)
if (step % 2 == 0) evenPlots++ else oddPlots++
}
}
var a1 = 0
var a2 = 0
var lastStep = 0
addNextStep(step = 0, start)
while (queue.isNotEmpty()) {
val (step, position) = queue.removeFirst()
if (lastStep != step) {
lastStep = step
if (step == patternHalfSize) {
a1 = oddPlots
a2 = evenPlots
}
}
for (neighbor in position.neighbors()) addNextStep(step + 1, neighbor)
}
val b = oddPlots - a1 - a2 * 4 + 1 // Why +1? I don't know, but it works
val patternsCount = (26501365L - patternHalfSize) / patternSize
var count = a1.toLong()
for (i in 1L..patternsCount) {
val a = if (i % 2 == 0L) a1 else a2
count += a * i * 4 + b * i
}
return count
}
private fun Matrix<Char>.getInfinite(position: Position): Char {
val (row, col) = position
return this[row.mod(rowCount), col.mod(columnCount)]
}
private fun readInput(name: String) = readMatrix(name)
| 0 | Kotlin | 0 | 5 | 6a67946122abb759fddf33dae408db662213a072 | 2,350 | advent-of-code | Apache License 2.0 |
src/main/kotlin/com/dvdmunckhof/aoc/event2023/Day03.kt | dvdmunckhof | 318,829,531 | false | {"Kotlin": 195848, "PowerShell": 1266} | package com.dvdmunckhof.aoc.event2023
import com.dvdmunckhof.aoc.size
import java.util.ArrayList
import kotlin.math.max
import kotlin.math.min
class Day03(private val input: List<String>) {
fun solvePart1(): Int {
val regex = Regex("\\d+")
return input.withIndex().sumOf { (index, line) ->
regex.findAll(line)
.filter { hasAdjacentSymbol(index, it.range) }
.sumOf { it.value.toInt() }
}
}
fun solvePart2(): Int {
val gearMap = mutableMapOf<Pair<Int, Int>, MutableList<Int>>()
val regex = Regex("\\d+")
for ((index, line) in input.withIndex()) {
for (match in regex.findAll(line)) {
for (point in adjacentPoints(index, match.range)) {
if (input[point.first][point.second] == '*') {
gearMap.getOrPut(point, ::mutableListOf) += match.value.toInt()
}
}
}
}
return gearMap.values.filter { it.size == 2 }.sumOf { it[0] * it[1] }
}
private fun adjacentPoints(lineIndex: Int, range: IntRange): List<Pair<Int, Int>> {
val adjacentRange = max(0, range.first - 1)..min(range.last + 1, input[lineIndex].lastIndex)
val list = ArrayList<Pair<Int, Int>>(2 * range.size + 6)
if (lineIndex > 0) {
adjacentRange.mapTo(list) { i -> lineIndex - 1 to i }
}
if (lineIndex < input.lastIndex) {
adjacentRange.mapTo(list) { i -> lineIndex + 1 to i }
}
if (range.first != adjacentRange.first) {
list += lineIndex to adjacentRange.first
}
if (range.last != adjacentRange.last) {
list += lineIndex to adjacentRange.last
}
return list
}
private fun hasAdjacentSymbol(lineIndex: Int, range: IntRange): Boolean {
return adjacentPoints(lineIndex, range).any { (i, j) ->
val c = input[i][j]
c !in '0'..'9' && c != '.'
}
}
}
| 0 | Kotlin | 0 | 0 | 025090211886c8520faa44b33460015b96578159 | 2,040 | advent-of-code | Apache License 2.0 |
src/day06/Task.kt | dniHze | 433,447,720 | false | {"Kotlin": 35403} | package day06
import readInput
fun main() {
val input = readInput("day06")
println(solvePartOne(input))
println(solvePartTwo(input))
}
fun solvePartOne(input: List<String>): Long = input.createFishColony()
.processDays(80)
.count()
fun solvePartTwo(input: List<String>): Long = input.createFishColony()
.processDays(256)
.count()
private fun List<String>.createFishColony() = flatMap { it.split(',') }
.filter { value -> value.isNotEmpty() }
.map { value -> value.toInt() }
.groupBy { value -> value }
.mapValues { (_, values) -> values.size.toLong() }
private fun FishColony.processDays(count: Int) = (0 until count)
.fold(this) { colony, _ -> processADay(colony) }
private fun processADay(input: FishColony): FishColony = buildMap {
for ((key, value) in input) {
if (key > 0) {
this[key - 1] = value + (this[key - 1] ?: 0)
} else {
this[8] = value
this[6] = value + (this[6] ?: 0)
}
}
}
private fun FishColony.count() = map { (_, values) -> values }.sum()
private typealias FishColony = Map<Int, Long>
| 0 | Kotlin | 0 | 1 | f81794bd57abf513d129e63787bdf2a7a21fa0d3 | 1,129 | aoc-2021 | Apache License 2.0 |
src/day24/Day24.kt | gr4cza | 572,863,297 | false | {"Kotlin": 93944} | package day24
import Direction
import Position
import readInput
fun main() {
fun simulate(valley: Valley, startPosition: Position, endPos: Position): Int {
var i = 0
var possiblePositions = setOf(startPosition)
while (!possiblePositions.contains(endPos)) {
valley.step()
possiblePositions = possiblePositions.map { pos ->
valley.possiblePositions(pos)
}.flatten().toSet()
i++
}
return i
}
fun part1(input: List<String>): Int {
val valley = Valley(input)
return simulate(valley, valley.startingPos, valley.endingPos)
}
fun part2(input: List<String>): Int {
val valley = Valley(input)
val firstRound = simulate(valley, valley.startingPos, valley.endingPos)
val secondRound = simulate(valley, valley.endingPos, valley.startingPos)
val thirdRoundRound = simulate(valley, valley.startingPos, valley.endingPos)
return firstRound + secondRound + thirdRoundRound
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day24/Day24_test")
val input = readInput("day24/Day24")
// check((part1(testInput)).also { println(it) } == 18)
// println(part1(input))
check(part2(testInput).also { println(it) } == 54)
println(part2(input))
}
class Valley(
input: List<String>,
) {
private val width: Int
private val height: Int
val startingPos: Position
val endingPos: Position
private val blizzards: List<Blizzard>
init {
width = input.first().length
height = input.size
startingPos = Position(input.first().indexOfFirst { it == '.' }, 0)
endingPos = Position(input.last().indexOfFirst { it == '.' }, height - 1)
blizzards = input.mapIndexed { y, row ->
row.mapIndexedNotNull { x, cell ->
if (cell !in "#.") {
Blizzard(pos = Position(x, y), Direction.fromDir(cell))
} else {
null
}
}
}.flatten()
}
override fun toString(): String {
return (0 until height).joinToString("\n") { y ->
(0 until width).joinToString("") { x ->
val pos = Position(x, y)
val blizzardPositions = blizzards.map { it.pos }
when {
isWall(pos) -> "#"
pos in blizzardPositions -> drawBlizzard(blizzards.filter { it.pos == pos })
else -> "."
}
}
}
}
private fun drawBlizzard(filter: List<Blizzard>): String {
return if (filter.size == 1) {
toString(filter.first().dir)
} else {
filter.size.toString()
}
}
private fun isWall(pos: Position): Boolean {
return ((pos.x in listOf(0, width - 1)) || (pos.y in listOf(0, height - 1)))
&& pos !in listOf(startingPos, endingPos)
}
fun step() {
blizzards.forEach { blizz ->
val newPosition = blizz.pos.newPosition(blizz.dir)
if (isWall(newPosition)) {
when (blizz.dir) {
Direction.U -> blizz.pos = blizz.pos.copy(y = height - 2)
Direction.D -> blizz.pos = blizz.pos.copy(y = 1)
Direction.L -> blizz.pos = blizz.pos.copy(x = width - 2)
Direction.R -> blizz.pos = blizz.pos.copy(x = 1)
}
} else {
blizz.pos = newPosition
}
}
}
fun possiblePositions(pos: Position): List<Position> {
val blizzardPositions = blizzards.map { it.pos }.toSet()
return listOf(
pos,
pos.newPosition(Direction.U),
pos.newPosition(Direction.R),
pos.newPosition(Direction.D),
pos.newPosition(Direction.L),
).filter { it !in blizzardPositions && !isWall(it) }
}
}
private fun toString(dir: Direction): String {
return when (dir) {
Direction.U -> "^"
Direction.D -> "v"
Direction.L -> "<"
Direction.R -> ">"
}
}
private fun Direction.Companion.fromDir(cell: Char): Direction = when (cell) {
'^' -> Direction.U
'>' -> Direction.R
'v' -> Direction.D
'<' -> Direction.L
else -> error("Wrong input")
}
data class Blizzard(
var pos: Position,
val dir: Direction,
)
| 0 | Kotlin | 0 | 0 | ceca4b99e562b4d8d3179c0a4b3856800fc6fe27 | 4,496 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day12.kt | allwise | 574,465,192 | false | null | import Direction.*
import kotlin.math.abs
fun main() {
fun part1(input: List<String>): Int {
val hillClimb = HillClimb(input)
val res = hillClimb.process()
println("res1: $res")
return res
}
fun part2(input: List<String>): Int {
val hillClimb = HillClimb(input)
val res = hillClimb.process2()
println("res2: $res")
return res
}
// 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))
}
class HillClimb(val input:List<String>){
var startpos=(0 to 0)
var endPos =(0 to 0)
var endFound=false
var smallest =1000
var permutations =0
var heightMap :List<List<Int>> = input.mapIndexed { x, line -> line.toCharArray()
.mapIndexed{y,cha ->
if(cha=='S') {
startpos=(x to y)
0
}else if(cha=='E'){
endPos=(x to y)
('z'-'a')
}else {
cha-'a'
}
}
}
var distanceMap:List<MutableList<Int>> =resetMovement()
fun process():Int{
distanceMap[endPos.first][endPos.second]=1000
//heightMap.forEach(::println)
// distanceMap.forEach(::println)
println( "$startpos -> $endPos")
var e: List<Movement>? = (walk(startpos, 0))
println("minmoves for $startpos -> $endPos ${e?.size}")
println(smallest)
distanceMap.forEach(::println)
println()
println("permutatons $permutations")
return smallest
}
fun resetMovement(): List<MutableList<Int>> {
val distanceMap = heightMap.map{ it.map{-1}.toMutableList() }.toList()
distanceMap[endPos.first][endPos.second]=1000
return distanceMap
}
fun process2():Int{
distanceMap[endPos.first][endPos.second]=1000
heightMap.forEachIndexed{x, row ->
row.forEachIndexed{y, height ->
if(height==0){
distanceMap = resetMovement()
startpos=(x to y)
var e: List<Movement>? = (walk(startpos, 0))
distanceMap.forEach(::println)
println()
println("minmoves for $startpos -> $endPos ${e?.size}")
if(e != null && smallest > e.size ){
smallest=e.size
}
}
}
}
var e: List<Movement>? = (walk(startpos, 0))
println("minmoves for $startpos -> $endPos ${e?.size}")
println("smallest: $smallest")
println("permutatons $permutations")
return smallest
}
fun walk(currentPos:Pair<Int,Int>,moves:Int):List<Movement>?{
permutations++
/*if(permutations%1000000==0){
distanceMap.forEach(::println)
println()
}*/
/* if(moves>=smallest || distanceMap[currentPos.first][currentPos.second]<moves){
// println("canceling at size ${moves.size} ${moves.map { it.direction }.joinToString()}")
return null
}*/
if(isShorter(currentPos, moves)){
distanceMap[currentPos.first][currentPos.second]=moves
}else{
return null
}
val validMoves = listOf(currentPos.move(RIGHT),currentPos.move(UP),currentPos.move(DOWN), currentPos.move(LEFT))
.filterNotNull()
.filter{isShorter(it.toPos, moves+1) }
//.filterNot { moves.map{it.fromPos }.contains(it.toPos) }
.sortedBy { abs(endPos.first-it.toPos.first) + abs(endPos.second-it.toPos.second) }
if(isEnd(currentPos)){
println("found an end after ${moves} moves ")
if(moves<smallest){
println("found smaller! $smallest -> $moves")
smallest=moves
}
endFound=true
return emptyList<Movement>()
} //Cannot continue from this point
if(validMoves.isEmpty()){
distanceMap[currentPos.first][currentPos.second]=moves
// println("no more valid moves after ${moves.size} moves ")
return null
}else{
// launch{
val best = validMoves.map{
walk(it.toPos, moves + 1)?.plus(it)
}
.filterNotNull()
.sortedBy { it.size }
.firstOrNull()
//
return best
}
}
fun isEnd(currentPos:Pair<Int,Int>):Boolean{
if(currentPos.first==endPos.first && currentPos.second==endPos.second ){
println("found End $currentPos")
return true
}
return false
}
fun Pair<Int,Int>.move(direction:Direction):Movement?{
val currentPos= this
val toPos =
when(direction){
UP -> currentPos.first-1 to currentPos.second
DOWN -> currentPos.first+1 to currentPos.second
LEFT -> currentPos.first to currentPos.second-1
RIGHT -> currentPos.first to currentPos.second+1
}
if(checkDirection(currentPos,toPos)){
return Movement(currentPos,toPos,direction)
}
return null
}
fun isShorter(currentPos:Pair<Int,Int>, distance:Int): Boolean {
val shortestDistance =distanceMap[currentPos.first][currentPos.second]
if(shortestDistance==-1 || distance<shortestDistance){
return true
}
return false
}
fun checkDirection(currentPos:Pair<Int,Int>, toPos:Pair<Int,Int>):Boolean{
//if outside map
if( toPos.first<0 || toPos.first>=heightMap.size || toPos.second<0 || toPos.second>=heightMap.first().size){
return false
}
//if dist>1
if( abs(currentPos.first-toPos.first)>1 || abs(currentPos.second-toPos.second)>1){
return false
}
val from = heightMap[currentPos.first][currentPos.second]
val to = heightMap[toPos.first][toPos.second]
if(to>from+1 ){
return false
}
return true
}
}
data class Movement(val fromPos:Pair<Int,Int>,val toPos:Pair<Int,Int>, val direction:Direction )
enum class Direction{
UP,
DOWN,
LEFT,
RIGHT,
//END
}
| 0 | Kotlin | 0 | 0 | 400fe1b693bc186d6f510236f121167f7cc1ab76 | 6,511 | advent-of-code-2022 | Apache License 2.0 |
src/Day04.kt | jandryml | 573,188,876 | false | {"Kotlin": 6130} | private infix fun IntRange.isSubrange(other: IntRange) = (this - other).isEmpty()
private infix fun IntRange.isOverlapping(other: IntRange) = this.intersect(other).isNotEmpty()
private fun part1(input: List<String>): Int {
return transferToRanges(input)
.map { (a, b) -> a isSubrange b || b isSubrange a }
.count { it }
}
private fun part2(input: List<String>): Int {
return transferToRanges(input)
.map { (a, b) -> a isOverlapping b }
.count { it }
}
private fun transferToRanges(input: List<String>) = input.map {
it.split(",").map { rawRange ->
rawRange.split("-").let { (a, b) -> IntRange(a.toInt(), b.toInt()) }
}
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
println(part1(testInput))
println(part2(testInput))
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 90c5c24334c1f26ee1ae5795b63953b22c7298e2 | 1,027 | Aoc-2022 | Apache License 2.0 |
2021/src/day19/Solution.kt | vadimsemenov | 437,677,116 | false | {"Kotlin": 56211, "Rust": 37295} | package day19
import java.nio.file.Files
import java.nio.file.Paths
import kotlin.math.absoluteValue
import kotlin.system.measureTimeMillis
fun main() {
val rotations = createRotations()
fun fullMap(input: Input): MutableList<Pair<Point, List<Point>>> {
val fixed = mutableListOf(Point(0, 0, 0) to input.first())
val remaining = input.withIndex().drop(1).toMutableList()
val tried = Array(input.size) { HashSet<Int>() }
while (remaining.isNotEmpty()) {
remaining.removeAll { (index, beacons) ->
for ((scannerIndex, scannerAndBeacons) in fixed.withIndex()) {
if (scannerIndex in tried[index]) continue
tried[index] += scannerIndex
for (rotation in rotations) {
val rotated = beacons.map { it.rotate(rotation) }
val (shift, frequency) = buildMap {
for (a in rotated) {
for (b in scannerAndBeacons.second) {
this.compute(b - a) { _, prev ->
1 + (prev ?: 0)
}
}
}
}.maxByOrNull { it.value }!!
if (frequency >= 12) {
fixed += shift to rotated.map { it + shift }
return@removeAll true
}
}
}
return@removeAll false
}
}
return fixed
}
fun part1(input: Input): Int {
return fullMap(input).map { it.second }.flatten().toSet().size
}
fun part2(input: Input): Int {
val scanners = fullMap(input).map { it.first }
return scanners.maxOf { a ->
scanners.maxOf { b ->
(a - b).magnitude()
}
}
}
check(part1(readInput("test-input.txt")) == 79)
check(part2(readInput("test-input.txt")) == 3621)
val millis = measureTimeMillis {
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
System.err.println("Done in $millis ms.")
}
private fun createRotations(): List<List<List<Int>>> {
fun createMatrices(sin: Int, cos: Int): List<List<List<Int>>> = listOf(
listOf( // Rx
listOf(1, 0, 0),
listOf(0, cos, sin),
listOf(0, -sin, cos),
),
listOf( // Ry
listOf(cos, 0, -sin),
listOf( 0, 1, 0),
listOf(sin, 0, cos),
),
listOf( // Rz
listOf( cos, sin, 0),
listOf(-sin, cos, 0),
listOf( 0, 0, 1),
),
)
return listOf(
1 to 0,
0 to 1,
-1 to 0,
0 to -1,
).flatMap { (cos, sin) ->
createMatrices(sin, cos)
}.let {
buildSet {
for (a in it) for (b in it) add(a * b)
check(size == 24)
}.toList()
}
}
private operator fun List<List<Int>>.times(other: List<List<Int>>): List<List<Int>> {
require(this.first().size == other.size)
return List(this.size) { i ->
List(other.first().size) { j ->
other.indices.sumOf { k ->
this[i][k] * other[k][j]
}
}
}
}
private data class Point(val x: Int, val y: Int, val z: Int)
private operator fun Point.plus(other: Point) =
Point(x + other.x, y + other.y, z + other.z)
private operator fun Point.minus(other: Point) =
Point(x - other.x, y - other.y, z - other.z)
private fun Point.rotate(rotation: List<List<Int>>): Point {
val (x, y, z) = (listOf(listOf(x, y, z)) * rotation).first()
return Point(x, y, z)
}
private fun Point.magnitude(): Int = x.absoluteValue + y.absoluteValue + z.absoluteValue
private fun readInput(s: String): Input {
return buildList<MutableList<Point>> {
Files.newBufferedReader(Paths.get("src/day19/$s")).forEachLine { line ->
if (line == "--- scanner $size ---") {
add(mutableListOf())
} else if (line.isNotBlank()) {
val (x, y, z) = line.split(",").map { it.toInt() }
last().add(Point(x, y, z))
}
}
}
}
private typealias Input = List<List<Point>> | 0 | Kotlin | 0 | 0 | 8f31d39d1a94c862f88278f22430e620b424bd68 | 3,824 | advent-of-code | Apache License 2.0 |
src/Day09.kt | khongi | 572,983,386 | false | {"Kotlin": 24901} | import kotlin.math.abs
data class Position(val x: Int, val y: Int)
enum class Direction {
UP,
DOWN,
LEFT,
RIGHT
}
fun Char.toDirection(): Direction = when (this) {
'U' -> Direction.UP
'D' -> Direction.DOWN
'L' -> Direction.LEFT
'R' -> Direction.RIGHT
else -> error("$this is not a valid direction")
}
fun Position.move(direction: Direction, by: Int): Position {
return when (direction) {
Direction.UP -> copy(y = y + by)
Direction.DOWN -> copy(y = y - by)
Direction.LEFT -> copy(x = x - by)
Direction.RIGHT -> copy(x = x + by)
}
}
fun Position.move(byX: Int = 0, byY: Int = 0): Position = copy(x = x + byX, y = y + byY)
fun Position.moveTowards(towards: Position): Position {
if (isTouching(towards)) {
return this
}
val isSameX = x == towards.x
val isSameY = y == towards.y
val differenceX = towards.x - x
val differenceY = towards.y - y
val (byX, byY) = if (!isSameX && !isSameY) {
if (abs(differenceX) > abs(differenceY)) {
differenceX.towardsZero() to differenceY
} else if (abs(differenceY) > abs(differenceX)) {
differenceX to differenceY.towardsZero()
} else {
differenceX.towardsZero() to differenceY.towardsZero()
}
} else if (isSameX) {
0 to differenceY.towardsZero()
} else {
differenceX.towardsZero() to 0
}
return move(byX = byX, byY = byY)
}
fun Position.isTouching(other: Position): Boolean {
val distanceX = abs(other.x - x)
val distanceY = abs(other.y - y)
return distanceX <= 1 && distanceY <= 1
}
fun Int.towardsZero(): Int {
return if (this > 0) {
this - 1
} else if (this < 0) {
this + 1
} else {
0
}
}
fun main() {
fun part1(input: List<String>): Int {
var head = Position(0, 0)
var tail = Position(0, 0)
val visited = mutableSetOf<Position>()
input.map { it.split(" ") }.map { it[0][0].toDirection() to it[1].toInt() }.forEach { (dir, by) ->
repeat(by) {
head = head.move(dir, 1)
tail = tail.moveTowards(head)
visited.add(tail.copy())
}
}
return visited.size
}
fun part2(input: List<String>): Int {
val rope = buildList(10) { repeat(10) { add(Position(0, 0)) } }.toMutableList()
val visited = mutableSetOf(Position(0, 0))
input.map { it.split(" ") }.map { it[0][0].toDirection() to it[1].toInt() }.forEach { (dir, by) ->
repeat(by) {
rope[0] = rope[0].move(dir, 1)
for (i in 1 until rope.size) {
rope[i] = rope[i].moveTowards(rope[i - 1])
}
visited.add(rope.last())
}
}
return visited.size
}
val testInput = readInput("Day09_test")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val testInput2 = readInput("Day09_test2")
check(part2(testInput2) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 9cc11bac157959f7934b031a941566d0daccdfbf | 3,159 | adventofcode2022 | Apache License 2.0 |
untitled/src/main/kotlin/Day3.kt | jlacar | 572,845,298 | false | {"Kotlin": 41161} | class Day3(private val fileName: String) : AocSolution {
override val description: String get() = "Day 3 - Rucksack Reorg ($fileName)"
private val input = InputReader(fileName).lines
override fun part1() = input.sumOf { ruckPriority(it) }
override fun part2() = input.chunked(3).sumOf { groupBadgePriority(it) }
}
fun ruckPriority(line: String): Int {
val (compartment1, compartment2) = halve(line)
return priority(commonItemIn(compartment1, compartment2))
}
fun groupBadgePriority(input: List<String>) =
badgePriority( input.map { it.toSet() } )
fun badgePriority(group: List<Set<Char>>): Int {
val (elf1, elf2, elf3) = group
return priority(elf1.intersect(elf2).intersect(elf3).first())
}
fun commonItemIn(compartment1: String, compartment2: String) =
compartment1.toSet().intersect(compartment2.toSet()).first()
fun halve(line: String): Pair<String, String> {
val half = line.length / 2
return Pair(line.substring(0, half), line.substring(half))
}
private const val lowercase_a_priority = 1;
private const val UPPERCASE_A_priority = 27;
fun priority(ch: Char) = ch.lowercaseChar() - 'a' +
if (ch.isLowerCase()) lowercase_a_priority else UPPERCASE_A_priority
fun main() {
Day3("Day3-sample.txt") solution {
part1() shouldBe 157
part2() shouldBe 70
}
Day3("Day3.txt") solution {
part1() shouldBe 7446
part2() shouldBe 2646
}
Day3("Day3-alt.txt") solution {
part1() shouldBe 8349
part2() shouldBe 2681
}
} | 0 | Kotlin | 0 | 2 | dbdefda9a354589de31bc27e0690f7c61c1dc7c9 | 1,537 | adventofcode2022-kotlin | The Unlicense |
src/Day02.kt | akleemans | 574,937,934 | false | {"Kotlin": 5797} | fun main() {
val shapeValues = mapOf("X" to 1, "Y" to 2, "Z" to 3, "A" to 1, "B" to 2, "C" to 3)
fun part1(input: List<String>): Int {
var score = 0
for (line in input) {
val (opponent, mine) = line.split(" ")
score += shapeValues.getOrDefault(mine, 0)
val pairing = opponent + mine
if (pairing in listOf("AX", "BY", "CZ")) {
score += 3
} else if (pairing in arrayOf("CX", "AY", "BZ")) {
score += 6
}
}
return score
}
val loseAgainst = mapOf("A" to "C", "B" to "A", "C" to "B")
val winAgainst = mapOf("A" to "B", "B" to "C", "C" to "A")
fun part2(input: List<String>): Int {
var score = 0
for (line in input) {
val (opponent, outcome) = line.split(" ")
val mine: String
if (outcome.equals("X")) {
mine = loseAgainst.get(opponent)!!
} else if (outcome.equals("Y")) {
mine = opponent
} else {
mine = winAgainst.get(opponent)!!
}
score += shapeValues.getOrDefault(mine, 0)
val pairing = opponent + mine
if (pairing in listOf("AA", "BB", "CC")) {
score += 3
} else if (pairing in arrayOf("CA", "AB", "BC")) {
score += 6
}
}
return score
}
val testInput = readInput("Day02_test_input")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02_input")
println("Part 1: " + part1(input))
println("Part 2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | fa4281772d89a6d1cda071db4b6fb92fff5b42f5 | 1,692 | aoc-2022-kotlin | Apache License 2.0 |
src/main/kotlin/de/dikodam/calendar/Day05.kt | dikodam | 433,719,746 | false | {"Kotlin": 51383} | package de.dikodam.calendar
import de.dikodam.AbstractDay
import de.dikodam.executeTasks
import kotlin.time.ExperimentalTime
@ExperimentalTime
fun main() {
Day05().executeTasks()
}
class Day05 : AbstractDay() {
val input = readInputLines()
// val input = """0,9 -> 5,9
//8,0 -> 0,8
//9,4 -> 3,4
//2,2 -> 2,1
//7,0 -> 7,4
//6,4 -> 2,0
//0,9 -> 2,9
//3,4 -> 1,4
//0,0 -> 8,8
//5,5 -> 8,2""".lines()
override fun task1(): String {
val lineDefs = input
.map { parsetoLineDefinition(it) }
.filter { it.isHorizontalOrVertical() }
return lineDefs
.flatMap { it.toPoints() }
.groupBy { it }
.mapValues { (_, pointList) -> pointList.size }
.filterValues { pointCount -> pointCount > 1 }
.count()
.toString()
}
fun parsetoLineDefinition(line: String): LineDefinition {
val (startPoint, endPoint) = line.split(" -> ")
.map { numbersString ->
val (leftNumber, rightNumber) = numbersString.split(",").map { it.toInt() }
Point(leftNumber, rightNumber)
}
return LineDefinition(startPoint, endPoint)
}
override fun task2(): String {
return input
.map { parsetoLineDefinition(it) }
.flatMap { it.toPoints() }
.groupBy { it }
.mapValues { (_, pointList) -> pointList.size }
.filterValues { pointCount -> pointCount > 1 }
.count()
.toString()
}
}
data class LineDefinition(val start: Point, val end: Point) {
fun isHorizontalOrVertical(): Boolean =
start.x == end.x || start.y == end.y
fun toPoints(): List<Point> {
fun makeRange(start: Int, end: Int): IntRange =
if (start < end) {
start..end
} else {
end..start
}
if (start.x == end.x) {
return makeRange(start.y, end.y)
.map { y -> Point(start.x, y) }
}
if (start.y == end.y) {
return makeRange(start.x, end.x)
.map { x -> Point(x, start.y) }
}
return makeDiagonalPoints()
}
fun makeDiagonalPoints(): List<Point> {
val xSeq = if (start.x < end.x) (start.x..end.x) else start.x downTo end.x
val ySeq = if (start.y < end.y) (start.y..end.y) else start.y downTo end.y
return xSeq.toList()
.zip(ySeq.toList())
.map { (x, y) -> Point(x, y) }
}
}
data class Point(val x: Int, val y: Int) {
}
| 0 | Kotlin | 0 | 1 | 4934242280cebe5f56ca8d7dcf46a43f5f75a2a2 | 2,600 | aoc-2021 | MIT License |
src/Day14.kt | MarkTheHopeful | 572,552,660 | false | {"Kotlin": 75535} | import kotlin.math.sign
import kotlin.math.min
import kotlin.math.max
private const val EMPTY = 0
private const val BLOCKED = 1
private val MOVES_SAND = listOf(0 to 1, -1 to 1, 1 to 1)
private class Field(walls: List<List<Pair<Int, Int>>>, blockVoid: Boolean = false) {
enum class MoveResultState { MOVED, BLOCKED, FREE }
inner class MoveResult(val state: MoveResultState, val newPoint: Pair<Int, Int>? = null)
val minY = min(0, walls.minOf { it.minOf { it2 -> it2.second } })
val maxY = walls.maxOf { it.maxOf { it2 -> it2.second } } + if (blockVoid) 2 else 0
val minX =
min(walls.minOf { it.minOf { it2 -> it2.first } }, min(500, if (blockVoid) 500 - (maxY - minY + 2) else 500))
val maxX =
max(walls.maxOf { it.maxOf { it2 -> it2.first } }, max(500, if (blockVoid) 500 + (maxY - minY + 2) else 500))
val field = MutableList(maxX - minX + 1) { MutableList(maxY - minY + 1) { EMPTY } }
init {
val walls2 = if (blockVoid) walls + listOf(listOf(Pair(minX, maxY), Pair(maxX, maxY))) else walls
walls2.forEach {
var currentPoint = it[0] - Pair(minX, minY)
field[currentPoint] = BLOCKED
it.forEach { it2 ->
while (currentPoint != it2 - Pair(minX, minY)) {
currentPoint += Pair(
(it2.first - minX - currentPoint.first).sign, (it2.second - minY - currentPoint.second).sign
)
field[currentPoint] = BLOCKED
}
}
}
}
private fun canMove(from: Pair<Int, Int>, dir: Pair<Int, Int>): MoveResult {
val newPoint = from + dir
if (newPoint.first !in (0..(maxX - minX)) || newPoint.second !in (0..(maxY - minY)))
return MoveResult(MoveResultState.FREE)
if (field[newPoint] == BLOCKED) return MoveResult(MoveResultState.BLOCKED)
return MoveResult(MoveResultState.MOVED, newPoint)
}
fun dropSand(): Boolean {
var sandPoint = Pair(500, 0) - Pair(minX, minY)
if (field[sandPoint] == BLOCKED) return false
field[sandPoint] = BLOCKED
while (true) {
var movedRes = false
run moves@{
MOVES_SAND.forEach { dir ->
val moved = canMove(sandPoint, dir)
if (moved.state == MoveResultState.FREE) {
return@dropSand false
}
if (moved.state == MoveResultState.MOVED) {
movedRes = true
field[sandPoint] = EMPTY
sandPoint = moved.newPoint!!
field[sandPoint] = BLOCKED
return@moves
}
}
}
if (!movedRes) break
}
return true
}
}
fun main() {
fun howMuchSand(field: Field): Int {
var answer = 0
while (field.dropSand()) {
answer++
}
return answer
}
fun parseWalls(input: List<String>) =
input.map { it.split(" -> ").map { it2 -> it2.split(",") }.map { (x, y) -> Pair(x.toInt(), y.toInt()) } }
fun part1(input: List<String>): Int {
return howMuchSand(Field(parseWalls(input)))
}
fun part2(input: List<String>): Int {
return howMuchSand(Field(parseWalls(input), true))
}
// 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))
}
| 0 | Kotlin | 0 | 0 | 8218c60c141ea2d39984792fddd1e98d5775b418 | 3,682 | advent-of-kotlin-2022 | Apache License 2.0 |
src/Day19.kt | abeltay | 572,984,420 | false | {"Kotlin": 91982, "Shell": 191} | fun main() {
val ore = 0
val clay = 1
val obsidian = 2
val geode = 3
var best = 0
fun parseInput(input: String): List<List<Int>> {
val robots = input.substringAfter(": ")
val inputLineRegex =
"""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()
val (ore, clay, obsidian1, obsidian2, geode1, geode2) = inputLineRegex
.matchEntire(robots)
?.destructured
?: throw IllegalArgumentException("Incorrect input line $robots")
return listOf(
listOf(ore.toInt(), 0, 0, 0),
listOf(clay.toInt(), 0, 0, 0),
listOf(obsidian1.toInt(), obsidian2.toInt(), 0, 0),
listOf(geode1.toInt(), 0, geode2.toInt(), 0)
)
}
fun canBuild(inventory: List<Int>, item: List<Int>): Boolean {
for (i in inventory.indices) {
if (inventory[i] < item[i])
return false
}
return true
}
fun collect(robots: List<Int>, inventory: MutableList<Int>) {
for (i in robots.indices) {
inventory[i] += robots[i]
}
}
fun fastForwardToBuild(
blueprint: List<List<Int>>,
robots: MutableList<Int>,
inventory: MutableList<Int>,
time: Int,
build: Int
): Int {
var countdown = time
while (countdown > 0) {
countdown--
if (canBuild(inventory, blueprint[build])) {
for (i in inventory.indices) {
inventory[i] -= blueprint[build][i]
}
collect(robots, inventory)
robots[build]++
break
} else {
collect(robots, inventory)
}
}
return countdown
}
fun isBetterThanBest(robots: List<Int>, inventory: List<Int>, time: Int): Boolean {
val potentialProduction = (0 until time).sumOf { it + robots[geode] }
return inventory[geode] + potentialProduction > best
}
fun mineGeode(blueprint: List<List<Int>>, maxOre: Int, robots: List<Int>, inventory: List<Int>, time: Int): Int {
if (time == 0) {
best = listOf(best, inventory.last()).max()
return inventory.last()
}
var geodeCollected = 0
for (robotToBuild in 3 downTo 0) {
if (
(robotToBuild == ore && robots[ore] >= maxOre) ||
(robotToBuild == clay && robots[clay] >= blueprint[obsidian][clay]) ||
(robotToBuild == obsidian && (robots[clay] == 0 || robots[obsidian] >= blueprint[geode][obsidian])) ||
(robotToBuild == geode && robots[obsidian] == 0) ||
(!isBetterThanBest(robots, inventory, time))
) continue
val newRobots = robots.toMutableList()
val newInventory = inventory.toMutableList()
val timeLeft = fastForwardToBuild(blueprint, newRobots, newInventory, time, robotToBuild)
val newGeode = mineGeode(blueprint, maxOre, newRobots, newInventory, timeLeft)
geodeCollected = listOf(geodeCollected, newGeode).max()
}
return geodeCollected
}
fun part1(input: List<String>): Int {
val blueprints = mutableListOf<List<List<Int>>>()
for (it in input) {
blueprints.add(parseInput(it))
}
var answer = 0
for (i in blueprints.indices) {
best = 0
val maxOre = blueprints[i].maxOf { it[0] }
val geodesMined = mineGeode(blueprints[i], maxOre, listOf(1, 0, 0, 0), listOf(0, 0, 0, 0), 24)
answer += (i + 1) * geodesMined
}
return answer
}
fun part2(input: String): Int {
best = 0
val blueprint = parseInput(input)
val maxOre = blueprint.maxOf { it[0] }
val answer = mineGeode(blueprint, maxOre, listOf(1, 0, 0, 0), listOf(0, 0, 0, 0), 32)
return answer
}
val testInput = readInput("Day19_test")
check(part1(testInput) == 33)
check(part2(testInput[0]) == 56)
check(part2(testInput[1]) == 62)
val input = readInput("Day19")
println(part1(input))
val blueprint1 = part2(input[0])
val blueprint2 = part2(input[1])
val blueprint3 = part2(input[2])
println(blueprint1 * blueprint2 * blueprint3)
}
| 0 | Kotlin | 0 | 0 | a51bda36eaef85a8faa305a0441efaa745f6f399 | 4,492 | advent-of-code-2022 | Apache License 2.0 |
2021/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2021/day16/Day16.kt | sanderploegsma | 224,286,922 | false | {"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171} | package nl.sanderp.aoc.aoc2021.day16
import nl.sanderp.aoc.common.readResource
fun main() {
val input = readResource("Day16.txt")
.map { it.toString().toInt(16) }
.joinToString("") { it.toString(2).padStart(4, '0') }
val packets = Reader(input).next()
println("Part one: ${packets.versions.sum()}")
println("Part two: ${packets.value}")
}
private sealed class Packet(val version: Int) {
abstract val versions: List<Int>
abstract val value: Long
}
private class LiteralValue(version: Int, override val value: Long) : Packet(version) {
override val versions: List<Int> = listOf(version)
}
private enum class OperatorType { Sum, Product, Minimum, Maximum, GreaterThan, LessThan, EqualTo }
private class Operator(version: Int, val type: OperatorType, val packets: List<Packet>) : Packet(version) {
override val versions: List<Int>
get() = listOf(version).plus(packets.flatMap { it.versions })
override val value
get() = when (type) {
OperatorType.Sum -> packets.sumOf { it.value }
OperatorType.Product -> packets.fold(1L) { p, v -> p * v.value }
OperatorType.Minimum -> packets.minOf { it.value }
OperatorType.Maximum -> packets.maxOf { it.value }
OperatorType.GreaterThan -> if (packets[0].value > packets[1].value) 1L else 0L
OperatorType.LessThan -> if (packets[0].value < packets[1].value) 1L else 0L
OperatorType.EqualTo -> if (packets[0].value == packets[1].value) 1L else 0L
}
}
private class Reader(data: String) {
private var buffer = data
fun next(): Packet {
val version = readBits(3).toInt(2)
return when (val typeId = readBits(3).toInt(2)) {
0 -> Operator(version, OperatorType.Sum, readOperatorPackets())
1 -> Operator(version, OperatorType.Product, readOperatorPackets())
2 -> Operator(version, OperatorType.Minimum, readOperatorPackets())
3 -> Operator(version, OperatorType.Maximum, readOperatorPackets())
4 -> LiteralValue(version, readLiteralValue())
5 -> Operator(version, OperatorType.GreaterThan, readOperatorPackets())
6 -> Operator(version, OperatorType.LessThan, readOperatorPackets())
7 -> Operator(version, OperatorType.EqualTo, readOperatorPackets())
else -> throw IllegalArgumentException("Invalid type ID '$typeId'")
}
}
private fun readLiteralValue(): Long {
val bits = buildString {
while (buffer.first() == '1') {
val chunk = readBits(5)
append(chunk.drop(1))
}
append(readBits(5).drop(1))
}
return bits.toLong(2)
}
private fun readOperatorPackets(): List<Packet> = when (readBits(1)) {
"0" -> buildList {
val length = readBits(15).toLong(2)
val bufferStopSize = buffer.length - length
while (buffer.length > bufferStopSize) {
add(next())
}
}
"1" -> buildList {
val packets = readBits(11).toLong(2)
for (i in 1..packets) {
add(next())
}
}
else -> throw IllegalArgumentException()
}
private fun readBits(n: Int) = buffer.take(n).also { buffer = buffer.drop(n) }
}
| 0 | C# | 0 | 6 | 8e96dff21c23f08dcf665c68e9f3e60db821c1e5 | 3,381 | advent-of-code | MIT License |
src/Day20.kt | max-zhilin | 573,066,300 | false | {"Kotlin": 114003} | import java.util.*
fun main() {
fun part1(input: List<String>): Int {
val numbers = input.map { it.toInt() }
val positions = IntArray(input.size) { it }
val lastIndex = input.lastIndex
fun move(from: Int, to: Int) {
// 2 5 3 7 1 - from 1 to 3 -
// 2 3 7 5 1
// 0 1 2 3 4
// 0 3 1 2 4
// 2 5 3 7 0 - from 3 to 1
// 2 7 5 3 0
// 0 1 2 3 4
// 0 2 3 1 4
// 2 5 3 7 1 - 1 from 4 to 1 - (pos[i] + n) % size + 1
// 2 1 3 7 5
// 0 1 2 3 4
// 2 5 3 7 10 - 10 from 4 to 1 - (pos[i] + n - 1) % (size - 1) + 1
// 2 5 3 7 _ 2 5 3 7 2 5 3 7 2 5 (10) 3 7
// 0 1 2 3 4
if (from < to) {
for (i in 0..lastIndex)
if (positions[i] in from + 1..to) positions[i]--
} else {
for (i in 0..lastIndex)
if (positions[i] in to..from - 1) positions[i]++
}
}
numbers.forEachIndexed { index, num ->
val from = positions[index]
val to = if (num == 0) from
else if (num > 0) (from + (num - 1)) % lastIndex + 1
// else lastIndex + (from - lastIndex + (num + 1)) % lastIndex - 1
else lastIndex + (from - lastIndex + num) % lastIndex
move(from, to)
positions[index] = to
// val sorted = (0..lastIndex).associate { positions[it] to numbers[it] }.toSortedMap()
// println(sorted.toList().joinToString { it.second.toString() })
}
var sum = 0
sum += numbers[positions.indexOf((positions[numbers.indexOf(0)] + 1000) % (lastIndex + 1))]
sum += numbers[positions.indexOf((positions[numbers.indexOf(0)] + 2000) % (lastIndex + 1))]
sum += numbers[positions.indexOf((positions[numbers.indexOf(0)] + 3000) % (lastIndex + 1))]
return sum
}
fun part2(input: List<String>, key: Long): Long {
val numbers = input.map { it.toLong() * key }
val positions = LongArray(input.size) { it.toLong() }
val lastIndex = input.lastIndex
fun move(from: Long, to: Long) {
if (from < to) {
for (i in 0..lastIndex)
if (positions[i] in from + 1..to) positions[i]--
} else {
for (i in 0..lastIndex)
if (positions[i] in to..from - 1) positions[i]++
}
}
repeat(10) {
numbers.forEachIndexed { index, num ->
val from = positions[index]
val to = if (num == 0L) from
else if (num > 0) 1 + (from - 1 + num) % lastIndex
// else lastIndex + (from - lastIndex + (num + 1)) % lastIndex - 1
else lastIndex + (from - lastIndex + num) % lastIndex
move(from, to)
positions[index] = to
// val sorted = (0..lastIndex).associate { positions[it] to numbers[it] }.toSortedMap()
// println(sorted.toList().joinToString { it.second.toString() })
}
}
var sum = 0L
sum += numbers[positions.indexOf((positions[numbers.indexOf(0)] + 1000) % (lastIndex + 1))]
sum += numbers[positions.indexOf((positions[numbers.indexOf(0)] + 2000) % (lastIndex + 1))]
sum += numbers[positions.indexOf((positions[numbers.indexOf(0)] + 3000) % (lastIndex + 1))]
return sum
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day20_test")
// val testInput2 = readInput("Day20_test2")
// println(part1(testInput))
// check(part1(testInput2) == 33)
check(part1(testInput) == 3)
// println(part2(testInput, 811589153))
check(part2(testInput, 811589153) == 1623178306L)
@Suppress("UNUSED_VARIABLE")
val input = readInput("Day20")
// check(part2(input, 811589153)) == 656575624777L
// println(part1(input))
println(part2(input, 811589153))
}
| 0 | Kotlin | 0 | 0 | d9dd7a33b404dc0d43576dfddbc9d066036f7326 | 4,076 | AoC-2022 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.