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/year2022/day03/Day03.kt | tiagoabrito | 573,609,974 | false | {"Kotlin": 73752} | package year2022.day03
import readInput
fun main() {
fun toValue(it: MutableList<Char>): Int {
return it.distinct().sumOf { if (it > 'a') it - 'a' + 1 else it - 'A' + 27 }
}
fun repeated(a: Pair<CharSequence, CharSequence>): MutableList<Char> {
val myList = a.first.toMutableList()
myList.retainAll(a.second.toList())
return myList
}
fun part1(input: List<String>): Int {
return input.map { it.substring(0, it.length / 2 ) to it.substring(it.length / 2) }.map { repeated(it) }.sumOf { toValue(it) }
}
fun part2(input: List<String>):Int {
return input.chunked(3).map {
repeated(repeated(it[0] to it[1]).joinToString() to it[2])
}.sumOf { toValue(it) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1f9becde3cbf5dcb345659a23cf9ff52718bbaf9 | 1,009 | adventOfCode | Apache License 2.0 |
kotlin/src/main/kotlin/days/Day2.kt | ochronus | 572,132,995 | false | {"Kotlin": 9226, "C#": 3907, "Python": 2279} | package days
class Day2 : Day(2) {
enum class Shape(
val sign: Char,
val signPart1: Char,
val score: Int
) {
ROCK('A', 'X', 1),
PAPER('B', 'Y', 2),
SCISSORS('C', 'Z', 3)
}
enum class Result(
val sign: Char,
val score: Int
) {
LOSE('X', 0),
DRAW('Y', 3),
WIN('Z', 6)
}
fun decideResult(line: String): Int {
val shapes = line
.split(' ')
.map { c ->
Shape.values().first { c[0] == it.sign || c[0] == it.signPart1 }
}
val resultScore = when (Math.floorMod(shapes.first().score - shapes.last().score, 3)) {
2 -> 6
0 -> 3
1 -> 0
else -> -1
}
return resultScore
}
override fun partOne(): Any {
return inputList.sumOf {
decideResult(it) + Shape.values().first { shape -> shape.signPart1 == it.last() }.score
}
}
fun decideShape(line: String): Shape {
val shapeOther = Shape.values().first { it.sign == line.first() }
val result = Result.values().first { it.sign == line.last() }
var score = shapeOther.score + (result.score / 3 - 1)
score = when (score) {
0 -> 3
4 -> 1
else -> score
}
return Shape.values().first { it.score == score }
}
override fun partTwo(): Any {
return inputList.sumOf { line ->
Result.values().first { it.sign == line.last() }.score + decideShape(line).score
}
}
}
| 0 | Kotlin | 0 | 1 | 93c5ef0afed730a2c0da748f2bf129e12f7f915c | 1,608 | advent-of-code-2022 | Creative Commons Zero v1.0 Universal |
src/day02/Day02.kt | mahan-ym | 572,901,965 | false | {"Kotlin": 4240} | package day02
import readInput
fun main() {
// A -> Rock, B -> Paper, C -> Scissors
// X -> Rock, Y -> Paper, Z -> Scissors
// you get 6 scores when you win, 3 scores when you draw and Rock = 1, Paper = 2, Scissors = 3 scores
// second part: X -> need to lose, Y -> need to draw, Z -> need to win
fun getFullScore(input: List<String>):Int {
var score = 0
input.forEach { record ->
score += record.getCombinationScore()
score += record.split(" ")[1].getPlayedElementScore()
}
return score
}
fun getFullScorePhase2(input: List<String>):Int {
var score = 0
input.forEach { record ->
score += record.split(" ")[1].getScorePhase2()
score += getPlayedElementScorePhase2(record.split(" ")[0], record.split(" ")[1])
}
return score
}
val testInput = readInput("Day02_test")
check(getFullScore(testInput) == 15)
check(getFullScorePhase2(testInput) == 12)
val input = readInput("Day02")
println(getFullScore(input))
println(getFullScorePhase2(input))
}
fun String.getPlayedElementScore(): Int =
if (this == "X") 1
else if(this == "Y") 2
else 3
fun String.getCombinationScore(): Int =
if (this == "A Y" || this == "B Z" || this == "C X") 6
else if(this == "A X" || this == "B Y" || this == "C Z") 3
else 0
fun String.getScorePhase2(): Int =
if (this == "Z") 6
else if(this == "Y") 3
else 0
fun getPlayedElementScorePhase2(played: String, status: String): Int {
return when(status) {
"X" -> {
lose(played)
}
"Y" -> {
draw(played)
}
else -> {
win(played)
}
}
}
fun lose(played: String): Int {
return when(played) {
"A" -> 3
"B" -> 1
else -> 2
}
}
fun win(played: String): Int {
return when(played) {
"A" -> 2
"B" -> 3
else -> 1
}
}
fun draw(played: String): Int {
return when(played) {
"A" -> 1
"B" -> 2
else -> 3
}
}
| 0 | Kotlin | 0 | 0 | d09acc419480bcc025d482afae9da9438b87e4eb | 2,121 | AOC-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/Day16.kt | i-redbyte | 433,743,675 | false | {"Kotlin": 49932} |
fun main() {
val data = readInputFile("day16")
fun part1(): Int {
val (packetTree, _) = Packet.parse(data.first().hexToBinary(), 0)
fun addUpVersions(packet: Packet): Int =
when (packet) {
is Packet.Literal -> packet.version
is Packet.Operator -> packet.version + packet.subPackets.sumOf { addUpVersions(it) }
}
return addUpVersions(packetTree)
}
fun part2(): Long {
return Packet.parse(data.first().hexToBinary(), 0).first.eval()
}
println("Result part1: ${part1()}")
println("Result part2: ${part2()}")
}
fun String.hexToBinary(): String {
val result = StringBuilder()
forEach {
result.append(
when (it) {
'0' -> "0000"
'1' -> "0001"
'2' -> "0010"
'3' -> "0011"
'4' -> "0100"
'5' -> "0101"
'6' -> "0110"
'7' -> "0111"
'8' -> "1000"
'9' -> "1001"
'A' -> "1010"
'B' -> "1011"
'C' -> "1100"
'D' -> "1101"
'E' -> "1110"
'F' -> "1111"
else -> ""
}
)
}
return result.toString()
}
sealed class Packet(val version: Int, val typeId: Int) {
abstract fun eval(): Long
class Literal(version: Int, val value: Long) : Packet(version, 4) {
override fun eval(): Long = value
companion object {
fun parse(source: String, version: Int, offset: Int): Pair<Literal, Int> {
val numberBytes = StringBuilder()
var soFar = offset
do {
val first = source[soFar]
soFar++
numberBytes.append(source.substring(soFar, soFar + 4))
soFar += 4
} while (first != '0')
val value = numberBytes.toString().toLong(2)
return Literal(version, value) to soFar
}
}
}
class Operator(version: Int, typeId: Int, val subPackets: List<Packet>) : Packet(version, typeId) {
override fun eval(): Long {
return when (typeId) {
0 -> subPackets.sumOf { it.eval() }
1 -> subPackets.fold(1.toLong()) { acc, packet -> acc * packet.eval() }
2 -> subPackets.minOf { it.eval() }
3 -> subPackets.maxOf { it.eval() }
5 -> {
if (subPackets[0].eval() > subPackets[1].eval()) 1.toLong() else 0.toLong()
}
6 -> {
if (subPackets[0].eval() < subPackets[1].eval()) 1.toLong() else 0.toLong()
}
7 -> {
if (subPackets[0].eval() == subPackets[1].eval()) 1.toLong() else 0.toLong()
}
else -> throw IllegalArgumentException("bad type")
}
}
companion object {
fun parse(source: String, version: Int, typeId: Int, offset: Int): Pair<Operator, Int> {
var soFar = offset
val lengthType = source[soFar].digitToInt(2)
soFar++
return when (lengthType) {
0 -> {
val totalLengthBits = source.substring(soFar, soFar + 15).toInt(2)
soFar += 15
val subPacketStart = soFar
val subpackets = mutableListOf<Packet>()
while (soFar < subPacketStart + totalLengthBits) {
val (subPacket, newOffset) = Packet.parse(source, soFar)
soFar = newOffset
subpackets.add(subPacket)
}
Operator(version, typeId, subpackets) to soFar
}
1 -> {
val numSubpackets = source.substring(soFar, soFar + 11).toInt(2)
soFar += 11
val subpackets = mutableListOf<Packet>()
repeat(numSubpackets) {
val (subPacket, newOffset) = Packet.parse(source, soFar)
soFar = newOffset
subpackets.add(subPacket)
}
Operator(version, typeId, subpackets) to soFar
}
else -> throw IllegalArgumentException("Inconceivable!")
}
}
}
}
companion object {
fun parse(source: String, offset: Int): Pair<Packet, Int> {
var soFar = offset
val versionBits = source.substring(soFar, soFar + 3)
soFar += 3
val typeBits = source.substring(soFar, soFar + 3)
soFar += 3
val version = versionBits.toInt(2)
val type = typeBits.toInt(2)
return when (type) {
4 -> Literal.parse(source, version, soFar)
else -> Operator.parse(source, version, type, soFar)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 6d4f19df3b7cb1906052b80a4058fa394a12740f | 5,252 | AOC2021 | Apache License 2.0 |
aoc21/day_05/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
import kotlin.math.abs
data class Pos(val x: Int, val y: Int)
data class Line(val from: Pos, val to: Pos)
fun parsePos(str: String) = str.split(",").let { Pos(it[0].toInt(), it[1].toInt()) }
fun parseLine(str: String): Line =
str.split("->").let { Line(parsePos(it[0].trim()), parsePos(it[1].trim())) }
fun range(from: Int, to: Int) = if (from < to) (from..to) else (from downTo to)
fun main() {
val lines = File("input").readLines().map { parseLine(it) }
val points = mutableMapOf<Pos, Int>()
for (line in lines) {
if (line.from.x == line.to.x) {
for (y in range(line.from.y, line.to.y))
points.merge(Pos(line.from.x, y), 1, Int::plus)
} else if (line.from.y == line.to.y) {
for (x in range(line.from.x, line.to.x))
points.merge(Pos(x, line.from.y), 1, Int::plus)
}
}
val first = points.filter { (_, n) -> n > 1 }.count()
println("First: $first")
for (line in lines) {
if (abs(line.from.x - line.to.x) == abs(line.from.y - line.to.y)) {
for ((x, y) in range(line.from.x, line.to.x).zip(range(line.from.y, line.to.y)))
points.merge(Pos(x, y), 1, Int::plus)
}
}
val second = points.filter { (_, n) -> n > 1 }.count()
println("Second: $second")
}
| 0 | Rust | 1 | 0 | f47ef85393d395710ce113708117fd33082bab30 | 1,341 | advent-of-code | MIT License |
src/Day20.kt | mrugacz95 | 572,881,300 | false | {"Kotlin": 102751} | fun main() {
fun List<String>.parse(): List<Int> {
return map { it.toInt() }
}
fun <T> List<T>.circulateIndex(index: Int): Int {
return ((index + 10 * (size - 1)) % (size - 1))
}
fun <T> List<T>.circulateIndex(index: Long): Int {
return (((index % (size - 1)).toInt()) + 10 * (size - 1)) % (size - 1)
}
fun mixNumbers(list: List<Int>, debug: Boolean = false): List<Int> {
val numbers = list.toMutableList()
val indices = numbers.indices.toMutableList()
for (i in 0 until numbers.size) {
val indexInIndices = indices.indexOf(i)
val number = numbers[indices[indexInIndices]]
var newIndex = indexInIndices + number
newIndex = numbers.circulateIndex(newIndex)
indices.removeAt(indexInIndices)
indices.add(newIndex, i)
if (debug) println("$number moves")
if (debug) println(indices.joinToString { numbers[it].toString() })
}
return indices.map { numbers[it] }
}
fun mixNumbersManyTimes(list: List<Long>, times: Int = 10, debug: Boolean = false): List<Long> {
val numbers = list.toMutableList()
val indices = numbers.indices.toMutableList()
for (round in 1..times) {
for (i in 0 until numbers.size) {
val indexInIndices = indices.indexOf(i)
val number = numbers[indices[indexInIndices]]
val newIndex = indexInIndices + number
val newIndexCirculated = numbers.circulateIndex(newIndex)
indices.removeAt(indexInIndices)
indices.add(newIndexCirculated, i)
}
if (debug) println("after $round round of mixing")
if (debug) println(indices.joinToString { numbers[it].toString() })
}
return indices.map { numbers[it] }
}
fun part1(input: List<String>, debug: Boolean = false): Int {
val mixed = mixNumbers(input.parse(), debug)
val zeroIndex = mixed.indexOf(0)
val numbers = (1000..3000 step 1000).map {
mixed[(it + zeroIndex) % mixed.size]
}
return numbers.reduce { acc, it -> acc + it }
}
fun List<Long>.getGroveCoordinates(): Long {
val zeroIndex = indexOf(0)
val numbers = (1000..3000 step 1000).map {
this[(it + zeroIndex) % size]
}
return numbers.reduce { acc, it -> acc + it }
}
fun part2(input: List<String>, debug: Boolean = false): Long {
return input.parse()
.map { it.toLong() * 811589153L }
.let { mixNumbersManyTimes(it, debug = debug) }.getGroveCoordinates()
}
val testInput = readInput("Day20_test")
val input = readInput("Day20")
assert(part1(testInput, debug = true), 3)
println(part1(input))
assert(part2(testInput, debug = true), 1623178306)
println(part2(input))
}
// Time: 01:12 | 0 | Kotlin | 0 | 0 | 29aa4f978f6507b182cb6697a0a2896292c83584 | 2,955 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2022/2022-14.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2022
import com.github.ferinagy.adventOfCode.Coord2D
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputLines
import kotlin.math.max
import kotlin.math.min
fun main() {
val input = readInputLines(2022, "14-input")
val testInput1 = readInputLines(2022, "14-test1")
println("Part1:")
part1(testInput1).println()
part1(input).println()
println()
println("Part2:")
part2(testInput1).println()
part2(input).println()
}
private fun part1(input: List<String>): Int {
val (max, occupied) = parse(input)
var result = 0
while (true) {
val next = simulateFall(Coord2D(500, 0), occupied, max, false)
if (next != null) {
result++
occupied += next
} else {
return result
}
}
}
private fun part2(input: List<String>): Int {
val (max, occupied) = parse(input)
var result = 0
while (true) {
val next = simulateFall(Coord2D(500, 0), occupied, max + 2, true)!!
result++
if (next != Coord2D(500, 0)) {
occupied += next
} else {
return result
}
}
}
private fun parse(input: List<String>): Pair<Int, MutableSet<Coord2D>> {
val paths = input.map { line ->
line.split(" -> ").map { pair ->
val (a, b) = pair.split(',').map { it.toInt() }
Coord2D(a, b)
}
}
val max = paths.maxOf { path -> path.maxOf { it.y } }
val occupied = paths.flatMap { path ->
path.windowed(2).flatMap { (a, b) ->
buildSet {
for (x in min(a.x, b.x)..max(a.x, b.x)) {
for (y in min(a.y, b.y)..max(a.y, b.y)) {
this += Coord2D(x, y)
}
}
}
}.toSet()
}.toMutableSet()
return Pair(max, occupied)
}
private fun simulateFall(current: Coord2D, occupied: Set<Coord2D>, maxY: Int, floor: Boolean = false): Coord2D? {
if (!floor && maxY < current.y) return null
fun isOnFloor(y: Int) = if (!floor) false else y == maxY
val down = current.copy(y = current.y + 1)
if (down !in occupied && !isOnFloor(down.y)) return simulateFall(down, occupied, maxY, floor)
val downLeft = current.copy(x = current.x - 1, y = current.y + 1)
if (downLeft !in occupied && !isOnFloor(downLeft.y)) return simulateFall(downLeft, occupied, maxY, floor)
val downRight = current.copy(x = current.x + 1, y = current.y + 1)
if (downRight !in occupied && !isOnFloor(downRight.y)) return simulateFall(downRight, occupied, maxY, floor)
return current
}
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 2,700 | advent-of-code | MIT License |
src/main/kotlin/aoc/Day02.kt | fluxxion82 | 573,716,300 | false | {"Kotlin": 39632} | package aoc
import aoc.Result.Companion.getResultFromCode
import aoc.State.Companion.getStateFromCode
import java.io.File
enum class State(val codeOne: String, val codeTwo: String) {
Rock("A", "X"),
Paper("B", "Y"),
Scissors("C", "Z");
companion object {
fun getStateFromCode(code: String): State? =
values().find {
it.codeOne == code || it.codeTwo == code
}
}
}
enum class Result(val code: String) {
Winner("Z"),
Loser("X"),
Draw("Y");
companion object {
fun getResultFromCode(code: String): Result? =
values().find { it.code == code }
}
}
fun playerTwoResult(playerOne: State, playerTwo: State): Result {
return when (playerTwo) {
State.Rock -> when (playerOne) {
State.Paper -> Result.Loser
State.Scissors -> Result.Winner
State.Rock -> Result.Draw
}
State.Paper -> when (playerOne) {
State.Paper -> Result.Draw
State.Scissors -> Result.Loser
State.Rock -> Result.Winner
}
State.Scissors -> when (playerOne) {
State.Paper -> Result.Winner
State.Scissors -> Result.Draw
State.Rock -> Result.Loser
}
}
}
fun getPointsForRound(result: Result): Int =
when (result) {
Result.Winner -> 6
Result.Loser -> 0
Result.Draw -> 3
}
fun getPointsForChoice(choice: State): Int =
when (choice) {
State.Paper -> 2
State.Scissors -> 3
State.Rock -> 1
}
fun playerTwoPlayFromResult(playerOne: State, playerTwo: Result): State {
return when (playerTwo) {
Result.Winner -> when (playerOne) {
State.Paper -> State.Scissors
State.Scissors -> State.Rock
State.Rock -> State.Paper
}
Result.Loser -> when (playerOne) {
State.Paper -> State.Rock
State.Scissors -> State.Paper
State.Rock -> State.Scissors
}
Result.Draw -> when (playerOne) {
State.Paper -> State.Paper
State.Scissors -> State.Scissors
State.Rock -> State.Rock
}
}
}
fun main() {
val testInput = File("src/Day02_test.txt").readText()
val input = File("src/Day02.txt").readText()
fun part1(input: String): Int =
input.split("\n").sumOf {
val round = it.split(" ")
val myPlay = getStateFromCode(round.last())!!
val opponentPlay = getStateFromCode(round.first())!!
val meResult = playerTwoResult(opponentPlay, myPlay)
getPointsForRound(meResult)+ getPointsForChoice(myPlay)
}
fun part2(input: String): Int =
input.split("\n").sumOf {
val round = it.split(" ")
val opponentPlay = getStateFromCode(round.first())!!
val meResult = getResultFromCode(round.last())!!
val myPlay = playerTwoPlayFromResult(opponentPlay, meResult)
getPointsForRound(meResult) + getPointsForChoice(myPlay)
}
println("part one test: ${part1(testInput)}")
println("part one: ${part1(input)}")
println("part two test: ${part2(testInput)}")
println("part two: ${part2(input)}")
} | 0 | Kotlin | 0 | 0 | 3920d2c3adfa83c1549a9137ffea477a9734a467 | 3,288 | advent-of-code-kotlin-22 | Apache License 2.0 |
2021/src/day18/Day18.kt | Bridouille | 433,940,923 | false | {"Kotlin": 171124, "Go": 37047} | package day18
import readInput
import java.util.*
fun List<String>.toListOfTree() : List<Node> = this.map { it.toTree()!! }
fun String.toTree(parent: Node? = null) : Node? {
if (all { it.isDigit() }) return Node(parent = parent, value = toInt())
var delimitersCount = 0
val subStr = this.drop(1).dropLast(1) // Removes the outermost '[' and ']'
for (idx in subStr.indices) {
if (subStr[idx] == '[') delimitersCount++
if (subStr[idx] == ']') delimitersCount--
if (subStr[idx] == ',' && delimitersCount == 0) {
return Node(parent = parent).apply {
left = subStr.take(idx).toTree(this)
right = subStr.drop(idx + 1).toTree(this)
}
}
}
return null
}
data class Node(
val id: String = UUID.randomUUID().toString(),
var left: Node? = null,
var right: Node? = null,
var parent: Node? = null,
var value: Int? = null
) {
override fun toString() : String {
if (left == null && right == null) return "$value"
return "[${left},${right}]"
}
override fun equals(other: Any?) = other is Node && id == other.id
fun add(toAdd: Node): Node {
val newRoot = Node(right = toAdd, left = this)
parent = newRoot
toAdd.parent = newRoot
return newRoot
}
// leaf => left == null && right == null
// return a list of leafs with their depth
private fun getLeafs(depth: Int = 0) : List<Pair<Int, Node>> {
if (left?.value != null && right?.value != null) {
return listOf(Pair(depth, this))
}
val leftLeaf = left?.getLeafs(depth + 1) ?: emptyList()
val rightLeaf = right?.getLeafs(depth + 1) ?: emptyList()
return (leftLeaf + rightLeaf).sortedByDescending { it.first }
}
private fun getFirstParentRight() : Node? {
var child: Node? = this
var root: Node? = this.parent
while (root?.parent != null && (root.right == null || root.right == child)) {
child = root
root = root.parent
}
if (root?.parent == null && root?.right == child) {
return null
}
return root?.right?.getLeftmostNode()
}
private fun getFirstParentLeft() : Node? {
var child: Node? = this
var root: Node? = this.parent
while (root?.parent != null && (root.left == null || root.left == child)) {
child = root
root = root.parent
}
if (root?.parent == null && root?.left == child) {
return null
}
return root?.left?.getRightmostNode()
}
private fun getRightmostNode(): Node = right?.let { it.getRightmostNode() } ?: this
private fun getLeftmostNode(): Node = left?.let { it.getLeftmostNode() } ?: this
// explode the tree, return true if an explode happened
private fun explodeAll() : Boolean {
val deepLeafs = getLeafs().filter { it.first >= 4 } // only get the leafs that are deeper than 4
if (deepLeafs.isEmpty()) return false
for (deep in deepLeafs) {
val leaf = deep.second
val leftValue = (leaf.left?.value ?: 0)
val rightValue = (leaf.right?.value ?: 0)
val parentLeft = leaf.getFirstParentLeft()
val parentRight = leaf.getFirstParentRight()
if (parentLeft != null) {
parentLeft.value = (parentLeft.value ?: 0) + leftValue
}
if (parentRight != null) {
parentRight.value = (parentRight.value ?: 0) + rightValue
}
leaf.value = 0
leaf.left = null
leaf.right = null
}
return true
}
// split the tree, left-most node first, return true if a split has happened
private fun split() : Boolean {
value?.let {
if (it >= 10) {
val leftValue = it / 2
val rightValue = it / 2 + it % 2
this.value = null
this.left = Node(value = leftValue, parent = this)
this.right = Node(value = rightValue, parent = this)
return true
}
}
val leftSplit = left?.let { it.split() } ?: false
// one action at a time, return if we already did a split on the left side
val rightSplit = if (!leftSplit) {
right?.let { it.split() } ?: false
} else false
return leftSplit || rightSplit
}
fun reduce() {
do {
explodeAll()
} while (split())
}
fun getMagnitude(): Long {
if (left == null && right == null) {
return value?.toLong()!!
}
return (left?.getMagnitude() ?: 0) * 3 + (right?.getMagnitude() ?: 0) * 2
}
}
fun part1(lines: List<String>): Long {
val trees = lines.toListOfTree()
var firstTree = trees.first()
for (tree in trees.drop(1)) {
firstTree = firstTree.add(tree)
firstTree.reduce()
}
println(firstTree)
return firstTree.getMagnitude()
}
fun part2(lines: List<String>): Long {
val trees = lines.toListOfTree().toMutableList()
var maxMagnitude = 0L
for (i in 0 until trees.size) {
for (j in i+1 until trees.size) {
if (i == j) continue // Do not add with yourself
val newTree = trees[i].add(trees[j])
newTree.reduce()
maxMagnitude = maxOf(newTree.getMagnitude(), maxMagnitude)
trees[i] = lines.toListOfTree()[i]
trees[j] = lines.toListOfTree()[j]
}
}
return maxMagnitude
}
fun main() {
val testInput = readInput("day18/test")
println("part1(testInput) => " + part1(testInput))
println("part2(testInput) => " + part2(testInput))
val input = readInput("day18/input")
println("part1(input) => " + part1(input))
println("part2(input) => " + part2(input))
}
| 0 | Kotlin | 0 | 2 | 8ccdcce24cecca6e1d90c500423607d411c9fee2 | 5,968 | advent-of-code | Apache License 2.0 |
src/day22/Day22.kt | andreas-eberle | 573,039,929 | false | {"Kotlin": 90908} | package day22
import Coordinate
import readInput
const val day = "22"
sealed interface Command
data class StepCommand(val steps: Int) : Command
data class TurnCommand(val turn: Char) : Command
data class Transform(val originDirection: Int, val origin: Coordinate, val target: Coordinate)
fun transforms(direction: Int, t1: Pair<Coordinate, Coordinate>, t2: Pair<Coordinate, Coordinate>): List<Transform> {
val allOrigins = t1.first lineTo t2.first
val allTargets = t1.second lineTo t2.second
val allOriginsWithTargets = allOrigins.zip(allTargets)
return allOriginsWithTargets.map { (origin, target) -> Transform(direction, origin, target) }
}
fun main() {
fun calculatePart1Score(input: List<String>): Int {
val (commands, board) = input.parseBoardAndCommands()
val (position, direction) = board.walkCommands(commands) { direction, position ->
var nextPos = position
while (this[nextPos] == ' ') {
nextPos = nextPos.goInDirection(direction).wrap(width, height)
}
nextPos
}
return 1000 * (position.y + 1) + 4 * (position.x + 1) + direction
}
fun calculatePart2Score(input: List<String>): Int {
val (commands, board) = input.parseBoardAndCommands()
val blockSize = board.width / 4
// 0 >
// 1 v
// 2 <
// 3 ^
val transforms = listOf(
transforms( // block 2 -> 4
2,
Coordinate(-1, blockSize) to Coordinate(3 * blockSize - 1, blockSize),
Coordinate(-1, 2 * blockSize - 1) to Coordinate(3 * blockSize - 1, 2 * blockSize - 1)
),
transforms( // block 4 -> 2
0,
Coordinate(3 * blockSize, blockSize) to Coordinate(0, blockSize),
Coordinate(3 * blockSize, 2 * blockSize - 1) to Coordinate(0, 2 * blockSize - 1)
),
transforms( // block 2 -> 1
3,
Coordinate(0, blockSize - 1) to Coordinate(3 * blockSize - 1, 0),
Coordinate(blockSize - 1, blockSize - 1) to Coordinate(2 * blockSize, 0)
),
transforms( // block 1 -> 2
2,
Coordinate(2 * blockSize, 0) to Coordinate(blockSize, blockSize),
Coordinate(2 * blockSize, blockSize - 1) to Coordinate(2 * blockSize - 1, blockSize)
),
transforms( // block 2
3,
Coordinate(blockSize, blockSize - 1) to Coordinate(2 * blockSize, 0),
Coordinate(2 * blockSize - 1, blockSize - 1) to Coordinate(2 * blockSize, blockSize - 1)
),
transforms( // block 1 -> 6
0,
Coordinate(3 * blockSize, 0) to Coordinate(4 * blockSize - 1, 3 * blockSize - 1),
Coordinate(3 * blockSize, blockSize - 1) to Coordinate(4 * blockSize - 1, 2 * blockSize)
),
// transforms(
// ,
// Coordinate(,) to Coordinate(,),
// Coordinate(,) to Coordinate(,)
// ),
// transforms(
// ,
// Coordinate(,) to Coordinate(,),
// Coordinate(,) to Coordinate(,)
// ),
// transforms(
// ,
// Coordinate(,) to Coordinate(,),
// Coordinate(,) to Coordinate(,)
// ),
)
val (position, direction) = board.walkCommands(commands) { direction, position ->
var nextPos = position
while (this[nextPos] == ' ') {
nextPos = nextPos.goInDirection(direction).wrap(width, height)
}
nextPos
}
return 1000 * (position.y + 1) + 4 * (position.x + 1) + direction
}
// 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)
// println("Part1 test points: $part1TestPoints")
// check(part1TestPoints == 6032)
//
// val part1points = calculatePart1Score(input)
// println("Part1 points: $part1points")
val part2TestPoints = calculatePart2Score(testInput)
println("Part2 test points: $part2TestPoints")
check(part2TestPoints == 1707)
val part2points = calculatePart2Score(input)
println("Part2 points: $part2points")
}
data class Board(val board: List<CharArray>) {
val height: Int = board.size
val width: Int = board[0].size
operator fun get(coordinate: Coordinate): Char = board[coordinate.y][coordinate.x]
}
fun List<CharArray>.print() = println(joinToString("\n") { it.joinToString("") })
fun Coordinate.goInDirection(direction: Int): Coordinate = when (direction) {
0 -> copy(x = x + 1)
1 -> copy(y = y + 1)
2 -> copy(x = x - 1)
3 -> copy(y = y - 1)
else -> error("hä? Wie das? direction: $direction")
}
fun List<String>.parseBoardAndCommands(): Pair<List<Command>, Board> {
val commandsString = last()
val mapLines = dropLast(2).map { it.toCharArray() }
val longestMapLineLength = mapLines.maxOf { it.size }
val board = mapLines.map { it + CharArray(longestMapLineLength - it.size) { ' ' } }
// board.print()
val commands = commandsString.toCharArray().fold(listOf<Command>(StepCommand(0))) { acc, c ->
val lastCommand = acc.last()
when {
c == 'R' || c == 'L' -> acc + listOf(TurnCommand(c))
lastCommand is StepCommand -> acc.dropLast(1) + listOf(StepCommand(lastCommand.steps * 10 + c.digitToInt()))
lastCommand is TurnCommand -> acc + listOf(StepCommand(c.digitToInt()))
else -> error("unknown $c")
}
}
return commands to Board(board)
}
fun Board.walkCommands(commands: List<Command>, wrapAround: Board.(direction: Int, pos: Coordinate) -> Coordinate): Pair<Coordinate, Int> {
val startY = 0
val startX = board[startY].indexOfFirst { it == '.' }
// play game
var pos = Coordinate(startX, startY)
var direction = 0
commands.forEach { command ->
when (command) {
is StepCommand -> {
for (step in 0 until command.steps) {
val nextPos = pos.goInDirection(direction).wrap(width, height)
val wrappedNextPos = wrapAround(direction, nextPos)
if (this[wrappedNextPos] == '#') {
break
}
pos = wrappedNextPos
}
}
is TurnCommand -> {
when (command.turn) {
'R' -> direction = (direction + 1).mod(4)
'L' -> direction = (direction - 1).mod(4)
}
}
}
}
return pos to direction
} | 0 | Kotlin | 0 | 0 | e42802d7721ad25d60c4f73d438b5b0d0176f120 | 6,953 | advent-of-code-22-kotlin | Apache License 2.0 |
src/year2015/day05/Day05.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2015.day05
import check
import readInput
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("2015", "Day05_test")
check(part1(testInput), 1)
check(part2(testInput), 1)
val input = readInput("2015", "Day05")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>) = input.count { isNice(it) }
private fun part2(input: List<String>) = input.count { isNicePartTwo(it) }
private val naughtyStrings = setOf("ab", "cd", "pq", "xy")
private val vowels = setOf('a', 'e', 'i', 'o', 'u')
private fun isNice(string: String): Boolean {
val vowelCount = string.count { it in vowels }
if (vowelCount < 3) return false
val hasNaughtyStrings = naughtyStrings.any { it in string }
if (hasNaughtyStrings) return false
return string.windowed(2, 1).any { it[0] == it[1] }
}
private fun isNicePartTwo(string: String): Boolean {
val cond1 = string.windowed(2, 1).any { string.indexOf(it) + 2 <= string.lastIndexOf(it) }
val cond2 = string.windowed(3, 1).any { it[0] == it[2] }
return cond1 && cond2
}
| 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 1,145 | AdventOfCode | Apache License 2.0 |
src/main/kotlin/_2022/Day19.kt | novikmisha | 572,840,526 | false | {"Kotlin": 145780} | package _2022
import readInput
fun main() {
fun parseBlueprint(input: String): BlueprintPaper {
var number = 0
val robotBlueprints = mutableListOf<RobotBlueprint>()
val strings = input.split(".", ":")
strings.forEachIndexed { index, str ->
when (index) {
0 -> number = str.replace("Blueprint ", "")
.replace(":", "")
.toInt()
1 -> {
val oreRobotNeededOre = str.replace("Each ore robot costs ", "")
.replace("ore", "")
.trim()
.toInt()
robotBlueprints.add(RobotBlueprint(Mineral.ORE, oreRobotNeededOre, 0, 0))
}
2 -> {
val clayRobotOreCost = str.replace("Each clay robot costs ", "")
.replace("ore", "")
.trim()
.toInt()
robotBlueprints.add(RobotBlueprint(Mineral.CLAY, clayRobotOreCost, 0, 0))
}
3 -> {
val numbers = str.replace("Each obsidian robot costs ", "")
.replace(" ore and ", ",")
.replace(" clay", "")
.trim()
.split(",")
.map(String::toInt)
robotBlueprints.add(RobotBlueprint(Mineral.OBSIDIAN, numbers[0], numbers[1], 0))
}
4 -> {
val numbers = str.replace("Each geode robot costs ", "")
.replace(" ore and ", ",")
.replace(" obsidian", "")
.trim()
.split(",")
.map(String::toInt)
robotBlueprints.add(RobotBlueprint(Mineral.GEODE, numbers[0], 0, numbers[1]))
}
}
}
return BlueprintPaper(number, robotBlueprints)
}
fun canCraftRobots(blueprintPaper: BlueprintPaper, mineralMap: MutableMap<Mineral, Int>): List<RobotBlueprint> {
return blueprintPaper.robotBlueprints.filter {
mineralMap.getOrDefault(Mineral.ORE, 0) >= it.oreCost
&& mineralMap.getOrDefault(Mineral.CLAY, 0) >= it.clayCost
&& mineralMap.getOrDefault(Mineral.OBSIDIAN, 0) >= it.obsidianCost
}
}
fun filterRobots(
blueprintPaper: BlueprintPaper,
existingRobots: MutableList<RobotBlueprint>,
canCraftRobots: List<RobotBlueprint>,
mineralMap: MutableMap<Mineral, Int>,
stepsLeft: Int
): List<RobotBlueprint> {
if (canCraftRobots.isEmpty()) {
return emptyList()
}
val geodeRobots = canCraftRobots.filter { it.miningMineral == Mineral.GEODE }
if (geodeRobots.isNotEmpty()) {
return geodeRobots
}
val filteredRobots = canCraftRobots.toMutableList()
val maxNeededOreProduction = blueprintPaper.robotBlueprints.maxOf { it.oreCost }
val existedOreProduction = existingRobots.count { it.miningMineral == Mineral.ORE }
if (existedOreProduction >= maxNeededOreProduction) {
filteredRobots.removeIf { it.miningMineral == Mineral.ORE }
}
if (stepsLeft * existedOreProduction + mineralMap.getOrDefault(Mineral.ORE, 0)
> maxNeededOreProduction * stepsLeft
) {
filteredRobots.removeIf { it.miningMineral == Mineral.ORE }
}
val maxNeededClayProduction = blueprintPaper.robotBlueprints.maxOf { it.clayCost }
val existedClayProduction = existingRobots.count { it.miningMineral == Mineral.CLAY }
if (existedClayProduction >= maxNeededClayProduction) {
filteredRobots.removeIf { it.miningMineral == Mineral.CLAY }
}
if (stepsLeft * existedClayProduction + mineralMap.getOrDefault(Mineral.CLAY, 0)
> maxNeededClayProduction * stepsLeft
) {
filteredRobots.removeIf { it.miningMineral == Mineral.CLAY }
}
val maxNeededObsidianProduction = blueprintPaper.robotBlueprints.maxOf { it.obsidianCost }
val existedObsidianProduction = existingRobots.count { it.miningMineral == Mineral.OBSIDIAN }
if (existedObsidianProduction >= maxNeededObsidianProduction) {
filteredRobots.removeIf { it.miningMineral == Mineral.OBSIDIAN }
}
if (stepsLeft * existedObsidianProduction + mineralMap.getOrDefault(Mineral.OBSIDIAN, 0)
> maxNeededObsidianProduction * stepsLeft
) {
filteredRobots.removeIf { it.miningMineral == Mineral.OBSIDIAN }
}
return filteredRobots
}
val hashResults = mutableMapOf<String, Int>()
fun buildHash(
mineralMap: MutableMap<Mineral, Int>,
robots: MutableList<RobotBlueprint>,
stepsLeft: Int
): String {
val existedOreProduction = robots.count { it.miningMineral == Mineral.ORE }
val existedClayProduction = robots.count { it.miningMineral == Mineral.CLAY }
val existedObsidianProduction = robots.count { it.miningMineral == Mineral.OBSIDIAN }
val existedGeodeProduction = robots.count { it.miningMineral == Mineral.GEODE }
val clays = mineralMap.getOrDefault(Mineral.CLAY, 0)
val ores = mineralMap.getOrDefault(Mineral.ORE, 0)
val obsidians = mineralMap.getOrDefault(Mineral.OBSIDIAN, 0)
val geodes = mineralMap.getOrDefault(Mineral.GEODE, 0)
return "step=$stepsLeft" +
"&obidianrobots=$existedObsidianProduction&clayrobots=$existedClayProduction&orerobots=$existedOreProduction" +
"&geoderobots=$existedGeodeProduction&clays=$clays&ores=$ores&obsidians=$obsidians&geodes=$geodes"
}
var best = -1
fun dfs(
blueprintPaper: BlueprintPaper,
mineralMap: MutableMap<Mineral, Int>,
robots: MutableList<RobotBlueprint>,
stepsLeft: Int
): Int {
val stepHash = buildHash(mineralMap, robots, stepsLeft)
val geodeRobots = robots.count { it.miningMineral == Mineral.GEODE }
val currentGeodeCount = mineralMap.getOrDefault(Mineral.GEODE, 0)
if (stepsLeft == 0) {
best = currentGeodeCount.coerceAtLeast(best)
hashResults[stepHash] = currentGeodeCount
return currentGeodeCount
}
if (stepsLeft == 1) {
best = (currentGeodeCount + geodeRobots).coerceAtLeast(best)
hashResults[stepHash] = currentGeodeCount + geodeRobots
return currentGeodeCount + geodeRobots
}
val possibleMaxGeodes =
currentGeodeCount + (geodeRobots * stepsLeft) + (0 until stepsLeft).sumOf { geodeRobots + it }
if (possibleMaxGeodes < best) {
hashResults[stepHash] = 0
return 0
}
if (hashResults.containsKey(stepHash)) {
return hashResults[stepHash]!!
}
val canCraftRobots = canCraftRobots(blueprintPaper, mineralMap)
val filteredRobotForCraft = filterRobots(blueprintPaper, robots, canCraftRobots, mineralMap, stepsLeft)
var maxOfGeodes = 0
if (filteredRobotForCraft.isNotEmpty()) {
maxOfGeodes = filteredRobotForCraft.maxOf {
val nextMineralMap = mineralMap.toMutableMap()
nextMineralMap[Mineral.CLAY] = nextMineralMap.getOrDefault(Mineral.CLAY, 0) - it.clayCost
nextMineralMap[Mineral.ORE] = nextMineralMap.getOrDefault(Mineral.ORE, 0) - it.oreCost
nextMineralMap[Mineral.OBSIDIAN] =
nextMineralMap.getOrDefault(Mineral.OBSIDIAN, 0) - it.obsidianCost
robots.forEach { robot ->
nextMineralMap[robot.miningMineral] =
nextMineralMap.computeIfAbsent(robot.miningMineral) { _ -> 0 }.inc()
}
val nextStepRobots = robots.toMutableList()
nextStepRobots.add(it)
dfs(
blueprintPaper,
nextMineralMap,
nextStepRobots,
stepsLeft - 1
)
}
}
var maxWithSkippingBuild = 0
if (!filteredRobotForCraft.any { it.miningMineral == Mineral.GEODE }) {
val nextMineralMap = mineralMap.toMutableMap()
robots.forEach { robot ->
nextMineralMap[robot.miningMineral] =
nextMineralMap.computeIfAbsent(robot.miningMineral) { _ -> 0 }.inc()
}
val nextStepRobots = robots.toMutableList()
maxWithSkippingBuild = dfs(
blueprintPaper,
nextMineralMap,
nextStepRobots,
stepsLeft - 1
)
}
maxOfGeodes = maxOfGeodes.coerceAtLeast(maxWithSkippingBuild)
hashResults[stepHash] = maxOfGeodes
best = maxOfGeodes.coerceAtLeast(best)
return maxOfGeodes
}
fun part1(input: List<String>): Int {
val bluePrints = input.map(::parseBlueprint)
return bluePrints.sumOf {
hashResults.clear()
best = -1
val result = dfs(it, mutableMapOf(), mutableListOf(RobotBlueprint(Mineral.ORE, 0, 0, 0)), 24)
println("$result for ${it.number}")
result * it.number
}
}
fun part2(input: List<String>): Int {
val bluePrints = input.map(::parseBlueprint)
return bluePrints.take(3).map {
hashResults.clear()
best = -1
val result = dfs(it, mutableMapOf(), mutableListOf(RobotBlueprint(Mineral.ORE, 0, 0, 0)), 32)
println("$result for ${it.number}")
result
}.reduce(Int::times)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day19_test")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day19")
println(part1(input))
println(part2(input))
}
data class BlueprintPaper(
val number: Int,
val robotBlueprints: List<RobotBlueprint>
)
data class RobotBlueprint(
val miningMineral: Mineral,
val oreCost: Int,
val clayCost: Int,
val obsidianCost: Int
)
enum class Mineral {
ORE, CLAY, OBSIDIAN, GEODE
} | 0 | Kotlin | 0 | 0 | 0c78596d46f3a8bf977bf356019ea9940ee04c88 | 10,494 | advent-of-code | Apache License 2.0 |
src/main/kotlin/day17/Day17.kt | Avataw | 572,709,044 | false | {"Kotlin": 99761} | package day17
fun solveA(input: List<String>): Int {
val jetStream = JetStream(input.first())
val shaper = Shaper()
val blocked = mutableSetOf<Position>()
var highestRock = 0
repeat(2022) {
highestRock += blocked.nextStep(highestRock, shaper, jetStream)
}
return highestRock
}
fun MutableSet<Position>.nextStep(highestRock: Int, shaper: Shaper, jetStream: JetStream): Int {
val start = Position(3, highestRock + 4)
val shape = shaper.next(start)
val newBlocked = shape.move(jetStream, this)
this.addAll(newBlocked)
return this.maxOf { it.y } - highestRock
}
fun solveB(input: List<String>): Long {
val jetStream = JetStream(input.first())
val shaper = Shaper()
val blocked = mutableSetOf<Position>()
var highestRock = 0
val previousSteps = mutableSetOf<String>()
var counting = 0
var cycleStart = 0
var cycleStartCode = ""
var startHighestRock = 0
var cycleHeight = 0
for (times in 0..5000) {
val heightDifference = blocked.nextStep(highestRock, shaper, jetStream)
highestRock += heightDifference
val code = "${shaper.current},${jetStream.current},$heightDifference"
if (!previousSteps.contains(code)) {
counting = 0
previousSteps.add(code)
continue
}
if (counting == 0) {
startHighestRock = highestRock
cycleStart = times
cycleStartCode = code
} else if (code == cycleStartCode) {
cycleHeight = highestRock - startHighestRock
break
}
counting++
}
val cycleTimes = (1000000000000 - 1 - cycleStart) / counting
val remainderTimes = ((1000000000000 - 1 - cycleStart) % counting).toInt()
var remainder = 0
repeat(remainderTimes) {
highestRock += blocked.nextStep(highestRock, shaper, jetStream).also { remainder += it }
}
return startHighestRock + cycleTimes * cycleHeight + remainder
}
data class JetStream(val input: String) {
var current = 0
fun blowsRight(): Boolean {
if (current >= input.length) current = 0
return input[current].also { current++ } == '>'
}
}
data class Shape(var start: Position, var cells: List<Position>) {
private var stopped = false
private var blocked = emptySet<Position>()
fun move(jetStream: JetStream, blocked: Set<Position>): List<Position> {
this.blocked = blocked
while (!stopped) {
if (jetStream.blowsRight()) moveRight()
else moveLeft()
moveDown()
}
return cells
}
private fun moveRight() {
if (cells.all { it.right().x < 8 && !blocked.contains(it.right()) }) cells = cells.map { it.right() }
}
private fun moveLeft() {
if (cells.all { it.left().x > 0 && !blocked.contains(it.left()) }) cells = cells.map { it.left() }
}
private fun moveDown() {
if (cells.all { it.down().y > 0 && !blocked.contains(it.down()) }) cells = cells.map { it.down() }
else stopped = true
}
}
class Shaper {
var current = 0
fun next(startAt: Position): Shape {
if (current == 5) current = 0
val nextShape = when (current) {
0 -> Shape(startAt, horizontalLine(startAt))
1 -> Shape(startAt, cross(startAt))
2 -> Shape(startAt, reverseL(startAt))
3 -> Shape(startAt, verticalLine(startAt))
4 -> Shape(startAt, square(startAt))
else -> throw Exception("Shape does not exist")
}
current++
return nextShape
}
}
data class Position(val x: Int, val y: Int) {
fun right(amount: Int = 1) = Position(x + amount, y)
fun left(amount: Int = 1) = Position(x - amount, y)
fun down(amount: Int = 1) = Position(x, y - amount)
fun up(amount: Int = 1) = Position(x, y + amount)
}
fun horizontalLine(start: Position) = listOf(start, start.right(), start.right(2), start.right(3))
fun cross(start: Position) = listOf(
start.right(), start.up(), start.up().right(),
start.up().right(2), start.up(2).right()
)
fun reverseL(start: Position) = listOf(
start, start.right(), start.right(2),
start.right(2).up(), start.right(2).up(2)
)
fun verticalLine(start: Position) = listOf(start, start.up(), start.up(2), start.up(3))
fun square(start: Position) = listOf(start, start.right(), start.up(), start.up().right())
| 0 | Kotlin | 2 | 0 | 769c4bf06ee5b9ad3220e92067d617f07519d2b7 | 4,474 | advent-of-code-2022 | Apache License 2.0 |
2020/day6/day6.kt | Deph0 | 225,142,801 | false | null | class day6 {
fun part1(input: List<String>): Int {
val inputGroupsSets = input.map {
it.split("\n").flatMap { group ->
group.split("").filter {
it.isNotBlank() // [, a, b,] because java is stupid
}.toSet()
}.toSet()
}
// println(inputGroupsSets)
var res = inputGroupsSets.sumBy {
it.size
}
return res
}
fun part2(input: List<String>): Int {
val inputGroups = input.map {
it.split("\n").map { group ->
group.split("").filter {
it.isNotBlank() // [, a, b,] because java is stupid
}// .toSet()
}//.toSet()
}
// var countGroups = inputGroups.map {
// var seen = hashMapOf<String, Int>()
// it.forEach {
// it.forEach {
// var value = seen.getOrPut(it) { 0 }
// seen.set(it, ++value )
// }
// }
// seen
// }
// println(inputGroups)
// println(countGroups)
// thx @Meowth52 github, was super lost on this part.. i got the hashmap hint from the puzzle but couldn't figure out how to apply it..
var res = 0
inputGroups.forEach { group ->
var seen = hashMapOf<String, Int>()
// println("group: $group")
group.forEach { ans ->
ans.forEach { ansChar ->
// println(ansChar)
var value = seen.getOrPut(ansChar) { 0 }
seen.set(ansChar, ++value )
}
}
// seen.forEach { (key, value) ->
seen.forEach { (_, value) ->
// println("$key = $value")
if (value == group.size) res ++
}
}
return res
}
init {
// val exampleinput = inputSep("inputs/day6-example.txt", "\n\n")
// println("day6-pt1-example: " + part1(exampleinput)) // 11
// println("day6-pt2-example: " + part2(exampleinput)) // 6
val input = inputSep("inputs/day6.txt", "\n\n")
println("day6-pt1: " + part1(input)) // 6587
println("day6-pt2: " + part2(input)) // 3235
}
}
| 0 | Kotlin | 0 | 0 | 42a4fce4526182737d9661fae66c011f0948e481 | 1,972 | adventofcode | MIT License |
src/Day12.kt | amelentev | 573,120,350 | false | {"Kotlin": 87839} | fun main() {
fun solve1(pattern: String, arr: List<Int>): Long {
val dp = Array(pattern.length+1) { LongArray(arr.size+1) }
dp[0][0] = 1
for (i in dp.indices) {
for (j in dp[i].indices) {
if (dp[i][j] <= 0) continue
if (i in pattern.indices && pattern[i] != '#') {
dp[i+1][j] += dp[i][j]
}
if (j in arr.indices) {
val end = i + arr[j]
if ((i until end).all { it in pattern.indices && pattern[it] != '.' } &&
(end == pattern.length || pattern[end] != '#'))
{
dp[end+1][j+1] += dp[i][j]
}
}
}
}
return dp[pattern.length][arr.size]
}
val input = readInput("Day12")
var res1 = 0L
var res2 = 0L
for (line in input) {
val pattern = line.substringBefore(' ')
val arr = line.substringAfter(' ').split(',').map { it.toInt() }
res1 += solve1("$pattern.", arr)
val pattern2 = (1..5).joinToString("?") { pattern }
val arr2 = (1..5).flatMap { arr }
res2 += solve1("$pattern2.", arr2)
}
println(res1)
println(res2)
} | 0 | Kotlin | 0 | 0 | a137d895472379f0f8cdea136f62c106e28747d5 | 1,278 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/day21/Code.kt | fcolasuonno | 317,324,330 | false | null | package day21
import isDebug
import java.io.File
fun main() {
val name = if (isDebug()) "test.txt" else "input.txt"
System.err.println(name)
val dir = ::main::class.java.`package`.name
val input = File("src/main/kotlin/$dir/$name").readLines()
val parsed = parse(input)
part1(parsed)
part2(parsed)
}
private val lineStructure = """(.+) \(contains (.+)\)""".toRegex()
fun parse(input: List<String>) = input.map {
lineStructure.matchEntire(it)?.destructured?.let {
val (ingredients, allergens) = it.toList()
ingredients.split(" ").toSet() to allergens.split(", ").toSet()
}
}.requireNoNulls()
fun part1(input: List<Pair<Set<String>, Set<String>>>) {
val allergens = input.flatMap { it.second }.toSet()
val useMap =
allergens.map { allergen -> allergen to input.filter { allergen in it.second }.map { it.first } }.toMap()
val possibleAllergens = useMap.values.flatMap { it.reduce { acc, set -> acc.intersect(set) } }.toSet()
val count = input.sumBy { it.first.count { it !in possibleAllergens } }
println("Part 1 = $count")
}
fun part2(input: List<Pair<Set<String>, Set<String>>>) {
val allergens = input.flatMap { it.second }.toSet()
val useMap =
allergens.map { allergen -> allergen to input.filter { allergen in it.second }.map { it.first } }.toMap()
val allergenMap = useMap.mapValues {
it.value.reduce { acc, set -> acc.intersect(set) }
}.toMutableMap()
val found = mutableSetOf<String>()
while (allergenMap.any { it.value.size > 1 }) {
found.addAll(allergenMap.values.filter { it.size == 1 }.flatten())
allergenMap.forEach { (allergen, possible) ->
if (possible.size > 1) {
allergenMap[allergen] = possible - found
}
}
}
val res = allergenMap.entries.sortedBy { it.key }.map { it.value.single() }.joinToString(",")
println("Part 2 = $res")
} | 0 | Kotlin | 0 | 0 | e7408e9d513315ea3b48dbcd31209d3dc068462d | 1,946 | AOC2020 | MIT License |
src/twentythree/Day08.kt | mihainov | 573,105,304 | false | {"Kotlin": 42574} | package twentythree
import readInputTwentyThree
fun main() {
fun part1(input: List<String>): Int {
val directions = input.first().map { it }
val nodes = input.filter { it.contains('=') }
.associate {
Pair(
it.substring(0, 3),
Pair(it.substring(7, 10), it.substring(12, 15))
)
}
var currentNode = "AAA"
var step = 0
while (currentNode != "ZZZ") {
if (directions[step % directions.size] == 'L') {
currentNode = nodes[currentNode]!!.first
} else {
currentNode = nodes[currentNode]!!.second
}
step++
}
return step
}
fun part2(input: List<String>): Long {
val directions = input.first().map { it }
val nodes = input.filter { it.contains('=') }
.associate {
Pair(
it.substring(0, 3),
Pair(it.substring(7, 10), it.substring(12, 15))
)
}
val currentNodes = nodes.keys.filter { it.endsWith("A") }.toMutableList()
var steps = 0L
var startTimer = System.currentTimeMillis()
while (!currentNodes.all { it.endsWith("Z") }) {
for (i in currentNodes.indices) {
if (directions[(steps % directions.size).toInt()] == 'L') {
currentNodes[i] = nodes[currentNodes[i]]!!.first
} else {
currentNodes[i] = nodes[currentNodes[i]]!!.second
}
}
steps++
if (steps % 10_000_000 == 0L) {
println("Steps $steps: $currentNodes; ${System.currentTimeMillis() - startTimer}")
startTimer = System.currentTimeMillis()
}
}
return steps
}
// test if implementation meets criteria from the description, like:
val testInput = readInputTwentyThree("Day08_test")
// check(part1(testInput).also(::println) == 2) yeet cuz part 2 does not work the same way
check(part2(testInput).also(::println) == 6L)
val input = readInputTwentyThree("Day08")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | a9aae753cf97a8909656b6137918ed176a84765e | 2,267 | kotlin-aoc-1 | Apache License 2.0 |
src/main/kotlin/mirecxp/aoc23/day06/Day06.kt | MirecXP | 726,044,224 | false | {"Kotlin": 42343} | package mirecxp.aoc23.day06
import mirecxp.aoc23.day04.toNumList
import mirecxp.aoc23.readInput
import java.util.*
//https://adventofcode.com/2023/day/6
class Day06(private val inputPath: String) {
private var lines: List<String> = readInput(inputPath).toMutableList()
fun solve(part2: Boolean): String {
println("Solving day 6 for ${lines.size} lines [$inputPath]")
if (part2) {
lines = lines.map { it.replace(" ", "") }
}
val times = lines[0].substringAfter("Time:").trim().toNumList().map { it.toInt() }
val distances = lines[1].substringAfter("Distance:").trim().toNumList()
var result = 1L
times.forEachIndexed { index, time ->
val distance = distances[index]
result *= numOfWays(time.toLong(), distance)
}
val solution = "$result"
println(solution)
return solution
}
fun numOfWays(time: Long, record: Long): Long {
var count = 0L
for (t in 0..time) {
if (t * (time - t) > record) count++
}
return count
}
}
fun main(args: Array<String>) {
val testProblem = Day06("test/day06t")
check(testProblem.solve(part2 = false) == "288")
check(testProblem.solve(part2 = true) == "71503")
val problem = Day06("real/day06a")
problem.solve(part2 = false)
problem.solve(part2 = true)
}
| 0 | Kotlin | 0 | 0 | 6518fad9de6fb07f28375e46b50e971d99fce912 | 1,401 | AoC-2023 | MIT License |
src/test/kotlin/com/igorwojda/list/sort/radixsort/Solution.kt | igorwojda | 159,511,104 | false | {"Kotlin": 254856} | package com.igorwojda.list.sort.radixsort
// Time complexity (Best): Ω(n^2)
// Time complexity (Average): Θ(n^2)
// Time complexity (Worst): O(n^2)
// Space complexity: O(1)
private object Solution1 {
private fun radixSort(list: List<Int>): List<Number> {
// create temp list
val tempList = list.toMutableList()
// got through the list as many times as there are digits in the longest number
val maxDigits = maxDigits(list)
(0 until maxDigits).forEach { digitRightIndex ->
// crate 10 buckets
val buckets = mutableMapOf<Char, MutableList<Int>>()
('0'..'9').forEach { buckets[it] = mutableListOf() }
// add numbers to the buckets
tempList.forEach {
val digit = it.getDigitAt(digitRightIndex)
buckets[digit]?.add(it)
}
// clean temp list (all numbers are in buckets by now)
tempList.clear()
// take numbers from buckets and add it to the temp list
('0'..'9').forEach { digit ->
buckets[digit]?.let { tempList.addAll(it) }
}
}
return tempList
}
private fun Int.getDigitAt(index: Int): Char {
val str = this.toString()
val rightIndex = str.lastIndex - index
return str.getOrElse(rightIndex) { '0' }
}
// This is mathematical alternative to this.toString().length witch has better performance
private val Int.digitCount: Int
get() = when (this) {
0 -> 1
else -> Math.log10(Math.abs(this.toDouble())).toInt() + 1
}
private fun maxDigits(list: List<Int>) = list.map { it.digitCount }.maxOrNull() ?: 0
}
private object KtLintWillNotComplain
| 9 | Kotlin | 225 | 895 | b09b738846e9f30ad2e9716e4e1401e2724aeaec | 1,774 | kotlin-coding-challenges | MIT License |
src/day08/Day08.kt | MaxBeauchemin | 573,094,480 | false | {"Kotlin": 60619} | package day08
import readInput
import kotlin.math.abs
fun main() {
fun parseInput(input: List<String>): List<List<Int>> {
return input.map { str ->
str.toList().map { char ->
char.digitToInt()
}
}
}
fun List<Int>.allSmallerThan(compare: Int) = this.all { it < compare }
fun List<List<Int>>.checkVisible(outerIdx: Int, innerIdx: Int): Boolean {
val outerLastIdx = this.size - 1
val innerLastIdx = this[outerIdx].size - 1
val height = this[outerIdx][innerIdx]
//Edge Check
if (outerIdx == 0 || innerIdx == 0 || outerIdx == outerLastIdx || innerIdx == innerLastIdx) return true
//Inner Checks
val innerBefore = this[outerIdx].subList(0, innerIdx)
if (innerBefore.allSmallerThan(height)) return true
val innerAfter = this[outerIdx].slice(innerIdx + 1..innerLastIdx)
if (innerAfter.allSmallerThan(height)) return true
//Outer Checks
val outerBefore = this.subList(0, outerIdx).map { it[innerIdx] }
if (outerBefore.allSmallerThan(height)) return true
val outerAfter = this.slice(outerIdx + 1..outerLastIdx).map { it[innerIdx] }
if (outerAfter.allSmallerThan(height)) return true
return false
}
fun List<List<Int>>.scenicScore(outerIdx: Int, innerIdx: Int): Int {
val outerLastIdx = this.size - 1
val innerLastIdx = this[outerIdx].size - 1
val height = this[outerIdx][innerIdx]
val outerBeforeScore = if (outerIdx == 0) 0 else {
var lastVisibleIdxAfter = -1
for (o in outerIdx - 1 downTo 0) {
if (lastVisibleIdxAfter == -1 && this[o][innerIdx] >= height) lastVisibleIdxAfter = o
}
if (lastVisibleIdxAfter == -1) outerIdx else {
abs(lastVisibleIdxAfter - outerIdx)
}
}
val outerAfterScore = if (outerIdx == outerLastIdx) 0 else {
var lastVisibleIdxAfter = -1
for (o in outerIdx + 1..outerLastIdx) {
if (lastVisibleIdxAfter == -1 && this[o][innerIdx] >= height) lastVisibleIdxAfter = o
}
if (lastVisibleIdxAfter == -1) outerLastIdx - outerIdx else {
abs(lastVisibleIdxAfter - outerIdx)
}
}
val innerBeforeScore = if (innerIdx == 0) 0 else {
var lastVisibleIdxBefore = -1
for (i in innerIdx - 1 downTo 0) {
if (lastVisibleIdxBefore == -1 && this[outerIdx][i] >= height) lastVisibleIdxBefore = i
}
if (lastVisibleIdxBefore == -1) innerIdx else {
abs(lastVisibleIdxBefore - innerIdx)
}
}
val innerAfterScore = if (innerIdx == innerLastIdx) 0 else {
var lastVisibleIdxAfter = -1
for (i in innerIdx + 1..innerLastIdx) {
if (lastVisibleIdxAfter == -1 && this[outerIdx][i] >= height) lastVisibleIdxAfter = i
}
if (lastVisibleIdxAfter == -1) innerLastIdx - innerIdx else {
abs(lastVisibleIdxAfter - innerIdx)
}
}
return outerBeforeScore * outerAfterScore * innerBeforeScore * innerAfterScore
}
fun part1(input: List<String>): Int {
return parseInput(input).let { data ->
data.mapIndexed { outerIdx, inner ->
inner.mapIndexed { innerIdx, _ ->
if (data.checkVisible(outerIdx, innerIdx)) 1 else 0
}
}
}.flatten().sum()
}
fun part2(input: List<String>): Int {
return parseInput(input).let { data ->
data.mapIndexed { outerIdx, inner ->
inner.mapIndexed { innerIdx, _ ->
data.scenicScore(outerIdx, innerIdx)
}
}
}.flatten().max()
}
val testInput = readInput("Day08_test")
val input = readInput("Day08")
println("Part 1 [Test] : ${part1(testInput)}")
check(part1(testInput) == 21)
println("Part 1 [Real] : ${part1(input)}")
println("Part 2 [Test] : ${part2(testInput)}")
check(part2(testInput) == 8)
println("Part 2 [Real] : ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 38018d252183bd6b64095a8c9f2920e900863a79 | 4,264 | advent-of-code-2022 | Apache License 2.0 |
kotlin-algorithm-sample/src/main/kotlin/yitian/study/algorithm/problem/ModProblem.kt | techstay | 89,333,432 | false | null | package yitian.study.algorithm.problem
/**
* 一筐鸡蛋:
* 1个1个拿,正好拿完。
* 2个2个拿,还剩1个。
* 3个3个拿,正好拿完。
* 4个4个拿,还剩1个。
* 5个5个拿,还差1个。
* 6个6个拿,还剩3个。
* 7个7个拿,正好拿完。
* 8个8个拿,还剩1个。
* 9个9个拿,正好拿完。
* 问:筐里最少有几个鸡蛋?
*
*/
class ModProblem
/**
* 直接暴力穷举
*/
fun answer1() {
var n = 0
while (true) {
if (n % 2 == 1 && n % 4 == 1 && n % 5 == 4 && n % 6 == 3 && n % 7 == 0 && n % 8 == 1 && n % 9 == 0) {
break
}
n++
}
println(n)
}
/**
* 改良版本
*/
fun answer2() {
var n = 63
var count = 0
while (true) {
count++
if (n % 4 == 1 && n % 5 == 4 && n % 6 == 3 && n % 8 == 1) {
break
}
n += 63 * 2
}
println("n=$n,count=$count")
}
/**
* 更优化版本
*/
fun answer3() {
var n = 63 * 3
var count = 0
while (true) {
count++
if (n % 8 == 1) {
break
}
n += 630
}
println("n=$n,count=$count")
}
/**
* 计算一个可以让所有余数都相等的数
*/
fun cal(): Int {
//由题意推出来的除数和余数的结果
val numbers = hashMapOf(
2 to 1,
3 to 0,
4 to 1,
5 to 4,
6 to 3,
7 to 0,
8 to 1,
9 to 0)
var n = 0
while (true) {
n++
for (k in numbers.keys) {
val old = numbers[k]
numbers[k] = (old!! + 1) % k
}
val set = numbers.values.toSet()
if (set.size == 1) {
break
}
}
println("这个数是:$n")
return n
}
/**
* greatest common divisor
* a和b的最大公约数
*/
tailrec fun gcd(a: Int, b: Int): Int {
val c = if (a > b) a % b else b % a
if (c == 0)
return b
else
return gcd(b, c)
}
/**
* lowest common multiple
* a和b的最小公倍数
*/
fun lcm(a: Int, b: Int): Int {
val c = gcd(a, b)
return a * b / c
}
/**
* 最后一种,通过把所有余数凑成相同的
* 然后使用最小公倍数来计算
*/
fun answer4() {
val n = cal()
val lcmOfAll = (2..10).reduce(::lcm)
println("结果是${lcmOfAll - n}")
}
fun main(args: Array<String>) {
answer1()
answer2()
answer3()
answer4()
} | 0 | Kotlin | 0 | 0 | 1380ce181b1c8d4fad4752a1d92348dcf5d1ed18 | 2,453 | algorithm-study | MIT License |
src/Day05.kt | ZiomaleQ | 573,349,910 | false | {"Kotlin": 49609} | import java.util.Scanner
fun main() {
fun part1(input: List<String>): String {
val splitIndex = input.withIndex().first { it.value.isBlank() }.index
val configuration = input.subList(0, splitIndex)
val moves = input.subList(splitIndex + 1, input.size)
val columns = mutableListOf<Int>()
val boxes = mutableListOf<Box>()
for (line in configuration) {
if (!line.contains('[') || !line.contains(']')) {
columns.addAll(line.filter { !it.isWhitespace() }.split("").filter { it.isNotBlank() }
.map { it.toInt() })
} else {
for ((index, char) in line.withIndex()) {
if (char.isLetter()) {
val numOfColumn = (index - 1) / 4
boxes.add(Box(char, numOfColumn + 1))
}
}
}
}
val mappedMoves = moves.map {
val scanner = Scanner(it)
scanner.next()
val num = scanner.nextInt()
scanner.next()
val from = scanner.nextInt()
scanner.next()
val to = scanner.nextInt()
Move(num, from, to)
}
val stacks: List<MutableList<Box>> = List(columns.size) { ind ->
boxes.filter { it.column == (ind + 1) }.toMutableList()
}
for (move in mappedMoves) {
var moved = 0
while (move.num > moved) {
stacks[move.to - 1].add(0, stacks[move.from - 1].removeFirst())
moved++
}
}
return stacks.joinToString("") { it.firstOrNull()?.id.toString() }
}
fun part2(input: List<String>): String {
val splitIndex = input.withIndex().first { it.value.isBlank() }.index
val configuration = input.subList(0, splitIndex)
val moves = input.subList(splitIndex + 1, input.size)
val columns = mutableListOf<Int>()
val boxes = mutableListOf<Box>()
for (line in configuration) {
if (!line.contains('[') || !line.contains(']')) {
columns.addAll(line.filter { !it.isWhitespace() }.split("").filter { it.isNotBlank() }
.map { it.toInt() })
} else {
for ((index, char) in line.withIndex()) {
if (char.isLetter()) {
val numOfColumn = (index - 1) / 4
boxes.add(Box(char, numOfColumn + 1))
}
}
}
}
val mappedMoves = moves.map {
val scanner = Scanner(it)
scanner.next()
val num = scanner.nextInt()
scanner.next()
val from = scanner.nextInt()
scanner.next()
val to = scanner.nextInt()
Move(num, from, to)
}
val stacks: List<MutableList<Box>> = List(columns.size) { ind ->
boxes.filter { it.column == (ind + 1) }.toMutableList()
}
for (move in mappedMoves) {
var moved = 0
while (move.num > moved) {
stacks[move.to - 1].add(moved, stacks[move.from - 1].removeFirst())
moved++
}
}
return stacks.joinToString("") { it.firstOrNull()?.id.toString() }
}
// 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))
}
data class Box(val id: Char, val column: Int) {
override fun toString(): String {
return "$id"
}
}
data class Move(val num: Int, val from: Int, val to: Int) | 0 | Kotlin | 0 | 0 | b8811a6a9c03e80224e4655013879ac8a90e69b5 | 3,837 | aoc-2022 | Apache License 2.0 |
advent-of-code/src/main/kotlin/com/akikanellis/adventofcode/year2022/Day07.kt | akikanellis | 600,872,090 | false | {"Kotlin": 142932, "Just": 977} | package com.akikanellis.adventofcode.year2022
object Day07 {
private val CD_REGEX = "\\$ cd (.+)".toRegex()
private val DIR_REGEX = "dir (.+)".toRegex()
private val FILE_REGEX = "([0-9]+) (.+)".toRegex()
fun sumOfAllDirectoriesWithTotalSizeLessThan100000(input: String) = rootDirectory(input)
.allSubdirectories()
.map { it.size() }
.filter { it <= 100_000 }
.sum()
fun sizeOfDirectoryToDelete(input: String): Int {
val rootDirectory = rootDirectory(input)
val unusedSpace = 70_000_000 - rootDirectory.size()
val extraUnusedSpaceNeeded = 30_000_000 - unusedSpace
return rootDirectory.allSubdirectories()
.map { it.size() }
.sortedDescending()
.last { it >= extraUnusedSpaceNeeded }
}
private fun rootDirectory(input: String): Directory {
val rootDirectory = Directory(name = "/")
input
.lines()
.fold(rootDirectory) { currentDirectory, terminalOutputLine ->
if (terminalOutputLine.matches(CD_REGEX)) {
val directoryName = CD_REGEX
.matchEntire(terminalOutputLine)!!
.groupValues[1]
return@fold when (directoryName) {
"/" -> rootDirectory
".." -> currentDirectory.parent!!
else -> currentDirectory.childDirectory(directoryName)
}
} else if (terminalOutputLine.matches(DIR_REGEX)) {
val newDirectoryName = DIR_REGEX
.matchEntire(terminalOutputLine)!!
.groupValues[1]
currentDirectory.addChildDirectory(newDirectoryName)
} else if (terminalOutputLine.matches(FILE_REGEX)) {
val newFile = FILE_REGEX
.matchEntire(terminalOutputLine)!!
.groupValues
.let { File(it[2], it[1].toInt()) }
currentDirectory.addChildFile(newFile)
}
return@fold currentDirectory
}
return rootDirectory
}
data class Directory(
val name: String,
val parent: Directory? = null,
val childDirectories: MutableList<Directory> = mutableListOf(),
val childFiles: MutableList<File> = mutableListOf()
) {
fun childDirectory(name: String) = childDirectories.single { it.name == name }
fun allSubdirectories(): List<Directory> =
childDirectories + childDirectories.flatMap { it.allSubdirectories() }
fun size(): Int = childDirectories.sumOf { it.size() } + childFiles.sumOf { it.size }
fun addChildDirectory(name: String) {
childDirectories += Directory(name = name, parent = this)
}
fun addChildFile(file: File) {
childFiles += file
}
}
data class File(val name: String, val size: Int)
}
| 8 | Kotlin | 0 | 0 | 036cbcb79d4dac96df2e478938de862a20549dce | 3,058 | advent-of-code | MIT License |
jk/src/main/kotlin/leetcode/Solution_LeetCode_Dynamic_Planning.kt | lchang199x | 431,924,215 | false | {"Kotlin": 86230, "Java": 23581} | package leetcode
import kotlin.math.max
class Solution_LeetCode_Dynamic_Planning {
fun fibonacci(n: Int): Int {
return if (n <= 1) 1 else fibonacci(n - 1) + fibonacci(n - 2)
}
fun fibonacciDp(n: Int): Int {
if (n <= 1) return 1
var pre1 = 1
var pre2 = 1
var result = 0
for (i in 2 until n) {
result = pre1 + pre2
pre2 = pre1
pre1 = result
}
return result
}
/**
* C(N) = 2/N(0->N-1累加C(i)) + N
*/
fun eval(n: Int): Double {
var result = 0.0
if (n == 0)
result = 1.0
else {
var sum = 0.0
for (i in 0 until n) {
sum += eval(i)
}
result = 2.0 / n * sum + n
}
return result
}
/**
* dp针对的是重复计算的部分,即0->N-1累加C(i)
*
* f(n)依赖0..n-1的子问题,所以要一个数组,fibonacci只依赖n-1和n-2,多以两个变量即可
*/
fun evalDp(n: Int): Double {
val nums = DoubleArray(n + 1)
nums[0] = 1.0
// 这里循环的人物不再是计算出result,而是计算出表nums中得每个item的值
for (i in 1..n) {
var sum = 0.0
for (j in 0 until i)
sum += nums[j]
nums[i] = 2.0 * sum / i + i
}
return nums[n]
}
/**
* 爬楼梯: 其实就是fibonacci数列
* [](https://leetcode-cn.com/problems/climbing-stairs/)
*/
fun climbStairs(n: Int): Int {
var pre1 = 1
var pre2 = 0
var result = 0
for (i in 0 until n) {
result = pre1 + pre2
pre2 = pre1
pre1 = result
}
return result
}
/**
* 跳跃游戏
* [](https://leetcode-cn.com/problems/jump-game/)
*/
fun canJump(nums: IntArray): Boolean {
var rightMost = 0
for (i in nums.indices) {
if (i < rightMost) {
rightMost = max(rightMost, i + nums[i])
if (rightMost > nums.size -1) {
return true
}
}
}
return false
}
}
fun main() {
println(Solution_LeetCode_Dynamic_Planning().evalDp(5))
} | 0 | Kotlin | 0 | 0 | 52a008325dd54fed75679f3e43921fcaffd2fa31 | 2,323 | Codelabs | Apache License 2.0 |
src/Day04.kt | filipradon | 573,512,032 | false | {"Kotlin": 6146} | fun main() {
fun String.toSet(): Set<Int> {
val (begin, end) = this.split("-")
return (begin.toInt()..end.toInt()).toSet()
}
fun part1(input: List<String>): Int {
return input
.map { it.split(",") } // into two ranges
.map { it[0].toSet() to it[1].toSet() }
.count {
val (first, second) = it
first.containsAll(second) || second.containsAll(first)
}
}
fun part2(input: List<String>): Int {
return input
.map { it.split(",") } // into two ranges
.map { it[0].toSet() to it[1].toSet() }
.count {
val (first, second) = it
(first intersect second).isNotEmpty()
// OR
// first.any { it in second }
}
}
val input = readInputAsList("input-day4")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | dbac44fe421e29ab2ce0703e5827e4645b38548e | 947 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/Day07Swag.kt | rileynull | 437,153,864 | false | null | package rileynull.aoc
import kotlin.math.absoluteValue
object Day07Swag {
fun quickSelect(list: MutableList<Int>, k: Int, left: Int = 0, right: Int = list.size - 1): Int {
if (left == right) return list[left]
var dstIndex = left
for (i in left..right) {
if (list[i] < list[right] || i == right) {
val tmp = list[dstIndex]
list[dstIndex] = list[i]
list[i] = tmp
dstIndex++
}
}
return when {
(k < dstIndex - 1) -> quickSelect(list, k, left, dstIndex - 2)
(k >= dstIndex) -> quickSelect(list, k, dstIndex, right)
else -> list[k]
}
}
fun linearDistance(x1: Int, x2: Int): Int = (x2 - x1).absoluteValue
fun triangularDistance(x1: Int, x2: Int): Int = linearDistance(x1, x2) * (linearDistance(x1, x2) + 1) / 2
}
fun main() {
val input = {}.javaClass.getResource("/day07.txt").readText().trim().split(',').map { it.toInt() }
val median = Day07Swag.quickSelect(input.toMutableList(), input.size / 2)
println("Answer to part A is ${input.sumBy { Day07Swag.linearDistance(it, median) }}.")
// There are other terms besides just the sum of squares but they don't affect the final answer for my input.
val mean = input.sum() / input.size
println("Answer to part B is ${input.sumBy { Day07Swag.triangularDistance(it, mean) }}.")
}
| 0 | Kotlin | 0 | 0 | 2ac42faa192767f00be5db18f4f1aade756c772b | 1,477 | adventofcode | Apache License 2.0 |
src/day14/Day14.kt | gautemo | 317,316,447 | false | null | package day14
import shared.getLines
fun initProgram(input: List<String>, isV2: Boolean = false): Long{
val computer = if(isV2) ComputerV2() else ComputerV1()
for(line in input){
if(line.contains("mask")){
val mask = line.split('=')[1].trim()
computer.mask = mask
}else{
val adress = Regex("""\d+(?=\])""").find(line)!!.value.toLong()
val number = line.split("=")[1].trim().toLong()
computer.addValue(adress, number)
}
}
return computer.values().sum()
}
interface Computer {
var mask: String
val memory: MutableMap<Long, Long>
fun values() = memory.values
fun addValue(adress: Long, input: Long)
}
class ComputerV1: Computer {
override val memory = mutableMapOf<Long, Long>()
override var mask = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
override fun addValue(adress: Long, input: Long){
val binary = input.toString(2).padStart(mask.length, '0').toCharArray()
for(i in mask.indices){
if(mask[i] != 'X'){
binary[i] = mask[i]
}
}
memory[adress] = binary.joinToString("").toLong(2)
}
override fun values() = memory.values
}
class ComputerV2: Computer {
override val memory = mutableMapOf<Long, Long>()
override var mask = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
override fun addValue(adress: Long, input: Long){
val adressBinary = adress.toString(2).padStart(mask.length, '0').toCharArray()
for(i in mask.indices){
if(mask[i] != '0'){
adressBinary[i] = mask[i]
}
}
val adresses = combinationsForX(adressBinary)
for(adr in adresses){
memory[adr.joinToString("").toLong(2)] = input
}
}
override fun values() = memory.values
}
fun combinationsForX(input: CharArray): List<CharArray>{
val list = mutableListOf<CharArray>()
val xIndex = input.indexOfFirst { it == 'X' }
if(xIndex != -1){
input[xIndex] = '1'
list.addAll(combinationsForX(input.clone()))
input[xIndex] = '0'
list.addAll(combinationsForX(input.clone()))
}else{
list.add(input)
}
return list
}
fun main(){
val input = getLines("day14.txt")
val sum = initProgram(input)
println(sum)
val sum2 = initProgram(input, true)
println(sum2)
} | 0 | Kotlin | 0 | 0 | ce25b091366574a130fa3d6abd3e538a414cdc3b | 2,409 | AdventOfCode2020 | MIT License |
src/Day04.kt | RusticFlare | 574,508,778 | false | {"Kotlin": 78496} | fun main() {
fun part1(input: List<String>): Int {
return input.count { line ->
val (a, b, x, y) = line.split(',', '-').map { it.toInt() }
(a <= x && y <= b) || (x <= a && b <= y)
}
}
fun part2(input: List<String>): Int {
return input.count { line ->
val (x, y) = line.split(',', '-').map { it.toInt() }.chunked(2) { (a, b) -> a..b }
(x intersect y).isNotEmpty()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readLines("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readLines("Day04")
check(part1(input) == 569)
println(part1(input))
check(part2(input) == 936)
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 10df3955c4008261737f02a041fdd357756aa37f | 800 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/Day08.kt | SimonMarquis | 724,825,757 | false | {"Kotlin": 30983} | class Day08(input: List<String>) {
private val instructions = input.first()
private val network = input.drop(2)
.map { it.split("""\W+""".toRegex()) }
.associateBy({ it.first() }, { (id, left, right) -> Node(id, left, right) })
data class Node(val id: String, val left: String, val right: String)
private fun Node.next(instruction: Char): Node = when (instruction) {
'L' -> left
'R' -> right
else -> error(instruction)
}.let(network::getValue)
fun part1(): Int {
var node = network.getValue("AAA")
return instructions.asSequence().infinite().indexOfFirst {
node.next(it).also { next ->
node = network[next.id]!!
}.id == "ZZZ"
}.inc()
}
fun part2(): Long = buildMap stepsByNodes@{
val nodes = network.values.filter { it.id.endsWith('A') }.map { it to it }.toMutableList()
instructions.asSequence().infinite().forEachIndexed { index, instruction ->
nodes.replaceAll { (start, current) -> start to current.next(instruction) }
nodes.removeAll { (start, current) -> current.id.endsWith('Z').also { if (it) put(start, index.inc()) } }
if (nodes.isEmpty()) return@stepsByNodes
}
}.map { it.value.toLong() }.reduce(::lcm)
}
| 0 | Kotlin | 0 | 1 | 043fbdb271603c84b7e5eddcd0e8f323c6ebdf1e | 1,322 | advent-of-code-2023 | MIT License |
src/main/kotlin/day07/Day07.kt | Malo-T | 575,370,082 | false | null | package day07
data class File(
val name: String,
val size: Int,
)
data class Directory(
val name: String,
val directories: MutableList<Directory> = mutableListOf(),
val files: MutableList<File> = mutableListOf(),
) {
// must not be in the constructor
lateinit var parent: Directory
fun size(): Int = files.sumOf { it.size } + directories.sumOf { it.size() }
fun children(): List<Directory> = directories + directories.flatMap { it.children() }
}
private fun root() = Directory(name = "/").apply { parent = this }
/** Return parent or child directory depending on command */
private fun Directory.cd(cmd: String): Directory =
when (val dir = cmd.substring(5)) {
".." -> parent
else -> directories.firstOrNull { it.name == dir }
?: Directory(name = dir)
.apply { parent = this@cd }
.also { directories.add(it) }
}
/** Create and add file to current directory. Return current directory */
private fun Directory.addFile(path: String): Directory = apply {
val (size, name) = path.split(' ')
if (files.none { it.name == name }) {
files += File(
name = name,
size = size.toInt()
)
}
}
class Day07 {
fun parse1(input: String): Directory =
root().apply {
input.lines()
.drop(1) // first line is "$ cd /" -> root
.fold(this) { dir, line ->
when {
line == "$ ls" -> dir// do nothing
line.startsWith("$ cd ") -> dir.cd(line)// move to directory (create it if necessary)
line.startsWith("dir ") -> dir // do nothing (directories are created on 'cd')
line[0].isDigit() -> dir.addFile(line)// add file to directory
else -> throw IllegalStateException("Invalid line: $line")
}
}
}
fun part1(root: Directory): Int =
root.children()
.map { it.size() }
.filter { it < 100_000 }
.sum()
fun part2(root: Directory): Int {
TODO()
}
}
| 0 | Kotlin | 0 | 0 | f4edefa30c568716e71a5379d0a02b0275199963 | 2,183 | AoC-2022 | Apache License 2.0 |
day19/src/main/kotlin/Main.kt | rstockbridge | 159,586,951 | false | null | import java.io.File
import java.lang.IllegalStateException
fun main() {
val partIDevice = parseInput(readInputFilePartI())
println("Part I: the solution is ${solvePartI(partIDevice)}.")
println("Part II: the solution is ${solvePartII(10551339)}.")
}
fun readInputFilePartI(): List<String> {
return File(ClassLoader.getSystemResource("input.txt").file).readLines()
}
fun parseInput(input: List<String>): Device {
val boundRegisterRegex = "#ip (\\d)".toRegex()
val (boundRegister) = boundRegisterRegex.matchEntire(input[0])!!.destructured.toList().map(String::toInt)
val instructionInput = input.toMutableList()
instructionInput.removeAt(0)
val instructionRegex = "([a-z]+) (\\d+) (\\d+) (\\d+)".toRegex()
val instructions = instructionInput
.map { instruction ->
val (opcodeAsString, a, b, c) = instructionRegex.matchEntire(instruction)!!.destructured
Instruction.fromInput(opcodeAsString, a.toInt(), b.toInt(), c.toInt())
}
return Device(boundRegister = boundRegister, instructions = instructions)
}
fun solvePartI(device: Device): Int {
while (device.instructionPointer < device.instructions.size) {
val instruction = device.instructions[device.instructionPointer]
device.registers[device.boundRegister] = device.instructionPointer
instruction.opcode.applyTo(device.registers, instruction.a, instruction.b, instruction.c)
device.instructionPointer = device.registers[device.boundRegister]
device.instructionPointer++
}
return device.registers[0]
}
fun solvePartII(number: Int): Int {
// device calculates the sum of all the factors of the input number
var result = 0
for (i in 1..number) {
if (number % i == 0) {
result += i
}
}
return result
}
data class Device(var registers: MutableList<Int> = mutableListOf(0, 0, 0, 0, 0, 0),
val boundRegister: Int,
var instructionPointer: Int = 0,
val instructions: List<Instruction>)
data class Instruction(val opcode: Opcode, val a: Int, val b: Int, val c: Int) {
companion object {
fun fromInput(opcodeString: String, a: Int, b: Int, c: Int): Instruction {
val opcode = when (opcodeString) {
"addr" -> Opcode.ADDR
"addi" -> Opcode.ADDI
"mulr" -> Opcode.MULR
"muli" -> Opcode.MULI
"banr" -> Opcode.BANR
"bani" -> Opcode.BANI
"borr" -> Opcode.BORR
"bori" -> Opcode.BORI
"setr" -> Opcode.SETR
"seti" -> Opcode.SETI
"gtir" -> Opcode.GTIR
"gtri" -> Opcode.GTRI
"gtrr" -> Opcode.GTRR
"eqir" -> Opcode.EQIR
"eqri" -> Opcode.EQRI
"eqrr" -> Opcode.EQRR
else -> {
throw IllegalStateException("This line should not be reached.")
}
}
return Instruction(opcode, a, b, c)
}
}
}
| 0 | Kotlin | 0 | 0 | c404f1c47c9dee266b2330ecae98471e19056549 | 3,148 | AdventOfCode2018 | MIT License |
src/Day03.kt | cak | 573,455,947 | false | {"Kotlin": 8236} | fun main() {
val abc = "abcdefghijklmnopqrstuvwxyz"
val chars = abc + abc.uppercase()
fun part1(input: List<String>): Int {
val result = input
.map { it.trim().toCharArray().toList() }
.map {
Pair(it.subList(0, it.size / 2), it.subList(it.size / 2, it.size))
}.sumOf { pair ->
pair.first
.intersect(pair.second.toSet())
.sumOf { (chars.indexOf(it) + 1) }
}
return result
}
fun part2(input: List<String>): Int {
val result = input
.map { it.trim().toCharArray().toList() }.chunked(3)
.flatMap { lists ->
lists[0]
.intersect(lists[1].toSet()).intersect(lists[2].toSet())
}.sumOf { (chars.indexOf(it) + 1) }
return result
}
val testInput = getTestInput()
check(part1(testInput) == 157)
val input = getInput()
check(part2(testInput) == 70)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | cab2dffae8c1b78405ec7d85e328c514a71b21f1 | 1,065 | advent-of-code-2022 | Apache License 2.0 |
lib/src/main/kotlin/utils/Graph.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | package utils
import java.util.ArrayDeque
import java.util.PriorityQueue
import java.util.concurrent.atomic.AtomicLong
class Graph<Node : Any, Edge: Any>(
val edgeFn: (Node) -> List<Pair<Edge, Node>>,
val weightFn: (Edge) -> Int = { 1 },
val nodes: Set<Node>? = null,
) {
fun dfs(start: Node, visit: (Node) -> Boolean): List<Node> {
val queue = ArrayDeque<Pair<Node, Int>>()
queue.add(start to 0)
val backtrace = mutableListOf(start)
while (queue.isNotEmpty()) {
val (node, depth) = queue.removeLast()
if (backtrace.size < depth + 1) {
backtrace.add(node)
} else {
backtrace[depth] = node
}
if (visit(node)) {
return backtrace.take(depth + 1)
}
edgeFn(node).forEach { (_, nextNode) ->
queue.add(nextNode to depth+1)
}
}
return emptyList()
}
fun shortestPath(start: Node, end: Node, heuristic: (Node) -> Int = { _ -> 0 }): Pair<Int, List<Pair<Node, Edge?>>> {
return shortestPath(start, heuristic = heuristic, end = { it == end })
}
fun shortestPath(
start: Node,
heuristic: (Node) -> Int = { _ -> 0 },
end: (Node) -> Boolean,
): Pair<Int, List<Pair<Node, Edge?>>> {
val queue = PriorityQueue<Pair<Node, Int>>(compareBy { it.second })
queue.add(start to 0)
val src = mutableMapOf<Node, Pair<Node, Edge>?>(start to null)
val cost = mutableMapOf(start to 0)
val counter = AtomicLong(0)
while (queue.isNotEmpty()) {
val (node, currentRisk) = queue.remove()
if (counter.incrementAndGet() % 1000000 == 0L) {
println("--- states ---")
println("Visited ${counter.get()} nodes")
println("Current node: cost=$currentRisk node=$node heuristic=${heuristic(node)}")
}
if (end(node)) {
var btnode = src[node]
val bt = mutableListOf<Pair<Node, Edge?>>(node to null)
while (btnode != null) {
bt += btnode
btnode = src[btnode.first]
}
return cost[node]!! to bt
}
edgeFn(node).forEach { (edge, nextNode) ->
val newNextCost = cost[node]!! + weightFn(edge)
val nextCost = cost[nextNode]
if (nextCost == null || newNextCost < nextCost) {
cost[nextNode] = newNextCost
src[nextNode] = node to edge
queue.add(nextNode to (newNextCost + heuristic(nextNode)))
}
}
}
throw IllegalStateException("No path from $start to $end")
}
fun shortestTour(): Int {
if (nodes == null) throw IllegalStateException("Cannot compute tour without nodes")
return nodes
.mapNotNull { shortestTour(it, nodes - it) }
.minOrNull()!!
}
fun longestTour(): Int {
if (nodes == null) throw IllegalStateException("Cannot compute tour without nodes")
return nodes
.mapNotNull { longestTour(it, nodes - it) }
.maxOrNull()!!
}
private fun shortestTour(from: Node, nodes: Set<Node>): Int? {
if (nodes.isEmpty()) return 0
return edgeFn(from)
.filter { (_, node) -> node in nodes }
.map { (edge, node) -> edge to shortestTour(node, nodes - node) }
.filter { (_, tour) -> tour != null }
.minOfOrNull { (edge, tour) -> weightFn(edge) + tour!! }
}
private fun longestTour(from: Node, nodes: Set<Node>): Int? {
if (nodes.isEmpty()) return 0
return edgeFn(from)
.filter { (_, node) -> node in nodes }
.map { (edge, node) -> edge to longestTour(node, nodes - node) }
.filter { (_, tour) -> tour != null }
.maxOfOrNull { (edge, tour) -> weightFn(edge) + tour!! }
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 3,601 | aoc_kotlin | MIT License |
src/questions/RegionsCutBySlashes.kt | realpacific | 234,499,820 | false | null | package questions
import _utils.UseCommentAsDocumentation
import utils.shouldBe
private const val LEFT = '/'
private const val RIGHT = '\\'
/**
* An n x n grid is composed of 1 x 1 squares where each 1 x 1 square consists of a '/', '\', or blank space ' '.
* These characters divide the square into contiguous regions.
* Given the grid `grid` represented as a string array, return the number of regions.
* Note that backslash characters are escaped, so a '\' is represented as '\\'.
*
* [Explanation](https://www.youtube.com/watch?v=Wafu5vOxPRE) – [Source](https://leetcode.com/problems/regions-cut-by-slashes/)
*/
@UseCommentAsDocumentation
private fun regionsBySlashes(grid: Array<String>): Int {
val dots = grid.size + 1
// this is basically a union find problem
// if there's a cycle, then add one to the result
val unionFind = UnionFind(dots)
// Connect the borders
for (i in 0 until dots) {
for (j in 0 until dots) {
if (i == 0 || i == dots - 1 || j == 0 || j == dots - 1) {
val cellNo = i * dots + j
if (cellNo != 0)
unionFind.union(0, cellNo)
}
}
}
// the border is a region
var result = 1
for (i in 0..grid.lastIndex) {
val row = grid[i].toCharArray()
for (j in 0..row.lastIndex) {
val isCycle = when (row[j]) {
LEFT -> {
val cellNoTop = (i * dots) + (j + 1)
val cellNoBottom = (i + 1) * dots + (j)
unionFind.union(cellNoTop, cellNoBottom)
}
RIGHT -> {
val cellNoTop = (i * dots) + (j)
val cellNoBottom = (i + 1) * dots + (j + 1)
unionFind.union(cellNoTop, cellNoBottom)
}
else -> {
false
}
}
if (isCycle) {
result++
}
}
}
return result
}
private class UnionFind(n: Int) {
private val parent = Array(n * n) { it }
private val rank = Array(n * n) { 1 }
fun union(x: Int, y: Int): Boolean {
val lx = find(x)
val ly = find(y)
if (lx == ly) {
return true
}
if (rank[lx] == rank[ly]) {
parent[lx] = ly
rank[ly]++
} else if (rank[lx] > rank[ly]) {
parent[ly] = lx
} else if (rank[lx] < rank[ly]) {
parent[lx] = ly
}
return false
}
fun find(x: Int): Int {
if (parent[x] == x) {
return x
}
val temp = find(parent[x])
parent[x] = temp
return temp
}
}
fun main() {
regionsBySlashes(arrayOf(" /", "/ ")) shouldBe 2
regionsBySlashes(arrayOf(" /", " ")) shouldBe 1
regionsBySlashes(arrayOf("\\/", "/\\")) shouldBe 4
regionsBySlashes(arrayOf("/\\", "\\/")) shouldBe 5
regionsBySlashes(arrayOf("//", "/ ")) shouldBe 3
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 3,027 | algorithms | MIT License |
src/main/kotlin/g2801_2900/s2801_count_stepping_numbers_in_range/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2801_2900.s2801_count_stepping_numbers_in_range
// #Hard #String #Dynamic_Programming #2024_01_19_Time_288_ms_(100.00%)_Space_38.2_MB_(100.00%)
import kotlin.math.abs
class Solution {
private lateinit var dp: Array<Array<Array<Array<Int?>>>>
fun countSteppingNumbers(low: String, high: String): Int {
dp = Array(low.length + 1) { Array(10) { Array(2) { arrayOfNulls(2) } } }
val count1 = solve(low, 0, 0, 1, 1)
dp = Array(high.length + 1) { Array(10) { Array(2) { arrayOfNulls(2) } } }
val count2 = solve(high, 0, 0, 1, 1)
return (count2!! - count1!! + isStep(low) + MOD) % MOD
}
private fun solve(s: String, i: Int, prevDigit: Int, hasBound: Int, curIsZero: Int): Int? {
if (i >= s.length) {
if (curIsZero == 1) {
return 0
}
return 1
}
if (dp[i][prevDigit][hasBound][curIsZero] != null) {
return dp[i][prevDigit][hasBound][curIsZero]
}
var count = 0
var limit = 9
if (hasBound == 1) {
limit = s[i].code - '0'.code
}
for (digit in 0..limit) {
val nextIsZero = if ((curIsZero == 1 && digit == 0)) 1 else 0
val nextHasBound = if ((hasBound == 1 && digit == limit)) 1 else 0
if (curIsZero == 1 || abs(digit - prevDigit) == 1) {
count = (count + solve(s, i + 1, digit, nextHasBound, nextIsZero)!!) % MOD
}
}
dp[i][prevDigit][hasBound][curIsZero] = count
return dp[i][prevDigit][hasBound][curIsZero]
}
private fun isStep(s: String): Int {
var isValid = true
for (i in 0 until s.length - 1) {
if (abs((s[i + 1].code - s[i].code)) != 1) {
isValid = false
break
}
}
if (isValid) {
return 1
}
return 0
}
companion object {
private const val MOD = (1e9 + 7).toInt()
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,012 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/advent/day8/SevenSegmentSearch.kt | hofiisek | 434,171,205 | false | {"Kotlin": 51627} | package advent.day8
import advent.loadInput
import java.io.File
/**
* @author <NAME>
*/
/*
0: 1: 2: 3: 4:
aaaa .... aaaa aaaa ....
b c . c . c . c b c
b c . c . c . c b c
.... .... dddd dddd dddd
e f . f e . . f . f
e f . f e . . f . f
gggg .... gggg gggg ....
5: 6: 7: 8: 9:
aaaa aaaa aaaa aaaa aaaa
b . b . . c b c b c
b . b . . c b c b c
dddd dddd .... dddd dddd
. f e f . f e f . f
. f e f . f e f . f
gggg gggg .... gggg gggg
Unique-segment-length numbers: 1, 4, 7, 8
- 2-segment-length: 1
- 3-segment-length: 7
- 4-segment-length: 4
- 8-segment-length: 8
5-segment-length numbers: 2, 3, 5
6-segment-length numbers: 0, 6, 9
*/
fun part1(input: File) = input.readLines()
.map { it.split(" | ") }
.flatMap { (_, output) -> output.split(" ") }
.count { listOf(2, 3, 4, 7).contains(it.length) }
fun String.toNumber() = when (this) {
"abcefg" -> 0
"cf" -> 1
"acdeg" -> 2
"acdfg" -> 3
"bcdf" -> 4
"abdfg" -> 5
"abdefg" -> 6
"acf" -> 7
"abcdefg" -> 8
"abcdfg" -> 9
else -> throw IllegalArgumentException("Unknown combination of segments: $this")
}
fun String.isNotSingleChar() = length == 0 || length > 1
infix fun String.containsAll(other: String) = other.all { contains(it) }
infix fun String.except(chars: String): String = filterNot { chars.contains(it) }
infix fun String.singleCommonCharWith(other: String): String =
singleOrNull { other.contains(it) }
?.toString()
?: throw IllegalArgumentException("$this has more than 1 common chars with $other")
fun Map<Char, String>.getValues(vararg chars: Char): String = chars
.map(this::get)
.filterNotNull()
.distinct()
.joinToString("")
fun part2(input: File) =
input.readLines()
.map { it.split(" | ") }
.map { (inputStr, outputStr) -> inputStr.split(" ") to outputStr.split(" ") }
.sumOf { (input, output) ->
val charToSegment = input
.sortedBy { it.length }
.fold(emptyMap<Char, String>()) { charToSegment, signals ->
when (signals.length) {
2 -> mapOf('c' to signals, 'f' to signals) // number 1
3 -> {
// number 7
val uniqueCharLeft = signals except charToSegment.getValue('c')
charToSegment + mapOf('a' to uniqueCharLeft)
}
4 -> {
// number 4
val possibleChars = signals except charToSegment.getValue('c')
charToSegment + mapOf('b' to possibleChars, 'd' to possibleChars)
}
5 -> {
charToSegment + when {
signals containsAll charToSegment.getValues('c', 'f') -> {
// must be number 3
val commonCharWith4 = signals singleCommonCharWith charToSegment.getValues('b', 'd')
val uniqueCharOf4 = charToSegment.getValue('b') except commonCharWith4
val uniqueCharLeft = signals except charToSegment.getValues('a', 'c', 'd', 'f')
mapOf(
'b' to uniqueCharOf4,
'd' to commonCharWith4,
'g' to uniqueCharLeft
)
}
signals containsAll charToSegment.getValues('b', 'd') -> {
// must be number 5
val comonCharWith1 = signals singleCommonCharWith charToSegment.getValues('c', 'f')
val uniqueCharOf1 = charToSegment.getValue('c') except comonCharWith1
val uniqueCharLeft = signals except charToSegment.getValues('a', 'b', 'd', 'f')
mapOf(
'c' to uniqueCharOf1,
'f' to comonCharWith1,
'g' to uniqueCharLeft
)
}
else -> {
// must be number 2
val commonCharWith1 = signals singleCommonCharWith charToSegment.getValues('c', 'f')
val commonCharWith4 = signals singleCommonCharWith charToSegment.getValues('b', 'd')
val unambiguousCharsLeft = signals except charToSegment.getValues('a', 'c', 'd')
buildMap {
put('c', commonCharWith1)
put('d', commonCharWith4)
if (charToSegment.getValues('e').isNotSingleChar())
put('e', unambiguousCharsLeft)
if (charToSegment.getValues('g').isNotSingleChar())
put('g', unambiguousCharsLeft)
}
}
}
}
6 -> charToSegment + when {
signals containsAll charToSegment.getValues('a', 'b', 'c', 'd', 'f') -> {
// must be number 9
val uniqueCharOfG = signals except charToSegment.getValues('a', 'b', 'c', 'd', 'f')
val uniqueCharOfE = (charToSegment.getValue('e') except uniqueCharOfG)
mapOf(
'e' to uniqueCharOfE,
'g' to uniqueCharOfG
)
}
else -> emptyMap()
}
7 -> charToSegment // all chars are known at this point
else -> throw IllegalArgumentException("Invalid length of signals: $signals")
}
}
.map { (segment, chars) -> chars.first() to segment }
.toMap()
output
.map { it.map(charToSegment::getValue).sorted().joinToString("").toNumber() }
.joinToString("")
.toInt()
}
fun main() {
// with(loadInput(day = 8, filename = "input_example.txt")) {
// with(loadInput(day = 8, filename = "input_example_single.txt")) {
with(loadInput(day = 8)) {
println(part1(this))
println(part2(this))
}
} | 0 | Kotlin | 0 | 2 | 3bd543ea98646ddb689dcd52ec5ffd8ed926cbbb | 7,243 | Advent-of-code-2021 | MIT License |
src/Day08.kt | seana-zr | 725,858,211 | false | {"Kotlin": 28265} | fun main() {
data class Branch(
val left: String,
val right: String
)
fun part1(input: List<String>): Int {
var result = 0
val directions = input[0]
val mapInput = input.drop(2)
val map = mutableMapOf<String, Branch>()
mapInput.forEach {
val key = it.substring(0..2)
val left = it.substring(7..9)
val right = it.substring(12..14)
map[key] = Branch(left, right)
}
var directionIndex = 0
var location = "AAA"
while (location != "ZZZ") {
if (directions[directionIndex] == 'L') {
location = map[location]!!.left
} else {
location = map[location]!!.right
}
result++
directionIndex = (directionIndex + 1) % (directions.length)
}
println("RESULT: $result")
return result
}
fun String.getLoop(map: Map<String, Branch>, directions: String): Int {
var result = 0
var directionIndex = 0
var location = this
while (location.last() != 'Z') {
if (directions[directionIndex] == 'L') {
location = map[location]!!.left
} else {
location = map[location]!!.right
}
result++
directionIndex = (directionIndex + 1) % (directions.length)
}
return result
}
fun calculateLCM(numbers: LongArray): Long {
// Function to find the GCD of two numbers using Euclidean algorithm
fun findGCD(a: Long, b: Long): Long {
return if (b == 0.toLong()) a else findGCD(b, a % b)
}
// Function to find the LCM of two numbers
fun findLCMOfTwo(a: Long, b: Long): Long {
return (a * b) / findGCD(a, b)
}
// Function to find the LCM of an array of numbers
fun findLCMOfArray(numbers: LongArray, index: Int, currentLCM: Long): Long {
return if (index == numbers.size) {
currentLCM
} else {
val currentNumber = numbers[index]
val gcd = findGCD(currentLCM, currentNumber)
val lcm = (currentLCM * currentNumber) / gcd
findLCMOfArray(numbers, index + 1, lcm)
}
}
// Check if the array has at least two elements
if (numbers.size < 2) {
throw IllegalArgumentException("Array must have at least two elements.")
}
// Start with the LCM of the first two numbers
val initialLCM = findLCMOfTwo(numbers[0], numbers[1])
// Find the LCM of the remaining numbers in the array
return findLCMOfArray(numbers, 2, initialLCM)
}
fun part2(input: List<String>): Long {
var result = 0.toLong()
val directions = input[0]
val mapInput = input.drop(2)
val map = mutableMapOf<String, Branch>()
val trackedNodes = mutableListOf<String>()
mapInput.forEach {
val key = it.substring(0..2)
val left = it.substring(7..9)
val right = it.substring(12..14)
map[key] = Branch(left, right)
if (key.last() == 'A') trackedNodes.add(key)
}
val loops = trackedNodes
.map { node -> node.getLoop(map, directions).toLong() }
println(trackedNodes)
println(loops)
// https://www.calculatorsoup.com/calculators/math/lcm.php
result = calculateLCM(loops.toLongArray())
println("RESULT: $result")
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 2)
val testInput2 = readInput("Day08_test_2")
check(part1(testInput2) == 6)
val testInput3 = readInput("Day08_test_3")
check(part2(testInput3) == 6.toLong())
val input = readInput("Day08")
// part1(input).println()
part2(input).println()
} | 0 | Kotlin | 0 | 0 | da17a5de6e782e06accd3a3cbeeeeb4f1844e427 | 4,041 | advent-of-code-kotlin-template | Apache License 2.0 |
hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_12935.kt | boris920308 | 618,428,844 | false | {"Kotlin": 137657, "Swift": 35553, "Java": 1947, "Rich Text Format": 407} | package main.kotlin.programmers.lv01
/**
*
* https://school.programmers.co.kr/learn/courses/30/lessons/12935
*
* 문제 설명
* 정수를 저장한 배열, arr 에서 가장 작은 수를 제거한 배열을 리턴하는 함수, solution을 완성해주세요.
* 단, 리턴하려는 배열이 빈 배열인 경우엔 배열에 -1을 채워 리턴하세요.
* 예를들어 arr이 [4,3,2,1]인 경우는 [4,3,2]를 리턴 하고, [10]면 [-1]을 리턴 합니다.
*
* 제한 조건
* arr은 길이 1 이상인 배열입니다.
* 인덱스 i, j에 대해 i ≠ j이면 arr[i] ≠ arr[j] 입니다.
* 입출력 예
* arr return
* [4,3,2,1] [4,3,2]
* [10] [-1]
*/
fun main() {
solution(intArrayOf(4,3,2,1))
solution(intArrayOf(10))
solution(intArrayOf())
}
private fun solution(arr: IntArray): IntArray {
if (arr.isEmpty()) return intArrayOf(-1)
var answer = intArrayOf()
var minValue = arr.first();
arr.forEach {
if (it < minValue) {
minValue = it
}
}
answer = arr.filter { it != minValue }.toIntArray()
if (answer.isEmpty()) return intArrayOf(-1)
return answer
}
//private fun solution_1(arr: IntArray): IntArray {
// if (arr.size == 1) return intArrayOf(-1)
// return arr.sorted().toIntArray().copyOfRange(1, arr.size);
//}
private fun solution_2(arr: IntArray): IntArray = if(arr.size == 1) intArrayOf(-1)
else arr.filter { it != arr.min() }.toIntArray() | 1 | Kotlin | 1 | 2 | 88814681f7ded76e8aa0fa7b85fe472769e760b4 | 1,520 | HoOne | Apache License 2.0 |
advent-of-code-2022/src/main/kotlin/eu/janvdb/aoc2022/day05/Day05.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2022.day05
import eu.janvdb.aocutil.kotlin.readGroupedLines
//const val FILENAME = "input05-test.txt"
const val FILENAME = "input05.txt"
val INSTRUCTION_REGEX = Regex("move (\\d+) from (\\d+) to (\\d+)")
fun main() {
val lines = readGroupedLines(2022, FILENAME)
val crates = Crates.parse(lines[0])
val instructions = lines[1].map(String::toInstruction)
runPart(crates, instructions, Crates::moveOneByOne)
runPart(crates, instructions, Crates::moveAllAtOnce)
}
private fun runPart(
crates: Crates, instructions: List<Instruction>,
mapper: (crates: Crates, instruction: Instruction) -> Crates
) {
var currentCrates = crates
for (instruction in instructions) {
currentCrates = mapper.invoke(currentCrates, instruction)
}
println(currentCrates.tops())
}
data class Crates(private val stacks: List<List<Char>> = listOf()) {
fun addTo(pos: Int, ch: Char): Crates {
val newStacks = stacks.toMutableList()
while (newStacks.size <= pos) newStacks.add(listOf())
newStacks[pos] = newStacks[pos] + ch
return Crates(newStacks)
}
fun moveOneByOne(instruction: Instruction): Crates {
val newStacks = stacks.map { it.toMutableList() }
for (i in 1..instruction.numberOfCrates) {
val crate = newStacks[instruction.from - 1].removeLast()
newStacks[instruction.to - 1].add(crate)
}
return Crates(newStacks)
}
fun moveAllAtOnce(instruction: Instruction): Crates {
val newStacks = stacks.toMutableList()
val fromStack = newStacks[instruction.from - 1]
val cratesToMove = fromStack.subList(fromStack.size - instruction.numberOfCrates, fromStack.size)
newStacks[instruction.from - 1] = fromStack.subList(0, fromStack.size - instruction.numberOfCrates)
newStacks[instruction.to - 1] = newStacks[instruction.to - 1] + cratesToMove
return Crates(newStacks)
}
fun tops(): String {
return stacks.map { it.last() }.joinToString("")
}
companion object {
fun parse(lines: List<String>): Crates {
var result = Crates()
lines.reversed().forEach { line ->
line.toCharArray()
.mapIndexed { index, ch -> Pair(index, ch) }
.filter { it.second.isLetter() }
.forEach {
val crateIndex = (it.first - 1) / 4
result = result.addTo(crateIndex, it.second)
}
}
return result
}
}
}
data class Instruction(val numberOfCrates: Int, val from: Int, val to: Int) {
}
fun String.toInstruction(): Instruction {
val match = INSTRUCTION_REGEX.matchEntire(this) ?: throw IllegalArgumentException(this)
return Instruction(match.groupValues[1].toInt(), match.groupValues[2].toInt(), match.groupValues[3].toInt())
} | 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 2,944 | advent-of-code | Apache License 2.0 |
src/Day09.kt | zdenekobornik | 572,882,216 | false | null | import kotlin.math.abs
import kotlin.math.sign
fun main() {
data class Point(var x: Int, var y: Int)
fun printMap(points: List<Point>) {
for (y in -5..0) {
for (x in 0..6) {
val index = points.indexOf(Point(x, y))
if (index == 0) {
print("H")
} else if (index != -1) {
print(index)
} else if (x == 0 && y == 0) {
print("S")
} else if (index == -1) {
print(".")
}
}
println()
}
println()
println("--------------- ---------- ")
println()
}
fun part1(input: List<String>): Int {
val commands = input.map {
val (move, count) = it.split(' ')
move.first() to count.toInt()
}
val head = Point(0, 0)
val tail = Point(0, 0)
val visited = mutableSetOf<Point>()
for ((move, count) in commands) {
repeat(count) {
val prevHead = head.copy()
when (move) {
'R' -> head.x++
'U' -> head.y--
'L' -> head.x--
'D' -> head.y++
}
val dx = head.x - tail.x
val dy = head.y - tail.y
if (abs(dx) > 1 || abs(dy) > 1) {
tail.x = prevHead.x
tail.y = prevHead.y
}
visited.add(tail.copy())
}
}
return visited.count()
}
fun part2(input: List<String>): Int {
val commands = input.map {
val (move, count) = it.split(' ')
move.first() to count.toInt()
}
val points = (1..10).map { Point(0, 0) }
val head = points[0]
val visited = mutableSetOf<Point>()
for ((move, count) in commands) {
repeat(count) {
when (move) {
'R' -> head.x++
'U' -> head.y--
'L' -> head.x--
'D' -> head.y++
}
for (index in 1 until points.size) {
val prevPoint = points[index - 1]
val point = points[index]
val dx = prevPoint.x - point.x
val dy = prevPoint.y - point.y
if (abs(dx) > 1 || abs(dy) > 1) {
point.x = point.x + dx.sign
point.y = point.y + dy.sign
}
}
visited.add(points.last().copy())
}
}
return visited.count()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
checkResult(part1(testInput), 13)
val testInput2 = readInput("Day09_test2")
checkResult(part2(testInput2), 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f73e4a32802fa43b90c9d687d3c3247bf089e0e5 | 3,096 | advent-of-code-2022 | Apache License 2.0 |
2021/src/day13/day13.kt | scrubskip | 160,313,272 | false | {"Kotlin": 198319, "Python": 114888, "Dart": 86314} | package day13
import java.io.File
fun main() {
val data = parseInput(File("src/day13", "day13input.txt").readLines())
var board = data.first
for (instruction in data.second) {
println("folding $instruction ${board.size}")
board = foldAlong(board, instruction.first, instruction.second)
}
println(board.size)
printOutput(board)
}
fun parseInput(input: List<String>): Pair<Set<Pair<Int, Int>>, List<Pair<Char, Int>>> {
val pointSet = mutableSetOf<Pair<Int, Int>>()
val instructionList = mutableListOf<Pair<Char, Int>>()
val splitList = input.filter { it.isNotBlank() }
.partition { !it.startsWith("fold along") }
pointSet.addAll(splitList.first.map {
with(it.split(",").map { coordinate -> coordinate.toInt() }) {
Pair(get(0), get(1))
}
})
instructionList.addAll(splitList.second.map { instruction ->
instruction.indexOf("=").let {
Pair(instruction[it - 1], instruction.substring(it + 1).toInt())
}
})
return Pair(pointSet, instructionList)
}
fun foldAlong(data: Set<Pair<Int, Int>>, axis: Char, coordinate: Int): Set<Pair<Int, Int>> {
// Iterate through the points. If a point is > the axis / coordinate,
// add its mirror, otherwise just add the point
val returnSet = mutableSetOf<Pair<Int, Int>>()
for (point in data) {
var x = point.first
var y = point.second
when (axis) {
'x' -> if (point.first > coordinate) x = coordinate - (x - coordinate)
'y' -> if (point.second > coordinate) y = coordinate - (y - coordinate)
}
returnSet.add(Pair(x, y))
}
return returnSet
}
fun printOutput(data: Set<Pair<Int, Int>>) {
// find max x and max y
var maxX: Int = 0
var maxY: Int = 0
data.forEach {
if (it.first > maxX) maxX = it.first
if (it.second > maxY) maxY = it.second
}
for (row in 0..maxY) {
println((0..maxX).joinToString(separator = "", postfix = "") {
when (data.contains(Pair(it, row))) {
true -> "#"
false -> "."
}
})
}
} | 0 | Kotlin | 0 | 0 | a5b7f69b43ad02b9356d19c15ce478866e6c38a1 | 2,174 | adventofcode | Apache License 2.0 |
day17/Part2.kt | anthaas | 317,622,929 | false | null | import java.io.File
private const val ALIVE = '#'
fun main(args: Array<String>) {
val input = File("input.txt").readLines()
var aliveCells =
input.mapIndexed { x, s ->
s.toCharArray().mapIndexed { y, c -> if (c == ALIVE) listOf(x, y, 0, 0) else emptyList() }
.filter { it.isNotEmpty() }
}.flatten()
for (i in (1..6)) {
aliveCells = evolve(aliveCells)
println("end of cycle $i")
}
println(aliveCells.size)
}
private fun evolve(aliveCells: List<List<Int>>): List<List<Int>> =
aliveCells.map { getNeighborsPosition(it[0], it[1], it[2], it[3]) }.flatten().distinct().mapNotNull {
val aliveNeighbors = getNeighborsPosition(it[0], it[1], it[2], it[3]).map { it in aliveCells }.count { it }
when {
(it in aliveCells && (aliveNeighbors == 2 || aliveNeighbors == 3)) -> it
(it !in aliveCells && aliveNeighbors == 3) -> it
else -> null
}
}
private fun getNeighborsPosition(x: Int, y: Int, z: Int, w: Int): List<List<Int>> {
val result = mutableListOf<List<Int>>()
(-1..1).map { a ->
(-1..1).map { b ->
(-1..1).map { c ->
(-1..1).map { d ->
if (!(a == 0 && b == 0 && c == 0 && d == 0)) result.add(listOf(x + a, y + b, z + c, w + d))
}
}
}
}
return result
}
| 0 | Kotlin | 0 | 0 | aba452e0f6dd207e34d17b29e2c91ee21c1f3e41 | 1,408 | Advent-of-Code-2020 | MIT License |
src/day08/Forest.kt | treegem | 572,875,670 | false | {"Kotlin": 38876} | package day08
class Forest(input: List<String>) {
private val treeHeights: Array<IntArray> = input.to2dArray()
private val indices1d = treeHeights.indices
private val trees = indices1d.map { row ->
indices1d.map { column ->
Tree(
height = treeHeights[row][column],
row = row,
column = column
)
}
}.flatten()
fun countVisibleTreesFromOutside() = trees.map(::isVisible).count { it }
fun calculateMaxScenicScore() = trees.maxOfOrNull(::calculateScenicScore)!!
private fun calculateScenicScore(tree: Tree) =
countVisibleTreesAbove(tree) *
countVisibleTreesBelow(tree) *
countVisibleTreesToTheLeft(tree) *
countVisibleTreesToTheRight(tree)
private fun countVisibleTreesAbove(tree: Tree): Int {
var currentRow = tree.row + 1
var visibleTrees = 0
while (currentRow in indices1d) {
visibleTrees += 1
if (treeHeights[currentRow][tree.column] >= tree.height) break
currentRow += 1
}
return visibleTrees
}
private fun countVisibleTreesBelow(tree: Tree): Int {
var currentRow = tree.row - 1
var visibleTrees = 0
while (currentRow in indices1d) {
visibleTrees += 1
if (treeHeights[currentRow][tree.column] >= tree.height) break
currentRow -= 1
}
return visibleTrees
}
private fun countVisibleTreesToTheLeft(tree: Tree): Int {
var currentColumn = tree.column - 1
var visibleTrees = 0
while (currentColumn in indices1d) {
visibleTrees += 1
if (treeHeights[tree.row][currentColumn] >= tree.height) break
currentColumn -= 1
}
return visibleTrees
}
private fun countVisibleTreesToTheRight(tree: Tree): Int {
var currentColumn = tree.column + 1
var visibleTrees = 0
while (currentColumn in indices1d) {
visibleTrees += 1
if (treeHeights[tree.row][currentColumn] >= tree.height) break
currentColumn += 1
}
return visibleTrees
}
private fun isVisible(tree: Tree) = when {
isOnEdge(tree)
|| isVisibleFromAbove(tree)
|| isVisibleFromBelow(tree)
|| isVisibleFromLeft(tree)
|| isVisibleFromRight(tree) -> true
else -> false
}
private fun isVisibleFromAbove(tree: Tree) =
(0 until tree.row).map { treeHeights[it][tree.column] }.all { it < tree.height }
private fun isVisibleFromBelow(tree: Tree) =
(tree.row + 1..indices1d.last).map { treeHeights[it][tree.column] }.all { it < tree.height }
private fun isVisibleFromLeft(tree: Tree) =
(0 until tree.column).map { treeHeights[tree.row][it] }.all { it < tree.height }
private fun isVisibleFromRight(tree: Tree) =
(tree.column + 1..indices1d.last).map { treeHeights[tree.row][it] }.all { it < tree.height }
private fun isOnEdge(tree: Tree) =
listOf(tree.row, tree.column).any { it == 0 || it == indices1d.last }
}
private fun List<String>.to2dArray(): Array<IntArray> =
this.map { it.toCharArray() }
.map { charArray -> charArray.map { it.toString() }.toTypedArray() }
.map { stringArray -> stringArray.map { it.toInt() }.toIntArray() }
.toTypedArray()
| 0 | Kotlin | 0 | 0 | 97f5b63f7e01a64a3b14f27a9071b8237ed0a4e8 | 3,477 | advent_of_code_2022 | Apache License 2.0 |
src/aoc2017/kot/Day08.kt | Tandrial | 47,354,790 | false | null | package aoc2017.kot
import java.io.File
import java.util.regex.Pattern
object Day08 {
fun solve(input: List<String>): Pair<Int, Int> {
val memory = mutableMapOf<String, Int>()
val regex = Pattern.compile("(\\w+) (inc|dec) (-?\\d+) if (\\w+) (>|<|==|>=|<=|!=) (-?\\d+)")
var maxCurr = -1
for (line in input) {
val m = regex.matcher(line)
if (m.find()) {
val reg = m.group(1).toString()
var mod = m.group(3).toInt()
if (m.group(2).toString() == "dec") mod *= -1
val checkReg = m.group(4).toString()
val value = m.group(6).toInt()
val cmp: (Int, Int) -> Boolean = when (m.group(5)) {
">" -> { r, v -> r > v }
"<" -> { r, v -> r < v }
">=" -> { r, v -> r >= v }
"<=" -> { r, v -> r <= v }
"==" -> { r, v -> r == v }
"!=" -> { r, v -> r != v }
else -> { _, _ -> false }
}
if (cmp(memory.getOrPut(checkReg) { 0 }, value)) memory[reg] = memory.getOrPut(reg) { 0 } + mod
maxCurr = maxOf(memory.getOrPut(reg) { 0 }, maxCurr)
}
}
return Pair(memory.values.max()!!, maxCurr)
}
}
fun main(args: Array<String>) {
val input = File("./input/2017/Day08_input.txt").readLines()
val (partOne, partTwo) = Day08.solve(input)
println("Part One = $partOne")
println("Part Two = $partTwo")
}
| 0 | Kotlin | 1 | 1 | 9294b2cbbb13944d586449f6a20d49f03391991e | 1,372 | Advent_of_Code | MIT License |
src/adventofcode/blueschu/y2017/day15/solution.kt | blueschu | 112,979,855 | false | null | package adventofcode.blueschu.y2017.day15
import kotlin.test.assertEquals
// puzzle input
const val GEN_START_A = 722L
const val GEN_START_B = 354L
// Generator factors
const val GEN_FACTOR_A = 16807
const val GEN_FACTOR_B = 48271
// Generator iterations considered by "the judge"
const val PART_ONE_ITERATIONS = 40_000_000
const val PART_TWO_ITERATIONS = 5_000_000
// Make a generator
fun makeGenerator(seed: Long, factor: Int) =
generateSequence(seed) { (it * factor) % 2147483647 }
// The generators
val generatorA: Sequence<Long> = makeGenerator(GEN_START_A, GEN_FACTOR_A)
val generatorB: Sequence<Long> = makeGenerator(GEN_START_B, GEN_FACTOR_B)
fun main(args: Array<String>) {
val exampleGenA = makeGenerator(65, GEN_FACTOR_A)
val exampleGenB = makeGenerator(8921, GEN_FACTOR_B)
assertEquals(588, countTailing16BitMatches(
exampleGenA.take(PART_ONE_ITERATIONS).iterator(),
exampleGenB.take(PART_ONE_ITERATIONS).iterator()
))
println("Part 1: ${part1()}")
assertEquals(309, countTailing16BitMatches(
exampleGenA.filter {it % 4 == 0L}.take(PART_TWO_ITERATIONS).iterator(),
exampleGenB.filter {it % 8 == 0L}.take(PART_TWO_ITERATIONS).iterator()))
println("Part 2: ${part2()}")
}
fun part1(): Int = countTailing16BitMatches(
genA = generatorA.take(PART_ONE_ITERATIONS).iterator(),
genB = generatorB.take(PART_ONE_ITERATIONS).iterator()
)
fun part2(): Int = countTailing16BitMatches(
genA = generatorA.filter { it % 4 == 0L }.take(PART_TWO_ITERATIONS).iterator(),
genB = generatorB.filter { it % 8 == 0L }.take(PART_TWO_ITERATIONS).iterator()
)
fun countTailing16BitMatches(genA: Iterator<Long>, genB: Iterator<Long>): Int {
var matchCount = 0
while (genA.hasNext() && genB.hasNext()) {
val a = genA.next()
val b = genB.next()
// compare only the last 16 bits
if (a and 0xFFFF == b and 0xFFFF) matchCount++
}
return matchCount
}
| 0 | Kotlin | 0 | 0 | 9f2031b91cce4fe290d86d557ebef5a6efe109ed | 1,973 | Advent-Of-Code | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxValueOfCoins.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.max
import kotlin.math.min
/**
* 2218. Maximum Value of K Coins From Piles
* @see <a href="https://leetcode.com/problems/maximum-value-of-k-coins-from-piles/">Source</a>
*/
fun interface MaxValueOfCoins {
operator fun invoke(piles: List<List<Int>>, k: Int): Int
}
class MaxValueOfCoinsTopDown : MaxValueOfCoins {
override operator fun invoke(piles: List<List<Int>>, k: Int): Int {
val memo = Array(piles.size + 1) {
arrayOfNulls<Int>(k + 1)
}
return dp(piles, memo, 0, k)
}
private fun dp(piles: List<List<Int>>, memo: Array<Array<Int?>>, i: Int, k: Int): Int {
if (k == 0 || i == piles.size) return 0
if (memo[i][k] != null) return memo[i][k]!!
var res = dp(piles, memo, i + 1, k)
var cur = 0
for (j in 0 until min(piles[i].size, k)) {
cur += piles[i][j]
res = max(res, cur + dp(piles, memo, i + 1, k - j - 1))
}
return res.also { memo[i][k] = it }
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,657 | kotlab | Apache License 2.0 |
src/Day09.kt | makohn | 571,699,522 | false | {"Kotlin": 35992} | import kotlin.math.abs
import kotlin.math.sign
fun main() {
data class Pos(var x: Int, var y: Int)
infix fun Pos.dist(other: Pos) =
(this.x - other.x) to (this.y - other.y)
fun part1(input: List<String>): Int {
val head = Pos(0, 0)
val tail = Pos(0, 0)
val tailPositions = mutableSetOf(Pos(0, 0))
for ((op, count) in input.map { it.split(" ") }) {
repeat(count.toInt()) {
when (op) {
"L" -> head.x--
"R" -> head.x++
"U" -> head.y++
"D" -> head.y--
}
val (dx, dy) = head dist tail
if (abs(dx) > 1 || abs(dy) > 1) {
tail.x += dx.sign
tail.y += dy.sign
tailPositions.add(tail.copy())
}
}
}
return tailPositions.size
}
fun part2(input: List<String>): Int {
val knots = Array(10) { Pos(0, 0) }
val head = knots[0]
val knotPositions = mutableSetOf(Pos(0,0))
for ((op, count) in input.map { it.split(" ") }) {
repeat(count.toInt()) {
when (op) {
"L" -> head.x--
"R" -> head.x++
"U" -> head.y++
"D" -> head.y--
}
for (i in 1 until knots.size) {
val knot = knots[i]
val pred = knots[i-1]
val (dx, dy) = pred dist knot
if (abs(dx) > 1 || abs(dy) > 1) {
knot.x += dx.sign
knot.y += dy.sign
}
if (i == 9) {
knotPositions.add(knot.copy())
}
}
}
}
return knotPositions.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
// check(part1(testInput) == 13)
check(part2(testInput) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 2734d9ea429b0099b32c8a4ce3343599b522b321 | 2,202 | aoc-2022 | Apache License 2.0 |
2021/src/main/kotlin/Day18.kt | eduellery | 433,983,584 | false | {"Kotlin": 97092} | import kotlin.math.floor
import kotlin.math.ceil
class Day18(val input: List<String>) {
private fun magnitude(num: SnailFishNumber): Long {
return when (num) {
is SnailFishNumber.Regular -> num.value.toLong()
is SnailFishNumber.Number -> magnitude(num.left) * 3 + magnitude(num.right) * 2
}
}
private fun reduce(num: SnailFishNumber): SnailFishNumber {
while (true) {
val canExplode = findExploding(num)
if (canExplode != null) {
explode(canExplode)
continue
}
val canSplit = findSplitting(num)
if (canSplit != null) {
split(canSplit)
continue
}
break
}
return num
}
private fun findExploding(num: SnailFishNumber, depth: Int = 1): SnailFishNumber.Number? {
return when (num) {
is SnailFishNumber.Regular -> null
is SnailFishNumber.Number -> {
if (depth == 5) {
num
} else {
findExploding(num.left, depth + 1) ?: findExploding(num.right, depth + 1)
}
}
}
}
private fun findSplitting(num: SnailFishNumber): SnailFishNumber.Regular? {
return when (num) {
is SnailFishNumber.Regular -> if (num.value >= 10) num else null
is SnailFishNumber.Number -> {
findSplitting(num.left) ?: findSplitting(num.right)
}
}
}
private fun explode(num: SnailFishNumber.Number) {
firstNonSideParent(num, SnailFishNumber.Number::left)?.let { rightMost(it.left) }?.apply {
value += (num.left as SnailFishNumber.Regular).value
}
firstNonSideParent(num, SnailFishNumber.Number::right)?.let { leftMost(it.right) }?.apply {
value += (num.right as SnailFishNumber.Regular).value
}
num.parent?.replace(num, SnailFishNumber.Regular(0))
}
private fun firstNonSideParent(
num: SnailFishNumber,
side: SnailFishNumber.Number.() -> SnailFishNumber
): SnailFishNumber.Number? {
var current = num
while (current.parent != null) {
if (current.parent!!.side() !== current) {
return current.parent
} else {
current = current.parent!!
}
}
return null
}
private fun rightMost(num: SnailFishNumber): SnailFishNumber.Regular {
return when (num) {
is SnailFishNumber.Regular -> num
is SnailFishNumber.Number -> rightMost(num.right)
}
}
private fun leftMost(num: SnailFishNumber): SnailFishNumber.Regular {
return when (num) {
is SnailFishNumber.Regular -> num
is SnailFishNumber.Number -> leftMost(num.left)
}
}
private fun split(num: SnailFishNumber.Regular) {
val l = floor(num.value / 2.0).toInt()
val r = ceil(num.value / 2.0).toInt()
val newNum = SnailFishNumber.Number(SnailFishNumber.Regular(l), SnailFishNumber.Regular(r))
num.parent?.replace(num, newNum)
}
private fun <E> permutations(list: List<E>, length: Int? = null): Sequence<List<E>> = sequence {
val n = list.size
val r = length ?: list.size
val indices = list.indices.toMutableList()
val cycles = (n downTo (n - r)).toMutableList()
yield(indices.take(r).map { list[it] })
run@ while (true) {
for (i in (r - 1) downTo 0) {
cycles[i]--
if (cycles[i] == 0) {
val end = indices[i]
for (j in i until indices.size - 1) {
indices[j] = indices[j + 1]
}
indices[indices.size - 1] = end
cycles[i] = n - i
} else {
val j = cycles[i]
val tmp = indices[i]
indices[i] = indices[-j + indices.size]
indices[-j + indices.size] = tmp
yield(indices.take(r).map { list[it] })
continue@run
}
}
break@run
}
}
fun solve1(): Long {
return input.map { SnailFishNumber.of(it) }.reduce { acc, snailFishNumber -> reduce(acc + snailFishNumber) }
.let { magnitude(it) }
}
fun solve2(): Long {
return permutations(input, length = 2).maxOf {
magnitude(reduce(SnailFishNumber.of(it[0]) + SnailFishNumber.of(it[1])))
}
}
sealed class SnailFishNumber(var parent: Number? = null) {
operator fun plus(other: SnailFishNumber): SnailFishNumber {
return Number(this, other)
}
data class Number(var left: SnailFishNumber, var right: SnailFishNumber) : SnailFishNumber() {
init {
left.parent = this
right.parent = this
}
fun replace(old: SnailFishNumber, new: SnailFishNumber) {
if (left === old) {
left = new
} else {
right = new
}
new.parent = this
}
}
data class Regular(var value: Int) : SnailFishNumber()
companion object {
fun of(line: String): SnailFishNumber {
return if (line.startsWith("[")) {
var bracketCount = 0
var commaIndex = 0
for ((i, c) in line.withIndex()) {
if (c == '[') bracketCount++
else if (c == ']') bracketCount--
else if (c == ',' && bracketCount == 1) {
commaIndex = i
break
}
}
Number(of(line.take(commaIndex).drop(1)), of(line.drop(commaIndex + 1).dropLast(1)))
} else {
Regular(line.toInt())
}
}
}
}
}
| 0 | Kotlin | 0 | 1 | 3e279dd04bbcaa9fd4b3c226d39700ef70b031fc | 6,201 | adventofcode-2021-2025 | MIT License |
2021/src/day04/Solution.kt | vadimsemenov | 437,677,116 | false | {"Kotlin": 56211, "Rust": 37295} | package day04
import java.io.BufferedReader
import java.nio.file.Files
import java.nio.file.Paths
fun main() {
fun solveBoard(board: Board, sequence: List<Int>): Pair<Int, Int> {
val rows = IntArray(5) { 5 }
val cols = IntArray(5) { 5 }
var sum = board.sumOf { it.sum() }
for ((index, number) in sequence.withIndex()) {
for (r in rows.indices) {
for (c in cols.indices) {
if (board[r][c] == number) {
rows[r]--
cols[c]--
sum -= number
}
}
}
if (rows.any { it == 0 } || cols.any { it == 0 }) {
return Pair(index, sum * number)
}
}
error("Polundra!")
}
fun part1(input: Pair<List<Int>, List<Board>>): Int {
val (sequence, boards) = input
return boards
.map { solveBoard(it, sequence) }
.minByOrNull { it.first }!!
.second
}
fun part2(input: Pair<List<Int>, List<Board>>): Int {
val (sequence, boards) = input
return boards
.map { solveBoard(it, sequence) }
.maxByOrNull { it.first }!!
.second
}
check(part1(readInput("test-input.txt")) == 4512)
check(part2(readInput("test-input.txt")) == 1924)
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
private fun readInput(s: String): Pair<List<Int>, List<Board>> {
val reader = Files.newBufferedReader(Paths.get("src/day04/$s"))
val sequence = reader.readLine()!!.split(",").map { it.toInt() }
val boards = ArrayList<Board>()
while (true) boards.add(
List(5) {
val row = reader.readNonBlankLine() ?: return Pair(sequence, boards)
check(row.isNotBlank())
row.split(" ").filter { it.isNotBlank() }.map { it.toInt() }
}
)
}
private fun BufferedReader.readNonBlankLine(): String? = readLine()?.ifBlank { readNonBlankLine() }
typealias Board = List<List<Int>> | 0 | Kotlin | 0 | 0 | 8f31d39d1a94c862f88278f22430e620b424bd68 | 1,873 | advent-of-code | Apache License 2.0 |
2021/src/day17/day17.kt | scrubskip | 160,313,272 | false | {"Kotlin": 198319, "Python": 114888, "Dart": 86314} | package day17
import java.lang.Integer.max
fun main() {
// target area: x=56..76, y=-162..-134
val target = TargetArea(56..76, -162..-134)
println(findMaxY(target))
}
fun findMaxY(area: TargetArea): Int {
var allMaxY = 0
for (x in 0..max(area.xRange.first, area.xRange.last)) {
for (y in area.yRange.first..500) {
with(runTest(area, StepData.startWithVelocity(x, y))) {
if (resultType == Result.Type.ON_TARGET) {
if (maxY > allMaxY) {
allMaxY = maxY
}
}
}
}
}
return allMaxY
}
fun countValid(area: TargetArea): Int {
var count = 0
for (x in 0..max(area.xRange.first, area.xRange.last)) {
// Now need to find the right Y
for (y in area.yRange.first..500) {
with(runTest(area, StepData.startWithVelocity(x, y))) {
if (resultType == Result.Type.ON_TARGET) {
count++
}
}
}
}
return count
}
fun runTest(area: TargetArea, initial: StepData): Result {
var currentStep = initial
var maxY = 0
while (true) {
if (area.contains(currentStep.position)) {
return Result(Result.Type.ON_TARGET, maxY)
} else if (area.isOvershoot(currentStep)) {
return Result(Result.Type.OVERSHOOT, maxY)
} else if (area.isUndershoot(currentStep)) {
return Result(Result.Type.UNDERSHOOT, maxY)
}
currentStep = currentStep.getNextStep()
if (currentStep.position.second > maxY) maxY = currentStep.position.second
}
}
data class StepData(var position: Pair<Int, Int>, var velocity: Pair<Int, Int>) {
fun getNextStep(): StepData {
val newPosition = Pair(position.first + velocity.first, position.second + velocity.second)
val newVelocityX = when {
velocity.first > 0 -> velocity.first - 1
velocity.first < 0 -> velocity.first + 1
else -> 0
}
return StepData(newPosition, Pair(newVelocityX, velocity.second - 1))
}
companion object {
fun startWithVelocity(velocityX: Int, velocityY: Int): StepData {
return StepData(Pair(0, 0), Pair(velocityX, velocityY))
}
}
}
class Result(val resultType: Type, val maxY: Int) {
enum class Type {
UNDERSHOOT, ON_TARGET, OVERSHOOT
}
}
data class TargetArea(val xRange: IntRange, val yRange: IntRange) {
fun contains(point: Pair<Int, Int>): Boolean {
return point.first in xRange && point.second in yRange
}
fun isOvershoot(stepData: StepData): Boolean {
// we are past target area if the x and y are outside the max range for x and the min range for y
return stepData.position.first > xRange.last && stepData.position.second < yRange.first
}
fun isUndershoot(stepData: StepData): Boolean {
return stepData.position.first <= xRange.last && stepData.position.second < yRange.first
}
} | 0 | Kotlin | 0 | 0 | a5b7f69b43ad02b9356d19c15ce478866e6c38a1 | 3,057 | adventofcode | Apache License 2.0 |
puzzles/kotlin/src/bender3.kt | hitszjsy | 337,974,982 | true | {"Python": 88057, "Java": 79734, "Kotlin": 52113, "C++": 33407, "TypeScript": 20480, "JavaScript": 17133, "PHP": 15544, "Go": 15296, "Ruby": 12722, "Haskell": 12635, "C#": 2600, "Scala": 1555, "Perl": 1250, "Shell": 1220, "Clojure": 753, "C": 598, "Makefile": 58} | import java.util.Scanner
// complexity names and functions
val complexities = arrayListOf(
Constant(),
Logarithmic(),
Linear(),
LogLinear(),
Quadratic(),
LogQuadratic(),
Cubic(),
Exponential()
)
fun main(args : Array<String>) {
// read standard input
val input = Scanner(System.`in`)
val nbPoints = input.nextInt()
val points = ArrayList<Pair<Int, Int>>(nbPoints)
for (i in 0 until nbPoints) {
val nbItems = input.nextInt()
val time = input.nextInt()
points.add(Pair(nbItems, time))
}
// compute the most probable computational complexity
var bestFit = ""
var minNormVariance = Double.POSITIVE_INFINITY
for (complexity in complexities) {
val ratios = points.map { it.second / complexity.function(it.first.toDouble()) }
// calculate the normalized variance
val meanRatios = ratios.sum() / ratios.size
val variances = ratios.map { Math.pow(it - meanRatios, 2.0) }
val normVariance = variances.sum() / Math.pow(meanRatios, 2.0)
if (normVariance < minNormVariance) {
minNormVariance = normVariance
bestFit = complexity.name()
}
}
println("O($bestFit)")
}
interface Complexity {
fun name(): String
fun function(n: Double): Double
}
class Constant : Complexity {
override fun name(): String { return "1" }
override fun function(n: Double): Double {
return 1.0
}
}
class Logarithmic : Complexity {
override fun name(): String { return "log n" }
override fun function(n: Double): Double {
return Math.log(n)
}
}
class Linear : Complexity {
override fun name(): String { return "n" }
override fun function(n: Double): Double {
return n
}
}
class LogLinear : Complexity {
override fun name(): String { return "n log n" }
override fun function(n: Double): Double {
return n * Math.log(n)
}
}
class Quadratic : Complexity {
override fun name(): String { return "n^2" }
override fun function(n: Double): Double {
return n * n
}
}
class LogQuadratic : Complexity {
override fun name(): String { return "n^2 log n" }
override fun function(n: Double): Double {
return n * n * Math.log(n)
}
}
// for validator test #7
class Cubic : Complexity {
override fun name(): String { return "n^3" }
override fun function(n: Double): Double {
return Math.pow(n, 2.1)
}
}
class Exponential : Complexity {
override fun name(): String { return "2^n" }
override fun function(n: Double): Double {
return Math.pow(2.0, n)
}
}
| 0 | null | 0 | 1 | 59d9856e66b1c4a3d660c60bc26a19c4dfeca6e2 | 2,500 | codingame | MIT License |
src/main/kotlin/Day3/Day03.kt | fisherthewol | 433,544,714 | false | {"Kotlin": 8877} | package Day3
import readInput
fun List<String>.toCols(): List<MutableList<Char>> {
val lineSize = this[0].length
val cols : MutableList<MutableList<Char>> = mutableListOf()
for (i in 0 until lineSize) {
cols.add(mutableListOf())
}
for (line in this) {
for (i in 0 until lineSize) {
val col = cols[i]
col.add(line[i])
}
}
return cols
}
fun binaryDiagnostics(lines: List<String>): Int {
val cols = lines.toCols()
var gamma = ""; var epsilon = ""
for (col in cols){
gamma += col.groupingBy { it }.eachCount().maxByOrNull { it.value }?.key
epsilon += col.groupingBy { it }.eachCount().minByOrNull { it.value }?.key
}
return gamma.padStart(16, '0').toInt(2) * epsilon.padStart(16, '0').toInt(2)
}
fun oxygenGenRating(lines: List<String>): Int {
val working = lines.toMutableList()
for (i in working.indices) {
if (working.size == 1) break
// Don't know what this does on equal values.
val d = working.toCols()[i].groupingBy { it }.eachCount()
val c: Char? = if (d['0'] == d['1']) '1'
else d.maxByOrNull { it.value }?.key
working.retainAll { it[i] == c }
}
return working[0].padStart(16, '0').toInt(2)
}
fun co2ScrubRating(lines: List<String>): Int {
val working = lines.toMutableList()
for (i in working.indices) {
if (working.size == 1) break
// Don't know what this does on equal values.
val d = working.toCols()[i].groupingBy { it }.eachCount()
val c: Char? = if (d['0'] == d['1']) '0'
else d.minByOrNull { it.value }?.key
working.retainAll { it[i] == c }
}
return working[0].padStart(16, '0').toInt(2)
}
fun lifeSupportRating(lines: List<String>): Int {
return oxygenGenRating(lines) * co2ScrubRating(lines)
}
fun main() {
val lines = readInput("Day3", "Day03Input")
println("Power Consumption: ${binaryDiagnostics(lines)}")
println("Life support rating: ${lifeSupportRating(lines)}")
} | 0 | Kotlin | 0 | 0 | d078aa647c666adf3d562fb1c67de6bef9956bcf | 2,048 | AoC2021 | MIT License |
src/Day12.kt | arnoutvw | 572,860,930 | false | {"Kotlin": 33036} | import java.lang.Math.abs
typealias GridPosition = Pair<Int, Int>
typealias Barrier = Set<GridPosition>
const val MAX_SCORE = 99999999
fun main() {
abstract class Grid() {
open fun heuristicDistance(start: GridPosition, finish: GridPosition): Int {
val dx = abs(start.first - finish.first)
val dy = abs(start.second - finish.second)
return (dx + dy) + (-2) * minOf(dx, dy)
}
abstract fun getNeighbours(position: GridPosition): List<GridPosition>
open fun moveCost(from: GridPosition, to: GridPosition) = 1
}
class SquareGrid(width: Int, height: Int, val input: List<String>) : Grid() {
private val heightRange: IntRange = (0 until height)
private val widthRange: IntRange = (0 until width)
private val validMoves = listOf(Pair(1, 0), Pair(-1, 0), Pair(0, 1), Pair(0, -1))
override fun getNeighbours(position: GridPosition): List<GridPosition> {
val n = validMoves
.map { GridPosition(position.first + it.first, position.second + it.second) }
.filter { inGrid(it) }
.filter { var current = input[position.second][position.first]
if(current == 'S') {
current = 'a'
}
var target = input[it.second][it.first]
if (target == 'E') {
target = '{'
}
val dif = target.code - current.code
dif <= 1 }
return n
}
private fun inGrid(it: GridPosition) = (it.first in widthRange) && (it.second in heightRange)
}
/**
* Implementation of the A* Search Algorithm to find the optimum path between 2 points on a grid.
*
* The Grid contains the details of the barriers and methods which supply the neighboring vertices and the
* cost of movement between 2 cells. Examples use a standard Grid which allows movement in 8 directions
* (i.e. includes diagonals) but alternative implementation of Grid can be supplied.
*
*/
fun aStarSearch(start: GridPosition, finish: GridPosition, grid: Grid): Pair<List<GridPosition>, Int> {
/**
* Use the cameFrom values to Backtrack to the start position to generate the path
*/
fun generatePath(currentPos: GridPosition, cameFrom: Map<GridPosition, GridPosition>): List<GridPosition> {
val path = mutableListOf(currentPos)
var current = currentPos
while (cameFrom.containsKey(current)) {
current = cameFrom.getValue(current)
path.add(0, current)
}
return path.toList()
}
val openVertices = mutableSetOf(start)
val closedVertices = mutableSetOf<GridPosition>()
val costFromStart = mutableMapOf(start to 0)
val estimatedTotalCost = mutableMapOf(start to grid.heuristicDistance(start, finish))
val cameFrom = mutableMapOf<GridPosition, GridPosition>() // Used to generate path by back tracking
while (openVertices.size > 0) {
val currentPos = openVertices.minBy { estimatedTotalCost.getValue(it) }!!
// Check if we have reached the finish
if (currentPos == finish) {
// Backtrack to generate the most efficient path
val path = generatePath(currentPos, cameFrom)
return Pair(path, estimatedTotalCost.getValue(finish)) // First Route to finish will be optimum route
}
// Mark the current vertex as closed
openVertices.remove(currentPos)
closedVertices.add(currentPos)
grid.getNeighbours(currentPos)
.filterNot { closedVertices.contains(it) } // Exclude previous visited vertices
.forEach { neighbour ->
val score = costFromStart.getValue(currentPos) + grid.moveCost(currentPos, neighbour)
if (score < costFromStart.getOrDefault(neighbour, MAX_SCORE)) {
if (!openVertices.contains(neighbour)) {
openVertices.add(neighbour)
}
cameFrom.put(neighbour, currentPos)
costFromStart.put(neighbour, score)
estimatedTotalCost.put(neighbour, score + grid.heuristicDistance(neighbour, finish))
}
}
}
throw IllegalArgumentException("No Path from Start $start to Finish $finish")
}
fun part1(input: List<String>): Int {
var start = GridPosition(0,0)
var end = GridPosition(7,7)
input.withIndex().forEach {(y, line) ->
line.withIndex().forEach { (x, char) ->
if(char == 'S') {
start = GridPosition(x, y)
} else if (char == 'E') {
end = GridPosition(x, y)
}
}
}
val (path, cost) = aStarSearch(start, end, SquareGrid(input[0].length,input.size, input))
return cost
}
fun part2(input: List<String>): Int {
val startnodes = mutableListOf<GridPosition>()
var end = GridPosition(7,7)
input.withIndex().forEach {(y, line) ->
line.withIndex().forEach { (x, char) ->
if(char == 'S' || char == 'a') {
startnodes.add(GridPosition(x, y))
} else if (char == 'E') {
end = GridPosition(x, y)
}
}
}
return startnodes.map {
try {
val (path, cost) = aStarSearch(it, end, SquareGrid(input[0].length,input.size, input))
cost
} catch (e: Exception) {
MAX_SCORE
}
}.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
println("Test")
val part1 = part1(testInput)
println(part1)
val part2 = part2(testInput)
println(part2)
check(part1 == 31)
check(part2 == 29)
println("Waarde")
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 0cee3a9249fcfbe358bffdf86756bf9b5c16bfe4 | 6,331 | aoc-2022-in-kotlin | Apache License 2.0 |
archive/src/main/kotlin/com/grappenmaker/aoc/year22/Day17.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year22
import com.grappenmaker.aoc.*
import com.grappenmaker.aoc.Direction.*
import kotlin.math.abs
fun PuzzleSet.day17() = puzzle {
val instructions = input.map {
when (it) {
'<' -> LEFT
'>' -> RIGHT
else -> error("Invalid input")
}
}
val rocks = """
####
.#.
###
.#.
..#
..#
###
#
#
#
#
##
##
""".trimIndent().split("\n\n").map { r ->
val rock = r.lines().asGrid { it == '#' }
rock.filterTrue().map { (x, y) -> PointL(x + 2L, y - rock.height.toLong()) }
}
data class Pattern(val instruction: Int, val piece: Int, val topRows: Set<PointL>)
data class PatternData(val y: Long, val iteration: Long)
fun solve(iters: Long): Long {
val seenPatterns = hashMapOf<Pattern, PatternData>()
val infPattern = instructions.asSequence().withIndex().repeatInfinitely().iterator()
val rockPattern = rocks.asSequence().withIndex().repeatInfinitely().iterator()
val points = hashSetOf<PointL>()
var iteration = 0L
var height = 0L
var repeatedHeight = 0L // part two shenanigans
while (iteration < iters) {
val (rockIdx, currentRockPoints) = rockPattern.next()
var rockPoints = currentRockPoints.map { it.copy(y = it.y + (height - 3L)) }
while (true) {
fun tryMove(dir: Direction): Boolean {
val new = rockPoints.map { it + dir }
val isBlocked = new.any { it in points }
val inHeight = new.all { it.y < 0 }
val inWidth = new.all { it.x in 0..<7 }
if (!isBlocked && inWidth && inHeight) rockPoints = new
return isBlocked || !inHeight
}
val (movIdx, movement) = infPattern.next()
tryMove(movement)
if (tryMove(DOWN)) {
points += rockPoints
height = points.minOf { it.y }
val topRows = points.filter { (height - it.y) >= -20L }.map { it.copy(y = height - it.y) }.toSet()
val pattern = Pattern(movIdx, rockIdx, topRows)
seenPatterns[pattern]?.let { seenPtr ->
val iterDiff = iteration - seenPtr.iteration
val repeat = (iters - iteration) / iterDiff
iteration += iterDiff * repeat
repeatedHeight += repeat * (height - seenPtr.y)
}
seenPatterns[pattern] = PatternData(height, iteration)
break
}
}
iteration++
}
return abs(height + repeatedHeight)
}
partOne = solve(2022).s()
partTwo = solve(1000000000000).s()
} | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 3,020 | advent-of-code | The Unlicense |
LeetCode/ThreeSum.kt | MartinWie | 702,541,017 | false | {"Kotlin": 90565} | class ThreeSum {
fun threeSum(nums: IntArray): List<List<Int>> {
val targetSum = 0
val resultsList = mutableListOf<List<Int>>()
val numsList = nums.toMutableList()
for (outerNum in numsList) {
for (midNum in numsList.minus(outerNum)) {
for (innerNum in numsList.minus(outerNum).minus(midNum)) {
if (innerNum + midNum + outerNum == targetSum) {
resultsList.add(listOf(innerNum, midNum, outerNum).sorted())
}
}
}
}
return resultsList.distinct()
}
fun threeSum2(nums: IntArray): List<List<Int>> {
val resultList = mutableListOf<List<Int>>()
nums.sort()
for (index in nums.indices) {
if (index > 0 && nums[index] == nums[index - 1]) continue
var leftPointer = index + 1
var rightPointer = nums.size - 1
while (leftPointer < rightPointer) {
val sum = nums[index] + nums[leftPointer] + nums[rightPointer]
when {
sum == 0 -> {
resultList.add(listOf(nums[index], nums[leftPointer], nums[rightPointer]))
leftPointer++
rightPointer--
while (leftPointer < rightPointer && nums[leftPointer] == nums[leftPointer - 1]) leftPointer++
while (leftPointer < rightPointer && nums[rightPointer] == nums[rightPointer + 1]) rightPointer--
}
sum < 0 -> {
leftPointer++
}
sum > 0 -> {
rightPointer--
}
}
}
}
return resultList
}
fun threeSum3(nums: IntArray): List<List<Int>> {
nums.sort()
val resultList = mutableListOf<List<Int>>()
for (index in nums.indices) {
// Avoid duplicate triplets
if (index == 0 || nums[index] != nums[index - 1]) {
twoSum(nums, index, -nums[index], resultList)
}
}
return resultList
}
private fun twoSum(
nums: IntArray,
startIndex: Int,
target: Int,
resultList: MutableList<List<Int>>,
) {
val seen = HashSet<Int>()
for (i in startIndex + 1 until nums.size) {
if (seen.contains(target - nums[i])) {
val triplet = listOf(-target, target - nums[i], nums[i])
// Add the triplet if it's not already in the list to avoid duplicates
if (!resultList.contains(triplet)) {
resultList.add(triplet)
}
}
seen.add(nums[i])
}
}
}
| 0 | Kotlin | 0 | 0 | 47cdda484fabd0add83848e6000c16d52ab68cb0 | 2,846 | KotlinCodeJourney | MIT License |
calendar/day11/Day11.kt | starkwan | 573,066,100 | false | {"Kotlin": 43097} | package day11
import Day
import Lines
class Day11 : Day() {
override fun part1(input: Lines): Any {
val monkeys = input.windowed(6, 7).map { Monkey(it) }
for (round in 1..20) {
monkeys.forEach { monkey ->
monkey.items.forEach { item ->
item.worryLevel = monkey.operation(item.worryLevel)
item.worryLevel /= 3
monkeys[monkey.test(item.worryLevel)].items.add(item)
}
monkey.inspectedCount += monkey.items.size
monkey.items.clear()
}
}
return monkeys.map { it.inspectedCount }.sorted().takeLast(2).let { it[0] * it[1] }
}
override fun part2(input: Lines): Any {
val monkeys = input.windowed(6, 7).map { MonkeyPart2(it) }
ItemPart2.divisors = monkeys.map { it.divisor }
monkeys.forEach(MonkeyPart2::generateItemsPart2)
for (round in 1..10000) {
monkeys.forEach { monkey ->
monkey.itemsPart2.forEach { itemPart2 ->
itemPart2.update { remainder -> monkey.operation(remainder) }
monkeys[monkey.test(itemPart2)].itemsPart2.add(itemPart2)
}
monkey.inspectedCount += monkey.itemsPart2.size
monkey.itemsPart2.clear()
}
}
return monkeys.map { it.inspectedCount.toLong() }.sorted().takeLast(2).let { it[0] * it[1] }
}
class Monkey(lines: List<String>) {
var items: MutableList<Item>
val operation: (old: Int) -> Int
val test: (item: Int) -> Int
var inspectedCount = 0
init {
items = lines[1].substring(" Starting items: ".length).split(", ").map { Item(it.toInt()) }.toMutableList()
operation = {
var parts = lines[2].substring(" Operation: new = ".length).split(" ")
var result = if (parts[0] == "old") it else parts[1].toInt()
parts = parts.drop(1)
while (parts.isNotEmpty()) {
when (parts[0]) {
"+" -> result += if (parts[1] == "old") result else parts[1].toInt()
"*" -> result *= if (parts[1] == "old") result else parts[1].toInt()
else -> error("unknown operator")
}
parts = parts.drop(2)
}
result
}
test = { worryLevel ->
val divisor = lines[3].split(" ").last().toInt()
val monkeyIfTrue = lines[4].split(" ").last().toInt()
val monkeyIfFalse = lines[5].split(" ").last().toInt()
if (worryLevel % divisor == 0) monkeyIfTrue else monkeyIfFalse
}
}
}
data class Item(var worryLevel: Int)
class MonkeyPart2(lines: List<String>) {
private var monkeyIndex = -1
private var initialWorryLevels: MutableList<Int> = mutableListOf()
var itemsPart2: MutableList<ItemPart2> = mutableListOf()
val divisor = lines[3].split(" ").last().toInt()
val operation: (old: Int) -> Int
val test: (itemPart2: ItemPart2) -> Int
var inspectedCount = 0
fun generateItemsPart2() {
itemsPart2 = initialWorryLevels.map { ItemPart2(it) }.toMutableList()
}
init {
monkeyIndex = lines[0].split(" ").last().dropLast(1).toInt()
initialWorryLevels =
lines[1].substring(" Starting items: ".length).split(", ").map(String::toInt).toMutableList()
operation = { remainder ->
var parts = lines[2].substring(" Operation: new = ".length).split(" ")
var result = if (parts[0] == "old") remainder else parts[1].toInt()
parts = parts.drop(1)
while (parts.isNotEmpty()) {
when (parts[0]) {
"+" -> result += if (parts[1] == "old") result else parts[1].toInt()
"*" -> result *= if (parts[1] == "old") result else parts[1].toInt()
else -> error("unknown operator")
}
parts = parts.drop(2)
}
result
}
test = { itemPart2 ->
val monkeyIfTrue = lines[4].split(" ").last().toInt()
val monkeyIfFalse = lines[5].split(" ").last().toInt()
if (itemPart2.remainders[monkeyIndex] == 0) monkeyIfTrue else monkeyIfFalse
}
}
}
class ItemPart2(private val initialValue: Int) {
var remainders: List<Int>
init {
remainders = divisors.map { initialValue % it }
}
fun update(operation: (Int) -> Int) {
remainders = (remainders zip divisors).map { (remainder, divisor) -> operation(remainder) % divisor }
}
companion object {
var divisors = listOf<Int>()
}
}
} | 0 | Kotlin | 0 | 0 | 13fb66c6b98d452e0ebfc5440b0cd283f8b7c352 | 5,058 | advent-of-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/com/github/solairerove/algs4/leprosorium/heap/MergeKSortedArrays.kt | solairerove | 282,922,172 | false | {"Kotlin": 251919} | package com.github.solairerove.algs4.leprosorium.heap
fun main() {
val arrays = listOf(listOf(1, 4, 5), listOf(1, 3, 4), listOf(2, 6))
print(mergeKSortedArrays(arrays)) // [1, 1, 2, 3, 4, 4, 5, 6]
}
// O(nlog(k) + k) time | O(n + k) space
// n - total elements, k - number of arrays
private fun mergeKSortedArrays(arrays: List<List<Int>>): List<Int> {
val res = mutableListOf<Int>()
val min = mutableListOf<Element>()
for (i in arrays.indices) {
min.add(Element(i, 0, arrays[i][0]))
}
val minHeap = ElementHeap(min)
while (minHeap.size() != 0) {
val (arrIdx, idx, el) = minHeap.remove()
res.add(el)
if (idx < arrays[arrIdx].size - 1) {
minHeap.insert(Element(arrIdx, idx + 1, arrays[arrIdx][idx + 1]))
}
}
return res
}
private data class Element(val arrIdx: Int, val idx: Int, val el: Int)
private class ElementHeap(arr: MutableList<Element>) {
private val heap: MutableList<Element> = arr
init {
val n = arr.size
for (k in n / 2 downTo 0) {
sink(arr, k, n - 1)
}
}
private fun sink(arr: MutableList<Element>, curr: Int, n: Int) {
var k = curr
while (2 * k + 1 <= n) {
var j = 2 * k + 1
if (j < n && less(arr, j, j + 1)) j++
if (!less(arr, k, j)) break
swap(arr, k, j)
k = j
}
}
private fun swim(arr: MutableList<Element>, curr: Int) {
var k = curr
while (k > 0 && less(arr, (k - 1) / 2, k)) {
swap(arr, (k - 1) / 2, k)
k = (k - 1) / 2
}
}
fun size(): Int = heap.size
fun remove(): Element {
swap(heap, 0, heap.size - 1)
val toRemove = heap.removeAt(heap.size - 1)
sink(heap, 0, heap.size - 1)
return toRemove
}
fun insert(value: Element) {
heap.add(value)
swim(heap, heap.size - 1)
}
private fun less(arr: MutableList<Element>, i: Int, j: Int): Boolean {
return arr[i].el > arr[j].el
}
private fun swap(arr: MutableList<Element>, i: Int, j: Int) {
val temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
}
| 1 | Kotlin | 0 | 3 | 64c1acb0c0d54b031e4b2e539b3bc70710137578 | 2,220 | algs4-leprosorium | MIT License |
src/Day03.kt | zirman | 572,627,598 | false | {"Kotlin": 89030} | fun main() {
fun score(char: Char): Long {
return if (char.isLowerCase()) {
char - 'a' + 1L
} else {
char - 'A' + 27L
}
}
fun part1(input: List<String>): Long {
return input.sumOf { pack ->
pack.slice(0 until pack.length / 2).toSet()
.intersect(pack.slice(pack.length / 2 until pack.length).toSet())
.sumOf { score(it) }
}
}
fun part2(input: List<String>): Long {
return input.chunked(3)
.sumOf { pack ->
pack.map { it.toSet() }
.reduce { a, b -> a.intersect(b) }
.sumOf { score(it) }
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157L)
check(part2(testInput) == 70L)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 2ec1c664f6d6c6e3da2641ff5769faa368fafa0f | 990 | aoc2022 | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2022/Day08.kt | tginsberg | 568,158,721 | false | {"Kotlin": 113322} | /*
* Copyright (c) 2022 by <NAME>
*/
/**
* Advent of Code 2022, Day 8 - Treetop Tree House
* Problem Description: http://adventofcode.com/2022/day/8
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2022/day8/
*/
package com.ginsberg.advent2022
class Day08(input: List<String>) {
private val grid: Array<IntArray> = parseInput(input)
private val gridHeight: Int = grid.size
private val gridWidth: Int = grid.first().size
fun solvePart1(): Int = (1 until gridHeight - 1).sumOf { y ->
(1 until gridWidth - 1).count { x ->
grid.isVisible(x, y)
}
} + (2 * gridHeight) + (2 * gridWidth) - 4
fun solvePart2(): Int = (1 until gridHeight - 1).maxOf { y ->
(1 until gridWidth - 1).maxOf { x ->
grid.scoreAt(x, y)
}
}
private fun Array<IntArray>.isVisible(x: Int, y: Int): Boolean =
viewFrom(x, y).any { direction ->
direction.all { it < this[y][x] }
}
private fun Array<IntArray>.scoreAt(x: Int, y: Int): Int =
viewFrom(x, y).map { direction ->
direction.takeUntil { it >= this[y][x] }.count()
}.product()
private fun Array<IntArray>.viewFrom(x: Int, y: Int): List<List<Int>> =
listOf(
(y - 1 downTo 0).map { this[it][x] }, // Up
(y + 1 until gridHeight).map { this[it][x] }, // Down
this[y].take(x).asReversed(), // Left
this[y].drop(x + 1) // Right
)
private fun parseInput(input: List<String>): Array<IntArray> = input.map { row ->
row.map(Char::digitToInt).toIntArray()
}.toTypedArray()
}
| 0 | Kotlin | 2 | 26 | 2cd87bdb95b431e2c358ffaac65b472ab756515e | 1,658 | advent-2022-kotlin | Apache License 2.0 |
src/Day10.kt | thiyagu06 | 572,818,472 | false | {"Kotlin": 17748} | import aoc22.printIt
import java.io.File
fun main() {
fun parseInput() = File("input/day10.txt").readLines()
val keyCycles = listOf(20, 60, 100, 140, 180, 220)
fun star1(input: List<StateRegister>): Int {
val signals = keyCycles.map { keyCycle ->
val count = input
.takeWhile { cycle -> cycle.cycle <= keyCycle }
.sumOf { cycle -> cycle.adjustment }
//println("keyCycle: $keyCycle, count: ${count + 1} = ${(count + 1) * keyCycle}")
(count + 1) * keyCycle
}
return signals.sum().printIt()
}
fun star2(input: List<String>): String {
val cycles = registerState(input)
val pixels = (0..239)
.map {
val position = 1 + cycles
.takeWhile { cycle -> cycle.cycle <= it }
.sumOf { cycle -> cycle.adjustment }
val pixel = if ((it % 40) in position - 0 .. position + 2) {
"#"
} else {
"-"
}
pixel
}
val result = pixels.chunked(40).map { it.joinToString("") }.joinToString("\n")
println(result)
return "EPJBRKAH"
}
val grid = parseInput()
val cycles = registerState(grid)
// test if implementation meets criteria from the description, like:
check(star1(cycles) == 11820)
check(star2(grid) == "EPJBRKAH")
}
data class StateRegister(val cycle: Int, val adjustment: Int)
fun registerState(input: List<String>): List<StateRegister> {
var cycle = 1
return input
.mapNotNull {
val instruction = it.split(" ")
when (instruction[0]) {
"noop" -> {
cycle += 1
null
}
"addx" -> {
cycle += 2
StateRegister(cycle, instruction[1].toInt())
}
else -> null
}
}
} | 0 | Kotlin | 0 | 0 | 55a7acdd25f1a101be5547e15e6c1512481c4e21 | 2,025 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/ru/timakden/aoc/year2015/Day06.kt | timakden | 76,895,831 | false | {"Kotlin": 321649} | package ru.timakden.aoc.year2015
import ru.timakden.aoc.util.measure
import ru.timakden.aoc.util.readInput
/**
* [Day 6: Probably a Fire Hazard](https://adventofcode.com/2015/day/6).
*/
object Day06 {
@JvmStatic
fun main(args: Array<String>) {
measure {
val input = readInput("year2015/Day06")
println("Part One: ${part1(input)}")
println("Part Two: ${part2(input)}")
}
}
fun part1(input: List<String>): Int {
val regex = "\\s(?!on|off)".toRegex()
val lightsGrid = List(1000) { MutableList(1000) { false } }
input.forEach {
val list = it.split(regex)
val action = list[0]
val coordinates1 = list[1].split(',')
val coordinates2 = list[3].split(',')
val pair1 = coordinates1[0].toInt() to coordinates1[1].toInt()
val pair2 = coordinates2[0].toInt() to coordinates2[1].toInt()
var i = pair1.first
while (i <= pair2.first) {
var j = pair1.second
while (j <= pair2.second) {
when (action) {
"toggle" -> lightsGrid[i][j] = !lightsGrid[i][j]
"turn on" -> lightsGrid[i][j] = true
"turn off" -> lightsGrid[i][j] = false
}
j++
}
i++
}
}
return lightsGrid.sumOf { booleans -> booleans.count { it } }
}
fun part2(input: List<String>): Int {
val regex = "\\s(?!on|off)".toRegex()
val brightnessGrid = List(1000) { MutableList(1000) { 0 } }
input.forEach {
val list = it.split(regex)
val action = list[0]
val coordinates1 = list[1].split(',')
val coordinates2 = list[3].split(',')
val pair1 = coordinates1[0].toInt() to coordinates1[1].toInt()
val pair2 = coordinates2[0].toInt() to coordinates2[1].toInt()
var i = pair1.first
while (i <= pair2.first) {
var j = pair1.second
while (j <= pair2.second) {
when (action) {
"toggle" -> brightnessGrid[i][j] += 2
"turn on" -> brightnessGrid[i][j]++
"turn off" -> if (brightnessGrid[i][j] > 0) brightnessGrid[i][j]--
}
j++
}
i++
}
}
return brightnessGrid.sumOf { ints -> ints.sum() }
}
}
| 0 | Kotlin | 0 | 3 | acc4dceb69350c04f6ae42fc50315745f728cce1 | 2,605 | advent-of-code | MIT License |
src/Day01.kt | BjornstadThomas | 572,616,128 | false | {"Kotlin": 9666} | fun main() {
fun groupCaloriesTogheter(input: String): List<Int> {
// println(input) //Print input for å se opprinnelig liste
val inputSplit = input.split("\r\n\r\n")
.map{ it.lines()
.map( String::toInt ).sum()}
.sortedDescending()
// println(inputSplit) //Print av sortert liste, descending
return inputSplit
}
fun getThreeLargestValuesAndSumThemTogheter(calories: List<Int>): Int {
val first = calories.get(0)
val second = calories.get(1)
val third = calories.get(2)
println("Første: " + first).toString()
println("Andre: " + second).toString()
println("Tredje: " + third).toString()
val sum = first + second + third
return sum
}
fun part1(input: String): String {
return groupCaloriesTogheter(input).first().toString()
}
fun part2(input: String): String {
val calories = groupCaloriesTogheter(input)
return getThreeLargestValuesAndSumThemTogheter(calories).toString()
}
val input = readInput("input_Day01")
println("Alven som bærer flest kalorier, bærer: " + part1(input))
println("Sum av de tre alvene med mest kalorier: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | 553e3381ca26e1e316ecc6c3831354928cf7463b | 1,262 | AdventOfCode-2022-Kotlin | Apache License 2.0 |
src/main/kotlin/days/aoc2022/Day18.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2022
import days.Day
import util.Point3d
import kotlin.math.max
import kotlin.math.min
class Day18 : Day(2022, 18) {
override fun partOne(): Any {
return countExposedSidesOfCubes(inputList)
}
override fun partTwo(): Any {
return countExposedExteriorSidesOfCubes(inputList)
}
fun countExposedSidesOfCubes(input: List<String>): Int {
val cubes = input.map { line ->
line.split(",").map { it.toInt() }.let {
Point3d(it[0], it[1], it[2])
}
}
return cubes.sumOf { cube ->
6 - cubes.minus(cube).count { other -> cube.distanceTo(other) == 1 }
}
}
fun countExposedExteriorSidesOfCubes(input: List<String>) : Int {
var min = Point3d(Int.MAX_VALUE, Int.MAX_VALUE, Int.MAX_VALUE)
var max = Point3d(Int.MIN_VALUE, Int.MIN_VALUE, Int.MIN_VALUE)
val cubes = input.map { line ->
line.split(",").map { it.toInt() }.let {
min = min.copy(x = min(min.x, it[0]), y = min(min.y, it[1]), z = min(min.z, it[2]))
max = max.copy(x = max(max.x, it[0]), y = max(max.y, it[1]), z = max(max.z, it[2]))
Point3d(it[0], it[1], it[2])
}
}
val exterior = mutableSetOf<Point3d>()
val queue = mutableListOf<Point3d>()
queue.add(min)
while (queue.isNotEmpty()) {
val location = queue.removeFirst()
exterior.add(location)
val neighbors = location.neighbors(min, max)
queue.addAll(neighbors.filter { it !in exterior && it !in cubes && it !in queue})
}
return cubes.sumOf { cube ->
cube.neighbors(min, max).count { it in exterior }
}
}
}
fun Point3d.neighbors(min: Point3d, max: Point3d): List<Point3d> {
val result = mutableListOf<Point3d>()
if (x + 1 in min.x - 1..max.x + 1) {
result.add(copy(x = x + 1))
}
if (x - 1 in min.x - 1..max.x + 1) {
result.add(copy(x = x - 1))
}
if (y + 1 in min.y - 1..max.y + 1) {
result.add(copy(y = y + 1))
}
if (y - 1 in min.y - 1..max.y + 1) {
result.add(copy(y = y - 1))
}
if (z + 1 in min.z + 1..max.z + 1) {
result.add(copy(z = z + 1))
}
if (z - 1 in min.z - 1..max.z + 1) {
result.add(copy(z = z - 1))
}
return result
} | 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 2,403 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
src/day04/Day04.kt | devEyosiyas | 576,863,541 | false | null | package day04
import println
import readInput
fun main() {
fun processSections(input: List<String>): MutableList<List<Pair<Int, Int>>> {
val sections = mutableListOf<List<Pair<Int, Int>>>()
input.forEach { pairs ->
val pair = mutableListOf<Pair<Int, Int>>()
pairs.split(",").forEach { section ->
val range = section.split("-").map { it.toInt() }
pair.add(Pair(range[0], range[1]))
}
sections.add(pair)
}
return sections
}
fun partOne(input: List<String>): Int {
val sections = processSections(input)
var counter = 0
sections.forEach { section ->
section.chunked(4).forEach { pair ->
if (pair[0].first <= pair[1].first && pair[0].second >= pair[1].second || pair[1].first <= pair[0].first && pair[1].second >= pair[0].second) counter++
}
}
return counter
}
fun partTwo(input: List<String>): Int {
val sections = processSections(input)
var overlap = 0
sections.forEach { section ->
section.chunked(2).forEach { pair ->
if (pair[1].first >= pair[0].first && pair[1].first <= pair[0].second || pair[0].first >= pair[1].first && pair[0].first <= pair[1].second) overlap++
}
}
return overlap
}
val testInput = readInput("day04", true)
val input = readInput("day04")
// part one
partOne(testInput).println()
partOne(input).println()
// part two
partTwo(testInput).println()
partTwo(input).println()
} | 0 | Kotlin | 0 | 0 | 91d94b50153bdab1a4d972f57108d6c0ea712b0e | 1,628 | advent_of_code_2022 | Apache License 2.0 |
codeforces/round872/c_to_upsolve.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.round872
import java.util.*
fun main() {
val n = readInt()
val a = readInts()
val nei = List(n) { mutableListOf<Int>() }
repeat(n - 1) {
val (u, v) = readInts().map { it - 1 }
nei[u].add(v); nei[v].add(u)
}
val price = IntArray(n)
val niceXor = IntArray(n)
val temp = TreeSet<Int>()
val nice = MutableList(n) { temp }
fun dfs(v: Int, p: Int) {
var kids = 0
for (u in nei[v]) if (u != p) {
dfs(u, v)
price[v] += price[u]
kids++
}
if (kids == 0) {
nice[v] = TreeSet<Int>().apply { add(a[v]) }
return
}
if (kids == 1) {
val u = nei[v].first { it != p }
nice[v] = nice[u]
niceXor[v] = niceXor[u] xor a[v]
return
}
val uu = nei[v].maxBy { nice[it].size }
val counter = TreeMap<Int, Int>()
for (u in nei[v]) if (u != p && u != uu) {
for (x in nice[u]) {
val y = x xor niceXor[u]
counter[y] = counter.getOrDefault(y, 0) + 1
}
}
val maxCount = counter.entries.maxOf { it.value }
val other = TreeSet(counter.filter { it.value == maxCount }.map { it.key })
val niceUU = nice[uu]
val niceXorUU = niceXor[uu]
fun unite(set1: TreeSet<Int>, xor1: Int, set2: TreeSet<Int>, xor2: Int) {
if (set1.size < set2.size) return unite(set2, xor2, set1, xor1)
val xor12 = xor1 xor xor2
val common = TreeSet<Int>()
for (x in set2) {
if (set1.contains(x xor xor12)) common.add(x xor xor2)
}
price[v] = kids - maxCount
if (common.isNotEmpty()) {
price[v]--
nice[v] = common
return
}
for (x in set2) {
set1.add(x xor xor12)
}
nice[v] = set1
niceXor[v] = xor1
}
unite(niceUU, niceXorUU, other, 0)
niceXor[v] = niceXor[v] xor a[v]
}
dfs(0, -1)
println(price[0])
}
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,890 | competitions | The Unlicense |
src/main/kotlin/days/Day6.kt | MisterJack49 | 729,926,959 | false | {"Kotlin": 31964} | package days
class Day6 : Day(6) {
override fun partOne() =
inputList.map { entry ->
entry.split(":")[1].split(" ").filter { it.isNotEmpty() }.map { it.toLong() }
}.run {
first().mapIndexed { index, i ->
Race(i, last()[index])
}
}.map { race ->
race.simulateRecordCount()
}.fold(1) { acc, i -> acc * i }
override fun partTwo() =
inputList.map { entry ->
entry.split(":")[1].replace(" ", "").toLong()
}.run {
Race(this.first(), this.last())
.extrapolateRecordCount()
}
}
private data class Race(val time: Long, val distance: Long) {
private fun getDistance(hold: Long): Long =
(time - hold) * hold
fun simulateRecordCount(): Int {
return (0..time).map {
getDistance(it)
}.count { it > distance }
}
fun extrapolateRecordCount(): Int {
val mid = (if (time % 2 == 1L) time -1 else time) / 2
val firstRecord = findFirstRecordTime(0, mid)
return (firstRecord..time - firstRecord).count()
}
private fun findFirstRecordTime(low: Long, high: Long): Long {
if (low > high) return -1
val stepSize = (high - low) / 2
val middle = low + stepSize
val middleDistance = getDistance(middle)
return if (middleDistance > distance) {
val res = findFirstRecordTime(low, middle - 1)
if (res != -1L) res else middle
} else {
findFirstRecordTime(middle + 1, high)
}
}
}
| 0 | Kotlin | 0 | 0 | 807a6b2d3ec487232c58c7e5904138fc4f45f808 | 1,624 | AoC-2023 | Creative Commons Zero v1.0 Universal |
src/day21/Main.kt | nikwotton | 572,814,041 | false | {"Kotlin": 77320} | package day21
import java.io.File
val workingDir = "src/${object {}.javaClass.`package`.name}"
fun main() {
val sample = File("$workingDir/sample.txt")
val input1 = File("$workingDir/input_1.txt")
println("Step 1a: ${runStep1(sample)}") // 152
println("Step 1b: ${runStep1(input1)}") // 78342931359552
println("Step 2a: ${runStep2(sample)}") // 301
println("Step 2b: ${runStep2(input1)}") // 3296135418820
}
typealias MonkeyMap = HashMap<String, String>
fun MonkeyMap.customGet(index: String): String {
val value = get(index)!!
if(value.toLongOrNull() != null) return value
val (x, op, y) = value.split(" ")
return when (op) {
"+" -> customGet(x).toLong() + customGet(y).toLong()
"-" -> customGet(x).toLong() - customGet(y).toLong()
"*" -> customGet(x).toLong() * customGet(y).toLong()
"/" -> customGet(x).toLong() / customGet(y).toLong()
else -> TODO()
}.toString()
}
fun File.toMonkeys(): MonkeyMap = readLines().associate {
val (name, op) = it.split(":").map { it.trim() }
name to op
}.toMutableMap() as MonkeyMap
fun runStep1(input: File): String = input.toMonkeys().customGet("root")
fun runStep2(input: File): String {
val monkeys = input.toMonkeys()
val (v1, v2) = monkeys["root"]!!.split(" + ")
fun removeVariables(value: String): String {
if (value == "humn") return "x"
if (value.toLongOrNull() != null) return value
return if (value.contains(" ")) {
val (x, op, y) = value.split(" ")
"(${removeVariables(x)} $op ${removeVariables(y)})"
} else {
removeVariables(monkeys[value]!!)
}
}
tailrec fun simplifyEquation(equation: String): String {
var ret = equation
Regex("\\([0-9]+ \\+ [0-9]+\\)").find(equation)?.let {
ret = equation.replaceRange(it.range, it.value.removeSurrounding("(", ")").split(" + ").sumOf(String::toLong).toString())
}
Regex("\\([0-9]+ - [0-9]+\\)").find(equation)?.let {
ret = equation.replaceRange(it.range, it.value.removeSurrounding("(", ")").split(" - ").map(String::toLong).reduce { acc, l -> acc - l }.toString())
}
Regex("\\([0-9]+ \\* [0-9]+\\)").find(equation)?.let {
ret = equation.replaceRange(it.range, it.value.removeSurrounding("(", ")").split(" * ").map(String::toLong).reduce { acc, l -> acc * l }.toString())
}
Regex("\\([0-9]+ / [0-9]+\\)").find(equation)?.let {
ret = equation.replaceRange(it.range, it.value.removeSurrounding("(", ")").split(" / ").map(String::toLong).reduce { acc, l -> acc / l }.toString())
}
return if (ret == equation) ret
else simplifyEquation(ret)
}
tailrec fun findX(number: Long, equation: String): Long {
val restOfEquationRegex = "[0-9\\(\\)\\s\\+\\-\\/\\*x]+"
if(equation == "x") return number
Regex("\\($restOfEquationRegex / [0-9]+\\)").matchEntire(equation)?.let {
val divisor = equation.dropLast(1).takeLastWhile { it.isDigit() }.toLong()
val newEquation = equation.removeSurrounding("(", " / ${divisor})")
return findX(number * divisor, newEquation)
}
Regex("\\([0-9]+ \\+ $restOfEquationRegex\\)").matchEntire(equation)?.let {
val num = equation.drop(1).takeWhile { it.isDigit() }.toLong()
val newEquation = equation.removeSurrounding("($num + ", ")")
return findX(number - num, newEquation)
}
Regex("\\([0-9]+ \\* $restOfEquationRegex\\)").matchEntire(equation)?.let {
val num = equation.drop(1).takeWhile { it.isDigit() }.toLong()
val newEquation = equation.removeSurrounding("($num * ", ")")
return findX(number / num, newEquation)
}
Regex("\\($restOfEquationRegex - [0-9]+\\)").matchEntire(equation)?.let {
val num = equation.dropLast(1).takeLastWhile { it.isDigit() }.toLong()
val newEquation = equation.removeSurrounding("(", " - ${num})")
return findX(number + num, newEquation)
}
Regex("\\([0-9]+ - $restOfEquationRegex\\)").matchEntire(equation)?.let {
val num = equation.drop(1).takeWhile { it.isDigit() }.toLong()
val newEquation = equation.removeSurrounding("($num - ", ")")
return findX((number - num) * -1, newEquation)
}
Regex("\\($restOfEquationRegex \\+ [0-9]+\\)").matchEntire(equation)?.let {
val num = equation.dropLast(1).takeLastWhile { it.isDigit() }.toLong()
val newEquation = equation.removeSurrounding("(", " + ${num})")
return findX(number - num, newEquation)
}
Regex("\\($restOfEquationRegex \\* [0-9]+\\)").matchEntire(equation)?.let {
val num = equation.dropLast(1).takeLastWhile { it.isDigit() }.toLong()
val newEquation = equation.removeSurrounding("(", " * ${num})")
return findX(number / num, newEquation)
}
TODO("Need to handle $equation")
}
val simpV1 = simplifyEquation(removeVariables(v1))
val simpV2 = simplifyEquation(removeVariables(v2))
val num = if (simpV1.toLongOrNull() != null) simpV1.toLong() else simpV2.toLong()
val eq = if (simpV1.toLongOrNull() != null) simpV2 else simpV1
return findX(num, eq).toString()
}
| 0 | Kotlin | 0 | 0 | dee6a1c34bfe3530ae6a8417db85ac590af16909 | 5,395 | advent-of-code-2022 | Apache License 2.0 |
problems/2818/kotlin/Solution.kt | misut | 678,196,869 | false | {"Kotlin": 32683} | import java.util.*
import kotlin.math.min
class Solution {
companion object {
const val mod = 1000000007
}
fun pow(x: Int, n: Int): Int {
if (n == 0)
return 1
var res = (pow(x, n / 2) % mod).toLong()
res = (res * res) % mod
return (if (n % 2 == 1) (res * x) % mod else res).toInt()
}
fun maximumScore(nums: List<Int>, k: Int): Int {
val len = nums.size
val upper = nums.max()!!
val prime = Array(100001) { true }
val primeScores = Array(100001) { 0 }
prime[0] = false
prime[1] = false
for (i in (2..upper)) {
if (prime[i]) {
for (j in (i..upper step i)) {
primeScores[j] += 1
prime[j] = false
}
}
}
val prevGreaterOrEqualElement = Array(len) { -1 }
val nextGreaterElement = Array(len) { len }
Stack<Int>().let {
for (i in (0..len - 1).reversed()) {
while (!it.empty() && primeScores[nums[i]] >= primeScores[nums[it.peek()]])
it.pop()
nextGreaterElement[i] = if (it.empty()) len else it.peek()
it.push(i)
}
it.clear()
for (i in (0..len - 1)) {
while (!it.empty() && primeScores[nums[i]] > primeScores[nums[it.peek()]])
it.pop()
prevGreaterOrEqualElement[i] = if (it.empty()) -1 else it.peek()
it.push(i)
}
}
var res = 1L
var tmp = k
nums.mapIndexed { idx, num -> num to idx }.sortedWith(Comparator { o1, o2 -> o2.first - o1.first }).forEach { (num, idx) ->
val ops = min(tmp, (idx - prevGreaterOrEqualElement[idx]) * (nextGreaterElement[idx] - idx))
res = (res * pow(num, ops)) % mod
tmp -= ops
if (tmp == 0)
return res.toInt()
}
return res.toInt()
}
} | 0 | Kotlin | 0 | 0 | 52fac3038dd29cb8eefebbf4df04ccf1dda1e332 | 2,026 | ps-leetcode | MIT License |
src/main/java/challenges/educative_grokking_coding_interview/merge_intervals/_1/MergeInterval.kt | ShabanKamell | 342,007,920 | false | null | package challenges.educative_grokking_coding_interview.merge_intervals._1
import challenges.educative_grokking_coding_interview.merge_intervals.Interval
import java.util.*
object MergeInterval {
private fun mergeIntervals(intervals: List<Interval>): List<Interval> {
// If the list is empty
val result: MutableList<Interval> = ArrayList<Interval>()
if (intervals.isEmpty()) {
println("The list is empty")
return result
}
// Adding pair in the result list
result.add(Interval(intervals[0].start, intervals[0].end))
for (i in 1 until intervals.size) {
// Getting the recent added interval in the result list
val lastAddedInterval: Interval = result[result.size - 1]
// Getting and initializing input pair
val currStart: Int = intervals[i].start
val currEnd: Int = intervals[i].end
println("\n\t\t\tCurrent input interval: [$currStart, $currEnd]\n")
// Getting the ending timestamp of the previous interval
lastAddedInterval.end
println("\t\t\t" + "| " + "curStart" + " | " + "curEnd" + " |")
println("\t\t\t" + " ----------------------------- ")
println("\t\t\t| $currStart | $currEnd |")
}
return result
}
fun intervalListtoStr(l1: List<Interval>): String {
var resultStr = "["
for (i in 0 until l1.size - 1) {
resultStr += "[" + l1[i].start.toString() + ", " + l1[i].end
.toString() + "], "
}
resultStr += "[" + l1[l1.size - 1].start.toString() + ", " + l1[l1.size - 1].end
.toString() + "]"
resultStr += "]"
return resultStr
}
@JvmStatic
fun main(args: Array<String>) {
val l1: List<Interval> =
listOf(Interval(1, 5), Interval(3, 7), Interval(4, 6))
val l2: List<Interval> = listOf(
Interval(1, 5),
Interval(4, 6),
Interval(6, 8),
Interval(11, 15)
)
val l3: List<Interval> = listOf(
Interval(3, 7),
Interval(6, 8),
Interval(10, 12),
Interval(11, 15)
)
val l4: List<Interval> = listOf(Interval(1, 5))
val l5: List<Interval> =
listOf(Interval(1, 9), Interval(3, 8), Interval(4, 4))
val l6: List<Interval> =
listOf(Interval(1, 2), Interval(3, 4), Interval(8, 8))
val l7: List<Interval> = listOf(Interval(1, 5), Interval(1, 3))
val l8: List<Interval> = listOf(Interval(1, 5), Interval(6, 9))
val l9: List<Interval> =
listOf(Interval(0, 0), Interval(1, 18), Interval(1, 3))
val allIntervals: List<List<Interval>> =
listOf(l1, l2, l3, l4, l5, l6, l7, l8, l9)
for (i in allIntervals.indices) {
println("${i + 1 }. Intervals to merge: " + intervalListtoStr(allIntervals[i]))
mergeIntervals(
allIntervals[i]
)
println(String(CharArray(100)).replace('\u0000', '-'))
}
}
} | 0 | Kotlin | 0 | 0 | ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70 | 3,175 | CodingChallenges | Apache License 2.0 |
src/Day02.kt | ChAoSUnItY | 572,814,842 | false | {"Kotlin": 19036} | fun main() {
val map = mapOf(
'A' to mapOf(
'X' to (3 + 1 to 3 + 0),
'Y' to (6 + 2 to 1 + 3),
'Z' to (0 + 3 to 2 + 6)
),
'B' to mapOf(
'X' to (0 + 1 to 1 + 0),
'Y' to (3 + 2 to 2 + 3),
'Z' to (6 + 3 to 3 + 6)
),
'C' to mapOf(
'X' to (6 + 1 to 2 + 0),
'Y' to (0 + 2 to 3 + 3),
'Z' to (3 + 3 to 1 + 6)
)
)
fun part1(data: List<Pair<Char, Char>>): Int =
data.sumOf { map[it.first]!![it.second]!!.first }
fun part2(data: List<Pair<Char, Char>>): Int =
data.sumOf { map[it.first]!![it.second]!!.second }
fun processData(data: List<String>): List<Pair<Char, Char>> =
data.map { it[0] to it[2] }
val input = readInput("Day02")
val processedInput = processData(input)
println(part1(processedInput))
println(part2(processedInput))
} | 0 | Kotlin | 0 | 3 | 4fae89104aba1428820821dbf050822750a736bb | 943 | advent-of-code-2022-kt | Apache License 2.0 |
src/year2021/day05/Day05.kt | kingdongus | 573,014,376 | false | {"Kotlin": 100767} | package year2021.day05
import Point2D
import readInputFileByYearAndDay
import readTestFileByYearAndDay
fun main() {
fun countOverlappingPoints(input: List<String>, lineCondition: (Point2D, Point2D) -> Boolean): Int =
input.asSequence()
.map { it.split(" -> ") }
.map { it[0].split(",") to it[1].split(",") }
.map {
Point2D(it.first[0].toInt(), it.first[1].toInt()) to Point2D(
it.second[0].toInt(), it.second[1].toInt()
)
}
.filter { lineCondition(it.first, it.second) }
.map { it.first..it.second }
.flatten()
.groupBy { it }
.filter { (it.value.size >= 2) }
.count()
fun part1(input: List<String>): Int =
countOverlappingPoints(input) { a, b -> a isHorizontalTo b || a isVerticalTo b }
fun part2(input: List<String>): Int =
countOverlappingPoints(input) { a, b -> a isHorizontalTo b || a isVerticalTo b || a isDiagonalTo b }
val testInput = readTestFileByYearAndDay(2021, 5)
check(part1(testInput) == 5)
check(part2(testInput) == 12)
val input = readInputFileByYearAndDay(2021, 5)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | aa8da2591310beb4a0d2eef81ad2417ff0341384 | 1,268 | advent-of-code-kotlin | Apache License 2.0 |
src/day23/Day23.kt | ritesh-singh | 572,210,598 | false | {"Kotlin": 99540} | package day23
import readInput
private data class Position(val row: Int, val col: Int)
private fun Position.north() = this.copy(row = this.row - 1)
private fun Position.south() = this.copy(row = this.row + 1)
private fun Position.west() = this.copy(col = this.col - 1)
private fun Position.east() = this.copy(col = this.col + 1)
private fun Position.northWest() = this.copy(row = this.row - 1, col = this.col - 1)
private fun Position.northEast() = this.copy(row = this.row - 1, col = this.col + 1)
private fun Position.southWest() = this.copy(row = this.row + 1, col = this.col - 1)
private fun Position.southEast() = this.copy(row = this.row + 1, col = this.col + 1)
private fun Position.eightAdjPositions() =
listOf(
this.north(), this.south(), this.west(), this.east(),
this.northWest(), this.northEast(), this.southWest(), this.southEast(),
)
private const val LAND = '.'
private const val ELVES = '#'
private fun Char.isElves() = this == ELVES
private class Grove(lines: List<String>) {
private val elvesPositions = hashSetOf<Position>()
init {
lines.forEachIndexed { index, string ->
string.forEachIndexed { charIdx, c ->
if (c.isElves()) elvesPositions.add(Position(row = index, col = charIdx))
}
}
}
fun printElves() {
val minRow = elvesPositions.minOf { it.row }
val maxRow = elvesPositions.maxOf { it.row }
val minCol = elvesPositions.minOf { it.col }
val maxCol = elvesPositions.maxOf { it.col }
for (row in minRow..maxRow) {
for (col in minCol..maxCol) {
if (elvesPositions.contains(Position(row, col))) {
print(ELVES)
} else {
print(LAND)
}
print(" ")
}
println()
}
println("--------------------------------------------")
}
private enum class Directions { N, S, W, E }
private var fourDirectionsToLook = ArrayDeque(listOf(Directions.N, Directions.S, Directions.W, Directions.E))
private fun rotateDirections() = fourDirectionsToLook.addLast(fourDirectionsToLook.removeFirst())
private fun Position.elvesExistsInAnyDirection() = this.eightAdjPositions().any { elvesPositions.contains(it) }
private fun List<Position>.noElvesInAllDirection() = this.all { !elvesPositions.contains(it) }
private fun firstSecondHalf():Boolean {
val elvesToMove = elvesPositions.filter { it.elvesExistsInAnyDirection() }
val whereToMove = hashMapOf<Position, Position>()
elvesToMove.forEach elves@{ elves ->
fourDirectionsToLook.forEach { directions ->
val lookup = when (directions) {
Directions.N -> listOf(elves.north(), elves.northEast(), elves.northWest())
Directions.S -> listOf(elves.south(), elves.southEast(), elves.southWest())
Directions.W -> listOf(elves.west(), elves.northWest(), elves.southWest())
Directions.E -> listOf(elves.east(), elves.northEast(), elves.southEast())
}
if (lookup.noElvesInAllDirection()) {
whereToMove[elves] = when (directions) {
Directions.N -> elves.north()
Directions.S -> elves.south()
Directions.W -> elves.west()
Directions.E -> elves.east()
}
return@elves
}
}
}
val duplicateMovePositions = whereToMove.values.groupingBy { it }.eachCount().filter { it.value >= 2 }.keys
val elvesEligibleToMove = whereToMove.filter { !duplicateMovePositions.contains(it.value) }
elvesEligibleToMove.forEach { (from, to) ->
elvesPositions.remove(Position(from.row, from.col))
elvesPositions.add(Position(to.row, to.col))
}
return elvesToMove.isNotEmpty()
}
fun moveElves():Boolean {
val canMove = firstSecondHalf()
rotateDirections()
return canMove
}
fun emptyGroundTiles(): Int {
val minRow = elvesPositions.minOf { it.row }
val maxRow = elvesPositions.maxOf { it.row }
val minCol = elvesPositions.minOf { it.col }
val maxCol = elvesPositions.maxOf { it.col }
val totalRow = maxRow - minRow + 1
val totalCol = maxCol - minCol + 1
return (totalRow * totalCol) - elvesPositions.size
}
}
fun main() {
fun solve1(lines: List<String>): Int {
val grove = Grove(lines = lines)
val rounds = 10
repeat(rounds) {
grove.moveElves()
}
return grove.emptyGroundTiles()
}
fun solve2(lines: List<String>): Int {
val grove = Grove(lines = lines)
var rounds = 0
while (true){
rounds++
val canMove = grove.moveElves()
if (!canMove)
break
}
return rounds
}
val input = readInput("/day23/Day23")
println(solve1(input))
println(solve2(input))
}
| 0 | Kotlin | 0 | 0 | 17fd65a8fac7fa0c6f4718d218a91a7b7d535eab | 5,179 | aoc-2022-kotlin | Apache License 2.0 |
src/Day01.kt | allwise | 574,465,192 | false | null | import java.io.File
fun main() {
fun part1(input: List<String>): Int {
val calories = Calories(input).countCalories()
return calories
}
fun part2(input: List<String>): Int {
val calories = Calories(input).countTop3Calories()
return calories
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
println(part1(testInput))
println(part2(testInput))
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println("""Biggest Calorie value ${part1(input)} C. """)
println("Sum of 3 biggest: $${part2(input)}")
}
class Calories(private val input: List<String>) {
fun countTop3Calories(): Int {
var calories: MutableMap<Int, Int> = mutableMapOf()
var count = 1
var currentSum = 0
input.forEach{
if (it.trim() == "") {
calories.put(count, currentSum)
count++
currentSum = 0
} else {
currentSum += it.toInt()
}
}
calories.put(count, currentSum)
return calories.toList().sortedByDescending { it.second }.take(3)
.sumOf { it.second }
}
fun countCalories(): Int {
var count = 1
var biggestElf = 0
var biggestValue = 0
var currentSum = 0
input.forEach {
if(it.trim()=="" ){
if(currentSum>biggestValue) {
biggestElf = count
biggestValue = currentSum
}
count++
currentSum=0
}else{
val value = it.toInt()
currentSum+=value
}
}
return biggestValue
}
}
| 0 | Kotlin | 0 | 0 | 400fe1b693bc186d6f510236f121167f7cc1ab76 | 1,847 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/lucaszeta/adventofcode2020/day21/day21.kt | LucasZeta | 317,600,635 | false | null | package com.lucaszeta.adventofcode2020.day21
import com.lucaszeta.adventofcode2020.ext.getResourceAsText
fun main() {
val foodList = getResourceAsText("/day21/food-list.txt")
.split("\n")
.filter { it.isNotEmpty() }
.map(::Food)
val riskyIngredients = findRiskyIngredients(foodList)
val riskyIngredientsName = riskyIngredients.flatMap { it.value }.toSet()
val safeIngredients = findSafeIngredients(foodList, riskyIngredientsName)
println("Safe ingredients count: ${safeIngredients.size}")
val dangerousIngredients = findDangerousIngredients(riskyIngredients)
println(
"Canonical dangerous ingredient list: %s".format(
dangerousIngredients.joinToString(",")
)
)
}
fun findDangerousIngredients(riskyIngredients: Map<String, MutableSet<String>>): List<String> {
val ingredients = riskyIngredients.toMutableMap()
val dangerousList = mutableMapOf<String, String>()
while (dangerousList.size < ingredients.keys.size) {
ingredients
.filter { it.value.size == 1 }
.forEach { (allergen, ingredient) ->
val dangerousIngredient = ingredient.first()
dangerousList[allergen] = dangerousIngredient
ingredients.forEach {
it.value.remove(dangerousIngredient)
}
}
}
return dangerousList
.toList()
.sortedBy { it.first }
.map { it.second }
}
fun findRiskyIngredients(foodList: List<Food>): Map<String, MutableSet<String>> {
val riskyIngredients = mutableMapOf<String, MutableSet<String>>()
for (food in foodList) {
food.allergens.forEach { allergen ->
if (riskyIngredients.containsKey(allergen)) {
val commonIngredients = riskyIngredients
.getValue(allergen)
.intersect(food.ingredients)
riskyIngredients[allergen] = commonIngredients.toMutableSet()
} else {
riskyIngredients[allergen] = food.ingredients.toMutableSet()
}
}
}
return riskyIngredients.toMap()
}
fun findSafeIngredients(
foodList: List<Food>,
riskyIngredients: Set<String>
) = foodList
.flatMap { it.ingredients }
.filterNot { riskyIngredients.contains(it) }
| 0 | Kotlin | 0 | 1 | 9c19513814da34e623f2bec63024af8324388025 | 2,350 | advent-of-code-2020 | MIT License |
src/main/kotlin/days/Day7.kt | MaciejLipinski | 317,582,924 | true | {"Kotlin": 60261} | package days
class Day7 : Day(7) {
override fun partOne(): Any {
val rules = inputList.map { BagRule.from(it) }
return rules
.filter { it.canContain("shiny gold", rules) }
.count()
}
override fun partTwo(): Any {
val rules = inputList.map { BagRule.from(it) }
return rules
.first { it.color == "shiny gold" }
.bagsRequiredInside(rules)
}
}
data class BagRule(val color: String, val allowedColors: Map<String, Int>) {
fun canContain(color: String, rules: List<BagRule>): Boolean {
return if (allowedColors.containsKey(color)) {
return true
} else {
allowedColors.keys.any { allowedColor ->
rules.first { it.color == allowedColor }
.canContain(color, rules)
}
}
}
fun bagsRequiredInside(rules: List<BagRule>): Int {
var count = 0
allowedColors.forEach { (color, bagCount) ->
count += bagCount + bagCount * rules.first { it.color == color }.bagsRequiredInside(rules)
}
return count
}
companion object {
fun from(input: String): BagRule {
val tokens = input.split(" ")
val color = tokens[0] + " " + tokens[1]
if (input.contains("contain no other bags")) {
return BagRule(color, emptyMap())
}
val rules = tokens
.subList(4, tokens.lastIndex)
.reduce { acc, s -> "$acc $s" }
.split(",")
.map {
val ruleTokens = it.trim().split(" ")
val number = ruleTokens[0].toInt()
val ruleColor = ruleTokens[1] + " " + ruleTokens[2]
ruleColor to number
}.toMap()
return BagRule(color, rules)
}
}
} | 0 | Kotlin | 0 | 0 | 1c3881e602e2f8b11999fa12b82204bc5c7c5b51 | 1,969 | aoc-2020 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/dev/shtanko/algorithms/leetcode/ClosestBST.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <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.LinkedList
import kotlin.math.abs
/**
* 270. Closest Binary Search Tree Value
* https://leetcode.com/problems/closest-binary-search-tree-value/
*/
fun interface ClosestBST {
fun closestValue(root: TreeNode?, target: Double): Int
}
/**
* Approach 1: Recursive Inorder + Linear search
* Time complexity : O(N)
* Space complexity : O(N)
*/
class RecursiveInorder : ClosestBST {
override fun closestValue(root: TreeNode?, target: Double): Int {
val nums = inorder(root)
val comparator = Comparator<Int> { o1, o2 ->
val first = abs(o1 - target)
val second = abs(o2 - target)
return@Comparator if (first < second) -1 else 1
}
return nums.minWith(comparator)
}
private fun inorder(root: TreeNode?): List<Int> {
if (root == null) return emptyList()
val nums = mutableListOf<Int>()
inorder(root.left)
nums.add(root.value)
inorder(root.right)
return nums
}
}
/**
* Approach 2: Iterative Inorder, O(k) time
*/
class IterativeInorder : ClosestBST {
override fun closestValue(root: TreeNode?, target: Double): Int {
val stack: LinkedList<TreeNode?> = LinkedList()
var pred = Int.MIN_VALUE
var node = root
while (stack.isNotEmpty() || node != null) {
while (node != null) {
stack.add(node)
node = node.left
}
node = stack.removeLast()
if (pred <= target && target < node!!.value) {
return if (abs(
pred - target,
) < abs(node.value - target)
) {
pred
} else {
node.value
}
}
pred = node!!.value
node = node.right
}
return pred
}
}
/**
* Approach 3: Binary Search
* Time complexity : O(H)
* Space complexity : O(1)
*/
class ClosestBSTBinarySearch : ClosestBST {
override fun closestValue(root: TreeNode?, target: Double): Int {
var value: Int
var node = root
var closest: Int = node?.value ?: 0
while (node != null) {
value = node.value
closest = if (abs(value - target) < abs(closest - target)) {
value
} else {
closest
}
node = if (target < node.value) {
node.left
} else {
node.right
}
}
return closest
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,232 | kotlab | Apache License 2.0 |
src/Day08.kt | vonElfvin | 572,857,181 | false | {"Kotlin": 11658} | fun main() {
fun checkVisible(x: Int, y: Int, trees: List<String>): Boolean {
val current = trees[y][x]
for (left in 0 until x) {
if (trees[y][left] >= current) break
if (left == x - 1) return true
}
for (right in x + 1 until trees[0].length) {
if (trees[y][right] >= current) break
if (right == trees[0].length - 1) return true
}
for (up in 0 until y) {
if (trees[up][x] >= current) break
if (up == y - 1) return true
}
for (down in y + 1 until trees.size) {
if (trees[down][x] >= current) break
if (down == trees.size - 1) return true
}
return false
}
fun checkScore(x: Int, y: Int, trees: List<String>): Int {
val current = trees[y][x]
var leftScore = 0
for (left in x - 1 downTo 0) {
leftScore++
if (trees[y][left] >= current) break
}
var rightScore = 0
for (right in x + 1 until trees[0].length) {
rightScore++
if (trees[y][right] >= current) break
}
var upScore = 0
for (up in y - 1 downTo 0) {
upScore++
if (trees[up][x] >= current) break
}
var downScore = 0
for (down in y + 1 until trees.size) {
downScore++
if (trees[down][x] >= current) break
}
return leftScore * rightScore * upScore * downScore
}
fun part1(trees: List<String>): Int {
val height = trees.size
val width = trees[0].length
var visible = width * 2 + height * 2 - 4
for (y in 1 until height - 1) {
for (x in 1 until width - 1) {
if (checkVisible(x, y, trees)) visible++
}
}
return visible
}
fun part2(trees: List<String>): Int {
val height = trees.size
val width = trees[0].length
var score = 0
for (y in 1 until height - 1) {
for (x in 1 until width - 1) {
score = maxOf(score, checkScore(x, y, trees))
}
}
return score
}
val input = readInput("Day08")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 6210f23f871f646fcd370ec77deba17da4196efb | 2,283 | Advent-of-Code-2022 | Apache License 2.0 |
src/Day04.kt | Jaavv | 571,865,629 | false | {"Kotlin": 14896} | import kotlin.time.ExperimentalTime
import kotlin.time.measureTimedValue
// https://adventofcode.com/2022/day/4
@OptIn(ExperimentalTime::class)
fun main() {
val input = readInput("Day04")
val testinput = readInput("Day04_test")
println(day04Part1(testinput)) //2
println(day04Part1(input)) //542
println(day04Part2(testinput)) //4
println(day04Part2(input)) //900
val timeOfCount = measureTimedValue {
day04partCount(input, ::coveredSection)
day04partCount(input, ::overlap)
}
println("function Count, Duration: ${timeOfCount.duration}") // function Count, Duration: 12.881300ms
val timeOfFilterSize = measureTimedValue {
day04partFilterSize(input, ::coveredSection)
day04partFilterSize(input, ::overlap)
}
println("function FilterSize, Duration: ${timeOfFilterSize.duration}") // function FilterSize, Duration: 4.876800ms
}
fun coveredSection(inp: String): Boolean {
val sections = inp.split("-", ",").map { it.toInt() }
return (sections[0] <= sections[2] && sections[1] >= sections[3]) || (sections[2] <= sections[0] && sections[3] >= sections[1])
}
fun day04Part1(input: List<String>): Int {
return input.filter { coveredSection(it) }.size
}
fun overlap(inp: String): Boolean {
val sections = inp.split("-", ",").map { it.toInt() }
return (sections[0]..sections[1]).any { it in (sections[2]..sections[3]) }
}
fun day04Part2(input: List<String>): Int {
return input.filter { overlap(it) }.size
}
fun day04partCount(input: List<String>, func: (String) -> Boolean): Int {
return input.count { func(it) }
}
fun day04partFilterSize(input: List<String>, func: (String) -> Boolean): Int {
return input.filter { func(it) }.size
}
| 0 | Kotlin | 0 | 0 | 5ef23a16d13218cb1169e969f1633f548fdf5b3b | 1,747 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | rod41732 | 572,917,438 | false | {"Kotlin": 85344} | fun main() {
val elfRucksacks = readInput("Day03")
fun part1(elfs: List<String>): Int {
return elfs.map { it.chunked(it.length / 2) }.map(::commonChar).sumOf(::calculatePriority)
}
fun part2(elfs: List<String>): Int {
return elfs.chunked(3).map(::commonChar).sumOf(::calculatePriority)
}
val elfRucksacksTest = readInput("Day03_test")
check(part1(elfRucksacksTest) == 157)
check(part2(elfRucksacksTest) == 70)
println("Part 1")
println(part1(elfRucksacks))
println("Part 2")
println(part2(elfRucksacks))
}
fun calculatePriority(char: Char): Int = (char.lowercaseChar() - 'a') + 1 + if (char.isUpperCase()) 26 else 0
fun commonChar(strings: Iterable<String>): Char {
return strings.map { it.toSet() }.reduce { acc, it -> acc intersect it }.first()
}
| 0 | Kotlin | 0 | 0 | 1d2d3d00e90b222085e0989d2b19e6164dfdb1ce | 824 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day18.kt | fmborghino | 573,233,162 | false | {"Kotlin": 60805} | // cubes
// for N cubes, there are N * 6 faces maximum
// for x, y, z location of a cube, there is a common face IFF i
// any pair xy, yz, xz is the same AND the other coordinate is off by one
// so for example Node(1, 1, 1) has a shared face with Node(1, 1, 2)
// for each shared face, subtract 2 from the faces maximum
data class Node3D(val x: Int, val y: Int, val z: Int) {
fun faceNeighbors(): Set<Node3D> {
return setOf(
Node3D(x -1 , y, z),
Node3D(x + 1, y, z),
Node3D(x, y - 1, z),
Node3D(x, y + 1, z),
Node3D(x, y, z - 1),
Node3D(x, y, z + 1),
)
}
companion object {
fun of(input: String): Node3D =
input.split(",").let { (x, y, z) -> Node3D(x.toInt(), y.toInt(), z.toInt()) }
}
}
fun main() {
val _day_ = 18
fun log(message: Any?) {
println(message)
}
fun parse(input: List<String>): Set<Node3D> {
return buildSet {
addAll(input.map { Node3D.of(it) })
}.toSet()
}
// we'll use Node3D.faceNeighbors to spot neighbor nodes
// we'll add BOTH "faces" as two pairs: Pair<nodeA, nodeB>, Pair<nodeB, nodeA> in a set
// this will de-dup when we compare the pair the other way
// this is a little wasteful, but we can optimize later if needed
fun findSharedFaces(grid: Set<Node3D>): Set<Pair<Node3D, Node3D>> {
val sharedFaces: Set<Pair<Node3D, Node3D>> = buildSet {
grid.forEach { a ->
a.faceNeighbors().forEach() { b ->
if (b in grid) {
add(Pair(a, b))
add(Pair(b, a))
}
}
}
}
return sharedFaces
}
fun part1(grid: Set<Node3D>): Int {
// faces not covered is all the possible faces minus the shared faces
return (grid.size * 6) - findSharedFaces(grid).size
}
// NOPE this doesn't account for empty inside nodes in adjacent groups
fun countEnclosedNodes(grid: Set<Node3D>): Int {
var count = 0
(grid.minOf { it.x } - 1..grid.maxOf { it.x } + 1).forEach { x ->
(grid.minOf { it.y } - 1..grid.maxOf { it.y } + 1).forEach { y ->
(grid.minOf { it.z } - 1..grid.maxOf { it.z } + 1).forEach { z ->
val n = Node3D(x, y, z)
if (n !in grid) { // it's a empty spot
if (n.faceNeighbors().filter { it in grid }.size == 6 ) { // and it's surrounded
count++
}
}
}
}
}
return count
}
fun findOutsideNodes(grid: Set<Node3D>): Set<Node3D> {
val minX = grid.minOf { it.x } - 1
val minY = grid.minOf { it.y } - 1
val minZ = grid.minOf { it.z } - 1
val maxX = grid.maxOf { it.x } + 1
val maxY = grid.maxOf { it.y } + 1
val maxZ = grid.maxOf { it.z } + 1
val startNode = Node3D(minX, minY, minZ)
val frontier = mutableListOf<Node3D>(startNode)
val visited: MutableSet<Node3D> = mutableSetOf()
val outside = mutableListOf<Node3D>(startNode)
while (frontier.isNotEmpty()) {
val n = frontier.removeAt(0)
if (n !in visited) {
visited.add(n)
n.faceNeighbors().forEach {
if (it.x in minX..maxX &&
it.y in minY..maxY &&
it.z in minZ..maxZ &&
it !in grid) {
frontier.add(it)
outside.add(it)
}
}
}
}
return outside.toSet()
}
fun part2(grid: Set<Node3D>): Int {
// 1. BFS to generate all outside nodes starting next to minX, minY, minZ, within maximum cube
// 2. iterate over the grid and count all that have outside node neighbors (each neighbor is an outside face)
val outsideNodes: Set<Node3D> = findOutsideNodes(grid)
return grid.sumOf { node -> node.faceNeighbors().count { it in outsideNodes } }
}
// test inputs
val testInput = readInput("Day${_day_}_test.txt")
val testGrid = parse(testInput)
// test part 1
val test1 = part1(testGrid)
check(test1 == 64) { "!!! test part 1 failed with: $test1" }
// game inputs
val gameInput = readInput("Day${_day_}.txt")
val gameGrid = parse(gameInput)
// game part 1
val game1 = part1(gameGrid)
println("*** game part 1: $game1")
check(game1 == 4604) { "!!! game part 1 failed with: $game1" }
// test part 2
val test2 = part2(testGrid)
check(test2 == 58) { "!!! test part 2 failed with: $test2" }
// game part 2
val game2 = part2(gameGrid)
println("*** game part 2: $game2")
check(game2 == 2604) { "!!! game part 2 failed with: $game2" }
}
| 0 | Kotlin | 0 | 0 | 893cab0651ca0bb3bc8108ec31974654600d2bf1 | 4,980 | aoc2022 | Apache License 2.0 |
src/day04/Day04.kt | ayukatawago | 572,742,437 | false | {"Kotlin": 58880} | package day04
import readInput
fun main() {
fun String.toIntSetPair(): Pair<Set<Int>, Set<Int>>? {
val splitInput = split(',')
if (splitInput.size != 2) return null
val firstInput = splitInput[0].split('-')
val secondInput = splitInput[1].split('-')
if (firstInput.size != 2 || secondInput.size != 2) return null
val firstRange = firstInput[0].toInt()..firstInput[1].toInt()
val secondRange = secondInput[0].toInt()..secondInput[1].toInt()
return firstRange.toSet() to secondRange.toSet()
}
fun part1(pairList: List<Pair<Set<Int>, Set<Int>>>): Int {
var score = 0
pairList.forEach { (firstSet, secondSet) ->
if (secondSet + firstSet == secondSet || firstSet + secondSet == firstSet) {
score++
}
}
return score
}
fun part2(pairList: List<Pair<Set<Int>, Set<Int>>>): Int {
var score = 0
pairList.forEach { (firstSet, secondSet) ->
if ((secondSet - firstSet) != secondSet || (firstSet - secondSet) != firstSet) {
score++
}
}
return score
}
val testInput = readInput("day04/Day04_test")
val testPairList: List<Pair<Set<Int>, Set<Int>>> = testInput.mapNotNull { it.toIntSetPair() }
println(part1(testPairList))
println(part2(testPairList))
}
| 0 | Kotlin | 0 | 0 | 923f08f3de3cdd7baae3cb19b5e9cf3e46745b51 | 1,395 | advent-of-code-2022 | Apache License 2.0 |
kotlin/src/main/kotlin/com/github/jntakpe/aoc2022/days/Day17.kt | jntakpe | 572,853,785 | false | {"Kotlin": 72329, "Rust": 15876} | package com.github.jntakpe.aoc2022.days
import com.github.jntakpe.aoc2022.shared.Day
import com.github.jntakpe.aoc2022.shared.readInput
object Day17 : Day {
override val input = readInput(17).map { Jet.from(it) }
override fun part1() = solve(2022)
override fun part2() = solve(1000000000000)
private fun solve(rounds: Long): Long {
var height = 0
var moves = 0
val blocked = buildSet { (0..7).map { add(Position(it, 0)) } }.toMutableSet()
val cycleCache = mutableMapOf<Cycle, Int>()
val heights = mutableListOf<Int>()
val shapes = Shape.values()
repeat(minOf(Int.MAX_VALUE.toLong(), rounds).toInt()) { i ->
val key = Cycle.from(height, blocked, moves, i)
val initial = Position(3, height + 4)
val (rock, idx) = rockFall(Rock(shapes[(i % shapes.size)], initial), moves, blocked)
moves = idx
blocked += rock.positions
height = maxOf(height, rock.positions.maxOf { it.y })
heights += height
cycleCache[key]?.also { return repeatCycles(it, i, height, heights, rounds) }
cycleCache[key] = i
}
return height.toLong()
}
private fun repeatCycles(previousIdx: Int, i: Int, height: Int, heights: List<Int>, rounds: Long): Long {
val diff = (heights[i] - heights[previousIdx]).toLong()
val cycles = (rounds - (i + 1)) / (i - previousIdx)
val rem = ((rounds - (i + 1)) % (i - previousIdx)).toInt()
return height.toLong() + cycles * diff + heights[previousIdx + rem] - heights[previousIdx]
}
private tailrec fun rockFall(rock: Rock, idx: Int, blocked: Set<Position>): Pair<Rock, Int> {
val jet = input[idx % input.size]
val pushed = rock.push(jet, blocked)
val down = pushed.down(blocked)
if (down.position == pushed.position) {
return down to idx + 1
}
return rockFall(down, idx + 1, blocked)
}
data class Cycle(val rocks: List<Boolean>, val shape: Int, val jet: Int) {
companion object {
fun from(height: Int, blocked: Set<Position>, moves: Int, i: Int): Cycle {
val floor = (1..7)
.map { (0..15).map { h -> Position(it, height - h) in blocked } }
.flatten()
return Cycle(floor, i % 5, moves % input.size)
}
}
}
enum class Jet {
LEFT,
RIGHT;
companion object {
fun from(char: Char) = when (char) {
'<' -> LEFT
'>' -> RIGHT
else -> error("Unknown char $char")
}
}
}
class Rock(private val shape: Shape, val position: Position) {
val positions = shape.positions.map { it + position }
fun push(jet: Jet, blockedPositions: Iterable<Position>): Rock {
return when (jet) {
Jet.RIGHT -> moveTowards(Position(1, 0))
Jet.LEFT -> moveTowards(Position(-1, 0))
}.takeIf { it.isValid(blockedPositions) } ?: this
}
fun down(blockedPositions: Iterable<Position>): Rock {
return moveTowards(Position(0, -1))
.takeIf { it.isValid(blockedPositions) }
?: this
}
private fun isValid(blockedPositions: Iterable<Position>): Boolean {
val withinWalls = positions.all { it.x in 1..7 }
val aboveFloor = positions.all { it.y > 0 }
val notOverlappingRocks = positions.none { it in blockedPositions }
return withinWalls && aboveFloor && notOverlappingRocks
}
private fun moveTowards(next: Position) = Rock(shape, position + next)
}
data class Position(val x: Int, val y: Int) {
operator fun plus(other: Position) = Position(x + other.x, y + other.y)
}
enum class Shape(val positions: List<Position>) {
MINUS((0..3).map { Position(it, 0) }),
PLUS(buildList {
add(Position(1, 0))
addAll((0..2).map { Position(it, 1) })
add(Position(1, 2))
}),
L((0..2).map { Position(it, 0) } + (1..2).map { Position(2, it) }),
BAR((0..3).map { Position(0, it) }),
SQUARE((0..1).flatMap { y -> (0..1).map { Position(it, y) } });
}
} | 1 | Kotlin | 0 | 0 | 63f48d4790f17104311b3873f321368934060e06 | 4,364 | aoc2022 | MIT License |
src/aoc2023/Day10.kt | anitakar | 576,901,981 | false | {"Kotlin": 124382} | package aoc2023
import readInput
fun main() {
data class Point(val x: Int, val y: Int)
data class Move(val nextPoint: Point, val dir: Char)
fun Point.isValid(maze: Array<Array<Char>>): Boolean {
return x >= 0 && x < maze.size && y >= 0 && y < maze[0].size
}
fun Point.nextStep(symbol: Char, dir: Char): Move? {
if (symbol == '|' && dir == 'N') return Move(Point(x - 1, y), 'N')
else if (symbol == '|' && dir == 'S') return Move(Point(x + 1, y), 'S')
else if (symbol == '-' && dir == 'E') return Move(Point(x, y + 1), 'E')
else if (symbol == '-' && dir == 'W') return Move(Point(x, y - 1), 'W')
else if (symbol == 'L' && dir == 'S') return Move(Point(x, y + 1), 'E')
else if (symbol == 'L' && dir == 'W') return Move(Point(x - 1, y), 'N')
else if (symbol == 'J' && dir == 'S') return Move(Point(x, y - 1), 'W')
else if (symbol == 'J' && dir == 'E') return Move(Point(x - 1, y), 'N')
else if (symbol == '7' && dir == 'N') return Move(Point(x, y - 1), 'W')
else if (symbol == '7' && dir == 'E') return Move(Point(x + 1, y), 'S')
else if (symbol == 'F' && dir == 'N') return Move(Point(x, y + 1), 'E')
else if (symbol == 'F' && dir == 'W') return Move(Point(x + 1, y), 'S')
else return null
}
fun findCycle(start: Point, maze: Array<Array<Char>>): List<Point>? {
for (dir in listOf('N', 'E', 'S', 'W')) {
var curDir = dir
val cycle = mutableListOf<Point>()
cycle.add(start)
var cur: Point? = when (curDir) {
'N' -> Point(start.x - 1, start.y)
'S' -> Point(start.x + 1, start.y)
'E' -> Point(start.x, start.y + 1)
'W' -> Point(start.x, start.y - 1)
else -> null
}
if (cur == null || !cur.isValid(maze)) continue
do {
cycle.add(cur!!)
val next = cur.nextStep(maze[cur.x][cur.y], curDir)
if (next != null && next.nextPoint.isValid(maze)) {
cur = next.nextPoint
curDir = next.dir
} else {
cur = null
}
} while (cur != start && cur != null)
if (cur != null && cycle.size > 1) {
return cycle
}
}
return null
}
fun part1(lines: List<String>): Int {
val maze = Array(lines.size) { Array(lines[0].length) { '.' } }
for ((index, line) in lines.withIndex()) {
maze[index] = line.toCharArray().toTypedArray()
}
val startX = maze.indexOfFirst { it.contains('S') }
val startY = maze[startX].indexOfFirst { it == 'S' }
val cycle = findCycle(Point(startX, startY), maze)
return (cycle!!.size + 1) / 2
}
fun findNeighbours(point: Point): List<Point> {
return listOf(
Point(point.x - 1, point.y),
Point(point.x + 1, point.y),
Point(point.x, point.y - 1),
Point(point.x, point.y + 1)
)
}
fun outsideLoop(cycle: List<Point>, maze: Array<Array<Char>>): MutableSet<Point> {
val outside = mutableSetOf<Point>()
for (i in maze[0].indices) {
if (!cycle.contains(Point(0, i))) {
outside.add(Point(0, i))
}
if (!cycle.contains(Point(maze.size - 1, i))) {
outside.add(Point(maze.size - 1, i))
}
}
for (i in maze.indices) {
if (!cycle.contains(Point(i, 0))) {
outside.add(Point(i, 0))
}
if (!cycle.contains(Point(i, maze[0].size - 1))) {
outside.add(Point(i, maze[0].size - 1))
}
}
val toAdd = mutableListOf<Point>()
do {
outside.addAll(toAdd)
toAdd.clear()
for (point in outside) {
for (neighbour in findNeighbours(point)) {
if (neighbour.isValid(maze) && !cycle.contains(neighbour) && !outside.contains(neighbour)) {
toAdd.add(neighbour)
}
}
}
} while (toAdd.isNotEmpty())
return outside
}
fun findInside(cycle: List<Point>, maze: Array<Array<Char>>): MutableSet<Point> {
val insideHorizontally = mutableSetOf<Point>()
for (i in maze.indices) {
var linesMet = 0
for (j in maze[i].indices) {
if (cycle.contains(Point(i, j))) {
val prev = Point(i, j - 1)
val next = Point(i, j + 1)
val cycleIndex = cycle.indexOf(Point(i, j))
val neighsInCycle = mutableSetOf<Point>()
neighsInCycle.add(cycle[if (cycleIndex == 0) (cycle.size - 1) else (cycleIndex - 1)])
neighsInCycle.add(cycle[(cycleIndex + 1) % cycle.size])
if (!neighsInCycle.containsAll(setOf(prev, next)))
linesMet += 1
} else if (linesMet % 2 == 1) {
insideHorizontally.add(Point(i, j))
}
}
}
val insideVertically = mutableSetOf<Point>()
for (j in maze[0].indices) {
var linesMet = 0
for (i in maze.indices) {
if (cycle.contains(Point(i, j))) {
val prev = Point(i - 1, j)
val next = Point(i + 1, j)
val cycleIndex = cycle.indexOf(Point(i, j))
val neighsInCycle = mutableSetOf<Point>()
neighsInCycle.add(cycle[if (cycleIndex == 0) (cycle.size - 1) else (cycleIndex - 1)])
neighsInCycle.add(cycle[(cycleIndex + 1) % cycle.size])
if (!neighsInCycle.containsAll(setOf(prev, next)))
linesMet += 1
} else if (linesMet % 2 == 1) {
insideVertically.add(Point(i, j))
}
}
}
return insideHorizontally.intersect(insideVertically).toMutableSet()
}
fun part2(lines: List<String>): Int {
val maze = Array(lines.size) { Array(lines[0].length) { '.' } }
for ((index, line) in lines.withIndex()) {
maze[index] = line.toCharArray().toTypedArray()
}
val startX = maze.indexOfFirst { it.contains('S') }
val startY = maze[startX].indexOfFirst { it == 'S' }
val cycle = findCycle(Point(startX, startY), maze)
val inside = findInside(cycle!!, maze)
return inside.size
}
println(part1(readInput("aoc2023/Day10_test")))
println(part1(readInput("aoc2023/Day10_test2")))
println(part1(readInput("aoc2023/Day10_test3")))
println(part1(readInput("aoc2023/Day10_test4")))
println(part1(readInput("aoc2023/Day10")))
println(part2(readInput("aoc2023/Day10_test5")))
println(part2(readInput("aoc2023/Day10_test6")))
println(part2(readInput("aoc2023/Day10_test7")))
println(part2(readInput("aoc2023/Day10_test8")))
println(part2(readInput("aoc2023/Day10")))
} | 0 | Kotlin | 0 | 1 | 50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf | 7,242 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/advent/day15/Chiton.kt | hofiisek | 434,171,205 | false | {"Kotlin": 51627} | package advent.day15
import advent.Matrix
import advent.Position
import advent.adjacents
import advent.loadInput
import java.io.File
import java.util.*
/**
* @author <NAME>
*/
data class CavePoint(val riskLevel: Int, val position: Position)
data class GraphNode(
val cavePoint: CavePoint,
val edgesTo: Set<CavePoint>,
var riskLevel: Int = cavePoint.riskLevel,
var visited: Boolean = false,
val path: MutableSet<CavePoint> = mutableSetOf()
) {
val position: Position by cavePoint::position
}
fun Matrix<CavePoint>.toGraph(): Matrix<GraphNode> = map { rowPoints ->
rowPoints.map { cavePoint -> GraphNode(cavePoint, adjacents(cavePoint.position)) }
}.let(::Matrix)
val <K> Matrix<K>.upperLeft: K
get() = this[0][0]
val <K> Matrix<K>.bottomRight: K
get() = this[rows - 1][cols - 1]
fun Matrix<CavePoint>.print() = joinToString(separator = "\n") { row ->
row.joinToString("") { it.riskLevel.toString() }
}.also(::println)
fun <E> priorityQueueOf(element: E, comparator: Comparator<E>) = PriorityQueue(comparator).apply { add(element) }
operator fun <E> PriorityQueue<E>.plus(elements: Collection<E>) = apply { addAll(elements) }
fun part1(input: File) = loadCavePoints(input)
.let(Matrix<CavePoint>::toGraph)
.let(Matrix<GraphNode>::dodgeThoseChitons)
.riskLevel
fun part2(input: File) = loadCavePoints(input)
.let { matrix ->
val newColsNumber = 5 * matrix.cols
val newRowsNumber = 5 * matrix.rows
val rightExpandedMatrix = matrix.map { row ->
generateSequence(row) { rowPoints ->
rowPoints.map { point ->
val newRiskLevel = (point.riskLevel % 9) + 1
val newRow = point.position.row
val newCol = (point.position.col + matrix.cols) % newColsNumber
CavePoint(newRiskLevel, Position(newRow, newCol))
}
}.take(5).toList().flatten()
}
val downExpandedMatrix = generateSequence(rightExpandedMatrix) { expandedMatrix ->
expandedMatrix.mapIndexed { rowIdx, row ->
row.mapIndexed { colIdx, point ->
val newRiskLevel = (expandedMatrix[rowIdx][colIdx].riskLevel % 9) + 1
val newRow = (point.position.row + matrix.rows) % newRowsNumber
val newCol = point.position.col
CavePoint(newRiskLevel, Position(newRow, newCol))
}
}
}.take(5).toList().flatten()
downExpandedMatrix
}
.let(::Matrix)
.also { it.print() }
.let(Matrix<CavePoint>::toGraph)
.let(Matrix<GraphNode>::dodgeThoseChitons)
.riskLevel
fun Matrix<GraphNode>.dodgeThoseChitons(): GraphNode {
// risk level is added only when a node is entered, so starting node has zero risk level
val start: GraphNode = upperLeft.copy(riskLevel = 0)
val queue: PriorityQueue<GraphNode> = priorityQueueOf(start, compareBy { it.riskLevel })
while (queue.isNotEmpty()) {
when (queue.first().position) {
bottomRight.position -> return queue.first()
else -> {
val curr = queue.remove()
curr.edgesTo
.filterNot { edgeTo -> edgeTo in curr.path } // filter out visited nodes
.map { edgeTo -> getOrThrow(edgeTo.position) }
.filterNot(GraphNode::visited) // filter out open nodes
.map { node ->
node.apply {
riskLevel += curr.riskLevel
visited = true
path.add(node.cavePoint)
}
}
.forEach(queue::add)
}
}
}
throw IllegalArgumentException("No solution")
}
fun loadCavePoints(input: File): Matrix<CavePoint> = input.readLines()
.map { it.split("").filterNot(String::isBlank).map(String::toInt) }
.mapIndexed { rowIdx, row ->
row.mapIndexed { colIdx, riskLevel -> CavePoint(riskLevel, Position(rowIdx, colIdx)) }
}.let(::Matrix)
fun main() {
with(loadInput(day = 15)) {
// with(loadInput(day = 15, filename = "input_example.txt")) {
println(part1(this))
println(part2(this))
}
} | 0 | Kotlin | 0 | 2 | 3bd543ea98646ddb689dcd52ec5ffd8ed926cbbb | 4,338 | Advent-of-code-2021 | MIT License |
leetcode2/src/leetcode/ShortestUnsortedContinuousSubarray.kt | hewking | 68,515,222 | false | null | package leetcode
import java.util.*
/**
* Created by test
* Date 2019/6/18 0:20
* Description
* https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray/
* 581. 最短无序连续子数组
*
* 给定一个整数数组,你需要寻找一个连续的子数组,如果对这个子数组进行升序排序,那么整个数组都会变为升序排序。
你找到的子数组应是最短的,请输出它的长度。
示例 1:
输入: [2, 6, 4, 8, 10, 9, 15]
输出: 5
解释: 你只需要对 [6, 4, 8, 10, 9] 进行升序排序,那么整个表都会变为升序排序。
说明 :
输入的数组长度范围在 [1, 10,000]。
输入的数组可能包含重复元素 ,所以升序的意思是<=。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
object ShortestUnsortedContinuousSubarray {
class Solution {
/**
* 思路:
* 1.先排序,因为如果步排序是不知道谁是最大的值
* 2.掐头去尾
* 3.l 循环中的<= 是因为重复元素,和已经排序好的 [1,2,3,4]的影响
*/
fun findUnsortedSubarray(nums: IntArray): Int {
val arr = nums.copyOf()
Arrays.sort(nums)
var l = 0
var r = nums.size -1
while (l <= r && nums[l] == arr[l]) {
l++
}
while (l < r && nums[r] == arr[r]) {
r--
}
return r - l + 1
}
}
} | 0 | Kotlin | 0 | 0 | a00a7aeff74e6beb67483d9a8ece9c1deae0267d | 1,673 | leetcode | MIT License |
src/Day17.kt | andrikeev | 574,393,673 | false | {"Kotlin": 70541, "Python": 18310, "HTML": 5558} | import kotlin.math.pow
fun main() {
fun simulation(input: String, steps: Long): Long {
return Chamber(steps, GasJets(input)).simulate()
}
fun part1(input: String): Long = simulation(input, 2022L)
fun part2(input: String): Long = simulation(input, 1_000_000_000_000)
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day17_test")
check(part1(testInput.first()).also { println("part1 test: $it") } == 3068L)
// check(part2(testInput.first()).also { println("part2 test: $it") } == 1514285714288)
val input = readInput("Day17")
println(part1(input.first()))
println(part2(input.first()))
}
private class Chamber(
private val steps: Long,
private val gasJets: GasJets,
) {
private val blockGenerator = BlockGenerator()
private var blocksArray = mutableListOf<Array<Boolean>>()
private var currentBlock = blockGenerator.get(3)
private var blocks = 0L
private var step = 0L
private var height = 0L
fun simulate(): Long {
while (blocks < steps) {
gasPush(gasJets.getNext())
detektCycle()
}
return height
}
private fun gasPush(direction: GasDirection) {
if (currentBlock.canGoTo(direction)) {
currentBlock.push(direction)
}
if (currentBlock.canFall()) {
currentBlock.fall()
} else {
addBlock()
}
}
private fun addBlock() {
blocks++
currentBlock.points().sortedBy(Pair<Long, Long>::second).forEach { (x, y) -> take(x, y) }
currentBlock = blockGenerator.get(blocksArray.size + 3L)
}
private fun take(x: Long, y: Long) {
if (y > blocksArray.lastIndex) {
blocksArray.add(Array(7) { j -> j == x.toInt() })
height++
} else {
blocksArray[y.toInt()][x.toInt()] = true
}
}
private fun taken(x: Long, y: Long): Boolean {
return y < blocksArray.size && blocksArray[(y).toInt()][x.toInt()]
}
private fun Block.intersects(): Boolean = points().any { (x, y) -> x < 0 || x > 6 || y < 0 || taken(x, y) }
private fun Block.canFall(): Boolean = !copyBlock(y = y - 1).intersects()
private fun Block.canGoTo(direction: GasDirection): Boolean = when (direction) {
GasDirection.Left -> !copyBlock(x = x - 1).intersects()
GasDirection.Right -> !copyBlock(x = x + 1).intersects()
}
private fun printArray() {
println()
blocksArray.reversed().take(100).forEach { row ->
row.forEach {
if (it) print("■") else print("∙")
}
println()
}
}
private var preCycleHeight = 0L
private var preCycleBlocks = 0L
private fun detektCycle() {
step++
if (step % 10091L == 0L) {
if (step / 10091L == 1L) {
preCycleHeight = height
preCycleBlocks = blocks
}
if (step / 10091L == 2L) {
val cycleHeight = height - preCycleHeight
val cycleBlocks = blocks - preCycleBlocks
val cyclesCount = (steps - preCycleBlocks) / cycleBlocks
height += cycleHeight * (cyclesCount - 1)
blocks += cycleBlocks * (cyclesCount - 1)
}
}
}
}
private class BlockGenerator {
private var index = 0
fun get(y: Long): Block {
if (index > 4) {
index %= 5
}
return when (index++) {
0 -> Block.Minus(2, y)
1 -> Block.Plus(2, y)
2 -> Block.Angle(2, y)
3 -> Block.Stick(2, y)
4 -> Block.Box(2, y)
else -> error("wrong index")
}
}
}
private sealed interface Block {
var x: Long
var y: Long
fun push(direction: GasDirection) {
when (direction) {
GasDirection.Left -> x--
GasDirection.Right -> x++
}
}
fun fall() {
y--
}
fun copyBlock(x: Long = this.x, y: Long = this.y): Block {
return when (this) {
is Angle -> copy(x = x, y = y)
is Box -> copy(x = x, y = y)
is Minus -> copy(x = x, y = y)
is Plus -> copy(x = x, y = y)
is Stick -> copy(x = x, y = y)
}
}
fun points(): Set<Pair<Long, Long>>
data class Minus(
override var x: Long,
override var y: Long,
) : Block {
override fun points(): Set<Pair<Long, Long>> = buildSet {
repeat(4) { i -> add(Pair(x + i, y)) }
}
}
data class Plus(
override var x: Long,
override var y: Long,
) : Block {
override fun points(): Set<Pair<Long, Long>> = buildSet {
add(Pair(x, y + 1))
add(Pair(x + 1, y))
add(Pair(x + 1, y + 1))
add(Pair(x + 1, y + 2))
add(Pair(x + 2, y + 1))
}
}
data class Angle(
override var x: Long,
override var y: Long,
) : Block {
override fun points(): Set<Pair<Long, Long>> = buildSet {
add(Pair(x, y))
add(Pair(x + 1, y))
add(Pair(x + 2, y))
add(Pair(x + 2, y + 1))
add(Pair(x + 2, y + 2))
}
}
data class Stick(
override var x: Long,
override var y: Long,
) : Block {
override fun points(): Set<Pair<Long, Long>> = buildSet {
repeat(4) { i -> add(Pair(x, y + i)) }
}
}
data class Box(
override var x: Long,
override var y: Long,
) : Block {
override fun points(): Set<Pair<Long, Long>> = buildSet {
repeat(2) { i -> repeat(2) { j -> add(Pair(x + i, y + j)) } }
}
}
}
private enum class GasDirection {
Left, Right
}
private class GasJets(input: String) {
private var index = 0
private val gas = input.toDirections()
private fun String.toDirections(): List<GasDirection> = map {
when (it) {
'<' -> GasDirection.Left
'>' -> GasDirection.Right
else -> error("wrong sign")
}
}
fun getNext(): GasDirection {
if (index > gas.lastIndex) {
index %= gas.size
}
return gas[index++]
}
}
| 0 | Kotlin | 0 | 1 | 1aedc6c61407a28e0abcad86e2fdfe0b41add139 | 6,363 | aoc-2022 | Apache License 2.0 |
day14/prob2.kts | rlei | 435,244,189 | false | {"Assembly": 7573, "C++": 6280, "C": 5787, "C#": 4212, "OCaml": 3872, "Elixir": 3744, "Ruby": 3675, "Dart": 3436, "Prolog": 3064, "JavaScript": 2938, "F#": 2713, "Kotlin": 2100, "D": 1883, "Python": 1686, "Go": 1657, "Julia": 1205, "Clojure": 444, "Awk": 187} | val template = readLine()!!
// skip blank line
readLine()!!
val rules = generateSequence(::readLine)
.map {
val (elemPair, insertion) = it.split(" -> ")
Pair(Pair(elemPair[0], elemPair[1]), insertion[0])
}
.toMap()
// prefix and suffix with something to make sure all characters are double counted
var elemPairs = ("_" + template + "_").windowed(2, 1)
.map { Pair(Pair(it[0], it[1]), 1L) }
.groupBy({ it.first }, { it.second })
.mapValues { (_, counts) -> counts.sum() }
val charCounts = elemPairs.flatMap { (charPair, count) -> listOf(Pair(charPair.first, count), Pair(charPair.second, count)) }
.groupBy({ it.first }, { it.second })
.mapValues { (_, counts) -> counts.sum() / 2 } // because we've double counted
.toMutableMap()
charCounts.remove('_')
// A mixture of FP and imperative - forgive my laziness :p
for (i in 1..40) {
elemPairs = elemPairs.flatMap { (charPair, count) ->
val (ch1, ch2) = charPair
if (ch1 == '_' || ch2 == '_') {
listOf(Pair(charPair, count))
} else {
val insertion = rules[charPair]!!
charCounts.compute(insertion, { _, oldVal -> (oldVal ?: 0) + count })
listOf(Pair(Pair(ch1, insertion), count), Pair(Pair(insertion, ch2), count))
}
}
.groupBy({ it.first }, { it.second })
.mapValues { (_, counts) -> counts.sum() }
}
//println(charCounts)
println(charCounts.maxOf { it.value } - charCounts.minOf { it.value })
| 0 | Assembly | 0 | 5 | 7d7a29b5a8b045fd563dc6625b16714c8e8bd993 | 1,560 | adventofcode2021 | Apache License 2.0 |
src/main/kotlin/Day04.kt | akowal | 434,506,777 | false | {"Kotlin": 30540} | fun main() {
println(Day04.solvePart1())
println(Day04.solvePart2())
}
object Day04 {
private const val BOARD_SIZE = 5
private val numbers: IntArray
private val boards: List<Board>
init {
val input = inputScanner("day04")
numbers = input.nextLine().toIntArray()
boards = sequence { while (input.hasNextInt()) yield(input.nextInt()) }
.windowed(BOARD_SIZE * BOARD_SIZE, BOARD_SIZE * BOARD_SIZE)
.map { createBoard(it) }
.toList()
}
fun solvePart1(): Int {
numbers.forEach { number ->
boards.forEach { board ->
if (board.mark(number) && board.hasWon()) {
return board.unmarked.keys.sum() * number
}
}
}
error("ouch")
}
fun solvePart2(): Int {
val boardsLeft = boards.toMutableList()
numbers.forEach { number ->
val iter = boardsLeft.iterator()
while (iter.hasNext()) {
val board = iter.next()
if (board.mark(number) && board.hasWon()) {
if (boardsLeft.size == 1) {
return board.unmarked.keys.sum() * number
}
iter.remove()
}
}
}
error("ouch")
}
private fun createBoard(values: List<Int>): Board {
val numToPos = values.mapIndexed { i, value ->
value to Position(i/ BOARD_SIZE, i % BOARD_SIZE)
}
return Board(numToPos.toMap().toMutableMap())
}
private data class Position(val row: Int, val col: Int)
@Suppress("ArrayInDataClass")
private data class Board(
val unmarked: MutableMap<Int, Position>,
val rowHits: IntArray = IntArray(BOARD_SIZE),
val colHits: IntArray = IntArray(BOARD_SIZE),
)
private fun Board.hasWon() = rowHits.any { it == BOARD_SIZE } || colHits.any { it == BOARD_SIZE }
private fun Board.mark(number: Int): Boolean {
return unmarked.remove(number)?.apply {
rowHits[row]++
colHits[col]++
} != null
}
}
| 0 | Kotlin | 0 | 0 | 08d4a07db82d2b6bac90affb52c639d0857dacd7 | 2,167 | advent-of-kode-2021 | Creative Commons Zero v1.0 Universal |
2k23/aoc2k23/src/main/kotlin/07.kt | papey | 225,420,936 | false | {"Rust": 88237, "Kotlin": 63321, "Elixir": 54197, "Crystal": 47654, "Go": 44755, "Ruby": 24620, "Python": 23868, "TypeScript": 5612, "Scheme": 117} | package d07
import input.read
fun main() {
println("Part 1: ${part1(read("07.txt"))}")
println("Part 2: ${part2(read("07.txt"))}")
}
class Hand(line: String) {
// A, K, Q, J, T, 9, 8, 7, 6, 5, 4, 3, or 2
enum class CardP1(val value: Char) {
TWO('2'),
THREE('3'),
FOUR('4'),
FIVE('5'),
SIX('6'),
SEVEN('7'),
EIGHT('8'),
NINE('9'),
T('T'),
J('J'),
Q('Q'),
K('K'),
A('A');
companion object {
fun fromChar(value: Char): CardP1? {
return entries.find { it.value == value }
}
}
}
// A, K, Q, T, 9, 8, 7, 6, 5, 4, 3, 2, or J
enum class CardP2(val value: Char) {
J('J'),
TWO('2'),
THREE('3'),
FOUR('4'),
FIVE('5'),
SIX('6'),
SEVEN('7'),
EIGHT('8'),
NINE('9'),
T('T'),
Q('Q'),
K('K'),
A('A');
companion object {
fun fromChar(value: Char): CardP2? {
return entries.find { it.value == value }
}
}
}
enum class Type {
HighCard,
OnePair,
TwoPair,
ThreeOfKind,
FullHouse,
FourOfKind,
FiveOfKind;
companion object {
private fun computeType(top1Count: Int, top2Count: Int): Type {
return when (top1Count) {
5 -> FiveOfKind
4 -> FourOfKind
3 -> {
if (top2Count == 2) {
FullHouse
} else {
ThreeOfKind
}
}
2 -> {
if (top2Count == 2) {
TwoPair
} else {
OnePair
}
}
else -> HighCard
}
}
fun fromHandP1(hand: List<CardP1>): Type {
val byValue = hand.groupBy { it.value }.mapValues { it.value.size }
val counts = byValue.values.sortedByDescending { it }
return computeType(counts[0], counts.getOrElse(1) { _ -> 0 })
}
fun fromHandP2(hand: List<CardP2>): Type {
val byValue = hand.groupBy { it.value }.mapValues { it.value.size }
val counts = byValue.filter { it.key != CardP2.J.value }.values.sortedByDescending { it }
val jokers = hand.count { it.value == CardP2.J.value }
if (jokers == 5) {
return Type.FiveOfKind
}
return computeType(counts[0] + jokers, counts.getOrElse(1) { _ -> 0 })
}
}
}
val cardsP1: List<CardP1>
val cardsP2: List<CardP2>
val typeP1: Type
val typeP2: Type
val bid: Int
init {
cardsP1 = line.split(" ").first().toCharArray().map { CardP1.fromChar(it)!! }
cardsP2 = line.split(" ").first().toCharArray().map { CardP2.fromChar(it)!! }
typeP1 = Type.fromHandP1(cardsP1)
typeP2 = Type.fromHandP2(cardsP2)
bid = line.split(" ").drop(1).first().toInt()
}
companion object {
fun comparatorP1(): Comparator<Hand> {
return Comparator { hand1, hand2 ->
if (hand1.typeP1 != hand2.typeP1) {
hand1.typeP1.compareTo(hand2.typeP1)
} else {
val ret = hand1.cardsP1.zip(hand2.cardsP1).find { s -> s.first != s.second }!!
ret.first.compareTo(ret.second)
}
}
}
fun comparatorP2(): Comparator<Hand> {
return Comparator { hand1, hand2 ->
if (hand1.typeP2 != hand2.typeP2) {
hand1.typeP2.compareTo(hand2.typeP2)
} else {
val ret = hand1.cardsP2.zip(hand2.cardsP2).find { s -> s.first != s.second }!!
ret.first.compareTo(ret.second)
}
}
}
}
}
fun part1(lines: List<String>): Int =
lines.map(::Hand).sortedWith(Hand.comparatorP1()).mapIndexed { index, hand -> (index + 1) * hand.bid }.sum()
fun part2(lines: List<String>): Int =
lines.map(::Hand).sortedWith(Hand.comparatorP2()).mapIndexed { index, hand -> (index + 1) * hand.bid }.sum()
| 0 | Rust | 0 | 3 | cb0ea2fc043ebef75aff6795bf6ce8a350a21aa5 | 4,516 | aoc | The Unlicense |
kotlin/pig-latin/src/main/kotlin/PigLatin.kt | Javran | 352,422,285 | false | {"Haskell": 449574, "Scheme": 220116, "Kotlin": 151245, "Rust": 150637, "Racket": 93970, "Clojure": 26350, "Makefile": 7050} | object PigLatin {
// List of char sequence that should be considered a single cluster of vowel / consonant.
// Longer elements must appear first.
private val clusters: List<Pair<String, Boolean>> = listOf(
"sch" to false, "thr" to false,
"xr" to true, "yt" to true,
"ch" to false, "qu" to false, "th" to false, "rh" to false,
"a" to true, "e" to true, "i" to true, "o" to true, "u" to true,
"y" to false
)
private data class SplitResult(
val head: String,
val headIsVowel: Boolean,
val tail: String
)
// Splits a non-empty word by first vowel / consonant cluster.
// INVARIANT: head + tail == <input word>, where head and tail are from SplitResult.
private fun splitFirstCluster(word: String): SplitResult {
for ((prefix, prefixIsVowel) in clusters) {
if (word.startsWith(prefix)) {
return SplitResult(prefix, prefixIsVowel, word.substring(prefix.length))
}
}
return SplitResult(word.substring(0, 1), false, word.substring(1))
}
// Translates a single word into Pig Latin. It is assumed that the word is not empty.
private fun translateWord(word: String): String {
val (head, headIsVowel, tail) = splitFirstCluster(word)
return when {
headIsVowel ->
// Rule 1
word + "ay"
tail.startsWith("y") ->
// Rule 4
tail + head + "ay"
tail.startsWith("qu") ->
// Rule 3
tail.substring(2) + head + "quay"
else ->
// Rule 2
tail + head + "ay"
}
}
fun translate(phrase: String): String =
phrase.split(" ").map(::translateWord).joinToString(" ")
}
| 0 | Haskell | 0 | 0 | 15891b189864bf6fff1ef79f0521aa560dc41f5b | 1,830 | exercism-solutions | Apache License 2.0 |
src/main/kotlin/Day7.kt | chjaeggi | 728,738,815 | false | {"Kotlin": 87254} | import utils.execFileByLine
import java.lang.IllegalArgumentException
private data class CamelCards(val hand: String, val bid: Int, val type: TYPES = TYPES.HighCard)
private enum class TYPES {
FiveOfAKind, FourOfAKind, FullHouse, ThreeOfAKind, TwoPair, OnePair, HighCard
}
class Day7 {
private val myCards = mutableListOf<CamelCards>()
fun solve(considerJokers: Boolean): Int {
execFileByLine("inputs/input7.txt") {
val split = it.split(" ")
myCards.add(
CamelCards(
split.first(),
split.last().toInt(),
split.first().toType(considerJokers)
)
)
}
return myCards
.sortedWith(higherFirstCardComparator(considerJokers))
.sortedBy { it.type }
.reversed()
.mapIndexed { index, camelCards ->
camelCards.bid * (index + 1)
}
.sum()
}
private fun String.toType(considerJokers: Boolean = false): TYPES {
val groups = this.toCharArray().groupBy { it }
val amountPerCard = mutableMapOf<Char, Int>()
groups.map {
amountPerCard[it.key] = it.value.size
}
if (considerJokers) {
replaceJokersForHighestAmountOfOtherCard(amountPerCard)
}
return when (amountPerCard.size) {
1 -> TYPES.FiveOfAKind
2 -> {
if (amountPerCard.values.any { it == 1 }) {
TYPES.FourOfAKind
} else {
TYPES.FullHouse
}
}
3 -> {
if (amountPerCard.values.any { it == 3 }) {
TYPES.ThreeOfAKind
} else {
TYPES.TwoPair
}
}
4 -> TYPES.OnePair
else -> TYPES.HighCard
}
}
private fun replaceJokersForHighestAmountOfOtherCard(amountPerCard: MutableMap<Char, Int>) {
val numberOfJ = amountPerCard['J']
if (numberOfJ != null && numberOfJ != 5) {
val maxNonJEntry = amountPerCard
.filter { it.key != 'J' }
.maxByOrNull { it.value }
maxNonJEntry?.let {
amountPerCard[it.key] = amountPerCard[it.key]!! + numberOfJ
amountPerCard.remove('J')
}
}
}
private fun higherFirstCardComparator(considerJokers: Boolean = false) =
Comparator<CamelCards> { a, b ->
val arrA = a.hand.toCharArray()
val arrB = b.hand.toCharArray()
var idx = -1
// get first non-matching card index
for (i in 0..arrA.lastIndex) {
if (arrA[i] != arrB[i]) {
idx = i
break
}
}
if (arrA[idx].card2Rank(considerJokers) < arrB[idx].card2Rank(considerJokers)) {
-1
} else {
1
}
}
private fun Char.card2Rank(considerJokers: Boolean = false): Int {
return when (this) {
'A' -> 0
'K' -> 1
'Q' -> 3
'J' -> {
if (!considerJokers) 4 else 14
}
'T' -> 5
'9' -> 6
'8' -> 7
'7' -> 8
'6' -> 9
'5' -> 10
'4' -> 11
'3' -> 12
'2' -> 13
else -> {
throw IllegalArgumentException("Not possible")
}
}
}
} | 0 | Kotlin | 1 | 1 | a6522b7b8dc55bfc03d8105086facde1e338086a | 3,625 | aoc2023 | Apache License 2.0 |
src/main/kotlin/com/github/brpeterman/advent2022/HillClimber.kt | brpeterman | 573,059,778 | false | {"Kotlin": 53108} | package com.github.brpeterman.advent2022
import java.util.LinkedList
class HillClimber(input: String) {
data class HeightMap(val startPos: Coords, val endPos: Coords, val elevations: Map<Coords, Int>)
data class Coords(val row: Int, val col: Int) {
operator fun plus(other: Coords): Coords {
return Coords(row + other.row, col + other.col)
}
}
val map = parseInput(input)
fun climb(): Int {
return climbFrom(map.startPos)!!
}
fun findBestTrail(): Int {
return map.elevations.filter { it.value == 1 }
.map { climbFrom(it.key) }
.filter { it != null }
.map { it!! }
.min()
}
fun climbFrom(start: Coords): Int? {
var current = start
val toVisit = LinkedList(getNeighbors(current))
val bestPathLength = mutableMapOf(current to 0)
toVisit.forEach { bestPathLength[it] = 1 }
while (toVisit.isNotEmpty()) {
current = toVisit.pop()
val pathLength = bestPathLength[current]!!
val neighbors = getNeighbors(current)
neighbors.forEach { neighbor ->
if (bestPathLength[neighbor] == null || bestPathLength[neighbor]!! > pathLength + 1) {
bestPathLength[neighbor] = pathLength + 1
toVisit.add(neighbor)
}
}
}
return bestPathLength[map.endPos]
}
fun getNeighbors(location: Coords): List<Coords> {
return listOf(
Coords(location.row - 1, location.col),
Coords(location.row + 1, location.col),
Coords(location.row, location.col - 1),
Coords(location.row, location.col + 1))
.filter { neighbor ->
map.elevations[neighbor] != null && (map.elevations[neighbor]!! - map.elevations[location]!! <= 1)
}
}
companion object {
fun parseInput(input: String): HeightMap {
val map = HashMap<Coords, Int>()
var startPos = Coords(0, 0)
var endPos = Coords(0, 0)
input.split("\n")
.filter { it.isNotBlank() }
.withIndex()
.forEach { (row, line) ->
line.toCharArray()
.withIndex()
.forEach { (column, char) ->
val elevation = when (char) {
'S' -> {
startPos = Coords(row, column)
1
}
'E' -> {
endPos = Coords(row, column)
26
}
else -> char.code - 96
}
map[Coords(row, column)] = elevation
}
}
return HeightMap(startPos, endPos, map)
}
}
}
| 0 | Kotlin | 0 | 0 | 1407ca85490366645ae3ec86cfeeab25cbb4c585 | 3,066 | advent2022 | MIT License |
src/main/kotlin/pl/jpodeszwik/aoc2023/Day19.kt | jpodeszwik | 729,812,099 | false | {"Kotlin": 55101} | package pl.jpodeszwik.aoc2023
import java.lang.Integer.parseInt
import java.util.*
data class Condition(val variable: Char, val operation: Char, val value: Int) {
fun isSatisfiedBy(systemPart: SystemPart): Boolean {
val varValue = systemPart.values[variable]!!
return when (operation) {
'>' -> varValue > value
'<' -> varValue < value
else -> throw IllegalStateException()
}
}
}
data class Rule(val condition: Condition?, val target: String) {
fun isMatched(systemPart: SystemPart): Boolean {
return condition == null || condition.isSatisfiedBy(systemPart)
}
}
data class SystemPart(val values: Map<Char, Int>)
data class ValueRange(val min: Int, val max: Int) {
fun split(condition: Condition): Pair<ValueRange?, ValueRange?> {
if (condition.operation == '>') {
if (max <= condition.value) {
return Pair(null, this)
}
if (min > condition.value) {
return Pair(this, null)
}
return Pair(ValueRange(condition.value + 1, max), ValueRange(min, condition.value))
}
if (min >= condition.value) {
return Pair(null, this)
}
if (max < condition.value) {
return Pair(this, null)
}
return Pair(ValueRange(min, condition.value - 1), ValueRange(condition.value, max))
}
fun size(): Int {
return max - min + 1
}
}
data class SystemPartValueRanges(val values: Map<Char, ValueRange>) {
fun splitOnCondition(condition: Condition?): Pair<SystemPartValueRanges?, SystemPartValueRanges?> {
if (condition == null) {
return Pair(this, null)
}
val variable = condition.variable
val valueRange = this.values[variable]!!
val pair = valueRange.split(condition)
val matchingRanges = if (pair.first != null) {
val newValues = HashMap(values)
newValues[variable] = pair.first!!
SystemPartValueRanges(newValues)
} else null
val nonMatchingRanges = if (pair.second != null) {
val newValues = HashMap(values)
newValues[variable] = pair.second!!
SystemPartValueRanges(newValues)
} else null
return Pair(matchingRanges, nonMatchingRanges)
}
}
private fun parseRule(ruleLine: String): List<Rule> {
return ruleLine.split(",").map {
val ruleParts = it.split(":", "<", ">")
if (ruleParts.size == 1) {
return@map Rule(null, ruleParts[0])
}
return@map Rule(Condition(it[0], it[1], parseInt(ruleParts[1])), ruleParts[2])
}
}
private fun parseRules(ruleLines: List<String>): Map<String, List<Rule>> {
val m = mutableMapOf<String, List<Rule>>()
ruleLines.forEach {
val parts = it.split("{", "}")
m[parts[0]] = parseRule(parts[1])
}
return m
}
private fun parseSystemParts(lines: List<String>): List<SystemPart> {
return lines.map {
val m = mutableMapOf<Char, Int>()
it.split("{", ",", "}")
.filter { it.isNotBlank() }
.forEach {
val parts = it.split("=")
m[parts[0][0]] = parseInt(parts[1])
}
return@map SystemPart(m)
}
}
private fun isAccepted(part: SystemPart, rules: Map<String, List<Rule>>): Boolean {
var currentStep = "in"
while (currentStep != "R" && currentStep != "A") {
currentStep = rules[currentStep]!!.find { it.isMatched(part) }!!.target
}
return currentStep == "A"
}
private fun part1(rules: Map<String, List<Rule>>, parts: List<SystemPart>) {
val result = parts.filter { isAccepted(it, rules) }.sumOf { it.values.values.sum() }
println(result)
}
private fun part2(rules: Map<String, List<Rule>>) {
val queue = LinkedList<Pair<String, SystemPartValueRanges>>()
queue.add(
Pair(
"in", SystemPartValueRanges(
mapOf(
'x' to ValueRange(1, 4000),
'm' to ValueRange(1, 4000),
'a' to ValueRange(1, 4000),
's' to ValueRange(1, 4000),
)
)
)
)
val winningRanges = mutableListOf<SystemPartValueRanges>()
while (queue.isNotEmpty()) {
val current = queue.pop()
val currentRules = rules[current.first]!!
var ranges = current.second
for (rule in currentRules) {
val splitOnCondition = ranges.splitOnCondition(rule.condition)
if (splitOnCondition.first != null) {
if (rule.target == "A") {
winningRanges.add(splitOnCondition.first!!)
} else if (rule.target != "R") {
queue.add(Pair(rule.target, splitOnCondition.first!!))
}
}
if (splitOnCondition.second == null) {
break
}
ranges = splitOnCondition.second!!
}
}
var sum = 0L
winningRanges.forEach {
var mul = 1L
it.values.values.forEach {
mul *= it.size()
}
sum += mul
}
println(sum)
}
fun main() {
val input = loadEntireFile("/aoc2023/input19")
val parts = input.split("\n\n").map { it.split("\n") }
part1(parseRules(parts[0]), parseSystemParts(parts[1]))
part2(parseRules(parts[0]))
}
| 0 | Kotlin | 0 | 0 | 2b90aa48cafa884fc3e85a1baf7eb2bd5b131a63 | 5,457 | advent-of-code | MIT License |
src/main/kotlin/day05.kt | mgellert | 572,594,052 | false | {"Kotlin": 19842} | import java.util.*
object SupplyStacks : Solution {
fun moveStacks(
supplyStack: SupplyStack,
operations: List<Operation>,
crateMover: (SupplyStack, Operation) -> Unit
): String {
operations.forEach { crateMover(supplyStack, it) }
val topCrates = StringBuilder()
supplyStack.filter { !it.isEmpty() }
.map { stack -> topCrates.append(stack.peek()) }
return topCrates.toString()
}
fun crateMover9000(state: SupplyStack, op: Operation) {
repeat(op.amount) {
val crate = state[op.from - 1].pop()
state[op.to - 1].push(crate)
}
}
fun crateMover9001(state: SupplyStack, op: Operation) {
val crates = state[op.from - 1].popMultiple(op.amount)
state[op.to - 1].pushMultiple(crates)
}
private fun Deque<Char>.popMultiple(amount: Int): List<Char> {
val popped = mutableListOf<Char>()
repeat(amount) {
popped.add(this.pop())
}
return popped.toList()
}
private fun Deque<Char>.pushMultiple(l: List<Char>) = l.reversed().forEach { this.push(it) }
fun readOperations() = readInput("day05").readLines()
.filter { it.startsWith("move") }
.map {
operationRegex.matchEntire(it)
?.destructured
?.let { (amount, from, to) ->
Operation(amount.toInt(), from.toInt(), to.toInt())
}
?: throw IllegalStateException()
}
fun dequeOf(vararg chars: Char): Deque<Char> = LinkedList(chars.reversed().toMutableList())
private val operationRegex = "move (\\d+) from (\\d+) to (\\d+)".toRegex()
}
data class Operation(val amount: Int, val from: Int, val to: Int)
typealias SupplyStack = List<Deque<Char>>
| 0 | Kotlin | 0 | 0 | 4224c762ad4961b28e47cd3db35e5bc73587a118 | 1,823 | advent-of-code-2022-kotlin | The Unlicense |
src/main/kotlin/Day04.kt | nmx | 572,850,616 | false | {"Kotlin": 18806} | fun main(args: Array<String>) {
fun toRange(str: String): IntRange {
val (lo, hi) = str.split("-")
return IntRange(lo.toInt(), hi.toInt())
}
fun rangesFullyContained(a: IntRange, b: IntRange): Boolean {
return (a.first <= b.first && a.last >= b.last) ||
(b.first <= a.first && b.last >= a.last)
}
fun rangesOverlap(a: IntRange, b: IntRange): Boolean {
return (a.first <= b.first && a.last >= b.first) ||
(b.first <= a.first && b.last >= a.first)
}
fun rowMeetsCriteria(row: String, func: (a: IntRange, b:IntRange) -> Boolean): Boolean {
if (row.isEmpty()) return false
val (left, right) = row.split(",")
val leftRange = toRange(left)
val rightRange = toRange(right)
return func(leftRange, rightRange)
}
fun partN(input: String, func: (a: IntRange, b:IntRange) -> Boolean) {
var sum = 0
input.split("\n").forEach {
if (rowMeetsCriteria(it, func))
sum++
}
println(sum)
}
fun part1(input: String) {
partN(input, ::rangesFullyContained)
}
fun part2(input: String) {
partN(input, ::rangesOverlap)
}
val input = object {}.javaClass.getResource("Day04.txt").readText()
part1(input)
part2(input)
}
| 0 | Kotlin | 0 | 0 | 33da2136649d08c32728fa7583ecb82cb1a39049 | 1,347 | aoc2022 | MIT License |
untitled/src/main/kotlin/Day11.kt | jlacar | 572,845,298 | false | {"Kotlin": 41161} | typealias WorryFunction = (Long) -> Long
class Day11(private val fileName: String) : AocSolution {
override val description: String get() = "Day 11 - Monkey in the Middle ($fileName)"
private val input = InputReader(fileName).lines
private fun monkeyTroop() = input.chunked(7).map { config -> Monkey.parse(config) }
override fun part1(): Long {
val monkeys = monkeyTroop()
monkeys.runRounds(20) { it / 3L }
return monkeys.business()
}
override fun part2(): Long {
val monkeys = monkeyTroop()
val divisorProduct = monkeys.map { it.divisor }.reduce(Long::times)
monkeys.runRounds(10000) { it % divisorProduct }
return monkeys.business()
}
private fun List<Monkey>.runRounds(rounds: Int, manageWorry: WorryFunction) {
repeat(rounds) {
forEach { monkey -> monkey.takeTurn(this, manageWorry) }
}
}
private fun List<Monkey>.business(): Long {
val (first, second) = map { it.inspections }.sortedDescending().take(2)
return first.toLong() * second.toLong()
}
class Item(val worryLevel: Long)
class Monkey(
val divisor: Long,
private val items: MutableList<Item>,
private val operation: WorryFunction,
private val pickTarget: (Item) -> Int
) {
var inspections = 0
companion object {
fun parse(config: List<String>): Monkey {
val items = startingItems(config[1].substringAfter(": "))
val divisor = config[3].substringAfterLast(" ").toLong()
val trueMonkey = config[4].substringAfterLast(" ").toInt()
val falseMonkey = config[5].substringAfterLast(" ").toInt()
return Monkey(
divisor,
items,
operation = opFun(config[2].substringAfter("= old ")),
pickTarget = ({ item -> if (item.worryLevel % divisor == 0L) trueMonkey else falseMonkey})
)
}
private fun startingItems(itemCsv: String) = mutableListOf<Item>().apply {
addAll(itemCsv.split(", ").map { Item(it.toLong()) })
}
private fun opFun(s: String): WorryFunction = s.substringAfter(" ").let { value ->
when {
value == "old" -> ({ it * it })
s.startsWith("+") -> ({ it + value.toLong() })
else -> ({ it * value.toLong() })
}
}
}
fun takeTurn(troop: List<Monkey>, manageWorry: WorryFunction) {
items.forEach { inspect(it, manageWorry).also { item -> throwTo(troop, item) } }
inspections += items.size
items.clear()
}
private fun catch(item: Item) = items.add(item)
private fun inspect(item: Item, manageWorry: WorryFunction) = Item(manageWorry(operation(item.worryLevel)))
private fun throwTo(troop: List<Monkey>, item: Item) = troop[pickTarget(item)].catch(item)
}
}
fun main() {
Day11("Day11-sample.txt") solution {
part1() shouldBe 10605L
part2() shouldBe 2713310158L
}
Day11("Day11.txt") solution {
part1() shouldBe 111210L
part2() shouldBe 15447387620L
}
Day11("Day11-alt.txt") solution {
part1() shouldBe 108240L
part2() shouldBe 25712998901L
}
}
/*==================
* NOTES
*
* The trick to part 2 is finding how to better manage the worry level. The problem is that
* the worry levels get exponentially larger as they keep transforming upon inspection.
* Part 1 strategy was to divide by 3. Part 2 required you to find a different way.
*
* I had to cheat on this one: the magic incantation is to multiply all the "divisible by" numbers
* of all the monkeys and mod the worry level with it. That is, newlevel = levelAfterInspection % modProduct.
*
* Found the Modulo trick info on Reddit.
* Same approach: (Rust): https://fasterthanli.me/series/advent-of-code-2022/part-11#part-2
* Other approach?: https://medium.com/@datasciencedisciple/advent-of-code-2022-in-python-day-11-5832b8f25c21
*
* Also had a heck of a time figuring out why this was giving different results for what looked like the same
* code as Day11-alt.kt code, except that one was not wrapped in a class. Problem was a wrong assumption: I
* thought part 2 started in a clean state when in fact it was starting in the state that part 1 ended in for
* monkey items. Had to parse the input at the start of each part solution to correctly initialize the items
* each monkey has at the start.
*/
| 0 | Kotlin | 0 | 2 | dbdefda9a354589de31bc27e0690f7c61c1dc7c9 | 4,666 | adventofcode2022-kotlin | The Unlicense |
year2022/src/main/kotlin/net/olegg/aoc/year2022/day10/Day10.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2022.day10
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.year2022.DayOf2022
import kotlin.math.abs
/**
* See [Year 2022, Day 10](https://adventofcode.com/2022/day/10)
*/
object Day10 : DayOf2022(10) {
private val TIMES = listOf(
20,
60,
100,
140,
180,
220,
)
override fun first(): Any? {
val ops = lines.map { Op.parse(it) }
val values = ops
.runningFold(1 to emptyList<Int>()) { (last, _), op ->
op.apply(last) to List(op.cycles) { last }
}
.flatMap { it.second }
return TIMES.sumOf { time -> time * values[time - 1] }
}
override fun second(): Any? {
val ops = lines.map { Op.parse(it) }
val values = ops
.runningFold(1 to emptyList<Int>()) { (last, _), op ->
op.apply(last) to List(op.cycles) { last }
}
.flatMap { it.second }
val lit = values.chunked(40) { row ->
row.mapIndexed { index, position ->
abs(index - position) < 2
}
}
return lit.joinToString(separator = "\n", prefix = "\n") {
row ->
row.joinToString(separator = "") {
if (it) "██" else ".."
}
}
}
sealed class Op(
val cycles: Int,
) {
open fun apply(x: Int): Int = x
object Noop : Op(1)
data class AddX(
val value: Int,
) : Op(2) {
override fun apply(x: Int): Int = x + value
}
companion object {
fun parse(raw: String): Op {
return when {
raw == "noop" -> Noop
raw.startsWith("addx ") -> AddX(raw.split(" ").last().toInt())
else -> error("Unable to parse $raw")
}
}
}
}
}
fun main() = SomeDay.mainify(Day10)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,712 | adventofcode | MIT License |
aoc21/day_09/main.kt | viktormalik | 436,281,279 | false | {"Rust": 227300, "Go": 86273, "OCaml": 82410, "Kotlin": 78968, "Makefile": 13967, "Roff": 9981, "Shell": 2796} | import pathutils.Pos
import pathutils.fourNeighs
import pathutils.reachable
import java.io.File
fun neighs(pos: Pos, map: Array<IntArray>): List<Pos> =
fourNeighs(pos, 0, map.size - 1, 0, map[0].size - 1)
fun basinNeighs(pos: Pos, map: Array<IntArray>): List<Pos> =
neighs(pos, map).filter { map[it.x][it.y] != 9 }
fun main() {
val map = File("input").readLines().map {
it.map(Char::digitToInt).toIntArray()
}.toTypedArray()
val points = (0 until map.size).flatMap { x ->
(0 until map[x].size).map { y -> Pos(x, y) }
}
val first = points.filter { p ->
neighs(p, map).all { n -> map[n.x][n.y] > map[p.x][p.y] }
}.map { map[it.x][it.y] + 1 }.sum()
println("First: $first")
val basins = mutableSetOf<Set<Pos>>()
while (true) {
val start = points.find { pt ->
map[pt.x][pt.y] != 9 && basins.none { it.contains(pt) }
} ?: break
basins.add(reachable(start, map, ::basinNeighs))
}
val second = basins.sortedBy { -it.size }.take(3).fold(1) { res, basin -> res * basin.size }
println("Second: $second")
}
| 0 | Rust | 1 | 0 | f47ef85393d395710ce113708117fd33082bab30 | 1,117 | advent-of-code | MIT License |
src/main/kotlin/com/adrielm/aoc2020/solutions/day10/Day10.kt | Adriel-M | 318,860,784 | false | null | package com.adrielm.aoc2020.solutions.day10
import com.adrielm.aoc2020.common.Solution
import com.adrielm.aoc2020.common.sumByLong
import org.koin.dsl.module
private val POSSIBLE_JOLT_DIFFS = listOf(1, 2, 3)
class Day10 : Solution<List<Int>, Long>(10) {
override fun solveProblem1(input: List<Int>): Long {
val sorted = input.sorted()
var previousNumber = 0
val joltDifferenceCounts = mutableMapOf(
3 to 1L // built in adapter
)
for (num in sorted) {
val diff = num - previousNumber
joltDifferenceCounts[diff] = joltDifferenceCounts.getOrDefault(diff, 0) + 1
previousNumber = num
}
return joltDifferenceCounts.getOrDefault(3, 0) * joltDifferenceCounts.getOrDefault(1, 0)
}
override fun solveProblem2(input: List<Int>): Long {
val inputSet = input.toSet()
val startingValue = inputSet.maxOrNull()!! + 3
val cache = mutableMapOf<Int, Long>()
fun traverse(currentValue: Int): Long {
if (currentValue in cache) return cache[currentValue]!!
val toReturn = when {
currentValue == 0 -> 1L
currentValue != startingValue && currentValue !in inputSet -> 0L
currentValue > 0 -> {
POSSIBLE_JOLT_DIFFS.sumByLong { traverse(currentValue - it) }
}
else -> 0L
}
cache[currentValue] = toReturn
return toReturn
}
return traverse(startingValue)
}
companion object {
val module = module {
single { Day10() }
}
}
}
| 0 | Kotlin | 0 | 0 | 8984378d0297f7bc75c5e41a80424d091ac08ad0 | 1,665 | advent-of-code-2020 | MIT License |
src/main/kotlin/org/sjoblomj/adventofcode/day4/Day4.kt | sjoblomj | 161,537,410 | false | null | package org.sjoblomj.adventofcode.day4
import org.sjoblomj.adventofcode.readFile
import java.time.format.DateTimeFormatter
import kotlin.system.measureTimeMillis
private const val inputFile = "src/main/resources/inputs/day4.txt"
fun day4() {
println("== DAY 4 ==")
val timeTaken = measureTimeMillis { calculateAndPrintDay4() }
println("Finished Day 4 in $timeTaken ms\n")
}
private fun calculateAndPrintDay4() {
val content = parseIndata(inputFile)
println("Guard who is most asleep * minute guard that guard is the most asleep: ${calculatePart1Checksum(content)}")
println("Guard who is most frequently asleep the same minute * that minute: ${calculatePart2Checksum(content)}")
}
internal fun parseIndata(fileName: String) = parseIndata(readFile(fileName))
internal fun calculatePart1Checksum(shifts: List<Shift>): Int {
val guardId = getGuardIdWhoIsTheMostAsleep(shifts)
val minute = getMinuteThatGuardIsTheMostAsleep(shifts, guardId)
return guardId * minute
}
internal fun calculatePart2Checksum(shifts: List<Shift>): Int {
val pair = shifts
.map { it.id }
.map { id -> Pair(id, getMinuteAndTheNumberOfTimesGuardIsAsleepTheMost(shifts, id)) }
.maxBy { (_, pairOfMinuteAndCount) -> pairOfMinuteAndCount.second }
?: throw RuntimeException("Couldn't find the guard who is the most asleep")
val guardId = pair.first
val minute = pair.second.first
return guardId * minute
}
internal fun getGuardIdWhoIsTheMostAsleep(shifts: List<Shift>): Int {
return shifts
.map { it.id }
.map { id -> Pair(id, getTotalSleepTime(shifts, id)) }
.maxBy { it.second }
?.first
?: throw RuntimeException("Couldn't find the guard who is the most asleep")
}
internal fun getMinuteThatGuardIsTheMostAsleep(shifts: List<Shift>, guardId: Int): Int {
val pairOfMinuteAndCount = getMinuteAndTheNumberOfTimesGuardIsAsleepTheMost(shifts, guardId)
return pairOfMinuteAndCount.first
}
private fun getMinuteAndTheNumberOfTimesGuardIsAsleepTheMost(shifts: List<Shift>, guardId: Int): Pair<Int, Int> {
val shiftsForGuard = shifts.filter { it.id == guardId }
return (0 until 60)
.map { minute ->
Pair(minute, shiftsForGuard
.map { shift -> isAsleepAtGivenMinute(shift, minute) }
.filter { isAsleep -> isAsleep }
.count()
)
}
.maxBy { it.second }
?: throw RuntimeException("Couldn't find the guard who is the most asleep")
}
private fun isAsleepAtGivenMinute(shift: Shift, minute: Int): Boolean {
for (i in shift.minuteWhenFallingAsleep.indices) {
if (minute >= shift.minuteWhenFallingAsleep[i] && minute < shift.minuteWhenAwoken[i])
return true
}
return false
}
internal fun getTotalSleepTime(shifts: List<Shift>, guardId: Int): Int {
return shifts
.filter { it.id == guardId }
.map { getTotalSleepTimeForShift(it) }
.sum()
}
private fun getTotalSleepTimeForShift(shift: Shift): Int {
return shift.minuteWhenFallingAsleep.zip(shift.minuteWhenAwoken) { timeAsleep, timeAwoken -> timeAwoken - timeAsleep }.sum()
}
internal fun visualize(indata: List<Shift>): String {
val maxIdLength = indata.map { it.id.toString().length }.max()?:3
val idSpaces = " ".repeat(maxIdLength)
return "" +
"Date ID$idSpaces Minute\n" +
" $idSpaces 000000000011111111112222222222333333333344444444445555555555\n" +
" $idSpaces 012345678901234567890123456789012345678901234567890123456789\n" +
indata.joinToString("\n") { visualizeShift(it, maxIdLength) }
}
private fun visualizeShift(shift: Shift, maxIdLength: Int): String {
val date = shift.date.format(DateTimeFormatter.ofPattern("MM-dd"))
val id = "#" + shift.id + " ".repeat(maxIdLength - shift.id.toString().length)
var s = ""
for (i in shift.minuteWhenFallingAsleep.indices) {
s += ".".repeat(shift.minuteWhenFallingAsleep[i] - s.length)
s += "#".repeat(shift.minuteWhenAwoken[i] - s.length)
}
s += ".".repeat(60 - s.length)
return "$date $id $s"
}
| 0 | Kotlin | 0 | 0 | 80db7e7029dace244a05f7e6327accb212d369cc | 3,988 | adventofcode2018 | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.