path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/Day04.kt | michaelYuenAE | 573,094,416 | false | {"Kotlin": 74685} | fun main() {
val input = readInput("day4_input")
println(part2(input))
}
fun part1(input: List<String>): Int {
return input.map { it.split(",", "-").map { it.toInt() } }.count {
val (first, second, third, fourth) = it
println("first $first second $second third $third fourth $fourth")
(first in third..fourth && second in third..fourth) || (third in first..second && fourth in first..second)
}
}
fun part2(input: List<String>): Int {
return input.map { it.split(",", "-").map { it.toInt() } }.count {
val (first, second, third, fourth) = it
(first in third..fourth || second in third..fourth) || (third in first..second || fourth in first..second)
}
}
fun solvePart1(input: List<String>): Int {
var counter = 0
input.forEach {
val firstElfStart = it.split(',')[0].split('-')[0]
val firstElfEnd = it.split(',')[0].split('-')[1]
val secondElfStart = it.split(',')[1].split('-')[0]
val secondElfEnd = it.split(',')[1].split('-')[1]
println("first $firstElfStart second $firstElfEnd third $secondElfStart fourth $secondElfEnd")
val firstElfSet = mutableSetOf<Int>()
for (i in firstElfStart.toInt() .. firstElfEnd.toInt()) {
firstElfSet.add(i)
}
val secondElfSet = mutableSetOf<Int>()
for (i in secondElfStart.toInt() .. secondElfEnd.toInt()) {
secondElfSet.add(i)
}
println("firstElfSet $firstElfSet")
println("secondElfSet $secondElfSet")
if (firstElfSet.intersect(secondElfSet).isNotEmpty() || secondElfSet.intersect(firstElfSet).isNotEmpty()) {
counter++
}
}
return counter
} | 0 | Kotlin | 0 | 0 | ee521263dee60dd3462bea9302476c456bfebdf8 | 1,724 | advent22 | Apache License 2.0 |
src/main/kotlin/tr/emreone/adventofcode/days/Day19.kt | EmRe-One | 726,902,443 | false | {"Kotlin": 95869, "Python": 18319} | package tr.emreone.adventofcode.days
import tr.emreone.kotlin_utils.automation.Day
import tr.emreone.kotlin_utils.automation.extractAllIntegers
enum class Category(name: String) {
X("Extremely cool looking"),
M("Musical"),
A("Aerodynamic"),
S("Shiny")
}
typealias PotentialPart = Map<Category, IntRange>
fun PotentialPart.patch(category: Category, newRange: IntRange?): PotentialPart? {
return newRange?.let { patched ->
val parts = this.toMutableMap()
parts[category] = patched
parts.toMap()
}
}
fun PotentialPart.combinations(): Long {
return this.values.fold(1) { acc, i ->
acc * (i.last - i.first + 1L)
}
}
class Day19 : Day(19, 2023, "Aplenty") {
sealed interface Rule {
val next: String
fun matches(part: Map<Category, Int>): Boolean
fun split(parts: PotentialPart): Pair<PotentialPart?, PotentialPart?>
data class LessThan(val category: Category, val value: Int, override val next: String) : Rule {
override fun matches(part: Map<Category, Int>) = part[category]!! < value
override fun split(parts: PotentialPart): Pair<PotentialPart?, PotentialPart?> {
val relevant = parts[category]!!
val (matching, notMatching) =
when {
value in relevant ->
(relevant.first..<value) to (value..relevant.last)
value > relevant.last ->
relevant to null
else -> null to null
}
return parts.patch(category, matching) to parts.patch(category, notMatching)
}
}
data class GreaterThan(val category: Category, val value: Int, override val next: String) : Rule {
override fun matches(part: Map<Category, Int>) = part[category]!! > value
override fun split(parts: PotentialPart): Pair<PotentialPart?, PotentialPart?> {
val relevant = parts[category]!!
val (matching, notMatching) =
when {
value in relevant ->
((value + 1)..relevant.last) to (relevant.first..value)
value < relevant.first ->
relevant to null
else -> null to null
}
return parts.patch(category, matching) to parts.patch(category, notMatching)
}
}
data class Unconditional(override val next: String) : Rule {
override fun matches(part: Map<Category, Int>) = true
override fun split(parts: PotentialPart): Pair<PotentialPart?, PotentialPart?> =
parts to null
}
}
data class Workflow(val name: String, val rules: List<Rule>)
private val workflows = inputAsGroups[0]
.map {
val (name, ruleString) = it.split('{')
val rules = ruleString.dropLast(1)
.split(',')
.map { r ->
if (':' in r) {
val (c, next) = r.split(':')
val category = when (c[0]) {
'x' -> Category.X
'm' -> Category.M
'a' -> Category.A
's' -> Category.S
else -> error(r)
}
when (c[1]) {
'>' -> Rule.GreaterThan(category, c.split('>')[1].toInt(), next)
'<' -> Rule.LessThan(category, c.split('<')[1].toInt(), next)
else -> error(r)
}
} else {
Rule.Unconditional(r)
}
}
Workflow(name, rules)
}
.associateBy { it.name }
.show()
private val partRatings = inputAsGroups[1]
.map {
Category.entries.zip(it.extractAllIntegers()).toMap()
}
.show()
override fun part1(): Int {
fun Map<Category, Int>.isAccepted(): Boolean {
var wf = "in"
while (true) {
if (wf == "R") return false
if (wf == "A") return true
wf = workflows[wf]!!.rules.first { r -> r.matches(this) }.next
}
}
return partRatings
.filter { it.isAccepted() }
.sumOf { it.values.sum() }
}
override fun part2(): Long {
val potentialParts = Category.entries.associateWith { 1..4000 }
fun countAccepted(wf: Workflow, parts: PotentialPart?): Long =
wf.rules.fold(parts to 0L) { (remaining, count), rule ->
if (remaining != null) {
val (matching, notMatching) = rule.split(remaining)
notMatching to count + when (rule.next) {
"A" -> matching?.combinations() ?: 0
"R" -> 0
else -> countAccepted(workflows[rule.next]!!, matching)
}
} else {
null to count
}
}.second
return countAccepted(workflows["in"]!!, potentialParts)
}
}
| 0 | Kotlin | 0 | 0 | c75d17635baffea50b6401dc653cc24f5c594a2b | 5,385 | advent-of-code-2023 | Apache License 2.0 |
src/day09/Day09.kt | martin3398 | 572,166,179 | false | {"Kotlin": 76153} | package day09
import readInput
import kotlin.math.absoluteValue
import kotlin.math.sign
data class Position(val x: Int, val y: Int) {
fun move(direction: Char): Position {
return when (direction) {
'U' -> Position(x, y + 1)
'D' -> Position(x, y - 1)
'R' -> Position(x + 1, y)
'L' -> Position(x - 1, y)
else -> throw IllegalArgumentException("Illegal Argument '$direction'")
}
}
fun moveTowards(other: Position): Position {
return if ((other.x - this.x).absoluteValue >= 2 || (other.y - this.y).absoluteValue >= 2) {
Position(x + (other.x - this.x).sign, y + (other.y - this.y).sign)
} else {
this
}
}
}
fun main() {
fun part1(input: List<Pair<Char, Int>>): Int {
var head = Position(0, 0)
var tail = Position(0, 0)
val positions = mutableSetOf(tail)
for (command in input) {
for (i in 0 until command.second) {
head = head.move(command.first)
tail = tail.moveTowards(head)
positions.add(tail)
}
}
return positions.size
}
fun part2(input: List<Pair<Char, Int>>, size: Int = 10): Int {
val knots = Array(size) { Position(0, 0) }
val positions = mutableSetOf(knots[size - 1])
for (command in input) {
for (i in 0 until command.second) {
knots[0] = knots[0].move(command.first)
for (knotIndex in 1 until size) {
knots[knotIndex] = knots[knotIndex].moveTowards(knots[knotIndex - 1])
}
positions.add(knots[size - 1])
}
}
return positions.size
}
fun preprocess(input: List<String>): List<Pair<Char, Int>> =
input.map {
val split = it.split(" ")
Pair(it[0], split.last().toInt())
}
// test if implementation meets criteria from the description, like:
val testInput = readInput(9, true)
check(part1(preprocess(testInput)) == 88)
val input = readInput(9)
println(part1(preprocess(input)))
check(part2(preprocess(testInput)) == 36)
println(part2(preprocess(input)))
}
| 0 | Kotlin | 0 | 0 | 4277dfc11212a997877329ac6df387c64be9529e | 2,268 | advent-of-code-2022 | Apache License 2.0 |
y2016/src/main/kotlin/adventofcode/y2016/Day08.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2016
import adventofcode.io.AdventSolution
import adventofcode.util.parser
object Day08 : AdventSolution(2016, 8, "Two-Factor Authentication") {
override fun solvePartOne(input: String) = solve(input).let { screen ->
screen.screen.sumOf { row -> row.count { it } }.toString()
}
override fun solvePartTwo(input: String) = solve(input).let { screen ->
screen.screen.joinToString("") { row ->
"\n" + row.joinToString("") { pixel -> if (pixel) "█" else " " }
}
}
private fun solve(input: String): Screen {
val parser = parser<(Screen) -> Unit> {
rule("rect (\\d+)x(\\d+)") { (x, y) ->
{ it.drawRectangle(x.toInt(), y.toInt()) }
}
rule("rotate row y=(\\d+) by (\\d+)") { (y, distance) ->
{ it.rotateRow(y.toInt(), distance.toInt()) }
}
rule("rotate column x=(\\d+) by (\\d+)") { (x, distance) ->
{ it.rotateColumn(x.toInt(), distance.toInt()) }
}
}
return Screen().apply {
input.lineSequence().forEach { line ->
val command = parser.parse(line) ?: throw IllegalStateException()
command(this)
}
}
}
private class Screen(private val rows: Int = 6, private val columns: Int = 50) {
val screen: Array<BooleanArray> = Array(rows) {
BooleanArray(columns) { false }
}
fun drawRectangle(width: Int, height: Int) {
for (x in 0 until width)
for (y in 0 until height)
screen[y][x] = true
}
fun rotateRow(y: Int, distance: Int) {
val rotatedRow = BooleanArray(columns) { screen[y][(it + columns - distance) % columns] }
rotatedRow.forEachIndexed { x, value -> screen[y][x] = value }
}
fun rotateColumn(x: Int, distance: Int) {
val rotatedColumn = BooleanArray(rows) { screen[(it + rows - distance) % rows][x] }
rotatedColumn.forEachIndexed { y, value -> screen[y][x] = value }
}
}
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,822 | advent-of-code | MIT License |
src/main/kotlin/tr/emreone/adventofcode/days/Day13.kt | EmRe-One | 568,569,073 | false | {"Kotlin": 166986} | package tr.emreone.adventofcode.days
import tr.emreone.adventofcode.readTextGroups
import java.util.*
object Day13 {
private const val OPENING_BRACKET = '['
private const val CLOSING_BRACKET = ']'
private fun String.getCommaIndices(): List<Int> {
val bracketStack = Stack<Int>()
val commas = mutableListOf<Int>()
commas.add(-1)
for (i in indices) {
when (this[i]) {
OPENING_BRACKET -> bracketStack.push(i)
CLOSING_BRACKET -> bracketStack.pop()
',' -> if (bracketStack.isEmpty()) commas.add(i)
}
}
commas.add(length)
return commas
}
interface Packet : Comparable<Packet> {
companion object {
fun parse(msg: String): Packet {
val elements = mutableListOf<Packet>()
val isGroup = msg.startsWith(OPENING_BRACKET) && msg.endsWith(CLOSING_BRACKET)
if (!isGroup) {
return NumberPacket(msg.toInt())
}
val droppedMessage = if (isGroup) msg.drop(1).dropLast(1) else msg
if (droppedMessage.isEmpty()) {
return GroupPacket(elements)
}
droppedMessage.getCommaIndices().windowed(2).forEach { (start, end) ->
val element = droppedMessage.substring(start + 1, end)
elements.add(this.parse(element))
}
return GroupPacket(elements)
}
}
override fun compareTo(other: Packet): Int {
if (this is NumberPacket && other is NumberPacket) {
return this.value.compareTo(other.value)
}
else if (this is NumberPacket && other is GroupPacket) {
return this.convertToGroupPacket().compareTo(other)
}
else if (this is GroupPacket && other is NumberPacket) {
return this.compareTo(other.convertToGroupPacket())
}
// both are groups
val leftGroup = this as GroupPacket
val rightGroup = other as GroupPacket
var leftIndex = 0
while (leftIndex < leftGroup.values.size) {
// if right group is smaller than left group, then left group is bigger
if (leftIndex > rightGroup.values.lastIndex) {
return 1
}
// if left == right then continue
else if (leftGroup.values[leftIndex] == rightGroup.values[leftIndex]) {
leftIndex++
}
else {
return leftGroup.values[leftIndex].compareTo(rightGroup.values[leftIndex])
}
}
// if code reaches here, then left group is smaller
return -1
}
}
data class NumberPacket(var value: Int = -1) : Packet {
fun convertToGroupPacket(): GroupPacket {
return GroupPacket(listOf(this))
}
}
data class GroupPacket(var values: List<Packet> = emptyList()) : Packet {}
fun part1(input: String): Int {
val groups = input.readTextGroups()
.mapIndexed { index, g ->
val (left, right) = g.lines()
index to (Packet.parse(left) to Packet.parse(right))
}
return groups.sumOf { (index, pairs) ->
val (left, right) = pairs
if (left < right) index + 1 else 0
}
}
fun part2(input: String): Int {
val elemTwo = Packet.parse("[[2]]")
val elemSix = Packet.parse("[[6]]")
val groups = input
.lines()
.filter {
it.isNotBlank()
}
.map { g ->
Packet.parse(g)
}.toMutableList()
.also {
it.add(elemTwo)
it.add(elemSix)
}
// works, because Packets are Comparable
groups.sort()
val indexOfTwo = groups.indexOf(elemTwo) + 1
val indexOfSix = groups.indexOf(elemSix) + 1
return indexOfTwo * indexOfSix
}
}
| 0 | Kotlin | 0 | 0 | a951d2660145d3bf52db5cd6d6a07998dbfcb316 | 4,215 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/adventofcode2022/solution/day_9.kt | dangerground | 579,293,233 | false | {"Kotlin": 51472} | package adventofcode2022.solution
import adventofcode2022.util.readDay
import kotlin.math.abs
fun main() {
Day9("9").solve()
}
class Day9(private val num: String) {
private val inputText = readDay(num)
fun solve() {
println("Day $num Solution")
println("* Part 1: ${solution1()}")
println("* Part 2: ${solution2()}")
}
fun solution1(): Long {
val head = Knot(0, 4)
val tail = Knot(0, 4)
val visits = VisitedMap()
inputText.lines().forEach {
println()
println(it)
when (it.direction()) {
"D" -> repeat(it.amount()) {
head.down()
tail.follow(head)
visits.track(tail)
visits.debug(head, listOf(tail))
}
"U" -> repeat(it.amount()) {
head.up()
tail.follow(head)
visits.track(tail)
visits.debug(head, listOf(tail))
}
"L" -> repeat(it.amount()) {
head.left()
tail.follow(head)
visits.track(tail)
visits.debug(head, listOf(tail))
}
"R" -> repeat(it.amount()) {
head.right()
tail.follow(head)
visits.track(tail)
visits.debug(head, listOf(tail))
}
}
}
return visits.map { it.value.size }.sum().toLong()
}
private fun String.direction() = substring(0, 1)
private fun String.amount() = substring(2).toInt()
fun solution2(): Long {
val knots = listOf(Knot(), Knot(), Knot(), Knot(), Knot(), Knot(), Knot(), Knot(), Knot(), Knot())
// val knots = listOf(Knot(), Knot())
val visits = VisitedMap()
inputText.lines().forEach {
println()
println(it)
when (it.direction()) {
"D" -> repeat(it.amount()) {
knots.first().down()
knots.filterIndexed { index, _ -> index > 0 }
.forEachIndexed { index, knot -> knot.follow(knots[index]) }
visits.track(knots.last())
}
"U" -> repeat(it.amount()) {
knots.first().up()
knots.filterIndexed { index, _ -> index > 0 }
.forEachIndexed { index, knot -> knot.follow(knots[index]) }
visits.track(knots.last())
}
"L" -> repeat(it.amount()) {
knots.first().left()
knots.filterIndexed { index, _ -> index > 0 }
.forEachIndexed { index, knot -> knot.follow(knots[index]) }
visits.track(knots.last())
}
"R" -> repeat(it.amount()) {
knots.first().right()
knots.filterIndexed { index, _ -> index > 0 }
.forEachIndexed { index, knot -> knot.follow(knots[index]) }
visits.track(knots.last())
visits.debug(knots.first(), knots.takeLast(9))
}
}
}
return visits.map { it.value.size }.sum().toLong()
}
}
typealias VisitedMap = HashMap<Int, MutableMap<Int, Boolean>>
fun VisitedMap.track(knot: Knot) {
putIfAbsent(knot.y, mutableMapOf())
get(knot.y)!![knot.x] = true
}
fun VisitedMap.debug(head: Knot, knots: List<Knot>) {
println("Debug ($head) -> ${knots}:")
IntRange(0, 4).forEach { y ->
IntRange(0, 5).forEach { x ->
if (head.x == x && head.y == y) {
print("H")
} else if (knots.any { it.x == x && it.y == y }) {
print(knots.indexOfFirst { it.x == x && it.y == y } + 1)
} else {
print(get(y)?.get(x)?.let { "." } ?: ".")
}
}
println()
}
}
data class Knot(var x: Int = 0, var y: Int = 4) {
private fun tooFar(other: Knot) = abs(x - other.x) > 1 || abs(y - other.y) > 1
fun follow(head: Knot) {
if (tooFar(head)) {
if (x == head.x) {
y += (head.y - y) / 2
} else if (y == head.y) {
x += (head.x - x) / 2
} else {
if (abs(y - head.y) == 2 && abs(x - head.x) == 2) {
x += (head.x - x) / 2
y += (head.y - y) / 2
} else if (abs(y - head.y) == 2) {
x = head.x
y += (head.y - y) / 2
} else {
y = head.y
x += (head.x - x) / 2
}
}
}
}
fun left() = x--
fun right() = x++
fun up() = y--
fun down() = y++
} | 0 | Kotlin | 0 | 0 | f1094ba3ead165adaadce6cffd5f3e78d6505724 | 4,960 | adventofcode-2022 | MIT License |
src/Day02.kt | zsmb13 | 572,719,881 | false | {"Kotlin": 32865} | fun main() {
fun part1(input: List<String>): Int {
fun shapeScore(shape: Char) = (shape - 'X' + 1)
fun resultScore(line: String): Int {
return when (line) {
"B X", "C Y", "A Z" -> 0
"A X", "B Y", "C Z" -> 3
"C X", "A Y", "B Z" -> 6
else -> error("Check your inputs")
}
}
return input.sumOf { round ->
shapeScore(shape = round[2]) + resultScore(round)
}
}
fun part2(input: List<String>): Int {
fun shapeScore(line: String): Int {
return when (line) {
"A Y", "B X", "C Z" -> 1
"B Y", "C X", "A Z" -> 2
"C Y", "A X", "B Z" -> 3
else -> error("Check your inputs")
}
}
fun resultScore(result: Char) = (result - 'X') * 3
return input.sumOf { round ->
shapeScore(round) + resultScore(round[2])
}
}
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 6 | 32f79b3998d4dfeb4d5ea59f1f7f40f7bf0c1f35 | 1,195 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | george-theocharis | 573,013,076 | false | {"Kotlin": 10656} | fun main() {
fun part1(input: List<String>): Int = input
.splitByElf()
.findCommonItem()
.sumOfPriorities()
fun part2(input: List<String>): Int = input
.splitByGroupOfElves()
.findGroupBadge()
.sumOfPriorities()
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
private fun List<String>.splitByElf() = map { items ->
val halfSize = items.length / 2
items.substring(0, halfSize) to items.substring(halfSize, items.length)
}
private fun List<Pair<String, String>>.findCommonItem() = map { (firstItem, secondItem) ->
firstItem.first {
secondItem.contains(it)
}
}
private fun List<Char>.sumOfPriorities() = sumOf {
if (it.isLowerCase()) {
('a'..'z').indexOf(it) + 1
} else {
(('A'..'Z').indexOf(it) + 27)
}
}
private fun List<String>.splitByGroupOfElves(): List<List<String>> = chunked(3)
private fun List<List<String>>.findGroupBadge() = map { group ->
group.toItems()
.first()
.first { character ->
group.toItems()
.mapNotNull { line: List<Char> -> if (line.contains(character)) character else null }
.size == group.size
}
}
private fun List<String>.toItems(): List<List<Char>> = map { it.toCharArray().toList() } | 0 | Kotlin | 0 | 0 | 7971bea39439b363f230a44e252c7b9f05a9b764 | 1,339 | aoc-2022 | Apache License 2.0 |
leetcode/src/daily/hard/Q1235.kt | zhangweizhe | 387,808,774 | false | null | package daily.hard
import java.util.*
import kotlin.Comparator
import kotlin.math.max
fun main() {
// 1235. 规划兼职工作
// https://leetcode.cn/problems/maximum-profit-in-job-scheduling/
println(jobScheduling1(intArrayOf(1,2,3,3), intArrayOf(3,4,5,6), intArrayOf(50,10,40,70)))
println(jobScheduling1(intArrayOf(1,2,3,4,6), intArrayOf(3,5,10,6,9), intArrayOf(20,20,100,70,60)))
println(jobScheduling1(intArrayOf(1,1,1), intArrayOf(2,3,4), intArrayOf(5,6,4)))
println(jobScheduling1(intArrayOf(1,2,2,3), intArrayOf(2,5,3,4), intArrayOf(3,4,1,2)))
}
fun jobScheduling1(startTime: IntArray, endTime: IntArray, profit: IntArray): Int {
// 考虑【选】还是【不选】,即要不要做第 i 号工作
val jobs = Array(startTime.size) {
Job(startTime[it], endTime[it], profit[it])
}
// 根据 endTime 对任务排序
Arrays.sort(jobs, object : Comparator<Job> {
override fun compare(p0: Job?, p1: Job?): Int {
return p0!!.et.compareTo(p1!!.et)
}
})
val dp = IntArray(startTime.size)
dp[0] = jobs[0].pt
for (i in 1 until startTime.size) {
var j = i-1
var prev = -1
while (j >= 0) {
// 向前寻找“最近的”“已完成的"兼职工作
if (jobs[i].st >= jobs[j].et) {
prev = j
break
}
j--
}
// “最近的”“已完成的"兼职工作的最大报酬
val prevMaxProfit = if (prev >= 0) {
dp[prev]
}else {
0
}
// 【选】第 i 个工作的报酬,就是 “最近的”“已完成的"兼职工作的最大报酬 + 本个工作的报酬jobs[i].pt
val selectProfit = prevMaxProfit + jobs[i].pt
// 【不选】第 i 个工作的报酬,那就是上一个工作的最大报酬
val noSelectProfit = dp[i-1]
dp[i] = max(selectProfit, noSelectProfit)
}
return dp[dp.size-1]
}
class Job(val st:Int, val et:Int, val pt:Int)
fun jobScheduling(startTime: IntArray, endTime: IntArray, profit: IntArray): Int {
// 考虑【选】还是【不选】,即要不要做第 i 号工作
/**
* 1. 状态定义
* dp[i] 表示前 i+1 个任务的最优解
* 2. 转移方程
* 2.1 【选】第 i 号工作:dp[i] = profit[i] + dp[prev[i]],prev[i] 表示在【选】了第 i 号工作的情况下,前一个能【选】的工作的序号
* 2.2 【不选】第 i 号工作:dp[i] = dp[i-1]
* 所以 dp[i] = max(profit[i] + dp[prev[i]], dp[i-1])
* 3. 初始值
* dp[0] = profit[0]
*/
// 根据 endTime 对任务排序,endTimeSortedIndex[0] 表示结束时间最小的工作序号,endTimeSortedIndex[1] 表示结束时间最大的工作序号
val endTimeSortedIndex = Array(endTime.size) {
it
}
Arrays.sort(endTimeSortedIndex, object : Comparator<Int>{
override fun compare(p0: Int?, p1: Int?): Int {
return endTime[p0!!].compareTo(endTime[p1!!])
}
})
val prevArray = IntArray(endTime.size) {
-1
}
// 填充 prevArray 数组,prev[i] 表示在【选】了第 i 号工作的情况下,前一个能【选】的工作的序号
for (i in endTimeSortedIndex.indices) {
val jobIndex = endTimeSortedIndex[i]
val curStartTime = startTime[jobIndex]
// endTimeSortedIndex 从后往前找,找第一个 endTime 小于等于 curStartTime 的任务需要,就是 prev[i]
var j = jobIndex-1
while (j >= 0) {
if (curStartTime >= endTime[endTimeSortedIndex[j]]) {
prevArray[jobIndex] = endTimeSortedIndex[j]
break
}
j--
}
}
val dp = IntArray(endTime.size)
dp[0] = profit[endTimeSortedIndex[0]]
for (i in 1 until endTimeSortedIndex.size) {
val jobIndex = endTimeSortedIndex[i]
// 选第 i 个工作的报酬
// 前一份工作能拿到的最优报酬
val prevMaxProfit = if (prevArray[jobIndex] == -1) {
0
}else {
dp[prevArray[jobIndex]]
}
val selectProfit = profit[jobIndex] + prevMaxProfit
// 不选第 i 个工作的报酬,就是 dp[i-1] 了
val noSelectProfit = dp[jobIndex -1]
dp[jobIndex] = max(selectProfit, noSelectProfit)
}
return dp[dp.size - 1]
} | 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 4,550 | kotlin-study | MIT License |
src/day12/Day12.kt | andreas-eberle | 573,039,929 | false | {"Kotlin": 90908} | package day12
import readInput
import java.util.*
const val day = "12"
fun main() {
fun findDijkstraPath(start: Pos, end: Pos, heightMap: List<List<Int>>): MutableList<Pos>? {
val height = heightMap.size
val width = heightMap[0].size
val backPointers = List(height) { MutableList<Pos?>(width) { null } }
val posQueue: Queue<Pos> = LinkedList()
posQueue.add(start)
backPointers[start.y][start.x] = start
while (posQueue.isNotEmpty()) {
val currPos = posQueue.poll()
if (currPos == end) {
break
}
val currentHeight = heightMap.of(currPos)
currPos.neighbors.filter { it.inBounds(width, height) }
.filter { neighbor -> heightMap.of(neighbor) <= currentHeight + 1 }
.filter { backPointers.of(it) == null }
.forEach { neighbor ->
posQueue.add(neighbor)
backPointers[neighbor.y][neighbor.x] = currPos
}
}
if(backPointers.of(end) == null) {
return null
}
val path = mutableListOf<Pos>()
var currentPos: Pos = end
while (currentPos != start) {
path.add(currentPos)
currentPos = backPointers.of(currentPos)
?: error("null")
}
return path
}
fun calculatePart1Score(input: List<String>): Int {
val charMap = input.map { it.toCharArray().toList() }
val heightMap = charMap.map { it.map { char -> char.mapToHeight() } }
val start = charMap.findValuePos('S')
val end = charMap.findValuePos('E')
val path = findDijkstraPath(start, end, heightMap)
return path?.size ?: 0
}
fun calculatePart2Score(input: List<String>): Int {
val charMap = input.map { it.toCharArray().toList() }
val heightMap = charMap.map { it.map { char -> char.mapToHeight() } }
val starts = heightMap.findValuePositions(0)
val end = charMap.findValuePos('E')
return starts.mapNotNull { start -> findDijkstraPath(start, end, heightMap) }.minOf { it.size }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("/day$day/Day${day}_test")
val input = readInput("/day$day/Day${day}")
val part1TestPoints = calculatePart1Score(testInput)
val part1points = calculatePart1Score(input)
println("Part1 test points: $part1TestPoints")
println("Part1 points: $part1points")
check(part1TestPoints == 31)
val part2TestPoints = calculatePart2Score(testInput)
val part2points = calculatePart2Score(input)
println("Part2 test points: \n$part2TestPoints")
println("Part2 points: \n$part2points")
check(part2TestPoints == 29)
}
fun <T> List<List<T>>.of(pos: Pos): T {
return this[pos.y][pos.x]
}
fun <T> List<List<T>>.findValuePos(value: T): Pos {
val y = indexOf(find { it.contains(value) })
val x = this[y].indexOf(value)
return Pos(x, y)
}
fun <T> List<List<T>>.findValuePositions(value: T): List<Pos> {
val indexedLocations = this.map { it.withIndex().filter { pos -> pos.value == value } }.withIndex().filter { it.value.isNotEmpty() }
return indexedLocations.flatMap { outer -> outer.value.map { Pos(it.index, outer.index) } }
}
fun Char.mapToHeight(): Int = when (this) {
in 'a'..'z' -> this - 'a'
'S' -> 0
'E' -> 'z' - 'a'
else -> error("Unknown char $this")
}
data class Pos(val x: Int, val y: Int) {
val neighbors: List<Pos>
get() = listOf(Pos(x - 1, y), Pos(x + 1, y), Pos(x, y + 1), Pos(x, y - 1))
fun inBounds(width: Int, height: Int): Boolean {
return x in 0 until width && y in 0 until height
}
} | 0 | Kotlin | 0 | 0 | e42802d7721ad25d60c4f73d438b5b0d0176f120 | 3,811 | advent-of-code-22-kotlin | Apache License 2.0 |
src/main/kotlin/com/groundsfam/advent/y2021/d14/Day14.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2021.d14
import com.groundsfam.advent.DATAPATH
import com.groundsfam.advent.timed
import kotlin.io.path.div
import kotlin.io.path.useLines
// Note about this problem: I verified that there are
// exactly 10 letters that occur in the (non-example) input,
// and there are 100 pair insertion rules, meaning that
// every pair of letters produces a new letter at every step.
private class Solution(private val insertionRules: Map<String, Char>, template: String) {
private var pairCounts: Map<String, Long>
private val lastChar = template.last()
init {
val initCounts = mutableMapOf<String, Long>()
(1 until template.length).forEach { i ->
val pair = template.substring(i - 1..i)
initCounts[pair] = (initCounts[pair] ?: 0) + 1
}
pairCounts = initCounts
}
fun step() {
val nextCounts = mutableMapOf<String, Long>()
pairCounts.forEach { (pair, count) ->
val newChar = insertionRules[pair]!!
listOf("${pair[0]}$newChar", "$newChar${pair[1]}").forEach { newPair ->
nextCounts[newPair] = (nextCounts[newPair] ?: 0) + count
}
}
pairCounts = nextCounts
}
fun mostMinusLeastCommon(): Long {
val charCounts = mutableMapOf<Char, Long>()
pairCounts.forEach { (pair, count) ->
val c = pair[0]
charCounts[c] = (charCounts[c] ?: 0) + count
}
charCounts[lastChar] = (charCounts[lastChar] ?: 0) + 1
return charCounts.values.let { counts ->
counts.maxOrNull()!! - counts.minOrNull()!!
}
}
}
fun main() = timed {
val solution =
(DATAPATH / "2021/day14.txt").useLines { lines ->
val rules = mutableMapOf<String, Char>()
var tmpl: String? = null
lines.forEachIndexed { i, line ->
if (i == 0) {
tmpl = line
}
if (i > 1) {
rules[line.substring(0..1)] = line[6]
}
}
Solution(rules, tmpl!!)
}
repeat(10) {
solution.step()
}
println("Part one: ${solution.mostMinusLeastCommon()}")
repeat(30) {
solution.step()
}
println("Part two: ${solution.mostMinusLeastCommon()}")
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 2,363 | advent-of-code | MIT License |
src/Day02.kt | asm0dey | 572,860,747 | false | {"Kotlin": 61384} | import Outcome.*
import RPS.*
private enum class Outcome(val value: Int) {
WIN(6), LOSE(0), DRAW(3);
}
private enum class RPS(val value:Int) {
ROCK(1) {
override fun outcome(m: RPS): Outcome = when (m) {
ROCK -> DRAW
PAPER -> WIN
SCISSORS -> LOSE
}
override fun findSecondSignByOutcome(outcome: Outcome): RPS = when (outcome) {
WIN -> PAPER
LOSE -> SCISSORS
DRAW -> ROCK
}
},
PAPER(2) {
override fun outcome(m: RPS): Outcome = when (m) {
ROCK -> LOSE
PAPER -> DRAW
SCISSORS -> WIN
}
override fun findSecondSignByOutcome(outcome: Outcome): RPS = when (outcome) {
WIN -> SCISSORS
LOSE -> ROCK
DRAW -> PAPER
}
},
SCISSORS(3) {
override fun outcome(m: RPS): Outcome = when (m) {
ROCK -> WIN
PAPER -> LOSE
SCISSORS -> DRAW
}
override fun findSecondSignByOutcome(outcome: Outcome): RPS = when (outcome) {
WIN -> ROCK
LOSE -> PAPER
DRAW -> SCISSORS
}
};
abstract fun outcome(m: RPS): Outcome
abstract fun findSecondSignByOutcome(outcome: Outcome): RPS
}
fun main() {
fun elfToSign(f: String): RPS = when (f) {
"A" -> ROCK
"B" -> PAPER
"C" -> SCISSORS
else -> throw IllegalArgumentException()
}
fun meToSign(s: String): RPS = when (s) {
"X" -> ROCK
"Y" -> PAPER
"Z" -> SCISSORS
else -> throw IllegalArgumentException()
}
fun meToOutcome(s: String) = when (s) {
"X" -> LOSE
"Y" -> DRAW
"Z" -> WIN
else -> throw IllegalArgumentException()
}
fun part1(input: List<String>): Int {
return input
.asSequence()
.map { it.split(' ') }
.filterNot { it.size != 2 }
.map { (f, s) -> elfToSign(f) to meToSign(s) }
.map { (elfSign, mySign) -> elfSign.outcome(mySign).value + mySign.value }
.sum()
}
fun part2(input: List<String>): Int {
return input
.asSequence()
.map { it.split(' ') }
.filterNot { it.size != 2 }
.map { (f, s) -> elfToSign(f) to meToOutcome(s) }
.map { (elfSign, outcome) -> elfSign.findSecondSignByOutcome(outcome).value + outcome.value }
.sum()
}
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 1 | Kotlin | 0 | 1 | f49aea1755c8b2d479d730d9653603421c355b60 | 2,674 | aoc-2022 | Apache License 2.0 |
adventofcode/src/main/kotlin/day3.kt | jmfayard | 71,764,270 | false | null | import io.kotlintest.specs.StringSpec
import java.io.File
/*
Now that you can think clearly, you move deeper into the labyrinth of hallways and office furniture that makes up this part of Easter Bunny HQ.
This must be a graphic design department; the walls are covered in specifications for triangles.
Or are they?
The design document gives the side lengths of each triangle it describes, but... 5 10 25? Some of these aren't triangles.
You can't help but mark the impossible ones.
In a valid triangle, the sum of any two sides must be larger than the remaining side.
For example, the "triangle" given above is impossible, because 5 + 10 is not larger than 25.
--- Part Two ---
Now that you've helpfully marked up their design documents, it occurs to you
that triangles are specified in groups of three vertically. Each set of three
numbers in a column specifies a triangle. Rows are unrelated.
For example, given the following specification, numbers with the same hundreds digit would be part of the same triangle:
101 301 501
102 302 502
103 303 503
201 401 601
202 402 602
203 403 603
In your puzzle input, and instead reading by columns, how many of the listed triangles are possible?
*/
class Day3 : StringSpec() { init {
"Parsing" {
" 566 477 376 ".toInts().toTriangle() shouldBe Triangle(376, 477, 566)
" 1 2 a".toInts().toTriangle() shouldBe null
}
"Valid triangles" {
Triangle(5, 10, 10).isValid() shouldBe true
Triangle(5, 10, 15).isValid() shouldBe false
Triangle(5, 10, 16).isValid() shouldBe false
}
val expected = 1050
val file = resourceFile("day3.txt")
"Solution: $expected " {
var solution = 0
file.forEachLine { line ->
val triangle = line.toInts().toTriangle()
if (triangle?.isValid() ?: false) {
solution++
}
}
println("Found $solution")
solution shouldBe expected
}
val expected2 = 1921
"Solutino part 2 : $expected2" {
val matrix = listOf(
listOf(0, 3, 6),
listOf(1, 4, 7),
listOf(2, 5, 8)
)
val triangles = mutableListOf<Triangle>()
val lines = file.readLines()
var i = 0
while (i + 2 < lines.size) {
val ints = lines[i].toInts()!! + lines[i + 1].toInts()!! + lines[i + 2].toInts()!!
for (row in matrix) {
val list = row.map { i -> ints[i] }
triangles += list.toTriangle()!!
}
i += 3
}
val solution = triangles.filter(Triangle::isValid).count()
solution shouldBe expected2
}
}
}
data class Triangle(val small: Int, val medium: Int, val big: Int) {
fun isValid(): Boolean = small + medium > big
}
val spaces = Regex("\\s+")
private fun String.toInts(): List<Int>? =
try {
trim().split(spaces).map(String::toInt).take(3)
} catch (e: Exception) {
null
}
private fun List<Int>?.toTriangle(): Triangle? =
this?.let { list ->
val (a, b, c) = list.sorted()
Triangle(a, b, c)
}
| 0 | Kotlin | 0 | 1 | 9e92090aa50127a470653f726b80335133dec38b | 3,144 | httplayground | ISC License |
src/main/kotlin/day11/part1/Part1.kt | bagguley | 329,976,670 | false | null | package day11.part1
import day11.data
fun main() {
var seats = data.map { it.toCharArray() }
while (true) {
val x = process(seats)
if (compare(x, seats)) break
seats = x
}
val z = seats.map { it.count { it == '#' } }.sum()
println(z)
}
fun process(seats: List<CharArray>): List<CharArray> {
val width = seats.first().size
val height = seats.size
val result = mutableListOf<CharArray>()
seats.forEach { result.add(CharArray(width){'.'}) }
for (h in 0 until height) {
for (w in 0 until width) {
result[h][w] = newState(seats, w, h)
}
}
return result
}
fun newState(seats: List<CharArray>, x: Int, y: Int): Char {
val width = seats.first().size
val height = seats.size
val d = arrayListOf(x-1, y-1, x, y-1, x+1, y-1, x-1, y, x+1, y, x-1, y+1, x, y+1, x+1, y+1).windowed(2, 2)
.map { (first, second) -> Pair(first, second)}.filter{ it.first in 0 until width && it.second in 0 until height }
return when (val seat = seats[y][x]) {
'L' -> if (d.map { seats[it.second][it.first] }.filter{it=='#'}.count() == 0) '#' else seat
'#' -> if (d.map { seats[it.second][it.first] }.filter{it=='#'}.count() >= 4) 'L' else seat
else -> seat
}
}
fun compare(seats1: List<CharArray>, seats2: List<CharArray>): Boolean {
return seats1.zip(seats2).all{ it.first.contentEquals(it.second) }
} | 0 | Kotlin | 0 | 0 | 6afa1b890924e9459f37c604b4b67a8f2e95c6f2 | 1,431 | adventofcode2020 | MIT License |
leetcode2/src/leetcode/merge-intervals.kt | hewking | 68,515,222 | false | null | package leetcode
import java.util.*
/**
* 56. 合并区间
* https://leetcode-cn.com/problems/merge-intervals/
* Created by test
* Date 2019/9/30 18:12
* Description
* 给出一个区间的集合,请合并所有重叠的区间。
示例 1:
输入: [[1,3],[2,6],[8,10],[15,18]]
输出: [[1,6],[8,10],[15,18]]
解释: 区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
示例 2:
输入: [[1,4],[4,5]]
输出: [[1,5]]
解释: 区间 [1,4] 和 [4,5] 可被视为重叠区间。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-intervals
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
object MergeIntervals {
@JvmStatic
fun main(args : Array<String>) {
Solution().merge2(arrayOf(intArrayOf(1,4), intArrayOf(2,3))).forEach {
println()
it.forEach {
print(it)
}
}
}
class Solution {
/**
* 思路:
* 1. 数组内部排序
* 2. 外部大数组排序
*
*/
fun merge(intervals: Array<IntArray>): Array<IntArray> {
if (intervals.isEmpty()) {
return intervals
}
intervals.map {
it.sort()
}
intervals.sortBy {
it[0]
}
val intervalsList = mutableListOf<IntArray>()
var tmpArr = IntArray(2)
tmpArr[0] = intervals[0][0]
intervalsList.add(tmpArr)
for (i in 1 until intervals.size) {
tmpArr[1] = intervals[i - 1][1]
if (intervals[i][0] <= intervals[i - 1][1]) {
tmpArr[1] = Math.max(intervals[i][1],intervals[i - 1][1])
} else {
tmpArr = IntArray(2)
intervalsList.add(tmpArr)
tmpArr[0] = Math.min(intervals[i][0],intervals[i - 1][1])
}
}
tmpArr[1] = Math.max(intervals.last()[1],intervals[intervals.size - 1][1])
return intervalsList.toTypedArray()
}
fun merge2(intervals: Array<IntArray>): Array<IntArray> {
if (intervals.isEmpty()) {
return intervals
}
intervals.sortBy {
it[0]
}
val intervalsList = mutableListOf<IntArray>()
for (i in 0 until intervals.size) {
if (intervalsList.isEmpty() || intervalsList.last()[1] < intervals[i][0]) {
intervalsList.add(intervals[i])
} else {
intervalsList.last()[1] = Math.max(intervalsList.last()[1],intervals[i][1])
}
}
return intervalsList.toTypedArray()
}
}
} | 0 | Kotlin | 0 | 0 | a00a7aeff74e6beb67483d9a8ece9c1deae0267d | 2,844 | leetcode | MIT License |
src/main/kotlin/nl/dirkgroot/adventofcode/year2020/Day19.kt | dirkgroot | 317,968,017 | false | {"Kotlin": 187862} | package nl.dirkgroot.adventofcode.year2020
import nl.dirkgroot.adventofcode.util.Input
import nl.dirkgroot.adventofcode.util.Puzzle
class Day19(input: Input) : Puzzle() {
interface Rule
data class Terminal(val value: Char) : Rule
data class Sequence(val rules: List<Int>) : Rule
data class EitherOr(val either: Rule, val or: Rule) : Rule
private val parts by lazy {
val parts = input.string().split("\n\n")
parts[0] to parts[1]
}
private val rules1 by lazy { parseRules(parts.first, false) }
private val rules2 by lazy { parseRules(parts.first, true) }
private val messages by lazy { parts.second.split("\n") }
private fun parseRules(rules: String, part2: Boolean) =
rules.split("\n").map { rule ->
rule.split(": ").let { (id, text) ->
val ruleId = id.toInt()
if (part2 && ruleId == 8) ruleId to parseRule("42 | 42 8")
else if (part2 && ruleId == 11) ruleId to parseRule("42 31 | 42 11 31")
else ruleId to parseRule(text)
}
}.toMap()
private val terminalRegex = "\".\"".toRegex()
private val sequenceRegex = "(\\d+ ?)+".toRegex()
private val eitherOrRegex = "(\\d+ ?)+ \\| (\\d+ ?)+".toRegex()
private fun parseRule(rule: String): Rule =
when {
rule.matches(terminalRegex) -> Terminal(rule[1])
rule.matches(sequenceRegex) -> {
val rules = rule.split(" ").map { it.toInt() }
Sequence(rules)
}
rule.matches(eitherOrRegex) -> {
val (either, or) = rule.split(" | ")
EitherOr(parseRule(either), parseRule(or))
}
else -> throw IllegalStateException("Cannot parse rule $rule")
}
override fun part1() = messages.count { message -> isMatch(message, listOf(rules1[0]!!), rules1) }
override fun part2() = messages.count { message -> isMatch(message, listOf(rules2[0]!!), rules2) }
private fun isMatch(message: CharSequence, shouldMatch: List<Rule>, rules: Map<Int, Rule>): Boolean {
when {
message.isEmpty() -> return shouldMatch.isEmpty()
shouldMatch.isEmpty() -> return false
}
return when (val rule = shouldMatch[0]) {
is Terminal ->
if (message[0] == rule.value) isMatch(message.drop(1), shouldMatch.drop(1), rules)
else false
is Sequence ->
rule.rules.map { rules[it]!! }
.let { isMatch(message, it + shouldMatch.drop(1), rules) }
is EitherOr ->
isMatch(message, listOf(rule.either) + shouldMatch.drop(1), rules) ||
isMatch(message, listOf(rule.or) + shouldMatch.drop(1), rules)
else -> throw IllegalStateException("Unknown rule")
}
}
} | 1 | Kotlin | 1 | 1 | ffdffedc8659aa3deea3216d6a9a1fd4e02ec128 | 2,896 | adventofcode-kotlin | MIT License |
src/main/aoc2015/Day21.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2015
import com.marcinmoskala.math.combinations
import kotlin.math.max
class Day21(input: List<String>) {
data class Item(val name: String, val cost: Int, val damage: Int, val armor: Int)
data class Character(val name: String, val baseDamage: Int = 0, val baseArmor: Int = 0,
val equipment: List<Item> = listOf(), var hp: Int = 100) {
val damage: Int
get() = baseDamage + equipment.sumOf { it.damage }
val armor: Int
get() = baseArmor + equipment.sumOf { it.armor }
val equipmentCost: Int
get() = equipment.sumOf { it.cost }
}
private val boss = Character("Boss",
hp = input[0].substringAfter(": ").toInt(),
baseDamage = input[1].substringAfter(": ").toInt(),
baseArmor = input[2].substringAfter(": ").toInt())
private val weapons = """
Weapons: Cost Damage Armor
Dagger 8 4 0
Shortsword 10 5 0
Warhammer 25 6 0
Longsword 40 7 0
Greataxe 74 8 0
""".trimIndent().parseItems()
private val armor = """
Armor: Cost Damage Armor
No_armor 0 0 0
Leather 13 0 1
Chainmail 31 0 2
Splintmail 53 0 3
Bandedmail 75 0 4
Platemail 102 0 5
""".trimIndent().parseItems()
private val rings = """
Rings: Cost Damage Armor
No_ring_1 0 0 0
No_ring_2 0 0 0
Damage_+1 25 1 0
Damage_+2 50 2 0
Damage_+3 100 3 0
Defense_+1 20 0 1
Defense_+2 40 0 2
Defense_+3 80 0 3
""".trimIndent().parseItems()
private fun String.parseItems(): List<Item> {
return split("\n").drop(1).map { line ->
val parts = line.split("\\s+".toRegex())
Item(parts[0], parts[1].toInt(), parts[2].toInt(), parts[3].toInt())
}
}
private fun allItemCombinations(): List<List<Item>> {
val ret = mutableListOf<List<Item>>()
for (weapon in weapons) {
for (a in armor) {
val ringCombinations = rings.toSet().combinations(2)
ringCombinations.forEach {
val items = mutableListOf(weapon, a).apply { addAll(it) }
ret.add(items)
}
}
}
return ret
}
/**
* A fight until death with the boss. If the player wins it still have hp
* remaining after the fight.
*/
private fun fightBoss(player: Character): Boolean {
val fighters = listOf(player, this.boss.copy())
var round = 0
while (true) {
val attacker = fighters[round % 2]
val defender = fighters[(round + 1) % 2]
val damageMade = max(1, attacker.damage - defender.armor)
defender.hp -= damageMade
if (defender.hp <= 0) {
return attacker == player
}
round++
}
}
/**
* @param sortOrder 1 for smallest first, -1 for largest first
* @param hpComparison for how what is an acceptable player hp after the fight
*/
private fun testAllItems(sortOrder: Int, hpComparison: (Int) -> Boolean): Int {
val combinations = allItemCombinations().sortedBy { it.sumOf { item -> sortOrder * item.cost } }
return combinations
.map { Character("Player", equipment = it) }
.first {
fightBoss(it)
hpComparison(it.hp)
}.equipmentCost
}
fun solvePart1(): Int {
return testAllItems(1) { hp -> hp > 0}
}
fun solvePart2(): Int {
return testAllItems(-1) { hp -> hp <= 0}
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 3,979 | aoc | MIT License |
src/Day04.kt | Loahrs | 574,175,046 | false | {"Kotlin": 7516} | import java.awt.font.NumericShaper
fun main() {
infix fun<T : Comparable<T>> ClosedRange<T>.fullyContains(otherRange : ClosedRange<T>) : Boolean {
return (this.start <= otherRange.start) && (this.endInclusive >= otherRange.endInclusive)
}
infix fun<T : Comparable<T>> ClosedRange<T>.partiallyOverlaps(otherRange : ClosedRange<T>) : Boolean {
return when {
this.start <= otherRange.start && otherRange.start <= this.endInclusive -> true
otherRange.start <= this.start && this.start <= otherRange.endInclusive -> true
else -> false
}
}
fun createRangeFromString(rangeString : String): IntRange {
val (start, end) = rangeString.split("-")
return start.toInt()..end.toInt()
}
fun part1(input: List<String>): Int {
return input.filter {
val (leftString, rightString) = it.split(",")
val leftRange = createRangeFromString(leftString)
val rightRange = createRangeFromString(rightString)
//println("$leftRange,$rightRange ${leftRange fullyContains rightRange} ${rightRange fullyContains leftRange}")
return@filter (leftRange fullyContains rightRange) or (rightRange fullyContains leftRange)
}.count()
}
fun part2(input: List<String>): Int {
return input.filter {
val (leftString, rightString) = it.split(",")
val leftRange = createRangeFromString(leftString)
val rightRange = createRangeFromString(rightString)
return@filter (leftRange partiallyOverlaps rightRange) or (rightRange partiallyOverlaps leftRange)
}.count()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b1ff8a704695fc6ba8c32a227eafbada6ddc0d62 | 1,925 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day04.kt | GarrettShorr | 571,769,671 | false | {"Kotlin": 82669} | fun main() {
fun part1(input: List<String>): Int {
var count = 0
for(jobs in input) {
val jobPair = jobs.split(",")
var range1 = extractRange(jobPair[0])
var range2 = extractRange(jobPair[1])
if(isRangeContained(range1, range2)) {
count++
}
}
return count
}
fun part2(input: List<String>): Int {
var count = 0
for(jobs in input) {
val jobPair = jobs.split(",")
var range1 = extractRange(jobPair[0])
var range2 = extractRange(jobPair[1])
if(isOverlapped(range1, range2)) {
count++
}
}
return count
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day04")
output(part1(input))
output(part2(input))
}
fun extractRange(str: String) : Pair<Int, Int> {
var nums = str.split("-").map { it.toInt() }
return Pair(nums[0], nums[1])
}
fun isRangeContained(range1: Pair<Int, Int>, range2: Pair<Int, Int>) : Boolean {
return range1.first <= range2.first && range1.second >= range2.second ||
range2.first<= range1.first && range2.second >= range1.second
}
fun isOverlapped(range1: Pair<Int, Int>, range2: Pair<Int, Int>) : Boolean {
return !(range1.second < range2.first || range1.first > range2.second)
} | 0 | Kotlin | 0 | 0 | 391336623968f210a19797b44d027b05f31484b5 | 1,380 | AdventOfCode2022 | Apache License 2.0 |
src/day08/Day08.kt | daniilsjb | 726,047,752 | false | {"Kotlin": 66638, "Python": 1161} | package day08
import java.io.File
fun main() {
val data = parse("src/day08/Day08.txt")
println("🎄 Day 08 🎄")
println()
println("[Part 1]")
println("Answer: ${part1(data)}")
println()
println("[Part 2]")
println("Answer: ${part2(data)}")
}
private data class Instructions(
val directions: String,
val network: Map<String, Pair<String, String>>,
)
private fun parse(path: String): Instructions {
val lines = File(path).readLines()
val directions = lines.first()
val network = lines.drop(2)
.mapNotNull { """(\w+) = \((\w+), (\w+)\)""".toRegex().find(it)?.destructured }
.associate { (key, left, right) -> key to (left to right) }
return Instructions(directions, network)
}
private fun lcm(a: Long, b: Long): Long {
var n1 = a
var n2 = b
while (n2 != 0L) {
n1 = n2.also { n2 = n1 % n2 }
}
return (a * b) / n1
}
private fun Instructions.generateNodeSequence(start: String): Sequence<Pair<Int, String>> =
generateSequence(seed = 0 to start) { (index, node) ->
val nextDirection = directions[index % directions.length]
val nextNode = if (nextDirection == 'L') {
network.getValue(node).let { (next, _) -> next }
} else {
network.getValue(node).let { (_, next) -> next }
}
(index + 1) to nextNode
}
private fun part1(data: Instructions): Long =
data.generateNodeSequence(start = "AAA")
.dropWhile { (_, node) -> node != "ZZZ" }
.first().let { (index, _) -> index.toLong() }
private fun Instructions.periodFrom(start: String): Long {
val path = mutableMapOf<Pair<String, Int>, Long>()
return generateNodeSequence(start)
.dropWhile { (index, node) ->
val key = node to index % directions.length
if (key !in path) {
true.also { path[key] = index.toLong() }
} else {
false
}
}
.first().let { (index, node) ->
val directionIndex = index % directions.length
val startingIndex = path.getValue(node to directionIndex)
index.toLong() - startingIndex
}
}
private fun part2(data: Instructions): Long =
data.network.keys
.filter { it.last() == 'A' }
.map(data::periodFrom)
.reduce(::lcm)
| 0 | Kotlin | 0 | 0 | 46a837603e739b8646a1f2e7966543e552eb0e20 | 2,452 | advent-of-code-2023 | MIT License |
leetcode-75-kotlin/src/main/kotlin/MaxNumberOfKSumPairs.kt | Codextor | 751,507,040 | false | {"Kotlin": 49566} | /**
* You are given an integer array nums and an integer k.
*
* In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array.
*
* Return the maximum number of operations you can perform on the array.
*
*
*
* Example 1:
*
* Input: nums = [1,2,3,4], k = 5
* Output: 2
* Explanation: Starting with nums = [1,2,3,4]:
* - Remove numbers 1 and 4, then nums = [2,3]
* - Remove numbers 2 and 3, then nums = []
* There are no more pairs that sum up to 5, hence a total of 2 operations.
* Example 2:
*
* Input: nums = [3,1,3,4,3], k = 6
* Output: 1
* Explanation: Starting with nums = [3,1,3,4,3]:
* - Remove the first two 3's, then nums = [1,4,3]
* There are no more pairs that sum up to 6, hence a total of 1 operation.
*
*
* Constraints:
*
* 1 <= nums.length <= 10^5
* 1 <= nums[i] <= 10^9
* 1 <= k <= 10^9
* @see <a href="https://leetcode.com/problems/max-number-of-k-sum-pairs/">LeetCode</a>
*/
fun maxOperations(nums: IntArray, k: Int): Int {
val countMap = mutableMapOf<Int, Int>()
var result = 0
nums.forEach { num ->
val complement = k - num
if (countMap.getOrDefault(complement, 0) > 0) {
countMap[complement] = countMap[complement]!! - 1
result += 1
} else {
countMap[num] = 1 + countMap.getOrDefault(num, 0)
}
}
return result
}
| 0 | Kotlin | 0 | 0 | 0511a831aeee96e1bed3b18550be87a9110c36cb | 1,397 | leetcode-75 | Apache License 2.0 |
src/day07/Day07.kt | idle-code | 572,642,410 | false | {"Kotlin": 79612} | package day07
import readInput
interface FSNode {
val size: Int
val name: String
}
class File(override val size: Int, override val name: String) : FSNode {
override fun toString(): String {
return "File '$name' ($size size)"
}
}
class Directory(override val name: String) : FSNode {
constructor(name: String, parentDir: Directory?) : this(name) {
parent = parentDir ?: this
}
override val size: Int
get() = children.sumOf { node -> node.size }
val children: MutableList<FSNode> = mutableListOf()
private val files: List<File>
get() = children.filterIsInstance<File>()
private val subdirectories: List<Directory>
get() = children.filterIsInstance<Directory>()
lateinit var parent: Directory
fun cd(childDirectoryName: String): Directory {
return when (childDirectoryName) {
"/" -> rootDirectory
".." -> parent
else -> {
var childDirectory =
subdirectories.find { node -> node.name == childDirectoryName }
if (childDirectory == null) {
childDirectory = Directory(childDirectoryName, this)
children.add(childDirectory)
}
childDirectory
}
}
}
fun tryAddChild(childNode: FSNode) {
if (children.find { node -> node.name == childNode.name } == null)
children.add(childNode)
}
fun filterRecursive(predicate: (FSNode) -> Boolean): List<FSNode> {
val results = ArrayList<FSNode>()
if (predicate(this))
results.add(this)
files.filterTo(results, predicate)
for (subdir in subdirectories) {
results.addAll(subdir.filterRecursive(predicate))
}
return results
}
override fun toString(): String {
return "Dir $name (${children.size} files)"
}
}
var rootDirectory = Directory("/", null)
fun parseFileTree(input: List<String>): Directory {
rootDirectory = Directory("/", null)
var currentDirectory: Directory = rootDirectory
for (line in input) {
if (line.startsWith("$ cd")) {
val directoryToGo = line.substringAfter("$ cd ")
currentDirectory = currentDirectory.cd(directoryToGo)
} else if (line.startsWith("dir ")) {
val directoryName = line.substringAfter("dir ")
val listedDirectory = Directory(directoryName, currentDirectory)
currentDirectory.tryAddChild(listedDirectory)
} else if (line == "$ ls") {
// Handling of file list is in the following branch
} else {
val size = line.substringBefore(" ").toInt()
val fileName = line.substringAfter(" ")
val listedFile = File(size, fileName)
currentDirectory.tryAddChild(listedFile)
}
}
return rootDirectory
}
fun toScript(input: List<String>): Directory {
for (line in input) {
if (line == "$ ls")
; // do nothing
else if (line.startsWith("$ cd"))
println(line.substringAfter("$ "))
else if (line.startsWith("dir ")) {
val directoryName = line.substringAfter("dir ")
println("mkdir $directoryName")
} else {
val size = line.substringBefore(" ").toInt()
val fileName = line.substringAfter(" ")
println("truncate -s $size $fileName")
}
}
return rootDirectory
}
fun main() {
fun part1(input: List<String>): Int {
val root = parseFileTree(input)
val directoriesLessThan100000 = root.filterRecursive { node -> node is Directory && node.size <= 100000 }
return directoriesLessThan100000.sumOf { node -> node.size }
}
fun part2(input: List<String>): Int {
val root = parseFileTree(input)
val fileSystemSize = 70000000
val minimumFreeSpace = 30000000
val freeSpace = fileSystemSize - root.size
val toFreeAtLeast = minimumFreeSpace - freeSpace
check(toFreeAtLeast > 0)
val candidateDirectories = root.filterRecursive { node -> node is Directory && node.size >= toFreeAtLeast }
val smallestDir = candidateDirectories.minByOrNull { it.size }!!
return smallestDir.size
}
val testInput = readInput("sample_data", 7)
println(part1(testInput))
check(part1(testInput) == 95437)
val mainInput = readInput("main_data", 7)
println(part1(mainInput))
check(part1(mainInput) == 1543140)
// println(part2(testInput))
// check(part2(testInput) == 0)
println(part2(mainInput))
check(part2(mainInput) == 1117448)
}
| 0 | Kotlin | 0 | 0 | 1b261c399a0a84c333cf16f1031b4b1f18b651c7 | 4,713 | advent-of-code-2022 | Apache License 2.0 |
src/year2023/day09/Solution.kt | TheSunshinator | 572,121,335 | false | {"Kotlin": 144661} | package year2023.day09
import arrow.core.nonEmptyListOf
import utils.ProblemPart
import utils.readInputs
import utils.runAlgorithm
fun main() {
val (realInput, testInputs) = readInputs(2023, 9, transform = ::parse)
runAlgorithm(
realInput = realInput,
testInputs = testInputs,
part1 = ProblemPart(
expectedResultsForTests = nonEmptyListOf(114),
algorithm = getSolution(::nextNumber),
),
part2 = ProblemPart(
expectedResultsForTests = nonEmptyListOf(2),
algorithm = getSolution(::previousNumber),
),
)
}
private fun parse(input: List<String>): List<List<Long>> = input.map { line ->
line.splitToSequence(' ').map { it.toLong() }.toList()
}
private fun getSolution(computeNumber: (List<Long>) -> Long): (List<List<Long>>) -> Long = { input ->
input.asSequence()
.map(computeNumber)
.sum()
}
private fun nextNumber(numberSequence: List<Long>) = computeSteps(numberSequence).sumOf { it.last() }
private fun computeSteps(numberSequence: List<Long>): List<List<Long>> {
return generateSequence(numberSequence) { previousSequence ->
previousSequence.zipWithNext { a, b -> b - a }
}
.takeWhile { sequence -> sequence.any { it != 0L } }
.toList()
.asReversed()
}
private fun previousNumber(numberSequence: List<Long>): Long {
return computeSteps(numberSequence).asSequence()
.map { it.first() }
.fold(0L) { nextLinePreviousNumber, currentFirstNumber -> currentFirstNumber - nextLinePreviousNumber }
}
| 0 | Kotlin | 0 | 0 | d050e86fa5591447f4dd38816877b475fba512d0 | 1,592 | Advent-of-Code | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/LongestPalindromicSubsequence.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.max
/**
* 516. Longest Palindromic Subsequence
* @see <a href="https://leetcode.com/problems/longest-palindromic-subsequence/">Source</a>
*/
fun interface LongestPalindromicSubsequence {
fun longestPalindromeSubseq(s: String): Int
}
/**
* Approach 1: Recursive Dynamic Programming
*/
class LPSRecursiveDP : LongestPalindromicSubsequence {
override fun longestPalindromeSubseq(s: String): Int {
val n: Int = s.length
val memo = Array(n) { IntArray(n) }
return lps(s, 0, n - 1, memo)
}
private fun lps(s: String, i: Int, j: Int, memo: Array<IntArray>): Int {
if (memo[i][j] != 0) {
return memo[i][j]
}
if (i > j) {
return 0
}
if (i == j) {
return 1
}
if (s[i] == s[j]) {
memo[i][j] = lps(s, i + 1, j - 1, memo) + 2
} else {
memo[i][j] = max(lps(s, i + 1, j, memo), lps(s, i, j - 1, memo))
}
return memo[i][j]
}
}
/**
* Approach 2: Iterative Dynamic Programming
*/
class LPSIterativeDP : LongestPalindromicSubsequence {
override fun longestPalindromeSubseq(s: String): Int {
val dp = Array(s.length) { IntArray(s.length) }
for (i in s.length - 1 downTo 0) {
dp[i][i] = 1
for (j in i + 1 until s.length) {
if (s[i] == s[j]) {
dp[i][j] = dp[i + 1][j - 1] + 2
} else {
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
}
}
}
return dp[0][s.length - 1]
}
}
/**
* Approach 3: Dynamic Programming with Space Optimization
*/
class LPSOptimizedDP : LongestPalindromicSubsequence {
override fun longestPalindromeSubseq(s: String): Int {
val n: Int = s.length
val dp = IntArray(n)
var dpPrev = IntArray(n)
for (i in n - 1 downTo 0) {
dp[i] = 1
for (j in i + 1 until n) {
if (s[i] == s[j]) {
dp[j] = dpPrev[j - 1] + 2
} else {
dp[j] = max(dpPrev[j], dp[j - 1])
}
}
dpPrev = dp.clone()
}
return dp[n - 1]
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,906 | kotlab | Apache License 2.0 |
src/Day05/Day05.kt | rooksoto | 573,602,435 | false | {"Kotlin": 16098} | package Day05
import profile
import readInputActual
import readInputTest
import java.util.*
private typealias Board = List<Stack<Char>>
private typealias Instruction = Triple<Int, Int, Int>
private const val DAY = "Day05"
fun main() {
fun part1(input: List<String>): String {
input.toRawGameComponents()
.toParsedGameComponents()
.let { (board, instructions) ->
instructions.forEach {
it.applyTo(board)
}
return board.topLetters()
}
}
fun part2(input: List<String>): String =
input.toRawGameComponents()
.toParsedGameComponents()
.let { (board, instructions) ->
instructions.forEach {
it.applyMultiTo(board)
}
return board.topLetters()
}
val testInput = readInputTest(DAY)
val input = readInputActual(DAY)
check(part1(testInput) == "CMZ")
profile(shouldLog = true) {
println("Part 1: ${part1(input)}")
} // Answer: SPFMVDTZT @ 18ms
check(part2(testInput) == "MCD")
profile(shouldLog = true) {
println("Part 2: ${part2(input)}")
} // Answer: ZFSJBPRFP @ 4ms
}
private fun List<Any?>.breakPoint(): Int =
indexOf("")
private fun List<String>.toRawGameComponents(): Triple<List<String>, String, List<String>> {
val boardStringList = subList(0, breakPoint() - 1)
val columnsString = subList(breakPoint() - 1, breakPoint()).first()
val instructionsStringList = subList(breakPoint() + 1, size)
return Triple(boardStringList, columnsString, instructionsStringList)
}
private fun Triple<List<String>, String, List<String>>.toParsedGameComponents(
): Pair<Board, List<Instruction>> {
val columns = second.last { it.isDigit() }.toString().toInt()
val board: List<Stack<Char>> = MutableList(columns) { Stack() }
first.reversed()
.map { row ->
row.chunked(4)
.map { it.dropLast(1) }
.map { it.filterNot { c -> c == ']' || c == '[' } }
.map { it.first() }
.forEachIndexed { index, s ->
if (s.isLetter()) board[index].push(s)
}
}
val instructions = third.map {
it.split(" ")
.filter { s -> s.first().isDigit() }
.map(String::toInt)
.let { (a, b, c) -> Instruction(a, b, c) }
}
return Pair(board, instructions)
}
private fun Instruction.applyTo(board: Board) {
val (a, b, c) = this
repeat(a) { board[c - 1].push(board[b - 1].pop()) }
}
private fun Instruction.applyMultiTo(board: Board) {
val (a, b, c) = this
val temp = Stack<Char>()
repeat(a) { temp.push(board[b - 1].pop()) }
repeat(a) { board[c - 1].push(temp.pop()) }
}
private fun Board.topLetters(): String =
map { it.peek() }
.joinToString("")
| 0 | Kotlin | 0 | 1 | 52093dbf0dc2f5f62f44a57aa3064d9b0b458583 | 2,938 | AoC-2022 | Apache License 2.0 |
src/Day05.kt | EnyediPeti | 573,882,116 | false | {"Kotlin": 8717} | fun main() {
class Move(val count: Int, val fromStack: Int, val toStack: Int)
fun part1(input: List<String>): String {
val blankLineIndex = input.indexOfFirst { it.isBlank() }
val crates = input.subList(0, blankLineIndex - 1)
val moves = input.subList(blankLineIndex + 1, input.size)
val stackNo = input[blankLineIndex - 1].last { it.isDigit() }.digitToInt()
val stacks = List(size = stackNo) { mutableListOf<Char>() }
crates.asReversed().forEach { crateLevel ->
crateLevel.chunked(4).forEachIndexed { index, content ->
content[1].takeIf { it.isLetter() }?.let { stacks[index].add(it) }
}
}
val mappedMoves = moves.map {
val digits = it.split(" ")
Move(
count = digits[1].toInt(),
fromStack = digits[3].toInt() - 1,
toStack = digits[5].toInt() - 1
)
}
mappedMoves.forEach { move ->
repeat(move.count) {
stacks[move.toStack].add(stacks[move.fromStack].removeLast())
}
}
return stacks.map {
it.lastOrNull() ?: ""
}.joinToString("")
}
fun part2(input: List<String>): String {
fun <T> MutableList<T>.removeLast(count: Int): List<T> {
val removeIndex = this.size - count
return List(size = count) { this.removeAt(removeIndex) }
}
val blankLineIndex = input.indexOfFirst { it.isBlank() }
val crates = input.subList(0, blankLineIndex - 1)
val moves = input.subList(blankLineIndex + 1, input.size)
val stackNo = input[blankLineIndex - 1].last { it.isDigit() }.digitToInt()
val stacks = List(size = stackNo) { mutableListOf<Char>() }
crates.asReversed().forEach { crateLevel ->
crateLevel.chunked(4).forEachIndexed { index, content ->
content[1].takeIf { it.isLetter() }?.let { stacks[index].add(it) }
}
}
val mappedMoves = moves.map {
val digits = it.split(" ")
Move(
count = digits[1].toInt(),
fromStack = digits[3].toInt() - 1,
toStack = digits[5].toInt() - 1
)
}
mappedMoves.forEach { move ->
stacks[move.toStack].addAll(stacks[move.fromStack].removeLast(move.count))
}
return stacks.map {
it.lastOrNull() ?: ""
}.joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 845ef2275540a6454a97a9e4c71f239a5f2dc295 | 2,816 | AOC2022 | Apache License 2.0 |
src/Day03.kt | kedvinas | 572,850,757 | false | {"Kotlin": 15366} | fun main() {
fun part1(input: List<String>): Int {
var sum = 0
for (i in input) {
val firstHalf = i.substring(0, i.length / 2).toCharArray().toSet()
val secondHalf = i.substring(i.length / 2).toCharArray().toSet()
val intersection = firstHalf.intersect(secondHalf).elementAt(0)
sum += if (intersection.isLowerCase()) {
intersection.code - 96
} else {
intersection.code - 38
}
}
return sum
}
fun part2(input: List<String>): Int {
return input.chunked(3).sumOf { group ->
val charArrays = group.map {
it.toCharArray().toSet()
}
val intersection = charArrays.fold(charArrays[0]) { acc, chars -> acc.intersect(chars) }
.elementAt(0)
if (intersection.isLowerCase()) {
intersection.code - 96
} else {
intersection.code - 38
}
}
}
val testInput = readInput("Day03_test")
println(part2(testInput))
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 04437e66eef8cf9388fd1aaea3c442dcb02ddb9e | 1,269 | adventofcode2022 | Apache License 2.0 |
src/Day08.kt | vladislav-og | 573,326,483 | false | {"Kotlin": 27072} | fun main() {
fun createForestMap(input: List<String>): ArrayList<ArrayDeque<Int>> {
val forestMap = arrayListOf<ArrayDeque<Int>>()
for (row in input) {
forestMap.add(ArrayDeque(row.map { it.digitToInt() }))
}
return forestMap
}
fun isSeen(treePosX: Int, treesPosY: Int, forestMap: ArrayList<ArrayDeque<Int>>): Boolean {
val curTreeHeight = forestMap[treesPosY][treePosX]
if (forestMap[treesPosY].subList(0, treePosX).max() < curTreeHeight) {
return true
}
if (forestMap[treesPosY].subList(treePosX + 1, forestMap.size).max() < curTreeHeight) {
return true
}
for (i in 0 until treesPosY) {
if (forestMap[i][treePosX] >= curTreeHeight) {
break
}
if (i == treesPosY - 1) {
return true
}
}
for (i in (treesPosY + 1) until forestMap.size) {
if (forestMap[i][treePosX] >= curTreeHeight) {
break
}
if (i == forestMap.size - 1) {
return true
}
}
return false
}
fun isSeenWithScore(treePosX: Int, treesPosY: Int, forestMap: ArrayList<ArrayDeque<Int>>): Int {
val curTreeHeight = forestMap[treesPosY][treePosX]
val treesSeen = arrayListOf(0, 0, 0, 0)
for (i in treePosX - 1 downTo 0) {
treesSeen[0]++
if (forestMap[treesPosY][i] >= curTreeHeight) {
break
}
}
for (i in (treePosX + 1) until forestMap.size) {
treesSeen[1]++
if (forestMap[treesPosY][i] >= curTreeHeight) {
break
}
}
for (i in treesPosY - 1 downTo 0) {
treesSeen[2]++
if (forestMap[i][treePosX] >= curTreeHeight) {
break
}
}
for (i in (treesPosY + 1) until forestMap.size) {
treesSeen[3]++
if (forestMap[i][treePosX] >= curTreeHeight) {
break
}
}
return treesSeen.fold(1) { acc, i -> acc * i }
}
fun part1(input: List<String>): Int {
val forestMap = createForestMap(input)
var score = forestMap.size * 4 - 4
for (i in 1 until forestMap.size - 1) {
for (j in 1 until forestMap.size - 1) {
if (isSeen(i, j, forestMap)) score++
}
}
return score
}
fun part2(input: List<String>): Int {
val forestMap = createForestMap(input)
var score = 0
for (i in 1 until forestMap.size - 1) {
for (j in 1 until forestMap.size - 1) {
val curScore = isSeenWithScore(i, j, forestMap)
if (curScore > score) {
score = curScore
}
}
}
return score
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
println(part1(testInput))
check(part1(testInput) == 21)
println(part2(testInput))
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input)) // 1794
println(part2(input)) // 199272
}
| 0 | Kotlin | 0 | 0 | b230ebcb5705786af4c7867ef5f09ab2262297b6 | 2,866 | advent-of-code-2022 | Apache License 2.0 |
src/Day12.kt | catcutecat | 572,816,768 | false | {"Kotlin": 53001} | import kotlin.system.measureTimeMillis
fun main() {
measureTimeMillis {
Day12.run {
solve1(31) // 330
solve2(29) // 321
}
}.let { println("Total: $it ms") }
}
object Day12 : Day.LineInput<Day12.Data, Int>("12") {
data class Data(val map: List<String>, val start: Pair<Int, Int>, val end: Pair<Int, Int>)
private val directions = arrayOf(1 to 0, 0 to 1, -1 to 0, 0 to -1)
override fun parse(input: List<String>): Data {
var start = 0 to 0
var end = 0 to 0
for (row in input.indices) {
for ((col, elevation) in input[row].withIndex()) {
if (elevation == 'S') start = row to col
else if (elevation == 'E') end = row to col
}
}
return Data(input, start, end)
}
override fun part1(data: Data): Int {
val (map, start, end) = data
val (startRow, startCol) = start
val steps = Array(map.size) { IntArray(map[it].length) { -1 } }.also { it[startRow][startCol] = 0 }
val (targetRow, targetCol) = end
val next = ArrayDeque<Pair<Int, Int>>().apply {
directions.map { (r, c) -> startRow + r to startCol + c }.forEach { (newRow, newCol) ->
if (newRow in steps.indices && newCol in steps[newRow].indices && map[newRow][newCol] <= 'b') {
steps[newRow][newCol] = 1
addLast(newRow to newCol)
}
}
}
while (next.isNotEmpty()) {
val (row, col) = next.removeFirst()
directions.map { (r, c) -> row + r to col + c }.forEach { (newRow, newCol) ->
if (newRow in steps.indices && newCol in steps[newRow].indices && steps[newRow][newCol] == -1) {
if (newRow == targetRow && newCol == targetCol) {
if (map[row][col] >= 'y') return steps[row][col] + 1
} else if (map[newRow][newCol] <= map[row][col] + 1) {
steps[newRow][newCol] = steps[row][col] + 1
next.addLast(newRow to newCol)
}
}
}
}
error("Cannot reach the destination.")
}
override fun part2(data: Data): Int {
val (map, _, end) = data
val (endRow, endCol) = end
val steps = Array(map.size) { IntArray(map[it].length) { -1 } }.also { it[endRow][endCol] = 0 }
val next = ArrayDeque<Pair<Int, Int>>().apply {
directions.map { (r, c) -> endRow + r to endCol + c }.forEach { (row, col) ->
if (row in steps.indices && col in steps[row].indices && map[row][col] >= 'y') {
steps[row][col] = 1
addLast(row to col)
}
}
}
while (next.isNotEmpty()) {
val (row, col) = next.removeFirst()
directions.map { (r, c) -> row + r to col + c }.forEach { (newRow, newCol) ->
if (newRow in steps.indices && newCol in steps[newRow].indices && steps[newRow][newCol] == -1) {
if (map[newRow][newCol] == 'a' || map[newRow][newCol] == 'S') {
if (map[row][col] == 'b') return steps[row][col] + 1
} else if (map[newRow][newCol] + 1 >= map[row][col]) {
steps[newRow][newCol] = steps[row][col] + 1
next.addLast(newRow to newCol)
}
}
}
}
error("Cannot reach the destination.")
}
} | 0 | Kotlin | 0 | 2 | fd771ff0fddeb9dcd1f04611559c7f87ac048721 | 3,586 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/day-04.kt | warriorzz | 434,696,820 | false | {"Kotlin": 16719} | package com.github.warriorzz.aoc
import java.nio.file.Files
import java.nio.file.Path
private fun main() {
println("Day 04:")
val lines = Files.readAllLines(Path.of("./input/day-04.txt"))
val pickedNumbers = lines[0].split(",").map { it.toInt() }
val boards = lines.subList(fromIndex = 2, lines.size).windowed(6, 6).map {
Board(it.subList(0, 5).map { string ->
string.split(" ").filter { filter -> filter != "" }.toMutableList().map { cell ->
Cell(cell.toInt())
}.toMutableList()
})
}
val finalScores = boards.map {
it.getFinalScore(pickedNumbers)
}
println("Solution part 1: ${finalScores.minByOrNull { it.first }!!.second}")
println("Solution part 2: ${finalScores.maxByOrNull { it.first }!!.second}")
}
data class Board(
val content: List<MutableList<Cell>>
) {
fun getFinalScore(markedNumbers: List<Int>): Pair<Int, Int> {
markedNumbers.forEachIndexed numbers@{ index, int ->
content.forEach {
it.forEach { cell ->
if (cell.number == int) {
cell.isMarked = true
if (checkWon()) {
return index to int * content.map { cellList ->
cellList.map { cell -> if (cell.isMarked) 0 else cell.number }.reduce { acc, i -> acc + i }
}.reduce { acc, i -> acc + i }
}
}
}
}
}
return -1 to -1
}
private fun checkWon(): Boolean {
var won = false
(0 until 5).forEach {
if (content[it][0].isMarked && content[it][1].isMarked && content[it][2].isMarked && content[it][3].isMarked && content[it][4].isMarked) won =
true
if (content[0][it].isMarked && content[1][it].isMarked && content[2][it].isMarked && content[3][it].isMarked && content[4][it].isMarked) won =
true
}
return won
}
}
data class Cell(val number: Int, var isMarked: Boolean = false)
fun day04() = main()
| 0 | Kotlin | 1 | 0 | 0143f59aeb8212d4ff9d65ad30c7d6456bf28513 | 2,214 | aoc-21 | MIT License |
src/Day05.kt | chbirmes | 572,675,727 | false | {"Kotlin": 32114} | import java.util.Stack
fun main() {
fun part1(input: String): String {
val split = input.split("\n\n")
val cargoBay = CargoBay.parse(split[0])
split[1].lines()
.map { parseInstruction(it) }
.forEach {
cargoBay.moveSingleCrates(it.first, it.second, it.third)
}
return cargoBay.topCrates()
}
fun part2(input: String): String {
val split = input.split("\n\n")
val cargoBay = CargoBay.parse(split[0])
split[1].lines()
.map { parseInstruction(it) }
.forEach {
cargoBay.moveStackOfCrates(it.first, it.second, it.third)
}
return cargoBay.topCrates()
}
val testInput = readInputAsString("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInputAsString("Day05")
println(part1(input))
println(part2(input))
}
private val instructionRegex = "move (\\d+) from (\\d+) to (\\d+)".toRegex()
private fun parseInstruction(line: String) =
instructionRegex.find(line)!!
.groupValues
.drop(1)
.map { it.toInt() }
.let { Triple(it[0], it[1], it[2]) }
private class CargoBay(val stacks: List<Stack<Char>>) {
fun moveSingleCrates(amount: Int, source: Int, target: Int) {
repeat(amount) {
stacks[target - 1].push(stacks[source - 1].pop())
}
}
fun moveStackOfCrates(amount: Int, source: Int, target: Int) {
val temp = Stack<Char>()
repeat(amount) {
temp.push(stacks[source - 1].pop())
}
repeat(amount) {
stacks[target - 1].push(temp.pop())
}
}
fun topCrates() =
stacks
.map { it.peek() }
.joinToString(separator = "")
companion object {
fun parse(s: String): CargoBay {
val lines = s.lines()
val numberOfStacks = lines.last().last().digitToInt()
val stacks = buildList {
repeat(numberOfStacks) { add(Stack<Char>()) }
}
lines.dropLast(1).asReversed().forEach { line ->
stacks.forEachIndexed { index, stack ->
val positionInString = index * 4 + 1
line.elementAtOrNull(positionInString)?.let {
if (it.isLetter()) {
stack.push(it)
}
}
}
}
return CargoBay(stacks)
}
}
}
| 0 | Kotlin | 0 | 0 | db82954ee965238e19c9c917d5c278a274975f26 | 2,579 | aoc-2022 | Apache License 2.0 |
src/Day07/Day07.kt | G-lalonde | 574,649,075 | false | {"Kotlin": 39626} | package Day07
import readInput
fun main() {
fun buildRoot(root: NTree<String>, input: List<String>) {
var cwd = root
var previousCommand = ""
for (line in input) {
val split = line.split(" ")
if (split[0] == "$") {
when (split[1]) {
"cd" -> {
previousCommand = "cd"
if (split[2] == "/") {
continue
} else if (split[2] == "..") {
cwd = cwd.parent!!
} else {
var child = cwd.find(split[2])
if (child == null) {
child = NTree(split[2], isDir = true)
cwd.appendChild(child)
}
cwd = child
}
}
"ls" -> {
previousCommand = "ls"
}
}
} else {
if (previousCommand == "ls") {
if (split[0] == "dir") {
if (cwd.find(split[1]) == null) {
cwd.appendChild(NTree(split[1], isDir = true))
}
} else {
val size = Integer.parseInt(split[0])
if (cwd.find(split[1]) == null) {
cwd.appendChild(NTree(split[1], isDir = false, size = size))
}
}
}
}
}
}
fun part1(input: List<String>): Int {
val atMostSize = 100000
val root = NTree("/", isDir = true)
buildRoot(root, input)
val sizes = arrayListOf<Int>()
root.traverseDepthFirst {
if (it.size() <= atMostSize) {
if (it.isDir) {
sizes.add(it.size())
}
}
}
return sizes.sum()
}
fun part2(input: List<String>): Int {
val totalDiskSpace = 70000000
val spaceForUpdate = 30000000
val root = NTree("/", isDir = true)
buildRoot(root, input)
val unusedSpace = totalDiskSpace - root.size()
val spaceNeeded = spaceForUpdate - unusedSpace
val sizes = arrayListOf<Int>()
root.traverseDepthFirst {
if (it.size() >= spaceNeeded) {
if (it.isDir) {
sizes.add(it.size())
}
}
}
return sizes.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07/Day07_test")
check(part1(testInput) == 95437) { "Got instead : ${part1(testInput)}" }
check(part2(testInput) == 24933642) { "Got instead : ${part2(testInput)}" }
val input = readInput("Day07/Day07")
println("Answer for part 1 : ${part1(input)}")
println("Answer for part 2 : ${part2(input)}")
}
class NTree<T>(name: T, var isDir: Boolean, var size: Int = 0) {
var name: T? = name
var parent: NTree<T>? = null
var children: MutableList<NTree<T>> = mutableListOf()
fun appendChild(child: NTree<T>) {
child.parent = this
this.children.add(child)
}
fun find(name: T): NTree<T>? {
for (child in children) {
if (child.name == name) {
return child
}
}
return null
}
fun traverseDepthFirst(visit: (NTree<T>) -> Unit) {
visit(this)
for (child in children) {
child.traverseDepthFirst(visit)
}
}
fun size(): Int {
var size = 0
traverseDepthFirst {
size += it.size
}
return size
}
}
| 0 | Kotlin | 0 | 0 | 3463c3228471e7fc08dbe6f89af33199da1ceac9 | 3,877 | aoc-2022 | Apache License 2.0 |
src/Day03.kt | timmiller17 | 577,546,596 | false | {"Kotlin": 44667} | fun main() {
fun part1(input: List<String>): Int {
val rucksacks = input.map { listOf(it.substring(0, it.length / 2), it.substring(it.length/2, it.length))}
val commonItems = mutableListOf<String>()
val itemPriorityMap = mutableMapOf<String, Int>()
val lowers = CharProgression.fromClosedRange('a', 'z', 1)
val uppers = CharProgression.fromClosedRange('A', 'Z', 1)
var i = 1
for (char in lowers) {
itemPriorityMap[char.toString()] = i++
}
for (char in uppers) {
itemPriorityMap[char.toString()] = i++
}
for (rucksack in rucksacks) {
val compartment1 = rucksack[0]
val compartment2 = rucksack[1]
for (item in compartment1) {
if (compartment2.contains(item)) {
commonItems.add(item.toString())
break
}
}
}
return commonItems.sumOf { itemPriorityMap[it]!! }
}
fun part2(input: List<String>): Int {
val rucksackGroups = input.chunked(3)
val commonItems = mutableListOf<String>()
val itemPriorityMap = mutableMapOf<String, Int>()
val lowers = CharProgression.fromClosedRange('a', 'z', 1)
val uppers = CharProgression.fromClosedRange('A', 'Z', 1)
var i = 1
for (char in lowers) {
itemPriorityMap[char.toString()] = i++
}
for (char in uppers) {
itemPriorityMap[char.toString()] = i++
}
for (group in rucksackGroups) {
for (item in group[0]) {
if (group[1].contains(item) && group[2].contains(item)) {
commonItems.add(item.toString())
break
}
}
}
return commonItems.sumOf { itemPriorityMap[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")
part1(input).println()
part2(input).println()
} | 0 | Kotlin | 0 | 0 | b6d6b647c7bb0e6d9e5697c28d20e15bfa14406c | 2,172 | advent-of-code-2022 | Apache License 2.0 |
03.kts | pin2t | 725,922,444 | false | {"Kotlin": 48856, "Go": 48364, "Shell": 54} | import java.util.*
import java.util.Collections.singleton
data class PartNumber(val start: Pair<Int, Int>, val end: Pair<Int, Int>, val value: Int)
val scanner = Scanner(System.`in`)
val numbers = HashSet<PartNumber>()
val symbols = HashSet<Pair<Int, Int>>()
val stars = HashSet<Pair<Int, Int>>()
var y = 0
while (scanner.hasNext()) {
val line = scanner.nextLine()
line.forEachIndexed { x, c -> if (c != '.' && !c.isDigit()) symbols.add(Pair(x, y)) }
line.forEachIndexed { x, c -> if (c == '*') stars.add(Pair(x, y)) }
var x = 0
while (x < line.length) {
if (line[x].isDigit()) {
val start = Pair(x, y)
x++
while (x < line.length && line[x].isDigit()) x++
numbers.add(PartNumber(start, Pair(x - 1, y), line.substring(start.first, x).toInt()))
}
x++
}
y++
}
fun around(pos: Pair<Int, Int>, symbols: Set<Pair<Int, Int>>): Boolean {
fun contains(dx: Int, dy: Int): Boolean = symbols.contains(Pair(pos.first + dx, pos.second + dy))
return contains(-1, -1) || contains(-1, 0) || contains(-1, 1) || contains(0, -1) || contains(0, 1) || contains(1, -1) || contains(1, 0) || contains(1, 1)
}
var ratios = 0
for (star in stars) {
val naround = numbers.filter { around(it.start, singleton(star)) || around(it.end, singleton(star)) }.toList()
if (naround.size == 2) {
ratios += naround[0].value * naround[1].value
}
}
var sum = numbers.filter { around(it.start, symbols) || around(it.end, symbols) }.sumOf { it.value }
println("$sum $ratios")
| 0 | Kotlin | 1 | 0 | 7575ab03cdadcd581acabd0b603a6f999119bbb6 | 1,564 | aoc2023 | MIT License |
day3/day3/src/main/kotlin/Day5.kt | teemu-rossi | 437,894,529 | false | {"Kotlin": 28815, "Rust": 4678} | import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
data class Point(val x: Int, val y: Int) {
companion object {
fun from(string: String): Point {
val s = string.split(",").mapNotNull { it.trim().takeUnless { it.isEmpty() } }
require(s.size == 2)
return Point(s[0].toInt(), s[1].toInt())
}
}
}
data class Line(val a: Point, val b: Point) {
companion object {
fun from(string: String): Line {
val s = string.split("->").mapNotNull { it.trim().takeUnless { it.isEmpty() } }
require(s.size == 2)
return Line(Point.from(s[0]), Point.from(s[1]))
}
}
}
data class Field(
val numbers: MutableList<Int>,
val span: Int
) {
fun get(x: Int, y: Int): Int = numbers[y * span + x]
fun inc(x: Int, y: Int) = set(x, y, get(x ,y) + 1)
fun set(x: Int, y: Int, value: Int) { numbers[y * span + x] = value }
fun incLine(line: Line) {
val minx = min(line.a.x, line.b.x)
val maxx = max(line.a.x, line.b.x)
val miny = min(line.a.y, line.b.y)
val maxy = max(line.a.y, line.b.y)
if (line.a.x == line.b.x) {
for (y in min(line.a.y, line.b.y)..max(line.a.y, line.b.y)) {
inc(line.a.x, y)
}
} else if (line.a.y == line.b.y) {
for (x in min(line.a.x, line.b.x)..max(line.a.x, line.b.x)) {
inc(x, line.a.y)
}
} else if (maxx - minx == maxy - miny) {
var x = line.a.x
var y = line.a.y
val dx = if (line.b.x > line.a.x) 1 else -1
val dy = if (line.b.y > line.a.y) 1 else -1
do {
inc(x, y)
x += dx
y += dy
} while (x != line.b.x)
inc(x, y)
} else {
assert(false) { "Invalid line $line" }
}
}
}
fun main(args: Array<String>) {
val values = generateSequence(::readLine)
.mapNotNull { line -> line.trim().takeUnless { trimmed -> trimmed.isBlank() } }
.toList()
val lines = values.map { Line.from(it) }
val width = lines.maxOf { max(it.a.x, it.b.x) } + 1
val height = lines.maxOf { max(it.a.y, it.b.y) } + 1
val field = Field(MutableList(width * height) { 0 }, width)
for (line in lines) {
field.incLine(line)
}
val count = field.numbers.count { it >= 2 }
println(count)
}
| 0 | Kotlin | 0 | 0 | 16fe605f26632ac2e134ad4bcf42f4ed13b9cf03 | 2,466 | AdventOfCode | MIT License |
src/poyea/aoc/mmxxii/day05/Day05.kt | poyea | 572,895,010 | false | {"Kotlin": 68491} | package poyea.aoc.mmxxii.day05
import poyea.aoc.utils.readInput
typealias Stack = ArrayDeque<Char>
data class InputData(val parts: List<String>, val allStacks: List<Stack>)
fun processInput(input: String): InputData {
return input.let {
val parts = input.split("\n\n")
val stacks = parts[0].split("\n").dropLast(1)
val allStacks = List(stacks.last().length / 4 + 1) { Stack() }
stacks.forEach {
it.chunked(4).forEachIndexed { index, s ->
if (!s[1].isWhitespace()) {
allStacks[index].addLast(s[1])
}
}
}
InputData(parts, allStacks)
}
}
fun part1(input: String): String {
return input.let {
val (parts, allStacks) = processInput(input)
parts[1].split("\n").forEach {
val tokens = it.split(" ")
val count = tokens[1].toInt()
val start = tokens[3].toInt()
val end = tokens[5].toInt()
for (i in 1..count) {
allStacks[end - 1].addFirst(allStacks[start - 1].removeFirst())
}
}
allStacks.map { it.removeFirst() }.joinToString("")
}
}
fun part2(input: String): String {
return input.let {
val (parts, allStacks) = processInput(input)
parts[1].split("\n").forEach {
val tokens = it.split(" ")
val count = tokens[1].toInt()
val start = tokens[3].toInt()
val end = tokens[5].toInt()
for (element in allStacks[start - 1].take(count).reversed()) {
allStacks[end - 1].addFirst(element)
allStacks[start - 1].removeFirst()
}
}
allStacks.map { it.removeFirst() }.joinToString("")
}
}
fun main() {
println(part1(readInput("Day05")))
println(part2(readInput("Day05")))
}
| 0 | Kotlin | 0 | 1 | fd3c96e99e3e786d358d807368c2a4a6085edb2e | 1,870 | aoc-mmxxii | MIT License |
src/Day08.kt | bkosm | 572,912,735 | false | {"Kotlin": 17839} | typealias Id = Int
typealias Height = Int
typealias Tree = Pair<Height, Id>
typealias TreeRow = List<Tree>
fun toTreeMatrixFlat(input: List<String>): List<TreeRow> {
var lastId = Int.MAX_VALUE
val horizontal = input.map { line ->
line.split("").filter(String::isNotBlank).map { Tree(it.toInt(), lastId--) }
}
val vertical = mutableListOf<TreeRow>().also {
val height = input.size
val width = input.first().length
for (i in 0 until width) {
val column = mutableListOf<Tree>()
for (j in 0 until height) {
column.add(horizontal[j][i])
}
it.add(column)
}
}
return horizontal + vertical
}
fun toHeightMatrix(input: List<String>): List<List<Height>> = input.map { line ->
line.split("").filter(String::isNotBlank).map { it.toInt() }
}
object Day08 : DailyRunner<Int, Int> {
override fun do1(input: List<String>, isTest: Boolean): Int {
val rows = toTreeMatrixFlat(input)
val allVisible = rows.map { visibleFrom(it) + visibleFrom(it.reversed()) }
return allVisible.flatten().toSet().count()
}
private fun visibleFrom(row: TreeRow): List<Tree> = mutableListOf(row.first()).apply {
var lastVisible = row.first()
row.drop(1).forEach {
if (it.first > lastVisible.first) {
lastVisible = it
add(it)
}
}
}
override fun do2(input: List<String>, isTest: Boolean): Int {
val scores = toHeightMatrix(input).run {
mapIndexed { j, row ->
row.mapIndexed { i, tree ->
scenicScore(this, i, j, tree)
}
}
}
return scores.flatten().max()
}
private fun scenicScore(matrix: List<List<Height>>, x: Int, y: Int, height: Height): Int {
var left = 0
for (i in x - 1 downTo 0) {
left++
if (height <= matrix[i][y]) break
}
var right = 0
for (i in x + 1 until matrix.first().size) {
right++
if (height <= matrix[i][y]) break
}
var up = 0
for (j in y - 1 downTo 0) {
up++
if (height <= matrix[x][j]) break
}
var down = 0
for (j in y + 1 until matrix.size) {
down++
if (height <= matrix[x][j]) break
}
return left * right * up * down
}
}
fun main() {
Day08.run()
}
| 0 | Kotlin | 0 | 1 | 3f9cccad1e5b6ba3e92cbd836a40207a2f3415a4 | 2,518 | aoc22 | Apache License 2.0 |
src/Day07.kt | esp-er | 573,196,902 | false | {"Kotlin": 29675} | package patriker.day07
import patriker.utils.*
import kotlin.collections.ArrayDeque
data class Directory(val name: String, var size: Int = 0 , var subDirs: List<Directory> = emptyList())
fun main() {
val testInput = readInput("Day07_test")
//val input = readInput("Day07_input")
println(solvePart1(testInput))
val input = readInput("Day07_input")
println(solvePart1(input))
//input.forEach{ println(solvePart1(it))}
println(solvePart2(testInput))
println(solvePart2(input))
//testInput.forEach{ println(solvePart2(it))}
//input.forEach{ println(solvePart2(it))}
}
fun String.isInteger() : Boolean {
return this.toIntOrNull() != null
}
fun calculateTotals(d: Directory, dirMap: Map<String,Directory>): Int{
val childrenSize = d.subDirs.sumOf{ calculateTotals( dirMap[it.name]!!, dirMap) }
return d.size + childrenSize
}
fun solvePart2(input: List<String>): Int {
val currentDir = ArrayDeque<Directory>().apply {
this.addFirst(Directory("root"))
}
var directories = mutableMapOf<String, Directory>()
input.forEach { line ->
if (line.startsWith("$")) {
val cmds = line.split(" ")
if (cmds[1] == "cd") {
when (cmds[2]) {
"/" -> {
currentDir.clear(); currentDir.addFirst(Directory("root"))
}
".." -> currentDir.removeFirst()
else -> {
currentDir.addFirst(Directory("${currentDir[0].name}/${cmds[2]}"))
}
}
}
} else {
val contents = line.split(" ")
val dirOrSize = contents.first()
when {
dirOrSize.isInteger() -> {
currentDir.first().size += dirOrSize.toInt()
directories[currentDir[0].name] = currentDir.first()
}
dirOrSize == "dir" -> {
currentDir[0].subDirs += Directory("${currentDir[0].name}/${contents[1]}")
directories[currentDir[0].name] = currentDir.first()
}
}
}
}
//println(directories)
val freeSpace = 70000000 - calculateTotals(directories["root"]!!, directories)
return directories.values.minOf { dir ->
val size = calculateTotals(dir, directories)
if(freeSpace + size >= 30000000)
size
else
Int.MAX_VALUE
}
}
fun solvePart1(input: List<String>): Int {
val currentDir = ArrayDeque<Directory>().apply {
this.addFirst(Directory("root"))
}
var directories = mutableMapOf<String, Directory>()
input.forEach { line ->
if (line.startsWith("$")) {
val cmds = line.split(" ")
if (cmds[1] == "cd") {
when (cmds[2]) {
"/" -> {
currentDir.clear(); currentDir.addFirst(Directory("root"))
}
".." -> currentDir.removeFirst()
else -> {
currentDir.addFirst(Directory("${currentDir[0].name}/${cmds[2]}"))
}
}
}
} else {
val contents = line.split(" ")
val dirOrSize = contents.first()
when {
dirOrSize.isInteger() -> {
currentDir.first().size += dirOrSize.toInt()
directories[currentDir[0].name] = currentDir.first()
}
dirOrSize == "dir" -> {
currentDir[0].subDirs += Directory("${currentDir[0].name}/${contents[1]}")
directories[currentDir[0].name] = currentDir.first()
}
}
}
}
//println(directories)
val smallDirsSum =
directories.values.sumOf{ dir ->
val size = calculateTotals(dir , directories)
if( size <= 100000)
size
else 0
}
return smallDirsSum
}
| 0 | Kotlin | 0 | 0 | f46d09934c33d6e5bbbe27faaf2cdf14c2ba0362 | 4,096 | aoc2022 | Apache License 2.0 |
src/day11/Day11.kt | dkoval | 572,138,985 | false | {"Kotlin": 86889} | package day11
import readInputAsString
import java.util.*
private const val DAY_ID = "11"
private data class Monkey(
val id: Int,
val items: List<Int>,
val operator: Operator,
val v: Value,
val divisor: Int,
val throwToIfTrue: Int,
val throwToIfFalse: Int
)
private enum class Operator : (Int, Int) -> Int {
ADD {
override fun invoke(a: Int, b: Int): Int = a + b
},
MULT {
override fun invoke(a: Int, b: Int): Int = a * b
};
companion object {
fun fromString(s: String): Operator = when (s) {
"+" -> ADD
"*" -> MULT
else -> error("Unknown operation: $s")
}
}
}
private sealed class Value {
data class Num(val x: Int) : Value()
object Old : Value()
companion object {
fun fromString(s: String): Value = if (s == "old") Old else Num(s.toInt())
}
}
private sealed interface WorryLevel {
infix fun isDivisibleBy(divisor: Int): Boolean
fun updateWith(op: Operator, v: Value): WorryLevel
class Part1(initial: Int, private val k: Int) : WorryLevel {
private var x = initial
override fun isDivisibleBy(divisor: Int): Boolean = x % divisor == 0
override fun updateWith(op: Operator, v: Value): WorryLevel {
x = op(x, v.get())
x /= k
return this
}
private fun Value.get(): Int = when (this) {
is Value.Num -> this.x
is Value.Old -> x
}
}
class Part2(initial: Int, private val divisors: Set<Int>) : WorryLevel {
// (a + b) % c = (a % c + b % c) % c
// (a * b) % c = (a % c * b % c) % c
private val remainders = divisors.associateWithTo(mutableMapOf()) { divisor -> initial % divisor }
override fun isDivisibleBy(divisor: Int): Boolean = remainders[divisor] == 0
override fun updateWith(op: Operator, v: Value): WorryLevel {
for (divisor in divisors) {
remainders[divisor] = op(remainders[divisor]!!, v.get(divisor)) % divisor
}
return this
}
private fun Value.get(divisor: Int): Int = when (this) {
is Value.Num -> this.x % divisor
is Value.Old -> remainders[divisor]!!
}
}
}
fun main() {
fun parseInput(input: String): List<Monkey> {
val operation = """old ([*+]) (\d+|old)""".toRegex()
return input.split("\n\n").mapIndexed { index, s ->
val lines = s.split("\n")
val items = lines[1].removePrefix(" Starting items: ").split(", ").map { it.toInt() }
val (op, v) = lines[2].removePrefix(" Operation: new = ").let { operation.find(it)!!.destructured }
val divisor = lines[3].removePrefix(" Test: divisible by ").toInt()
val throwToMonkeyIfTrue = lines[4].removePrefix(" If true: throw to monkey ").toInt()
val throwToMonkeyIfFalse = lines[5].removePrefix(" If false: throw to monkey ").toInt()
Monkey(
index,
items,
Operator.fromString(op),
Value.fromString(v),
divisor,
throwToMonkeyIfTrue,
throwToMonkeyIfFalse
)
}
}
fun solve(monkeys: List<Monkey>, rounds: Int, transform: (x: Int) -> WorryLevel): Long {
val n = monkeys.size
val state: List<Queue<WorryLevel>> = monkeys.map { it.items.mapTo(ArrayDeque()) { x -> transform(x) } }
val inspectedItems = IntArray(n)
repeat(rounds) {
state.forEachIndexed { index, items ->
with(monkeys[index]) {
inspectedItems[index] += items.size
while (!items.isEmpty()) {
val old = items.poll()
val new = old.updateWith(operator, v)
val throwTo = if (new isDivisibleBy divisor) throwToIfTrue else throwToIfFalse
state[throwTo].offer(new)
}
}
}
}
return inspectedItems
.also { it.sortDescending() }
.take(2)
.fold(1L) { acc, x -> acc * x }
}
fun part1(input: String): Long {
val rounds = 20
val k = 3
val monkeys = parseInput(input)
return solve(monkeys, rounds) { x -> WorryLevel.Part1(x, k) }
}
fun part2(input: String): Long {
val rounds = 10000
val monkeys = parseInput(input)
val divisors = monkeys.asSequence().map { it.divisor }.toSet()
return solve(monkeys, rounds) { x -> WorryLevel.Part2(x, divisors) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInputAsString("day${DAY_ID}//Day${DAY_ID}_test")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158L)
val input = readInputAsString("day${DAY_ID}/Day$DAY_ID")
println(part1(input)) // answer = 76728
println(part2(input)) // answer = 21553910156
}
| 0 | Kotlin | 1 | 0 | 791dd54a4e23f937d5fc16d46d85577d91b1507a | 5,099 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/g0301_0400/s0329_longest_increasing_path_in_a_matrix/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0301_0400.s0329_longest_increasing_path_in_a_matrix
// #Hard #Top_Interview_Questions #Dynamic_Programming #Depth_First_Search #Breadth_First_Search
// #Graph #Memoization #Topological_Sort #2022_11_12_Time_322_ms_(92.65%)_Space_39.2_MB_(100.00%)
class Solution {
fun longestIncreasingPath(matrix: Array<IntArray>): Int {
var maxIncreasingSequenceCount = 0
val n = matrix.size - 1
val m = matrix[0].size - 1
val memory = Array(n + 1) { IntArray(m + 1) }
for (i in matrix.indices) {
for (j in matrix[i].indices) {
maxIncreasingSequenceCount = Math.max(maxIncreasingSequenceCount, move(i, j, n, m, matrix, memory))
}
}
return maxIncreasingSequenceCount
}
private fun move(row: Int, col: Int, n: Int, m: Int, matrix: Array<IntArray>, memory: Array<IntArray>): Int {
if (memory[row][col] == 0) {
var count = 1
// move down
if (row < n && matrix[row + 1][col] > matrix[row][col]) {
count = Math.max(count, move(row + 1, col, n, m, matrix, memory) + 1)
}
// move right
if (col < m && matrix[row][col + 1] > matrix[row][col]) {
count = Math.max(count, move(row, col + 1, n, m, matrix, memory) + 1)
}
// move up
if (row > 0 && matrix[row - 1][col] > matrix[row][col]) {
count = Math.max(count, move(row - 1, col, n, m, matrix, memory) + 1)
}
// move left
if (col > 0 && matrix[row][col - 1] > matrix[row][col]) {
count = Math.max(count, move(row, col - 1, n, m, matrix, memory) + 1)
}
memory[row][col] = count
}
return memory[row][col]
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,812 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/aoc23/day05.kt | asmundh | 573,096,020 | false | {"Kotlin": 56155} | package aoc23
import getLongList
import runTask
import utils.InputReader
fun day5part1(input: List<List<String>>): Long {
val seedMapRoute = getSeedMapRoute(input)
seedMapRoute.traverse()
return seedMapRoute.seeds.minOf { it.currentValue }
}
fun day5part2(input: List<List<String>>): Long {
val seedMapRoute = getSeedMapRoute(input)
return seedMapRoute.traversePart2().minOf { it.lower }
}
fun SeedMapRoute.traverse() {
seeds.asSequence().forEach { seed ->
categories.asSequence().forEach mapping@{ plantMappings ->
plantMappings.asSequence().forEach { plantMap ->
with(plantMap) {
if (seed.currentValue >= source && seed.currentValue <= source + plusBy) {
seed.currentValue = destination + seed.currentValue - source
return@mapping
}
}
}
}
}
}
fun SeedMapRoute.traversePart2(): List<Seed2> {
return seeds2.flatMap { seedRange ->
var seedRanges: List<Seed2> = listOf(seedRange)
categories.asSequence().forEach { category ->
for (i in seedRanges.indices) {
category.asSequence().forEach { plantMap ->
if (!seedRanges.all { it.mappedByCategory }) {
seedRanges = seedRanges.flatMap { it.applyMap(plantMap) }
}
}
}
seedRanges.forEach { it.mappedByCategory = false }
}
seedRanges
}
}
fun getSeedMapRoute(input: List<List<String>>) =
SeedMapRoute(
seeds = getSeeds(input.first().first()),
seeds2 = getSeedsPart2(input.first().first()),
categories = input.drop(1).map { getPlantMap(it) }
)
fun getSeeds(inputSeeds: String): List<Seed> =
inputSeeds.substringAfter(':').getLongList().map { Seed(startValue = it, currentValue = it) }
fun getSeedsPart2(inputSeeds: String): List<Seed2> =
inputSeeds.substringAfter(':').getLongList()
.chunked(2)
.map {
Seed2(
it.first(),
it.first() + it.last()
)
}
fun getPlantMap(section: List<String>): List<PlantMap> =
section.drop(1).map { row ->
row.getLongList()
.let {
PlantMap(
source = it[1],
destination = it[0],
plusBy = it[2]
)
}
}
data class SeedMapRoute(
val seeds: List<Seed>,
val seeds2: List<Seed2>,
val categories: List<List<PlantMap>>
)
data class Seed(
val startValue: Long,
var currentValue: Long
)
data class Seed2(
val lower: Long,
val upper: Long,
var mappedByCategory: Boolean = false
) {
fun applyMap(plantMap: PlantMap): List<Seed2> {
if (mappedByCategory || upper < plantMap.source || lower > plantMap.upperLimitSource()) {
return listOf(this)
}
if (upper > plantMap.upperLimitSource() && lower < plantMap.source) { // Spans entire range +more
return listOf(
Seed2(lower, plantMap.source - 1),
Seed2(plantMap.upperLimitSource() + 1, upper),
Seed2(plantMap.source + plantMap.getStep(), plantMap.upperLimitSource() + plantMap.getStep(), true),
)
}
val newSeeds: MutableList<Seed2> = mutableListOf()
var newLower = lower
var newUpper = upper
if (lower < plantMap.source && (upper in plantMap.source..plantMap.upperLimitSource())) {
newSeeds.add(
Seed2(lower, plantMap.source - 1)
)
newLower = plantMap.source
}
if (upper > plantMap.upperLimitSource() && (lower in plantMap.source..plantMap.upperLimitSource())) {
newSeeds.add(
Seed2(plantMap.upperLimitSource() + 1, upper)
)
newUpper = plantMap.upperLimitSource()
}
newSeeds.add(
Seed2(
lower = newLower + plantMap.getStep(),
upper = newUpper + plantMap.getStep(),
mappedByCategory = true
)
)
return newSeeds
}
}
data class PlantMap(
val destination: Long,
val source: Long,
val plusBy: Long
) {
fun upperLimitSource() = source + plusBy - 1
fun getStep(): Long =
destination - source
}
fun main() {
val input: List<List<String>> = InputReader.getInputListSeparatedByBlankLines(5)
runTask("D5p1") { day5part1(input) }
runTask("D5p2") { day5part2(input) }
}
| 0 | Kotlin | 0 | 0 | 7d0803d9b1d6b92212ee4cecb7b824514f597d09 | 4,636 | advent-of-code | Apache License 2.0 |
src/year2022/07/Day07.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2022.`07`
import readInput
sealed class Record {
abstract val title: String
abstract var size: Long
data class File(
override val title: String,
override var size: Long,
val parent: Dir,
) : Record()
data class Dir(
override val title: String,
override var size: Long,
val parent: Dir?,
val files: MutableList<Record>,
) : Record()
}
sealed class Line {
object LS : Line()
data class CD(val directory: String) : Line()
data class Dir(val title: String) : Line()
data class File(val size: Long, val title: String) : Line()
companion object {
fun parseLine(string: String): Line {
val nodes = string.split(" ")
return if (nodes.first() == "$") {
when (nodes[1]) {
"ls" -> LS
"cd" -> CD(nodes[2])
else -> error("!!")
}
} else {
if (nodes[0] == "dir") {
Dir(nodes[1])
} else {
File(nodes[0].toLong(), nodes[1])
}
}
}
}
}
fun calculateSizes(currentRecord: Record): Long {
return when (currentRecord) {
is Record.Dir -> {
val size = currentRecord.files.sumOf { calculateSizes(it) }
currentRecord.size = size
size
}
is Record.File -> currentRecord.size
}
}
fun fillListWithDirsThatAre(
currentDir: Record,
list: MutableList<Record>,
predicate: (Long) -> Boolean
) {
if (currentDir is Record.Dir) {
if (predicate(currentDir.size)) {
list.add(currentDir)
}
currentDir.files.forEach { fillListWithDirsThatAre(it, list, predicate) }
}
}
fun builtTree(input: List<String>): Record.Dir {
val rootDir: Record.Dir = Record.Dir("/", 0, null, mutableListOf())
var currentDir: Record.Dir = rootDir
input
.drop(1)
.map { Line.parseLine(it) }
.forEach { command ->
when (command) {
is Line.CD -> {
currentDir = if (command.directory == "..") {
currentDir.parent!!
} else {
currentDir
.files
.filterIsInstance<Record.Dir>()
.find { file -> file.title == command.directory }!!
}
}
is Line.File -> {
val record = Record.File(
title = command.title,
size = command.size,
parent = currentDir,
)
currentDir.files.add(record)
}
is Line.Dir -> {
val record = Record.Dir(command.title, 0, currentDir, mutableListOf())
currentDir.files.add(record)
}
is Line.LS -> Unit
}
}
return rootDir
}
fun main() {
fun part1(input: List<String>): Long {
val totalSize = 100_000
val rootDir: Record.Dir = builtTree(input)
.also { calculateSizes(it) }
return mutableListOf<Record>()
.also { fillListWithDirsThatAre(rootDir, it) { size -> size <= totalSize } }
.sumOf { it.size }
}
fun part2(input: List<String>): Long {
val rootDir: Record.Dir = builtTree(input)
val filledSize = calculateSizes(rootDir)
val updateSize = 30_000_000
val totalSize = 70_000_000
val unusedSpace = updateSize - (totalSize - filledSize)
return mutableListOf<Record>()
.also { fillListWithDirsThatAre(rootDir, it) { size -> size >= unusedSpace } }
.minOf { it.size }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
val part1Test = part2(testInput)
println(part1Test)
check(part1Test == 24933642L)
val input = readInput("Day07")
println("Part1: " + part1(input))
println("Part2: " + part2(input))
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 4,225 | KotlinAdventOfCode | Apache License 2.0 |
src/aoc22/Day18.kt | mihassan | 575,356,150 | false | {"Kotlin": 123343} | @file:Suppress("PackageDirectoryMismatch")
package aoc22.day18
import lib.Solution
data class Cube(val x: Int, val y: Int, val z: Int) {
fun adjacentCubes(): Set<Cube> = setOf(
Cube(x - 1, y, z),
Cube(x + 1, y, z),
Cube(x, y - 1, z),
Cube(x, y + 1, z),
Cube(x, y, z - 1),
Cube(x, y, z + 1)
)
companion object {
fun parse(str: String): Cube {
val (x, y, z) = str.split(",").map(String::toInt)
return Cube(x, y, z)
}
}
}
data class Bound3D(val xRange: IntRange, val yRange: IntRange, val zRange: IntRange) {
operator fun contains(cube: Cube): Boolean =
cube.x in xRange && cube.y in yRange && cube.z in zRange
fun growBy(amount: Int): Bound3D =
Bound3D(xRange.growBy(amount), yRange.growBy(amount), zRange.growBy(amount))
fun cubesOnBorder(): Set<Cube> = buildSet {
xRange.forEach { x ->
yRange.forEach { y ->
add(Cube(x, y, zRange.first))
add(Cube(x, y, zRange.last))
}
}
yRange.forEach { y ->
zRange.forEach { z ->
add(Cube(xRange.first, y, z))
add(Cube(xRange.last, y, z))
}
}
zRange.forEach { z ->
xRange.forEach { x ->
add(Cube(x, yRange.first, z))
add(Cube(x, yRange.last, z))
}
}
}
private fun IntRange.growBy(amount: Int): IntRange = first - amount..last + amount
companion object {
fun of(cubes: Set<Cube>): Bound3D {
val xRange = cubes.minOf { it.x }..cubes.maxOf { it.x }
val yRange = cubes.minOf { it.y }..cubes.maxOf { it.y }
val zRange = cubes.minOf { it.z }..cubes.maxOf { it.z }
return Bound3D(xRange, yRange, zRange)
}
}
}
typealias Input = Set<Cube>
typealias Output = Int
private val solution = object : Solution<Input, Output>(2022, "Day18") {
override fun parse(input: String): Input = input.lines().map { Cube.parse(it) }.toSet()
override fun format(output: Output): String = "$output"
override fun part1(input: Input): Output {
return input.sumOf { cube ->
cube.adjacentCubes().filter { it !in input }.size
}
}
override fun part2(input: Input): Output {
val bound = Bound3D.of(input).growBy(1)
val cubesToVisit = bound.cubesOnBorder().toMutableSet()
val visitedCubes = mutableSetOf<Cube>()
var result = 0
while (cubesToVisit.isNotEmpty()) {
val cube = cubesToVisit.first()
visitedCubes.add(cube)
cube.adjacentCubes().forEach { nextCube ->
if (nextCube in input) {
result += 1
} else if (nextCube in bound && nextCube !in visitedCubes && nextCube !in cubesToVisit) {
cubesToVisit.add(nextCube)
}
}
cubesToVisit.remove(cube)
}
return result
}
}
fun main() = solution.run()
| 0 | Kotlin | 0 | 0 | 698316da8c38311366ee6990dd5b3e68b486b62d | 2,751 | aoc-kotlin | Apache License 2.0 |
src/Day07.kt | CrazyBene | 573,111,401 | false | {"Kotlin": 50149} | fun main() {
data class Directory(val name: String) {
val directories = mutableMapOf<String, Directory>()
val files = mutableMapOf<String, Long>()
fun addDirectory(directory: Directory) {
directories[directory.name] = directory
}
fun addFile(name: String, size: Long) {
files[name] = size
}
fun toPrettyString(indentation: Int = 0): String {
var string = "- $name (dir)"
for(directory in directories.values) {
string += "\n"
for(i in 0 .. indentation) string += "\t"
string += directory.toPrettyString(indentation + 1)
}
for(file in files.toList()) {
string += "\n"
for(i in 0 .. indentation) string += "\t"
string += "- ${file.first} (file, size=${file.second})"
}
return string
}
fun getSize(): Long {
val sizeOfChildren = directories.values.sumOf {
it.getSize()
}
val sizeOfFiles = files.values.sumOf {
it
}
return sizeOfChildren + sizeOfFiles
}
fun getDirectoriesWithSize(): List<Pair<String, Long>> {
val d = mutableListOf<Pair<String, Long>>()
d.add(name to getSize())
directories.values.forEach {
d.addAll(it.getDirectoriesWithSize())
}
return d
}
}
fun getCurrentDirectory(rootDirectory: Directory, currentPath: List<String>): Directory {
var currentDirectory = rootDirectory
for(d in currentPath) {
currentDirectory = currentDirectory.directories[d]!!
}
return currentDirectory
}
fun List<String>.toFileSystem(): Directory {
val currentPath = mutableListOf<String>()
val rootDirectory = Directory("/")
this.forEach {
val currentDirectory = getCurrentDirectory(rootDirectory, currentPath)
val words = it.split(" ")
when (words[0]) {
"$" -> {
if (words[1] == "cd") {
when (words[2]) {
"/" -> currentPath.clear()
".." -> currentPath.removeLast()
else -> currentPath.add(words[2])
}
}
}
"dir" -> {
currentDirectory.addDirectory(Directory(words[1]))
}
else -> {
currentDirectory.addFile(words[1], words[0].toLong())
}
}
}
return rootDirectory
}
fun part1(input: List<String>) : Long {
val rootDirectory = input.toFileSystem()
return rootDirectory.getDirectoriesWithSize()
.filter {
it.second <= 100000
}
.sumOf { it.second }
}
fun part2(input: List<String>) : Long {
val rootDirectory = input.toFileSystem()
val freeSpace = 70000000 - rootDirectory.getSize()
val neededSpace = 30000000 - freeSpace
return rootDirectory.getDirectoriesWithSize()
.filter {
it.second >= neededSpace
}
.minOf { it.second }
}
val testInput = readInput("Day07Test")
check(part1(testInput) == 95437.toLong())
check(part2(testInput) == 24933642.toLong())
val input = readInput("Day07")
println("Question 1 - Answer: ${part1(input)}")
println("Question 2 - Answer: ${part2(input)}")
} | 0 | Kotlin | 0 | 0 | dfcc5ba09ca3e33b3ec75fe7d6bc3b9d5d0d7d26 | 3,693 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/shared/Algorithms.kt | waikontse | 572,850,856 | false | {"Kotlin": 63258} | package shared
import java.util.*
typealias AdjacencyMatrix = Array<IntArray>
typealias Node = Int
class Algorithms {
data class Edge(val endPoint: Node, val cost: Int)
data class GraphSize(val width: Int, val height: Int)
class Graph(val size: GraphSize) {
private val graph: MutableMap<Node, MutableList<Edge>> = mutableMapOf()
init {
(0 until (size.height * size.width)).onEach { graph[it] = mutableListOf() }
}
fun addEdges(node: Node, edges: List<Edge>) {
graph[node]?.addAll(edges)
}
fun getEdges(node: Node): List<Edge> {
return graph[node]?.toList() ?: listOf()
}
fun vertices(): Set<Node> = graph.keys
fun verticesCount(): Int = graph.keys.size
fun print() = graph.keys.onEach { println("From: $it with edges: ${getEdges(it)}") }
}
companion object {
fun dijkstra(firstNode: Node, graph: Graph): Pair<IntArray, Map<Node, Edge>> {
val distances = IntArray(graph.verticesCount()) { if (it == firstNode) 0 else Int.MAX_VALUE }
val visited = BooleanArray(graph.verticesCount()) { it == firstNode }
val pathMap = mutableMapOf<Node, Edge>()
val pq = PriorityQueue<Edge> { left, right -> left.cost - right.cost }
pq.offer(Edge(firstNode, 0))
while (pq.isNotEmpty()) {
val u = pq.poll().endPoint
val distU = distances[u]
for (edge in graph.getEdges(u)) {
val distV = distances[edge.endPoint]
val pathWeight = edge.cost + distU
if (!visited[edge.endPoint] || (distV > pathWeight)) {
visited[edge.endPoint] = true
distances[edge.endPoint] = pathWeight
pathMap[edge.endPoint] = edge
pq.offer(Edge(edge.endPoint, pathWeight))
}
}
}
return Pair(distances, pathMap)
}
/**
* Floyd-Warshall algorithm. An all pairs shortest path algorithm.
* Slower than Dijkstra, but is very compact code.
* N (the number of nodes) should be <= 450 (According to competitive programming book ed. 4)
*/
fun floydWarshall(adjacencyMatrix: AdjacencyMatrix): AdjacencyMatrix {
val adjacencyMatrixAllPairs = adjacencyMatrix.clone()
val v = adjacencyMatrix.size
for (k in 0 until v) {
for (i in 0 until v) {
for (j in 0 until v) {
adjacencyMatrixAllPairs[i][j] = Math.min(adjacencyMatrixAllPairs[i][j], adjacencyMatrixAllPairs[i][k] + adjacencyMatrixAllPairs[k][j])
}
}
}
return adjacencyMatrixAllPairs
}
}
}
| 0 | Kotlin | 0 | 0 | 860792f79b59aedda19fb0360f9ce05a076b61fe | 2,908 | aoc-2022-in-kotllin | Creative Commons Zero v1.0 Universal |
src/main/kotlin/aoc2023/Day22.kt | Ceridan | 725,711,266 | false | {"Kotlin": 110767, "Shell": 1955} | package aoc2023
import kotlin.math.max
import kotlin.math.min
class Day22 {
fun part1(input: List<String>): Int {
val bricks = parseInput(input)
val (landed, supportedBy, _) = fall(bricks)
val onlySupporterIds = getOnlySupporters(supportedBy)
return landed.size - onlySupporterIds.size
}
fun part2(input: List<String>): Long {
val bricks = parseInput(input)
val (landed, supportedBy, _) = fall(bricks)
val onlySupporterIds = getOnlySupporters(supportedBy)
var globalMoved = 0L
for (id in onlySupporterIds) {
val landedWithoutCurrent = landed.filter { it.id != id }
val (_, _, moved) = fall(landedWithoutCurrent)
globalMoved += moved
}
return globalMoved
}
private fun getOnlySupporters(supportedBy: Map<Int, Set<Int>>): Set<Int> =
supportedBy.filter { it.value.size == 1 }.flatMap { it.value }.toSet()
private fun fall(bricks: List<Brick>): Triple<List<Brick>, Map<Int, Set<Int>>, Long> {
val pile = mutableMapOf<Int, MutableSet<Brick>>()
val supportedBy = bricks.map { it.id }.associateWith { mutableSetOf<Int>() }
var moved = 0L
for (fallBrick in bricks.sortedBy { it.zr.first }) {
var landedZ = 1
for (maxZ in pile.keys.filter { it < fallBrick.zr.first }.sortedDescending()) {
for (landedBrick in pile[maxZ]!!) {
if (landedBrick.intersectOnXY(fallBrick)) {
supportedBy[fallBrick.id]!!.add(landedBrick.id)
landedZ = maxZ + 1
}
}
if (landedZ != 1) break
}
var newLandedBrick = fallBrick
if (fallBrick.zr.first != landedZ) {
newLandedBrick = fallBrick.fallTo(landedZ)
moved++
}
if (newLandedBrick.zr.last !in pile) {
pile[newLandedBrick.zr.last] = mutableSetOf()
}
pile[newLandedBrick.zr.last]!!.add(newLandedBrick)
}
return Triple(pile.values.flatten(), supportedBy, moved)
}
private fun parseInput(input: List<String>): List<Brick> = input.withIndex().map { (i, line) ->
val (p1, p2) = line.split('~').map { it.split(',') }
val (x1, y1, z1) = p1.map { it.toInt() }
val (x2, y2, z2) = p2.map { it.toInt() }
Brick(
i,
xr = IntRange(min(x1, x2), max(x1, x2)),
yr = IntRange(min(y1, y2), max(y1, y2)),
zr = IntRange(min(z1, z2), max(z1, z2))
)
}
data class Brick(val id: Int, val xr: IntRange, val yr: IntRange, val zr: IntRange) {
fun intersectOnXY(other: Brick): Boolean = xr.rangeIntersect(other.xr) && yr.rangeIntersect(other.yr)
fun fallTo(z: Int): Brick {
val deltaZ = zr.first - z
if (deltaZ == 0) return this
val newZr = IntRange(zr.first - deltaZ, zr.last - deltaZ)
return Brick(id, xr = xr, yr = yr, zr = newZr)
}
private fun IntRange.rangeIntersect(other: IntRange): Boolean =
!(this.first > other.last || this.last < other.first)
}
}
fun main() {
val day22 = Day22()
val input = readInputAsStringList("day22.txt")
println("22, part 1: ${day22.part1(input)}")
println("22, part 2: ${day22.part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 18b97d650f4a90219bd6a81a8cf4d445d56ea9e8 | 3,445 | advent-of-code-2023 | MIT License |
src/main/kotlin/com/colinodell/advent2023/Day15.kt | colinodell | 726,073,391 | false | {"Kotlin": 114923} | package com.colinodell.advent2023
class Day15(input: String) {
private val steps = input.split(",")
private fun hash(step: String) = step.fold(0) { acc, c -> (acc + c.code) * 17 % 256 }
private data class Step(val lens: String, val op: Char, val focalLength: Int?) {
companion object {
fun parse(input: String): Step {
val (label, op, focalLength) = Regex("""([a-z]+)([=-])(\d+)?""").matchEntire(input)!!.destructured
return Step(label, op[0], focalLength.toIntOrNull())
}
}
}
fun solvePart1() = steps.sumOf { hash(it) }
fun solvePart2() = steps
// Convert each step string into a Step object
.map { Step.parse(it) }
// Create an array of 256 boxes, each containing a list of lenses
.fold(Array(256) { mutableListOf<Pair<String, Int>>() }) { boxes, step ->
val targetBox = hash(step.lens)
if (step.op == '-') {
// Remove lens via filter, which reindexes the list if needed
boxes[targetBox] = boxes[targetBox].filter { it.first != step.lens }.toMutableList()
} else if (boxes[targetBox].any { it.first == step.lens }) {
// Replace existing lens in-place
boxes[targetBox] = boxes[targetBox].map { if (it.first == step.lens) Pair(it.first, step.focalLength!!) else it }.toMutableList()
} else {
// Add new lens to the end
boxes[targetBox].add(Pair(step.lens, step.focalLength!!))
}
boxes
}
// Calculate the focusing power
.flatMapIndexed { boxNumber, lenses ->
lenses.mapIndexed { slot, lens ->
(boxNumber + 1) * (slot + 1) * (lens.second)
}
}
// Sum the focusing powers
.sum()
}
| 0 | Kotlin | 0 | 0 | 97e36330a24b30ef750b16f3887d30c92f3a0e83 | 1,866 | advent-2023 | MIT License |
src/main/kotlin/Day12.kt | bent-lorentzen | 727,619,283 | false | {"Kotlin": 68153} | import java.time.LocalDateTime
import java.time.ZoneOffset
import kotlin.math.min
fun main() {
fun getValues(input: List<String>) =
input.map {
val list = it.split(" ")
list.first() to list[1]
}.map {
it.first to it.second.split(",").map { s -> s.toInt() }
}
fun permut4(s: String, groupSizes: List<Int>, localMaxPoints: Int): Long {
val remainingGroups = groupSizes.indices.associate { index ->
val numberOfGroups = groupSizes.lastIndex
val sizedOfRemainingGroups = groupSizes.mapIndexed { ix, i -> if (ix > index - 1) i else 0 }.sum()
val sizeOfMinimumGroupsSeparators = (numberOfGroups - index)
index - 1 to sizedOfRemainingGroups + sizeOfMinimumGroupsSeparators
}
fun permuteString(
s: CharSequence,
currentChar: Char,
previous: Char?,
index: Int,
groupNumber: Int,
localPointCount: Int,
hashCount: Int
): Long {
// Check for enough space for remaining groups
if (s.length - index < (remainingGroups[groupNumber] ?: 0))
return 0
if (index == s.length) {
return 1
}
return when (currentChar) {
'.' -> {
if (previous == '#' && hashCount != groupSizes[groupNumber]) return 0
if (previous == '.' && localPointCount == localMaxPoints) return 0
permuteString(s, s[min(index + 1, s.lastIndex)], currentChar, index + 1, groupNumber, localPointCount + 1, 0)
}
'#' -> {
if (previous == '.' && groupNumber == groupSizes.lastIndex) return 0
if (previous == '#' && hashCount == groupSizes[groupNumber]) return 0
permuteString(
s,
s[min(index + 1, s.lastIndex)],
currentChar,
index + 1,
if (previous == '#') groupNumber else groupNumber + 1,
0,
hashCount + 1
)
}
else -> {
permuteString(s, '#', previous, index, groupNumber, localPointCount, hashCount) +
permuteString(s, '.', previous, index, groupNumber, localPointCount, hashCount)
}
}
}
return permuteString(s, s[0], null, 0, -1, 0, 0)
}
fun countPermutations(recordToGroups: Pair<String, List<Int>>): Long {
val groupSizes = recordToGroups.second
val periodCount = recordToGroups.first.length - groupSizes.sum()
val maxPeriodLength = periodCount - (groupSizes.size - 1) + 1
val temp = permut4(recordToGroups.first, groupSizes, maxPeriodLength)
return temp
}
fun part1(input: List<String>): Long {
val lines = getValues(input)
var count = 0
return lines.sumOf {
count++
val temp = countPermutations(it)
temp
}
}
fun part2(input: List<String>): Long {
val lines = getValues(input)
var count = 0
val newLines = lines.map {
(0..4).joinToString("?") { _ ->
val temp = it.first
temp
} to (0..4).map { _ -> it.second }.flatten()
}
return newLines.sumOf {
val timer = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli()
count++
val temp = countPermutations(it)
println("$count = $temp ${LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() - timer} ms")
temp
}
}
val timer = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli()
val input =
readLines("day12-input.txt")
val result1 = part1(input)
"Result1: $result1".println()
println("${LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() - timer} ms")
val result2 = part2(input)
"Result2: $result2".println()
println("${LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() - timer} ms")
}
| 0 | Kotlin | 0 | 0 | 41f376bd71a8449e05bbd5b9dd03b3019bde040b | 4,277 | aoc-2023-in-kotlin | Apache License 2.0 |
aoc16/day_04/main.kt | viktormalik | 436,281,279 | false | {"Rust": 227300, "Go": 86273, "OCaml": 82410, "Kotlin": 78968, "Makefile": 13967, "Roff": 9981, "Shell": 2796} | import java.io.File
data class Room(val name: String, val id: Int, val checksum: String)
fun parseRoom(line: String): Room {
val regex = "(.*)-(\\d+)\\[(.*)\\]".toRegex()
val match = regex.find(line)
val name = match?.groupValues?.get(1)
val id = match?.groupValues?.get(2)?.toInt()
val checksum = match?.groupValues?.get(3)
return Room(name!!, id!!, checksum!!)
}
fun isRoom(room: Room): Boolean {
var occurrences = mutableMapOf<Char, Int>()
for (c in room.name) {
if (c != '-') {
var v = occurrences.getOrDefault(c, 0)
occurrences.put(c, v + 1)
}
}
val checksum = occurrences
.toList()
.sortedWith(compareBy({ (_, value) -> -value }, { (c, _) -> c }))
.map { (c, _) -> c }
.slice(0..4)
.toCharArray()
.joinToString("")
return checksum == room.checksum
}
fun decrypt(room: Room): String = room
.name
.map { if (it == '-') it else ((it.code - 'a'.code + room.id) % 26 + 'a'.code).toChar() }
.toCharArray()
.joinToString("")
fun main() {
val rooms = File("input").readLines().map { parseRoom(it) }
val first = rooms.filter { isRoom(it) }.map { it.id }.sum()
println("First: $first")
val second = rooms.find { decrypt(it) == "northpole-object-storage" }?.id
println("Second: $second")
}
| 0 | Rust | 1 | 0 | f47ef85393d395710ce113708117fd33082bab30 | 1,364 | advent-of-code | MIT License |
src/day24/Code.kt | fcolasuonno | 221,697,249 | false | null | package day24
import java.io.File
fun main() {
val name = if (false) "test.txt" else "input.txt"
val dir = ::main::class.java.`package`.name
val input = File("src/$dir/$name").readLines()
val (parsed, points) = parse(input)
println("Part 1 = ${part1(parsed, points)}")
println("Part 2 = ${part2(parsed, points)}")
}
fun parse(input: List<String>) = input.withIndex().flatMap { (j, s) ->
s.withIndex().mapNotNull { (i, c) -> if (c == '#') Pair(i, j) else null }
}.toSet() to input.withIndex().flatMap { (j, s) ->
s.withIndex().mapNotNull { (i, c) -> if (c.isDigit()) Pair(i, j) to c else null }
}.toMap()
fun part1(input: Set<Pair<Int, Int>>, nodesToExplores: Map<Pair<Int, Int>, Char>): Any? {
val frontier = nodesToExplores.filterValues { it == '0' }.keys.map { Triple(it, setOf('0'), 0) }.toSortedSet(compareBy<Triple<Pair<Int, Int>, Set<Char>, Int>> { it.third }
.thenByDescending { it.second.size }.thenBy { it.second.sorted().joinToString("") }.thenBy { it.first.first }.thenBy { it.first.second })
val seen = mutableMapOf<Set<Char>, MutableSet<Pair<Int, Int>>>()
while (frontier.isNotEmpty()) {
val current = frontier.first()
frontier.remove(current)
if (current.second.size == nodesToExplores.size) {
return current.third
}
seen.getOrPut(current.second) { mutableSetOf<Pair<Int, Int>>() }.add(current.first)
val next = current.first.neighbours().filter { it !in input && it !in seen.getValue(current.second) }.map {
Triple(it, current.second + (nodesToExplores[it] ?: '0'), current.third + 1)
}
frontier.addAll(next)
}
return 0
}
fun part2(input: Set<Pair<Int, Int>>, nodesToExplores: Map<Pair<Int, Int>, Char>): Any? {
val frontier = nodesToExplores.filterValues { it == '0' }.keys.map { Triple(it, setOf('0'), 0) }.toSortedSet(compareBy<Triple<Pair<Int, Int>, Set<Char>, Int>> { it.third }
.thenByDescending { it.second.size }.thenBy { it.second.sorted().joinToString("") }.thenBy { it.first.first }.thenBy { it.first.second })
val seen = mutableMapOf<Set<Char>, MutableSet<Pair<Int, Int>>>()
while (frontier.isNotEmpty()) {
val current = frontier.first()
frontier.remove(current)
if (current.second.size == nodesToExplores.size && nodesToExplores[current.first] == '0') {
return current.third
}
seen.getOrPut(current.second) { mutableSetOf<Pair<Int, Int>>() }.add(current.first)
val next = current.first.neighbours().filter { it !in input && it !in seen.getValue(current.second) }.map {
Triple(it, current.second + (nodesToExplores[it] ?: '0'), current.third + 1)
}
frontier.addAll(next)
}
return 0
}
private fun Pair<Int, Int>.neighbours() = listOf(
copy(first = first - 1),
copy(second = second - 1),
copy(first = first + 1),
copy(second = second + 1)
) | 0 | Kotlin | 0 | 0 | 73110eb4b40f474e91e53a1569b9a24455984900 | 2,975 | AOC2016 | MIT License |
src/main/kotlin/net/wrony/aoc2023/a13/thirteen.kt | kopernic-pl | 727,133,267 | false | {"Kotlin": 52043} | package net.wrony.aoc2023.a13
import kotlin.io.path.Path
import kotlin.io.path.readLines
fun gradeSymmetry(r: List<String>, pos: Int, len: Int): Int {
return r.subList(pos - len + 1, pos + 1).zip(r.subList(pos + 1, pos + len + 1).reversed())
.sumOf { (str1, str2) -> str1.zip(str2).count { (c1, c2) -> c1 != c2 } }
}
fun findSymmetryAxis(lines: List<String>, accuracyNeeded: Int): Int? {
return (0..<lines.size - 1).map { pos ->
val lenToCompare = minOf(pos + 1, lines.size - pos - 1)
pos to gradeSymmetry(lines, pos, lenToCompare)
}.firstOrNull { (_, diff) -> diff == accuracyNeeded }
?.let { (pos, _) -> pos }
}
fun main() {
Path("src/main/resources/13.txt").readLines()
.fold(mutableListOf(mutableListOf<String>())) { acc, line ->
if (line.isBlank()) {
acc.add(mutableListOf())
} else {
acc.last().add(line)
}
acc
}.map { it.toList() }.toList().map { pattern ->
pattern to pattern[0].indices.fold(
listOf<String>()
) { acc, idx ->
acc + pattern.map { row -> row[idx] }.joinToString("")
}
}.also {
it.sumOf { (rows, cols) ->
val r = findSymmetryAxis(rows, 0)
val c = findSymmetryAxis(cols, 0)
(c?.let { c + 1 } ?: 0) + (r?.let { (r + 1) * 100 } ?: 0)
}.let { r -> println("Part 1: $r") }
}.also {
it.sumOf { (rows, cols) ->
val r = findSymmetryAxis(rows, 1)
val c = findSymmetryAxis(cols, 1)
(c?.let { c + 1 } ?: 0) + (r?.let { (r + 1) * 100 } ?: 0)
}.let { r -> println("Part 2: $r") }
}
} | 0 | Kotlin | 0 | 0 | 1719de979ac3e8862264ac105eb038a51aa0ddfb | 1,781 | aoc-2023-kotlin | MIT License |
src/day09/Day09.kt | Regiva | 573,089,637 | false | {"Kotlin": 29453} | package day09
import readLines
fun main() {
val id = "09"
val testOutput = 13
val testOutputTwo = 36
val testInput = readInput("day$id/Day${id}_test")
val testInputTwo = readInput("day$id/Day${id}_test_two")
println(part1(testInput))
println(part2(testInputTwo))
check(part1(testInput) == testOutput)
check(part2(testInputTwo) == testOutputTwo)
val input = readInput("day$id/Day$id")
println(part1(input))
println(part2(input))
}
private fun readInput(fileName: String): List<Pair<Command, Int>> {
return readLines(fileName).map {
val (command, steps) = it.split(" ")
Command.valueOf(command) to steps.toInt()
}
}
// Time — O(), Memory — O()
private fun part1(input: List<Pair<Command, Int>>): Int {
var head = 0 to 0
var tail = 0 to 0
val visited = mutableSetOf<Pair<Int, Int>>()
input.forEach { (command, steps) ->
repeat(steps) {
head = head.applyCommand(command)
tail = tail.adjustTo(head)
visited.add(tail)
}
}
return visited.size
}
// Time — O(), Memory — O()
private fun part2(input: List<Pair<Command, Int>>): Int {
val rope = Array(10) { 0 to 0 }
val visited = mutableSetOf<Pair<Int, Int>>()
input.forEach { (command, steps) ->
repeat(steps) {
rope[0] = rope.first().applyCommand(command)
for (i in 1..rope.lastIndex) {
val prev = rope[i - 1]
rope[i] = rope[i].adjustTo(prev)
}
visited.add(rope.last())
}
}
return visited.size
}
private enum class Command(val dx: Int = 0, val dy: Int = 0) {
U(dy = +1),
D(dy = -1),
L(dx = -1),
R(dx = +1);
}
private fun Pair<Int, Int>.applyCommand(command: Command): Pair<Int, Int> {
val (x, y) = this
return (x + command.dx) to (y + command.dy)
}
private fun Pair<Int, Int>.adjustTo(head: Pair<Int, Int>): Pair<Int, Int> {
val (hx, hy) = head
var (tx, ty) = this
val dx = hx - tx
val dy = hy - ty
when {
dx > 1 -> {
tx++
if (dy > 0) ty++ else if (dy < 0) ty--
}
dx < -1 -> {
tx--
if (dy > 0) ty++ else if (dy < 0) ty--
}
dy > 1 -> {
ty++
if (dx > 0) tx++ else if (dx < 0) tx--
}
dy < -1 -> {
ty--
if (dx > 0) tx++ else if (dx < 0) tx--
}
}
return tx to ty
}
| 0 | Kotlin | 0 | 0 | 2d9de95ee18916327f28a3565e68999c061ba810 | 2,505 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/tr/emreone/adventofcode/days/Day16.kt | EmRe-One | 568,569,073 | false | {"Kotlin": 166986} | package tr.emreone.adventofcode.days
import java.util.*
import kotlin.collections.HashMap
object Day16 {
// Regex to match comma seperated words
val VALVE_PATTERN = """^Valve (?<name>\w+) has flow rate=(?<flowRate>\d+); tunnel(s)? lead(s)? to valve(s)? (?<adj>[\w\s,]+)$""".toRegex()
data class State(
var at: String,
var remainingTime: Int,
var elephantAt: String? = null,
var remainingElTime: Int? = null,
var openedValves: Set<String> = setOf(),
var totalFlow: Int = 0,
) : Comparable<State> {
override fun compareTo(other: State) = compareValuesBy(this, other) { -it.totalFlow }
}
data class Valve(val name: String, val flowRate: Int, val adjTunnels: List<String>)
class TunnelSystem {
lateinit var valves: Map<String, Valve>
lateinit var nonZeroNeighborsMap: Map<String, Map<String, Int>>
fun initTunnelsystem() {
this.nonZeroNeighborsMap = this.valves.keys.associateWith {
getNonZeroNeighbors(it)
}
}
fun getNonZeroNeighbors(curr: String, dist: Int = 0, visited: Set<String> = setOf()): Map<String, Int> {
val neighbours = HashMap<String, Int>()
for (adj in valves[curr]!!.adjTunnels.filter { it !in visited }) {
if (valves[adj]!!.flowRate != 0) {
neighbours[adj] = dist+1
}
for ((name, d) in getNonZeroNeighbors(adj, dist+1, visited + setOf(curr))) {
neighbours[name] = minOf(d, neighbours.getOrDefault(name, 1000))
}
}
return neighbours
}
fun solve(initialState: State): Int {
val queue = PriorityQueue<State>().also { it.add(initialState) }
var best = 0
val visited: MutableMap<List<String>, Int> = mutableMapOf()
while (queue.isNotEmpty()) {
var (at, remainingTime,
elephantAt, remainingElTime,
openedValves, totalFlow) = queue.remove()
best = maxOf(best, totalFlow)
val vis = (openedValves.toList() + listOf(at, elephantAt ?: "")).sorted()
if (visited.getOrDefault(vis, -1) >= totalFlow)
continue
visited[vis] = totalFlow
if (remainingElTime != null && elephantAt != null && remainingTime < remainingElTime) {
remainingTime = remainingElTime.also {
remainingElTime = remainingTime
}
at = elephantAt.also {
elephantAt = at
}
}
for ((neighbor, dist) in nonZeroNeighborsMap[at]!!) {
val newTime = remainingTime - dist - 1
val newFlow = totalFlow + this.valves[neighbor]!!.flowRate * newTime
if (newTime >= 0 && neighbor !in openedValves)
queue.add(
State(neighbor, newTime,
elephantAt, remainingElTime,
openedValves + setOf(neighbor), newFlow)
)
}
}
return best
}
companion object {
fun parseFrom(input: List<String>): TunnelSystem {
return TunnelSystem().apply {
valves = input
.map {line ->
val matches = VALVE_PATTERN.matchEntire(line)!!.groups as MatchNamedGroupCollection
matches.let {
Valve(
it["name"]!!.value,
it["flowRate"]!!.value.toInt(),
it["adj"]!!.value.split(", ")
)
}
}
.associateBy { it.name }
}
}
}
}
fun part1(input: List<String>): Int {
val tunnelSystem = TunnelSystem.parseFrom(input)
tunnelSystem.initTunnelsystem()
return tunnelSystem.solve(State("AA", 30))
}
fun part2(input: List<String>): Int {
val tunnelSystem = TunnelSystem.parseFrom(input)
tunnelSystem.initTunnelsystem()
return tunnelSystem.solve(State("AA", 26, "AA", 26))
}
}
| 0 | Kotlin | 0 | 0 | a951d2660145d3bf52db5cd6d6a07998dbfcb316 | 4,520 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/nl/dirkgroot/adventofcode/year2020/Day17.kt | dirkgroot | 317,968,017 | false | {"Kotlin": 187862} | package nl.dirkgroot.adventofcode.year2020
import nl.dirkgroot.adventofcode.util.Input
import nl.dirkgroot.adventofcode.util.Puzzle
import kotlin.math.max
import kotlin.math.min
class Day17(input: Input) : Puzzle() {
class Slice(val cubes: List<List<Boolean>>)
private val dimension by lazy {
val inputSlice = parseSlice(input.lines())
val inactiveSlice = inactiveCopyOf(inputSlice)
List(6) { inactiveSlice } + inputSlice + List(6) { inactiveSlice }
}
private val dimension4d by lazy {
val emptyDimension = List(dimension.size) {
Slice(List(dimension[0].cubes.size) {
List(dimension[0].cubes[0].size) { false }
})
}
List(6) { emptyDimension } + listOf(dimension) + List(6) { emptyDimension }
}
private fun parseSlice(lines: List<String>): Slice {
val width = lines[0].length + 12
val height = lines.size + 12
return Slice(
List(height) { index ->
if (index < 6 || index >= (height - 6)) List(width) { false }
else List(6) { false } + lines[index - 6].map { it == '#' } + List(6) { false }
}
)
}
private fun inactiveCopyOf(source: Slice) = Slice(source.cubes.map { it.map { false } })
override fun part1(): Int {
val dim = (1..6).fold(dimension) { dim, _ ->
generation(dim)
}
return countActiveCells(dim)
}
override fun part2(): Int {
val dim = (1..6).fold(dimension4d) { dim, _ ->
generation4d(dim)
}
return countActiveCells4d(dim)
}
private fun countActiveCells4d(dim: List<List<Slice>>) =
dim.sumOf { countActiveCells(it) }
private fun countActiveCells(dim: List<Slice>) = dim.sumOf {
it.cubes.sumOf { row ->
row.count { active -> active }
}
}
private fun generation4d(dim: List<List<Slice>>): List<List<Slice>> {
return dim.mapIndexed { w, wdim ->
wdim.mapIndexed { z, slice ->
Slice(slice.cubes.mapIndexed { y, line ->
line.mapIndexed { x, _ ->
shouldBeActive4d(dim, x, y, z, w)
}
})
}
}
}
private fun generation(dim: List<Slice>) = dim.mapIndexed { z, slice ->
Slice(slice.cubes.mapIndexed { y, line ->
line.mapIndexed { x, _ ->
shouldBeActive(dim, x, y, z)
}
})
}
private fun shouldBeActive4d(dim: List<List<Slice>>, x: Int, y: Int, z: Int, w: Int) =
if (dim[w][z].cubes[y][x]) activeNeighbors4d(dim, x, y, z, w) in 2..3
else activeNeighbors4d(dim, x, y, z, w) == 3
private fun shouldBeActive(dim: List<Slice>, x: Int, y: Int, z: Int) =
if (dim[z].cubes[y][x]) activeNeighbors(dim, x, y, z) in 2..3
else activeNeighbors(dim, x, y, z) == 3
private fun activeNeighbors4d(dim: List<List<Slice>>, x: Int, y: Int, z: Int, w: Int): Int {
return (max(0, w - 1)..min(dim.lastIndex - 1, w + 1)).sumOf { wn ->
(max(0, z - 1)..min(dim[w].lastIndex - 1, z + 1)).sumOf { zn ->
(max(0, y - 1)..min(dim[w][z].cubes.lastIndex - 1, y + 1)).sumOf { yn ->
(max(0, x - 1)..min(dim[w][z].cubes[y].lastIndex - 1, x + 1)).count { xn ->
if (xn == x && yn == y && zn == z && wn == w) false
else dim[wn][zn].cubes[yn][xn]
}
}
}
}
}
private fun activeNeighbors(dim: List<Slice>, x: Int, y: Int, z: Int): Int {
return (max(0, z - 1)..min(dim.lastIndex - 1, z + 1)).sumOf { zn ->
(max(0, y - 1)..min(dim[z].cubes.lastIndex - 1, y + 1)).sumOf { yn ->
(max(0, x - 1)..min(dim[z].cubes[y].lastIndex - 1, x + 1)).count { xn ->
if (xn == x && yn == y && zn == z) false
else dim[zn].cubes[yn][xn]
}
}
}
}
} | 1 | Kotlin | 1 | 1 | ffdffedc8659aa3deea3216d6a9a1fd4e02ec128 | 4,078 | adventofcode-kotlin | MIT License |
src/Day05.kt | ech0matrix | 572,692,409 | false | {"Kotlin": 116274} |
fun main() {
fun parseInput(input: List<String>): Pair<Map<Int, ArrayDeque<Char>>, List<Instruction>> {
val inputSplitIndex = input.indexOf("")
// Allocate stacks
val stacksInput = input.subList(0, inputSplitIndex)
val stackNumToIndex: Map<Int, Int> = stacksInput[stacksInput.size - 1]
.split(' ')
.filter { it.isNotEmpty() }
.associate {
Pair(it.toInt(), stacksInput[stacksInput.size - 1].indexOf(it[0]))
}
val stacks: Map<Int, ArrayDeque<Char>> = stackNumToIndex.keys.associateWith { ArrayDeque() }
// Initialize stacks
stacksInput.dropLast(1).reversed().forEach{ line ->
stackNumToIndex.forEach{ (stackNum, index) ->
val crate = line[index]
if (crate != ' ') {
stacks[stackNum]!!.addLast(crate)
}
}
}
// Parse instructions
val instructionInput = input.subList(inputSplitIndex+1, input.size)
val instructions = instructionInput.map {
val split = it.split(' ')
// Example: move 1 from 2 to 1
check(split[0] == "move")
val amount = split[1].toInt()
check(split[2] == "from")
val source = split[3].toInt()
check(split[4] == "to")
val destination = split[5].toInt()
Instruction(amount, source, destination)
}
return Pair(stacks, instructions)
}
fun buildOutput(stacks: Map<Int, ArrayDeque<Char>>): String {
return stacks.entries.sortedBy { it.key }.map { it.value.last() }.joinToString("")
}
fun part1(input: List<String>): String {
val (stacks, instructions) = parseInput(input)
// Run instructions
instructions.forEach {
val sourceStack = stacks[it.source]!!
val destinationStack = stacks[it.destination]!!
repeat(it.amount) {
val crate = sourceStack.removeLast()
destinationStack.addLast(crate)
}
}
// Build output
return buildOutput(stacks)
}
fun part2(input: List<String>): String {
val (stacks, instructions) = parseInput(input)
// Run instructions
instructions.forEach {
val sourceStack = stacks[it.source]!!
val destinationStack = stacks[it.destination]!!
val tempStack = ArrayDeque<Char>()
repeat(it.amount) {
val crate = sourceStack.removeLast()
tempStack.addLast(crate)
}
repeat(it.amount) {
val crate = tempStack.removeLast()
destinationStack.addLast(crate)
}
}
// Build output
return buildOutput(stacks)
}
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
data class Instruction(
val amount: Int,
val source: Int,
val destination: Int
) | 0 | Kotlin | 0 | 0 | 50885e12813002be09fb6186ecdaa3cc83b6a5ea | 3,163 | aoc2022 | Apache License 2.0 |
src/year2022/day16/Day16.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2022.day16
import check
import readInput
import java.util.concurrent.ConcurrentHashMap
import kotlin.math.max
import kotlin.system.measureTimeMillis
import kotlin.time.Duration.Companion.milliseconds
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("2022", "Day16_test")
check(part1(testInput), 1651)
check(part2(testInput), 1707)
val input = readInput("2022", "Day16")
measureTimeMillis { print(part1(input)) }.also { println(" (Part 1 took ${it.milliseconds})") }
measureTimeMillis { print(part2(input)) }.also { println(" (Part 2 took ${it.milliseconds})") }
}
private fun part1(input: List<String>): Int {
val valvesById = parseValvesById(input)
val shortestPathSteps = getStepsByPath(valvesById)
return findMaxPressureRelease(
pos = "AA",
remainingValves = valvesById.values.filter { it.flowRate > 0 }.mapTo(hashSetOf()) { it.id },
valvesById = valvesById,
shortestPathSteps = shortestPathSteps,
)
}
private fun part2(input: List<String>): Int {
val valvesById = parseValvesById(input)
val shortestPathSteps = getStepsByPath(valvesById)
return findMaxPressureReleaseWithElephant(
posA = "AA",
posB = "AA",
remainingValves = valvesById.values.filter { it.flowRate > 0 }.mapTo(hashSetOf()) { it.id },
valvesById = valvesById,
shortestPathSteps = shortestPathSteps,
)
}
private fun getStepsByPath(valvesById: Map<String, Valve>): Map<String, Int> {
val shortestPathSteps = hashMapOf<String, Int>()
for (a in valvesById.keys) {
for (b in valvesById.keys) {
if (a == b) continue
val key = "$a>$b"
shortestPathSteps[key] = findShortestPathSteps(valvesById, a, b)
}
}
return shortestPathSteps
}
private data class CacheKey1(
val pos: String,
val timeLeft: Int,
val remainingValves: Set<String>,
)
private fun findMaxPressureRelease(
pos: String,
timeLeft: Int = 30,
remainingValves: Set<String>,
valvesById: Map<String, Valve>,
shortestPathSteps: Map<String, Int>,
cache: HashMap<CacheKey1, Int> = hashMapOf(),
): Int {
if (remainingValves.isEmpty()) {
return 0
}
val key = CacheKey1(
pos = pos,
timeLeft = timeLeft,
remainingValves = remainingValves,
)
return cache.getOrPut(key) {
remainingValves.maxOf {
val steps = shortestPathSteps["$pos>$it"]!!
val duration = steps + 1
val pressureRelease = (timeLeft - duration) * valvesById[it]!!.flowRate
if (timeLeft - duration <= 0) {
0
} else pressureRelease + findMaxPressureRelease(
pos = it,
timeLeft = timeLeft - duration,
remainingValves = remainingValves - it,
valvesById = valvesById,
shortestPathSteps = shortestPathSteps,
cache = cache,
)
}
}
}
private data class CacheKey2(
val posA: String,
val posB: String,
val timeLeftA: Int,
val timeLeftB: Int,
val remainingValves: Set<String>,
)
private fun findMaxPressureReleaseWithElephant(
posA: String,
posB: String,
timeLeftA: Int = 26,
timeLeftB: Int = 26,
remainingValves: Set<String>,
valvesById: Map<String, Valve>,
shortestPathSteps: Map<String, Int>,
cache: MutableMap<CacheKey2, Int> = ConcurrentHashMap(),
): Int {
if (remainingValves.isEmpty()) {
return 0
}
if (timeLeftA == 0) {
return findMaxPressureRelease(
pos = posB,
timeLeft = timeLeftB,
remainingValves = remainingValves,
valvesById = valvesById,
shortestPathSteps = shortestPathSteps,
)
}
if (timeLeftB == 0) {
return findMaxPressureRelease(
pos = posA,
timeLeft = timeLeftA,
remainingValves = remainingValves,
valvesById = valvesById,
shortestPathSteps = shortestPathSteps,
)
}
if (remainingValves.size == 1) {
val valve = valvesById[remainingValves.first()]!!
val stepsA = findShortestPathSteps(valvesById, posA, valve.id)
val stepsB = findShortestPathSteps(valvesById, posB, valve.id)
val durationA = stepsA + 1
val durationB = stepsB + 1
val finalReleaseA = (timeLeftA - durationA) * valve.flowRate
val finalReleaseB = (timeLeftB - durationB) * valve.flowRate
return max(max(finalReleaseA, finalReleaseB), 0)
}
val key = CacheKey2(
posA = posA,
posB = posB,
timeLeftA = timeLeftA,
timeLeftB = timeLeftB,
remainingValves = remainingValves,
)
return cache.getOrPut(key) {
val isTopOfCallStack = timeLeftA == 26 && timeLeftB == 26
val combinations = getCombinations(remainingValves).let {
if (isTopOfCallStack) it.unique() else it
}
if (isTopOfCallStack)
combinations.parallelStream().map { pair ->
findPressureReleaseForPair(
pair = pair,
shortestPathSteps = shortestPathSteps,
posA = posA,
posB = posB,
timeLeftA = timeLeftA,
valvesById = valvesById,
timeLeftB = timeLeftB,
remainingValves = remainingValves,
cache = cache,
)
}.toList().max()
else combinations.maxOf { pair ->
findPressureReleaseForPair(
pair = pair,
shortestPathSteps = shortestPathSteps,
posA = posA,
posB = posB,
timeLeftA = timeLeftA,
valvesById = valvesById,
timeLeftB = timeLeftB,
remainingValves = remainingValves,
cache = cache,
)
}
}
}
private fun findPressureReleaseForPair(
pair: List<String>,
shortestPathSteps: Map<String, Int>,
posA: String,
posB: String,
timeLeftA: Int,
valvesById: Map<String, Valve>,
timeLeftB: Int,
remainingValves: Set<String>,
cache: MutableMap<CacheKey2, Int>,
): Int {
val (a, b) = pair
val stepsA = shortestPathSteps["$posA>$a"]!!
val stepsB = shortestPathSteps["$posB>$b"]!!
val durationA = stepsA + 1
val durationB = stepsB + 1
val pressureReleaseA = (timeLeftA - durationA) * valvesById[a]!!.flowRate
val pressureReleaseB = (timeLeftB - durationB) * valvesById[b]!!.flowRate
return if (timeLeftA - durationA <= 0 && timeLeftB - durationB <= 0) {
0
} else if (timeLeftA - durationA <= 0) {
pressureReleaseB + findMaxPressureReleaseWithElephant(
posA = posA,
posB = b,
timeLeftA = 0,
timeLeftB = timeLeftB - durationB,
remainingValves = remainingValves - b,
valvesById = valvesById,
shortestPathSteps = shortestPathSteps,
cache = cache,
)
} else if (timeLeftB - durationB <= 0) {
pressureReleaseA + findMaxPressureReleaseWithElephant(
posA = a,
posB = posB,
timeLeftA = timeLeftA - durationA,
timeLeftB = 0,
remainingValves = remainingValves - a,
valvesById = valvesById,
shortestPathSteps = shortestPathSteps,
cache = cache,
)
} else {
pressureReleaseA + pressureReleaseB + findMaxPressureReleaseWithElephant(
posA = a,
posB = b,
timeLeftA = timeLeftA - durationA,
timeLeftB = timeLeftB - durationB,
remainingValves = remainingValves - a - b,
valvesById = valvesById,
shortestPathSteps = shortestPathSteps,
cache = cache,
)
}
}
private fun findShortestPathSteps(graph: Map<String, Valve>, start: String, target: String): Int {
val stack = ArrayDeque<List<String>>()
val visited = mutableSetOf(start)
stack.addLast(listOf(start))
while (stack.isNotEmpty()) {
val path = stack.removeFirst()
val current = path.last()
val ways = graph[current]?.connectedTo ?: emptyList()
for (next in ways) {
if (next !in visited) {
visited += next
val newPath = path + next
if (target == next) return newPath.size - 1
stack.addLast(newPath)
}
}
}
error("no path found")
}
private fun parseValvesById(input: List<String>): Map<String, Valve> {
val pattern =
"Valve (?<id>[A-Z]{2}) has flow rate=(?<flowRate>\\d+); tunnels? leads? to valves? (?<connections>[A-Z, ]+)".toRegex()
return input.map { line ->
val groups = pattern.find(line)?.groups ?: error("Error: $line")
val id = groups["id"]?.value ?: error("!")
val flowRate = groups["flowRate"]?.value?.toInt() ?: error("!")
val connections = groups["connections"]?.value?.split(", ") ?: error("!")
Valve(id, flowRate, connections)
}.associateBy { it.id }
}
private data class Valve(
val id: String,
val flowRate: Int,
val connectedTo: List<String>,
)
private fun getCombinations(valves: Set<String>, current: List<String> = emptyList()): Set<List<String>> {
if (current.size == 2) return setOf(current)
val result = mutableSetOf<List<String>>()
for (next in valves) {
result += getCombinations(valves - next, current + next)
}
return result
}
private fun Set<List<String>>.unique() = map { it.toSet() }.toSet().map { it.toList() }
| 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 9,836 | AdventOfCode | Apache License 2.0 |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[剑指 Offer 42]连续子数组的最大和.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | //输入一个整型数组,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。
//
// 要求时间复杂度为O(n)。
//
//
//
// 示例1:
//
// 输入: nums = [-2,1,-3,4,-1,2,1,-5,4]
//输出: 6
//解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
//
//
//
// 提示:
//
//
// 1 <= arr.length <= 10^5
// -100 <= arr[i] <= 100
//
//
// 注意:本题与主站 53 题相同:https://leetcode-cn.com/problems/maximum-subarray/
//
//
// Related Topics 分治算法 动态规划
// 👍 192 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun maxSubArray(nums: IntArray): Int {
//动态规划 创建 dp 数组 dp[i] 保存对应遍历到位置的最大值
//动态规划方程
//dp[i] = max(dp[i-1]+dp[i],dp[i])
var dp = IntArray(nums.size)
dp[0] = nums[0]
var maxres = dp[0]
for (i in 1 until nums.size){
dp[i] = Math.max(dp[i-1]+nums[i],nums[i])
maxres = Math.max(maxres,dp[i])
}
return maxres
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 1,196 | MyLeetCode | Apache License 2.0 |
src/main/kotlin/day12/Day12.kt | afTrolle | 572,960,379 | false | {"Kotlin": 33530} | package day12
import Day
import ext.findInMatrix
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.update
import kotlin.math.absoluteValue
fun main() {
Day12("Day12").solve()
}
data class Vertex(
val y: Int,
val x: Int,
val encodedAltitude: Char,
) {
val altitude: Int = Day12.convertChar[encodedAltitude]!!
var left: Vertex? = null
var right: Vertex? = null
var up: Vertex? = null
var down: Vertex? = null
val neighbors get() = listOfNotNull(left, right, up, down)
}
fun Vertex.pointIsValidHeight(current: Vertex): Vertex? = takeIf {
altitude <= current.altitude + 1
}
class Day12(input: String) : Day<List<List<Vertex>>>(input) {
private val List<List<Vertex>>.start
get() = findInMatrix { _, _, vertex ->
if (vertex.encodedAltitude == startChar) vertex else null
}!!
private val List<List<Vertex>>.end
get() = findInMatrix { _, _, vertex ->
if (vertex.encodedAltitude == endChar) vertex else null
}!!
private fun bfs(start: Vertex, end: Vertex): Int {
val queue = ArrayDeque<Pair<Long, Vertex>>()
val visited = mutableSetOf<Vertex>()
visited.add(start)
queue.add(1L to start)
var counter = 0
while (queue.isNotEmpty()) {
val (depth, item) = queue.removeFirst()
val adj = item.neighbors
if (end == item) {
return depth.toInt()
}
adj.forEach {
if (!visited.contains(it)) {
if (end == it) {
return depth.toInt()
}
visited.add(it)
queue.add(depth + 1 to it)
counter++
}
}
}
return Int.MAX_VALUE
}
override fun parseInput(): List<List<Vertex>> {
val graph = inputByLines.map { it.toList() }.mapIndexed { rowIndex, row ->
row.mapIndexed { colIndex, c ->
Vertex(rowIndex, colIndex, c)
}
}
graph.forEach { rows ->
rows.forEach { vertex ->
vertex.apply {
down = graph.getOrNull(y + 1)?.getOrNull(x)?.pointIsValidHeight(this)
up = graph.getOrNull(y - 1)?.getOrNull(x)?.pointIsValidHeight(this)
left = graph.getOrNull(y)?.getOrNull(x - 1)?.pointIsValidHeight(this)
right = graph.getOrNull(y)?.getOrNull(x + 1)?.pointIsValidHeight(this)
}
}
}
return graph
}
override fun part1(input: List<List<Vertex>>): Any {
val start = input.start
val end = input.end
return bfs(start, end)
}
override fun part2(input: List<List<Vertex>>): Any {
val end = input.end
return input.asSequence().flatten().filter { it.encodedAltitude == 'a' }.map { bfs(it, end) }.min()
}
companion object {
const val startChar = 'S'
const val endChar = 'E'
val convertChar: Map<Char, Int> = buildMap {
('a'..'z').forEach {
put(it, it - 'a')
}
// S is same as a
put(startChar, get('a')!!)
// E is same as z
put(endChar, get('z')!!)
}
}
}
| 0 | Kotlin | 0 | 0 | 4ddfb8f7427b8037dca78cbf7c6b57e2a9e50545 | 3,400 | aoc-2022 | Apache License 2.0 |
src/adventofcode/blueschu/y2017/day08/solution.kt | blueschu | 112,979,855 | false | null | package adventofcode.blueschu.y2017.day08
import java.io.File
import kotlin.math.max
import kotlin.test.assertEquals
fun input() = File("resources/y2017/day08.txt").useLines { it.toList() }
fun main(args: Array<String>) {
val exampleInstructions = listOf(
"b inc 5 if a > 1",
"a inc 1 if b < 5",
"c dec -10 if a >= 1",
"c inc -20 if c == 10"
)
assertEquals(1, part1(exampleInstructions))
println("Part 1: ${part1(input())}")
assertEquals(10, part2(exampleInstructions))
println("Part 2: ${part2(input())}")
}
data class Instruction(val action: Action, val condition: Condition)
class Condition(
private val registerKey: String,
private val operator: ComparisonOperator,
private val literal: Int
) {
constructor(registerKey: String, operator: String, literal: String) :
this(
registerKey,
ComparisonOperator.parseToken(operator),
literal.toInt()
)
enum class ComparisonOperator {
EQUAL, LESS_THAN, GREATER_THAN, GREATER_OR_EQUAL, LESS_OR_EQUAL, NOT_EQUAL;
companion object {
fun parseToken(token: String): ComparisonOperator = when (token) {
"==" -> EQUAL
">" -> GREATER_THAN
"<" -> LESS_THAN
">=" -> GREATER_OR_EQUAL
"<=" -> LESS_OR_EQUAL
"!=" -> NOT_EQUAL
else -> throw IllegalArgumentException("token cannot be mapped to a comparison operator: $token")
}
}
}
fun satisfiedBy(registerTable: RegisterRepository): Boolean = when (operator) {
ComparisonOperator.EQUAL -> registerTable[registerKey] == literal
ComparisonOperator.LESS_THAN -> registerTable[registerKey] < literal
ComparisonOperator.GREATER_THAN -> registerTable[registerKey] > literal
ComparisonOperator.GREATER_OR_EQUAL -> registerTable[registerKey] >= literal
ComparisonOperator.LESS_OR_EQUAL -> registerTable[registerKey] <= literal
ComparisonOperator.NOT_EQUAL -> registerTable[registerKey] != literal
}
}
// ensuring expandability as part two may introduce new actions
// ...it didn't
abstract class Action(private val registerKey: String) {
abstract fun apply(previousValue: Int): Int
fun applyTo(registerTable: RegisterRepository) {
registerTable[registerKey] = apply(registerTable[registerKey])
}
}
class ActionIncrement(registerKey: String, private val magnitude: Int) :
Action(registerKey) {
override fun apply(previousValue: Int): Int = previousValue + magnitude
}
class RegisterRepository {
private val registerTable = mutableMapOf<String, Int>()
operator fun get(registerKey: String): Int {
if (registerKey !in registerTable) {
registerTable += registerKey to 0
}
return registerTable[registerKey] ?:
throw IllegalStateException("Register '$registerKey' missing")
}
operator fun set(registerKey: String, value: Int) {
if (registerKey !in registerTable) {
registerTable += registerKey to value
} else {
registerTable[registerKey] = value
}
}
fun maxRegisterValue() = registerTable.map { it.value }.max() ?: 0
}
class Interpreter(val registerTable: RegisterRepository) {
constructor() : this(RegisterRepository())
fun execute(instr: Instruction) {
if (instr.condition.satisfiedBy(registerTable)) {
instr.action.applyTo(registerTable)
}
}
fun executeAll(instr: Collection<Instruction>) = instr.forEach { execute(it) }
}
fun parseAction(
registerKey: String,
operation: String,
literal: String
): Action {
val literalMagnitude = when (operation) {
"inc" -> literal.toInt()
"dec" -> -literal.toInt()
else -> throw IllegalArgumentException("action operator could not be parsed: $operation")
}
return ActionIncrement(registerKey, literalMagnitude)
}
fun parseInstruction(instr: String): Instruction {
val pattern = "^(?<ActReg>\\w+) (?<ActOp>\\w{3}) (?<ActLit>[-\\d]+) if (?<CondReg>\\w+) (?<CondOp>[<=>!]{1,2}) (?<CondLit>[-\\d]+)\$".toRegex()
val parsedFields = pattern.matchEntire(instr)?.groups
?: throw IllegalArgumentException("Malformed instruction: $instr")
val action = parseAction(
parsedFields["ActReg"]!!.value,
parsedFields["ActOp"]!!.value,
parsedFields["ActLit"]!!.value
)
val condition = Condition(
parsedFields["CondReg"]!!.value,
parsedFields["CondOp"]!!.value,
parsedFields["CondLit"]!!.value
)
return Instruction(action, condition)
}
fun part1(input: List<String>): Int {
val interpreter = Interpreter()
interpreter.executeAll(input.map { parseInstruction(it) })
return interpreter.registerTable.maxRegisterValue()
}
fun part2(input: List<String>): Int {
val interpreter = Interpreter()
val instructions = input.map { parseInstruction(it) }
var maxRegisterValue = Int.MIN_VALUE
instructions.forEach {
interpreter.execute(it)
maxRegisterValue = max(
maxRegisterValue,
interpreter.registerTable.maxRegisterValue()
)
}
return maxRegisterValue
}
| 0 | Kotlin | 0 | 0 | 9f2031b91cce4fe290d86d557ebef5a6efe109ed | 5,311 | Advent-Of-Code | MIT License |
src/Day06.kt | cypressious | 572,916,585 | false | {"Kotlin": 40281} | fun main() {
fun part1(input: List<String>): Int {
val fish = input[0].split(',').mapTo(mutableListOf(), String::toInt)
repeat(80) {
for (i in fish.indices) {
fish[i]--
if (fish[i] < 0) {
fish.add(8)
fish[i] = 6
}
}
}
return fish.size
}
fun part2(input: List<String>): Long {
val fish = input[0].split(',').map(String::toInt).groupingBy { it }.eachCount()
var counts = LongArray(9)
for ((key, value) in fish) {
counts[key] = value.toLong()
}
repeat(256) {
val newCounts = LongArray(9)
counts.drop(1).forEachIndexed { index, count -> newCounts[index] = count }
newCounts[6] += counts[0]
newCounts[8] = counts[0]
counts = newCounts
}
return counts.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
check(part1(testInput) == 5934)
check(part2(testInput) == 26984457539L)
val input = readInput("Day06")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 169fb9307a34b56c39578e3ee2cca038802bc046 | 1,241 | AdventOfCode2021 | Apache License 2.0 |
src/Day05.kt | Migge | 572,695,764 | false | {"Kotlin": 9496} | private fun part1(input: List<String>): String {
val (stacksStr, instrs) = input.splitOnEmpty()
val stacks = initStacks(stacksStr)
for ((nr, from, to) in instrs.ints()) {
repeat (nr) {
stacks[to-1].addLast(stacks[from-1].removeLast())
}
}
return stacks.toList().map { it.last() }.join()
}
private fun part2(input: List<String>): String {
val (stacksStr, instrs) = input.splitOnEmpty()
val stacks = initStacks(stacksStr)
for ((nr, from, to) in instrs.ints()) {
val stack = ArrayDeque<Char>()
repeat (nr) {
stack.addFirst(stacks[from-1].removeLast())
}
stacks[to-1].addAll(stack)
}
return stacks.toList().map { it.last() }.join()
}
private fun initStacks(stacksStr: List<String>): Array<ArrayDeque<Char>> {
val size = stacksStr.last().takeLast(2).trim().toInt()
val stacks = Array(size) { ArrayDeque<Char>() }
stacksStr.dropLast(1).forEach {
for (i in 0 until size) {
if (it.length > i*4+1 && it[i*4+1] != ' ') {
stacks[i].addFirst(it[i*4+1])
}
}
}
return stacks
}
fun main() {
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | c7ca68b2ec6b836e73464d7f5d115af3e6592a21 | 1,377 | adventofcode2022 | Apache License 2.0 |
src/Day05.kt | thorny-thorny | 573,065,588 | false | {"Kotlin": 57129} | class Cargo(stacksAmount: Int) {
private val stacks = MutableList(stacksAmount) { listOf<Char>() }
fun pushItem(item: Char, index: Int) {
stacks[index] = stacks[index] + item
}
fun runInstruction(instruction: CargoInstruction, oneItemAtTime: Boolean) {
when (instruction) {
is CargoInstruction.Move -> {
val stack = stacks[instruction.from - 1]
var chunk = stack.slice((stack.lastIndex - instruction.amount + 1)..stack.lastIndex)
if (oneItemAtTime) {
chunk = chunk.reversed()
}
stacks[instruction.from - 1] = stack.dropLast(instruction.amount)
stacks[instruction.to - 1] = stacks[instruction.to - 1] + chunk
}
}
}
fun topItems() = stacks
.map { it.last() }
.joinToString("")
}
sealed class CargoInstruction {
class Move(val amount: Int, val from: Int, val to: Int): CargoInstruction()
}
fun main() {
// Returns cargo and index of next line
fun parseCargo(lines: List<String>): Pair<Cargo, Int> {
val separatorIndex = lines.indexOf("")
val cargo = Cargo((lines[separatorIndex - 1].length + 2) / 4)
((separatorIndex - 2) downTo 0).forEach { index ->
lines[index]
.windowed(3, 4)
.map { it[1] }
.forEachIndexed { itemIndex, item ->
if (!item.isWhitespace()) {
cargo.pushItem(item, itemIndex)
}
}
}
return cargo to (separatorIndex + 1)
}
fun parseInstruction(line: String): CargoInstruction {
val parts = line.split(' ', limit = 2)
return when (parts.first()) {
"move" -> {
val match = Regex("""(\d+) from (\d+) to (\d+)""").matchEntire(parts.last())
val (amount, from, to) = match?.destructured ?: throw Exception("Bad instruction arguments")
CargoInstruction.Move(amount.toInt(), from.toInt(), to.toInt())
}
else -> throw Exception("Unknown instruction")
}
}
fun part1(input: List<String>): String {
val (cargo, instructionsIndex) = parseCargo(input)
(instructionsIndex..input.lastIndex).forEach { index ->
cargo.runInstruction(parseInstruction(input[index]), true)
}
return cargo.topItems()
}
fun part2(input: List<String>): String {
val (cargo, instructionsIndex) = parseCargo(input)
(instructionsIndex..input.lastIndex).forEach { index ->
cargo.runInstruction(parseInstruction(input[index]), false)
}
return cargo.topItems()
}
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 843869d19d5457dc972c98a9a4d48b690fa094a6 | 2,969 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaximumWidthOfBinaryTree.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.AbstractMap.SimpleEntry
import java.util.LinkedList
import java.util.Queue
import kotlin.math.max
/**
* 662. Maximum Width of Binary Tree
* @see <a href="https://leetcode.com/problems/maximum-width-of-binary-tree/">Source</a>
*/
fun interface MaximumWidthOfBinaryTree {
fun widthOfBinaryTree(root: TreeNode?): Int
}
class MaximumWidthOfBinaryTreeDFS : MaximumWidthOfBinaryTree {
override fun widthOfBinaryTree(root: TreeNode?): Int {
val lefts: MutableList<Int> = ArrayList() // left most nodes at each level;
val res = IntArray(1) // max width
dfs(root, 1, 0, lefts, res)
return res[0]
}
private fun dfs(node: TreeNode?, id: Int, depth: Int, lefts: MutableList<Int>, res: IntArray) {
if (node == null) return
if (depth >= lefts.size) lefts.add(id) // add left most node
res[0] = Integer.max(res[0], id + 1 - lefts[depth])
dfs(node.left, id * 2, depth + 1, lefts, res)
dfs(node.right, id * 2 + 1, depth + 1, lefts, res)
}
}
class MaximumWidthOfBinaryTreeBFS : MaximumWidthOfBinaryTree {
override fun widthOfBinaryTree(root: TreeNode?): Int {
if (root == null) return 0
var max = 0
val q: Queue<SimpleEntry<TreeNode, Int>> = LinkedList()
q.offer(SimpleEntry(root, 1))
while (q.isNotEmpty()) {
val l: Int = q.peek().value
var r = l // right started same as left
var i = 0
val n: Int = q.size
while (i < n) {
val node: TreeNode = q.peek().key
r = q.poll().value
if (node.left != null) q.offer(SimpleEntry(node.left, r * 2))
if (node.right != null) q.offer(SimpleEntry(node.right, r * 2 + 1))
i++
}
max = max(max, r + 1 - l)
}
return max
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,527 | kotlab | Apache License 2.0 |
src/main/kotlin/Day04.kt | JPQuirmbach | 572,636,904 | false | {"Kotlin": 11093} | fun main() {
fun getRange(s: String): Set<Int> {
val split = s.split("-")
return IntRange(split.first().toInt(), split.last().toInt()).toSet()
}
fun part1(input: String): Int {
return input.lines()
.map {
val split = it.split(",")
split.first() to split.last()
}.sumOf {
val first = getRange(it.first)
val second = getRange(it.second)
if (first.containsAll(second) || second.containsAll(first))
1L
else
0L
}.toInt()
}
fun part2(input: String): Int {
return input.lines()
.map {
val split = it.split(",")
split.first() to split.last()
}.sumOf {
val first = getRange(it.first)
val second = getRange(it.second)
if ((first intersect second).isNotEmpty())
1L
else
0L
}.toInt()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 829e11bd08ff7d613280108126fa6b0b61dcb819 | 1,351 | advent-of-code-Kotlin-2022 | Apache License 2.0 |
kotlin/MaxFlowDinic.kt | indy256 | 1,493,359 | false | {"Java": 545116, "C++": 266009, "Python": 59511, "Kotlin": 28391, "Rust": 4682, "CMake": 571} | // https://en.wikipedia.org/wiki/Dinic%27s_algorithm in O(V^2 * E)
class MaxFlowDinic(nodes: Int) {
data class Edge(val t: Int, val rev: Int, val cap: Int, var f: Int = 0)
val graph = (1..nodes).map { arrayListOf<Edge>() }.toTypedArray()
val dist = IntArray(nodes)
fun addBidiEdge(s: Int, t: Int, cap: Int) {
graph[s].add(Edge(t, graph[t].size, cap))
graph[t].add(Edge(s, graph[s].size - 1, 0))
}
fun dinicBfs(src: Int, dest: Int, dist: IntArray): Boolean {
dist.fill(-1)
dist[src] = 0
val q = IntArray(graph.size)
var sizeQ = 0
q[sizeQ++] = src
var i = 0
while (i < sizeQ) {
val u = q[i++]
for (e in graph[u]) {
if (dist[e.t] < 0 && e.f < e.cap) {
dist[e.t] = dist[u] + 1
q[sizeQ++] = e.t
}
}
}
return dist[dest] >= 0
}
fun dinicDfs(ptr: IntArray, dest: Int, u: Int, f: Int): Int {
if (u == dest)
return f
while (ptr[u] < graph[u].size) {
val e = graph[u][ptr[u]]
if (dist[e.t] == dist[u] + 1 && e.f < e.cap) {
val df = dinicDfs(ptr, dest, e.t, Math.min(f, e.cap - e.f))
if (df > 0) {
e.f += df
graph[e.t][e.rev].f -= df
return df
}
}
++ptr[u]
}
return 0
}
fun maxFlow(src: Int, dest: Int): Int {
var flow = 0
while (dinicBfs(src, dest, dist)) {
val ptr = IntArray(graph.size)
while (true) {
val df = dinicDfs(ptr, dest, src, Int.MAX_VALUE)
if (df == 0)
break
flow += df
}
}
return flow
}
// invoke after maxFlow()
fun minCut() = dist.map { it != -1 }.toBooleanArray()
fun clearFlow() {
for (edges in graph)
for (edge in edges)
edge.f = 0
}
}
// Usage example
fun main(args: Array<String>) {
val flow = MaxFlowDinic(3)
flow.addBidiEdge(0, 1, 3)
flow.addBidiEdge(0, 2, 2)
flow.addBidiEdge(1, 2, 2)
println(4 == flow.maxFlow(0, 2))
}
| 97 | Java | 561 | 1,806 | 405552617ba1cd4a74010da38470d44f1c2e4ae3 | 2,290 | codelibrary | The Unlicense |
src/Day04.kt | naturboy | 572,742,689 | false | {"Kotlin": 6452} | fun main() {
data class Entry(val rangeOne: IntProgression, val rangeTwo: IntProgression)
fun String.toRange(): IntProgression {
val (start, stop) = this.split("-")
return start.toInt()..stop.toInt()
}
fun parseInput(input: List<String>) = input.map {
val (rangeInputOne, rangeInputTwo) = it.split(",")
val rangeOne = rangeInputOne.toRange()
val rangeTwo = rangeInputTwo.toRange()
if (rangeOne.first < rangeTwo.first || (rangeOne.first == rangeTwo.first && rangeOne.last > rangeTwo.last)) {
Entry(rangeOne, rangeTwo)
} else {
Entry(rangeTwo, rangeOne)
}
}
fun part1(input: List<String>): Int {
val entries = parseInput(input)
return entries.filter { (rangeOne, rangeTwo) -> rangeTwo.last <= rangeOne.last}.size
}
fun part2(input: List<String>): Int {
val entries = parseInput(input)
return entries.filter { (rangeOne, rangeTwo) -> rangeTwo.any { rangeOne.contains(it) } }.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInputLineByLine("Day04_test")
check(part1(testInput) == 2)
val input = readInputLineByLine("Day04")
println(part1(input))
check(part2(testInput) == 4)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 852871f58218d80702c3b49dd0fd453096e56a43 | 1,334 | advent-of-code-kotlin-2022 | Apache License 2.0 |
Kotlin/problems/0011_evaluate_division.kt | oxone-999 | 243,366,951 | true | {"C++": 961697, "Kotlin": 99948, "Java": 17927, "Python": 9476, "Shell": 999, "Makefile": 187} | //Problem Statement
// Equations are given in the format A / B = k, where A and B are variables
// represented as strings, and k is a real number (floating point number).
// Given some queries, return the answers. If the answer does not exist, return -1.0.
//
// Example:
// Given a / b = 2.0, b / c = 3.0.
// queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? .
// return [6.0, 0.5, -1.0, 1.0, -1.0 ].
import java.util.ArrayDeque;
class Solution {
fun calcEquation(equations: Array<Array<String>>, values: DoubleArray, queries: Array<Array<String>>): DoubleArray {
val graph = HashMap<String,ArrayList<Pair<String,Double>>>();
val result: MutableList<Double> = mutableListOf<Double>();
var numerator:String = "";
var denominator:String = "";
var value:Double = 1.0;
for(i in equations.indices){
numerator = equations[i][0];
denominator = equations[i][1];
value = values[i];
if(!graph.contains(numerator)){
graph.put(numerator,arrayListOf<Pair<String,Double>>());
}
graph[numerator]!!.add(Pair(denominator,value));
if(!graph.contains(denominator)){
graph.put(denominator,arrayListOf<Pair<String,Double>>());
}
graph[denominator]!!.add(Pair(numerator,1/value));
}
for(querie in queries){
numerator = querie[0];
denominator = querie[1];
if(!graph.contains(numerator) || !graph.contains(denominator)){
result.add(-1.0);
}
else if(numerator == denominator){
result.add(1.0);
}else{
val bfs = ArrayDeque<Pair<String,Double>> ();
val visited = HashSet<String>();
var found:Boolean = false;
bfs.add(Pair(numerator,1.0));
while(!bfs.isEmpty() && !found){
var vertex:Pair<String,Double> = bfs.pollFirst();
if(!visited.contains(vertex.first)){
visited.add(vertex.first);
for(connections in graph[vertex.first].orEmpty()){
if(connections.first == denominator){
result.add(connections.second*vertex.second);
found = true;
break;
}else{
bfs.add(Pair(connections.first,vertex.second*connections.second));
}
}
}
}
if(!found){
result.add(-1.0);
}
}
}
return result.toDoubleArray();
}
}
fun main(args:Array<String>){
val equations:Array<Array<String>> = arrayOf(arrayOf("a","b"),arrayOf("b","c"),arrayOf("e","d"));
val queries:Array<Array<String>> = arrayOf(arrayOf("a", "c"), arrayOf("b", "a"), arrayOf("a", "e"), arrayOf("a", "a"), arrayOf("x", "x"));
val values:DoubleArray = doubleArrayOf(2.0,3.0,5.0);
val sol:Solution = Solution();
println(sol.calcEquation(equations,values,queries).joinToString(prefix = "[", postfix = "]"));
}
| 0 | null | 0 | 0 | 52dc527111e7422923a0e25684d8f4837e81a09b | 3,296 | algorithms | MIT License |
src/Day21.kt | ech0matrix | 572,692,409 | false | {"Kotlin": 116274} | fun main() {
fun parseInput(input: List<String>): Map<String, String> {
return input.associate { line ->
val split = line.split(": ")
Pair(split[0], split[1])
}
}
fun getMonkeyValue(monkeyName: String, monkeys: Map<String, String>): Long {
val monkey = monkeys[monkeyName]!!
val split = monkey.split(" ")
if (split.size == 1) {
return split[0].toLong()
} else if (split.size != 3) {
throw IllegalArgumentException("Expected 3 parts to the equation: $split")
}
val part1 = getMonkeyValue(split[0], monkeys)
val part2 = getMonkeyValue(split[2], monkeys)
return when (split[1]) {
"+" -> part1 + part2
"-" -> part1 - part2
"*" -> part1 * part2
"/" -> part1 / part2
else -> throw IllegalArgumentException("Unknown operand: ${split[1]}")
}
}
fun part1(input: List<String>): Long {
val monkeys = parseInput(input)
return getMonkeyValue("root", monkeys)
}
// This doesn't actually solve for "humn", but instead provides a tool for guess and check
fun part2(input: List<String>, humanAdjustment: Long): Long {
val monkeys = parseInput(input).mapValues { (k, v) ->
if (k == "humn") {
(v.toLong() + humanAdjustment).toString()
} else {
v
}
}
val rootMonkey = monkeys["root"]!!
val split = rootMonkey.split(" ")
val part1 = getMonkeyValue(split[0], monkeys)
val part2 = getMonkeyValue(split[2], monkeys)
println("Term1: $part1")
println("Term1: $part2")
return if (part1 == part2) {
val humanValue = monkeys["humn"]!!.toLong()
println("Equal when human: $humanValue")
humanValue
} else {
-1
}
}
val testInput = readInput("Day21_test")
check(part1(testInput) == 152L)
check(part2(testInput, 296L) == 301L)
val input = readInput("Day21")
println("**Part1 answer: ${part1(input)}")
println("**Part2 answer: ${part2(input, 3221245821750L)}")
}
| 0 | Kotlin | 0 | 0 | 50885e12813002be09fb6186ecdaa3cc83b6a5ea | 2,213 | aoc2022 | Apache License 2.0 |
src/main/kotlin/advent/y2018/day4.kt | IgorPerikov | 134,053,571 | false | {"Kotlin": 29606} | package advent.y2018
import misc.readAdventInput
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
/**
* https://adventofcode.com/2018/day/3
*/
private typealias GuardId = Int
private typealias Minute = Int
private typealias Count = Int
fun main(args: Array<String>) {
val guardToIntervalsMap = buildGuardToIntervalsMap()
whoSleepTheMostTotal(guardToIntervalsMap).also { println(it) }
whoSleepTheMostAtAnyMinute(guardToIntervalsMap).also { println(it) }
}
private fun whoSleepTheMostTotal(guardToIntervalsMap: Map<GuardId, List<Interval>>): Int {
val guardWhoSleepTheMost = guardToIntervalsMap.maxBy { it.value.sumBy { it.end - it.start } }!!
val totalSleepDistribution = mutableMapOf<Minute, Int>()
for (interval in guardWhoSleepTheMost.value) {
for (min in interval.start until interval.end) {
totalSleepDistribution.merge(min, 1) { old, new -> old + new }
}
}
val guardId = guardWhoSleepTheMost.key
val mostPopularMinute = totalSleepDistribution.maxBy { entry -> entry.value }!!.key
return mostPopularMinute * guardId
}
private fun whoSleepTheMostAtAnyMinute(guardToIntervalsMap: Map<GuardId, List<Interval>>): Int {
val distribution = mutableMapOf<Minute, MutableMap<GuardId, Count>>()
for ((guardId, intervals) in guardToIntervalsMap) {
for (interval in intervals) {
for (min in interval.start until interval.end) {
distribution
.computeIfAbsent(min) { mutableMapOf() }
.merge(guardId, 1) { old, new -> old + new }
}
}
}
var max = 0
var guard = 0
var maxMinute = 0
for (minute in distribution.keys) {
val mostFrequentGuard = distribution[minute]!!.maxBy { entry -> entry.value }!!.key
val frequency = distribution[minute]!!.values.max()!!
if (frequency > max) {
max = frequency
guard = mostFrequentGuard
maxMinute = minute
}
}
return maxMinute * guard
}
private fun buildGuardToIntervalsMap(): Map<GuardId, List<Interval>> {
val guardEvents: List<GuardEvent> = readAdventInput(4, 2018)
.map(::parseEvent)
.sortedBy { it.eventDateTime }
val guardToIntervalsMap = mutableMapOf<GuardId, MutableList<Interval>>()
var currentGuardId: GuardId = 0
var currentIntervalStart: Minute = 0
for (i in 0 until guardEvents.size) {
val guardEvent = guardEvents[i]
val guardId = guardEvent.getGuardId()
when {
guardId != null -> {
currentGuardId = guardId
}
guardEvent.isFallsAsleep() -> {
currentIntervalStart = guardEvent.minute
}
guardEvent.isAwake() -> {
val interval = Interval(currentIntervalStart, guardEvent.minute)
guardToIntervalsMap.computeIfAbsent(currentGuardId) { mutableListOf() }.add(interval)
}
}
}
return guardToIntervalsMap
}
private fun parseEvent(event: String): GuardEvent {
return GuardEvent(
LocalDateTime.parse(event.substringAfter("[").substringBefore("]"), dtf),
event.substringAfter("] ")
)
}
private val dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
private data class Interval(val start: Minute, val end: Minute)
private data class GuardEvent(val eventDateTime: LocalDateTime, val message: String) {
fun getGuardId(): GuardId? {
return if (message.contains("#")) {
message.substringAfter("#").substringBefore(" ").toInt()
} else {
null
}
}
fun isFallsAsleep(): Boolean = message == "falls asleep"
fun isAwake(): Boolean = message == "wakes up"
val minute: Minute = eventDateTime.minute
}
| 0 | Kotlin | 0 | 0 | b30cf179f7b7ae534ee55d432b13859b77bbc4b7 | 3,825 | kotlin-solutions | MIT License |
kotlin/2369-check-if-there-is-a-valid-partition-for-the-array.kt | neetcode-gh | 331,360,188 | false | {"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750} | // rolling dp O(1) space
class Solution {
fun validPartition(nums: IntArray): Boolean {
val n = nums.size
val dp = booleanArrayOf(false, false, false, true)
for (i in 0 until n) {
dp[i % 4] = false
if (i > 0 && nums[i - 1] == nums[i])
dp[i % 4] = dp[i % 4] or dp[(i + 2) % 4]
if (i > 1 && nums[i - 1] == nums[i] && nums[i - 2] == nums[i])
dp[i % 4] = dp[i % 4] or dp[(i + 1) % 4]
if (i > 1 && nums[i - 1] + 1 == nums[i] && nums[i - 2] + 2 == nums[i])
dp[i % 4] = dp[i % 4] or dp[(i + 1) % 4]
}
return dp[(n - 1) % 4]
}
}
//dp O(n) space
class Solution {
fun validPartition(nums: IntArray): Boolean {
val n = nums.size
val dp = BooleanArray (n + 1).apply { this[0] = true }
for (i in 2..n) {
dp[i] = dp[i] or (nums[i - 1] == nums[i - 2] && dp[i - 2])
dp[i] = dp[i] or (i > 2 && nums[i - 1] == nums[i - 2] && nums[i - 1] == nums[i - 3] && dp[i - 3])
dp[i] = dp[i] or (i > 2 && nums[i - 1] - 1 == nums[i - 2] && nums[i - 1] - 2 == nums[i - 3] && dp[i - 3])
}
return dp[n]
}
}
//recursion
class Solution {
fun validPartition(nums: IntArray): Boolean {
val n = nums.size
val dp = IntArray (n) { -1 }
fun dfs(i: Int): Int {
if (i == n) return 1
if (dp[i] != -1) return dp[i]
if (i + 1 < n && nums[i] == nums[i + 1])
if (dfs(i + 2) == 1) return 1
if (i + 2 < n && nums[i] == nums[i + 1] && nums[i] == nums[i + 2])
if (dfs(i + 3) == 1) return 1
if (i + 2 < n && nums[i] + 1 == nums[i + 1] && nums[i] + 2 == nums[i + 2])
if (dfs(i + 3) == 1) return 1
dp[i] = 0
return dp[i]
}
return dfs(0) == 1
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 1,911 | leetcode | MIT License |
src/main/kotlin/Day05.kt | jcornaz | 573,137,552 | false | {"Kotlin": 76776} | import java.util.*
object Day05 {
fun part1(input: String): String {
val stacks = input.initialState()
input.instructions().forEach { instruction ->
repeat(instruction.count) {
stacks[instruction.to].push(stacks[instruction.from].pop())
}
}
return topOfStackToString(stacks)
}
fun part2(input: String): String {
val stacks = input.initialState()
input.instructions().forEach { instruction ->
(1..instruction.count)
.map { stacks[instruction.from].pop() }
.reversed()
.forEach { stacks[instruction.to].push(it) }
}
return topOfStackToString(stacks)
}
private fun topOfStackToString(stacks: List<Stack<Char>>): String =
stacks
.map { it.pop() }
.joinToString(separator = "")
private fun String.initialState(): List<Stack<Char>> {
val indices = generateSequence(1) { it + 4 }
val initialStateLines = lines().takeWhile { "1" !in it }
return indices
.takeWhile { it < initialStateLines.first().length }
.map { i ->
val stack = Stack<Char>()
initialStateLines.mapNotNull { line -> line.getOrNull(i)?.takeIf { !it.isWhitespace() } }
.forEach(stack::push)
stack.reverse()
stack
}.toList()
}
private fun String.instructions(): Sequence<Instruction> =
lineSequence()
.dropWhile { it.isNotBlank() }
.drop(1)
.map {
val (n, _, from, _, to) = it.removePrefix("move ").split(" ")
Instruction(n.toInt(), from.toInt() - 1, to.toInt() - 1)
}
}
data class Instruction(val count: Int, val from: Int, val to: Int)
| 1 | Kotlin | 0 | 0 | 979c00c4a51567b341d6936761bd43c39d314510 | 1,862 | aoc-kotlin-2022 | The Unlicense |
src/day07/Day07.kt | zoricbruno | 573,440,038 | false | {"Kotlin": 13739} | package day07
import readInput
abstract class FileAbstraction(
private val name: String,
private val parent: FileAbstraction?
) {
fun getParent(): FileAbstraction? = parent
fun getName(): String = name
abstract fun getTotalSize(): Int
abstract fun add(file: FileAbstraction)
abstract fun getChildren(): List<FileAbstraction>
abstract fun getChildSizes(): List<Int>
}
class File(name: String, parent: FileAbstraction, private val size: Int) : FileAbstraction(name, parent) {
override fun getTotalSize(): Int = size
override fun add(file: FileAbstraction) {}
override fun getChildren() = listOf<FileAbstraction>()
override fun getChildSizes(): List<Int> = listOf()
}
class Directory(name: String, parent: FileAbstraction?) : FileAbstraction(name, parent) {
private val contents = mutableListOf<FileAbstraction>()
override fun getTotalSize(): Int {
var total = 0
for (child in getChildren()) {
total += child.getTotalSize()
}
return total
}
override fun add(file: FileAbstraction) {
contents.add(file)
}
override fun getChildren(): List<FileAbstraction> = contents
override fun getChildSizes(): List<Int> {
val sizes = mutableListOf<Int>()
sizes.add(this.getTotalSize())
for (child in getChildren()) {
sizes.addAll(child.getChildSizes())
}
return sizes
}
}
class FileSystem {
private val root = Directory("/", null)
private var current: FileAbstraction = root
fun run(commands: List<String>) {
var i = 0
while (i < commands.size) {
if (commands[i] == "$ cd /") {
current = root
} else if (commands[i] == "$ ls") {
i++
while (i < commands.size && !commands[i].startsWith("$")) {
add(commands[i])
i++
}
i--
} else if (commands[i] == "$ cd ..") {
current = current.getParent() ?: root
} else if (commands[i].startsWith("$ cd")) {
val parts = commands[i].split(" ")
current = current.getChildren().find { it.getName() == parts.last() } ?: root
}
i++
}
}
private fun getDirectorySizes(): List<Int> = root.getChildSizes()
fun getSumOfSmallDirectoriesToDelete(): Int = getDirectorySizes().filter { it < 100000 }.sum()
fun getSmallestDirectoryToDelete(): Int {
val sizes = getDirectorySizes()
val freeSpace = 70_000_000 - sizes.first()
val spaceToFree = 30_000_000 - freeSpace
return sizes.filter { it >= spaceToFree }.min()
}
private fun add(node: String) {
val parts = node.split(" ")
if (node.startsWith("dir")) {
current.add(Directory(parts.last(), current))
} else {
current.add(File(parts.last(), current, parts.first().toInt()))
}
}
}
fun part1(input: List<String>): Int {
val filesystem = FileSystem()
filesystem.run(input)
return filesystem.getSumOfSmallDirectoriesToDelete()
}
fun part2(input: List<String>): Int {
val filesystem = FileSystem()
filesystem.run(input)
return filesystem.getSmallestDirectoryToDelete()
}
fun main() {
val day = "Day07"
val test = "${day}_test"
val testInput = readInput(day, test)
val input = readInput(day, day)
val testFirst = part1(testInput)
println(testFirst)
check(testFirst == 95437)
println(part1(input))
val testSecond = part2(testInput)
println(testSecond)
check(testSecond == 24933642)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 16afa06aff0b6e988cbea8081885236e4b7e0555 | 3,719 | kotlin_aoc_2022 | Apache License 2.0 |
src/Lesson5PrefixSums/GenomicRangeQuery.kt | slobodanantonijevic | 557,942,075 | false | {"Kotlin": 50634} | /**
* 100/100
* @param S
* @param P
* @param Q
* @return
*/
fun solution(S: String, P: IntArray, Q: IntArray): IntArray? {
val genomePrefixSums = formGenomePrefixSums(S)
val result = IntArray(P.size)
for (i in P.indices) {
val fromIndex = P[i]
val toIndex = Q[i] + 1
if (genomePrefixSums[0][toIndex] - genomePrefixSums[0][fromIndex] > 0) {
result[i] = 1
} else if (genomePrefixSums[1][toIndex] - genomePrefixSums[1][fromIndex] > 0) {
result[i] = 2
} else if (genomePrefixSums[2][toIndex] - genomePrefixSums[2][fromIndex] > 0) {
result[i] = 3
} else {
result[i] = 4
}
}
return result
}
fun formGenomePrefixSums(S: String): Array<IntArray> {
val genomePrefixSums = Array(3) { IntArray(S.length + 1) }
var a: Int
var c: Int
var g: Int
for (i in 0 until S.length) {
a = 0
c = 0
g = 0
if (S[i] == 'A') {
a = 1
} else if (S[i] == 'C') {
c = 1
} else if (S[i] == 'G') {
g = 1
}
genomePrefixSums[0][i + 1] = genomePrefixSums[0][i] + a
genomePrefixSums[1][i + 1] = genomePrefixSums[1][i] + c
genomePrefixSums[2][i + 1] = genomePrefixSums[2][i] + g
}
return genomePrefixSums
}
/**
* A DNA sequence can be represented as a string consisting of the letters A, C, G and T, which correspond to the types of successive nucleotides in the sequence. Each nucleotide has an impact factor, which is an integer. Nucleotides of types A, C, G and T have impact factors of 1, 2, 3 and 4, respectively. You are going to answer several queries of the form: What is the minimal impact factor of nucleotides contained in a particular part of the given DNA sequence?
*
* The DNA sequence is given as a non-empty string S = S[0]S[1]...S[N-1] consisting of N characters. There are M queries, which are given in non-empty arrays P and Q, each consisting of M integers. The K-th query (0 ≤ K < M) requires you to find the minimal impact factor of nucleotides contained in the DNA sequence between positions P[K] and Q[K] (inclusive).
*
* For example, consider string S = CAGCCTA and arrays P, Q such that:
*
* P[0] = 2 Q[0] = 4
* P[1] = 5 Q[1] = 5
* P[2] = 0 Q[2] = 6
* The answers to these M = 3 queries are as follows:
*
* The part of the DNA between positions 2 and 4 contains nucleotides G and C (twice), whose impact factors are 3 and 2 respectively, so the answer is 2.
* The part between positions 5 and 5 contains a single nucleotide T, whose impact factor is 4, so the answer is 4.
* The part between positions 0 and 6 (the whole string) contains all nucleotides, in particular nucleotide A whose impact factor is 1, so the answer is 1.
* Write a function:
*
* class Solution { public int[] solution(String S, int[] P, int[] Q); }
*
* that, given a non-empty string S consisting of N characters and two non-empty arrays P and Q consisting of M integers, returns an array consisting of M integers specifying the consecutive answers to all queries.
*
* Result array should be returned as an array of integers.
*
* For example, given the string S = CAGCCTA and arrays P, Q such that:
*
* P[0] = 2 Q[0] = 4
* P[1] = 5 Q[1] = 5
* P[2] = 0 Q[2] = 6
* the function should return the values [2, 4, 1], as explained above.
*
* Write an efficient algorithm for the following assumptions:
*
* N is an integer within the range [1..100,000];
* M is an integer within the range [1..50,000];
* each element of arrays P, Q is an integer within the range [0..N − 1];
* P[K] ≤ Q[K], where 0 ≤ K < M;
* string S consists only of upper-case English letters A, C, G, T.
*/ | 0 | Kotlin | 0 | 0 | 155cf983b1f06550e99c8e13c5e6015a7e7ffb0f | 3,791 | Codility-Kotlin | Apache License 2.0 |
src/main/kotlin/day3/Aoc.kt | widarlein | 225,589,345 | false | null | package day3
import java.io.File
import kotlin.IllegalArgumentException
fun main(args: Array<String>) {
if (args.size < 1) {
println("Must provide input data")
System.exit(0)
}
val inputLines = File("src/main/kotlin/day3/${args[0]}").readLines()
val wiresDirections = inputLines.map { it.split(",") }
val wiresCoordinates = wiresDirections.map { getWireCoorinates(it).drop(1)}
val intersections = findWireIntersections(wiresCoordinates[0], wiresCoordinates[1])
val closestIntersection = intersections.minBy { it.distance }
println("Part 1. Distance to closest intersection($closestIntersection): ${closestIntersection?.distance}")
val closestIntersectionAndSteps = findIntersectionWithLeastSteps(intersections, wiresCoordinates)
println("Part 2. Fewest steps to intersection ${closestIntersectionAndSteps?.first} with ${closestIntersectionAndSteps?.second} steps")
}
private fun getWireCoorinates(wireDirections: List<String>): List<Pair<Int, Int>> {
return wireDirections.fold(listOf(0 to 0)) { sum, move ->
val lastCoordinate = sum.last()
val moveCoords = when (move.direction()) {
'R' -> right(move.steps() from lastCoordinate)
'L' -> left(move.steps() from lastCoordinate)
'U' -> up(move.steps() from lastCoordinate)
'D' -> down(move.steps() from lastCoordinate)
else -> throw IllegalArgumentException("NO SUCH DIRECTION: ${move.direction()}")
}
sum + moveCoords
}
}
private fun findIntersectionWithLeastSteps(intersections: List<Pair<Int, Int>>, wiresCoordinates: List<List<Pair<Int, Int>>>): Pair<Pair<Int, Int>, Int>? {
return intersections.map { it to stepsToIntersectionForWire(it, wiresCoordinates[0]) + stepsToIntersectionForWire(it, wiresCoordinates[1]) }
.minBy { it.second }
}
private fun stepsToIntersectionForWire(intersection: Pair<Int, Int>, wireCoordinates: List<Pair<Int, Int>>) = wireCoordinates.indexOf(intersection) + 1
private fun right(stepsFromPoint: Pair<Int, Pair<Int, Int>>): List<Pair<Int, Int>> {
val (steps, point) = stepsFromPoint
val x = point.first
val y = point.second
return (x+1..x+steps).map { it to y }
}
private fun left(stepsFromPoint: Pair<Int, Pair<Int, Int>>): List<Pair<Int, Int>> {
val (steps, point) = stepsFromPoint
val x = point.first
val y = point.second
return (x-1 downTo x-steps).map { it to y }
}
private fun up(stepsFromPoint: Pair<Int, Pair<Int, Int>>): List<Pair<Int, Int>> {
val (steps, point) = stepsFromPoint
val x = point.first
val y = point.second
return (y+1..y+steps).map { x to it }
}
private fun down(stepsFromPoint: Pair<Int, Pair<Int, Int>>): List<Pair<Int, Int>> {
val (steps, point) = stepsFromPoint
val x = point.first
val y = point.second
return (y-1 downTo y-steps).map { x to it }
}
private fun findWireIntersections(wire1: List<Pair<Int, Int>>, wire2: List<Pair<Int, Int>>) = wire1.filter { wire2.contains(it) }
private infix fun Int.from(point: Pair<Int, Int>) = this to point
private fun String.direction() = this[0]
private fun String.steps() = this.substring(1).toInt()
val Pair<Int, Int>.distance: Int
get() = Math.abs(this.first) + Math.abs(this.second)
private infix fun <A, B, C> Pair<A, B>.and(third: C): Triple<A, B, C> = Triple(this.first, this.second, third) | 0 | Kotlin | 0 | 0 | b4977e4a97ad61177977b8eeb1dcf298067e8ab4 | 3,407 | AdventOfCode2019 | MIT License |
src/main/kotlin/com/anahoret/aoc2022/day21/main.kt | mikhalchenko-alexander | 584,735,440 | false | null | package com.anahoret.aoc2022.day21
import java.io.File
import kotlin.system.measureTimeMillis
enum class Operation {
PLUS, MINUS, TIMES, DIVIDE;
}
sealed class Creature(val name: String) {
abstract fun calculate(): Long
}
sealed class NumberCreature(name: String, val number: Long) : Creature(name) {
override fun calculate(): Long {
return number
}
}
class NumberMonkey(name: String, number: Long) : NumberCreature(name, number)
class Human(name: String, number: Long) : NumberCreature(name, number)
class WaitingMonkey(name: String, val left: Creature, val right: Creature, val operation: Operation) : Creature(name) {
override fun calculate(): Long {
return when (operation) {
Operation.PLUS -> left.calculate() + right.calculate()
Operation.MINUS -> left.calculate() - right.calculate()
Operation.TIMES -> left.calculate() * right.calculate()
Operation.DIVIDE -> left.calculate() / right.calculate()
}
}
}
fun parseMonkeys(str: String): WaitingMonkey {
val operationMap = mapOf(
"+" to Operation.PLUS,
"-" to Operation.MINUS,
"*" to Operation.TIMES,
"/" to Operation.DIVIDE,
)
val rootName = "root"
val humanName = "humn"
val creatureCache = mutableMapOf<String, Creature>()
val nameDataMap = str.split("\n").associate {
val (name, data) = it.split(": ")
name to data
}
fun parse(name: String, dataLine: String): Creature {
val cached = creatureCache[name]
return if (cached != null) {
cached
} else {
val data = dataLine.split(" ")
when {
data.size == 1 && name == humanName -> Human(name, data.first().toLong()).also { creatureCache[name] = it }
data.size == 1 -> NumberMonkey(name, data.first().toLong()).also { creatureCache[name] = it }
else -> {
val (l, o, r) = data
val left = parse(l, nameDataMap.getValue(l))
val right = parse(r, nameDataMap.getValue(r))
WaitingMonkey(name, left, right, operationMap.getValue(o))
}
}.also { creatureCache[name] = it }
}
}
return parse(rootName, nameDataMap.getValue(rootName)) as WaitingMonkey
}
fun main() {
val input = File("src/main/kotlin/com/anahoret/aoc2022/day21/input.txt")
.readText()
.trim()
val rootMonkey = parseMonkeys(input)
// Part 1
part1(rootMonkey).also { println("P1: ${it}ms") }
// Part 2
part2(rootMonkey).also { println("P2: ${it}ms") }
}
private fun part1(rootMonkey: WaitingMonkey) = measureTimeMillis {
rootMonkey.calculate().also(::println)
}
private fun part2(rootMonkey: WaitingMonkey) = measureTimeMillis {
fun hasHuman(creature: Creature): Boolean {
return when (creature) {
is Human -> true
is NumberMonkey -> false
is WaitingMonkey -> hasHuman(creature.left) || hasHuman(creature.right)
}
}
fun match(goal: Long, creature: Creature): Long {
return when (creature) {
is Human -> goal
is NumberMonkey -> creature.number
is WaitingMonkey -> {
if (hasHuman(creature.left)) {
val rightValue = creature.right.calculate()
val leftGoal = when(creature.operation) {
Operation.PLUS -> goal - rightValue
Operation.MINUS -> goal + rightValue
Operation.TIMES -> goal / rightValue
Operation.DIVIDE -> goal * rightValue
}
match(leftGoal, creature.left)
} else {
val leftValue = creature.left.calculate()
val rightGoal = when(creature.operation) {
Operation.PLUS -> goal - leftValue
Operation.MINUS -> leftValue - goal
Operation.TIMES -> goal / leftValue
Operation.DIVIDE -> leftValue / goal
}
match(rightGoal, creature.right)
}
}
}
}
if (hasHuman(rootMonkey.left)) {
val rightValue = rootMonkey.right.calculate()
match(rightValue, rootMonkey.left)
} else {
val leftValue = rootMonkey.left.calculate()
match(leftValue, rootMonkey.right)
}.also { println(it) }
}
| 0 | Kotlin | 0 | 0 | b8f30b055f8ca9360faf0baf854e4a3f31615081 | 4,575 | advent-of-code-2022 | Apache License 2.0 |
src/day11/Day11.kt | martinhrvn | 724,678,473 | false | {"Kotlin": 27307, "Jupyter Notebook": 1336} | package day11
import day10.Coord
import elementPairs
import println
import readInput
import kotlin.math.abs
data class Point(val x: Long, val y: Long)
data class GalaxyMap(val input: List<String>, val expansion: Long) {
val colsToMultipy = getEmptyCols()
val rowsToMultipy = getEmptyRows()
fun getEmptyRows(): List<Int> {
return input.mapIndexedNotNull { i, r -> if (!r.contains("#")) i else null}
}
fun getEmptyCols(): List<Int> {
return input[0].indices.filter { i -> input.none { line -> line[i] == '#' }}
}
fun getGalaxies(): List<Point> {
return input.flatMapIndexed { y, row ->
row.mapIndexedNotNull { x, elm ->
val expandedX = colsToMultipy.count { x > it} * (expansion - 1)
val expandedY = rowsToMultipy.count { y > it} * (expansion - 1)
if (elm == '#')
Point(x.toLong() + expandedX, y.toLong() + expandedY)
else
null
}
}
}
fun getGalaxyPairs(): Sequence<Pair<Point, Point>> {
return elementPairs(getGalaxies())
}
fun getGalaxyDistance(g1: Point, g2: Point): Long {
return abs(g2.x - g1.x) + abs(g2.y - g1.y)
}
fun getSumOfDistances(): Long {
return getGalaxyPairs().sumOf { (g1, g2) -> getGalaxyDistance(g1, g2) }
}
}
class Day11(val input: List<String>) {
fun part1(): Long {
return GalaxyMap(input, 2).getSumOfDistances()
}
fun part2(): Long {
return GalaxyMap(input, 1000000).getSumOfDistances()
}
}
fun main() {
val day11 = Day11(readInput("day11/Day11"))
day11.part1().println()
day11.part2().println()
} | 0 | Kotlin | 0 | 0 | 59119fba430700e7e2f8379a7f8ecd3d6a975ab8 | 1,715 | advent-of-code-2023-kotlin | Apache License 2.0 |
src/main/kotlin/day11/Day11.kt | daniilsjb | 434,765,082 | false | {"Kotlin": 77544} | package day11
import java.io.File
fun main() {
val data = parse("src/main/kotlin/day11/Day11.txt")
val answer1 = part1(data.toMutableList())
val answer2 = part2(data.toMutableList())
println("🎄 Day 11 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private fun parse(path: String): List<Int> =
File(path)
.readLines()
.flatMap { it.map(Char::digitToInt) }
private fun adjacentNodes(x: Int, y: Int): List<Pair<Int, Int>> =
listOfNotNull(
if (x - 1 >= 0 && y - 1 >= 0) x - 1 to y - 1 else null,
if ( y - 1 >= 0) x to y - 1 else null,
if (x + 1 < 10 && y - 1 >= 0) x + 1 to y - 1 else null,
if (x - 1 >= 0 ) x - 1 to y else null,
if (x + 1 < 10 ) x + 1 to y else null,
if (x - 1 >= 0 && y + 1 < 10) x - 1 to y + 1 else null,
if ( y + 1 < 10) x to y + 1 else null,
if (x + 1 < 10 && y + 1 < 10) x + 1 to y + 1 else null,
)
private fun step(energy: MutableList<Int>): Int {
var flashCount = 0
val flashQueue = ArrayDeque<Pair<Int, Int>>(100)
for (y in 0 until 10) {
for (x in 0 until 10) {
val index = y * 10 + x
if (++energy[index] > 9) {
flashQueue.addLast(x to y)
energy[index] = 0
}
}
}
while (flashQueue.isNotEmpty()) {
val (x, y) = flashQueue.removeLast()
for ((nx, ny) in adjacentNodes(x, y)) {
val index = ny * 10 + nx
if (energy[index] != 0 && ++energy[index] > 9) {
flashQueue.addLast(nx to ny)
energy[index] = 0
}
}
++flashCount
}
return flashCount
}
private fun part1(energy: MutableList<Int>) =
(0 until 100)
.sumOf { step(energy) }
private fun part2(energy: MutableList<Int>) =
generateSequence(1) { it + 1 }
.first { step(energy) == 100 }
| 0 | Kotlin | 0 | 1 | bcdd709899fd04ec09f5c96c4b9b197364758aea | 2,083 | advent-of-code-2021 | MIT License |
src/day1/Day01.kt | TP1cks | 573,328,994 | false | {"Kotlin": 5377} | fun main() {
part1()
part2()
}
fun part1() {
println("Part 1: Highest calorie count: ${highestCalorieCount(getElfEntries())}")
}
fun part2() {
println("Part 2: Top three calorie count sum: ${topNHighestCalorieCount(getElfEntries(), 3)}")
}
fun highestCalorieCount(elfEntries: List<List<String>>) : Int {
val max = elfEntries.map { calorieEntries ->
calorieEntries.map { calorieEntry ->
calorieEntry.toInt()
}.sum()
}.max()
return max
}
fun topNHighestCalorieCount(elfEntries: List<List<String>>, n: Int) : Int {
val sortedCalorieCounts = elfEntries.map { calorieEntries ->
calorieEntries.map { calorieEntry ->
calorieEntry.toInt()
}.sum()
}.sorted()
return sortedCalorieCounts.takeLast(n).sum()
}
fun getElfEntries() : List<List<String>> {
return readInput("day1/input").split("\n\n").map { it.split("\n") }
}
| 0 | Kotlin | 0 | 0 | 52f79a4593384fe651d905ddaea379f49ddfe513 | 916 | advent-of-code-2022 | Apache License 2.0 |
src/Day18.kt | StephenVinouze | 572,377,941 | false | {"Kotlin": 55719} | data class Cube(
val x: Int,
val y: Int,
val z: Int,
)
fun main() {
fun List<String>.toCubes(): List<Cube> =
map {
val split = it.split(",")
Cube(split[0].toInt(), split[1].toInt(), split[2].toInt())
}
fun computeUncoveredSides(cubes: List<Cube>): Int =
cubes.fold(0) { acc, currentCube ->
var uncoveredSides = acc
val otherCubes = cubes.filterNot { it == currentCube }
if (otherCubes.none { cube -> cube.x == currentCube.x - 1 && cube.y == currentCube.y && cube.z == currentCube.z }) uncoveredSides++
if (otherCubes.none { cube -> cube.x == currentCube.x + 1 && cube.y == currentCube.y && cube.z == currentCube.z }) uncoveredSides++
if (otherCubes.none { cube -> cube.y == currentCube.y - 1 && cube.x == currentCube.x && cube.z == currentCube.z }) uncoveredSides++
if (otherCubes.none { cube -> cube.y == currentCube.y + 1 && cube.x == currentCube.x && cube.z == currentCube.z }) uncoveredSides++
if (otherCubes.none { cube -> cube.z == currentCube.z - 1 && cube.x == currentCube.x && cube.y == currentCube.y }) uncoveredSides++
if (otherCubes.none { cube -> cube.z == currentCube.z + 1 && cube.x == currentCube.x && cube.y == currentCube.y }) uncoveredSides++
uncoveredSides
}
fun part1(input: List<String>): Int =
computeUncoveredSides(input.toCubes())
fun part2(input: List<String>): Int {
return 0
}
check(part1(readInput("Day18_test")) == 64)
//check(part2(readInput("Day18_test")) == 58)
val input = readInput("Day18")
println(part1(input))
//println(part2(input))
} | 0 | Kotlin | 0 | 0 | 11b9c8816ded366aed1a5282a0eb30af20fff0c5 | 1,712 | AdventOfCode2022 | Apache License 2.0 |
src/day12/Day12.kt | martinhrvn | 724,678,473 | false | {"Kotlin": 27307, "Jupyter Notebook": 1336} | package day12
import readInput
fun generateCombinations(n: Int, maxHash: Int): List<String> {
return sequence {
val range = 0 until (1 shl n)
for (num in range) {
val binaryString = num.toString(2).padStart(n, '0')
val combination = binaryString.map { if (it == '0') '.' else '#' }.joinToString("")
yield(combination)
}
}.filter { it.count { char -> char == '#' } == maxHash }
.toList()
}
class Day12(val input: List<String>) {
fun part1(): Long {
val filled = input.map {
val (springs, countsStr) = it.split(" ")
val toFill = springs.count { it == '?' }
val brokenCount = countsStr.split(",").map { it.toInt() }
val brokenSprings = springs.count { it == '#' }
val combinations = generateCombinations(toFill, brokenCount.sum() - brokenSprings)
combinations.map { combination ->
combination.fold(springs) { acc, char ->
acc.replaceFirst('?', char)
}
}.filter {
it.split("\\.+".toRegex()).filter { it.isNotEmpty()
}.map { it.length } == brokenCount
}
}
return filled.map { it.size }.sum().toLong()
}
}
fun main() {
val day12 = Day12(readInput("day12/Day12"))
println(day12.part1())
} | 0 | Kotlin | 0 | 0 | 59119fba430700e7e2f8379a7f8ecd3d6a975ab8 | 1,383 | advent-of-code-2023-kotlin | Apache License 2.0 |
src/main/kotlin/aoc2021/Day02.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2021
import readInput
private enum class Direction { FORWARD, DOWN, UP }
private data class Movement(val direction: Direction, val distance: Int) {
companion object {
fun fromString(str: String): Movement {
val split = str.split(" ")
return Movement(Direction.valueOf(split[0].uppercase()), split[1].toInt())
}
}
}
private fun part1(input: List<String>): Int {
var x = 0
var y = 0
input.map(Movement.Companion::fromString).forEach {
when (it.direction) {
Direction.FORWARD -> x += it.distance
Direction.DOWN -> y += it.distance
Direction.UP -> y -= it.distance
}
}
return x * y
}
private fun part2(input: List<String>): Int {
var x = 0
var y = 0
var aim = 0
input.map(Movement.Companion::fromString).forEach {
when (it.direction) {
Direction.FORWARD -> {
x += it.distance
y += it.distance * aim
}
Direction.DOWN -> aim += it.distance
Direction.UP -> aim -= it.distance
}
}
return x * y
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 150)
check(part2(testInput) == 900)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 1,436 | adventOfCode | Apache License 2.0 |
day-21/src/main/kotlin/DiracDice.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 {
val lines = readInputLines()
val player1 = Player(lines[0].split(":")[1].strip().toInt(), 0, 1000)
val player2 = Player(lines[1].split(":")[1].strip().toInt(), 0, 1000)
val die = Die()
while (!player1.hasWon() && !player2.hasWon()) {
player1.move(die.roll().value + die.roll().value + die.roll().value)
if (player1.hasWon()) {
break
}
player2.move(die.roll().value + die.roll().value + die.roll().value)
}
val losingScore = if (player1.score > player2.score) player2.score else player1.score
return die.rolls * losingScore
}
private fun partTwo(): Long {
val lines = readInputLines()
val player1 = Player(lines[0].split(":")[1].strip().toInt(), 0, 21)
val player2 = Player(lines[1].split(":")[1].strip().toInt(), 0, 21)
val cache = mutableMapOf<Universe, List<Universe>>()
val universe = Universe(player1, player2)
fillCache(universe, cache)
val result = getResult(cache)
return result[universe]!!.maxOf { it.value }
}
private fun getResult(cache: MutableMap<Universe, List<Universe>>): Map<Universe, Map<String, Long>> {
val results = mutableMapOf<Universe, Map<String, Long>>()
cache.entries
.filter { (k, _) -> k.hasWon() }
.forEach { (k, _) ->
results[k] = mutableMapOf(k.whoWon() to 1)
}
while (results.size != cache.size) {
cache.entries
.filter { entry -> entry.key !in results && entry.value.all { it in results } }
.forEach { (k, v) ->
val universeResult = mutableMapOf<String, Long>()
for (subUniverse in v) {
results[subUniverse]!!.forEach {
universeResult.merge(it.key, it.value) { old, new -> old + new }
}
}
results[k] = universeResult
}
}
return results
}
private fun fillCache(universe: Universe, cache: MutableMap<Universe, List<Universe>>) {
if (universe in cache) return
if (universe.hasWon()) {
cache[universe] = emptyList()
return
}
val roll = universe.roll()
cache[universe] = roll
roll.forEach { fillCache(it, cache) }
}
data class Universe(
val player1: Player,
val player2: Player,
) {
fun hasWon() = player1.hasWon() || player2.hasWon()
fun whoWon() = if (player1.hasWon()) "player1" else "player2"
fun roll(): List<Universe> {
val player1Universes = mutableListOf<Universe>()
for (x in 1..3) {
for (y in 1..3) {
for (z in 1..3) {
player1Universes.add(Universe(player1.copy().apply { move(x + y + z) }, player2))
}
}
}
val universes = mutableListOf<Universe>()
for (u in player1Universes) {
if (u.hasWon()) {
universes.add(u)
continue
}
for (x in 1..3) {
for (y in 1..3) {
for (z in 1..3) {
universes.add(u.copy(player2 = u.player2.copy().apply { move(x + y + z) }))
}
}
}
}
return universes
}
}
data class Die(
var value: Int = 100,
var rolls: Int = 0,
) {
fun roll(): Die {
if (value == 100) {
value = 1
} else {
value++
}
rolls++
return this
}
}
data class Player(
var position: Int,
var score: Int,
val winningScore: Int,
) {
fun move(value: Int) {
val toAdd = value % 10
position += toAdd
if (position > 10) position -= 10
score += position
}
fun hasWon() = score >= winningScore
}
private fun readInputLines(): List<String> {
return {}::class.java.classLoader.getResource("input.txt")!!
.readText()
.split("\n")
.filter { it.isNotBlank() }
}
| 0 | Kotlin | 0 | 0 | 17af21b269739e04480cc2595f706254bc455008 | 4,360 | aoc-2021 | MIT License |
src/main/java/com/booknara/problem/array/RemoveIntervalKt.kt | booknara | 226,968,158 | false | {"Java": 1128390, "Kotlin": 177761} | package com.booknara.problem.array
/**
* 1272. Remove Interval (Medium)
* https://leetcode.com/problems/remove-interval/
*/
class RemoveIntervalKt {
// T:O(n), S:O(n)
fun removeInterval(intervals: Array<IntArray>, toBeRemoved: IntArray): List<List<Int>> {
// input check, intervals.length >= 1
val res: MutableList<List<Int>> = ArrayList()
for (i in intervals.indices) {
val start = intervals[i][0]
val end = intervals[i][1]
val startMax = Math.max(start, toBeRemoved[0])
val endMin = Math.min(end, toBeRemoved[1])
if (startMax < endMin) {
// overlapped
if (start < toBeRemoved[0]) {
res.add(listOf(start, toBeRemoved[0]))
}
if (end > toBeRemoved[1]) {
res.add(listOf(toBeRemoved[1], end))
}
} else {
// non-overlapped
res.add(listOf(intervals[i][0], intervals[i][1]))
}
}
return res
}
}
/**
Sorted intervals
Input: intervals = [[0,2],[3,4],[5,7]], toBeRemoved = [1,6]
Output: [[0,1],[6,7]]
[0 2]
[3 4]
[5 7]
[1 6]
[0,1], [6,7]
loop intervals
start, end
1. non-overlapped -> add the interval to result set
2. overlapped ->
- the start point check
start point < toBeRemoved.start -> [start,toBeRemoved.start]
- the end point check
end point > toBeRemoved.end -> [toBeRemoved.end,end]
- fully overlapped -> skip
*/ | 0 | Java | 1 | 1 | 04dcf500ee9789cf10c488a25647f25359b37a53 | 1,534 | playground | MIT License |
src/main/kotlin/Forest.kt | alebedev | 573,733,821 | false | {"Kotlin": 82424} | fun main() {
Forest.solve()
}
private object Forest {
fun solve() {
val grid = readInput()
println("Visible trees: ${countVisible(grid)}")
println("Max scenic score: ${maxScenicScore(grid)}")
}
private fun readInput(): Grid {
return generateSequence(::readLine).map {
it.split("").filterNot { it.isEmpty() }.map { it.toInt(10) }
}.toList()
}
private fun maxScenicScore(trees: Grid): Int {
var result = 0
trees.forEachIndexed { i, line ->
line.forEachIndexed { j, tree ->
var leftView = 0
for (left in (j - 1) downTo 0) {
leftView += 1
if (trees[i][left] >= tree) break
}
var rightView = 0
for (right in (j + 1) until line.size) {
rightView += 1
if (trees[i][right] >= tree) break
}
var topView = 0
for (top in (i - 1) downTo 0) {
topView += 1
if (trees[top][j] >= tree) break
}
var bottomView = 0
for (bottom in (i + 1) until trees.size) {
bottomView += 1
if (trees[bottom][j] >= tree) break
}
result = maxOf(result, leftView * rightView * topView * bottomView)
}
}
return result
}
private fun countVisible(trees: Grid): Int {
var result = 0
trees.forEachIndexed { i, line ->
line.forEachIndexed { j, item ->
if (i == 0 || j == 0 || i == trees.size - 1 || j == line.size - 1) {
result += 1
} else if (line.subList(0, j).max() < item) {
result += 1
} else if (line.subList(j + 1, line.size).max() < item) {
result += 1
} else {
var topVisible = true
var bottomVisible = true
for (z in trees.indices) {
if (z == i) continue
if (topVisible && z < i) {
topVisible = trees[z][j] < item
}
if (bottomVisible && z > i) {
bottomVisible = trees[z][j] < item
}
}
if (topVisible || bottomVisible) result += 1
}
}
}
return result
}
}
private typealias Grid = List<List<Int>> | 0 | Kotlin | 0 | 0 | d6ba46bc414c6a55a1093f46a6f97510df399cd1 | 2,652 | aoc2022 | MIT License |
codeforces/round783/b_wrong.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.round783
import kotlin.math.sign
fun solve(a: List<Int>): Int {
val pref = mutableListOf(0L)
val prefIndex = mutableListOf(0)
val prefIndexRight = mutableListOf(0)
var prefSum = 0L
val dp = IntArray(a.size + 1)
for (i in a.indices) {
prefSum -= a[i]
dp[i + 1] = dp[i] + a[i].sign
if (prefSum > pref.last()) {
pref.add(prefSum)
prefIndex.add(i + 1)
prefIndexRight.add(i + 1)
continue
}
val bs = pref.binarySearch(prefSum)
if (bs >= 0) {
val j = prefIndexRight[bs]
dp[i + 1] = maxOf(dp[i + 1], dp[j])
prefIndexRight[bs] = i + 1
}
if (prefSum < pref.last()) {
val b = if (bs >= 0) bs + 1 else - 1 - bs
val j = prefIndex[b]
dp[i + 1] = maxOf(dp[i + 1], dp[j] + i + 1 - j)
}
if (pref.size >= 2 && prefSum > pref[pref.size - 2] && prefSum < pref.last() && dp[i + 1] - dp[prefIndex.last()] > i + 1 - prefIndex.last()) {
pref.removeLast()
prefIndex.removeLast()
prefIndexRight.removeLast()
pref.add(prefSum)
prefIndex.add(i + 1)
prefIndexRight.add(i + 1)
}
var improve = false
while (true) {
if (pref.isNotEmpty() && prefSum <= pref.last() && dp[i + 1] - dp[prefIndex.last()] > i + 1 - prefIndex.last()) {
pref.removeLast()
prefIndex.removeLast()
prefIndexRight.removeLast()
improve = true
continue
}
break
}
if (improve) {
pref.add(prefSum)
prefIndex.add(i + 1)
prefIndexRight.add(i + 1)
}
}
return dp.last()
}
private fun solve() {
readLn()
val a = readInts()
println(solve(a))
}
fun main() = repeat(readInt()) { 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,754 | competitions | The Unlicense |
src/main/kotlin/_2023/Day12.kt | novikmisha | 572,840,526 | false | {"Kotlin": 145780} | package _2023
import Day
import InputReader
class Day12 : Day(2023, 12) {
data class Hash(
val schema: String,
val groups: String
)
override val firstTestAnswer = 21L
override val secondTestAnswer = 525152L
private fun solve(
schema: String,
neededGroups: List<Int>
) = solve(schema, neededGroups, mutableMapOf())
private fun process(schema: String, neededGroups: List<Int>, hash: MutableMap<Hash, Long>): Long {
if (neededGroups.isEmpty()) {
return 0L
}
val currentGroup = neededGroups.first()
if (schema.length < currentGroup) {
return 0L
}
for (i in 1 until currentGroup) {
if (schema[i] == '.') {
return 0L
}
}
if (currentGroup == schema.length) {
if (neededGroups.size == 1) {
return 1L
}
return 0L
}
if (schema[currentGroup] == '#') {
return 0L
}
return solve(schema.drop(currentGroup + 1), neededGroups.drop(1), hash)
}
private fun solve(schema: String, neededGroups: List<Int>, hash: MutableMap<Hash, Long>): Long =
hash.getOrPut(Hash(schema, neededGroups.joinToString { "," })) {
if (schema.isEmpty()) {
return@getOrPut if (neededGroups.isEmpty()) {
1L
} else {
0L
}
}
when (schema.first()) {
'.' -> {
solve(schema.drop(1), neededGroups, hash)
}
'#' -> {
process(schema, neededGroups, hash)
}
'?' -> {
solve(schema.drop(1), neededGroups, hash) + process(schema, neededGroups, hash)
}
else -> {
error("")
}
}
}
override fun first(input: InputReader) = input.asLines().sumOf { line ->
val (unparsedGroups, unparsedNeededGroups) = line.split(" ")
val neededGroups = unparsedNeededGroups.trim().split(",").map { it.trim().toInt() }
val schema = unparsedGroups.split(".").filter { it.isNotEmpty() }.joinToString(separator = ".")
solve(schema, neededGroups)
}
override fun second(input: InputReader) = input.asLines().sumOf { line ->
val (unparsedGroups, unparsedNeededGroups) = line.split(" ")
val neededGroups =
("${unparsedNeededGroups.trim()},").repeat(5).trim().split(",").filter { it.isNotEmpty() }
.map { it.trim().toInt() }
val schema = ("${unparsedGroups.trim()}?").repeat(5).dropLast(1).split(".").filter { it.isNotEmpty() }
.joinToString(separator = ".")
solve(schema, neededGroups)
}
}
fun main() {
Day12().solve()
} | 0 | Kotlin | 0 | 0 | 0c78596d46f3a8bf977bf356019ea9940ee04c88 | 2,930 | advent-of-code | Apache License 2.0 |
src/Day12.kt | EdoFanuel | 575,561,680 | false | {"Kotlin": 80963} |
import utils.aStar
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
data class Path(val start: Pair<Int, Int>, val end: Pair<Int, Int>, val grid: Array<IntArray>) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Path
if (start != other.start) return false
if (end != other.end) return false
if (!grid.contentDeepEquals(other.grid)) return false
return true
}
override fun hashCode(): Int {
var result = start.hashCode()
result = 31 * result + end.hashCode()
result = 31 * result + grid.contentDeepHashCode()
return result
}
}
fun main() {
val directions = listOf(
-1 to 0,
1 to 0,
0 to -1,
0 to 1
)
fun convertToPath(input: List<String>): Path {
var startPoint = 0 to 0
var endPoint = 0 to 0
val result = input.mapIndexed { i, row -> row.mapIndexed { j, c ->
when(c) {
'S' -> {
startPoint = i to j
0
}
'E' -> {
endPoint = i to j
25
}
else -> c - 'a'
}
}.toIntArray()}.toTypedArray()
return Path(startPoint, endPoint, result)
}
fun part1(input: Path): Int {
val path = aStar(
input.start,
{p -> p == input.end},
{ (x, y) -> directions
.map { (dx, dy) -> x + dx to y + dy }
.filter { (nx, ny) -> nx >= 0 && nx <= input.grid.lastIndex
&& ny >= 0 && ny <= input.grid[nx].lastIndex
&& input.grid[nx][ny] <= input.grid[x][y] + 1}},
{ (x, y) -> max(abs(x - input.end.first), abs(y - input.end.second)) * 1.0 }
)
return path.size
}
fun part2(input: Path): Int {
var minPath = Int.MAX_VALUE
for (i in input.grid.indices) {
for (j in input.grid[i].indices) {
if (input.grid[i][j] == 0) {
val path = aStar(
i to j,
{p -> p == input.end},
{ (x, y) -> directions
.map { (dx, dy) -> x + dx to y + dy }
.filter { (nx, ny) -> nx >= 0 && nx <= input.grid.lastIndex
&& ny >= 0 && ny <= input.grid[nx].lastIndex
&& input.grid[nx][ny] <= input.grid[x][y] + 1}},
{ (x, y) -> max(abs(x - input.end.first), abs(y - input.end.second)) * 1.0 }
)
if (path.isEmpty()) continue
minPath = min(minPath, path.size)
}
}
}
return minPath
}
val test = readInput("Day12_test")
println(part1(convertToPath(test)))
println(part2(convertToPath(test)))
val input = readInput("Day12")
println(part1(convertToPath(input)))
println(part2(convertToPath(input)))
} | 0 | Kotlin | 0 | 0 | 46a776181e5c9ade0b5e88aa3c918f29b1659b4c | 3,198 | Advent-Of-Code-2022 | Apache License 2.0 |
src/main/kotlin/days/day23/Day23.kt | Stenz123 | 725,707,248 | false | {"Kotlin": 123279, "Shell": 862} | package days.day23
import days.Day
import java.util.*
import kotlin.collections.HashMap
//Note: Increase your stack size -Xss10m
//Part 1: I implemented dijkstra algorithm wich worked amazing for p
//Part 2: I couldn't get dijkstra to work, so i redid everything with a recursive solution
class Day23 : Day() {
override fun partOne(): Any {
val map = mutableMapOf<Coordinate, Char>()
readInput().forEachIndexed { y, line ->
line.forEachIndexed { x, char ->
if (char != '#') {
map[Coordinate(x, y)] = char
}
}
}
val start = map.keys.first { it.y == 0 }
val end = map.keys.first { it.y == readInput().size - 1 }
return dijkstra(start, end, map)
}
override fun partTwo(): Any {
val map = mutableMapOf<Coordinate, Char>()
readInput().forEachIndexed { y, line ->
line.forEachIndexed { x, char ->
if (char != '#') {
map[Coordinate(x, y)] = '.'
}
}
}
val start = map.keys.first { it.y == 0 }
val end = map.keys.first { it.y == readInput().size - 1 }
val visited = HashMap<Coordinate, Boolean>()
map.keys.forEach { visited[it] = false }
return solve(start, end, visited, 0, map)
}
fun solve(current: Coordinate, end: Coordinate, visited: HashMap<Coordinate, Boolean>, currentLength: Int, map: Map<Coordinate, Char>):Int {
if (current !in map.keys || visited[current]!!) {
return -1
}
if (current == end) {
if (highest < currentLength) {
println(currentLength)
highest = currentLength
}
return currentLength
}
visited[current] = true
val result = current.getNeighbours(map[current]!!).maxOf {neighbour ->
solve(neighbour, end, visited, currentLength + 1, map)
}
visited[current] = false
return result
}
companion object {
var highest = 0
}
}
fun dijkstra(start: Coordinate, end: Coordinate, map: Map<Coordinate, Char>): Int {
val distances = mutableMapOf<Coordinate, Int>()
val visited = mutableSetOf<Coordinate>()
val priorityQueue: Queue<Coordinate> = LinkedList()
val previous = mutableMapOf<Coordinate, Coordinate>()
var result = 0
// Initialization
distances[start] = 0
priorityQueue.add(start)
priorityQueue.add(start)
while (priorityQueue.isNotEmpty()) {
val current = priorityQueue.poll()
visited.add(current)
val neighbors = current.getNeighbours(map[current]!!)
.filter { map.containsKey(it) }
.filter { !getPath(previous, start, current).contains(it) }
for (neighbor in neighbors) {
val newDistance = distances[current]!! + 1
if (!priorityQueue.contains(neighbor)) {
priorityQueue.add(neighbor)
}
if (newDistance > distances.getOrDefault(neighbor, Int.MIN_VALUE)) {
distances[neighbor] = newDistance
previous[neighbor] = current
if (neighbor == end) {
// Reached the destination, reconstruct and print the path
if (distances[neighbor]!! > result) {
//printPath(previous, start, end, map)
println("\u001B[32m${distances[neighbor]!!}\u001B[0m")
result = distances[neighbor]!!
}
}
}
}
}
printPath(previous, start, end, map)
return result
}
fun getPath(previous: Map<Coordinate, Coordinate>, start: Coordinate, end: Coordinate): List<Coordinate> {
var current = end
val path = mutableListOf<Coordinate>()
while (current != start) {
path.add(current)
current = previous[current] ?: break
}
path.add(start)
path.reverse()
return path
}
fun printPath(previous: Map<Coordinate, Coordinate>, start: Coordinate, end: Coordinate, map: Map<Coordinate, Char>) {
val path = getPath(previous, start, end)
for (y in 0..path.maxOfOrNull { it.y }!!) {
for (x in 0..path.maxOfOrNull { it.x }!!) {
if (path.contains(Coordinate(x, y))) {
print("\u001B[35m*\u001B[0m")
} else if (map.containsKey(Coordinate(x, y))) {
print(map[Coordinate(x, y)])
} else {
print('#')
}
}
println()
}
println("Shortest path from $start to $end: $path")
}
class Coordinate(val x: Int, val y: Int) {
fun getNeighbours(c: Char): List<Coordinate> {
return when (c) {
'>' -> listOf(Coordinate(x + 1, y))
'<' -> listOf(Coordinate(x - 1, y))
'v' -> listOf(Coordinate(x, y + 1))
else -> listOf(
Coordinate(x - 1, y),
Coordinate(x, y - 1),
Coordinate(x, y + 1),
Coordinate(x + 1, y),
)
}
}
override fun toString(): String {
return "($x, $y)"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Coordinate
if (x != other.x) return false
if (y != other.y) return false
return true
}
override fun hashCode(): Int {
var result = x
result = 31 * result + y
return result
}
}
| 0 | Kotlin | 1 | 0 | 3de47ec31c5241947d38400d0a4d40c681c197be | 5,626 | advent-of-code_2023 | The Unlicense |
src/Day02.kt | kaeaton | 572,831,118 | false | {"Kotlin": 7766} | fun main() {
fun part1(input: List<String>): Int {
var score = 0
// val A = "Rock"
// val B = "Paper"
// val C = "Scissors"
// Rock = X for 1 point
// Paper = Y for 2 points
// Scissors = Z for 3 points
val responseValues = mapOf("X" to 1,
"Y" to 2,
"Z" to 3)
val winningCombos = mapOf("A Y" to 8,
"B Z" to 9,
"C X" to 7,
"A X" to 4,
"B Y" to 5,
"C Z" to 6)
input.forEach {
if(winningCombos.containsKey(it)) {
score += winningCombos[it]!!
} else {
val elementPlayed = it.split(" ")[1]
score += responseValues[elementPlayed]!!
}
}
return score
}
fun part2(input: List<String>): Int {
var score = 0
val actionValues = mapOf("X" to 0,
"Y" to 3,
"Z" to 6)
val rockValues = mapOf("X" to "scissors",
"Y" to "rock",
"Z" to "paper")
val paperValues = mapOf("X" to "rock",
"Y" to "paper",
"Z" to "scissors")
val scissorValues = mapOf("X" to "paper",
"Y" to "scissors",
"Z" to "rock")
val elements = mapOf("A" to rockValues,
"B" to paperValues,
"C" to scissorValues)
val elementValues = mapOf("rock" to 1,
"paper" to 2,
"scissors" to 3)
input.forEach {
val round = it.split(" ")
// Did they play rock paper or scissors?
val yourResponseLookUpTable = elements[round[0]]!!
// what were you supposed to play in response?
val yourResponse = yourResponseLookUpTable[round[1]]
score += elementValues[yourResponse]!!
score += actionValues[round[1]]!!
}
return score
}
val input = readInput("input_2")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | c2a92c68bd5822c72c1075f055fc2163762d6deb | 1,780 | AoC-2022 | Apache License 2.0 |
calendar/day02/Day2.kt | rocketraman | 573,845,375 | false | {"Kotlin": 45660} | package day02
import Day
import Lines
import day02.Move.*
class Day2 : Day() {
val inputMap = mapOf(
"A" to ROCK,
"X" to ROCK,
"B" to PAPER,
"Y" to PAPER,
"C" to SCISSORS,
"Z" to SCISSORS,
)
val part2InputMap = mapOf(
"X" to 0,
"Y" to 3,
"Z" to 6,
)
val scoreTable = mapOf(
ROCK to mapOf(
ROCK to 3,
PAPER to 0,
SCISSORS to 6,
),
PAPER to mapOf(
ROCK to 6,
PAPER to 3,
SCISSORS to 0,
),
SCISSORS to mapOf(
ROCK to 0,
PAPER to 6,
SCISSORS to 3,
),
)
val invertedScoreTable = mapOf(
ROCK to mapOf(
3 to ROCK,
0 to SCISSORS,
6 to PAPER,
),
PAPER to mapOf(
0 to ROCK,
3 to PAPER,
6 to SCISSORS,
),
SCISSORS to mapOf(
6 to ROCK,
0 to PAPER,
3 to SCISSORS,
),
)
fun shapeScore(self: Move): Int = self.value
fun gameScore(opponent: Move, self: Move): Int = scoreTable[self]!![opponent]!!
fun invertedGameMove(opponent: Move, self: Int): Move = invertedScoreTable[opponent]!![self]!!
override fun part1(input: Lines): Any {
val games = input.map { it.split(" ").map { inputMap[it]!! } }
val scores = games.map { gameScore(it[0], it[1]) + shapeScore(it[1]) }
return scores.sum()
}
override fun part2(input: Lines): Any {
val games = input.map {
val (opponent, desiredScore) = it.split(" ")
inputMap[opponent]!! to part2InputMap[desiredScore]!!
}
val scores = games.map {
val selfMove = invertedGameMove(it.first, it.second)
shapeScore(selfMove) + it.second
}
return scores.sum()
}
}
enum class Move(val opponent: Char, val self: Char, val value: Int) {
ROCK('A', 'X', 1),
PAPER('B', 'Y', 2),
SCISSORS('C', 'Z', 3),
}
| 0 | Kotlin | 0 | 0 | 6bcce7614776a081179dcded7c7a1dcb17b8d212 | 1,803 | adventofcode-2022 | Apache License 2.0 |
src/Day02.kt | bjornchaudron | 574,072,387 | false | {"Kotlin": 18699} | fun main() {
fun part1(input: List<String>): Int {
return input
.map { it.uppercase().split(" ") }
.map {
val opponent = parseChoice(it[0])
val player = parseChoice(it[1])
getScore(player) + getMatchBonus(player, opponent)
}.sum()
}
fun part2(input: List<String>): Int {
return input
.map { it.uppercase().split(" ") }
.map {
val opponent = parseChoice(it[0])
val result = parseMatchResult(it[1])
val player = getFixedChoice(opponent, result)
getScore(player) + getMatchBonus(player, opponent)
}.sum()
}
// test if implementation meets criteria from the description, like:
val day = "02"
val testInput = readLines("Day${day}_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readLines("Day$day")
println(part1(input))
println(part2(input))
}
fun parseChoice(choice: String) = when (choice) {
"X", "A" -> "rock"
"Y", "B" -> "paper"
"Z", "C" -> "scissors"
else -> error("Invalid choice!")
}
fun getScore(choice: String) = when (choice) {
"rock" -> 1
"paper" -> 2
"scissors" -> 3
else -> error("Invalid choice!")
}
fun getMatchBonus(playerChoice: String, opponentChoice: String) =
when {
playerChoice == "rock" && opponentChoice == "scissors" -> 6
playerChoice == "paper" && opponentChoice == "rock" -> 6
playerChoice == "scissors" && opponentChoice == "paper" -> 6
playerChoice == opponentChoice -> 3
else -> 0
}
fun parseMatchResult(result: String) =
when (result) {
"X" -> "loss"
"Y" -> "draw"
"Z" -> "win"
else -> error("Invalid choice!")
}
fun getFixedChoice(opponentChoice: String, result: String) =
when {
opponentChoice == "rock" && result == "win" -> "paper"
opponentChoice == "rock" && result == "loss" -> "scissors"
opponentChoice == "paper" && result == "win" -> "scissors"
opponentChoice == "paper" && result == "loss" -> "rock"
opponentChoice == "scissors" && result == "win" -> "rock"
opponentChoice == "scissors" && result == "loss" -> "paper"
else -> opponentChoice
} | 0 | Kotlin | 0 | 0 | f714364698966450eff7983fb3fda3a300cfdef8 | 2,352 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/Day03.kt | margaret-lin | 575,169,915 | false | {"Kotlin": 9536} | package main.kotlin// https://adventofcode.com/2022/day/3
private val input = readInput("day03_input")
private fun part1(input: List<String>): Int {
return input.map { it.take(it.length / 2) to it.substring(it.length / 2) }
.map { (it.first.toSet() intersect it.second.toSet()).single() }
.sumOf(Char::getPriority)
}
//private fun part2(main.kotlin.input: List<String>): Int {
// return main.kotlin.input.map(String::toSet)
// .chunked(3)
// .map { it.reduce(Set<Char>::main.kotlin.intersect).single() }
// .sumOf(Char::main.kotlin.getPriority) //same as sumOf { it.main.kotlin.getPriority() }
//}
// solution from Sebastian
private fun part2Sebastian(input: List<String>): Int {
val badges = input.chunked(3) {
val (a, b, c) = it
val badge = a.toSet() intersect b.toSet() intersect c.toSet()
badge.single()
}
return badges.sumOf { it.getPriority() }
}
//val Char.main.kotlin.getPriority
// get(): Int {
// return if (isLowerCase()) {
// this - 'a' + 1
// } else {
// this - 'A' + 27
// }
// }
// to have fewer manuel calls to `toSet()`
infix fun String.intersect(other: String) = toSet() intersect other.toSet()
private fun Char.getPriority() = (('a'..'z') + ('A'..'Z')).indexOf(this) + 1
fun main() {
println(part1(input))
println(part2Sebastian(input))
}
//var main.kotlin.input = main.kotlin.readInput("day03_test_input ").map {
// it.chunked(it.length / 2)
//}
// we need to split line in half -> modulo or remainder -> chuncked!
// we need to compare split array 1 and array 2, find the identical item(character)
// we need to convert the found char to ASCII
// we need to add all nums together | 0 | Kotlin | 0 | 0 | 7ef7606a04651ef88f7ca96f4407bae7e5de8a45 | 1,783 | advent-of-code-kotlin-22 | Apache License 2.0 |
src/Day25.kt | i-tatsenko | 575,595,840 | false | {"Kotlin": 90644} | import java.lang.IllegalArgumentException
val snafuDigits = listOf('=', '-', '0', '1', '2')
fun indexOffset(snufDigit: Char): Int {
return when (snufDigit) {
'2', '1', '0' -> snufDigit.digitToInt()
'-' -> -1
else -> -2
}
}
val sumSnafu = { left: String, right: String ->
var (first, second) = if (left.length > right.length) left to right else right to left
first = first.reversed()
second = second.reversed()
var result = ""
var correction = 0
first.forEachIndexed{digitIndex, f ->
val s = if (digitIndex >= second.length) '0' else second[digitIndex]
val resultingIndex = snafuDigits.indexOf(f) + indexOffset(s) + correction
correction = 0
if (resultingIndex >= 0 && resultingIndex < snafuDigits.size) {
result += snafuDigits[resultingIndex]
} else if (resultingIndex >= snafuDigits.size) {
correction = 1
result += snafuDigits[resultingIndex % snafuDigits.size]
} else {
correction = -1
result += snafuDigits[snafuDigits.size + resultingIndex]
}
}
if (correction == 1) {
result += "1"
} else if (correction == -1) throw IllegalArgumentException("quaquaqua")
result.reversed()
}
fun main() {
fun part1(input: List<String>): String {
return input.foldRight("0", sumSnafu)
}
fun part2(input: List<String>): String {
return "-1"
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day25_test")
println(part1(testInput))
check(part1(testInput) == "2=-1=0")
println(part2(testInput))
val input = readInput("Day25")
println(part1(input))
check(part1(input) == "20-==01-2-=1-2---1-0")
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 0a9b360a5fb8052565728e03a665656d1e68c687 | 1,822 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/days/Day6.kt | vovarova | 726,012,901 | false | {"Kotlin": 48551} | package days
import util.DayInput
class Day6 : Day("6") {
/*
Time: 7 15 30
Distance: 9 40 200
*/
class RecordTime(val time: Long, val record: Long) {
}
override fun partOne(dayInput: DayInput): Any {
val inputList = dayInput.inputList()
val time =
inputList[0].replace("Time:", "").split(" ").map { it.trim() }.filter { it.isNotEmpty() }
.map { it.toLong() }
val record = inputList[1].replace("Distance:", "").split(" ").map { it.trim() }.filter { it.isNotEmpty() }
.map { it.toLong() }
val recordTimeRecords = time.mapIndexed { index, timeItem ->
RecordTime(timeItem, record[index])
}
val map = recordTimeRecords.map {
//X^2-xT+R<0
val disriminant = it.time * it.time - 4 * it.record
val x1 = Math.ceil((it.time - Math.sqrt(disriminant.toDouble())) / 2).toInt()
val x2 = Math.floor((it.time + Math.sqrt(disriminant.toDouble())) / 2).toInt()
var result = x2 - x1 - 1
if (x1 * x1 - x1 * it.time + it.record < 0) result++
if (x2 * x2 - x2 * it.time + it.record < 0) result++
result
}
return map.reduce { acc, i -> acc * i }
}
fun raceResult(button: Long, time: Long): Long {
return button * (time - button)
}
override fun partTwo(dayInput: DayInput): Any {
val inputList = dayInput.inputList()
val time =
inputList[0].replace("Time:", "").split(" ").map { it.trim() }.filter { it.isNotEmpty() }.joinToString("")
.toLong()
val record = inputList[1].replace("Distance:", "").split(" ").map { it.trim() }.filter { it.isNotEmpty() }
.joinToString("").toLong()
val disriminant = time * time - 4 * record
val x1 = Math.ceil((time.toDouble() - Math.sqrt(disriminant.toDouble())) / 2.toDouble()).toLong()
val x2 = Math.floor((time.toDouble() + Math.sqrt(disriminant.toDouble())) / 2.toDouble()).toLong()
var result = x2 - x1 - 1
if (raceResult(x1, time) > record) result++
if (raceResult(x2, time) > record) result++
return result
}
}
fun main() {
Day6().run()
}
| 0 | Kotlin | 0 | 0 | 77df1de2a663def33b6f261c87238c17bbf0c1c3 | 2,269 | adventofcode_2023 | Creative Commons Zero v1.0 Universal |
src/Day02.kt | mzlnk | 573,124,510 | false | {"Kotlin": 14876} | fun main() {
fun part1(input: List<String>): Int {
val strategies = mapOf(
"A" to mapOf(
"X" to 4,
"Y" to 8,
"Z" to 3
),
"B" to mapOf(
"X" to 1,
"Y" to 5,
"Z" to 9
),
"C" to mapOf(
"X" to 7,
"Y" to 2,
"Z" to 6
)
)
var score = 0
for(line: String in input) {
val data = line.split(' ')
val opponent = data[0]
val you = data[1]
score += strategies[opponent]?.get(you) ?: 0
}
return score
}
fun part2(input: List<String>): Int {
val strategies = mapOf(
"A" to mapOf(
"X" to 3,
"Y" to 4,
"Z" to 8
),
"B" to mapOf(
"X" to 1,
"Y" to 5,
"Z" to 9
),
"C" to mapOf(
"X" to 2,
"Y" to 6,
"Z" to 7
)
)
var score = 0
for(line: String in input) {
val data = line.split(' ')
val opponent = data[0]
val you = data[1]
score += strategies[opponent]?.get(you) ?: 0
}
return score
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 3a8ec82e9a8b4640e33fdd801b1ef87a06fa5cd5 | 1,684 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/aoc23/Day06.kt | tom-power | 573,330,992 | false | {"Kotlin": 254717, "Shell": 1026} | package aoc23
import aoc23.Day06Domain.DesertIsland
import aoc23.Day06Parser.toDesertIsland
import aoc23.Day06Solution.part1Day06
import aoc23.Day06Solution.part2Day06
import common.Collections.product
import common.Year23
object Day06 : Year23 {
fun List<String>.part1(): Long = part1Day06()
fun List<String>.part2(): Long = part2Day06()
}
object Day06Solution {
fun List<String>.part1Day06(): Long =
with(toDesertIsland()) {
records.map(::numberOfWaysToBeat)
}.product()
fun List<String>.part2Day06(): Long =
with(toDesertIsland()) {
numberOfWaysToBeat(record)
}
}
object Day06Domain {
data class RaceRecord(val time: Long, val distance: Long)
data class Race(val buttonTime: Long, val duration: Long) {
fun distance() = (duration - buttonTime) * buttonTime
}
data class DesertIsland(
val records: List<RaceRecord>
) {
val record: RaceRecord =
RaceRecord(
time = records.joinToString("") { it.time.toString() }.toLong(),
distance = records.joinToString("") { it.distance.toString() }.toLong()
)
fun numberOfWaysToBeat(record: RaceRecord): Long =
(0..record.time).toList()
.filter { Race(it, record.time).distance() > record.distance }
.size
.toLong()
}
}
object Day06Parser {
fun List<String>.toDesertIsland(): DesertIsland {
fun String.toLongs(): List<Long> =
this
.split(":").last().split(" ")
.filterNot { it.isBlank() }.map { it.toLong() }
val times = this[0].toLongs()
val distances = this[1].toLongs()
return DesertIsland(
records = times.zip(distances).map { Day06Domain.RaceRecord(it.first, it.second.toLong()) }
)
}
}
| 0 | Kotlin | 0 | 0 | baccc7ff572540fc7d5551eaa59d6a1466a08f56 | 1,889 | aoc | Apache License 2.0 |
src/main/kotlin/g0001_0100/s0084_largest_rectangle_in_histogram/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0001_0100.s0084_largest_rectangle_in_histogram
// #Hard #Top_100_Liked_Questions #Top_Interview_Questions #Array #Stack #Monotonic_Stack
// #Big_O_Time_O(n_log_n)_Space_O(log_n) #2023_07_10_Time_476_ms_(90.79%)_Space_51.8_MB_(84.21%)
import kotlin.math.max
class Solution {
fun largestRectangleArea(heights: IntArray): Int {
return largestArea(heights, 0, heights.size)
}
private fun largestArea(a: IntArray, start: Int, limit: Int): Int {
if (a.isEmpty()) {
return 0
}
if (start == limit) {
return 0
}
if (limit - start == 1) {
return a[start]
}
if (limit - start == 2) {
val maxOfTwoBars = Math.max(a[start], a[start + 1])
val areaFromTwo = Math.min(a[start], a[start + 1]) * 2
return Math.max(maxOfTwoBars, areaFromTwo)
}
return if (checkIfSorted(a, start, limit)) {
var maxWhenSorted = 0
for (i in start until limit) {
if (a[i] * (limit - i) > maxWhenSorted) {
maxWhenSorted = a[i] * (limit - i)
}
}
maxWhenSorted
} else {
val minInd = findMinInArray(a, start, limit)
maxOfThreeNums(
largestArea(a, start, minInd),
a[minInd] * (limit - start),
largestArea(a, minInd + 1, limit)
)
}
}
private fun findMinInArray(a: IntArray, start: Int, limit: Int): Int {
var min = Int.MAX_VALUE
var minIndex = -1
for (index in start until limit) {
if (a[index] < min) {
min = a[index]
minIndex = index
}
}
return minIndex
}
private fun checkIfSorted(a: IntArray, start: Int, limit: Int): Boolean {
for (i in start + 1 until limit) {
if (a[i] < a[i - 1]) {
return false
}
}
return true
}
private fun maxOfThreeNums(a: Int, b: Int, c: Int): Int {
return max(max(a, b), c)
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,138 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/pl/jpodeszwik/aoc2023/Day02.kt | jpodeszwik | 729,812,099 | false | {"Kotlin": 55101} | package pl.jpodeszwik.aoc2023
import java.lang.Long.parseLong
private val totalAmounts = mapOf(
"red" to 12L,
"green" to 13L,
"blue" to 14L,
)
private fun parseGame(line: String): Pair<Long, Boolean> {
val parts = line.substring(5).split(": ")
val gameNumber = parseLong(parts[0])
val sets = parts[1].split("; ")
var allSetsMatch = true
for (set in sets) {
val setAmounts = mutableMapOf(
"red" to 0L,
"green" to 0L,
"blue" to 0L,
)
val colors = set.split(", ")
for (color in colors) {
val colorParts = color.split(" ")
setAmounts[colorParts[1]] = parseLong(colorParts[0])
}
val setMatch = setAmounts.all { e ->
totalAmounts[e.key]!! >= e.value
}
allSetsMatch = allSetsMatch && setMatch
}
return Pair(gameNumber, allSetsMatch)
}
private fun part1(lines: List<String>) {
var sum = 0L
for (line in lines) {
val (gameNumber, possible) = parseGame(line)
if (possible) {
sum += gameNumber
}
}
println(sum)
}
private fun parseGame2(line: String): Long {
val parts = line.substring(5).split(": ")
val sets = parts[1].split("; ")
val minimalAmounts = mutableMapOf(
"red" to 0L,
"green" to 0L,
"blue" to 0L,
)
for (set in sets) {
val colors = set.split(", ")
for (color in colors) {
val colorParts = color.split(" ")
val colorNumber = parseLong(colorParts[0])
val colorName = colorParts[1]
if (minimalAmounts[colorName]!! < colorNumber) {
minimalAmounts[colorName] = colorNumber
}
}
}
var power = 1L
for (amount in minimalAmounts) {
power *= amount.value
}
return power
}
private fun part2(lines: List<String>) {
var sum = 0L
for (line in lines) {
val power = parseGame2(line)
sum += power
}
println(sum)
}
fun main() {
val lines = loadFile("/aoc2023/input2")
part1(lines)
part2(lines)
}
| 0 | Kotlin | 0 | 0 | 2b90aa48cafa884fc3e85a1baf7eb2bd5b131a63 | 2,134 | advent-of-code | MIT License |
aoc_2023/src/main/kotlin/problems/day18/LavaTrench.kt | Cavitedev | 725,682,393 | false | {"Kotlin": 228779} | package problems.day18
open class LavaTrench(lines: List<String>) {
val digList: List<DigData> = lines.map { line ->
val (dir, amount) = line.split(" ")
DigData(
when (dir) {
"R" -> {
EastTrenchDir.getInstance()
}
"D" -> {
SouthTrenchDir.getInstance()
}
"L" -> {
WestTrenchDir.getInstance()
}
"U" -> {
NorthTrenchDir.getInstance()
}
else -> {
NorthTrenchDir.getInstance()
}
},
amount.toInt(),
)
}
fun filledCellsCount(): Long {
val enhancedDigData = enhancedDigData()
var total = enhancedDigData.fold(0L) { acc, dig ->
acc + dig.digData.amount
}
for (dig in enhancedDigData) {
if (dig.digData.direction.isHorizontal()) {
val i = dig.i + 1
val firstRange: IntRange = dig.toHorizontalRange()
val adjacentPosJ = dig.digData.direction.nextPos(dig.i, dig.j).second
val wallsToLeft = getWallsToLeft(enhancedDigData, i, adjacentPosJ)
// Out horizontal
if (wallsToLeft.size % 2 == 0) {
continue
}
total += totalRange(firstRange, i, enhancedDigData)
}
}
return total
}
fun getWallsToLeft(
enhancedDigData: List<EnhancedDigData>,
i: Int,
j: Int
): List<EnhancedDigData> {
val wallsLeft = enhancedDigData.filter { it.isInRow(i) && it.j < j }
// return wallsLeft
return wallsLeft.filter {
val endPos = it.endPos()
!wallsLeft.any { it.i == endPos.first && it.j == endPos.second }
}
}
private fun totalRange(
checkRange: IntRange,
i: Int,
enhancedDigData: List<EnhancedDigData>,
): Long {
var total = 0L
val intersectDirs = enhancedDigData.filter { it.isInRow(i) }
val fallRanges: MutableList<IntRange> = mutableListOf(checkRange)
val nextI =
enhancedDigData.filter { it.digData.direction.isHorizontal() && it.i > i }.minOfOrNull { it.i } ?: return 0L
for (intersectDir in intersectDirs) {
val intersectRange = intersectDir.toHorizontalRange()
val overlappedRanges =
fallRanges.filter {
(intersectRange.contains(it.first) || intersectRange.contains(it.last)) ||
(intersectRange.first > it.first && intersectRange.last < it.last)
}
for (overlapRange in overlappedRanges) {
fallRanges.remove(overlapRange)
// Left
if (intersectRange.first > overlapRange.first) {
val nextRange = overlapRange.first..intersectRange.first - 1
fallRanges.add(nextRange)
}
// Right
if (intersectRange.last < overlapRange.last) {
val nextRange = intersectRange.last + 1..overlapRange.last
fallRanges.add(nextRange)
}
}
}
total += fallRanges.sumOf {
totalRange(it, nextI, enhancedDigData)
}
val spacesInRow = fallRanges.fold(0L) { acc, range ->
acc + range.last - range.first + 1
}
total += spacesInRow * (nextI - i).toLong()
return total
}
fun printInput() {
val enhancedData = enhancedDigData()
val minI = enhancedData.minOf { it.i }
val minJ = enhancedData.minOf { it.j }
val maxI = enhancedData.maxOf { it.i }
val maxJ = enhancedData.maxOf { it.j }
for (i in minI..maxI) {
val chars = mutableListOf<Char>()
for (j in minJ..maxJ) {
val exists = enhancedData.any { it.isInCell(i, j) }
val addChar = if (exists) '#' else '.'
chars.add(addChar)
}
println(chars.joinToString(""))
}
}
fun enhancedDigData(): List<EnhancedDigData> {
val returnData = mutableListOf<EnhancedDigData>()
var i = 0
var j = 0
for (dig in digList) {
returnData.add(EnhancedDigData(i, j, dig))
val (i2, j2) = dig.direction.nextPos(i, j)
var di = i2 - i
var dj = j2 - j
di *= dig.amount
dj *= dig.amount
i += di
j += dj
}
return returnData
}
} | 0 | Kotlin | 0 | 1 | aa7af2d5aa0eb30df4563c513956ed41f18791d5 | 4,778 | advent-of-code-2023 | MIT License |
Algo_Ds_Notes-master/Algo_Ds_Notes-master/Circle_Sort/Circle_Sort.kts | rajatenzyme | 325,100,742 | false | {"C++": 709855, "Java": 559443, "Python": 397216, "C": 381274, "Jupyter Notebook": 127469, "Go": 123745, "Dart": 118962, "JavaScript": 109884, "C#": 109817, "Ruby": 86344, "PHP": 63402, "Kotlin": 52237, "TypeScript": 21623, "Rust": 20123, "CoffeeScript": 13585, "Julia": 2385, "Shell": 506, "Erlang": 385, "Scala": 310, "Clojure": 189} | fun<T: Comparable<T>> circleSort(array: Array<T>, lo: Int, hi: Int, nSwaps: Int): Int {
if (lo == hi) return nSwaps
fun swap(array: Array<T>, i: Int, j: Int) {
val temp = array[i]
array[i] = array[j]
array[j] = temp
}
var high = hi
var low = lo
val mid = (hi - lo) / 2
var swaps = nSwaps
while (low < high) {
if (array[low] > array[high]) {
swap(array, low, high)
swaps++
}
low++
high--
}
if (low == high)
if (array[low] > array[high + 1]) {
swap(array, low, high + 1)
swaps++
}
swaps = circleSort(array, lo, lo + mid, swaps)
swaps = circleSort(array, lo + mid + 1, hi, swaps)
return swaps
}
fun main(args: Array<String>) {
// -- ExampleArray1 --
val array = arrayOf(6, 7, 8, 9, 2, 5, 3, 4, 1)
println("Unsorted Array: ${array.asList()}")
while (circleSort(array, 0, array.size - 1, 0) != 0) ;
println("Sorted Array : ${array.asList()}") //Sorted Array
println()
// -- ExampleArray2 --
val array2 = arrayOf("the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog")
println("Unsorted Array : ${array2.asList()}")
while (circleSort(array2, 0, array2.size - 1, 0) != 0) ;
println("Sorted Array : ${array2.asList()}") //Sorted Array
}
//output
Unsorted Array: [6, 7, 8, 9, 2, 5, 3, 4, 1]
Sorted Array : [1, 2, 3, 4, 5, 6, 7, 8, 9]
Unsorted Array : [the, quick, brown, fox, jumps, over, the, lazy, dog]
Sorted Array : [brown, dog, fox, jumps, lazy, over, quick, the, the]
| 0 | C++ | 0 | 0 | 65a0570153b7e3393d78352e78fb2111223049f3 | 1,630 | Coding-Journey | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.