path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/day02/Day02.kt | rolf-rosenbaum | 543,501,223 | false | {"Kotlin": 17211} | package day02
import diff
import readInput
import second
fun part1(input: List<String>): Int {
val pairs = input.map { it.findPairsAndTriples() }
return pairs.count { it.first } * pairs.count { it.second }
}
fun part2(input: List<String>): String {
input.forEach { line ->
val similar = input.filter { it.diff(line) == 1 }
if (similar.size == 1) {
return (similar + line).commonChars()
}
}
error("no similar ids found")
}
fun main() {
val input = readInput("main/day02/Day02")
println(part1(input))
println(part2(input))
}
fun String.findPairsAndTriples(): Pair<Boolean, Boolean> {
val byChar = this.groupingBy { it }.eachCount()
return byChar.any { it.value == 2 } to byChar.any { it.value == 3 }
}
fun List<String>.commonChars(): String {
return first().mapIndexedNotNull { index, c ->
if (second()[index] == c) c else null
}.joinToString("")
}
| 0 | Kotlin | 0 | 0 | dfd7c57afa91dac42362683291c20e0c2784e38e | 948 | aoc-2018 | Apache License 2.0 |
archive/src/main/kotlin/com/grappenmaker/aoc/year23/Day24.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year23
import com.grappenmaker.aoc.*
fun PuzzleSet.day24() = puzzle(day = 24) {
data class Stone(val pos: List<Double>, val vel: List<Double>)
val stones = inputLines.map { l ->
val (a, b) = l.split(" @ ").map {
"-?\\d+".toRegex().findAll(it).map { p -> p.value.toDouble() }.toList()
}
Stone(a, b)
}
data class Line(val d: Double, val inter: Double, val stone: Stone)
fun Line.eval(x: Double) = d * x + inter
val ls = stones.map { (pos, vel) ->
val (x0, y0) = pos
val (vx0, vy0) = vel
val d = (vy0) / (vx0)
val inter = y0 - d * x0
Line(d, inter, Stone(pos, vel))
}
val r = 200000000000000.0..400000000000000.0
partOne = ls.combinations(2).count { (a, b) ->
if (a.d == b.d) return@count false
val xi = (a.d * a.stone.pos[0] - a.stone.pos[1] + b.stone.pos[1] - b.d * b.stone.pos[0]) / ((a.d - b.d))
val yi = a.eval(xi)
((xi in r && yi in r) &&
(if (a.stone.vel[0] < 0) xi < a.stone.pos[0] else xi > a.stone.pos[0]) &&
(if (a.stone.vel[1] < 0) yi < a.stone.pos[1] else yi > a.stone.pos[1]) &&
(if (b.stone.vel[0] < 0) xi < b.stone.pos[0] else xi > b.stone.pos[0]) &&
(if (b.stone.vel[1] < 0) yi < b.stone.pos[1] else yi > b.stone.pos[1]))
}.s()
// Line visualization for desmos
// partTwo = (stones.map { (pos, vel) ->
// val (a) = listOf(pos).map { l -> l.map { it / 100000000000000.0 } }
// Stone(a, vel)
// }.joinToString("\n") { (pos, vel) ->
// "(" + (pos.zip(vel).joinToString(",") { (p, t) -> "${p.toBigDecimal()} + (t(100))(${t.toBigDecimal()})" }) + ")"
// })
// Generating the python script
// println(stones.joinToString("\n") { (pos, vel) ->
// "stones.append(((${pos.joinToString(", ") { it.toLong().toString() }}), (${vel.joinToString(", ") { it.toLong().toString() }})))"
// })
partTwo = "No part two solution in Kotlin. Ended up using z3 in a small Python script."
} | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 2,085 | advent-of-code | The Unlicense |
src/Day08.kt | Narmo | 573,031,777 | false | {"Kotlin": 34749} | fun main() {
fun toGrid(input: List<String>): List<IntArray> = input.map { line -> line.map { it.digitToInt() }.toIntArray() }
fun List<IntArray>.getColumn(index: Int): IntArray = this.map { it[index] }.toIntArray()
fun IntArray.toPrintableString(): String = joinToString(",")
fun visibleIn(line: IntArray, index: Int, fromLeft: Boolean): Pair<Boolean, Int> {
if (fromLeft && index == 0) {
return true to 0
}
if (!fromLeft && index == line.size - 1) {
return true to 0
}
val range = if (fromLeft) (index - 1 downTo 0) else (index + 1 until line.size)
var score = 0
for (i in range) {
score += 1
if (line[i] >= line[index]) {
return false to score
}
}
return true to score
}
fun part1(input: List<String>): Int {
val grid = toGrid(input)
var counter = 0
grid.forEachIndexed row@{ rowIndex, row ->
row.forEachIndexed column@{ columnIndex, tree ->
val column = grid.getColumn(columnIndex)
println("Row: ${row.toPrintableString()}")
println("Column: ${column.toPrintableString()}")
if (visibleIn(row, columnIndex, true).first) {
println("Visible from left: $tree")
counter += 1
return@column
}
if (visibleIn(row, columnIndex, false).first) {
println("Visible from right: $tree")
counter += 1
return@column
}
if (visibleIn(column, rowIndex, true).first) {
println("Visible from top: $tree")
counter += 1
return@column
}
if (visibleIn(column, rowIndex, false).first) {
println("Visible from bottom: $tree")
counter += 1
return@column
}
}
}
println("Counter: $counter")
return counter
}
fun part2(input: List<String>): Int {
val grid = toGrid(input)
return grid.mapIndexed row@{ rowIndex, row ->
row.mapIndexed column@{ columnIndex, _ ->
val column = grid.getColumn(columnIndex)
val leftScore = visibleIn(row, columnIndex, true).second
val rightScore = visibleIn(row, columnIndex, false).second
val topScore = visibleIn(column, rowIndex, true).second
val bottomScore = visibleIn(column, rowIndex, false).second
leftScore * rightScore * topScore * bottomScore
}.max()
}.max()
}
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 335641aa0a964692c31b15a0bedeb1cc5b2318e0 | 2,376 | advent-of-code-2022 | Apache License 2.0 |
src/Day11.kt | Excape | 572,551,865 | false | {"Kotlin": 36421} | fun main() {
val monkeyRegex =
Regex("""Starting items:\s(?<startingItems>.+)\n.+old\s(?<op>.)\s(?<rhs>.+)\n.+by\s(?<mod>\d+)\n.+monkey\s(?<m1>\d+)\n.+monkey\s(?<m2>\d+)""")
class Monkey(input: String, val part2: Boolean) {
val items: ArrayDeque<Long>
private val operation: (old: Long) -> Long
val modTest: Int
private val ifTrueMonkeyIndex: Int
private val ifFalseMonkeyIndex: Int
private var ifTrueMonkey: Monkey? = null
private var ifFalseMonkey: Monkey? = null
var inspected: Int = 0
init {
val match = monkeyRegex.find(input) ?: throw IllegalStateException("Regex doesn't match input")
val (startingItems, op, rhs, mod, m1, m2) = match.destructured
items = ArrayDeque(startingItems.split(", ").map { it.toLong() })
modTest = mod.toInt()
operation = parseOperation(op, rhs, modTest, part2)
ifTrueMonkeyIndex = m1.toInt()
ifFalseMonkeyIndex = m2.toInt()
}
override fun toString(): String {
return items.toString()
}
fun takeTurn(part2: Boolean = false) {
inspected += items.size
while (items.isNotEmpty()) {
val item = items.removeFirst()
val level = operation(item) / 3
val target = if (level % modTest == 0L) ifTrueMonkey else ifFalseMonkey
target!!.items.addLast(level)
}
}
fun takeTurnPart2(lcm: Int) {
inspected += items.size
while (items.isNotEmpty()) {
val item = items.removeFirst()
val level = operation(item) % lcm
val target = if (level % modTest == 0L) ifTrueMonkey else ifFalseMonkey
target!!.items.addLast(level)
}
}
fun linkWithOthers(monkeys: List<Monkey>) {
ifTrueMonkey = monkeys[ifTrueMonkeyIndex]
ifFalseMonkey = monkeys[ifFalseMonkeyIndex]
}
private fun parseOperation(op: String, rhs: String, mod: Int, part2: Boolean): (old: Long) -> Long {
val operator: Long.(Long) -> Long = when (op) {
"+" -> Long::plus
"*" -> Long::times
else -> throw IllegalArgumentException("invalid operator $op")
}
return when (rhs) {
"old" -> {
{ old -> operator(old, old) }
}
else -> {
{ old -> operator(old, rhs.toLong()) }
}
}
}
}
fun initMonkeys(input: String, part2: Boolean): List<Monkey> {
val monkeys = input.split("\n\n").map { Monkey(it, part2) }
monkeys.forEach { it.linkWithOthers(monkeys) }
return monkeys
}
fun getMonkeyBusiness(monkeys: List<Monkey>) =
monkeys.map { it.inspected.toLong() }.sortedDescending().subList(0, 2).reduce(Long::times)
fun part1(input: String): Long {
val monkeys = initMonkeys(input, false)
repeat(20) { round ->
println("Play round $round")
monkeys.forEach { it.takeTurn() }
}
return getMonkeyBusiness(monkeys)
}
fun part2(input: String): Long {
val monkeys = initMonkeys(input, true)
// since the input modTest only contain prime numbers, their LCM is the product of all numbers
val lcm = monkeys.map { it.modTest }.reduce(Int::times)
repeat(10000) { round ->
println("Play round $round")
monkeys.forEach { it.takeTurnPart2(lcm) }
}
return getMonkeyBusiness(monkeys)
}
val testInput = readInputAsString("Day11_test")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158)
val input = readInputAsString("Day11")
val part1Answer = part1(input)
val part2Answer = part2(input)
println("part 1: $part1Answer")
println("part 2: $part2Answer")
}
| 0 | Kotlin | 0 | 0 | a9d7fa1e463306ad9ea211f9c037c6637c168e2f | 4,041 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/net/voldrich/aoc2021/Day12.kt | MavoCz | 434,703,997 | false | {"Kotlin": 119158} | package net.voldrich.aoc2021
import net.voldrich.BaseDay
// link to task
fun main() {
Day12().run()
}
class Day12 : BaseDay() {
override fun task1() : Int {
val uniquePaths = CaveGraph(false).getUniquePaths()
//uniquePaths.forEach { path -> println(path) }
return uniquePaths.size
}
override fun task2() : Int {
val uniquePaths = CaveGraph(true).getUniquePaths()
//uniquePaths.forEach { path -> println(path) }
return uniquePaths.size
}
inner class CaveGraph(val oneSmallCaveTwice : Boolean) {
private val nodeMap = HashMap<String, CaveNode>()
init {
input.lines().forEach{ line ->
val split = line.split("-")
val startNode = getOrCreateNode(split[0])
val endNode = getOrCreateNode(split[1])
startNode.nextNodes.add(endNode)
endNode.nextNodes.add(startNode)
}
}
private fun getOrCreateNode(name: String): CaveNode {
return nodeMap.computeIfAbsent(name) { CaveNode(it) }
}
fun getUniquePaths(): List<CavePath> {
val startNode = nodeMap["start"]!!// ?: Exception("Start node not found")
return startNode.nextNodes.flatMap { findPath(it, CavePath(startNode)) }
}
private fun findPath(node: CaveNode, nodePath: CavePath) : List<CavePath> {
if (node.name == "end") {
return listOf(CavePath(nodePath, node))
}
if (node.name == "start") {
return listOf()
}
if (!node.isBigCave) {
if (oneSmallCaveTwice) {
val groupBy = nodePath.nodes.filter { !it.isBigCave }.groupBy { it.name }
if (groupBy.values.maxOf { it.size } == 2) {
if (groupBy.contains(node.name)) {
return listOf()
}
}
} else {
if (nodePath.nodes.contains(node)) {
return listOf()
}
}
}
return node.nextNodes.flatMap { nextNode -> findPath(nextNode, CavePath(nodePath, node)) }
}
}
class CavePath {
val nodes: List<CaveNode>
constructor(node: CaveNode) {
nodes = listOf(node)
}
constructor(path: CavePath, node: CaveNode) {
val pathCopy = path.nodes.toMutableList()
pathCopy.add(node)
nodes = pathCopy.toList()
}
override fun toString(): String {
return "CavePath(nodes=${nodes.joinToString { it.name }})"
}
}
class CaveNode(val name: String) {
val isBigCave: Boolean = name.uppercase() == name
var nextNodes = ArrayList<CaveNode>()
}
}
| 0 | Kotlin | 0 | 0 | 0cedad1d393d9040c4cc9b50b120647884ea99d9 | 2,913 | advent-of-code | Apache License 2.0 |
aoc-day14/src/Day14.kt | rnicoll | 438,043,402 | false | {"Kotlin": 90620, "Rust": 1313} | import java.lang.StringBuilder
import java.nio.file.Files
import java.nio.file.Path
object Day14 {
val cache: MutableMap<Triple<Char, Char, Int>, Map<Char, Long>> = mutableMapOf()
}
fun main() {
var input: String? = null
val instructions = mutableListOf<Instruction>()
Files.readAllLines(Path.of("input")).spliterator().apply {
tryAdvance { line -> input = line }
tryAdvance { // Skip a blank line
}
forEachRemaining { it ->
instructions.add(Instruction.parse(it))
}
}
val mappedInstructions = instructions.groupBy { it.input }
println(part1(input!!, mappedInstructions))
println(part2(input!!, mappedInstructions))
}
private fun part1(
input: String,
mappedInstructions: Map<String, List<Instruction>>
): Int {
val result = polymerise(input, mappedInstructions, 10)
val counts = result
.toCharArray().toList().groupingBy { it }.eachCount()
val most = counts.values.maxOf { it }
val least = counts.values.minOf { it }
return most - least
}
fun polymerise(input: String, instructions: Map<String, List<Instruction>>, iterations: Int): String {
// println(input)
if (iterations == 0) {
return input
}
val builder = StringBuilder(input)
var i = 0
while (i < (builder.length - 1)) {
val pair = builder.substring(i, i + 2)
val apply = instructions[pair]
apply?.forEach {
builder.insert(i + 1, it.insert)
i++
}
i++
}
return polymerise(builder.toString(), instructions, iterations - 1)
}
fun part2(input: String, instructions: Map<String, List<Instruction>>): Long {
val counts = mutableMapOf<Char, Long>()
for (i in input.indices) {
counts.compute(input[i]) { _, value ->
if (value == null) {
1
} else {
value + 1
}
}
}
for (i in 0..(input.length - 2)) {
addCounts(input[i], input[i + 1], instructions, 40)
.forEach { (key, value) -> apply(counts, key, value) }
}
val most = counts.values.maxOf { it }
val least = counts.values.minOf { it }
return most - least
}
fun addCounts(a: Char, b: Char, instructions: Map<String, List<Instruction>>, iterations: Int): Map<Char, Long> {
if (iterations == 0) {
return emptyMap()
}
val cacheKey = Triple(a, b, iterations)
if (Day14.cache.contains(cacheKey)) {
return Day14.cache[cacheKey]!!
}
val pair = StringBuilder().run {
append(a)
append(b)
toString()
}
val instruction = instructions[pair]!!.single()
val counts: MutableMap<Char, Long> = mutableMapOf(Pair(instruction.insert, 1))
addCounts(a, instruction.insert, instructions, iterations - 1)
.forEach { (key, value) -> apply(counts, key, value) }
addCounts(instruction.insert, b, instructions, iterations - 1)
.forEach { (key, value) -> apply(counts, key, value) }
Day14.cache[cacheKey] = counts
return counts
}
private fun apply(counts: MutableMap<Char, Long>, key: Char, value: Long) {
counts.compute(key) { _, innerValue ->
when (innerValue) {
null -> {
value
}
else -> {
innerValue + value
}
}
}
} | 0 | Kotlin | 0 | 0 | 8c3aa2a97cb7b71d76542f5aa7f81eedd4015661 | 3,372 | adventofcode2021 | MIT License |
src/main/kotlin/net/navatwo/adventofcode2023/day9/Day9Solution.kt | Nava2 | 726,034,626 | false | {"Kotlin": 100705, "Python": 2640, "Shell": 28} | package net.navatwo.adventofcode2023.day9
import net.navatwo.adventofcode2023.framework.ComputedResult
import net.navatwo.adventofcode2023.framework.Solution
sealed class Day9Solution : Solution<List<Day9Solution.History>> {
data object Part1 : Day9Solution() {
override fun solve(input: List<History>): ComputedResult {
val predictions = input.map { history ->
val rowHistory = history.values.map { it.value }
val lastElementStack = ArrayDeque<Long>()
val constDiff = computeLinearRegression(rowHistory, lastElementStack = lastElementStack)
// Iterate the stack of last elements and walk back up adding the prediction to the previous one
var prediction = constDiff
while (lastElementStack.isNotEmpty()) {
val lastElement = lastElementStack.removeLast()
prediction += lastElement
}
prediction
}
return ComputedResult.Simple(predictions.reduce(Long::plus))
}
}
protected fun computeLinearRegression(
initialHistory: List<Long>,
firstElementStack: ArrayDeque<Long>? = null,
lastElementStack: ArrayDeque<Long>? = null,
): Long {
var history = initialHistory
var constDiff: Long? = null
do {
// compute the differences between each value and its next
val differences = history.zipWithNext { a, b -> b - a }
firstElementStack?.addLast(history.first())
lastElementStack?.addLast(history.last())
history = differences
val differenceCandidate = differences.first()
if (differences.all { it == differenceCandidate }) {
// if all differences are the same, we have found the linear regression
// and can compute the next value
constDiff = differenceCandidate
}
} while (constDiff == null)
return constDiff
}
data object Part2 : Day9Solution() {
override fun solve(input: List<History>): ComputedResult {
val predictions = input.map { history ->
val firstElementStack = ArrayDeque<Long>()
val constDiff = computeLinearRegression(history.values.map { it.value }, firstElementStack = firstElementStack)
// Iterate the stack of last elements and walk back up adding the prediction to the previous one
var prediction = constDiff
while (firstElementStack.isNotEmpty()) {
val lastElement = firstElementStack.removeLast()
prediction = lastElement - prediction
}
prediction
}
return ComputedResult.Simple(predictions.reduce(Long::plus))
}
}
override fun parse(lines: Sequence<String>): List<History> {
return lines
.filter { it.isNotBlank() }
.map { line ->
History(
line.splitToSequence(' ')
.map { it.toLong() }
.map { History.Value(it) }
.toList()
)
}
.toList()
}
@JvmInline
value class History(val values: List<Value>) {
@JvmInline
value class Value(val value: Long)
}
}
| 0 | Kotlin | 0 | 0 | 4b45e663120ad7beabdd1a0f304023cc0b236255 | 3,013 | advent-of-code-2023 | MIT License |
src/main/Day11.kt | ssiegler | 572,678,606 | false | {"Kotlin": 76434} | package day11
import utils.readInput
typealias ThrowItem = Pair<Long, Int>
val ThrowItem.item
get() = first
val ThrowItem.target
get() = second
class Monkey(
private var items: List<Long>,
private val operation: Long.() -> Long,
val divisor: Long,
private val whenTrue: Int,
private val whenFalse: Int,
) {
private var inspections: Long = 0
val totalInspections: Long
get() = inspections
val currentItems: List<Long>
get() = items
fun catch(caught: List<Long>) {
items = items + caught
}
fun onTurn(relief: Boolean): List<ThrowItem> =
items.map { it.inspect(relief) }.also { items = emptyList() }
private fun Long.inspect(relief: Boolean): ThrowItem {
inspections++
val worryLevel = operation().let { if (relief) it.div(3) else it }
return worryLevel to
if (worryLevel % divisor == 0L) {
whenTrue
} else {
whenFalse
}
}
}
fun List<Monkey>.turn() {
forEach {
it.onTurn(relief = true).groupBy(ThrowItem::target, ThrowItem::item).forEach {
(target, items) ->
get(target).catch(items)
}
}
}
fun List<Monkey>.turnsWithoutRelief(n: Int) {
val commonDivisor = map { it.divisor }.reduce(Long::times)
repeat(n) {
forEach {
it.onTurn(relief = false).groupBy(ThrowItem::target, ThrowItem::item).forEach {
(target, items) ->
get(target).catch(items.map { item -> item % commonDivisor })
}
}
}
}
fun List<Monkey>.businessLevel(): Long =
map { it.totalInspections }.sortedDescending().take(2).reduce(Long::times)
fun List<String>.readMonkeys(): List<Monkey> = chunked(7).map(List<String>::readMonkey)
private fun List<String>.readMonkey() =
Monkey(
get(1).readItems(),
get(2).readOperation(),
get(3).readDivisor(),
get(4).readTarget("true"),
get(5).readTarget("false")
)
private fun String.readItems(): List<Long> =
removePrefix(" Starting items: ").split(", ".toRegex()).map { it.toLong() }
private fun String.readOperation(): (Long) -> Long {
val (operator, operand) = removePrefix(" Operation: new = old ").split(' ')
return when (operator) {
"+" -> operation(operand, Long::plus)
"*" -> operation(operand, Long::times)
else -> error("Unknown operator: $operator")
}
}
private fun operation(operand: String, operator: (Long, Long) -> Long): (Long) -> Long =
when (operand) {
"old" -> {
{ operator(it, it) }
}
else -> {
operand.toLong().let { amount -> { operator(it, amount) } }
}
}
private fun String.readDivisor(): Long = removePrefix(" Test: divisible by ").toLong()
private fun String.readTarget(case: String): Int =
removePrefix(" If $case: throw to monkey ").toInt()
private const val filename = "Day11"
fun part1(filename: String): Long {
val monkeys = readInput(filename).readMonkeys()
repeat(20) { monkeys.turn() }
return monkeys.businessLevel()
}
fun part2(filename: String): Long {
val monkeys = readInput(filename).readMonkeys()
monkeys.turnsWithoutRelief(10000)
return monkeys.businessLevel()
}
fun main() {
println(part1(filename))
println(part2(filename))
}
| 0 | Kotlin | 0 | 0 | 9133485ca742ec16ee4c7f7f2a78410e66f51d80 | 3,400 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/day20.kt | Arch-vile | 572,557,390 | false | {"Kotlin": 132454} | package day20
import aoc.utils.readInput
import kotlin.math.E
import kotlin.math.abs
fun main() {
part2().let { println(it) }
}
data class Holder(var left: Holder?, var right: Holder?, var move: Long, var originalValue: Long) {
override fun toString(): String {
return "$move"
}
}
fun part2(): Long {
// Keep in the list to preserve the original order
val originalOrder = readInput("day20-input.txt")
.map { value ->
Holder(null, null, 0, value.toLong() * 811589153L) }
val count = originalOrder.size
// Normalize
originalOrder.forEach {
it.move = it.originalValue % (count.toLong()-1)
}
// originalOrder.forEach { println(it.move) }
// Create links
originalOrder.forEachIndexed { index, holder ->
val left = if (index == 0) originalOrder.last() else originalOrder[index - 1]
val right = if (index == count - 1) originalOrder[0] else originalOrder[index + 1]
holder.left = left
holder.right = right
}
repeat(10) {
originalOrder.forEach {
if (it.move != 0L) {
// Link left and right of this instead, i.e. remove this from between
it.left?.right = it.right
it.right?.left = it.left
// Find the new left neighbour
val newLeft = move(it, it.move)
// Place this between
val oldRight = newLeft.right
newLeft.right = it
oldRight?.left = it
it.left = newLeft
it.right = oldRight
}
// printIt(originalOrder)
}
}
printIt(originalOrder)
val zero = originalOrder.firstOrNull { it.originalValue == 0L }!!
val thousandth1 = move(zero, 1000)
val thousandth2 = move(zero, 2000)
val thousandth3 = move(zero, 3000)
println(thousandth1.originalValue)
println(thousandth2.originalValue)
println(thousandth3.originalValue)
return thousandth1.originalValue + thousandth2.originalValue + thousandth3.originalValue
}
private fun printIt(originalOrder: List<Holder>) {
var current = originalOrder[0]
repeat(originalOrder.size) {
print(current.originalValue.toString() + ", ")
current = current.right!!
}
println()
}
fun move(it: Holder, amount: Long): Holder {
var repeat = abs(amount)
if(amount<0)
repeat+=1
var index = 0
var current = it
while(index < repeat) {
current = if (amount < 0) current.left!! else current.right!!
index+=1
}
// var current = it
// repeat(abs(amount.toInt()) + if (amount < 0) 1 else 0) {
// current = if (amount < 0) current.left!! else current.right!!
// }
return current
}
| 0 | Kotlin | 0 | 0 | e737bf3112e97b2221403fef6f77e994f331b7e9 | 2,796 | adventOfCode2022 | Apache License 2.0 |
common/number/src/main/kotlin/com/curtislb/adventofcode/common/number/Multiples.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | package com.curtislb.adventofcode.common.number
import com.curtislb.adventofcode.common.collection.mapToMap
import java.math.BigInteger
/**
* Returns the largest positive integer that evenly divides both [m] and [n].
*
* @throws IllegalArgumentException If either [m] or [n] is negative or 0.
*/
fun greatestCommonDivisor(m: Int, n: Int): Int {
require(m > 0) { "First argument must be positive: $m" }
require(n > 0) { "Second argument must be positive: $n" }
var a = m
var b = n
while (b != 0) {
a = b.also { b = a % it }
}
return a
}
/**
* Returns the largest positive integer that evenly divides both [m] and [n].
*
* @throws IllegalArgumentException If either [m] or [n] is negative or 0.
*/
fun greatestCommonDivisor(m: Long, n: Long): Long {
require(m > 0L) { "First argument must be positive: $m" }
require(n > 0L) { "Second argument must be positive: $n" }
var a = m
var b = n
while (b != 0L) {
a = b.also { b = a % it }
}
return a
}
/**
* Returns the smallest whole number that can be evenly divided by both [m] and [n].
*
* @throws IllegalArgumentException If either [m] or [n] is negative or 0.
*/
fun leastCommonMultiple(m: Int, n: Int): Int {
require(m > 0) { "First argument must be positive: $m" }
require(n > 0) { "Second argument must be positive: $n" }
return m / greatestCommonDivisor(m, n) * n
}
/**
* Returns the smallest whole number that can be evenly divided by both [m] and [n].
*
* @throws IllegalArgumentException If either [m] or [n] is negative or 0.
*/
fun leastCommonMultiple(m: Long, n: Long): Long {
require(m > 0L) { "First argument must be positive: $m" }
require(n > 0L) { "Second argument must be positive: $n" }
return m / greatestCommonDivisor(m, n) * n
}
/**
* Returns the smallest whole number that can be evenly divided by each of the given [numbers].
*
* @throws IllegalArgumentException If any value in [numbers] is negative or 0.
*/
fun leastCommonMultiple(numbers: Iterable<Long>): Long {
val factorization = numbers.fold(emptyMap<Long, Int>()) { acc, num ->
require(num > 0L) { "Each vararg value must be positive: $num" }
takeLargestPowers(acc, primeFactorization(num))
}
return factorization.entries.fold(1L) { acc, (factor, power) -> acc * factor.pow(power) }
}
/**
* Returns a map from each factor in [factorization1] and/or [factorization2] to the larger of its
* powers from the two factorizations.
*/
private fun takeLargestPowers(
factorization1: Map<Long, Int>,
factorization2: Map<Long, Int>
): Map<Long, Int> {
val factors = factorization1.keys union factorization2.keys
return factors.mapToMap { factor ->
factor to maxOf(factorization1[factor] ?: 0, factorization2[factor] ?: 0)
}
}
/**
* Returns the least positive integer greater than [n] that is a multiple of this one.
*
* @throws IllegalArgumentException If this number is negative or 0, or if [n] is negative.
*/
fun Int.nextMultipleAbove(n: Int): Int {
require(this > 0) { "Number must be positive: $this" }
require(n >= 0) { "Argument must be non-negative: $n" }
return this - (n % this) + n
}
/**
* Returns the least positive integer greater than [n] that is a multiple of this one.
*
* @throws IllegalArgumentException If this number is negative or 0, or if [n] is negative.
*/
fun Long.nextMultipleAbove(n: Long): Long {
require(this > 0L) { "Number must be positive: $this" }
require(n >= 0L) { "Argument must be non-negative: $n" }
return this - (n % this) + n
}
/**
* Returns the least positive integer greater than [n] that is a multiple of this one.
*
* @throws IllegalArgumentException If this number is negative or 0, or if [n] is negative.
*/
fun BigInteger.nextMultipleAbove(n: BigInteger): BigInteger {
require(this > BigInteger.ZERO) { "Number must be positive: $this" }
require(n >= BigInteger.ZERO) { "Argument must be non-negative: $n" }
return this - (n % this) + n
}
/**
* Returns the least integer greater than or equal to [n] that is a multiple of this one.
*
* @throws IllegalArgumentException If this number is negative or 0, or if [n] is negative.
*/
fun Int.nextMultipleAtLeast(n: Int): Int {
require(this > 0) { "Number must be positive: $this" }
require(n >= 0) { "Argument must be non-negative: $n" }
return if (n % this == 0) n else nextMultipleAbove(n)
}
/**
* Returns the least integer greater than or equal to [n] that is a multiple of this one.
*
* @throws IllegalArgumentException If this number is negative or 0, or if [n] is negative.
*/
fun Long.nextMultipleAtLeast(n: Long): Long {
require(this > 0L) { "Number must be positive: $this" }
require(n >= 0L) { "Argument must be non-negative: $n" }
return if (n % this == 0L) n else nextMultipleAbove(n)
}
/**
* Returns the least integer greater than or equal to [n] that is a multiple of this one.
*
* @throws IllegalArgumentException If this number is negative or 0, or if [n] is negative.
*/
fun BigInteger.nextMultipleAtLeast(n: BigInteger): BigInteger {
require(this > BigInteger.ZERO) { "Number must be positive: $this" }
require(n >= BigInteger.ZERO) { "Argument must be non-negative: $n" }
return if (n % this == BigInteger.ZERO) n else nextMultipleAbove(n)
}
/**
* Returns the greatest integer less than or equal to [n] that is a multiple of this one.
*
* @throws IllegalArgumentException If this number is negative or 0, or if [n] is negative.
*/
fun Int.prevMultipleAtMost(n: Int): Int {
require(this > 0) { "Number must be positive: $this" }
require(n >= 0) { "Argument must be non-negative: $n" }
return n - (n % this)
}
/**
* Returns the greatest integer less than or equal to [n] that is a multiple of this one.
*
* @throws IllegalArgumentException If this number is negative or 0, or if [n] is negative.
*/
fun Long.prevMultipleAtMost(n: Long): Long {
require(this > 0L) { "Number must be positive: $this" }
require(n >= 0L) { "Argument must be non-negative: $n" }
return n - (n % this)
}
/**
* Returns the greatest integer less than or equal to [n] that is a multiple of this one.
*
* @throws IllegalArgumentException If this number is negative or 0, or if [n] is negative.
*/
fun BigInteger.prevMultipleAtMost(n: BigInteger): BigInteger {
require(this > BigInteger.ZERO) { "Number must be positive: $this" }
require(n >= BigInteger.ZERO) { "Argument must be non-negative: $n" }
return n - (n % this)
}
/**
* Returns the greatest integer less than [n] that is a multiple of this one.
*
* @throws IllegalArgumentException If this number is negative or 0, or if [n] is negative.
*/
fun Int.prevMultipleBelow(n: Int): Int {
require(this > 0) { "Number must be positive: $this" }
require(n >= 0) { "Argument must be non-negative: $n" }
return if (n % this == 0) n - this else prevMultipleAtMost(n)
}
/**
* Returns the greatest integer less than [n] that is a multiple of this one.
*
* @throws IllegalArgumentException If this number is negative or 0, or if [n] is negative.
*/
fun Long.prevMultipleBelow(n: Long): Long {
require(this > 0L) { "Number must be positive: $this" }
require(n >= 0L) { "Argument must be non-negative: $n" }
return if (n % this == 0L) n - this else prevMultipleAtMost(n)
}
/**
* Returns the greatest integer less than [n] that is a multiple of this one.
*
* @throws IllegalArgumentException If this number is negative or 0, or if [n] is negative.
*/
fun BigInteger.prevMultipleBelow(n: BigInteger): BigInteger {
require(this > BigInteger.ZERO) { "Number must be positive: $this" }
require(n >= BigInteger.ZERO) { "Argument must be non-negative: $n" }
return if (n % this == BigInteger.ZERO) n - this else prevMultipleAtMost(n)
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 7,856 | AdventOfCode | MIT License |
kotlin/2021/round-1a/hacked-exam/src/main/kotlin/AnalysisSolution.kt | ShreckYe | 345,946,821 | false | null | import java.math.BigInteger
fun main() {
val t = readLine()!!.toInt()
repeat(t, ::testCase)
}
fun testCase(ti: Int) {
val (n, q) = readLine()!!.splitToSequence(' ').map { it.toInt() }.toList()
val ass = List(n) {
val lineInputs = readLine()!!.splitToSequence(' ').toList()
lineInputs[0].map { it == 'T' } to lineInputs[1].toInt()
}
val qTypeAndNums = (0 until q).map { qi ->
ass.asSequence()
.map { it.first[qi] } // get all students' answers to Question qi
.mapIndexed { si, a -> (if (a) 1 else 0) shl si }.reduce { a, b -> a or b } // convert to its type in Int
}.groupBy { it }
val coefficients = ass.map { it.second }
val answers = TODO() as List<Boolean>
val expectedScore = TODO()
println("Case #${ti + 1}: ${answers.joinToString("") { if (it) "T" else "F" }} $expectedScore")
}
val half = 1 divBy 2
// copied from Fractions.kt
data class Fraction internal constructor(val numerator: BigInteger, val denominator: BigInteger) {
init {
require(denominator > BigInteger.ZERO)
}
operator fun plus(that: Fraction) =
reducedFraction(
numerator * that.denominator + that.numerator * denominator,
denominator * that.denominator
)
operator fun unaryMinus() =
Fraction(-numerator, denominator)
operator fun minus(that: Fraction) =
this + -that
operator fun times(that: Fraction) =
reducedFraction(numerator * that.numerator, denominator * that.denominator)
fun reciprocal() =
if (numerator > BigInteger.ZERO) Fraction(denominator, numerator)
else Fraction(-denominator, -numerator)
operator fun div(that: Fraction) =
this * that.reciprocal()
operator fun compareTo(that: Fraction) =
(numerator * that.denominator).compareTo(that.numerator * denominator)
override fun toString(): String =
"$numerator/$denominator"
fun toSimplestString(): String =
if (denominator == BigInteger.ONE) numerator.toString()
else toString()
companion object {
val zero = Fraction(BigInteger.ZERO, BigInteger.ONE)
val one = Fraction(BigInteger.ONE, BigInteger.ONE)
}
}
fun reducedFraction(numerator: BigInteger, denominator: BigInteger): Fraction {
val gcd = numerator.gcd(denominator)
val nDivGcd = numerator / gcd
val dDivGcd = denominator / gcd
return if (denominator > BigInteger.ZERO) Fraction(nDivGcd, dDivGcd)
else Fraction(-nDivGcd, -dDivGcd)
}
infix fun BigInteger.divBy(that: BigInteger) = reducedFraction(this, that)
infix fun Int.divBy(that: Int) = toBigInteger() divBy that.toBigInteger()
infix fun Long.divBy(that: Long) = toBigInteger() divBy that.toBigInteger()
fun BigInteger.toFraction() =
Fraction(this, BigInteger.ONE)
fun Int.toFraction() = toBigInteger().toFraction()
fun Long.toFraction() = toBigInteger().toFraction() | 0 | Kotlin | 1 | 1 | 743540a46ec157a6f2ddb4de806a69e5126f10ad | 2,948 | google-code-jam | MIT License |
src/main/kotlin/com/dvdmunckhof/aoc/event2021/Day18.kt | dvdmunckhof | 318,829,531 | false | {"Kotlin": 195848, "PowerShell": 1266} | package com.dvdmunckhof.aoc.event2021
import kotlin.math.ceil
import kotlin.math.floor
class Day18(input: List<String>) {
private val numbers = input.map(::parse)
fun solvePart1(): Int = sum().magnitude()
fun solvePart2(): Int = numbers.maxOf { numberA ->
numbers.minus(numberA).maxOf { numberB -> (numberA + numberB).magnitude() }
}
fun sum(): SnailFishNumber = numbers.reduce { numberA, numberB -> numberA + numberB }
data class SnailFishNumber(private val list: MutableList<Node>) {
@Suppress("ControlFlowWithEmptyBody")
fun reduce(): SnailFishNumber {
while (explode() || split());
return this
}
fun explode(): Boolean {
for (i in list.indices) {
val nodeA = list[i]
if (nodeA.depth <= 4) {
continue
}
if (i > 0) {
val nodeLeft = list[i - 1]
list[i - 1] = nodeLeft.copy(value = nodeLeft.value + nodeA.value)
}
val nodeB = list[i + 1]
if (i + 2 < list.size) {
val nodeRight = list[i + 2]
list[i + 2] = nodeRight.copy(value = nodeRight.value + nodeB.value)
}
list[i] = Node(0, nodeA.depth - 1)
list.removeAt(i + 1)
return true
}
return false
}
fun split(): Boolean {
for (i in list.indices) {
val node = list[i]
if (node.value < 10) {
continue
}
val half = node.value.toFloat() / 2
list[i] = Node(floor(half).toInt(), node.depth + 1)
list.add(i + 1, Node(ceil(half).toInt(), node.depth + 1))
return true
}
return false
}
fun magnitude(): Int = MagnitudeTransformer().transform()
operator fun plus(other: SnailFishNumber): SnailFishNumber {
val result = ArrayList<Node>(this.list.size + other.list.size)
this.list.mapTo(result) { node -> node.copy(depth = node.depth + 1) }
other.list.mapTo(result) { node -> node.copy(depth = node.depth + 1) }
return SnailFishNumber(result).reduce()
}
override fun toString(): String = StringTransformer().transform()
private abstract inner class TreeTransformer<T> {
private var index = 0
fun transform(): T = processNode(0)
private fun processNode(depth: Int): T {
val node = list[index]
return if (node.depth == depth) {
index++
transformNode(node)
} else {
val valueA = processNode(depth + 1)
val valueB = processNode(depth + 1)
transformPair(valueA, valueB)
}
}
abstract fun transformNode(node: Node): T
abstract fun transformPair(valueA: T, valueB: T): T
}
private inner class StringTransformer : TreeTransformer<String>() {
override fun transformNode(node: Node): String = node.value.toString()
override fun transformPair(valueA: String, valueB: String): String = "[$valueA,$valueB]"
}
private inner class MagnitudeTransformer : TreeTransformer<Int>() {
override fun transformNode(node: Node): Int = node.value
override fun transformPair(valueA: Int, valueB: Int): Int = valueA * 3 + valueB * 2
}
}
data class Node(val value: Int, val depth: Int)
companion object {
fun parse(line: String): SnailFishNumber {
var depth = 0
val result = mutableListOf<Node>()
for (c in line) {
when (c) {
'[' -> depth += 1
']' -> depth -= 1
',' -> {}
else -> result += Node(c.digitToInt(), depth)
}
}
return SnailFishNumber(result)
}
}
}
| 0 | Kotlin | 0 | 0 | 025090211886c8520faa44b33460015b96578159 | 4,198 | advent-of-code | Apache License 2.0 |
src/Day04.kt | aneroid | 572,802,061 | false | {"Kotlin": 27313} | class Day04(input: List<String>) {
private val data = parseInput(input)
fun partOne() =
data
.filter { (assign1, assign2) -> assign1 contains assign2 || assign2 contains assign1 }
.size
fun partTwo(): Int =
data
.filter { (assign1, assign2) -> assign1 overlapsWith assign2 || assign2 overlapsWith assign1 }
.size
private companion object {
fun parseInput(input: List<String>) =
input.map { line ->
val (range1, range2) = line.split(",").map { it.toRange() }
range1 to range2
}
private fun String.toRange() =
substringBefore("-").toInt()..substringAfter("-").toInt()
}
private infix fun IntRange.contains(other: IntRange): Boolean =
first <= other.first && last >= other.last
private infix fun IntRange.overlapsWith(other: IntRange): Boolean =
other.first in this || other.last in this
}
fun main() {
val testInput = readInput("Day04_test")
check(Day04(testInput).partOne() == 2)
check(Day04(testInput).partTwo() == 4) // uncomment when ready
val input = readInput("Day04")
println("partOne: ${Day04(input).partOne()}\n")
println("partTwo: ${Day04(input).partTwo()}\n") // uncomment when ready
}
| 0 | Kotlin | 0 | 0 | cf4b2d8903e2fd5a4585d7dabbc379776c3b5fbd | 1,353 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/Day04.kt | thpz2210 | 575,577,457 | false | {"Kotlin": 50995} | private class Solution04(input: List<String>) {
private val sections = input.map { Section(it) }
private class Section(line: String) {
private var elf1: IntRange
private var elf2: IntRange
init {
val limits = line.split(",", "-").map { it.toInt() }
elf1 = IntRange(limits[0], limits[1])
elf2 = IntRange(limits[2], limits[3])
}
fun isFullyContained() = (elf1 subtract elf2).isEmpty() || (elf2 subtract elf1).isEmpty()
fun isOverlapping() = (elf1 intersect elf2).isNotEmpty()
}
fun part1() = sections.count { it.isFullyContained() }
fun part2() = sections.count { it.isOverlapping() }
}
fun main() {
val testSolution = Solution04(readInput("Day04_test"))
check(testSolution.part1() == 2)
check(testSolution.part2() == 4)
val solution = Solution04(readInput("Day04"))
println(solution.part1())
println(solution.part2())
}
| 0 | Kotlin | 0 | 0 | 69ed62889ed90692de2f40b42634b74245398633 | 959 | aoc-2022 | Apache License 2.0 |
src/Day05.kt | timhillgit | 572,354,733 | false | {"Kotlin": 69577} | private typealias Stacks = Array<ArrayDeque<Char>>
private typealias Instructions = List<List<Int>>
private fun buildStacks(startingPosition: List<String>): Stacks {
val numStacks = startingPosition.last().split(" ").last().toInt()
val stacks = Stacks(numStacks + 1) { // add one for easier indexing
ArrayDeque(startingPosition.size - 1)
}
startingPosition.reversed().drop(1).forEach {
for (i in 1..numStacks) {
val cratePosition = 4 * (i - 1) + 1
val crate = it.getOrElse(cratePosition) { ' ' }
if (crate.isLetter()) {
stacks[i].add(crate)
}
}
}
return stacks
}
private fun Stacks.getAnswer() = drop(1).map { it.last() }.joinToString("")
private fun Stacks.rearrangeCrates(
instructions: Instructions,
reverse: Boolean = true
) {
instructions.forEach { (numCrates, from, to) ->
val fromStack = get(from)
val toStack = get(to)
val toMove = fromStack.subList(fromStack.size - numCrates, fromStack.size)
if (reverse) {
toMove.reverse()
}
toStack.addAll(toMove)
toMove.clear()
}
}
fun main() {
val (startingPosition, procedure) = readInput("Day05").split(String::isBlank)
val instructions = procedure.parseAllInts()
var stacks = buildStacks(startingPosition)
stacks.rearrangeCrates(instructions)
println(stacks.getAnswer())
stacks = buildStacks(startingPosition)
stacks.rearrangeCrates(instructions, false)
println(stacks.getAnswer())
}
| 0 | Kotlin | 0 | 1 | 76c6e8dc7b206fb8bc07d8b85ff18606f5232039 | 1,569 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/jacobhyphenated/day20/Day20.kt | jacobhyphenated | 572,119,677 | false | {"Kotlin": 157591} | package com.jacobhyphenated.day20
import com.jacobhyphenated.Day
import java.io.File
import java.util.*
// Donut Maze
class Day20: Day<String> {
override fun getInput(): String {
return this.javaClass.classLoader.getResource("day20/input.txt")!!
.readText()
}
/**
* The maze has portals (described with 2-letter codes) that connect separate parts of the maze.
* Find the shortest path between the start node (AA) and the end node (ZZ).
*
* Note that portal nodes (AA,ZZ,AK, etc.) are not spaces in the maze, but labels next to their adjacent spaces
* (stepping onto the portal does not count as a step)
*
* For part 1, parsing a graph from the maze input is the hard part.
* Once that graph is created, use Dijkstra's algorithm.
*/
override fun part1(input: String): Number {
val start = createGraph(input)
val distances: MutableMap<String, Int> = mutableMapOf()
// Use a priority queue implementation - min queue sorted by lowest "cost"
val queue = PriorityQueue<NodeCost> { a, b -> a.cost - b.cost }
queue.add(NodeCost(start, 0))
distances[start.name] = 0
while (queue.size > 0) {
// Traverse from the lowest cost position on our queue. This position is "solved"
val current = queue.remove()
// If we already found a less expensive way to reach this position
if (current.cost > (distances[current.node.name] ?: Int.MAX_VALUE)) {
continue
}
// We've found the end of the maze, we can stop
if (current.node.name == "ZZ") {
break
}
current.node.neighbors.forEach {
// when computing cost, do not increment cost for portal spaces
val cost = distances.getValue(current.node.name) + if (current.node.isPortal) { 0 } else { 1 }
// If the cost to this space is less than what was previously known, put this on the queue
if (cost < (distances[it.name] ?: Int.MAX_VALUE)) {
distances[it.name] = cost
queue.add(NodeCost(it, cost))
}
}
}
return distances["ZZ"]!! - 1 // subtract 1 because "ZZ" is not technically a space
}
/**
* Each portal in the maze is in the interior or the exterior of the maze.
* When a portal is passed through, you enter a new depth (interior portals increase depth, exterior portals decrease).
* You start on depth of 0 and can only exit ZZ at depth 0.
* Find the shortest number of steps to get from AA to ZZ.
*/
override fun part2(input: String): Number {
val start = createGraph(input)
val next = start.neighbors[0]
return recursiveMaze(next, start, 0, 0)!!
}
/**
* Use a recursive Depth First Search driven by this function.
* Each move taken goes from on portal location to another portal location (use Dijkstra to find the shortest path to each portal).
*
* @param current the current node - this node is always adjecent to the portal that was just passed through
* @param previous the node representing the portal that was just passed through (so we don't go backwards)
* @param currentCost the total cost so far to reach this node
* @param depth the current depth
* @param solutions a mutable map representing all solutions found so far
*
* @return the total cost to solve the maze for this DFS branch, or null if the DFS branch is invalid
*/
private fun recursiveMaze(current: Node, previous: Node, currentCost: Int, depth: Int, solutions: MutableSet<Int> = mutableSetOf() ): Int? {
// We've already solved the maze in less time, we can prune this DFS branch
if (currentCost > (solutions.minOrNull() ?: Int.MAX_VALUE)) {
return null
}
// The puzzle input has less than 30 portals. We should never go that deep.
// Also set a boundary for too much cost
// Use these to prune DFS branches that are clearly not going to be correct
if (depth > 30 || currentCost > 20000) {
return null
}
// Use Dijkstra to find all accessible portals and the cost to get their
val distances: MutableMap<String, Int> = mutableMapOf()
val queue = PriorityQueue<NodeCost> { a, b -> a.cost - b.cost }
queue.add(NodeCost(current, 0))
distances[current.name] = 0
val portals: MutableList<Pair<Node, Int>> = mutableListOf()
while (queue.size > 0) {
val currentNode = queue.remove()
// If we already found a less expensive way to reach this position
if (currentNode.cost > (distances[currentNode.node.name] ?: Int.MAX_VALUE)) {
continue
}
for (neighbor in currentNode.node.neighbors){
// don't go back through the portal we came from
if (neighbor.name == previous.name) {
continue
}
val cost = distances.getValue(currentNode.node.name)
// Don't traverse to portals, instead save the node/cost to the portal's edge
if (neighbor.isPortal) {
portals.add(Pair(currentNode.node, cost))
}
else if (cost + 1 < (distances[neighbor.name] ?: Int.MAX_VALUE)) {
distances[neighbor.name] = cost + 1
queue.add(NodeCost(neighbor, cost))
}
}
}
// Once we have the portals, recursively search the next leg of the solution for each portal we can reach
return portals.mapNotNull { (node, costToPortal) ->
val portal = node.neighbors.filter { it.isPortal }[0]
if (portal.name == "AA") { // we never go back to the start
null
} else if (portal.name == "ZZ"){
if (depth != 0) {
null// can't solve the maze unless we are at depth 0
} else {
// We have a valid solution!
solutions.add(currentCost + costToPortal)
currentCost + costToPortal
}
} else{
val nextNode = portal.neighbors.filter { it.name != node.name }[0]
val nextDepth = if (node.outer) { depth - 1 } else { depth + 1}
if (nextDepth < 0) {
null
}else {
recursiveMaze(nextNode, portal, currentCost + costToPortal + 1, nextDepth, solutions)
}
}
}.minOrNull() // Filter our invalid null branches, then keep only the lowest cost branch
}
/**
* Create a graph of nodes, where each node is a position in the maze
*
* Portals count as their own nodes connecting separate parts of the graph
* (this is important since portals don't really work that way in the maze.
* In the maze, you pass from one node next to the portal to the other in 1 step.
* But since we need info on the portal for part 2, we keep them in the graph)
*
* @param input string representation of the maze
* @return the starting node of the maze
*/
private fun createGraph(input: String): Node{
val grid = input.lines().map { it.toCharArray().map { c -> c } }
val byPosition: MutableMap<Pair<Int,Int>, Node> = mutableMapOf()
val byName: MutableMap<String, Node> = mutableMapOf()
val startName = "AA"
val (startingPosition, startDirection) = findPortalPosition(grid, startName)
val startNode = Node(startName, outer = true, isPortal = true)
// To prevent duplicate node creation, maintain lookup maps for position and portal name
byPosition[startingPosition] = startNode
byName[startName] = startNode
// Use a stack to track nodes/positions we need to resolve
val stack = mutableListOf(ResolveNode(startDirection.location(startingPosition), startDirection, startNode))
while (stack.isNotEmpty()) {
val next = stack.removeAt(0)
if (next.position in byPosition) {
val existingNode = byPosition[next.position]!!
next.parent.neighbors.add(existingNode)
existingNode.neighbors.add(next.parent)
continue
}
val (row,col) = next.position
// use an outer/inner label to help determine portal depth for part 2
// anything along the outside edge of the maze gets labeled outer
val outer = row < 3 || row >= grid.size - 3 || col < 3 || col >= grid[row].size - 3
// Nodes must have a name for identification (use a position string for maze nodes and the portal name for portals)
var node = Node(next.position.let{ (r,c) -> "$r,$c"}, outer)
// This next node is a named portal, so it requires special logic
if (grid[row][col] != '.') {
val c1 = grid[row][col]
val c2 = next.direction.location(next.position).let { (r,c) -> grid[r][c] }
val name = when(next.direction) {
Direction.DOWN, Direction.RIGHT -> "$c1$c2"
Direction.LEFT, Direction.UP -> "$c2$c1"
}
// If we don't already know about this portal, create the node
if (!byName.contains(name)) {
node = Node(name, outer,true)
byName[name] = node
if (name != "ZZ"){
// Find the portal's other end, and continue parsing out the graph from there as well
val (otherPortal, otherDirection) = findPortalPosition(grid, name, next.position)
val neighborPosition = otherDirection.location(otherPortal)
stack.add(ResolveNode(neighborPosition, otherDirection, node))
}
}
}
next.parent.neighbors.add(node)
node.neighbors.add(next.parent)
byPosition[next.position] = node
// find neighbors
if (grid[row][col] == '.') {
for (direction in Direction.values()) {
if (direction == next.direction.reverse()) {
continue
}
val position = direction.location(next.position)
val (r,c) = position
if (grid[r][c] == ' ' || grid[r][c] == '#') {
continue
}
stack.add(ResolveNode(position, direction, node))
}
}
}
return startNode
}
/**
* Parsing out portals from the maze is difficult because they are 2 characters in length and can be up/down or sideways
*
* This method looks through the 2d input grid for a portal of a particular 2 character name.
* For portals that are not AA and ZZ, there are two such locations, so there is an optional exclusion for one end of the portal.
*
* @return The position in the grid of the portal (adjacent to an open maze position '.')
* AND the direction from this position the open maze position is.
*/
private fun findPortalPosition(grid: List<List<Char>>, name: String, exclude: Pair<Int,Int>? = null): Pair<Pair<Int,Int>, Direction> {
val (char1, char2) = name.toCharArray().map { c -> c }
for (r in 0 until grid.size - 1) {
for (c in 0 until grid[r].size - 1) {
if (exclude != null ) {
// don't look for the portal in areas we explicitly excluded (to keep from finding the portal end we already know about)
val (excludeR, excludeC) = exclude
if (r >= excludeR - 1 && r <= excludeR + 1 && c >= excludeC - 1 && c <= excludeC + 1) {
continue
}
}
if (grid[r][c] == char1) {
// up/down
if (grid[r+1][c] == char2) {
return if (r > 0 && grid[r-1][c] == '.') { Pair(Pair(r,c), Direction.UP) } else { Pair(Pair(r+1, c), Direction.DOWN) }
}
// sideways
if (grid[r][c+1] == char2) {
return if (c > 0 && grid[r][c-1] == '.') { Pair(Pair(r,c), Direction.LEFT) } else { Pair(Pair(r, c+1), Direction.RIGHT) }
}
}
}
}
throw UnsupportedOperationException("Could not find the portal location $name")
}
}
private class Node(val name: String, val outer: Boolean, val isPortal: Boolean = false, val neighbors: MutableList<Node> = mutableListOf())
private class ResolveNode(val position: Pair<Int,Int>, val direction: Direction, val parent: Node)
private class NodeCost(val node: Node, val cost: Int)
/**
* Helper enum class used when initially creating the graph
* Helps track what direction we are traversing the input grid to prevent duplications
*/
private enum class Direction {
UP,
LEFT,
DOWN,
RIGHT;
fun location(current: Pair<Int,Int>): Pair<Int,Int> {
val (r,c) = current
return when(this) {
UP -> Pair(r-1,c)
LEFT -> Pair(r, c-1)
DOWN -> Pair(r+1, c)
RIGHT -> Pair(r, c+1)
}
}
fun reverse(): Direction {
return when(this) {
UP -> DOWN
LEFT -> RIGHT
DOWN -> UP
RIGHT -> LEFT
}
}
} | 0 | Kotlin | 0 | 0 | 1a0b9cb6e9a11750c5b3b5a9e6b3d63649bf78e4 | 13,833 | advent2019 | The Unlicense |
app/src/main/kotlin/day08/Day08.kt | KingOfDog | 433,706,881 | false | {"Kotlin": 76907} | package day08
import common.InputRepo
import common.readSessionCookie
import common.solve
fun main(args: Array<String>) {
val day = 8
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay08Part1, ::solveDay08Part2)
}
fun solveDay08Part1(input: List<String>): Int {
val entries = input.map { it.split(" | ") }.map { line -> line[0].split(" ") to line[1].split(" ") }
var count = 0
entries.forEach { entry ->
val (tests, outputs) = entry
val numberCombinations = mutableMapOf<Int, List<Char>>()
tests.forEach { test ->
val chars = test.toCharArray().sorted()
when (chars.size) {
2 -> numberCombinations[1] = chars
4 -> numberCombinations[4] = chars
3 -> numberCombinations[7] = chars
7 -> numberCombinations[8] = chars
}
}
outputs.forEach { output ->
val chars = output.toCharArray().sorted()
if (numberCombinations.containsValue(chars)) count++
}
}
return count
}
fun solveDay08Part2(input: List<String>): Int {
val entries = input.map { it.split(" | ") }.map { line -> line[0].split(" ") to line[1].split(" ") }
return entries.sumOf { entry ->
val (tests, outputs) = entry
val display = SevenSegmentDisplay()
display.discriminateAll(tests)
println(display)
outputs.map { display.guess(it) }.joinToString("").toInt()
}
}
@OptIn(ExperimentalStdlibApi::class)
class SevenSegmentDisplay() {
private val matrix = Array(7) { Array(7) { true } }
val guaranteed = mutableMapOf<Char, Char>()
fun discriminateAll(rawDigits: List<String>) {
rawDigits
.map { it.toSegments() }
.map { segments -> segments to digitsWithSameSegmentCount(segments) }
.sortedBy { it.second.size }
.forEach { rawDigit ->
val rawSegmentIndices = rawDigit.first.map { it.toIndex() }
val digitCandidate = calculateDigitCandidate(rawSegmentIndices)
val possibleDigits = getPossibleDigitsForCandidate(rawDigit.second, digitCandidate)
val digit = findMatchingDigit(possibleDigits.values.toList(), rawSegmentIndices)
val d = digit.map { it - 'a' }
for (i in matrix.indices) {
if (!d.contains(i)) {
rawSegmentIndices.forEach { matrix[it][i] = false }
}
if (!rawSegmentIndices.contains(i)) {
d.forEach { matrix[i][it] = false }
}
}
}
}
private fun findMatchingDigit(
possibleDigits: List<List<Char>>,
rawSegmentIndices: List<Int>
): List<Char> {
return possibleDigits.first { possibleDigit -> hasNoUnusedSegments(rawSegmentIndices, possibleDigit) }
}
private fun hasNoUnusedSegments(
rawSegmentIndices: List<Int>,
possibleDigit: List<Char>
): Boolean = findUnusedSegmentsForDigit(rawSegmentIndices, possibleDigit).isEmpty()
private fun findUnusedSegmentsForDigit(
rawSegmentIndices: List<Int>,
possibleDigit: List<Char>
): List<Char> {
val rawSegmentIndicesToBeUsed = rawSegmentIndices.toMutableList()
val requiredSegments = possibleDigit.toMutableList()
while (rawSegmentIndicesToBeUsed.size > 0 && requiredSegments.size > 0) {
val actualSegment = requiredSegments.random()
val possibleSegmentIndices = findPossibleSegments(rawSegmentIndicesToBeUsed, actualSegment.toIndex())
when(possibleSegmentIndices.size) {
0 -> break
1 -> {
rawSegmentIndicesToBeUsed.remove(possibleSegmentIndices.first())
requiredSegments.remove(actualSegment)
}
else -> {
if (areAllSegmentsPossible(rawSegmentIndicesToBeUsed, possibleSegmentIndices)) {
rawSegmentIndicesToBeUsed.removeAll(possibleSegmentIndices)
requiredSegments.removeAllPossibleSegments()
}
}
}
}
return requiredSegments
}
private fun MutableList<Char>.removeAllPossibleSegments() {
removeAll { segment -> getPossibleSegmentsForRawIndex(0).any { 'a' + it.index == segment } }
}
private fun areAllSegmentsPossible(
rawSegmentIndicesToBeUsed: List<Int>,
possibleSegmentIndices: List<Int>,
) = rawSegmentIndicesToBeUsed.containsAll(possibleSegmentIndices) && possibleSegmentIndices.all {
getPossibleSegmentsForRawIndex(it) == getPossibleSegmentsForRawIndex(0)
}
private fun getPossibleSegmentsForRawIndex(rawIndex: Int) =
matrix[rawIndex].withIndex().filter { it.value }
private fun findPossibleSegments(
rawSegmentIndicesToBeUsed: List<Int>,
actualSegmentIndex: Int
) = rawSegmentIndicesToBeUsed.filter { index -> isOpen(index, actualSegmentIndex) }
private fun isOpen(rawIndex: Int, actualIndex: Int) = matrix[rawIndex][actualIndex]
private fun getPossibleDigitsForCandidate(
digitPool: Map<Int, List<Char>>,
digitCandidate: MutableMap<Char, SegmentState>
): Map<Int, List<Char>> = digitPool.filterValues { digit ->
digit.all { segment -> digitCandidate[segment] != SegmentState.OFF }
}
private fun calculateDigitCandidate(rawSegmentIndices: List<Int>): MutableMap<Char, SegmentState> {
val digitCandidate = mutableMapOf<Char, SegmentState>()
rawSegmentIndices.forEach { index ->
val stuff = matrix[index].withIndex().filter { it.value }
if (stuff.size > 1) {
stuff.forEach { i ->
val state = digitCandidate['a' + i.index]
digitCandidate['a' + i.index] =
if (state == SegmentState.POSSIBLE) SegmentState.ON else SegmentState.POSSIBLE
}
} else if (stuff.size == 1) {
digitCandidate['a' + stuff.first().index] = SegmentState.ON
}
}
return digitCandidate
}
private fun digitsWithSameSegmentCount(segments: List<Char>) =
digits.filterValues { it.size == segments.size }
fun guess(digit: String): Int {
val chars = digit.toCharArray()
val segments =
chars.map { char -> matrix[char.toIndex()].withIndex().first { it.value }.index.toSegment() }.sorted()
return digits.filterValues { it == segments }.keys.first()
}
override fun toString(): String {
var result = ""
matrix.forEach { row ->
row.forEach { cell ->
result += if (cell) " " else "X"
}
result += "\n"
}
return result
}
companion object {
private val digits = mapOf(
0 to listOf('a', 'b', 'c', 'e', 'f', 'g'),
1 to listOf('c', 'f'),
2 to listOf('a', 'c', 'd', 'e', 'g'),
3 to listOf('a', 'c', 'd', 'f', 'g'),
4 to listOf('b', 'c', 'd', 'f'),
5 to listOf('a', 'b', 'd', 'f', 'g'),
6 to listOf('a', 'b', 'd', 'e', 'f', 'g'),
7 to listOf('a', 'c', 'f'),
8 to listOf('a', 'b', 'c', 'd', 'e', 'f', 'g'),
9 to listOf('a', 'b', 'c', 'd', 'f', 'g'),
)
}
}
enum class SegmentState {
OFF,
POSSIBLE,
ON
}
private fun String.toSegments() = toCharArray().sorted()
private fun Int.toSegment(): Char = 'a' + this
private fun Char.toIndex(): Int = this - 'a'
| 0 | Kotlin | 0 | 0 | 576e5599ada224e5cf21ccf20757673ca6f8310a | 7,765 | advent-of-code-kt | Apache License 2.0 |
src/Day02.kt | chbirmes | 572,675,727 | false | {"Kotlin": 32114} | import java.lang.IllegalArgumentException
fun main() {
fun score1(opponentChoice: Char, ownChoice: Char) =
when (Pair(opponentChoice, ownChoice)) {
Pair('A', 'X') -> 1 + 3
Pair('A', 'Y') -> 2 + 6
Pair('A', 'Z') -> 3 + 0
Pair('B', 'X') -> 1 + 0
Pair('B', 'Y') -> 2 + 3
Pair('B', 'Z') -> 3 + 6
Pair('C', 'X') -> 1 + 6
Pair('C', 'Y') -> 2 + 0
Pair('C', 'Z') -> 3 + 3
else -> throw IllegalArgumentException()
}
fun part1(input: List<String>): Int = input.sumOf { score1(it[0], it[2]) }
fun score2(opponentChoice: Char, outcome: Char) =
when (Pair(opponentChoice, outcome)) {
Pair('A', 'X') -> 3 + 0
Pair('A', 'Y') -> 1 + 3
Pair('A', 'Z') -> 2 + 6
Pair('B', 'X') -> 1 + 0
Pair('B', 'Y') -> 2 + 3
Pair('B', 'Z') -> 3 + 6
Pair('C', 'X') -> 2 + 0
Pair('C', 'Y') -> 3 + 3
Pair('C', 'Z') -> 1 + 6
else -> throw IllegalArgumentException()
}
fun part2(input: List<String>): Int = input.sumOf { score2(it[0], it[2]) }
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | db82954ee965238e19c9c917d5c278a274975f26 | 1,402 | aoc-2022 | Apache License 2.0 |
kotlin/2022/round-1a/equal-sum/src/main/kotlin/Solution.kt | ShreckYe | 345,946,821 | false | null | import kotlin.system.exitProcess
fun main() {
val t = readLineOrExit()!!.toInt()
repeat(t) { testCase() }
}
fun readLineOrExit() =
readLine().also {
if (it == "-1")
exitProcess(0)
}
fun testCase() {
val nn = readLineOrExit()!!.toInt()
val aas = generateAas(nn)
println(aas.joinToString(" "))
val bbs = readLineOrExit()!!.splitToSequence(' ').map { it.toLong() }.toList()
val expectedSum = (bbs.sum() + aas.sum()) / 2
println(solve(nn, bbs, expectedSum).joinToString(" "))
}
fun solve(nn: Int, bbs: List<Long>, expectedSum: Long): List<Long> =
greedyAndPick(bbs, expectedSum, nn)!!
fun generateAas(nn: Int) =
List(nn) { (1 shl it.coerceAtMost(29)).toLong() }
fun greedyPartitionMinDiff(bbs: List<Long>): Pair<Long, List<Long>> {
val sbbs = bbs.sortedDescending()
val firstSubset = ArrayList<Long>(bbs.size * 2)
var firstSubsetSum = 0L
var secondSubsetSum = 0L
for (b in sbbs)
if (firstSubsetSum <= secondSubsetSum) {
firstSubset += b
firstSubsetSum += b
} else
secondSubsetSum += b
return firstSubsetSum to firstSubset
}
fun greedyAndPick(bbs: List<Long>, expectedSum: Long, nn: Int): List<Long>? {
val (firstSubsetSum, firstSubset) = greedyPartitionMinDiff(bbs)
val n = nn.coerceAtMost(29)
return if (canPick(firstSubsetSum, expectedSum, n))
firstSubset + pickAAs((expectedSum - firstSubsetSum).toIntExact(), n)
else null
}
fun Long.toIntExact() =
Math.toIntExact(this)
fun maxSum(n: Int): Int {
require(n <= 29)
return 2 shl (n + 1) - 1
}
fun canPick(bbsFirstSubsetSum: Long, expectedSum: Long, n: Int): Boolean {
require(n <= 29)
return bbsFirstSubsetSum <= expectedSum && bbsFirstSubsetSum + maxSum(n) >= expectedSum
}
fun pickAAs(diff: Int, n: Int): List<Long> {
require(n <= 29)
val list = ArrayList<Long>(n + 1)
for (i in 0..n) {
val twoPowI = 1 shl i
if (diff and twoPowI != 0)
list.add(twoPowI.toLong())
}
return list
}
| 0 | Kotlin | 1 | 1 | 743540a46ec157a6f2ddb4de806a69e5126f10ad | 2,078 | google-code-jam | MIT License |
src/main/kotlin/day9.kt | Gitvert | 433,947,508 | false | {"Kotlin": 82286} | fun day9() {
val lines: List<String> = readFile("day09.txt")
day9part1(lines)
day9part2(lines)
}
fun day9part1(lines: List<String>) {
val heightMap = getHeightMap(lines)
val lowPoints = getLowPoints(heightMap)
val answer = lowPoints.sumOf { heightMap[it.first][it.second] + 1 }
println("9a: $answer")
}
fun day9part2(lines: List<String>) {
val heightMap = getHeightMap(lines)
val lowPoints = getLowPoints(heightMap)
var basinCoordinates: MutableSet<Pair<Int, Int>>
val basinSizes: MutableList<Int> = mutableListOf()
lowPoints.forEach {
basinCoordinates = mutableSetOf()
getBasinCoordinates(heightMap, it.first, it.second, basinCoordinates)
basinSizes.add(basinCoordinates.size)
}
val answer = basinSizes.sortedDescending().subList(0, 3).reduce { product, i -> product * i }
println("9b: $answer")
}
fun getLowPoints(heightMap: Array<IntArray>): List<Pair<Int, Int>> {
val lowPoints: MutableList<Pair<Int, Int>> = mutableListOf()
heightMap.forEachIndexed { i, row ->
row.forEachIndexed { j, _ ->
if (isLowPoint(heightMap, i, j)) {
lowPoints.add(Pair(i, j))
}
}
}
return lowPoints
}
fun isLowPoint(heightMap: Array<IntArray>, i: Int, j: Int): Boolean {
var isLowPoint = true
if (i > 0 && heightMap[i][j] >= heightMap[i-1][j]) {
isLowPoint = false
}
if (i < heightMap.size - 1 && heightMap[i][j] >= heightMap[i+1][j]) {
isLowPoint = false
}
if (j > 0 && heightMap[i][j] >= heightMap[i][j-1]) {
isLowPoint = false
}
if (j < heightMap[0].size - 1 && heightMap[i][j] >= heightMap[i][j+1]) {
isLowPoint = false
}
return isLowPoint
}
fun getBasinCoordinates(heightMap: Array<IntArray>, i: Int, j: Int, basinCoordinates: MutableSet<Pair<Int, Int>>) {
basinCoordinates.add(Pair(i, j))
if (i > 0 && heightMap[i][j] < heightMap[i-1][j] && heightMap[i-1][j] != 9) {
getBasinCoordinates(heightMap, i-1, j, basinCoordinates)
}
if (i < heightMap.size - 1 && heightMap[i][j] < heightMap[i+1][j] && heightMap[i+1][j] != 9) {
getBasinCoordinates(heightMap, i+1, j, basinCoordinates)
}
if (j > 0 && heightMap[i][j] < heightMap[i][j-1] && heightMap[i][j-1] != 9) {
getBasinCoordinates(heightMap, i, j-1, basinCoordinates)
}
if (j < heightMap[0].size - 1 && heightMap[i][j] < heightMap[i][j+1] && heightMap[i][j+1] != 9) {
getBasinCoordinates(heightMap, i, j+1, basinCoordinates)
}
}
fun getHeightMap(lines: List<String>): Array<IntArray> {
val heightMap = Array(lines.size) { IntArray(lines[0].length) { 0 } }
lines.forEachIndexed { i, row ->
row.forEachIndexed { j, _ ->
heightMap[i][j] = Integer.valueOf(row[j].toString())
}
}
return heightMap
}
| 0 | Kotlin | 0 | 0 | 02484bd3bcb921094bc83368843773f7912fe757 | 2,893 | advent_of_code_2021 | MIT License |
src/Day04.kt | kent10000 | 573,114,356 | false | {"Kotlin": 11288} | import kotlin.math.abs
fun main() {
fun part1(input: List<String>): Int {
var count = 0
for (line in input) {
val parts = line.split(Regex("[-,]"))
val elf1 = Pair(parts.component1().toInt(), parts.component2().toInt())
val elf2 = Pair(parts.component3().toInt(), parts.component4().toInt())
/*val r1 = abs(elf2.second - elf1.second)
val r2 = abs(elf2.first - elf1.first)
println(("$r1 $r2"))*/
//2, 0
//7,0
//4,4
//4..6 and 6..6
//9..10 2..10
if (elf1.second == elf2.second ) {
count++
continue
}
if (elf1.second > elf2.second ) {
if (elf1.first <= elf2.first) count++
continue
}
if (elf1.first >= elf2.first) {
count++
continue
}
}
return count
}
fun part2(input: List<String>): Int {
var count = 0
for (line in input) {
val parts = line.split(Regex("[-,]"))
val elf1 = parts.component1().toInt()..parts.component2().toInt()
val elf2 = parts.component3().toInt()..parts.component4().toInt()
if (elf1.intersect(elf2).isNotEmpty()) count++
}
return count
}
/* test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 1)
*/
val input = readInput("day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | c128d05ab06ecb2cb56206e22988c7ca688886ad | 1,637 | advent-of-code-2022 | Apache License 2.0 |
src/stack/LeetCode150.kt | Alex-Linrk | 180,918,573 | false | null | package stack
import java.util.*
/**
* 根据逆波兰表示法,求表达式的值。
有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。
说明:
整数除法只保留整数部分。
给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。
示例 1:
输入: ["2", "1", "+", "3", "*"]
输出: 9
解释: ((2 + 1) * 3) = 9
示例 2:
输入: ["4", "13", "5", "/", "+"]
输出: 6
解释: (4 + (13 / 5)) = 6
示例 3:
输入: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
输出: 22
解释:
((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/evaluate-reverse-polish-notation
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
class LeetCode150 {
fun evalRPN(tokens: Array<String>): Int {
val nums = Stack<Int>()
val symbols = arrayOf("+", "-", "*", "/")
for (item in tokens) {
when (item) {
in symbols -> {
if (nums.size > 1) {
val second = nums.pop()
val first = nums.pop()
when (item) {
"+" -> {
nums.push(first + second)
}
"-" -> {
nums.push(first - second)
}
"*" -> {
nums.push(first * second)
}
"/" -> {
nums.push(first / second)
}
}
}
}
else -> {
nums.push(item.toInt())
}
}
}
return nums.pop()
}
}
fun main() {
println(LeetCode150().evalRPN(
arrayOf("2", "1", "+", "3", "*")
))
println(LeetCode150().evalRPN(
arrayOf("4", "13", "5", "/", "+")
))
println(LeetCode150().evalRPN(
arrayOf("10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+")
))
} | 0 | Kotlin | 0 | 0 | 59f4ab02819b7782a6af19bc73307b93fdc5bf37 | 2,476 | LeetCode | Apache License 2.0 |
app/src/main/kotlin/solution/Solution834.kt | likexx | 559,794,763 | false | {"Kotlin": 136661} | package solution
import solution.annotation.Leetcode
class Solution834 {
@Leetcode(834)
class Solution {
fun sumOfDistancesInTree(n: Int, edges: Array<IntArray>): IntArray {
// we could come up with 2 formulas:
// 1. if j is the neighbor of i, distances[i] += distances[j] + # of nodes in node j, and iterate for each j
// 2. if there is edge (i,j), for subtree i and subtree j, we have:
// distances[i] - distances[j] = (N - count[i]) - count[i] =>
// distances[i] = distances[j] + (N-2*count[i])
val neighbors = hashMapOf<Int, MutableSet<Int>>()
for (e in edges) {
var vertices = neighbors.getOrDefault(e[0], mutableSetOf())
vertices.add(e[1])
neighbors[e[0]] = vertices
vertices = neighbors.getOrDefault(e[1], mutableSetOf())
vertices.add(e[0])
neighbors[e[1]] = vertices
}
// total nodes in subtree of i
val count = IntArray(n) { 1 }
val distances = IntArray(n) { 0 }
// find the result for distance[0], and update count[i]
fun countForRoot(i: Int, parent: Int) {
val vertices = neighbors.getOrDefault(i, mutableSetOf())
for (j in vertices) {
if (j == parent) {
continue
}
countForRoot(j, i)
count[i] += count[j]
distances[i] += distances[j] + count[j]
}
}
// update for each node
fun updateForEachNode(i: Int, parent: Int) {
val vertices = neighbors.getOrDefault(i, mutableSetOf())
for (j in vertices) {
if (j==parent) {
continue
}
distances[j] = distances[i] + n - 2 * count[j]
updateForEachNode(j, i)
}
}
countForRoot(0, -1)
updateForEachNode(0, -1)
return distances
}
fun sumOfDistancesInTree_Naive(n: Int, edges: Array<IntArray>): IntArray {
val neighbors = hashMapOf<Int, MutableSet<Int>>()
for (e in edges) {
var vertices = neighbors.getOrDefault(e[0], mutableSetOf())
vertices.add(e[1])
neighbors[e[0]] = vertices
vertices = neighbors.getOrDefault(e[1], mutableSetOf())
vertices.add(e[0])
neighbors[e[1]] = vertices
}
val distances = hashMapOf<Pair<Int, Int>, Int>()
val visited = hashSetOf<Int>()
fun findDistance(i:Int, j:Int):Int {
if (i==j) {
return 0
}
val key1 = Pair(i, j)
if (distances.contains(key1)) {
return distances[key1]!!
}
val key2 = Pair(j, i)
if (distances.contains(key2)) {
return distances[key2]!!
}
visited.add(i)
var distance = -1
val vertices = neighbors.getOrDefault(i, mutableSetOf())
for (v in vertices) {
if (visited.contains(v)) {
continue
}
val d = findDistance(v, j)
if (d==-1) {
continue
}
distance = 1 + d
break
}
if (distance>=0) {
distances[key1] = distance
distances[key2] = distance
}
visited.remove(i)
return distance
}
val sum = IntArray(n)
for (i in 0..n-1) {
var d = 0
for (j in 0..n-1) {
d += findDistance(i,j)
}
sum[i]=d
}
return sum
}
}
} | 0 | Kotlin | 0 | 0 | 376352562faf8131172e7630ab4e6501fabb3002 | 4,184 | leetcode-kotlin | MIT License |
src/Day06.kt | illarionov | 572,508,428 | false | {"Kotlin": 108577} | fun main() {
fun part1(input: String, markerLength: Int = 4): Int {
var i = markerLength - 1
while (i <= input.lastIndex) {
var lastMatch: Int? = null
var j = 0
while (lastMatch == null && j < markerLength) {
val compareSymbol = input[i - j]
lastMatch = (j + 1 until markerLength).firstOrNull { k ->
input[i - k] == compareSymbol
}
j += 1
}
if (lastMatch != null) {
i += (markerLength - lastMatch)
} else {
return i + 1
}
}
return 0
}
fun part2(input: String): Int {
//return input.size
return part1(input, 14)
// Dirty solution with windowed, sets
// var i = 0
// return input.windowed(14, 1) { t: CharSequence ->
// if (t.toSet().size == 14) {
// return@windowed i
// }
// i += 1
// return@windowed -1
// }.first { it != -1 } + 14
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test").single()
val part1 = part1(testInput)
println("part1: $part1")
check(part1 == 11)
val input = readInput("Day06").single()
val part1Result = part1(input)
println(part1Result)
//check(part1Result == 1034)
val part2Result = part2(input)
println(part2Result)
//check(part2Result == 2472)
}
| 0 | Kotlin | 0 | 0 | 3c6bffd9ac60729f7e26c50f504fb4e08a395a97 | 1,533 | aoc22-kotlin | Apache License 2.0 |
kotlin/src/katas/kotlin/leetcode/k_closest_points_to_origin/KClosestPointsToOrigin.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.leetcode.k_closest_points_to_origin
import datsok.shouldEqual
import org.junit.Test
import kotlin.math.sqrt
class KClosestPointsToOriginTests {
@Test fun examples() {
kClosest(listOf(Point(1, 1), Point(2, 2)), k = 2) shouldEqual setOf(Point(1, 1), Point(2, 2))
kClosest(listOf(Point(3, 3), Point(2, 2), Point(1, 1)), k = 2) shouldEqual setOf(Point(1, 1), Point(2, 2))
kClosest(listOf(Point(4, 4), Point(3, 3), Point(2, 2), Point(1, 1)), k = 2) shouldEqual setOf(Point(1, 1), Point(2, 2))
val hundredPoints = (1..100).map { Point(it, it) }.shuffled()
kClosest(hundredPoints, k = 3) shouldEqual setOf(Point(1, 1), Point(2, 2), Point(3, 3))
kClosest(listOf(Point(1, 3), Point(-2, 2)), k = 1) shouldEqual setOf(Point(-2, 2))
kClosest(listOf(Point(3, 3), Point(5, -1), Point(-2, 4)), k = 2) shouldEqual setOf(Point(3, 3), Point(-2, 4))
}
}
private fun kClosest(points: List<Point>, k: Int): Set<Point> {
require(k <= points.size)
var from = 0
var to = points.size
val pivot = points.first()
val (left, right) = points.partition { it.distanceToOrigin < pivot.distanceToOrigin }
// if (left.size < k)
return points.sortedBy { it.distanceToOrigin }.take(k).toSet()
}
private fun kClosest_(points: List<Point>, k: Int) = points.sortedBy { it.distanceToOrigin }.take(k)
private data class Point(val x: Int, val y: Int) {
val distanceToOrigin: Double = sqrt(x.toDouble() * x + y * y)
} | 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 1,499 | katas | The Unlicense |
src/main/kotlin/day17/Day17.kt | Arch-vile | 317,641,541 | false | null | package day17
import readFile
data class Coordinates(val x: Int, val y: Int, val z: Int, val w: Int)
data class Cube(var state: Boolean) {
fun stateSymbol(): Char {
return if (state) '#' else '.'
}
}
class World {
// Let's make world enough to contain everything after 6 rounds of expansion
// Also +2 to make sure we have neighbours for the edge pieces available.
var data: List<List<List<List<Cube>>>> = IntRange(0, 40)
.map {
IntRange(0, 40)
.map {
IntRange(0, 40)
.map {
IntRange(0, 40)
.map { Cube(false) }
}
}
}
fun getCube(x: Int, y: Int, z: Int, w: Int) = data[x][y][z][w]
fun all(): Sequence<Pair<Coordinates, Cube>> {
return sequence {
for (x in 1 until data.size - 1) {
for (y in 1 until data[0].size - 1) {
for (z in 1 until data[0][0].size - 1) {
for (w in 1 until data[0][0][0].size - 1) {
yield(Pair(Coordinates(x, y, z, w), data[x][y][z][w]))
}
}
}
}
}
}
fun getNeighbours(x: Int, y: Int, z: Int, w: Int): List<Cube> {
return IntRange(-1, 1).flatMap { xOffset ->
IntRange(-1, 1).flatMap { yOffset ->
IntRange(-1, 1).flatMap { zOffset ->
IntRange(-1, 1).map { wOffset ->
if (xOffset == 0 && yOffset == 0 && zOffset == 0 && wOffset == 0) {
null
} else {
getCube(x + xOffset, y + yOffset, z + zOffset, w + wOffset)
}
}
}
}
}.filterNotNull()
}
}
fun main(args: Array<String>) {
val input = readFile("./src/main/resources/day17Input.txt")
.map { it.toCharArray() }
val world = World()
val xOffset = 15
val yOffset = 15
val w = 15
val z = 15
// Load the initial state from input
input.forEachIndexed { y, line ->
line.forEachIndexed { x, cubeState ->
if (cubeState == '#') {
world.getCube(x + xOffset, -y + yOffset, z, w).state = true
}
}
}
repeat(6) {
val statesToSwitch = mutableListOf<Cube>()
world.all().forEach {
val (x, y, z, w) = it.first
val cube = it.second
val activeNeighbours =
world.getNeighbours(x, y, z, w)
.filter { it.state }
if (cube.state) {
if (!(activeNeighbours.size == 2 || activeNeighbours.size == 3)) {
statesToSwitch.add(cube)
}
} else {
if (activeNeighbours.size == 3) {
statesToSwitch.add(cube)
}
}
}
statesToSwitch.forEach { it.state = !it.state }
}
println(
world.all()
.filter { it.second.state }
.count())
// printWorld(world)
}
fun printWorld(world: World) {
for (z in world.data[0][0].indices) {
println("Z: $z")
for (y in world.data[0].indices) {
for (x in world.data.indices) {
print(world.getCube(x, world.data[0].size - 1 - y, z, 0).stateSymbol())
}
println("")
}
println("-------------------------------------------------")
}
}
| 0 | Kotlin | 0 | 0 | 12070ef9156b25f725820fc327c2e768af1167c0 | 3,066 | adventOfCode2020 | Apache License 2.0 |
src/Day02_part1.kt | rdbatch02 | 575,174,840 | false | {"Kotlin": 18925} | class Move(
val representations: List<String>,
val points: Int,
val beats: String
) {
companion object {
fun parseMove(input: String): Move {
return when(input) {
"A" -> rock()
"X" -> rock()
"B" -> paper()
"Y" -> paper()
"C" -> scissors()
"Z" -> scissors()
else -> throw NotImplementedError()
}
}
private fun rock(): Move = Move(
representations = listOf("A", "X"),
points = 1,
beats = "C"
)
private fun paper(): Move = Move(
representations = listOf("B", "Y"),
points = 2,
beats = "A"
)
private fun scissors(): Move = Move(
representations = listOf("C", "Z"),
points = 3,
beats = "B"
)
}
}
fun main() {
fun parseData(input: List<String>): List<Pair<Move, Move>> {
return input.map {
val moves = it.split(" ")
Pair(Move.parseMove(moves.first()), Move.parseMove(moves.last()))
}
}
fun checkWin(round: Pair<Move, Move>): Boolean = round.first.representations.contains(round.second.beats)
fun checkDraw(round: Pair<Move, Move>): Boolean = round.first.beats == round.second.beats
fun part1(input: List<String>): Int {
val rounds = parseData(input)
var totalScore = 0
rounds.forEach {
totalScore += it.second.points // Add points for my move regardless of win
if (checkWin(it)) {
totalScore += 6 // 6 points for win
}
else if (checkDraw(it)) {
totalScore += 3 // 3 points for draw
}
}
return totalScore
}
val input = readInput("Day02")
println("Part 1 - " + part1(input))
}
| 0 | Kotlin | 0 | 1 | 330a112806536910bafe6b7083aa5de50165f017 | 1,905 | advent-of-code-kt-22 | Apache License 2.0 |
src/Day01.kt | ajmfulcher | 573,611,837 | false | {"Kotlin": 24722} | fun main() {
fun part1(input: List<String>): Int {
var curr = 0
var largest = 0
input.forEach { item ->
when (item) {
"" -> {
if (curr > largest) largest = curr
curr = 0
}
else -> curr += item.toInt()
}
}
return largest
}
fun part2(input: List<String>): Int {
val ec = mutableListOf<Int>(0)
input.forEach { item ->
when(item) {
"" -> ec.add(0)
else -> ec[ec.lastIndex] += item.toInt()
}
}
return ec
.sortedDescending()
.take(3)
.fold(0) { acc, i -> acc + i }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
val input = readInput("Day01")
println(part1(input))
check(part2(testInput) == 45000)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 981f6014b09e347241e64ba85e0c2c96de78ef8a | 1,037 | advent-of-code-2022-kotlin | Apache License 2.0 |
2023/src/main/kotlin/day4_fast.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parser
import utils.Solution
import utils.mapItems
import utils.pow2
fun main() {
Day4Imp.run(skipTest = false)
}
object Day4Imp : Solution<List<Day4Imp.Card>>() {
override val name = "day4"
override val parser = Parser.lines
.mapItems { Day4.parseCard(it) }
.mapItems { card ->
val sz = card.numbers.max() + 1
Card(BooleanArray(sz) { it in card.winning }, card.numbers.toIntArray())
}
class Card(
private val winning: BooleanArray,
private val numbers: IntArray,
) {
val score: Pair<Int, Int> get() {
val count = numbers.count { winning[it] }
val score = if (count == 0) 0 else pow2(count - 1)
return count to score
}
}
override fun part1(input: List<Card>): Int {
return input.sumOf { it.score.second }
}
override fun part2(input: List<Card>): Int {
val counts = IntArray(input.size) { 1 }
input.indices.forEach { i ->
val card = input[i]
val (count, _) = card.score
(0 until count).forEach {
counts[i + it + 1] += counts[i]
}
}
return counts.sum()
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 1,105 | aoc_kotlin | MIT License |
src/Day05.kt | sungi55 | 574,867,031 | false | {"Kotlin": 23985} | fun main() {
val day = "Day05"
val testPackages = mapOf<Int, List<String>>(
1 to mutableListOf("N", "Z"),
2 to mutableListOf("D", "C", "M"),
3 to mutableListOf("P")
)
val inputPackages = mapOf<Int, List<String>>(
1 to mutableListOf("N", "R", "J", "T", "Z", "B", "D", "F"),
2 to mutableListOf("H", "J", "N", "S", "R"),
3 to mutableListOf("Q", "F", "Z", "G", "J", "N", "R", "C"),
4 to mutableListOf("Q", "T", "R", "G", "N", "V", "F"),
5 to mutableListOf("F", "Q", "T", "L"),
6 to mutableListOf("N", "G", "R", "B", "Z", "W", "C", "Q"),
7 to mutableListOf("M", "H", "N", "S", "L", "C", "F"),
8 to mutableListOf("J", "T", "M", "Q", "N", "D"),
9 to mutableListOf("S", "G", "P")
)
fun getBottomPackages(
packages: Map<Int, List<String>>,
commands: List<String>,
isReverseOrdering: Boolean
): String {
val stack = packages.toMutableMap()
return commands.map {
it.split(" ").let { move ->
Triple(move[1].toInt(), move[3].toInt(), move[5].toInt())
}
}.forEach { (amount, from, to) ->
val fromColumn = stack[from]!!.take(amount)
val toColumn = fromColumn.let { if (isReverseOrdering) it.reversed() else it }.plus(stack[to]!!)
val newFromColumn = stack[from]!!.drop(amount)
stack[from] = newFromColumn
stack[to] = toColumn
}.let {
stack.values.joinToString("") { it.first() }
}
}
fun part1(packages: Map<Int, List<String>>, commands: List<String>): String =
getBottomPackages(packages, commands, isReverseOrdering = true)
fun part2(packages: Map<Int, List<String>>, commands: List<String>): String =
getBottomPackages(packages, commands, isReverseOrdering = false)
val testInput = readInput(name = "${day}_test")
val inputCommands = readInput(name = day)
check(part1(testPackages, testInput) == "CMZ")
check(part2(testPackages, testInput) == "MCD")
println(part1(inputPackages, inputCommands))
println(part2(inputPackages, inputCommands))
} | 0 | Kotlin | 0 | 0 | 2a9276b52ed42e0c80e85844c75c1e5e70b383ee | 2,189 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2022/2022-04.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2022
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputLines
fun main() {
val input = readInputLines(2022, "04-input")
val testInput1 = readInputLines(2022, "04-test1")
println("Part1:")
part1(testInput1).println()
part1(input).println()
println()
println("Part2:")
part2(testInput1).println()
part2(input).println()
}
private fun String.toRange(): IntRange = split('-').let { (a,b) -> a.toInt()..b.toInt() }
private fun part1(input: List<String>): Int {
val ranges = parseRanges(input)
return ranges.count { (a, b) -> a.first in b && a.last in b || b.first in a && b.last in a }
}
private fun part2(input: List<String>): Int {
val ranges = parseRanges(input)
return ranges.count { (a, b) -> a.first in b || a.last in b || b.first in a || b.last in a }
}
private fun parseRanges(input: List<String>) = input
.map { it.split(',') }
.map { (a, b) -> a.toRange() to b.toRange() }
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 1,038 | advent-of-code | MIT License |
solution/kotlin/aoc/src/main/kotlin/codes/jakob/aoc/Day03.kt | loehnertz | 573,145,141 | false | {"Kotlin": 53239} | package codes.jakob.aoc
import codes.jakob.aoc.shared.splitByEach
import codes.jakob.aoc.shared.splitInHalf
import codes.jakob.aoc.shared.splitMultiline
class Day03 : Solution() {
override fun solvePart1(input: String): Any {
return input
.splitMultiline()
.asSequence()
.map { it.splitByEach() }
.map { it.splitInHalf() }
.map { (compartmentA: List<Char>, compartmentB: List<Char>) ->
compartmentA.toSet() intersect compartmentB.toSet()
}
.map { it.first() }
.sumOf { it.toPriority() }
}
override fun solvePart2(input: String): Any {
return input
.splitMultiline()
.asSequence()
.chunked(3)
.map { group: List<String> ->
group.map { rucksack: String -> rucksack.splitByEach().toSet() }
}
.map { (elfA: Set<Char>, elfB: Set<Char>, elfC: Set<Char>) ->
elfA intersect elfB intersect elfC
}
.map { it.first() }
.sumOf { it.toPriority() }
}
}
fun Char.toPriority(): Int {
return if (this.isUpperCase()) {
(this - 38).code
} else {
(this - 96).code
}
}
fun main() = Day03().solve()
| 0 | Kotlin | 0 | 0 | ddad8456dc697c0ca67255a26c34c1a004ac5039 | 1,294 | advent-of-code-2022 | MIT License |
src/Day10.kt | dmarmelo | 573,485,455 | false | {"Kotlin": 28178} | private sealed class Instruction {
abstract val cycles: Int
object Noop : Instruction() {
override val cycles: Int
get() = 1
}
data class Addx(val argument: Int) : Instruction() {
override val cycles: Int
get() = 2
}
}
fun main() {
fun String.toInstruction() = with(this) {
when {
equals("noop") -> Instruction.Noop
startsWith("addx") -> Instruction.Addx(removePrefix("addx ").toInt())
else -> error("Unknown instriction $this")
}
}
fun List<String>.parseInput(): List<Instruction> = map { it.toInstruction() }
fun List<Instruction>.run(onCycle: (cycle: Int, x: Int) -> Unit) {
val iterator = iterator()
// Load first Instruction
var instruction = iterator.next()
var remainigCycles = instruction.cycles
var x = 1
for (cycle in (1..240)) {
onCycle(cycle, x)
remainigCycles--
if (remainigCycles == 0) {
// Execute Instruction
if (instruction is Instruction.Addx) {
x += instruction.argument
}
// Load next Instruction if there is one
if (iterator.hasNext()) {
instruction = iterator.next()
remainigCycles = instruction.cycles
}
}
}
}
fun part1(input: List<Instruction>): Int {
var signalStrength = 0
input.run { cycle, x ->
if (cycle in (20..220 step 40)) {
signalStrength += cycle * x
}
}
return signalStrength
}
fun part2(input: List<Instruction>): String {
val crtWidth = 40
var crt = ""
input.run { cycle, x ->
val crtHorizontalPosition = (cycle - 1) % crtWidth
crt += if (crtHorizontalPosition in (x - 1..x + 1)) "#" else "."
if (crtHorizontalPosition == crtWidth - 1) crt += "\n"
}
return crt
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test").parseInput()
check(part1(testInput) == 13140)
println(part2(testInput))
val input = readInput("Day10").parseInput()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5d3cbd227f950693b813d2a5dc3220463ea9f0e4 | 2,368 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | JanTie | 573,131,468 | false | {"Kotlin": 31854} | fun main() {
fun executeInstructions(
input: List<String>,
transactionHandling: (map: MutableMap<Int, List<Char>>, amount: Int, from: Int, to: Int) -> Unit,
): Map<Int, List<Char>> {
val dividerIndex = input.indexOfFirst { it.isBlank() }
val map = input.subList(0, dividerIndex - 1)
val indices = input.subList(dividerIndex - 1, dividerIndex)[0]
val mutableMap = indices
.filter { !it.isWhitespace() }
.map { indices.indexOf(it) }
.associate { index ->
indices[index].digitToInt() to map.reversed()
.mapNotNull { it.getOrNull(index)?.takeIf { !it.isWhitespace() } }
}
.toMutableMap()
val instructions = input.subList(dividerIndex + 1, input.size)
.map {
it.split("move ", " from ", " to ")
.mapNotNull { it.toIntOrNull() }
}
instructions.forEach { (amount, from, to) ->
transactionHandling(mutableMap, amount, from, to)
}
return mutableMap
}
fun part1(input: List<String>): String {
return executeInstructions(input) { map, amount, from, to ->
(0 until amount).forEach {
val char: Char = map[from]!!.last()
map[from] = map[from]!!.dropLast(1)
map[to] = map[to]!! + char
}
}
.map { it.value.last() }
.joinToString("")
}
fun part2(input: List<String>): String {
return executeInstructions(input) { map, amount, from, to ->
val chars: List<Char> = map[from]!!.takeLast(amount)
map[from] = map[from]!!.dropLast(amount)
map[to] = map[to]!! + chars
}
.map { it.value.last() }
.joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
val input = readInput("Day05")
check(part1(testInput) == "CMZ")
println(part1(input))
check(part2(testInput) == "MCD")
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 3452e167f7afe291960d41b6fe86d79fd821a545 | 2,143 | advent-of-code-2022 | Apache License 2.0 |
src/day14/day.kt | LostMekka | 574,697,945 | false | {"Kotlin": 92218} | package day14
import day14.Tile.Empty
import day14.Tile.Sand
import day14.Tile.Wall
import util.Grid
import util.Point
import util.readInput
import util.shouldBe
import kotlin.math.sign
fun main() {
val testInput = readInput(Input::class, testInput = true).parseInput()
testInput.part1() shouldBe 24
testInput.part2() shouldBe 93
val input = readInput(Input::class).parseInput()
println("output for part1: ${input.part1()}")
println("output for part2: ${input.part2()}")
}
private class Input(
val minX: Int,
val maxX: Int,
val minY: Int,
val maxY: Int,
val lines: List<List<Point>>,
)
private fun List<String>.parseInput(): Input {
var minX = Int.MAX_VALUE
var maxX = Int.MIN_VALUE
val minY = 0
var maxY = Int.MIN_VALUE
val lines = map { line ->
line.split(" -> ")
.map { point ->
val (x, y) = point.split(",").map { it.toInt() }
if (x < minX) minX = x
if (x > maxX) maxX = x
if (y > maxY) maxY = y
Point(x, y)
}
}
maxY += 2
minX = minOf(minX, 500 - maxY)
maxX = maxOf(maxX, 500 + maxY)
return Input(
minX,
maxX,
minY,
maxY,
lines,
)
}
private enum class Tile { Empty, Wall, Sand }
private fun Input.createGrid(): Grid<Tile> {
val grid = Grid(maxX - minX + 1, maxY - minY + 1) { Empty }
for (line in lines) {
var x = -1
var y = -1
var isFirstSegment = true
for ((a, b) in line.windowed(2)) {
val dx = (b.x - a.x).sign
val dy = (b.y - a.y).sign
if (dx != 0 && dy != 0) error("found diagonal wall")
if (isFirstSegment) {
isFirstSegment = false
x = a.x
y = a.y
grid[x - minX, y - minY] = Wall
}
while (x != b.x || y != b.y) {
x += dx
y += dy
grid[x - minX, y - minY] = Wall
}
}
}
return grid
}
private fun Input.simulateSand(grid: Grid<Tile>): Int {
val startPoint = Point(500 - minX, 0)
var sandCount = 0
outer@ while (true) {
var (x, y) = startPoint
while (true) {
when {
y == maxY -> break@outer
grid[x, y + 1] == Empty -> y++
x == 0 -> break@outer
grid[x - 1, y + 1] == Empty -> {
x--; y++
}
x == grid.width - 1 -> break@outer
grid[x + 1, y + 1] == Empty -> {
x++; y++
}
else -> {
grid[x, y] = Sand
sandCount++
if (x == startPoint.x && y == startPoint.y) break@outer
break
}
}
}
}
return sandCount
}
private fun Input.part1(): Int {
val grid = createGrid()
return simulateSand(grid)
}
private fun Input.part2(): Int {
val grid = createGrid()
for (x in grid.xRange) grid[x, grid.height - 1] = Wall
return simulateSand(grid)
}
| 0 | Kotlin | 0 | 0 | 58d92387825cf6b3d6b7567a9e6578684963b578 | 3,197 | advent-of-code-2022 | Apache License 2.0 |
mpp-library/src/commonMain/kotlin/ru/tetraquark/kotlin/playground/shared/leetcode/FunWithArrays.kt | Tetraquark | 378,612,246 | false | null | package ru.tetraquark.kotlin.playground.shared.leetcode
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.runBlocking
import kotlin.math.pow
fun listWork(list: List<*>) {
val anyList = list as List<Any>
println("listWork: ${anyList.joinToString()}")
}
fun mainTest() {
//duplicateZerosTest()
val listInt = listOf(1, 2, 3)
val listString = listOf("1", "2")
val anyList: List<Any> = listInt
listWork(anyList)
listWork(listString)
val flow = flow<String> {
emit("123")
}
runBlocking {
println("1 ${flow.first()}")
println("2 ${flow.first()}")
}
var i = 0
val a = i++ + 1
val b = ++i + 1
println("a $a b $b i $i")
listOf(
"1 2 3", "4 5 6", "0 10"
).flatMap {
it.split(" ")
}
val intList = listOf(2, 3, 4)
val result = listOf(
"1"
) + intList.map { it.toString() }
println(result)
}
fun twoSum(nums: IntArray, target: Int): IntArray {
var resArr: Array<Int>? = null
var i = 0
while (i < nums.size) {
var j = i + 1
while (j < nums.size) {
if (nums[i] + nums[j] == target) {
resArr = arrayOf(i, j)
i = nums.size
break
}
j++
}
i++
}
return resArr?.toIntArray() ?: IntArray(0)
}
fun twoSum2(nums: IntArray, target: Int): IntArray {
var i = 0
val hashMap = mutableMapOf<Int, Int>()
while (i < nums.size) {
val cmp = target - nums[i]
if (hashMap.containsKey(cmp)) {
val res = IntArray(2)
res[0] = hashMap[cmp]!!
res[1] = i
return res
}
hashMap[nums[i]] = i
i++
}
return IntArray(0)
}
fun findMaxConsecutiveOnes(nums: IntArray): Int {
var consCount = 0
var maxCons = 0
nums.forEachIndexed { index, i ->
if (i == 1) {
consCount++
} else {
if (consCount > maxCons) maxCons = consCount
consCount = 0
}
}
if (consCount > maxCons) maxCons = consCount
return maxCons
}
fun findNumbers_3(nums: IntArray): IntArray {
return nums.map { it * it }.sorted().toIntArray()
for (i in nums) {
i * i
}
}
fun findNumbers_1(nums: IntArray): Int {
return nums.asSequence()
.map { it.toString() }
.filter { it.length % 2 == 0 }
.count()
}
fun findNumbers_2(nums: IntArray): Int {
var result = 0
var i = 0
while (i < nums.size) {
var num = 0
do {
nums[i] /= 10
num++
} while (nums[i] > 1 || nums[i] == 1)
if (num % 2 == 0) result++
i++
}
return nums.filter{ "$it".length % 2 == 0 }.size
return result
return nums.asSequence()
.map { it.toString() }
.filter { it.length % 2 == 0 }
.count()
}
fun sortedSquares(nums: IntArray): IntArray {
var i = 0
while (i < nums.size) {
nums[i] = nums[i] * nums[i]
i++
}
return nums.sortedArray()
//return nums.map { it * it }.sorted().toIntArray()
}
internal class ListNode(var `val`: Int) {
var next: ListNode? = null
}
internal fun listNodeToInt(node: ListNode?): Int {
if (node == null) return 0
var result = 0
var depthLvl = 0
var next: ListNode? = node
while (next != null) {
result += next.`val` * 10f.pow(depthLvl).toInt()
next = next.next
depthLvl++
}
return result
}
internal fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {
val l1Res = listNodeToInt(l1)
val l2Res = listNodeToInt(l2)
val strRes = (l1Res + l2Res).toString()
var i = strRes.length - 1
var prev: ListNode? = null
var result: ListNode? = null
while (i >= 0) {
val node = ListNode(strRes[i].toString().toInt())
if (i == strRes.length - 1) result = node
prev?.next = node
prev = node
i--
}
return result
}
fun duplicateZerosTest() {
val arr = arrayOf(0, 4, 1, 0, 0, 8, 0, 0, 3).toIntArray()
println("IN: ${arr.asList()}")
duplicateZeros(arr)
println("OUT: ${arr.asList()}")
}
/**
* in: [1,0,2,3,0,4,5,0]
* out: [1,0,0,2,3,0,0,4]
*/
fun duplicateZeros(arr: IntArray): Unit {
var i = 0
while (i < arr.size) {
if (arr[i] == 0 && i + 1 < arr.size) {
var j = i + 1
var tmp1 = 0
var tmp2 = arr[j]
while (j < arr.size) {
arr[j] = tmp1
tmp1 = tmp2
j++
if (j < arr.size) tmp2 = arr[j]
}
i++
}
i++
}
}
| 0 | Kotlin | 0 | 0 | bd86209874d438233cc5383cec2e705d5e7d9f83 | 4,755 | KotlinPlayground | Apache License 2.0 |
src/com/ajithkumar/aoc2022/Day03.kt | ajithkumar | 574,372,025 | false | {"Kotlin": 21950} | package com.ajithkumar.aoc2022
import com.ajithkumar.utils.*
import kotlin.streams.toList
fun main() {
fun charToPriorityTranslate(char: Int): Int {
if(char in 97..122)
return char-96
if(char in 65..90)
return char-64+26
return 0
}
fun findIntersection(splitStrings: List<String>): Set<Int> {
val initialAcc = splitStrings[0].chars().toList().toSet()
return splitStrings.fold(initialAcc) { acc, s -> acc.intersect(s.chars().toList().toSet()) }
}
fun part1(input: List<String>): Int {
return input.map { rucksackString -> rucksackString.chunked(rucksackString.length/2)}
.map { splitStrings -> findIntersection(splitStrings) }
.sumOf { intersection -> charToPriorityTranslate(intersection.toList()[0]) }
}
fun part2(input: List<String>): Int {
return input.chunked(3)
.map { chunkedStrings -> findIntersection(chunkedStrings) }
.sumOf { intersection -> charToPriorityTranslate(intersection.toList()[0]) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(testInput.size == 6)
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f95b8d1c3c8a67576eb76058a1df5b78af47a29c | 1,370 | advent-of-code-kotlin-template | Apache License 2.0 |
src/day11/Day11.kt | IThinkIGottaGo | 572,833,474 | false | {"Kotlin": 72162} | package day11
import readString
import java.math.BigInteger
import java.util.*
fun main() {
fun part1(input: String): Long {
val monkeyList = parseInput(input)
repeat(20) { // 20 rounds
monkeyList.forEach { monkey ->
monkey.inspect(monkeyList) // each turn
}
}
return getTwoMostActiveMonkeysResult(monkeyList)
}
fun part2(input: String): Long {
// program will run nearly infinite in this way, can not solve this part in time.
val monkeyList = parseInput(input)
repeat(10000) {
monkeyList.forEach { monkey ->
monkey.inspect(monkeyList, soWorriedCannotReliefBy3 = true)
}
}
return getTwoMostActiveMonkeysResult(monkeyList)
}
val testInput = readString("day11_test")
check(part1(testInput) == 10605L)
// check(part2(testInput) == 2713310158)
val input = readString("day11")
println(part1(input)) // 118674
// println(part2(input)) //
}
fun parseInput(input: String): List<Monkey> {
val monkeyList = mutableListOf<Monkey>()
val monkeys = input.split("\n\n")
monkeys.forEach { monkey ->
val lines = monkey.lines()
monkeyList.add(
Monkey(
lines[1].substringAfterLast(":").split(",").mapTo(LinkedList()) { it.trim().toBigInteger() },
lines[2].substringAfterLast("=").trim(),
lines.subList(3, lines.size).map(String::trim)
)
)
}
return monkeyList
}
fun getTwoMostActiveMonkeysResult(monkeyList: List<Monkey>): Long {
val (most, secondary) = monkeyList.sortedByDescending { it.inspectionCounts }.take(2)
return most.inspectionCounts * secondary.inspectionCounts
}
data class Monkey(
val holdingItems: Queue<BigInteger>,
val operation: String,
val test: List<String>,
var inspectionCounts: Long = 0
) {
private val _operation: (BigInteger) -> (BigInteger) = operationParse()
private val _test: (BigInteger) -> (Int) = testParse()
fun inspect(monkeyList: List<Monkey>, soWorriedCannotReliefBy3: Boolean = false) {
while (holdingItems.isNotEmpty()) {
++inspectionCounts
var item = holdingItems.poll()
item = if (soWorriedCannotReliefBy3) _operation(item) else _operation(item) / 3.toBigInteger()
throwTo(monkeyList[_test(item)], item)
}
}
private fun operationParse(): (BigInteger) -> (BigInteger) {
var opArg: BigInteger
val (_, arg2, arg3) = operation.split(" ")
return when (arg2) {
"+" -> {
{
opArg = getOldOrNum(it, arg3)
it + opArg
}
}
"*" -> {
{
opArg = getOldOrNum(it, arg3)
it * opArg
}
}
else -> error("unexpected operation!")
}
}
private fun testParse(): (BigInteger) -> (Int) {
val divider = test[0].substringAfterLast(" ").toBigInteger()
val trueCondition = test[1].substringAfterLast(" ").toInt()
val falseCondition = test[2].substringAfterLast(" ").toInt()
return { if (it % divider == BigInteger.ZERO) trueCondition else falseCondition }
}
private fun throwTo(other: Monkey, item: BigInteger) {
other.holdingItems.offer(item)
}
private fun getOldOrNum(old: BigInteger, arg3: String): BigInteger =
if (arg3 == "old") old else arg3.toBigInteger()
} | 0 | Kotlin | 0 | 0 | 967812138a7ee110a63e1950cae9a799166a6ba8 | 3,613 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day10/Day10.kt | TheSench | 572,930,570 | false | {"Kotlin": 128505} | package day10
import runDay
import utils.Point
fun main() {
fun part1(input: List<String>): Int {
val counter = Counter(20)
input.toInstructions()
.fold(Signals(counter::track)) { signals, processor ->
signals.processInstruction(processor)
}
return counter.toStrengths()
.filter { (cycle) ->
cycle in setOf(20, 60, 100, 140, 180, 220)
}.sumOf { it.second }
}
fun part2(input: List<String>): String {
val crt = CRT()
input.toInstructions()
.fold(Signals(crt::print)) { signals, processor ->
signals.processInstruction(processor)
}
return "$crt"
}
(object {}).runDay(
part1 = ::part1,
part1Check = 13140,
part2 = ::part2,
part2Check = """
##..##..##..##..##..##..##..##..##..##..
###...###...###...###...###...###...###.
####....####....####....####....####....
#####.....#####.....#####.....#####.....
######......######......######......####
#######.......#######.......#######.....
""".trimIndent(),
)
}
private class Signals(private val signalProcessor: (Signal, Signal) -> Unit) {
var lastSignal = Signal()
private set
fun processInstruction(processor: InstructionProcessor): Signals {
val nextSignal = processor.invoke(lastSignal)
signalProcessor(lastSignal, nextSignal)
lastSignal = nextSignal
return this
}
}
private class Counter(val checkFrequency: Int = 20) {
var signals = listOf<Signal>()
private set
fun track(lastSignal: Signal, nextSignal: Signal) {
if (nextSignal.cycle / checkFrequency > lastSignal.cycle / checkFrequency) {
signals += lastSignal
}
}
fun toStrengths() = signals.mapIndexed { i, signal ->
val cycle = (i + 1) * 20
val strength = cycle * signal.x
cycle to strength
}
}
private fun Point.move() = when {
(x < 39) -> Point(x + 1, y)
else -> Point(0, y + 1)
}
private val Point.row get() = y
private val Point.left get() = x
private class CRT {
val screen = MutableList(6) {
MutableList(40) { '.' }
}
var cursor = Point(0, 0)
fun print(lastSignal: Signal, nextSignal: Signal) {
repeat(nextSignal.cycle - lastSignal.cycle) {
lastSignal.x.let { x ->
screen[cursor.row][cursor.left] = when (cursor.left) {
in (x - 1..x + 1) -> '#'
else -> '.'
}
}
cursor = cursor.move()
}
}
override fun toString() = screen.joinToString("\n") {
it.joinToString("")
}
}
private data class Signal(val x: Int = 1, val cycle: Int = 0)
private typealias InstructionProcessor = (Signal) -> Signal
private val noop: InstructionProcessor = { (x, cycle) -> Signal(x, cycle + 1) }
private fun List<String>.toInstructions() =
map {
when (it) {
"noop" -> noop
else -> parseAdd(it)
}
}
private fun parseAdd(raw: String): InstructionProcessor =
raw.split(' ', limit = 2)
.last()
.let {
{ (x, cycle) ->
val addedX = it.toInt()
Signal(x + addedX, cycle + 2)
}
}
| 0 | Kotlin | 0 | 0 | c3e421d75bc2cd7a4f55979fdfd317f08f6be4eb | 3,417 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | ShuffleZZZ | 572,630,279 | false | {"Kotlin": 29686} | private fun compartments(input: List<String>) = input.map { it.trim().chunked(it.length / 2) }
private fun groups(input: List<String>) = input.windowed(3, 3)
private fun List<List<String>>.intersect() = flatMap { it.map(String::toSet).reduce(Set<Char>::intersect) }
private fun Char.toPriority() = if (isLowerCase()) this - 'a' + 1 else this - 'A' + 27
fun main() {
fun part1(input: List<String>) = compartments(input).intersect().sumOf { it.toPriority() }
fun part2(input: List<String>) = groups(input).intersect().sumOf { it.toPriority() }
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5a3cff1b7cfb1497a65bdfb41a2fe384ae4cf82e | 830 | advent-of-code-kotlin | Apache License 2.0 |
code-sample-kotlin/algorithms/src/main/kotlin/com/codesample/leetcode/medium/1609_even_odd_tree.kt | aquatir | 76,377,920 | false | {"Java": 674809, "Python": 143889, "Kotlin": 112192, "Haskell": 57852, "Elixir": 33284, "TeX": 20611, "Scala": 17065, "Dockerfile": 6314, "HTML": 4714, "Shell": 387, "Batchfile": 316, "Erlang": 269, "CSS": 97} | package com.codesample.leetcode.medium
fun main() {
// [5,9,1,3,5,7] -> false
val root1 = TreeNode(5);
val childLeft1 = TreeNode(9);
val childRight1 = TreeNode(1);
root1.left = childLeft1;
root1.right = childRight1;
childLeft1.left = TreeNode(3)
childLeft1.right = TreeNode(5)
childRight1.left = TreeNode(7)
println(isEvenOddTree(root1))
// [1,10,4,3,null,7,9,12,8,6,null,null,2] -> true
val root2 = TreeNode(5)
root2.left = TreeNode(10)
root2.left!!.left = TreeNode(3)
root2.left!!.left!!.left = TreeNode(12)
root2.left!!.left!!.right = TreeNode(8)
root2.right = TreeNode(4)
root2.right!!.left = TreeNode(7)
root2.right!!.right = TreeNode(9)
root2.right!!.left!!.left = TreeNode(6)
root2.right!!.right!!.right = TreeNode(2)
println(isEvenOddTree(root2))
// [2,12,8,5,9,null,null,18,16]
val root3 = TreeNode(2)
root3.left = TreeNode(12)
root3.right = TreeNode(8)
root3.left!!.left = TreeNode(5)
root3.left!!.right = TreeNode(9)
root3.left!!.left!!.left = TreeNode(8)
root3.left!!.left!!.right = TreeNode(16)
println(isEvenOddTree(root3))
// [11,18,14,3,7,null,null,null,null,18,null,6]
}
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
/**
* 1609 Even Odd Tree https://leetcode.com/problems/even-odd-tree
*
* A binary tree is named Even-Odd if it meets the following conditions:
* The root of the binary tree is at level index 0, its children are at level index 1, their children are at level index 2, etc.
* For every even-indexed level, all nodes at the level have odd integer values in strictly increasing order (from left to right).
* For every odd-indexed level, all nodes at the level have even integer values in strictly decreasing order (from left to right).
* Given the root of a binary tree, return true if the binary tree is Even-Odd, otherwise return false.
*/
// Ideally, a normal BFS should be used here instead of building a list of children on each iteration.
fun isEvenOddTree(root: TreeNode?): Boolean {
/** odd = 1, 3, 5... */
fun isOdd(value: Int) = value % 2 == 1
/** even = 2, 4, 6...*/
fun isEven(value: Int) = !isOdd(value)
fun createChildrenList(checkList: List<TreeNode>): List<TreeNode> {
val mutableChildList = mutableListOf<TreeNode>()
for (element in checkList) {
if (element.left != null) {
mutableChildList.add(element.left!!)
}
if (element.right != null) {
mutableChildList.add(element.right!!)
}
}
return mutableChildList
}
// descending and each element is even
fun elementsCorrectOnOddLevel(roots: List<TreeNode>): Boolean {
if (roots.size == 1) {
return isEven(roots[0].`val`)
}
for (i in 0..roots.size - 2) {
if (roots[i].`val` > roots[i + 1].`val` && isEven(roots[i].`val`) && isEven(roots[i + 1].`val`)) {
//
} else {
return false
}
}
return true
}
// ascending and each element is odd
fun elementsCorrectOnEvenLevel(roots: List<TreeNode>): Boolean {
if (roots.size == 1) {
return isOdd(roots[0].`val`)
}
for (i in 0..roots.size - 2) {
if (roots[i].`val` < roots[i + 1].`val` && isOdd(roots[i].`val`) && isOdd(roots[i + 1].`val`)) {
//
} else {
return false
}
}
return true
}
fun isValidChecklist(roots: List<TreeNode>, currentLevel: Int): Boolean {
val isOddLevel = isOdd(currentLevel)
if (isOddLevel) {
return elementsCorrectOnOddLevel(roots)
} else {
return elementsCorrectOnEvenLevel(roots)
}
}
if (root == null || isEven(root.`val`)) {
return false;
}
var currentLevel = 1;
var checkList: List<TreeNode> = listOf(root);
while (true) {
checkList = createChildrenList(checkList)
if (checkList.isEmpty()) {
return true
}
if (!isValidChecklist(checkList, currentLevel)) {
return false
}
currentLevel++
}
}
| 1 | Java | 3 | 6 | eac3328ecd1c434b1e9aae2cdbec05a44fad4430 | 4,333 | code-samples | MIT License |
src/main/kotlin/adventofcode/year2021/Day08SevenSegmentSearch.kt | pfolta | 573,956,675 | false | {"Kotlin": 199554, "Dockerfile": 227} | package adventofcode.year2021
import adventofcode.Puzzle
import adventofcode.PuzzleInput
class Day08SevenSegmentSearch(customInput: PuzzleInput? = null) : Puzzle(customInput) {
private val signalPatterns by lazy { input.lines().map { it.split("|").first().trim().split(" ") } }
private val outputValues by lazy { input.lines().map { it.split("|").last().trim().split(" ") } }
private val digitMap = mapOf(
setOf('a', 'b', 'c', 'e', 'f', 'g') to 0,
setOf('c', 'f') to 1,
setOf('a', 'c', 'd', 'e', 'g') to 2,
setOf('a', 'c', 'd', 'f', 'g') to 3,
setOf('b', 'c', 'd', 'f') to 4,
setOf('a', 'b', 'd', 'f', 'g') to 5,
setOf('a', 'b', 'd', 'e', 'f', 'g') to 6,
setOf('a', 'c', 'f') to 7,
setOf('a', 'b', 'c', 'd', 'e', 'f', 'g') to 8,
setOf('a', 'b', 'c', 'd', 'f', 'g') to 9
)
private fun List<String>.getPatternsForDigit(digit: Int) = when (digit) {
0 -> filter { it.length == 6 }
1 -> filter { it.length == 2 }
2 -> filter { it.length == 5 }
3 -> filter { it.length == 5 }
4 -> filter { it.length == 4 }
5 -> filter { it.length == 5 }
6 -> filter { it.length == 6 }
7 -> filter { it.length == 3 }
8 -> filter { it.length == 7 }
9 -> filter { it.length == 6 }
else -> throw IllegalArgumentException("$digit is not a unique digit")
}.map(String::toSet)
override fun partOne() = outputValues.map { entry -> entry.filter { it.length in listOf(2, 3, 4, 7) } }.sumOf(List<String>::size)
override fun partTwo() = outputValues
.mapIndexed { index, outputValue ->
val signalPattern = signalPatterns[index]
val a = signalPattern
.getPatternsForDigit(7)
.first()
.minus(signalPattern.getPatternsForDigit(1).first())
.first()
val g = signalPattern
.getPatternsForDigit(9)
.map { it.toSet().minus(signalPattern.getPatternsForDigit(4).first()).minus(signalPattern.getPatternsForDigit(7).first()) }
.first { it.size == 1 }
.first()
val e = signalPattern
.getPatternsForDigit(8)
.first()
.minus(setOf(a, g))
.minus(signalPattern.getPatternsForDigit(4).first())
.first()
val b = signalPattern
.getPatternsForDigit(6)
.map { it.toSet().minus(setOf(a, e, g)).minus(signalPattern.getPatternsForDigit(1).first()) }
.first { it.size == 1 }
.first()
val d = signalPattern
.getPatternsForDigit(8)
.first()
.minus(setOf(a, b, e, g))
.minus(signalPattern.getPatternsForDigit(1).first())
.first()
val f = signalPattern
.getPatternsForDigit(0)
.map { it.toSet().minus(setOf(a, b, d, e, g)) }
.first { it.size == 1 }
.first()
val c = signalPattern
.getPatternsForDigit(8)
.first()
.minus(setOf(a, b, d, e, f, g))
.first()
val wireSegmentMap = mapOf(
a to 'a',
b to 'b',
c to 'c',
d to 'd',
e to 'e',
f to 'f',
g to 'g'
)
outputValue
.map { digit -> digit.map { wireSegmentMap[it] }.toSet() }
.map { digit -> digitMap[digit] }
.joinToString("")
}
.sumOf(String::toInt)
}
| 0 | Kotlin | 0 | 0 | 72492c6a7d0c939b2388e13ffdcbf12b5a1cb838 | 3,749 | AdventOfCode | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/FreedomTrail.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 dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT
import kotlin.math.min
/**
* 514. Freedom Trail
* @see <a href="https://leetcode.com/problems/freedom-trail/">Source</a>
*/
fun interface FreedomTrail {
fun findRotateSteps(ring: String, key: String): Int
}
class FreedomTrailDP : FreedomTrail {
override fun findRotateSteps(ring: String, key: String): Int {
val n: Int = ring.length
val m: Int = key.length
val dp = Array(m + 1) { IntArray(n) }
val clock = preproc(ring, 1)
val anti = preproc(ring, -1)
for (i in m - 1 downTo 0) {
val idx: Int = key[i] - 'a'
for (j in 0 until n) { // fill dp[i][j]
val p = clock[j][idx]
val q = anti[j][idx]
dp[i][j] = min(dp[i + 1][p] + (j + n - p) % n, dp[i + 1][q] + (q + n - j) % n)
}
}
return dp[0][0] + m
}
private fun preproc(r: String, inc: Int): Array<IntArray> {
val n = r.length
val ans = Array(n) { IntArray(ALPHABET_LETTERS_COUNT) }
val map = IntArray(ALPHABET_LETTERS_COUNT)
var i = 0
var j = 0
while (j < n * 2 - 1) {
map[r[i] - 'a'] = i
System.arraycopy(map, 0, ans[i], 0, ALPHABET_LETTERS_COUNT)
i = (i + inc + n) % n
++j
}
return ans
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,021 | kotlab | Apache License 2.0 |
app/src/y2021/day07/Day07TheTreacheryOfWhales.kt | henningBunk | 432,858,990 | false | {"Kotlin": 124495} | package y2021.day07
import common.Answers
import common.AocSolution
import common.annotations.AoCPuzzle
import kotlin.math.abs
fun main(args: Array<String>) {
Day07TheTreacheryOfWhales().solveThem()
}
@AoCPuzzle(2021, 7)
class Day07TheTreacheryOfWhales : AocSolution {
override val answers = Answers(samplePart1 = 37, samplePart2 = 168, part1 = 352254, part2 = 99053143)
override fun solvePart1(input: List<String>): Any = calculateTotalFuelCosts(
horizontalPositions = input.first().split(",").map { it.toInt() },
fuelCostCalculation = { crabPosition, target -> abs(target - crabPosition) }
)
override fun solvePart2(input: List<String>): Any = calculateTotalFuelCosts(
horizontalPositions = input.first().split(",").map { it.toInt() },
fuelCostCalculation = { crabPosition, target ->
(0..abs(target - crabPosition)).fold(0) { acc, step -> acc + step }
}
)
private fun calculateTotalFuelCosts(horizontalPositions: List<Int>, fuelCostCalculation: (Int, Int) -> Int): Int =
(0..horizontalPositions.maxOrNull()!!)
.minOfOrNull { candidate ->
horizontalPositions.sumOf { crab -> fuelCostCalculation(crab, candidate) }
} ?: -1
}
/**
* Runtime under 100 ms
*/
@AoCPuzzle(2021, 7)
class Day07UsingTriangleNumbers : AocSolution {
override val answers = Answers(samplePart1 = 37, samplePart2 = 168, part1 = 352254, part2 = 99053143)
override fun solvePart1(input: List<String>): Any = {
TODO("Only part two is implemented")
}
override fun solvePart2(input: List<String>): Any = calculateTotalFuelCosts(
horizontalPositions = input.first().split(",").map { it.toInt() },
fuelCostCalculation = { crabPosition, target -> fuelCost(abs(target - crabPosition)) }
)
private fun fuelCost(n: Int): Int = n * (n + 1) / 2
private fun calculateTotalFuelCosts(horizontalPositions: List<Int>, fuelCostCalculation: (Int, Int) -> Int): Int =
(0..horizontalPositions.maxOrNull()!!)
.minOfOrNull { candidate ->
horizontalPositions.sumOf { crab -> fuelCostCalculation(crab, candidate) }
} ?: -1
}
/**
* Even more effective solution!
* Runtime under 20 ms.
* Wow the higher order function takes a hefty toll
*/
@AoCPuzzle(2021, 7)
class Day07UsingTriangleNumbersButNoHigherOrderFunction : AocSolution {
override val answers = Answers(samplePart1 = 37, samplePart2 = 168, part1 = 352254, part2 = 99053143)
override fun solvePart1(input: List<String>): Any = {
TODO("Only part two is implemented")
}
override fun solvePart2(input: List<String>): Any {
val horizontalPositions = input.first().split(",").map { it.toInt() }
return (0..horizontalPositions.maxOrNull()!!)
.minOfOrNull { candidate ->
horizontalPositions.sumOf { crab -> fuelCost(abs(crab - candidate)) }
} ?: -1
}
private fun fuelCost(n: Int): Int = n * (n + 1) / 2
}
/**
* Fastest yet, instead of finding the best row by brute forcing them all, just take the average and take the floor of it.
* Runs in 500 us
*/
@AoCPuzzle(2021, 7)
class Day07UsingTriangleNumbersAndGettingTheCorrectRowByAveraging : AocSolution {
override val answers = Answers(samplePart1 = 37, samplePart2 = 168, part1 = 352254, part2 = 99053143)
override fun solvePart1(input: List<String>): Any = {
TODO("Only part two is implemented")
}
override fun solvePart2(input: List<String>): Any {
val horizontalPositions = input.first().split(",").map { it.toInt() }
val row = horizontalPositions.average().toInt() // floor the average
return horizontalPositions.sumOf { crab -> fuelCost(abs(crab - row)) }
}
private fun fuelCost(n: Int): Int = n * (n + 1) / 2
}
| 0 | Kotlin | 0 | 0 | 94235f97c436f434561a09272642911c5588560d | 3,861 | advent-of-code-2021 | Apache License 2.0 |
src/pl/shockah/aoc/y2021/Day5.kt | Shockah | 159,919,224 | false | null | package pl.shockah.aoc.y2021
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import pl.shockah.aoc.AdventTask
import pl.shockah.aoc.UnorderedPair
import kotlin.math.max
import kotlin.math.min
class Day5: AdventTask<List<UnorderedPair<Day5.Point>>, Int, Int>(2021, 5) {
data class Point(
val x: Int,
val y: Int
)
override fun parseInput(rawInput: String): List<UnorderedPair<Point>> {
return rawInput.trim().lines().map {
val split = it.split("->").map { it.trim().split(',').map { it.toInt() } }
return@map UnorderedPair(Point(split[0][0], split[0][1]), Point(split[1][0], split[1][1]))
}
}
private fun printGrid(grid: Map<Point, Int>, lines: List<UnorderedPair<Point>>) {
val minX = lines.minOf { min(it.first.x, it.second.x) }
val minY = lines.minOf { min(it.first.y, it.second.y) }
val maxX = lines.maxOf { max(it.first.x, it.second.x) }
val maxY = lines.maxOf { max(it.first.y, it.second.y) }
println(
(minY .. maxY).joinToString("\n") { y ->
(minX .. maxX).joinToString("") { x ->
grid[Point(x, y)]?.let { "$it" } ?: "."
}
}
)
}
private fun task(input: List<UnorderedPair<Point>>, includeDiagonals: Boolean): Int {
val grid = mutableMapOf<Point, Int>()
for (line in input) {
val minX = min(line.first.x, line.second.x)
val minY = min(line.first.y, line.second.y)
val maxX = max(line.first.x, line.second.x)
val maxY = max(line.first.y, line.second.y)
if (minX == maxX) {
(minY .. maxY).forEach {
val point = Point(line.first.x, it)
grid[point] = (grid[point] ?: 0) + 1
}
} else if (minY == maxY) {
(minX .. maxX).forEach {
val point = Point(it, line.first.y)
grid[point] = (grid[point] ?: 0) + 1
}
} else if (includeDiagonals) {
(0 .. (maxX - minX)).forEach {
val point = Point(
line.first.x + (if (line.second.x > line.first.x) it else -it),
line.first.y + (if (line.second.y > line.first.y) it else -it)
)
grid[point] = (grid[point] ?: 0) + 1
}
}
}
return grid.values.count { it >= 2 }
}
override fun part1(input: List<UnorderedPair<Point>>): Int {
return task(input, includeDiagonals = false)
}
override fun part2(input: List<UnorderedPair<Point>>): Int {
return task(input, includeDiagonals = true)
}
class Tests {
private val task = Day5()
private val rawInput = """
0,9 -> 5,9
8,0 -> 0,8
9,4 -> 3,4
2,2 -> 2,1
7,0 -> 7,4
6,4 -> 2,0
0,9 -> 2,9
3,4 -> 1,4
0,0 -> 8,8
5,5 -> 8,2
""".trimIndent()
@Test
fun part1() {
val input = task.parseInput(rawInput)
Assertions.assertEquals(5, task.part1(input))
}
@Test
fun part2() {
val input = task.parseInput(rawInput)
Assertions.assertEquals(12, task.part2(input))
}
}
} | 0 | Kotlin | 0 | 0 | 9abb1e3db1cad329cfe1e3d6deae2d6b7456c785 | 2,785 | Advent-of-Code | Apache License 2.0 |
app/src/main/java/org/sil/storyproducer/model/WordLinkSearchTree.kt | sillsdev | 93,890,166 | false | null | package org.sil.storyproducer.model
/**
* The purpose of this class is to make searching for multi-word wordlinks possible and fast within a larger paragraph of text.
* The point of this class is to quickly differentiate between similar wordlinks (ones which begin with the same words).
* Example: feast, Feast of Pentecost, Feast of Shelters
*
* In this class a word refers to a consecutive string of letters, or any individual non-letter symbol.
*
* When building the WordLinkSearchTree (WordLink Search Tree) all starting words of wordlinks that are the same would get combined into a single node.
* The children of that node would be all the possible next words that could come after the starting word to make up a wordlinks.
* When searching we would traverse this tree word by word as long as we get words that match.
* This will get us the longest match - the longest possible wordlinks from a given list of words.
*/
class WordLinkSearchTree {
private val root: WordNode = WordNode()
/**
* This function takes in a single term and builds up the tree based on the words in that term.
* The tree would be as deep as the term with the most words.
* If a given word already exists in current node's map, navigate down that node, otherwise create a new node.
*
* @param word the word to insert into the tree
*/
fun insertTerm(word: String) {
val words = splitBeforeAndAfterAnyNonLetters(word)
var currentNode = root
for (w in words) {
val nextNode = currentNode.childWords[w.toLowerCase()] ?: WordNode()
currentNode.childWords[w.toLowerCase()] = nextNode
currentNode = nextNode
}
currentNode.isWordLink = true
}
/**
* The purpose of this function is to split a paragraph of text into a list of wordlinks and non-wordlinks strings between those wordlinks.
*
* @param text the text containing wordlinks
* @return A list of Strings
*/
fun splitOnWordLinks(text: String): List<String> {
val words = splitBeforeAndAfterAnyNonLetters(text)
val resultPhrases: MutableList<String> = mutableListOf()
var nonWordLinkPhrase = ""
while (words.size > 0) {
val wordLinkPhrase = getIfWordLink(words, root)
// If the returned wordlink is empty, no wordlink was found.
// All parsed words are reinserted onto the list of terms to parse.
// The first word is removed as this word is guaranteed to not be part of a wordlink.
// That first word is appended to the string of words since the last wordlink was found.
if(wordLinkPhrase == ""){
nonWordLinkPhrase += words.removeAt(0)
}
else{
resultPhrases.add(nonWordLinkPhrase)
resultPhrases.add(wordLinkPhrase)
nonWordLinkPhrase = ""
}
}
resultPhrases.add(nonWordLinkPhrase)
resultPhrases.removeAll{ it == "" }
return resultPhrases
}
/**
* The purpose of this function is to return the longest possible term made up of the next consecutive words left to parse.
* It returns an empty string if no wordlink can be found
* and any consumed words are reinserted into the main list of words that have yet to be parsed.
*
* This function is recursive. It will navigate down the tree as long as
* the next word to be parsed matches a word in the current node's map.
* When this occurs, the function will propagate back up until it finds a node that is the end of a wordlink
* and will then begin appending words to its return value.
*
* @param words
* @param currentNode
* @return A string
*/
private fun getIfWordLink(words: MutableList<String>, currentNode: WordNode): String{
if(words.isNotEmpty()){
val word = words.removeAt(0)
if(currentNode.childWords.containsKey(word.toLowerCase())){
val nextNode = currentNode.childWords[word.toLowerCase()]!!
val wordLink = getIfWordLink(words, nextNode)
if(nextNode.isWordLink || wordLink != ""){
return word + wordLink
}
}
words.add(0, word)
}
return ""
}
/**
* This function splits a given string so that all consecutive characters that are letters are split into their own strings.
* Every other individual character (",", ".", " ", etc.) are split into their own strings.
* This makes it possible to separate symbols from words.
* Example: Jesus's Spirit -> "Jesus", "'", "s", " ", "Spirit"
*
* @param text
* @return A list of strings
*/
private fun splitBeforeAndAfterAnyNonLetters(text: String): MutableList<String>{
// This regex uses lookahead and lookbehind characters to check if any character has a non-letter before or after it
val words = text.split(Regex("(?![a-zA-Z])|(?<![a-zA-Z])")).toMutableList()
words.removeAll { it == "" }
return words
}
private class WordNode {
var isWordLink: Boolean = false
/*
* The key in the map and it's corresponding WordNode together represent a word.
* The word string isn't stored in the WordNode itself as it isn't needed in the algorithm.
* A map is used because it can be quickly searched by a key which would be the next words.
* A word could have any number of next words because multiple wordlinks could start with the same word.
*/
var childWords: MutableMap<String, WordNode> = mutableMapOf()
}
} | 92 | Kotlin | 8 | 3 | 0220d9acf4aa63b82e6f29655328354265e6cab5 | 5,734 | StoryProducer | MIT License |
src/Day24.kt | AlaricLightin | 572,897,551 | false | {"Kotlin": 87366} | fun main() {
fun part1(input: List<String>): Int {
val simulation = ValleySimulation(input)
return simulation.simulate(simulation.mapStartPoint, simulation.mapEndPoint)
}
fun part2(input: List<String>): Int {
val simulation = ValleySimulation(input)
return simulation.simulate(simulation.mapStartPoint, simulation.mapEndPoint) +
simulation.simulate(simulation.mapEndPoint, simulation.mapStartPoint) +
simulation.simulate(simulation.mapStartPoint, simulation.mapEndPoint)
}
val testInput = readInput("Day24_test")
check(part1(testInput) == 18)
check(part2(testInput) == 54)
val input = readInput("Day24")
println(part1(input))
println(part2(input))
}
private class ValleySimulation(
input: List<String>
) {
private val valleyHeight = input.size - 2
private val valleyWidth = input[0].length - 2
val mapStartPoint: Coords = getStartPoint(input)
val mapEndPoint: Coords = getEndPoint(input)
private var pathStartPoint = mapStartPoint
private var pathEndPoint = mapEndPoint
private val blizzards: Array<Blizzard> = getBlizzards(input)
private val blizzardPositions: Array<Coords> = Array(blizzards.size) {
blizzards[it].start
}
fun simulate(pathStartPoint: Coords, pathEndPoint: Coords): Int {
this.pathStartPoint = pathStartPoint
this.pathEndPoint = pathEndPoint
var step = 0
var positionSet: Set<Coords> = setOf(pathStartPoint)
do {
step++
updateBlizzardPositions()
positionSet = getNextPositionSet(positionSet)
println("Step = $step VariantsCount = ${positionSet.size}")
} while (!positionSet.contains(pathEndPoint))
return step
}
private fun updateBlizzardPositions() {
blizzards.forEachIndexed { index, blizzard ->
var x = blizzardPositions[index].x + blizzard.move.x
var y = blizzardPositions[index].y + blizzard.move.y
if (x < 1)
x = valleyWidth
else if (x > valleyWidth)
x = 1
if (y < 1)
y = valleyHeight
else if (y > valleyHeight)
y = 1
blizzardPositions[index] = Coords(x, y)
}
}
private fun getNextPositionSet(positionSet: Set<Coords>): Set<Coords> {
val potentialPositions = getPotentialPositions(positionSet)
val blizzardPositionSet = blizzardPositions.toSet()
return potentialPositions.minus(blizzardPositionSet)
}
private fun getPotentialPositions(positionSet: Set<Coords>): Set<Coords> {
val resultSet = mutableSetOf<Coords>()
positionSet.forEach { coords ->
MOVE_LIST.forEach {
val x = coords.x + it.x
val y = coords.y + it.y
if (x == pathEndPoint.x && y == pathEndPoint.y) {
resultSet.clear()
resultSet.add(pathEndPoint)
return resultSet
}
if ((x in 1..valleyWidth && y in 1..valleyHeight) ||
(y == pathStartPoint.y && x == pathStartPoint.x))
resultSet.add(Coords(x, y))
}
}
return resultSet
}
private fun getBlizzards(input: List<String>): Array<Blizzard> {
val list = mutableListOf<Blizzard>()
input.forEachIndexed { rowIndex, s ->
s.forEachIndexed { columnIndex, c ->
val move: Move? = when (c) {
'^' -> Move(0, -1)
'>' -> Move(1, 0)
'<' -> Move(-1, 0)
'v' -> Move(0, 1)
else -> null
}
if (move != null)
list.add(Blizzard(Coords(columnIndex, rowIndex), move))
}
}
return list.toTypedArray()
}
private fun getEndPoint(input: List<String>): Coords {
input.last().forEachIndexed { index, c ->
if (c == '.')
return Coords(index, valleyHeight + 1)
}
throw IllegalArgumentException()
}
private fun getStartPoint(input: List<String>): Coords {
input[0].forEachIndexed { index, c ->
if (c == '.')
return Coords(index, 0)
}
throw IllegalArgumentException()
}
}
private data class Blizzard(val start: Coords, val move: Move)
private val MOVE_LIST = arrayOf(
Move(0, -1),
Move(1, 0),
Move(0, 1),
Move(-1, 0),
Move(0, 0)
) | 0 | Kotlin | 0 | 0 | ee991f6932b038ce5e96739855df7807c6e06258 | 4,631 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/aoc2023/Day09.kt | Ceridan | 725,711,266 | false | {"Kotlin": 110767, "Shell": 1955} | package aoc2023
class Day09 {
fun part1(input: List<String>): Int = predictNextElement(input, isBackward = false)
fun part2(input: List<String>): Int = predictNextElement(input, isBackward = true)
private fun predictNextElement(input: List<String>, isBackward: Boolean = false): Int {
val histories = input.map { line -> line.split(' ').map { it.toInt() } }
var valuesSum = 0
for (history in histories) {
val sequences = mutableListOf(history)
var prevSequence = history
while (!prevSequence.all { it == 0 }) {
val nextSequence = mutableListOf<Int>()
for (i in 1..<prevSequence.size) {
nextSequence.add(prevSequence[i] - prevSequence[i - 1])
}
sequences.add(nextSequence)
prevSequence = nextSequence
}
var nextElement = 0
for (i in sequences.size - 2 downTo 0) {
nextElement = if (isBackward) sequences[i].first() - nextElement else sequences[i].last() + nextElement
}
valuesSum += nextElement
}
return valuesSum
}
}
fun main() {
val day09 = Day09()
val input = readInputAsStringList("day09.txt")
println("09, part 1: ${day09.part1(input)}")
println("09, part 2: ${day09.part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 18b97d650f4a90219bd6a81a8cf4d445d56ea9e8 | 1,379 | advent-of-code-2023 | MIT License |
advent-of-code2015/src/main/kotlin/day5/Advent5.kt | REDNBLACK | 128,669,137 | false | null | package day5
import chunk
import parseInput
import splitToLines
/**
--- Day 5: Doesn't He Have Intern-Elves For This? ---
Santa needs help figuring out which strings in his text file are naughty or nice.
A nice string is one with all of the following properties:
It contains at least three vowels (aeiou only), like aei, xazegov, or aeiouaeiouaeiou.
It contains at least one letter that appears twice in a row, like xx, abcdde (dd), or aabbccdd (aa, bb, cc, or dd).
It does not contain the strings ab, cd, pq, or xy, even if they are part of one of the other requirements.
For example:
ugknbfddgicrmopn is nice because it has at least three vowels (u...i...o...), a double letter (...dd...), and none of the disallowed substrings.
aaa is nice because it has at least three vowels and a double letter, even though the letters used by different rules overlap.
jchzalrnumimnmhp is naughty because it has no double letter.
haegwjzuvuyypxyu is naughty because it contains the string xy.
dvszwmarrgswjxmb is naughty because it contains only one vowel.
How many strings are nice?
--- Part Two ---
Realizing the error of his ways, Santa has switched to a better model of determining whether a string is naughty or nice. None of the old rules apply, as they are all clearly ridiculous.
Now, a nice string is one with all of the following properties:
It contains a pair of any two letters that appears at least twice in the string without overlapping, like xyxy (xy) or aabcdefgaa (aa), but not like aaa (aa, but it overlaps).
It contains at least one letter which repeats with exactly one letter between them, like xyx, abcdefeghi (efe), or even aaa.
For example:
qjhvhtzxzqqjkmpb is nice because is has a pair that appears twice (qj) and a letter that repeats with exactly one letter between them (zxz).
xxyxx is nice because it has a pair that appears twice and a letter that repeats with one between, even though the letters used by each rule overlap.
uurcxstgmygtbstg is naughty because it has a pair (tg) but no repeat with a single letter between them.
ieodomkazucvgmuy is naughty because it has a repeating letter with one between (odo), but no pair that appears twice.
How many strings are nice under these new rules?
*/
fun main(args: Array<String>) {
println("ugknbfddgicrmopn".isNice())
println(!"jchzalrnumimnmh".isNice())
println(!"aegwjzuvuyypxyu".isNice())
println(!"dvszwmarrgswjxmb".isNice())
println("qjhvhtzxzqqjkmpb".isNiceSecond())
println("xxyxx".isNiceSecond())
println(!"uurcxstgmygtbstg".isNiceSecond())
println(!"ieodomkazucvgmuy".isNiceSecond())
val input = parseInput("day5-input.txt")
println(countNice(input))
}
fun countNice(input: String) = input.splitToLines()
.let { mapOf("first" to it.count(String::isNice), "second" to it.count(String::isNiceSecond)) }
private fun String.isNice(): Boolean {
fun hasAtLeastThreeVowels() = filter { it in "aeiou" }.count() >= 3
fun hasRepeatingLetter() = chunk(2).filter { it[0] == it[1] }.count() > 0
fun notContainsSubstring() = sequenceOf("ab", "cd", "pq", "xy").find { it in this } == null
return hasAtLeastThreeVowels() && hasRepeatingLetter() && notContainsSubstring()
}
private fun String.isNiceSecond(): Boolean {
fun hasRepeatingPair() = chunk(2).groupBy { it }.count { it.value.size >= 2 } > 0
&& chunk(3).count { it[0] == it[1] && it[0] == it[2] } == 0
fun hasLetterBetweenEqual() = chunk(3).count { it[0] == it[2] && it[1] != it[0] } > 0
return hasRepeatingPair() && hasLetterBetweenEqual()
}
| 0 | Kotlin | 0 | 0 | e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7 | 3,574 | courses | MIT License |
src/Day20.kt | MisterTeatime | 560,956,854 | false | {"Kotlin": 37980} | import java.math.BigInteger
fun main() {
fun part1(input: List<String>): Int {
val encrypted = input.map { it.toInt() }.mapIndexed { index, i -> index to i }
val decrypted = encrypted.toMutableList()
encrypted.forEach { (key, steps) ->
val index = decrypted.indexOfFirst { it.first == key }
val size = decrypted.size
val newIndex = (index + steps).mod(size - 1)
decrypted.moveAt(index, newIndex)
}
val index0 = decrypted.indexOfFirst { it.second == 0}
val pos1 = decrypted[(1000 + index0).mod(decrypted.size)].second
val pos2 = decrypted[(2000 + index0).mod(decrypted.size)].second
val pos3 = decrypted[(3000 + index0).mod(decrypted.size)].second
return pos1 + pos2 + pos3
}
fun part2(input: List<String>): Long {
val decryptKey = 811589153
val encrypted = input.map { it.toLong() * decryptKey }.mapIndexed { index, i -> index to i }
val decrypted = encrypted.toMutableList()
repeat(10)
{
encrypted.forEach { (key, steps) ->
val index = decrypted.indexOfFirst { it.first == key }
val size = decrypted.size
val newIndex = (index + steps).mod(size - 1)
decrypted.moveAt(index, newIndex)
}
}
val index0 = decrypted.indexOfFirst { it.second == 0L}
val pos1 = decrypted[(1000 + index0).mod(decrypted.size)].second
val pos2 = decrypted[(2000 + index0).mod(decrypted.size)].second
val pos3 = decrypted[(3000 + index0).mod(decrypted.size)].second
return pos1 + pos2 + pos3
}
println((-5).mod(3))
println((-5) % 3)
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day20_test")
check(part1(testInput) == 3)
check(part2(testInput) == 1623178306L)
val input = readInput("Day20")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8ba0c36992921e1623d9b2ed3585c8eb8d88718e | 2,023 | AoC2022 | Apache License 2.0 |
2021/src/test/kotlin/Day04.kt | jp7677 | 318,523,414 | false | {"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338} | import kotlin.test.Test
import kotlin.test.assertEquals
class Day04 {
data class Board constructor(val rows: List<List<Int>>, val cols: List<List<Int>>) {
constructor(rows: List<List<Int>>) :
this(
rows,
List(rows.first().size) { index -> rows.map { it[index] } }
)
val all get() = rows.flatten()
}
@Test
fun `run part 01`() {
val (boards, numbers) = getGame()
val winningBoard = playGame(boards, numbers).first()
val score = calcScore(winningBoard, numbers)
assertEquals(55770, score)
}
@Test
fun `run part 02`() {
val (boards, numbers) = getGame()
val winningBoard = playGame(boards, numbers).last()
val score = calcScore(winningBoard, numbers)
assertEquals(2980, score)
}
private fun getGame(): Pair<List<Board>, List<Int>> {
val bingoSubSystem = Util.getInputAsListOfString("day04-input.txt")
val numbers = bingoSubSystem.first()
.split(",")
.map { Integer.parseInt(it) }
val size = bingoSubSystem[2].toRow().size
val boards = bingoSubSystem
.drop(1)
.filter { it.isNotBlank() }
.chunked(size)
.map { Board(it.map { s -> s.toRow() }) }
return boards to numbers
}
private fun playGame(boards: List<Board>, numbers: List<Int>) = numbers.indices
.flatMap { draw ->
numbers
.take(draw)
.let { drawnNumbers ->
boards
.filter {
it.rows.any { r -> drawnNumbers.containsAll(r) } ||
it.cols.any { c -> drawnNumbers.containsAll(c) }
}
.map { it to drawnNumbers.last() }
}
}
.distinctBy { it.first }
private fun calcScore(winningBoard: Pair<Board, Int>, numbers: List<Int>) = winningBoard.first
.all
.filterNot { numbers.takeUntil(winningBoard.second).contains(it) }
.sum() * winningBoard.second
private fun List<Int>.takeUntil(last: Int): List<Int> = this
.takeWhile { it != last } + last
private fun String.toRow() = this
.split("\\s".toRegex())
.filter { it.isNotBlank() }
.map { Integer.parseInt(it) }
}
| 0 | Kotlin | 1 | 2 | 8bc5e92ce961440e011688319e07ca9a4a86d9c9 | 2,412 | adventofcode | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxRequests.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.max
/**
* 1601. Maximum Number of Achievable Transfer Requests
* @see <a href="https://leetcode.com/problems/maximum-number-of-achievable-transfer-requests/">Source</a>
*/
fun interface MaxRequests {
fun maximumRequests(n: Int, requests: Array<IntArray>): Int
}
/**
* Approach 1: Backtracking
*/
class MaxRequestsBacktracking : MaxRequests {
private var answer = 0
override fun maximumRequests(n: Int, requests: Array<IntArray>): Int {
val inDegree = IntArray(n)
maxRequest(requests, inDegree, n, 0, 0)
return answer
}
private fun maxRequest(requests: Array<IntArray>, inDegree: IntArray, n: Int, index: Int, count: Int) {
if (index == requests.size) {
// Check if all buildings have an in-degree of 0.
for (i in 0 until n) {
if (inDegree[i] != 0) {
return
}
}
answer = max(answer, count)
return
}
// Consider this request, increment and decrement for the buildings involved.
inDegree[requests[index][0]]--
inDegree[requests[index][1]]++
// Move on to the next request and also increment the count of requests.
maxRequest(requests, inDegree, n, index + 1, count + 1)
// Backtrack to the previous values to move back to the original state before the second recursion.
inDegree[requests[index][0]]++
inDegree[requests[index][1]]--
// Ignore this request and move on to the next request without incrementing the count.
maxRequest(requests, inDegree, n, index + 1, count)
}
}
/**
* Approach 2: Bitmasking
*/
class MaxRequestsBitmasking : MaxRequests {
override fun maximumRequests(n: Int, requests: Array<IntArray>): Int {
var answer = 0
for (mask in 0 until (1 shl requests.size)) {
val inDegree = IntArray(n)
var pos: Int = requests.size - 1
// Number of set bits representing the requests we will consider.
val bitCount = Integer.bitCount(mask)
// If the request count we're going to consider is less than the maximum request
// We have considered without violating the constraints; then we can return it cannot be the answer.
if (bitCount <= answer) {
continue
}
// For all the 1's in the number, update the array in degree for the building it involves.
var curr = mask
while (curr > 0) {
if (curr and 1 == 1) {
inDegree[requests[pos][0]]--
inDegree[requests[pos][1]]++
}
curr = curr shr 1
pos--
}
var flag = true
// Check if it doesn't violate the constraints
for (i in 0 until n) {
if (inDegree[i] != 0) {
flag = false
break
}
}
if (flag) {
answer = bitCount
}
}
return answer
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,782 | kotlab | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem1639/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem1639
/**
* LeetCode page: [1639. Number of Ways to Form a Target String Given a Dictionary](https://leetcode.com/problems/number-of-ways-to-form-a-target-string-given-a-dictionary/);
*/
class Solution {
private val mod = 1_000_000_007
/* Complexity:
* Time O(MN+KN) and Space O(K) where M, N and K are the size of words, the length of each word,
* and the length of target, respectively.
*/
fun numWays(words: Array<String>, target: String): Int {
val wordCount = WordCount(words)
/* subResult[i]@j ::= number of ways to form suffix of target that starts from index i,
* using the columns starting from index j;
*/
val subResult = subResultHolder(target).apply {
// Base case is j equals the length of word
updateBaseCases(target, this)
// Update the sub result in decreasing j, until j equals 0
updateRemainingCases(words, target, wordCount, this)
}
return originalProblem(subResult)
}
private class WordCount(words: Array<String>) {
private val count = count(words)
private fun count(words: Array<String>): Array<IntArray> {
val wordLength = words[0].length
val count = Array(wordLength) { IntArray(26) }
for (word in words) {
for ((index, char) in word.withIndex()) {
count[index][char.intIndex()]++
}
}
return count
}
private fun Char.intIndex(): Int = this - 'a'
fun count(matching: Char, atIndex: Int): Int {
return count[atIndex][matching.intIndex()]
}
}
private fun subResultHolder(target: String): IntArray {
return IntArray(target.length + 1)
}
private fun updateBaseCases(target: String, subResultHolder: IntArray) {
// Using column at word.length, i.e. empty column, to form suffixes of target
for (suffixStart in target.indices) {
subResultHolder[suffixStart] = 0
}
subResultHolder[target.length] = 1
}
private fun updateRemainingCases(
words: Array<String>,
target: String,
wordCount: WordCount,
subResultHolder: IntArray
) {
val wordLength = words[0].length
for (startColumn in wordLength - 1 downTo 0) {
for (startSuffix in target.indices) {
val numWaysUsingStartColumn =
wordCount.count(target[startSuffix], startColumn).toLong() * subResultHolder[startSuffix + 1]
val numWaysNotUsingStartColumn = subResultHolder[startSuffix]
val subResult = (numWaysUsingStartColumn + numWaysNotUsingStartColumn) % mod
subResultHolder[startSuffix] = subResult.toInt()
}
}
}
private fun originalProblem(subResultHolder: IntArray): Int {
return subResultHolder[0]
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,996 | hj-leetcode-kotlin | Apache License 2.0 |
src/Day14.kt | GarrettShorr | 571,769,671 | false | {"Kotlin": 82669} | import java.lang.Exception
import java.lang.Integer.max
import java.lang.Integer.min
data class Point(val x: Int, val y: Int)
data class Line(val p1: Point, val p2: Point) {
fun isHorizontal() : Boolean {
return p1.x != p2.x && p1.y == p2.y
}
fun isVertical() : Boolean {
return p1.x == p2.x && p1.y != p2.y
}
fun intersects(grain : Sand, dx: Int, dy: Int) : Boolean {
if(isHorizontal()) {
return grain.y + dy == p1.y && grain.x + dx>= min(p2.x, p1.x) && grain.x + dx <= max(p2.x, p1.x)
}
if(isVertical()) {
return grain.x + dx == p1.x && grain.y + dy >= min(p2.y, p1.y) && grain.y + dy <= max(p2.y, p1.y)
}
throw Exception("No diagonal lines yet?")
}
}
data class Sand(var x: Int, var y: Int, var atRest: Boolean = false) {
// center, left, right
fun calculateClearPaths(sandPile: List<Sand>, structures: List<Line>) : Triple<Boolean, Boolean, Boolean> {
var (center, left, right) = Triple(true, true, true)
for(rocks in structures) {
if(rocks.intersects(this, 0, 1)) {
center = false
}
if(rocks.intersects(this, -1, 1)) {
left = false
}
if(rocks.intersects(this, 1, 1)) {
right = false
}
}
for(grain in sandPile) {
if(grain.y == this.y + 1 && grain.x == this.x) {
center = false
}
if(grain.y == this.y + 1 && grain.x == this.x - 1) {
left = false
}
if(grain.y == this.y + 1 && grain.x == this.x + 1) {
right = false
}
}
return Triple(center, left, right)
}
fun isAbyssBound(sandPile: List<Sand>, rockStructures: MutableList<Line>): Boolean {
return sandPile.all { it.y < this.y } && rockStructures.all { max(it.p1.y, it.p2.y) < this.y }
}
}
fun main() {
fun simulateSandFall(grain: Sand, rockStructures: MutableList<Line>, sandPile: List<Sand>): Boolean {
do {
var clearPaths = grain.calculateClearPaths(sandPile, rockStructures)
if(clearPaths.first) {
grain.y++
} else if(clearPaths.second) {
grain.y++
grain.x--
} else if(clearPaths.third) {
grain.y++
grain.x++
} else {
grain.atRest = true
}
var abyssBound = grain.isAbyssBound(sandPile, rockStructures)
} while(clearPaths != Triple(false, false, false) && !abyssBound && !grain.atRest)
return grain.atRest
}
fun part1(input: List<String>): Int {
var rockStructures = mutableListOf<Line>()
for(line in input) {
line.split(" -> ").map {
Point(it.split(",")[0].toInt(), it.split(",")[1].toInt())
}.zipWithNext { a, b -> Line(a, b) }.forEach { rockStructures.add(it) }
}
var sandAtRest = 0
var sandPile = mutableListOf<Sand>()
do {
val grain = Sand(500, 0)
var sandFellAndRested = simulateSandFall(grain, rockStructures, sandPile)
if(sandFellAndRested) {
sandAtRest++
sandPile.add(grain)
println(grain)
}
} while(sandFellAndRested)
return sandAtRest
}
fun part2(input: List<String>): Int {
var rockStructures = mutableListOf<Line>()
for(line in input) {
line.split(" -> ").map {
Point(it.split(",")[0].toInt(), it.split(",")[1].toInt())
}.zipWithNext { a, b -> Line(a, b) }.forEach { rockStructures.add(it) }
}
var lowestRock = rockStructures.maxBy { max(it.p1.y, it.p2.y) }
var floorY = max(lowestRock.p1.y, lowestRock.p2.y) + 2
var floor = Line(Point(-1000000, floorY), Point(1000000, floorY))
rockStructures.add(floor)
var sandAtRest = 0
var sandPile = mutableListOf<Sand>()
do {
val grain = Sand(500, 0)
var sandFellAndRested = simulateSandFall(grain, rockStructures, sandPile)
if(sandFellAndRested) {
sandAtRest++
sandPile.add(grain)
}
if(sandAtRest % 1000 == 0) {
println(grain)
}
// println("${grain.x}, ${grain.y}, ${grain.y != 0 && grain.x != 500}")
} while(grain.y != 0 || grain.x != 500)
return sandAtRest
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test")
// println(part1(testInput))
// println(part2(testInput))
val input = readInput("Day14")
// output(part1(input))
output(part2(input))
}
| 0 | Kotlin | 0 | 0 | 391336623968f210a19797b44d027b05f31484b5 | 4,305 | AdventOfCode2022 | Apache License 2.0 |
src/aoc2022/Day11.kt | NoMoor | 571,730,615 | false | {"Kotlin": 101800} | package aoc2022
import utils.*
import java.rmi.UnexpectedException
internal class Day11(val lines: List<String>) {
/** Parse the input into a number of monkeys. */
fun parseInputs(): Pair<List<Monkey>, Long> {
val monkeys = lines.splitBy { it == "" } // Groups the lines by the blank line.
// Map the list of lines to a monkey.
.map {
val monkeyNum = it[0].split(" ")[1].removeSuffix(":").toLong()
val startingItems = it[1].split(": ").last().split(", ").map { it.toLong() }.toMutableList()
val (op, second) = it[2].split("=")[1].removePrefix(" old ").split(" ")
val divisor = it[3].split(" ").last().toLong()
val trueMonkey = it[4].split(" ").last().toInt()
val falseMonkey = it[5].split(" ").last().toInt()
Monkey(monkeyNum, startingItems, op, second, divisor, trueMonkey, falseMonkey)
}.toList()
// Get the least common multiple of the test divisors to keep the total worry down.
val lcm = monkeys.map { it.testDivisor }.reduce { acc, bigInteger -> acc * bigInteger }
return monkeys to lcm
}
fun part1(): Any {
val (monkeys) = parseInputs()
repeat(20) {
for (m in monkeys) {
for (item in m.items) {
m.inspectionCount++
val newLevel = calcNewWorryLevel(item, m.op, m.op2)
val relief = newLevel / 3
monkeys[if (relief % m.testDivisor == 0L) m.trueMonkey else m.falseMonkey].items.add(relief)
}
m.items.clear()
}
}
return computeMonkeyBusiness(monkeys)
}
fun part2(): Any {
val (monkeys, lcm) = parseInputs()
repeat(10000) {
for (m in monkeys) {
for (item in m.items) {
m.inspectionCount++
val newLevel = calcNewWorryLevel(item, m.op, m.op2)
// Reduce the number using modulo of the lcm since addition and multiplication work the same under
// modulo lcm since all the potential divisors are co-prime.
// https://en.wikipedia.org/wiki/Modular_arithmetic#Properties
val relief = newLevel % lcm
monkeys[if (relief % m.testDivisor == 0L) m.trueMonkey else m.falseMonkey].items.add(relief)
}
m.items.clear()
}
}
return computeMonkeyBusiness(monkeys)
}
private fun computeMonkeyBusiness(monkeys: List<Monkey>) : Long {
println(monkeys.map { it.inspectionCount })
return monkeys.map { it.inspectionCount }.sortedDescending().take(2).let { it[0] * it[1] }
}
private fun calcNewWorryLevel(worryLevel: Long, op: String, op2: String): Long {
return when (op) {
"*" -> {
if (op2 == "old") worryLevel * worryLevel else worryLevel * op2.toLong()
}
"+" -> {
if (op2 == "old") worryLevel + worryLevel else worryLevel + op2.toLong()
}
else -> throw UnexpectedException("This hsouldn't happen $op")
}
}
class Monkey(
val id: Long,
val items: MutableList<Long>,
val op: String,
val op2: String,
val testDivisor: Long,
val trueMonkey: Int,
val falseMonkey: Int) {
var inspectionCount = 0L
}
}
fun main() {
val day = "11".toInt()
val todayTest = Day11(readInput(day, 2022, true))
execute(todayTest::part1, "Day[Test] $day: pt 1", 10605L)
val today = Day11(readInput(day, 2022))
execute(today::part1, "Day $day: pt 1", 55458L)
execute(todayTest::part2, "Day[Test] $day: pt 2", 2713310158L)
execute(today::part2, "Day $day: pt 2", 14508081294L)
}
| 0 | Kotlin | 1 | 2 | d561db73c98d2d82e7e4bc6ef35b599f98b3e333 | 3,488 | aoc2022 | Apache License 2.0 |
src/main/kotlin/Day8.kt | noamfreeman | 572,834,940 | false | {"Kotlin": 30332} | import kotlin.math.max
private val exampleInput = """
30373
25512
65332
33549
35390
""".trimIndent()
fun main() {
println("day8")
println()
println("part1")
assertEquals(part1(exampleInput), 21)
println(part1(readInputFile("day8_input.txt")))
println()
println("part2")
assertEquals(part2(exampleInput), 8)
println(part2(readInputFile("day8_input.txt")))
}
private fun part1(input: String): Int {
val trees = parseInput(input)
val cache = mutableMapOf<Triple<Int, Int, Direction>, Int>()
return Direction.values()
.flatMap { dir ->
// all visible trees from a direction
trees.allCoords().filter { coord ->
trees.isTreeVisibleFromDirection(coord, dir, memoizationCache = cache)
}
}
.toSet() // some trees are visible from more than one direction
.count()
}
private fun part2(input: String): Int {
val trees = parseInput(input)
val cache = mutableMapOf<LookPosition, Int>()
return trees.allCoords().map { coord ->
val score = Direction.values().fold(1) { acc, dir ->
acc * trees.treesSeenFrom(LookPosition(xy = coord, z = trees[coord], dir = dir), memoizationCache = cache)
}
score
}.max()
}
private fun parseInput(input: String): Matrix<Int> {
return input
.lines()
.map { line -> line.map { it.digitToInt() } }
.let { Matrix(it) }
}
private fun Matrix<Int>.isTreeVisibleFromDirection(
coord: MatrixCoord, dir: Direction,
memoizationCache: MutableMap<Triple<Int, Int, Direction>, Int>
): Boolean =
// if there is a tree higher than this tree, it doesn't see the edge.
maxValueInDirection(coord, dir.opposite(), memoizationCache) < this[coord]
private fun Matrix<Int>.maxValueInDirection(
coord: MatrixCoord, dir: Direction,
memoizationCache: MutableMap<Triple<Int, Int, Direction>, Int>
): Int = memoizationCache.getOrPut(Triple(coord.y, coord.x, dir)) {
val neighborCoord = coord + dir
if (isOnEdge(coord, dir)) -1// no values in this direction
else max(
this[neighborCoord],
maxValueInDirection(neighborCoord, dir, memoizationCache)
)
}
private data class LookPosition(val xy: MatrixCoord, val z: Int, val dir: Direction)
private fun Matrix<Int>.treesSeenFrom(
lookPosition: LookPosition,
memoizationCache: MutableMap<LookPosition, Int>
): Int {
val coord = lookPosition.xy
val dir = lookPosition.dir
val neighborCoord = coord + dir
val sightFromNeighbor = lookPosition.copy(xy = neighborCoord)
return memoizationCache.getOrPut(lookPosition) {
if (isOnEdge(coord, dir)) 0
else if (this[neighborCoord] >= lookPosition.z) return 1 // we see only the neighbor
else treesSeenFrom(
sightFromNeighbor, memoizationCache
) + 1// we see one more than the neighbor would have seen if he had been high as we
}
}
private class Matrix<T>(private val data: List<List<T>>) {
val rows = data.size
val columns = data[0].size
init {
data.forEachIndexed { y, row ->
require(row.size == columns) { "row $y size: ${row.size} != $columns" }
}
}
operator fun get(coord: MatrixCoord) = data[coord.y][coord.x]
fun isOnEdge(coord: MatrixCoord, edge: Direction) = when (edge) {
Direction.UP -> coord.y == 0
Direction.DOWN -> coord.y == rows - 1
Direction.LEFT -> coord.x == 0
Direction.RIGHT -> coord.x == columns - 1
}
fun allCoords() = sequence {
(0 until rows).forEach { y ->
(0 until columns).forEach { x ->
yield(MatrixCoord(x, y))
}
}
}
}
| 0 | Kotlin | 0 | 0 | 1751869e237afa3b8466b213dd095f051ac49bef | 3,755 | advent_of_code_2022 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/LongestIncreasingPathInMatrix.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
/**
* 329. Longest Increasing Path in a Matrix
* @see <a href="https://leetcode.com/problems/longest-increasing-path-in-a-matrix/">Source</a>
*/
fun interface LongestIncreasingPathInMatrix {
operator fun invoke(matrix: Array<IntArray>): Int
}
class LongestIncreasingPathInMatrixDFS : LongestIncreasingPathInMatrix {
private val dirs = arrayOf(intArrayOf(0, 1), intArrayOf(1, 0), intArrayOf(0, -1), intArrayOf(-1, 0))
override operator fun invoke(matrix: Array<IntArray>): Int {
if (matrix.isEmpty()) return 0
val m: Int = matrix.size
val n: Int = matrix[0].size
val cache = Array(m) { IntArray(n) }
var max = 1
for (i in 0 until m) {
for (j in 0 until n) {
val len = dfs(matrix, i, j, m, n, cache)
max = max(max, len)
}
}
return max
}
fun dfs(matrix: Array<IntArray>, i: Int, j: Int, m: Int, n: Int, cache: Array<IntArray>): Int {
if (cache[i][j] != 0) return cache[i][j]
var max = 1
for (dir in dirs) {
val x = i + dir[0]
val y = j + dir[1]
val local = x < 0 || x >= m || y < 0 || y >= n
if (local || matrix[x][y] <= matrix[i][j]) continue
val len = 1 + dfs(matrix, x, y, m, n, cache)
max = max(max, len)
}
cache[i][j] = max
return max
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,078 | kotlab | Apache License 2.0 |
kotlin/src/main/kotlin/com/github/jntakpe/aoc2021/days/day10/Day10.kt | jntakpe | 433,584,164 | false | {"Kotlin": 64657, "Rust": 51491} | package com.github.jntakpe.aoc2021.days.day10
import com.github.jntakpe.aoc2021.shared.Day
import com.github.jntakpe.aoc2021.shared.readInputLines
object Day10 : Day {
override val input = readInputLines(10)
override fun part1() = input.mapNotNull { Line.from(it).illegalPoints() }.sum()
override fun part2() = input.mapNotNull { Line.from(it).missingPoints() }.sorted().let { it[it.size / 2] }
class Line(private val illegal: LegalPairs? = null, private val incomplete: List<LegalPairs>? = null) {
companion object {
fun from(line: String): Line {
val stack = mutableListOf<LegalPairs>()
line.toList().forEach { char ->
if (char in LegalPairs.openingChars) {
stack.add(LegalPairs.openingValueOf(char))
} else {
LegalPairs.closingValueOf(char).run {
if (char in LegalPairs.closingChars && stack.last() == this) {
stack.removeLast()
} else {
return Line(this)
}
}
}
}
return Line(incomplete = stack.reversed())
}
}
fun illegalPoints() = illegal?.illegalPoints
fun missingPoints() = incomplete?.fold(0L) { a, c -> a * 5 + c.missingPoints }
}
enum class LegalPairs(val opening: Char, val closing: Char, val illegalPoints: Int, val missingPoints: Int) {
PARENTHESIS('(', ')', 3, 1),
CURLY_BRACKETS('{', '}', 57, 3),
BRACKETS('[', ']', 1197, 2),
ANGLE_BRACKETS('<', '>', 25137, 4);
companion object {
val openingChars = values().map { it.opening }
val closingChars = values().map { it.closing }
fun openingValueOf(char: Char) = values().single { it.opening == char }
fun closingValueOf(char: Char) = values().single { it.closing == char }
}
}
}
| 0 | Kotlin | 1 | 5 | 230b957cd18e44719fd581c7e380b5bcd46ea615 | 2,079 | aoc2021 | MIT License |
app/src/main/java/online/vapcom/codewars/algorithms/Skyscrapers.kt | vapcomm | 503,057,535 | false | {"Kotlin": 142486} | package online.vapcom.codewars.algorithms
/**
* #25 7×7 Skyscrapers
*
* We use universal algorithm for all this katas:
*```
* https://www.codewars.com/kata/4-by-4-skyscrapers/ -- 4 kyu
* https://www.codewars.com/kata/6-by-6-skyscrapers/ -- 2 kyu
* https://www.codewars.com/kata/5917a2205ffc30ec3a0000a8 -- 1 kyu
* ```
*/
object Skyscrapers {
/**
* Main function, start point of solution finding
*/
fun solvePuzzle(clues: IntArray): Array<IntArray> {
println("== solvePuzzle: clues: ${clues.joinToString()}")
val hints = Hints(clues)
val cluesEngine = CluesEngine(hints)
cluesEngine.makeGridGenerators()
val result = cluesEngine.execute { grid, permutations, gridCache ->
findSolution(hints.emptyCluesColumns, 0, hints.emptyCluesRows, 0, grid, permutations, gridCache)
}
println("== solvePuzzle: findSolutionCount: $findSolutionCount, putColumnToGridCount: $putColumnToGridCount, putRowToGrid: $putRowToGrid")
return result.toArrays()
}
data class PairClue(
val index: Int, // column or row index in grid
val startClue: Int, // start and end clue values
val endClue: Int
)
data class SingleClue(val index: Int, val isStart: Boolean, val clue: Int)
/**
* Helper class to keep all parsed clues data
*/
class Hints(clues: IntArray) {
val gridSize: Int = when (clues.size) {
16 -> 4
24 -> 6
28 -> 7
//NOTE: current implementation supports up to 8x8 grid, see packPermutationToLong()
else -> throw IllegalArgumentException("Unsupported clues size ${clues.size}")
}
private val topClues = clues.copyOfRange(0, gridSize)
private val rightClues = clues.copyOfRange(gridSize, gridSize * 2)
private val bottomClues = clues.copyOfRange(gridSize * 2, gridSize * 3).reversedArray()
private val leftClues = clues.copyOfRange(gridSize * 3, clues.size).reversedArray()
init {
println("-- top: ${topClues.joinToString()}, right: ${rightClues.joinToString()}, " +
"bottom: ${bottomClues.joinToString()}, left: ${leftClues.joinToString()}")
}
private fun pairTransform(index: Int, a: Int, b: Int): PairClue =
if(a > 0 && b > 0) PairClue(index, a, b)
else PairClue(-1, 0, 0)
val pairCluesColumns = topClues.zipIndexed(bottomClues, ::pairTransform).filter { it.index >= 0 }
val pairCluesRows = leftClues.zipIndexed(rightClues, ::pairTransform).filter { it.index >= 0 }
private fun singleTransform(index: Int, a: Int, b: Int): SingleClue = when {
a > 0 && b == 0 -> SingleClue(index, true, a)
a == 0 && b > 0 -> SingleClue(index, false, b)
else -> SingleClue(-1, false, 0)
}
val singleCluesColumns = topClues.zipIndexed(bottomClues, ::singleTransform).filter { it.index >= 0 }
val singleCluesRows = leftClues.zipIndexed(rightClues, ::singleTransform).filter { it.index >= 0 }
private fun emptyTransform(index: Int, a: Int, b: Int): Int =
if (a == 0 && b == 0) index else -1
val emptyCluesColumns = topClues.zipIndexed(bottomClues, ::emptyTransform).filter { it >= 0 }
val emptyCluesRows = leftClues.zipIndexed(rightClues, ::emptyTransform).filter { it >= 0 }
init {
println("-- pairs: columns: $pairCluesColumns, rows: $pairCluesRows")
println("-- singles: columns: $singleCluesColumns, rows: $singleCluesRows")
println("-- empty: columns: $emptyCluesColumns, rows: $emptyCluesRows")
}
private inline fun <V> IntArray.zipIndexed(other: IntArray, transform: (index: Int, a: Int, b: Int) -> V): List<V> {
val size = minOf(size, other.size)
val list = ArrayList<V>(size)
for (i in 0 until size) {
list.add(transform(i, this[i], other[i]))
}
return list
}
} // Hints
/**
* Compact and fast grid storage.
* @param size grid size, it should be <= 8
*/
class Grid(private val size: Int) {
companion object {
val EMPTY: Grid = Grid(0)
fun fromArrays(src: Array<IntArray>): Grid {
val g = Grid(src.size)
src.forEachIndexed { ri, row ->
g.grid[ri] = packRowToInt(row)
}
return g
}
/**
* Pack row from IntArray to Int, last value to the least value tetrad
*/
private fun packRowToInt(row: IntArray): Int {
var result = 0
row.forEach { result = (result shl 4) or (it and 0x0F) }
return result
}
}
val grid = IntArray(size) // rows packed in Ints
/**
* Return a deep copy of this grid
*/
fun clone(): Grid {
val g = Grid(this.size)
grid.copyInto(g.grid)
return g
}
/**
* Return true if given column permutation matches grid and can be inserted into it
*/
fun columnPermutationMatches(column: Int, permutation: Int): Boolean {
val maxIndex = size - 1
val shift = 4 * (size - 1 - column)
for (row in 0 until size) {
val cell = (grid[row] shr shift) and 0x0F
if (cell != 0 && cell != (permutation shr (4 * (maxIndex - row))) and 0x0F)
return false
}
return true
}
/**
* Copy this grid to dst and put permutation on column
*/
fun putColumnToGrid(column: Int, permutation: Int, dst: Grid) {
//+++
putColumnToGridCount++
//+++
val shift = 4 * (size - 1 - column)
val maxIndex = size - 1
for (row in 0 until size) {
val p = (((permutation shr (4 * (maxIndex - row))) and 0x0F) shl (4 * (maxIndex - column)))
dst.grid[row] = (grid[row] and (0x0F shl shift).inv()) or p
}
}
fun packColumnToInt(column: Int): Int {
val shift = 4 * (size - 1 - column)
var result = 0
for (row in 0 until size) {
result = (result shl 4) or ((grid[row] shr shift) and 0xF)
}
return result
}
fun getRow(row: Int): Int = grid[row]
/**
* Return true if given row permutation matches grid and can be inserted into it
*/
fun rowPermutationMatches(rowIndex: Int, permutation: Int): Boolean {
val row = grid[rowIndex]
//TODO: make wise bits check without loop and shifts
for (i in 0 until size) {
val cell = (row shr (4 * i)) and 0x0F
if (cell != 0 && cell != (permutation shr (4 * i)) and 0x0F)
return false
}
return true
}
fun putRowToGrid(row: Int, permutation: Int, dst: Grid) {
//+++
putRowToGrid++
//+++
grid.copyInto(dst.grid)
dst.grid[row] = permutation
}
/**
* Check all grid's rows have valid possible permutation values,
* i.e. all non-zero numbers in row should appear only once
*/
fun isPossibleValidRows(): Boolean {
grid.forEach { row ->
var bits = 0
for (i in 0 until size) {
val cell = (row shr (4 * i)) and 0x0F
if (cell > 0) { // skip zeros
val bit = 1 shl cell
if (bits and bit != 0) { // already have this number
return false
} else bits = bits or bit
}
}
}
return true
}
/**
* Strong correctness check of all columns in grid (without zeros)
*/
fun isValidColumns(): Boolean {
for (column in 0 until size) {
var bits = 0
grid.forEach { row ->
val cell = (row shr (4 * (size - 1 - column))) and 0x0F
if (cell == 0)
return false
val bit = 1 shl cell
if (bits and bit != 0) { // already have this number
return false
} else bits = bits or bit
}
}
return true
}
/**
* Return true if it is a final solution, all columns and rows have correct permutations
*/
fun checkSolution(): Boolean {
println("====== CHECK:\n${toLogString()}")
return if (isValidColumns() && isPossibleValidRows()) {
println("====== FOUND SOLUTION!")
true
} else false
}
/**
* Convert internal grid to required result format
*/
fun toArrays(): Array<IntArray> {
return Array(size) { r ->
IntArray(size) { c ->
(grid[r] shr (4 * (size - 1 - c))) and 0x0F
}
}
}
//+++
@OptIn(ExperimentalStdlibApi::class)
fun toLogString(): String = grid.joinToString("\n") { it.toHexString() }
//+++
}
/**
* First stage of solution, generates grids based on given clues
*/
class CluesEngine(private val hints: Hints) {
/**
* Base class for a first stage grid generators
*/
abstract class GridGenerator(gridSize: Int) {
protected abstract val perms: List<Int>
fun permutationsSize(): Int = perms.size
protected var currentPermutation = 0
// buffer for new generated grids to not to allocate them during grid compose
val nextGrid = Grid(gridSize)
fun reset() {
currentPermutation = 0
}
fun hasNextGrid(startGrid: Grid): Boolean {
//TODO: change linear search to something faster
while (currentPermutation < perms.size) {
if (isCurrentPermMatchGrid(startGrid)) {
return true
}
currentPermutation++
}
return false
}
abstract fun makeGrid(startGrid: Grid, nextGrid: Grid)
abstract fun isCurrentPermMatchGrid(startGrid: Grid): Boolean
}
/**
* Base class for pair clues grid generators
*/
abstract inner class PairClueGridGenerator(protected val pairClue: PairClue) : GridGenerator(hints.gridSize) {
override val perms = permutations.filterIndexed { index, _ ->
startVisible[index] == pairClue.startClue && endVisible[index] == pairClue.endClue
}
}
inner class PairColumnGridGenerator(pairClue: PairClue) : PairClueGridGenerator(pairClue) {
override fun isCurrentPermMatchGrid(startGrid: Grid): Boolean =
startGrid.columnPermutationMatches(pairClue.index, perms[currentPermutation])
override fun makeGrid(startGrid: Grid, nextGrid: Grid) =
startGrid.putColumnToGrid(pairClue.index, perms[currentPermutation++], nextGrid)
}
inner class PairRowGridGenerator(pairClue: PairClue) : PairClueGridGenerator(pairClue) {
override fun isCurrentPermMatchGrid(startGrid: Grid): Boolean =
startGrid.rowPermutationMatches(pairClue.index, perms[currentPermutation])
override fun makeGrid(startGrid: Grid, nextGrid: Grid) =
startGrid.putRowToGrid(pairClue.index, perms[currentPermutation++], nextGrid)
}
/**
* Base class for single clue grid generators
*/
abstract inner class SingleClueGridGenerator(private val singleClue: SingleClue) : GridGenerator(hints.gridSize) {
private val visible = if (singleClue.isStart) startVisible else endVisible
override val perms = permutations.filterIndexed { index, _ ->
visible[index] == singleClue.clue
}
}
inner class SingleColumnGridGenerator(private val singleClue: SingleClue) : SingleClueGridGenerator(singleClue) {
override fun isCurrentPermMatchGrid(startGrid: Grid): Boolean =
startGrid.columnPermutationMatches(singleClue.index, perms[currentPermutation])
override fun makeGrid(startGrid: Grid, nextGrid: Grid) =
startGrid.putColumnToGrid(singleClue.index, perms[currentPermutation++], nextGrid)
}
inner class SingleRowGridGenerator(private val singleClue: SingleClue) : SingleClueGridGenerator(singleClue) {
override fun isCurrentPermMatchGrid(startGrid: Grid): Boolean =
startGrid.rowPermutationMatches(singleClue.index, perms[currentPermutation])
override fun makeGrid(startGrid: Grid, nextGrid: Grid) =
startGrid.putRowToGrid(singleClue.index, perms[currentPermutation++], nextGrid)
}
// generate all possible columns and rows permutations of given grid size
val permutations = Array(hints.gridSize) { it + 1 }.toList().permutations().map { packPermutationToInt(it) }.sorted()
// Count visible skyscrapers for all permutations:
// Start | Permutation | End: 4 | 1, 2, 3, 4 | 1
val startVisible = getVisibleFromStart(permutations)
val endVisible = getVisibleFromEnd(permutations)
private val gridGenerators = ArrayList<GridGenerator>()
// pre allocated grids for findSolution()
private val gridsCache = Array(hints.gridSize) { Array(hints.gridSize) { Grid(hints.gridSize) } }
/**
* Make generators list based on clues. Pair clues go first.
*/
fun makeGridGenerators() {
hints.pairCluesColumns.forEach { pairClue ->
gridGenerators.add(PairColumnGridGenerator(pairClue))
}
hints.pairCluesRows.forEach { pairClue ->
gridGenerators.add(PairRowGridGenerator(pairClue))
}
hints.singleCluesColumns.forEach { singleClue ->
gridGenerators.add(SingleColumnGridGenerator(singleClue))
}
hints.singleCluesRows.forEach { singleClue ->
gridGenerators.add(SingleRowGridGenerator(singleClue))
}
}
/**
* Compose first stage girds based on given clues and call findSolutionBlock() to find final solution
*/
fun execute(findSolutionBlock: (grid: Grid, permutations: List<Int>, gridsCache: Array<Array<Grid>>) -> Pair<Boolean, Grid>): Grid {
println("## execute: generators: ")
gridGenerators.forEachIndexed { index, g ->
println("#### gen[$index]: perms: ${g.permutationsSize()}")
}
println("#### total clues permutations: ${gridGenerators.fold(1L) { mult, ps -> mult * ps.permutationsSize().toLong()} }")
val emptyGrid = Grid(hints.gridSize)
if (gridGenerators.isEmpty()) {
// no clues at all, do our best
val res = findSolutionBlock(emptyGrid, permutations, gridsCache)
return if (res.first) res.second else emptyGrid
}
val res = composeGrid(0, emptyGrid) { grid ->
findSolutionBlock(grid, permutations, gridsCache)
}
println("## execute: compose count: $composeCount")
return if (res.first) res.second else emptyGrid
}
private var composeCount = 0L
/**
* Recursively compose grid from all clue grid generators and try it with solution finder block
*/
private fun composeGrid(genIndex: Int, startGrid: Grid,
finderBlock: (grid: Grid) -> Pair<Boolean, Grid>): Pair<Boolean, Grid> {
// println("###### composeGrid: gen[$genIndex]: startGrid:\n${startGrid.toLogString()}")
// println("###### composeGrid: gen[$genIndex]")
composeCount++
if (genIndex >= gridGenerators.size) {
return finderBlock(startGrid)
}
val generator = gridGenerators[genIndex]
generator.reset()
while (generator.hasNextGrid(startGrid)) {
generator.makeGrid(startGrid, generator.nextGrid)
val res = composeGrid(genIndex + 1, generator.nextGrid, finderBlock)
if (res.first) return res
}
return Pair(false, Grid(0)) //TODO: optimize Pair creation, use constant
}
} // CluesEngine
var findSolutionCount = 0L
/**
* Second iteration does recursive search of columns and rows with no clues from a given startGrid.
*/
private fun findSolution(
emptyColumns: List<Int>, columnOffset: Int, emptyRows: List<Int>, rowOffset: Int,
startGrid: Grid, permutations: List<Int>, gridCache: Array<Array<Grid>>
): Pair<Boolean, Grid> {
// println("\n++++ findSolution: emptyColumns: $emptyColumns, coff:$columnOffset, emptyRows: $emptyRows, roff: $rowOffset," +
// " start grid:\n${startGrid.toLogString()}")
findSolutionCount++
if (columnOffset < emptyColumns.size) { // columns cycle
// println("++++++ findSolution: try column ${emptyColumns[columnOffset]}")
val columnMask = startGrid.packColumnToInt(emptyColumns[columnOffset])
//TODO: change linear search to the faster method
permutations.forEach { perm ->
if (perm and columnMask == columnMask) { // possible column permutation
val nextGrid = gridCache[rowOffset][columnOffset]
startGrid.putColumnToGrid(emptyColumns[columnOffset], perm, nextGrid)
if (nextGrid.isPossibleValidRows()) {
val res = findSolution(emptyColumns, columnOffset + 1, emptyRows, rowOffset, nextGrid, permutations, gridCache)
if (res.first)
return res
}
}
}
} else {
if (rowOffset < emptyRows.size) { // rows cycle
// println("++++++ findSolution: try row ${emptyRows[rowOffset]}")
// empty columns may already fill the entire grid, check it
if (startGrid.checkSolution())
return Pair(true, startGrid)
val rowMask = startGrid.getRow(emptyRows[rowOffset])
//TODO: change linear search to the faster method
permutations.forEach { perm ->
if (perm and rowMask == rowMask) {
val nextGrid = gridCache[rowOffset][columnOffset]
startGrid.putRowToGrid(emptyRows[rowOffset], perm, nextGrid)
val res = findSolution(emptyColumns, columnOffset, emptyRows, rowOffset + 1, nextGrid, permutations, gridCache)
if (res.first)
return res
}
}
} else {
// it was last empty row, check the final variant
return if (startGrid.checkSolution()) return Pair(true, startGrid) else Pair(false, Grid.EMPTY)
}
}
//TODO: remove object allocation, return Int with column and row and grid in cache, or -1 if nothing found
return Pair(false, Grid.EMPTY)
}
/**
* Pack one permutation array to Int, last value to the least value byte
*
* NOTE: permutation.size should be <= 8
*/
fun packPermutationToInt(permutation: List<Int>): Int {
var result = 0
permutation.forEach { result = (result shl 4) or (it and 0x0F) }
return result
}
/**
* Permutations generator by Heap’s algorithm
*/
fun <V> List<V>.permutations(): List<List<V>> {
val result = mutableListOf<List<V>>()
fun swap(list: MutableList<V>, i: Int, j: Int) {
list[i] = list.set(j, list[i])
}
fun generate(size: Int, src: MutableList<V>) {
if (size <= 1) {
result.add(src.toList())
} else {
for (i in 0 until size) {
generate(size - 1, src)
if (size % 2 == 0)
swap(src, i, size - 1)
else swap(src, 0, size - 1)
}
}
}
generate(this.size, this.toMutableList())
return result
}
/**
* Return list of visible skyscrapers for each permutation from it's start
*/
internal fun getVisibleFromStart(permutations: List<Int>): List<Int> = getVisibleFrom(permutations, 7 downTo 0)
/**
* Return list of visible skyscrapers for each permutation from it's end
*/
internal fun getVisibleFromEnd(permutations: List<Int>): List<Int> = getVisibleFrom(permutations, 0..7)
private fun getVisibleFrom(permutations: List<Int>, interval: IntProgression): List<Int> {
return permutations.map { p ->
var visible = 0
var maxHeight = 0
for (i in interval) {
val height = ((p shr (4 * i)) and 0xF)
if (height > maxHeight) {
maxHeight = height
visible++
}
}
visible
}
}
//+++
var putColumnToGridCount = 0L
var putRowToGrid = 0L
//+++
}
fun Array<IntArray>.toLogString(): String = this.joinToString("\n") { it.joinToString(" ") }
| 0 | Kotlin | 0 | 0 | 97b50e8e25211f43ccd49bcee2395c4bc942a37a | 22,104 | codewars | MIT License |
src/Day07.kt | shepard8 | 573,449,602 | false | {"Kotlin": 73637} | import java.util.*
import kotlin.math.min
class Directory(val path: String) {
val children = mutableListOf<Directory>()
var totalSize: Int = 0
}
fun main() {
fun part1(input: Directory): Int {
val rec = input.children.sumOf { part1(it) }
return (input.totalSize.takeIf { it < 100000 } ?: 0) + rec
}
fun findBest(input: Directory, minimumToDelete: Int, maximumToDelete: Int): Int {
val dirSize = input.totalSize
if (dirSize < minimumToDelete) return maximumToDelete
val tempBest = min(maximumToDelete, dirSize)
return input.children.minOf { findBest(it, minimumToDelete, tempBest) }
}
fun part2(input: Directory): Int {
val needed = 30000000
val unused = 70000000 - input.totalSize
val minimumToDelete = needed - unused
return findBest(input, minimumToDelete, unused)
}
val input = readInput("Day07").drop(1)
val root = Directory("/")
val dirStack = Stack<Directory>()
dirStack.push(root)
input.forEach { line ->
if (line == "$ cd ..") {
val popped = dirStack.pop()
dirStack.peek().totalSize += popped.totalSize
}
else if (line.startsWith("$ cd ")) {
val path = dirStack.peek().path + "/" + line.split(" ").last()
val directory = Directory(path)
dirStack.peek().children.add(directory)
dirStack.push(directory)
}
else if (line == "$ ls") {
// Do nothing
}
else if (line.startsWith("dir ")) {
// Do nothing
}
else {
dirStack.peek().totalSize += line.split(" ").first().toInt()
}
}
println(part1(root))
println(part2(root))
}
| 0 | Kotlin | 0 | 1 | 81382d722718efcffdda9b76df1a4ea4e1491b3c | 1,761 | aoc2022-kotlin | Apache License 2.0 |
src/year2021/11/Day11.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2021.`11`
import readInput
//private const val NUMBER = 5
private const val NUMBER = 10
private const val ENABLE_LOGS = false
private data class Point(
val x: Int,
val y: Int,
) {
override fun toString(): String = "[$x,$y]"
}
private fun Point.neighbours(): Set<Point> {
return setOf(
Point(x + 1, y),
Point(x - 1, y),
Point(x, y + 1),
Point(x, y - 1),
Point(x + 1, y + 1),
Point(x - 1, y - 1),
Point(x + 1, y - 1),
Point(x - 1, y + 1),
)
}
private fun printMap(initialMap: Map<Point, Int>, number: Int, enableLog: Boolean = ENABLE_LOGS) {
if (enableLog.not()) return
val sortedPoints = initialMap.keys.toList()
.sortedWith(compareBy({ it.y }, { it.x }))
sortedPoints.forEachIndexed { index, point ->
if (index % number == 0) {
println()
}
print(" " + initialMap[point])
}
println()
}
private fun parseMap(input: List<String>): Map<Point, Int> {
val mutableMap = mutableMapOf<Point, Int>()
input.forEachIndexed { y, line ->
line.split("")
.filter { it.isNotBlank() }
.forEachIndexed { x, value ->
mutableMap[Point(x, y)] = value.toInt()
}
}
return mutableMap
}
private fun mergeTwoMatrix(one: Map<Point, Int>, two: Map<Point, Int>): Map<Point, Int> {
return one.mapValues { (key, value) ->
value + two.getOrElse(key) { error("Illegal key $key") }
}
}
private fun step1(initialMap: Map<Point, Int>): Map<Point, Int> {
val newMap = mutableMapOf<Point, Int>()
initialMap.keys.forEach { currentPoint ->
newMap[currentPoint] = initialMap
.getOrElse(currentPoint) { error("Illegal key $currentPoint") }
.inc()
}
return newMap
}
private fun step2(initialMap: Map<Point, Int>, count: (Int) -> Unit = {}): Map<Point, Int> {
var currentMap = initialMap.toMutableMap()
var deltaMap = currentMap
val setOfFlashedPoints = mutableSetOf<Point>()
while (currentMap.any { it.value > 9 }) {
deltaMap = deltaMap
.mapValues { 0 }
.toMutableMap()
currentMap.forEach { (currentPoint, value) ->
if (value > 9 && currentPoint !in setOfFlashedPoints) {
// flash and increase neighbours
currentPoint.neighbours()
.filter { it in deltaMap }
.forEach { neighbour ->
deltaMap.computeIfPresent(neighbour) { _, value -> value.inc() }
}
setOfFlashedPoints.add(currentPoint)
}
}
if (ENABLE_LOGS) {
println("-----------".repeat(5))
println("currentMap")
printMap(currentMap, NUMBER)
println("Delta")
printMap(deltaMap, NUMBER)
}
currentMap = mergeTwoMatrix(currentMap, deltaMap)
.mapValues { (point, value) ->
if (value > 9 && point in setOfFlashedPoints) {
0
} else {
value
}
}
.toMutableMap()
if (ENABLE_LOGS) {
println("Merge Result")
printMap(currentMap, NUMBER)
}
}
return currentMap
.mapValues { (point, value) ->
if (point in setOfFlashedPoints) {
0
} else {
value
}
}
.toMutableMap()
.also {
count(setOfFlashedPoints.size)
if (ENABLE_LOGS) {
println("Final Result")
printMap(it, NUMBER)
println("-----------".repeat(5))
}
}
}
fun main() {
fun part1(input: List<String>): Int {
var parsedMap = parseMap(input)
var counter = 0
repeat(100) {
printMap(parsedMap, NUMBER)
parsedMap = step2(step1(parsedMap)) {
counter += it
}
}
return counter
}
fun part2(input: List<String>): Int {
var parsedMap = parseMap(input)
var counter = 0
while (parsedMap.all { it.value == 0 }.not()) {
parsedMap = step2(step1(parsedMap))
counter++
}
return counter
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
val part1Test = part1(testInput)
println(part1Test)
check(part1Test == 1656)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 4,681 | KotlinAdventOfCode | Apache License 2.0 |
src/main/kotlin/aoc2015/Day06.kt | lukellmann | 574,273,843 | false | {"Kotlin": 175166} | package aoc2015
import AoCDay
import aoc2015.Day06.Instruction.*
import util.illegalInput
import util.match
// https://adventofcode.com/2015/day/6
object Day06 : AoCDay<Int>(
title = "Probably a Fire Hazard",
part1ExampleAnswer = 1_000_000 - 1_000 - 4,
part1Answer = 400410,
part2ExampleAnswer = 1_000_000 + 2_000 - 4,
part2Answer = 15343601,
) {
private enum class Instruction { TURN_ON, TOGGLE, TURN_OFF }
private fun String.toInstruction() = when (this) {
"turn on" -> TURN_ON
"toggle" -> TOGGLE
"turn off" -> TURN_OFF
else -> illegalInput(this)
}
private val INSTRUCTION_REGEX = Regex("""(turn on|toggle|turn off) (\d+),(\d+) through (\d+),(\d+)""")
private inline fun <T> configureLights(
input: String,
lights: Array<T>,
configureSingleLight: (Instruction, lightRow: T, x: Int) -> Unit,
) {
input
.lineSequence()
.map { line -> INSTRUCTION_REGEX.match(line) }
.forEach { (instr, x1, y1, x2, y2) ->
val instruction = instr.toInstruction()
val xs = x1.toInt()..x2.toInt()
val ys = y1.toInt()..y2.toInt()
for (y in ys) {
for (x in xs) {
val lightRow = lights[y]
configureSingleLight(instruction, lightRow, x)
}
}
}
}
override fun part1(input: String): Int {
val lights = Array(size = 1000) { BooleanArray(size = 1000) }
configureLights(input, lights) { instruction, lightRow, x ->
when (instruction) {
TURN_ON -> lightRow[x] = true
TOGGLE -> lightRow[x] = !lightRow[x]
TURN_OFF -> lightRow[x] = false
}
}
return lights.sumOf { lightRow -> lightRow.count { it } }
}
override fun part2(input: String): Int {
val lights = Array(size = 1000) { IntArray(size = 1000) }
configureLights(input, lights) { instruction, lightRow, x ->
when (instruction) {
TURN_ON -> lightRow[x] += 1
TOGGLE -> lightRow[x] += 2
TURN_OFF -> {
val prev = lightRow[x]
if (prev > 0) lightRow[x] = prev - 1
}
}
}
return lights.sumOf { lightRow -> lightRow.sum() }
}
}
| 0 | Kotlin | 0 | 1 | 344c3d97896575393022c17e216afe86685a9344 | 2,458 | advent-of-code-kotlin | MIT License |
src/day07/Day07.kt | Puju2496 | 576,611,911 | false | {"Kotlin": 46156} | package day07
import readInput
import java.util.*
fun main() {
// test if implementation meets criteria from the description, like:
val input = readInput("src/day07", "Day07")
println("Part1")
val tree = part1(input)
println("Part2")
part2(tree)
}
private fun part1(inputs: List<String>): Node {
val tree = buildTree(inputs)
var totalSize = 0L
println("start")
tree.updateNode(tree.calculateSize())
tree.depthSearch {
println("node - ${it.name} - ${it.type} - ${it.size}")
if (it.type == NodeType.DIR && it.size <= 100000)
totalSize += it.size
}
println("total size - $totalSize")
return tree
}
private fun part2(tree: Node) {
val usedSpace = tree.size
val unusedSpace = 70000000 - usedSpace
val requiredMoreSpace = 30000000 - unusedSpace
println("required space- $requiredMoreSpace")
var min = tree.size
tree.depthSearch {
if (it.type == NodeType.DIR && it.size in requiredMoreSpace until min)
min = it.size
}
println("file size to delete to free space - $min ")
}
private fun buildTree(inputs: List<String>): Node {
val parentNode = Node(name = "/", type = NodeType.DIR)
var currentNode: Node? = parentNode
var nextList = false
inputs.forEach {
val nodeValue = it.split(" ")
when (nodeValue[0]) {
"$" -> {
if (nodeValue[1] == "ls")
nextList = true
else if (nodeValue[1] == "cd") {
nextList = false
currentNode = when (nodeValue[2]) {
"/" -> {
parentNode
}
".." -> {
currentNode?.parent
}
else -> {
currentNode?.searchValue(nodeValue[2])
}
}
}
}
"dir" -> {
val node = Node(name = nodeValue[1], type = NodeType.DIR, parent = currentNode)
currentNode?.addNode(node)
}
else -> {
val node = Node(name = it, type = NodeType.FILE, parent = currentNode, size = nodeValue[0].toLong())
currentNode?.addNode(node)
}
}
}
return parentNode
} | 0 | Kotlin | 0 | 0 | e04f89c67f6170441651a1fe2bd1f2448a2cf64e | 2,415 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/DisjointIntervals.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.TreeMap
import kotlin.math.max
/**
* 352. Data Stream as Disjoint Intervals
* @see <a href="https://leetcode.com/problems/data-stream-as-disjoint-intervals/">Source</a>
*/
class DisjointIntervals {
var map: TreeMap<Int, IntArray> = TreeMap()
fun addNum(value: Int) {
if (map.containsKey(value)) return
val low = map.lowerKey(value)
val high = map.higherKey(value)
when {
low != null && high != null && value == map[low]!![1] + 1 && value == map[high]!![0] - 1 -> {
// low =1,val=3 high=4 and high has key =[4,5] and low has key [1,2]
// now 4 has no use as 1 2 3 4 5 is possible so [1,5]
map[low]!![1] = map[high]!![1]
map.remove(high)
}
low != null && value <= map[low]!![1] + 1 -> {
// for example if 2,8 exists and val is 7 nothing happens but if it is 9 then 2,9
// if i dont put <= then on 7 as val,new value is added in the last else part which is incorrect
map[low]!![1] = max(value, map[low]!![1])
}
high != null && value == map[high]!![0] - 1 -> {
// if 5,8 exists and val is 4 so new=[4,8] and 5 is removed
map[value] = intArrayOf(value, map[high]!![1])
map.remove(high)
}
else -> {
map[value] = intArrayOf(value, value)
}
}
}
fun getIntervals(): Array<IntArray> {
val res = Array(map.size) { IntArray(2) }
var i = 0
for (x in map.values) {
res[i++] = x
}
return res
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,337 | kotlab | Apache License 2.0 |
src/main/kotlin/com/scavi/brainsqueeze/adventofcode/Day21AllergenAssessment.kt | Scavi | 68,294,098 | false | {"Java": 1449516, "Kotlin": 59149} | package com.scavi.brainsqueeze.adventofcode
import java.lang.StringBuilder
class Day21AllergenAssessment {
private val splitPattern = """([^\(]*)(\(contains\s)([^\)]*)""".toRegex()
private data class Food(
val allIngredients: MutableMap<String, Int>,
val allergenToIngredients: MutableMap<String, MutableSet<String>>)
fun solveA(input: List<String>): Int {
val food = filter(prepare(input))
return food.allIngredients.values.sum()
}
fun solveB(input: List<String>): String {
val food = filter(prepare(input))
val tmp = StringBuilder()
for (k in food.allergenToIngredients.keys.sorted()) {
tmp.append(food.allergenToIngredients[k]!!.first()).append(",")
}
return tmp.toString().substring(0, tmp.length - 1)
}
private fun prepare(input: List<String>): Food {
val allIngredients = mutableMapOf<String, Int>()
val allergenToIngredients = mutableMapOf<String, MutableSet<String>>()
for (line in input) {
val (tmpIngredients, _, allergens) = splitPattern.find(line)!!.destructured
val ingredients = tmpIngredients.trim().split(" ").toHashSet()
for (ingredient in ingredients) {
allIngredients[ingredient] = allIngredients.getOrDefault(ingredient, 0) + 1
}
for (tmpAllergen in allergens.split(",")) {
val allergen = tmpAllergen.trim()
if (allergen in allergenToIngredients) {
allergenToIngredients[allergen] = allergenToIngredients[allergen]!!.intersect(ingredients).toMutableSet()
} else {
allergenToIngredients[allergen] = ingredients
}
}
}
return Food(allIngredients, allergenToIngredients)
}
private fun filter(food: Food): Food {
var hasChanges = true
while (hasChanges) {
hasChanges = false
for ((k1, v1) in food.allergenToIngredients) {
if (v1.size == 1) {
for ((k2, v2) in food.allergenToIngredients) {
if (k2 != k1) {
hasChanges = hasChanges or v2.removeAll(v1)
}
}
}
}
}
for ((_, v) in food.allergenToIngredients) {
food.allIngredients.remove(v.first())
}
return food
}
}
| 0 | Java | 0 | 1 | 79550cb8ce504295f762e9439e806b1acfa057c9 | 2,489 | BrainSqueeze | Apache License 2.0 |
src/test/kotlin/amb/aoc2020/day11.kt | andreasmuellerbluemlein | 318,221,589 | false | null | package amb.aoc2020
import org.junit.jupiter.api.Test
import java.util.stream.IntStream.range
import kotlin.streams.toList
class Spot(val isSeat: Boolean, var isOccupied: Boolean) {
override fun toString(): String {
return if (!isSeat) "." else if (isOccupied) "#" else "L"
}
}
typealias SpotMap = List<List<Spot>>
class Day11 : TestBase() {
private fun getMap(file: String): SpotMap {
val input = getTestData(file)
return input.map { line ->
line.map { char ->
Spot(char != '.', char == '#')
}
}.filter { it.isNotEmpty() }
}
private fun printMap(map: SpotMap) {
println()
map.forEach { line ->
line.forEach { spot ->
print(spot.toString())
}
println()
}
}
private fun getMapDifference(map1: SpotMap, map2: SpotMap): Int {
return map1.mapIndexed { x, row ->
row.mapIndexed { y, spot ->
if (spot.isOccupied != map2[x][y].isOccupied) 1 else 0
}.sum()
}.sum()
}
private fun getOccupiedSeats(map: SpotMap): Int {
return map.map { row ->
row.map { spot ->
if (spot.isOccupied) 1 else 0
}.sum()
}.sum()
}
private fun getNeighbours(x: Int, y: Int, xSize: Int, ySize: Int): Sequence<Pair<Int, Int>> {
return sequence {
if (x > 0) yield(Pair(x - 1, y))
if (x > 0 && y > 0) yield(Pair(x - 1, y - 1))
if (y > 0) yield(Pair(x, y - 1))
if (y > 0 && x < xSize - 1) yield(Pair(x + 1, y - 1))
if (x < xSize - 1) yield(Pair(x + 1, y))
if (x < xSize - 1 && y < ySize - 1) yield(Pair(x + 1, y + 1))
if (y < ySize - 1) yield(Pair(x, y + 1))
if (x > 0 && y < ySize - 1) yield(Pair(x - 1, y + 1))
}
}
private fun getNeighbours2(x: Int, y: Int, xSize: Int, ySize: Int): Sequence<List<Pair<Int, Int>>> {
return sequence {
val minusXRange = range(0,x).toList().reversed()
val minusYRange = range(0,y).toList().reversed()
val xRange = range(x,xSize).toList() - x
val yRange = range(y,ySize).toList() - y
yield(minusXRange.map { Pair(it,y) })
yield(minusXRange.zip(minusYRange).map { Pair(it.first,it.second) })
yield(minusYRange.map{Pair(x,it)})
yield(xRange.zip(minusYRange).map { Pair(it.first,it.second) })
yield(xRange.map{Pair(it,y)})
yield(xRange.zip(yRange).map { Pair(it.first,it.second) })
yield(yRange.map{Pair(x,it)})
yield(minusXRange.zip(yRange).map{Pair(it.first,it.second)})
}
}
private fun getOccupiedInSight(spots: List<Spot>):Int{
val firstOccupied = spots.indexOfFirst { it.isSeat && it.isOccupied }
var firstFree = spots.indexOfFirst { it.isSeat && !it.isOccupied }
if(firstFree == -1) firstFree = Int.MAX_VALUE
return if(firstOccupied in 0 until firstFree) 1 else 0
}
private fun getOccupiedInSight(map: SpotMap, x: Int, y: Int) : Int{
val xSize = map.count()
val ySize = map[x].count()
val neighbours = getNeighbours2(x,y,xSize,ySize)
return neighbours.map { lane ->
getOccupiedInSight(lane.map { map[it.first][it.second] })
}.sum()
}
private fun playRound(map: SpotMap): SpotMap {
return map.mapIndexed { x, row ->
row.mapIndexed { y, spot ->
var newSpot = Spot(spot.isSeat, spot.isOccupied)
if (spot.isSeat) {
val neighbours = getNeighbours(x, y, map.count(), row.count())
val numOccupied = neighbours.count { map[it.first][it.second].isOccupied }
if (spot.isOccupied && (numOccupied >= 4))
newSpot.isOccupied = false
if (!spot.isOccupied && (numOccupied == 0))
newSpot.isOccupied = true
}
newSpot
}
}
}
private fun playRound2(map: SpotMap): SpotMap {
return map.mapIndexed { x, row ->
row.mapIndexed { y, spot ->
var newSpot = Spot(spot.isSeat, spot.isOccupied)
if (spot.isSeat) {
val numOccupied = getOccupiedInSight(map,x,y)
if (spot.isOccupied && (numOccupied >= 5))
newSpot.isOccupied = false
if (!spot.isOccupied && (numOccupied == 0))
newSpot.isOccupied = true
}
newSpot
}
}
}
@Test
fun task1() {
var map = getMap("input11")
var difference = 1
var round = 0
while (difference > 0) {
round++
printMap(map)
var newMap = playRound(map)
difference = getMapDifference(map, newMap)
map = newMap
}
logger.info { "game ended after round $round with ${getOccupiedSeats(map)} occupied seats" }
}
@Test
fun task2() {
var map = getMap("input11")
logger.info { getOccupiedInSight(listOf(Spot(false,false),Spot(true,true))).toString()}
var difference = 1
var round = 0
while(difference > 0){
round++
//printMap(map)
var newMap = playRound2(map)
difference = getMapDifference(map,newMap)
map = newMap
}
logger.info { "game ended after round $round with ${getOccupiedSeats(map)} occupied seats" }
}
}
| 1 | Kotlin | 0 | 0 | dad1fa57c2b11bf05a51e5fa183775206cf055cf | 5,713 | aoc2020 | MIT License |
src/main/kotlin/day19/Day19.kt | Jessevanbekkum | 112,612,571 | false | null | package day19
import util.readLines
val n = Pair(0, -1)
val o = Pair(1, 0)
val w = Pair(-1, 0)
val z = Pair(0, 1)
fun day19_1(input: String): Pair<String, Int> {
val maze = readMaze(input)
val result = mutableListOf<Char>()
val startX = maze.indexOfFirst { l -> l[0] != ' ' }
var current = Pair(startX, 0)
var direc = z
while (true) {
val next = peek(maze, current, direc)
if (next == ' ') {
val options = corner(direc)
if (peek(maze, current, options[0]) != ' ') {
direc = options[0]
} else if (peek(maze, current, options[1]) != ' ') {
direc = options[1]
} else {
break;
}
} else {
result.add(next);
current = add(current, direc)
}
}
return Pair(result.filter { c -> c.isLetter() }.joinToString(""), result.size +1)
}
private fun peek(maze: List<List<Char>>, current: Pair<Int, Int>, direc: Pair<Int, Int>): Char {
val x = current.first + direc.first
val y = current.second + direc.second
if (!(x in (0..maze.size - 1)) || !(y in (0..maze[0].size - 1))) {
return ' '
}
return maze[x][y]
}
fun corner(direc: Pair<Int, Int>): List<Pair<Int, Int>> {
if (direc == n || direc == z) {
return listOf(o, w)
} else {
return listOf(n, z)
}
}
fun add(p1: Pair<Int, Int>, p2: Pair<Int, Int>): Pair<Int, Int> {
return Pair(p1.first + p2.first, p1.second + p2.second)
}
fun readMaze(input: String): List<List<Char>> {
val readLines = readLines(input)
val result = mutableListOf<MutableList<Char>>()
val Y = readLines.size -1
val X = readLines.map { l -> l.length }.max()!! -1
for (x in 0..X) {
result.add(mutableListOf())
for (y in 0..Y) {
result[x].add(' ')
}
}
for (y in 0..readLines.size - 1) {
for (x in 0..readLines[y].length - 1) {
result[x][y] = readLines[y].elementAt(x)
}
}
return result;
} | 0 | Kotlin | 0 | 0 | 1340efd354c61cd070c621cdf1eadecfc23a7cc5 | 2,059 | aoc-2017 | Apache License 2.0 |
src/Day02.kt | aadityaguptaa | 572,618,899 | false | null |
fun main() {
fun part1(input: List<String>): Int {
var points = mapOf('X' to 1, 'Y' to 2, 'Z' to 3)
var draw = mapOf('A' to 'X', 'B' to 'Y', 'C' to 'Z')
var loss = mapOf('C' to 'Y', 'A' to 'Z', 'B' to 'X')
var score = 0;
for(element in input){
var li = element.split("\\s".toRegex()).toTypedArray()
if(li[1][0] == draw[li[0][0]]){
score += 3
}else if(li[1][0] != loss[li[0][0]]){
score+=6
}
score+= points[li[1][0]]!!
}
return score
}
fun part2(input: List<String>): Int {
var draw = mapOf('A' to 1, 'B' to 2, 'C' to 3)
var loss = mapOf('C' to 2, 'A' to 3, 'B' to 1)
var win = mapOf('C' to 1, 'A' to 2, 'B' to 3)
var score = 0;
for(element in input){
var li = element.split("\\s".toRegex()).toTypedArray()
if(li[1][0] == 'X'){
score+=0
score+=loss[li[0][0]]!!
}else if(li[1][0] == 'Y'){
score+=3
score+=draw[li[0][0]]!!
}else{
score+=6
score+=win[li[0][0]]!!
}
}
return score
}
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Python | 2 | 10 | d76ac48851a9b833fbbd3493a7730f7e0b365da8 | 1,359 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/days/day09.kt | josergdev | 573,178,933 | false | {"Kotlin": 20792} | package days
import java.io.File
import kotlin.math.abs
import kotlin.math.max
fun Pair<Int, Int>.moveHead(cmd: Char) = when (cmd) {
'U' -> this.first to this.second + 1
'R' -> this.first + 1 to this.second
'D' -> this.first to this.second - 1
'L' -> this.first - 1 to this.second
else -> throw IllegalArgumentException()
}
fun Pair<Int, Int>.moveTail(head: Pair<Int, Int>) = when {
this.isTouching(head) -> this
this.second == head.second -> when {
head.first < this.first -> this.first - 1 to this.second
else -> this.first + 1 to this.second
}
this.first == head.first -> when {
head.second < this.second -> this.first to this.second - 1
else -> this.first to this.second + 1
}
else -> when {
head.second < this.second -> when {
head.first < this.first -> this.first - 1 to this.second - 1
else -> this.first + 1 to this.second - 1
}
else -> when {
head.first < this.first -> this.first - 1 to this.second + 1
else -> this.first + 1 to this.second + 1
}
}
}
fun Pair<Int, Int>.isTouching(point: Pair<Int, Int>) = max(abs(point.first - this.first), abs(point.second - this.second)) <= 1
fun tailPositions(commands: List<String>, knotsSize: Int) = commands
.map { it.split(" ") }
.map { it[0].repeat(it[1].toInt()) }
.flatMap { it.toList() }
.scan(List(knotsSize) { 0 to 0 }) { knots, cmd ->
knots.drop(1).fold(listOf(knots.first().moveHead(cmd))) { acc, knot ->
acc + knot.moveTail(acc.last())
}
}
.map { it.last() }
.toSet()
.size
fun day9part1() = tailPositions(File("input/09.txt").readLines(), 2)
fun day9part2() = tailPositions(File("input/09.txt").readLines(), 10)
| 0 | Kotlin | 0 | 0 | ea17b3f2a308618883caa7406295d80be2406260 | 1,800 | aoc-2022 | MIT License |
2023/src/day15/Day15.kt | scrubskip | 160,313,272 | false | {"Kotlin": 198319, "Python": 114888, "Dart": 86314} | package day15
import java.io.File
fun main() {
val input = File("src/day15/day15.txt").readLines().first().split(",")
println(input.sumOf { getHash(it) })
val boxes = getBoxes(input)
// println(boxes.map { "${it.boxNumber} ${it.getFocusPower()}" })
println(boxes.sumOf { it.getFocusPower() })
}
fun getHash(input: String): Int {
var currentValue = 0
input.forEach {
currentValue += it.code
currentValue *= 17
currentValue %= 256
}
return currentValue
}
data class Lens(val label: String, var focalLength: Int)
class Box(val boxNumber: Int) {
private val lensList = mutableListOf<Lens>()
fun doOperation(label: String, operation: String) {
if ("-" == operation) {
lensList.removeIf { it.label == label }
} else if ('=' == operation.first()) {
val found = lensList.find { it.label == label }
val focalLength = operation.drop(1).toInt()
if (found != null) {
found.focalLength = focalLength
} else {
lensList.add(Lens(label, focalLength))
}
}
}
fun getFocusPower(): Int {
return lensList.mapIndexed { index, lens -> (boxNumber + 1) * (index + 1) * lens.focalLength }
.sum()
}
}
val LABEL = Regex("""(\w+)""")
fun getBoxes(input: List<String>): List<Box> {
var boxMap = mutableMapOf<Int, Box>()
input.forEach {
val instruction = it
val match = LABEL.find(instruction)
match?.let {
val label = match.value
val boxIndex = getHash(label)
val box = boxMap.getOrPut(boxIndex) { Box(boxIndex) }
box.doOperation(label, instruction.substring(match.range.last + 1))
}
}
return boxMap.keys.sorted().map { boxMap[it]!! }
} | 0 | Kotlin | 0 | 0 | a5b7f69b43ad02b9356d19c15ce478866e6c38a1 | 1,842 | adventofcode | Apache License 2.0 |
src/Day04.kt | alexdesi | 575,352,526 | false | {"Kotlin": 9824} | import java.io.File
fun main() {
val regex = """(\d+)-(\d+),(\d+)-(\d+)""".toRegex() // to group use round parenthesis
fun sections(input: List<String>): List<List<Int>> {
return input.map { line ->
val matchResult = regex.find(line)
matchResult!!.groupValues.subList(1, 5).map { it.toInt() }
}
}
fun part1(input: List<String>): Int {
val fullyContainedSections = sections(input).filter { (a1, a2, b1, b2) ->
((a1 in b1..b2) && (a2 in b1..b2)) || ((b1 in a1..a2) && (b2 in a1..a2))
}
return fullyContainedSections.count()
}
fun part2(input: List<String>): Int {
val containedSections = sections((input)).filter { (a1, a2, b1, b2) ->
((a2 in b1..b2) || (b2 in a1..a2))
}
return containedSections.count()
}
// test if implementation meets criteria from the description
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 56a6345e0e005da09cb5e2c7f67c49f1379c720d | 1,118 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/dp/LConvexS.kt | yx-z | 106,589,674 | false | null | package dp
import util.*
// longest convex subsequence
// a convex sequence satisfies a[i] - a[i - 1] > a[i - 1] - a[i - 2]
fun main(args: Array<String>) {
val A = oneArrayOf(1, 4, 8, 13, 14, 18, 19)
println(A.lcs())
}
fun OneArray<Int>.lcs(): Int {
val A = this
val n = size
// dp[i, j] = len of lcs w/ 1st 2 elem as A[i] and A[j]
// memoization structure: 2d arr dp[1..n, 1..n]
val dp = OneArray(n) { OneArray(n) { 0 } }
// space: O(n^2)
// base case:
// dp[i, j] = 0 if i, j !in 1..n OR i >= j
// = 2 if j = n
for (i in 1 until n) {
dp[i, n] = 2
}
// recursive case:
// assume max { } = 0
// dp[i, j] = 1 + max_k { dp[j, k] } where k in j + 1..n : A[k] - A[j] > A[j] - A[i]
// dependency: dp[i, j] depends on dp[j, k] where k > j > i
// so it is entries to the lower right
// eval order: outer loop for i from n - 2 down to 1
for (i in n - 2 downTo 1) {
// inner loop for j is a no care, say i + 1..n
for (j in i + 1 until n) {
dp[i, j] = 1 + ((j + 1..n)
.filter { k -> A[k] - A[j] > A[j] - A[i] }
.map { k -> dp[j, k] }
.max() ?: 0)
}
}
// time: O(n^2)
// dp.prettyPrintTable()
// we want max_{i, j} { dp[i, j] }
return dp.maxBy { it.max() ?: 0 }?.max() ?: 0
} | 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 1,243 | AlgoKt | MIT License |
src/Day02.kt | alexladeira | 573,196,827 | false | {"Kotlin": 3920} | fun main() {
val finalValues = mapOf("X" to 1, "Y" to 2, "Z" to 3)
val sum = readInput("Day02").fold(0) { acc, s ->
val values = s.split(" ").toMutableList()
values[1] = updateSecondValue(values)
when {
"A" == values[0] && "Z" == values[1] || "C" == values[0] && "Y" == values[1] || "B" == values[0] && "X" == values[1] -> acc + finalValues[values[1]]!!
"A" == values[0] && "X" == values[1] || "C" == values[0] && "Z" == values[1] || "B" == values[0] && "Y" == values[1] -> acc + finalValues[values[1]]!! + 3
else -> acc + finalValues[values[1]]!! + 6
}
}
print(sum)
}
fun updateSecondValue(values: List<String>): String {
return if (values[1] == "X") {
val lose = mapOf("A" to "Z", "B" to "X", "C" to "Y")
lose[values[0]]!!
} else if (values[1] == "Y") {
val draw = mapOf("A" to "X", "B" to "Y", "C" to "Z")
draw[values[0]]!!
} else {
val win = mapOf("A" to "Y", "B" to "Z", "C" to "X")
win[values[0]]!!
}
} | 0 | Kotlin | 0 | 0 | facafc2d92de2ad2b6264610be4159c8135babcb | 1,058 | aoc-2022-in-kotlin | Apache License 2.0 |
src/AoC18.kt | Pi143 | 317,631,443 | false | null | import java.io.File
fun main() {
println("Starting Day 18 A Test 1")
calculateDay18PartA("Input/2020_Day18_A_Test1")
println("Starting Day 18 A Real")
calculateDay18PartA("Input/2020_Day18_A")
println("Starting Day 18 B Test 1")
calculateDay18PartB("Input/2020_Day18_A_Test1")
println("Starting Day 18 B Real")
calculateDay18PartB("Input/2020_Day18_A")
}
fun calculateDay18PartA(file: String): Long {
var calculations = readDay18Data(file)
var result: Long = 0
for (singleCalc in calculations) {
val reversedCalc = singleCalc.asReversed()
result += calculateValue(reversedCalc)
}
println("result: $result")
return result
}
fun calculateValue(calculations: List<String>): Long {
if (calculations.size == 1) {
return calculations[0].toLong()
}
var currentInput = calculations[0]
if (currentInput.contains(")")) {
var bracketsOpen = 0
var currentPosition = 0
bracketsOpen += calculations[currentPosition].count { ")".contains(it) }
bracketsOpen -= calculations[currentPosition].count { "(".contains(it) }
while (bracketsOpen > 0) {
currentPosition++
bracketsOpen += calculations[currentPosition].count { ")".contains(it) }
bracketsOpen -= calculations[currentPosition].count { "(".contains(it) }
}
if (currentPosition == calculations.size - 1) {
val subList = calculations.toMutableList()
subList[0] = subList[0].removeSuffix(")")
subList[currentPosition] = subList[currentPosition].removePrefix("(")
return calculateValue(subList)
} else {
val subList = calculations.subList(0, currentPosition + 1).toMutableList()
subList[0] = subList[0].removeSuffix(")")
subList[currentPosition] = subList[currentPosition].removePrefix("(")
when (calculations[currentPosition + 1]) {
"+" -> return calculateValue(subList) + calculateValue(calculations.subList(currentPosition + 2, calculations.size))
"*" -> return calculateValue(subList) * calculateValue(calculations.subList(currentPosition + 2, calculations.size))
}
}
}
currentInput.contains("(")
val number = calculations[0].toLong()
when (calculations[1]) {
"+" -> return number + calculateValue(calculations.subList(2, calculations.size))
"*" -> return number * calculateValue(calculations.subList(2, calculations.size))
}
return 0
}
fun calculateDay18PartB(file: String): Long {
var calculations = readDay18Data(file)
var result: Long = 0
for (singleCalc in calculations) {
val reversedCalc = singleCalc.asReversed()
val advancedCalcs = addMultiplicationBrackets(reversedCalc)
result += calculateValue(advancedCalcs)
}
println("result: $result")
return result
}
fun addMultiplicationBrackets(reversedcalc: List<String>): List<String> {
val mutableCalcs = reversedcalc.toMutableList()
//even is number
for (currentPosition in 0 until mutableCalcs.size-1 step 2) {
if (reversedcalc[currentPosition + 1] == "+") {
if (!reversedcalc[currentPosition].contains("(")) {
mutableCalcs[currentPosition] = mutableCalcs[currentPosition] + ")"
} else {
var bracketsOpen = 0
var bracketPosition = currentPosition
bracketsOpen += reversedcalc[bracketPosition].count { "(".contains(it) }
bracketsOpen -= reversedcalc[bracketPosition].count { ")".contains(it) }
while (bracketsOpen > 0) {
bracketPosition--
bracketsOpen += reversedcalc[bracketPosition].count { "(".contains(it) }
bracketsOpen -= reversedcalc[bracketPosition].count { ")".contains(it) }
}
mutableCalcs[bracketPosition] = mutableCalcs[bracketPosition] + ")"
}
if (!reversedcalc[currentPosition + 2].contains(")")) {
mutableCalcs[currentPosition + 2] = "(" + mutableCalcs[currentPosition + 2]
} else {
var bracketsOpen = 0
var bracketPosition = currentPosition + 2
bracketsOpen += reversedcalc[bracketPosition].count { ")".contains(it) }
bracketsOpen -= reversedcalc[bracketPosition].count { "(".contains(it) }
while (bracketsOpen > 0) {
bracketPosition++
bracketsOpen += reversedcalc[bracketPosition].count { ")".contains(it) }
bracketsOpen -= reversedcalc[bracketPosition].count { "(".contains(it) }
}
mutableCalcs[bracketPosition] = "(" + mutableCalcs[bracketPosition]
}
}
}
return mutableCalcs
}
fun readDay18Data(input: String): MutableList<List<String>> {
var calculations = mutableListOf<List<String>>()
File(localdir + input).forEachLine { calculations.add(it.split(" ")) }
return calculations
}
| 0 | Kotlin | 0 | 1 | fa21b7f0bd284319e60f964a48a60e1611ccd2c3 | 5,156 | AdventOfCode2020 | MIT License |
src/Day02.kt | kritanta | 574,453,685 | false | {"Kotlin": 8568} | import java.util.zip.DataFormatException
enum class Hand {
Rock, Paper, Scissors
}
enum class CodedHand(val hand: Hand, val handScore: Int) {
A(Hand.Rock, 1),
B(Hand.Paper, 2),
C(Hand.Scissors, 3),
X(Hand.Rock, 1),
Y(Hand.Paper, 2),
Z(Hand.Scissors, 3),
}
enum class CodedHand2(val score: Int) {
A(1),
B(2),
C(3),
X(0),
Y(3),
Z(6),
}
fun main() {
fun getScore(input: List<String>): Int {
var sum = 0
input.forEach {
s ->
var opponent = CodedHand.valueOf(s[0].toString());
var me = CodedHand.valueOf(s[2].toString());
var pointsForMatch = 0
if(opponent.handScore - me.handScore == -1 || (opponent.hand == Hand.Scissors && me.hand == Hand.Rock)){
pointsForMatch = 6
}
else if(opponent.handScore == me.handScore){
pointsForMatch = 3;
}
sum += pointsForMatch + me.handScore;
}
return sum;
}
fun part1(input: List<String>): Int {
return getScore(input);
}
fun part2(input: List<String>): Int {
var sum = 0
input.forEach {
s ->
var opponent = CodedHand2.valueOf(s[0].toString());
var me = CodedHand2.valueOf(s[2].toString());
var pointsForItem: Int
pointsForItem = when (me) {
CodedHand2.X -> {
opponent.score -1;
}
CodedHand2.Z -> {
opponent.score +1;
}
CodedHand2.Y -> {
opponent.score;
}
else -> {
throw DataFormatException("Unexpected data")
}
}
//fix rollover cases
if(pointsForItem == 0){
pointsForItem = 3;
}
if(pointsForItem == 4){
pointsForItem = 1;
}
sum += pointsForItem + me.score;
}
return sum;
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
println(part1(testInput))
println(part2(testInput))
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 834259cf076d0bfaf3d2e06d1bc1d5df13cffd6c | 2,437 | AOC-2022-Kotlin | Apache License 2.0 |
src/Day04.kt | LesleySommerville-Ki | 577,718,331 | false | {"Kotlin": 9590} | fun main() {
fun part1(input: List<String>): Int {
var totalNumber = 0
input.forEach {
val split = it.split(",")
val start = split[0].split("-")[0].toInt()
val end = split[0].split("-")[1].toInt()
val array = (start.. end).toList().toMutableSet()
val start2 = split[1].split("-")[0].toInt()
val end2 = split[1].split("-")[1].toInt()
val array2 = (start2.. end2).toList().toMutableSet()
val isSubArr = array + array2
if ( isSubArr.size === array.size || isSubArr.size === array2.size) {
totalNumber += 1
}
}
return totalNumber
}
fun part2(input: List<String>): Int {
var totalNumber = 0
input.forEach {
val split = it.split(",")
val start = split[0].split("-")[0].toInt()
val end = split[0].split("-")[1].toInt()
val array = (start.. end).toList().toSet()
val start2 = split[1].split("-")[0].toInt()
val end2 = split[1].split("-")[1].toInt()
val array2 = (start2.. end2).toList().toSet()
val intersect = array.intersect(array2)
if (intersect.isNotEmpty()) {
totalNumber += 1
}
}
return totalNumber
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
val input = readInput("Day04")
part1(input).println()
part2(input).println()
} | 0 | Kotlin | 0 | 0 | ea657777d8f084077df9a324093af9892c962200 | 1,600 | AoC | Apache License 2.0 |
year2021/src/main/kotlin/net/olegg/aoc/year2021/day15/Day15.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2021.day15
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.Directions.Companion.NEXT_4
import net.olegg.aoc.utils.Vector2D
import net.olegg.aoc.utils.fit
import net.olegg.aoc.utils.get
import net.olegg.aoc.utils.set
import net.olegg.aoc.year2021.DayOf2021
/**
* See [Year 2021, Day 15](https://adventofcode.com/2021/day/15)
*/
object Day15 : DayOf2021(15) {
override fun first(): Any? {
val map = lines.map { line ->
line.map { it.digitToInt() }
}
return solve(map)
}
override fun second(): Any? {
val map = lines.map { line ->
line.map { it.digitToInt() }
}
val mappings = (1..9).associateWith { start ->
(1..9).scan(start) { acc, _ ->
if (acc < 9) acc + 1 else 1
}
}
val largeMap = (0..4).flatMap { dy ->
map.map { row ->
(0..4).flatMap { dx ->
row.map { value ->
mappings.getValue(value)[dx + dy]
}
}
}
}
return solve(largeMap)
}
private fun solve(map: List<List<Int>>): Int {
val best = map.map { line ->
line.map { 1_000_000 }.toMutableList()
}
best[Vector2D(0, 0)] = 0
val queue = ArrayDeque(listOf(Vector2D(0, 0)))
while (queue.isNotEmpty()) {
val curr = queue.removeFirst()
val value = best[curr] ?: 1_000_000
NEXT_4.map { curr + it.step }
.filter { map.fit(it) }
.map { it to value + map[it]!! }
.filter { it.second < best[it.first]!! }
.forEach { (next, nextVal) ->
best[next] = nextVal
queue += next
}
}
return best.last().last()
}
}
fun main() = SomeDay.mainify(Day15)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,693 | adventofcode | MIT License |
src/main/kotlin/Day07.kt | zychu312 | 573,345,747 | false | {"Kotlin": 15557} | class Day07 {
interface Size {
val size: Int
}
data class File(val path: String, val filename: String, override val size: Int) : Size
data class Folder(
val path: String,
val name: String,
val parentFolder: Folder?,
var folders: MutableSet<Folder> = mutableSetOf(),
var files: MutableSet<File> = mutableSetOf()
) : Size {
override fun hashCode(): Int {
return path.hashCode()
}
override val size: Int
get() = (files + folders).sumOf { it.size }
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Folder
if (path != other.path) return false
return true
}
fun printContent(level: Int = 1) {
val spacer = " ".repeat(level) + "- "
val spacerContent = " ".repeat(level + 1) + "- "
println("${spacer}${name} (dir)")
files.forEach { f -> println("${spacerContent}${f.filename} (file)") }
folders.forEach { f -> f.printContent(level + 1) }
}
fun traverse(acc: List<Folder> = emptyList()): List<Folder> {
return acc + this@Folder + folders.flatMap { f -> f.traverse() }
}
}
fun solve() {
val rootFolder = Folder(name = "root", parentFolder = null, path = "/")
var currentFolder = rootFolder
loadFile("Day07Input.txt")
.readLines()
.forEach { line ->
if (line.startsWith("$ cd")) {
val (_, _, folderArg) = line.split(" ")
when (folderArg) {
"/" -> {
currentFolder = rootFolder
}
".." -> {
val parentFolder = currentFolder.parentFolder ?: throw Error("Cannot go up")
currentFolder = parentFolder
}
else -> {
val folderName = folderArg
currentFolder = currentFolder.folders.find { it.name == folderName }
?: throw Error("Cannot find folder $folderName")
}
}
}
if (line.startsWith("dir")) {
val (_, name) = line.split(" ")
currentFolder.folders.add(
Folder(
name = name,
parentFolder = currentFolder,
path = "${currentFolder.path}${if (currentFolder.path != "/") "/" else ""}$name"
)
)
}
val (firstPart, name) = line.split(" ")
if (firstPart.first().isDigit()) {
val size = firstPart.toInt()
currentFolder.files.add(
File(
path = "${currentFolder.path}${if (currentFolder.path != "/") "/" else ""}$name",
filename = name, size = size
)
)
}
}
rootFolder.printContent()
println("Total size: ${rootFolder.size}")
val sizeOfFoldersWithGivenSize = rootFolder
.traverse()
.filter { it.size <= 100_000 }
.sumOf { it.size }
println("Problem 1: Size of folders with given size: $sizeOfFoldersWithGivenSize")
val hardDriveSize = 70_000_000
val currentlyOccupied = rootFolder.size
val currentFreeSpace = hardDriveSize - currentlyOccupied
val freeSpaceNeeded = 30_000_000
val needsToBeDeleted = freeSpaceNeeded - currentFreeSpace
rootFolder
.traverse()
.filter { it.size >= needsToBeDeleted }
.minByOrNull { it.size }
?.let { println("Problem 2: Folder to be deleted: ${it.path} size: ${it.size}") }
}
}
fun main() {
Day07().solve()
} | 0 | Kotlin | 0 | 0 | 3e49f2e3aafe53ca32dea5bce4c128d16472fee3 | 4,206 | advent-of-code-kt | Apache License 2.0 |
src/main/kotlin/adventofcode/common/Collections.kt | pfolta | 573,956,675 | false | {"Kotlin": 199554, "Dockerfile": 227} | package adventofcode.common
// Returns every nth element in a list shifted by an optional offset
// e.g. listOf(1, 2, 3, 4).everyNth(2, 1) -> listOf(2, 4)
inline fun <reified T : Any?> Collection<T>.everyNth(n: Int, offset: Int = 0) = filterIndexed { index, _ -> index % n == offset }
// Returns the product of all elements in a Int/Long collection, similar to sum()
fun Collection<Int>.product() = reduce(Int::times)
fun Collection<Long>.product() = reduce(Long::times)
/**
* Returns the cartesian product of a collection of collections
*/
inline fun <reified T : Any?> Collection<Collection<T>>.cartesianProduct() =
fold(listOf(listOf<T>())) { product, list -> product.flatMap { subList -> list.map { element -> subList + element } } }
/**
* Returns a set of valid neighbors in any 2D grid
*
* Excluding diagonals: Including diagonals:
* _ N _ N N N
* N P N N P N
* _ N _ N N N
* where N is a neighbor of P.
*/
inline fun <reified T : Any?> List<List<T>>.neighbors(x: Int, y: Int, includeDiagonals: Boolean): Set<Pair<Int, Int>> =
when {
includeDiagonals -> setOf(
x - 1 to y - 1,
x to y - 1,
x + 1 to y - 1,
x - 1 to y,
x + 1 to y,
x - 1 to y + 1,
x to y + 1,
x + 1 to y + 1
)
else -> setOf(
x to y - 1,
x - 1 to y,
x + 1 to y,
x to y + 1
)
}
.filter { it.first >= 0 && it.second >= 0 }
.filter { it.first < this[y].size && it.second < size }
.toSet()
/**
* Transposes a 2D collection by rotating it 90deg clockwise:
*
* Original collection: After transposing:
* A B C G D A
* D E F H E B
* G H I I F C
*/
inline fun <reified T : Any?> Collection<Collection<T>>.transpose(): Collection<Collection<T>> {
val result = first().map { mutableListOf<T>() }
forEach { list -> result.zip(list).forEach { it.first.add(it.second) } }
return result.map { it.reversed() }
}
| 0 | Kotlin | 0 | 0 | 72492c6a7d0c939b2388e13ffdcbf12b5a1cb838 | 2,134 | AdventOfCode | MIT License |
solutions/aockt/y2021/Y2021D22.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2021
import io.github.jadarma.aockt.core.Solution
import kotlin.math.absoluteValue
object Y2021D22 : Solution {
/** Represents a cuboid in 3D space, arranged orthogonally with respect to the axes. */
private data class Cuboid(val xRange: LongRange, val yRange: LongRange, val zRange: LongRange) {
init {
require(listOf(xRange, yRange, zRange).none { it.isEmpty() }) { "Empty range, this step does nothing." }
}
companion object {
/** Ensures the ranger are valid and returns a [Cuboid] bound by them, or `null` otherwise. */
fun of(xRange: LongRange, yRange: LongRange, zRange: LongRange): Cuboid? {
if (xRange.isEmpty() || yRange.isEmpty() || zRange.isEmpty()) return null
return Cuboid(xRange, yRange, zRange)
}
}
}
/** Computes the volume of a [Cuboid]. */
private val Cuboid.volume: Long
get() = listOf(xRange, yRange, zRange).map { it.last + 1 - it.first }.reduce(Long::times).absoluteValue
/** Return the range of values for the given [axis]: `X`, `Y`, or `Z`. */
private operator fun Cuboid.get(axis: Char): LongRange = when (axis) {
'X' -> xRange
'Y' -> yRange
'Z' -> zRange
else -> error("Invalid axis.")
}
/**
* Split a [Cuboid] into a maximum of three parts, by splitting an [axis] at a given [range], which must not be
* necessarily contained within this cuboid range.
* The first value is whatever is _left_ of the range _(exclusive)_.
* The second value is whatever is _within_ the range _(inclusive)_.
* The third value is whatever is _right_ of the range _(exclusive)_.
*/
private fun Cuboid.split(axis: Char, range: LongRange): Triple<Cuboid?, Cuboid?, Cuboid?> {
val axisRange = this[axis]
val l = axisRange.first until range.first
val m = maxOf(axisRange.first, range.first)..minOf(axisRange.last, range.last)
val r = (range.last + 1)..axisRange.last
return when (axis) {
'X' -> Triple(Cuboid.of(l, yRange, zRange), Cuboid.of(m, yRange, zRange), Cuboid.of(r, yRange, zRange))
'Y' -> Triple(Cuboid.of(xRange, l, zRange), Cuboid.of(xRange, m, zRange), Cuboid.of(xRange, r, zRange))
'Z' -> Triple(Cuboid.of(xRange, yRange, l), Cuboid.of(xRange, yRange, m), Cuboid.of(xRange, yRange, r))
else -> error("Invalid axis.")
}
}
/** Returns the set of [Cuboid]s that sum up to the result of removing intersecting regions with the [other] one. */
private operator fun Cuboid.minus(other: Cuboid): Set<Cuboid> = when {
this intersect other == null -> setOf(this)
else -> buildSet {
"XYZ".fold(this@minus) { remaining, axis ->
val (left, middle, right) = remaining.split(axis, other[axis])
if (left != null) add(left)
if (right != null) add(right)
middle ?: return@buildSet
}
}
}
/** Returns the [Cuboid] that is defined by the intersection of this and the [other], or `null` if they do not. */
private infix fun Cuboid.intersect(other: Cuboid): Cuboid? = Cuboid.of(
xRange = maxOf(xRange.first, other.xRange.first)..minOf(xRange.last, other.xRange.last),
yRange = maxOf(yRange.first, other.yRange.first)..minOf(yRange.last, other.yRange.last),
zRange = maxOf(zRange.first, other.zRange.first)..minOf(zRange.last, other.zRange.last),
)
/** A submarine core boot-up sequence. */
private data class Step(val turnOn: Boolean, val region: Cuboid) {
/** Returns whether this step executes entirely within the initialization region. */
val isInsideInitializationRegion: Boolean
get() = with(region) {
xRange.first >= -50 && xRange.last <= 50
&& yRange.first >= -50 && yRange.last <= 50
&& zRange.first >= -50 && zRange.last <= 50
}
}
/**
* Execute the submarine core boot up sequence following the [steps] and returns all [Cuboid] regions where the
* reactor cubes are turned on.
*/
private fun coreBootUpSequence(steps: Iterable<Step>): Set<Cuboid> = steps.fold(emptySet()) { cuboids, step ->
val (turnOn, region) = step
buildSet {
cuboids.forEach { cuboid -> addAll(cuboid - region) }
if (turnOn) add(region)
}
}
/** Parse the [input] and return the sequence of boot-up [Step]s for the submarine's core. */
private fun parseInput(input: String): Sequence<Step> {
val stepRegex = Regex("""^(on|off) x=(-?\d+)\.\.(-?\d+),y=(-?\d+)\.\.(-?\d+),z=(-?\d+)\.\.(-?\d+)$""")
return input
.lineSequence()
.map { stepRegex.matchEntire(it)?.destructured ?: throw IllegalArgumentException("Invalid input.") }
.map { (turn, xl, xh, yl, yh, zl, zh) ->
Step(
turnOn = turn == "on",
region = Cuboid(xl.toLong()..xh.toLong(), yl.toLong()..yh.toLong(), zl.toLong()..zh.toLong())
)
}
}
override fun partOne(input: String) = parseInput(input)
.filter { it.isInsideInitializationRegion }
.let { coreBootUpSequence(it.asIterable()) }
.sumOf { it.volume }
override fun partTwo(input: String) = coreBootUpSequence(parseInput(input).asIterable()).sumOf { it.volume }
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 5,520 | advent-of-code-kotlin-solutions | The Unlicense |
2016/src/main/java/p2/Problem2.kt | ununhexium | 113,359,669 | false | null | package p2
import com.google.common.io.Resources
import more.Input
import p1.Direction
import p1.Direction.DOWN
import p1.Direction.LEFT
import p1.Direction.RIGHT
import p1.Direction.UP
import kotlin.math.max
import kotlin.math.min
val keypad = listOf(
listOf(1, 2, 3),
listOf(4, 5, 6),
listOf(7, 8, 9)
).map { it.map { ('0'.toInt() + it).toChar() } }
val stupidPad = listOf(
listOf(' ', ' ', '1', ' ', ' '),
listOf(' ', '2', '3', '4', ' '),
listOf('5', '6', '7', '8', '9'),
listOf(' ', 'A', 'B', 'C', ' '),
listOf(' ', ' ', 'D', ' ', ' ')
)
data class Position(
private val x: Int,
private val y: Int,
private val pad: List<List<Char>>
)
{
fun move(
direction: Direction
): Position
{
val xMax = pad[0].size - 1
val yMax = pad.size - 1
return conditionalMove(
when (direction)
{
UP -> Position(x, max(0, y - 1), pad)
DOWN -> Position(x, min(yMax, y + 1), pad)
LEFT -> Position(max(0, x - 1), y, pad)
RIGHT -> Position(min(xMax, x + 1), y, pad)
}
)
}
private fun conditionalMove(position: Position) =
if (position.asKeyCode() == ' ') this else position
fun asKeyCode() = pad[y][x]
}
fun main(args: Array<String>)
{
val steps = Input.getFor("p2")
.split("\n")
.map { it.map { Direction.from(it) } }
val code = findCode(steps, keypad, '5')
println(code)
println(findCode(steps, stupidPad, '5'))
}
fun findCode(
steps: List<List<Direction>>,
pad: List<List<Char>>,
startingKey: Char
): String
{
return steps
.fold(listOf<Position>()) { code, line ->
val startingButton = code.lastOrNull() ?: findKey(startingKey, pad)
val digit = line.fold(startingButton) { position, direction ->
position.move(direction)
}
code + digit
}
.map { it.asKeyCode() }
.joinToString(separator = "")
}
fun findKey(key: Char, pad: List<List<Char>>): Position
{
val button = pad.
mapIndexed { y, list ->
list.mapIndexed { x, c ->
Triple(x, y, c)
}
}
.flatten()
.first { it.third == key }
return Position(button.first, button.second, pad)
}
| 6 | Kotlin | 0 | 0 | d5c38e55b9574137ed6b351a64f80d764e7e61a9 | 2,232 | adventofcode | The Unlicense |
src/Day12.kt | Tomcat88 | 572,566,485 | false | {"Kotlin": 52372} | import java.util.Stack
object Day12 {
@JvmStatic
fun main(args: Array<String>) {
fun part1(grid: List<List<GridLetter>>) {
val visited = mutableSetOf<GridLetter>()
val start = grid.column(0).first { it.c == 'S' }
var currList = setOf(start)
var step = 0
while (true) {
visited.addAll(currList)
if (currList.any { it.c == 'z' + 1 }) {
break
}
currList = currList.flatMap { curr ->
setOfNotNull(curr.up, curr.down, curr.left, curr.right)
.filterNot { visited.contains(it) }
.filterIsInstance<GridLetter>().filterNot { it.c == 'S' }
.filter { nv -> curr.c == 'S' || nv.c - curr.c == 1 || curr.c >= nv.c }
}.toSet()
// grid.forEach {
// it.map { if (visited.contains(it)) "█" else it.c }.forEach { print(it) }
// println()
// }
step++
}
step.log("part1")
}
fun part2(grid: List<List<GridLetter>>) {
val visited = mutableSetOf<GridLetter>()
val start = grid.flatMap { it.filter { it.c == 'a' } }
var currList = start.toSet()
var step = 0
while (true) {
visited.addAll(currList)
if (currList.any { it.c == 'z' + 1 }) {
break
}
currList = currList.flatMap { curr ->
setOfNotNull(curr.up, curr.down, curr.left, curr.right)
.filterNot { visited.contains(it) }
.filterIsInstance<GridLetter>().filterNot { it.c == 'S' }
.filter { nv -> curr.c == 'S' || nv.c - curr.c == 1 || curr.c >= nv.c }
}.toSet()
// grid.forEach {
// it.map { if (visited.contains(it)) "█" else it.c }.forEach { print(it) }
// println()
// }
step++
}
step.log("part2")
}
val input = downloadAndReadInput("Day12", "\n").filter { it.isNotBlank() }.map { it.replace('E', 'z' + 1).toCharArray().toList()}
val map = mutableMapOf<Point, GridLetter>()
val grid = input.mapIndexed { y, row ->
row.mapIndexed { x, c ->
val point = Point(x, y)
val l = map[point] ?: GridLetter(c, point)
map[point] = l
listOf(Up, Down, Right, Left).map { move ->
if (point.canMove(move, input)) {
val moved = point.move(move)
val movedGridLetter: GridLetter = map[moved] ?: GridLetter(input.getPoint(moved), moved)
l.set(move, movedGridLetter)
map[moved] = movedGridLetter
movedGridLetter
}
}
l
}
}
// grid.forEach {
// it.forEach { print(it.c) }
// println()
// }
part1(grid)
part2(grid)
}
data class GridLetter(
val c: Char, val p: Point,
var up: GridLetter? = null,
var down: GridLetter? = null,
var left: GridLetter? = null,
var right: GridLetter? = null) {
fun set(mvmt: Move, l: GridLetter) {
when(mvmt) {
Down -> down = l
Left -> left = l
Right -> right = l
Up -> up = l
}
}
override fun toString(): String {
return "GridLetter(c=$c, p=$p)"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is GridLetter) return false
if (c != other.c) return false
if (p != other.p) return false
return true
}
override fun hashCode(): Int {
var result = c.hashCode()
result = 31 * result + p.hashCode()
return result
}
}
private fun Grid.getPoint(p: Point): Char {
return this[p.y][p.x]
}
data class Point(var x: Int, var y: Int) {
fun canMove(mvmt: Move, grid: Grid): Boolean {
return when (mvmt) {
is Down -> y < grid.size -1
is Left -> x >= 1
is Right -> x < grid[0].size -1
is Up -> y >= 1
}
}
fun move(mvmt: Move): Point {
return when(mvmt) {
is Down -> Point(x,y + 1)
is Left -> Point(x - 1, y)
is Right -> Point(x + 1, y)
is Up -> Point(x, y - 1)
}
}
}
sealed interface Move
object Up : Move
object Down : Move
object Left : Move
object Right : Move
}
typealias Grid = List<List<Char>>
| 0 | Kotlin | 0 | 0 | 6d95882887128c322d46cbf975b283e4a985f74f | 5,071 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/g1401_1500/s1420_build_array_where_you_can_find_the_maximum_exactly_k_comparisons/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1401_1500.s1420_build_array_where_you_can_find_the_maximum_exactly_k_comparisons
// #Hard #Dynamic_Programming #2023_06_07_Time_153_ms_(100.00%)_Space_36.8_MB_(100.00%)
class Solution {
fun numOfArrays(n: Int, m: Int, k: Int): Int {
var ways = Array(m + 1) { LongArray(k + 1) }
var sums = Array(m + 1) { LongArray(k + 1) }
for (max in 1..m) {
ways[max][1] = 1
sums[max][1] = ways[max][1] + sums[max - 1][1]
}
for (count in 2..n) {
val ways2 = Array(m + 1) { LongArray(k + 1) }
val sums2 = Array(m + 1) { LongArray(k + 1) }
for (max in 1..m) {
for (cost in 1..k) {
val noCost = max * ways[max][cost] % MOD
val newCost = sums[max - 1][cost - 1]
ways2[max][cost] = (noCost + newCost) % MOD
sums2[max][cost] = (sums2[max - 1][cost] + ways2[max][cost]) % MOD
}
}
ways = ways2
sums = sums2
}
return sums[m][k].toInt()
}
companion object {
private const val MOD = 1000000007
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,172 | LeetCode-in-Kotlin | MIT License |
Kotlin for Java Developers. Week 4/Rationals/Task/src/rationals/Rational.kt | vnay | 251,709,901 | false | null | package rationals
import java.math.BigInteger
infix fun Int.divBy(r: Int): Rational =
Rational(toBigInteger(), r.toBigInteger())
infix fun Long.divBy(r: Long): Rational =
Rational(toBigInteger(), r.toBigInteger())
infix fun BigInteger.divBy(r: BigInteger): Rational =
Rational(this, r)
fun String.toRational(): Rational {
val number = split("/")
return when {
number.size == 1 -> Rational(number[0].toBigInteger(), 1.toBigInteger())
else -> Rational(number[0].toBigInteger(), number[1].toBigInteger())
}
}
fun hcf(n1: BigInteger, n2: BigInteger): BigInteger =
if(n2 != 0.toBigInteger()) hcf(n2, n1 % n2) else n1
fun simplify(r: Rational): Rational {
val hcf = hcf(r.n, r.d).abs()
return Rational(r.n.div(hcf), r.d.div(hcf))
}
fun formatRational(r: Rational): String =
r.n.toString() + "/" + r.d.toString()
class Rational(val n: BigInteger, val d: BigInteger) : Comparable<Rational> {
operator fun plus(r: Rational): Rational =
(n.times(r.d).plus(r.n.times(d))).divBy(r.d.times(d))
operator fun minus(r: Rational): Rational =
(n.times(r.d).minus(r.n.times(d))).divBy(r.d.times(d))
operator fun times(r: Rational): Rational =
(n.times(r.n)).divBy(r.d.times(d))
operator fun div(r: Rational): Rational =
(n.times(r.d)).divBy(d.times(r.n))
operator fun unaryMinus(): Rational =
Rational(n.negate(), d)
override fun compareTo(other: Rational): Int =
n.times(other.d).compareTo(other.n.times(d))
override fun equals(other: Any?): Boolean {
if(this === other) return true
other as Rational
val thisN = simplify(this)
val otherN = simplify(other)
return (thisN.n.toDouble().div(thisN.d.toDouble())) == (otherN.n.toDouble().div(otherN.d.toDouble()))
}
override fun toString(): String {
return when {
(d == 1.toBigInteger() || n.rem(d) == 0.toBigInteger()) -> n.div(d).toString()
else -> {
val r = simplify(this)
if(r.d < 0.toBigInteger() || (r.n < 0.toBigInteger() && r.d < 0.toBigInteger())) {
formatRational(Rational(r.n.negate(), r.d.negate()))
}
else {
formatRational(Rational(r.n, r.d))
}
}
}
}
override fun hashCode(): Int {
var result = n.hashCode()
result = 31 * result + d.hashCode()
return result
}
}
fun main() {
val half = 1 divBy 2
val third = 1 divBy 3
val sum: Rational = half + third
println(5 divBy 6 == sum)
val difference: Rational = half - third
println(1 divBy 6 == difference)
val product: Rational = half * third
println(1 divBy 6 == product)
val quotient: Rational = half / third
println(3 divBy 2 == quotient)
val negation: Rational = -half
println(-1 divBy 2 == negation)
println((2 divBy 1).toString() == "2")
println((-2 divBy 4).toString() == "-1/2")
println("117/1098".toRational().toString() == "13/122")
val twoThirds = 2 divBy 3
println(half < twoThirds)
println(half in third..twoThirds)
println(2000000000L divBy 4000000000L == 1 divBy 2)
println("912016490186296920119201192141970416029".toBigInteger() divBy
"1824032980372593840238402384283940832058".toBigInteger() == 1 divBy 2)
} | 0 | Kotlin | 0 | 0 | ce638b0272bd5fac80891a669cd17848bf6d0721 | 3,462 | Kotlin-for-Java-Developers | MIT License |
src/Day11.kt | Kietyo | 573,293,671 | false | {"Kotlin": 147083} | import java.math.BigInteger
import kotlin.math.absoluteValue
import kotlin.math.min
import kotlin.math.pow
import kotlin.math.roundToInt
import kotlin.math.sign
import kotlin.math.sqrt
fun main() {
data class Monkey(
val items: MutableList<BigInteger>,
val op: (old: BigInteger) -> BigInteger,
val testDivisibleNum: BigInteger,
val testMonkeyTrue: Int,
val testMonkeyFalse: Int,
var numItemsInspected: Long = 0
)
fun parseMonkeys(input: List<String>): MutableList<Monkey> {
println(input)
val seq = input.iterator()
val monkeys = mutableListOf<Monkey>()
while (seq.hasNext()) {
seq.next() // monkey line
val items = seq.next().split(" ", limit = 5).last().split(", ").map { it.toBigInteger() }.toMutableList()
println(items)
val opSplit = seq.next().split(" ", limit = 4).last().split(" ")
println(opSplit)
val data = opSplit[4]
val opFn = when (opSplit[3]) {
"*" -> {it: BigInteger -> it * when (data) {
"old" -> it
else -> data.toBigInteger()
} }
"+" -> {it: BigInteger -> it + data.toBigInteger()}
else -> TODO()
}
val testDivisibleNum = seq.next().split(" ", limit = 6).last().toBigInteger()
val testMonkeyTrue = seq.next().split(" ").last().toInt()
val testMonkeyFalse = seq.next().split(" ").last().toInt()
val monkey = Monkey(items, opFn, testDivisibleNum, testMonkeyTrue, testMonkeyFalse)
monkeys.add(monkey)
println(monkey)
seq.next() // Eat new line
}
println("Done parsing monkeys")
return monkeys
}
fun part1(input: List<String>): Unit {
val monkeys = parseMonkeys(input)
fun runRound() {
monkeys.forEach { monkey ->
monkey.items.forEach {
val worryLevelStep1 = monkey.op(it)
val worryLevelStep2 = (worryLevelStep1 / BigInteger("3"))
if (worryLevelStep2 % monkey.testDivisibleNum == BigInteger.ZERO) {
monkeys[monkey.testMonkeyTrue].items.add(worryLevelStep2)
} else {
monkeys[monkey.testMonkeyFalse].items.add(worryLevelStep2)
}
monkey.numItemsInspected++
}
monkey.items.clear()
}
println(monkeys.joinToString("\n"))
}
repeat(20) {
runRound()
println()
}
println(monkeys.map { it.numItemsInspected }.sorted().takeLast(2).reduce { acc, i -> acc * i })
}
fun part2(input: List<String>): Unit {
val monkeys = parseMonkeys(input)
val blah = monkeys.map { it.testDivisibleNum }.reduce { acc, bigInteger -> acc * bigInteger }
fun runRound() {
monkeys.forEach { monkey ->
monkey.items.forEach {
val worryLevelStep1 = monkey.op(it)
val worryLevelStep2 = worryLevelStep1 % blah
if (worryLevelStep2 % monkey.testDivisibleNum == BigInteger.ZERO) {
monkeys[monkey.testMonkeyTrue].items.add(worryLevelStep2)
} else {
monkeys[monkey.testMonkeyFalse].items.add(worryLevelStep2)
}
monkey.numItemsInspected++
}
monkey.items.clear()
}
// println(monkeys.joinToString("\n"))
}
repeat(10000) {
runRound()
println(it)
}
println(monkeys.map { it.numItemsInspected }.sorted().takeLast(2).reduce { acc, i -> acc * i })
}
val dayString = "day11"
// test if implementation meets criteria from the description, like:
val testInput = readInput("${dayString}_test")
// part1(testInput)
// part2(testInput)
val input = readInput("${dayString}_input")
// part1(input)
part2(input)
}
| 0 | Kotlin | 0 | 0 | dd5deef8fa48011aeb3834efec9a0a1826328f2e | 4,203 | advent-of-code-2022-kietyo | Apache License 2.0 |
src/main/kotlin/com/nibado/projects/advent/y2018/Day15.kt | nielsutrecht | 47,550,570 | false | null | package com.nibado.projects.advent.y2018
import com.nibado.projects.advent.Day
import com.nibado.projects.advent.Point
import com.nibado.projects.advent.collect.CharMap
import com.nibado.projects.advent.resourceLines
object Day15 : Day {
val input = resourceLines(2018, 17)
fun log(s: String) {
//println(s)
}
data class Entity(val type: Char, var pos: Point, var hitpoints: Int = 200) {
val power = 3
fun turn(grid: Grid): Boolean {
if(hitpoints <= 0) {
return false
}
//Each unit begins its turn by identifying all possible targets (enemy units).
// If no targets remain, combat ends.
val targets = grid.entities().filter(::isTarget)
if (targets.isEmpty()) {
return true
}
val targetSquares = targets.map { it to grid.squaresFor(it) }.filter { it.second.isNotEmpty() }
.flatMap { it.second }
val inRange = targetSquares.filter { it.neighborsHv().contains(it) }.sorted()
if(inRange.isEmpty()) {
log(grid.toString(targetSquares.toSet(), '?'))
val paths = targetSquares.map { it to grid.search(pos, it) }
.filterNot { it.second.isEmpty() }
log(grid.toString(paths.map { it.first }.toSet(), '@'))
if(paths.isNotEmpty()) {
val minDistance = paths.minByOrNull { it.second.size }!!.second.size
val closest = paths.filter { it.second.size == minDistance }
log(grid.toString(closest.map { it.first }.toSet(), '!'))
val chosen = closest.sortedBy { it.first }
log(grid.toString(setOf(chosen.first().first), '+'))
if(chosen.isNotEmpty()) {
val nextStep = chosen.first().second[1]
grid.move(this, nextStep)
}
log(grid.toString())
}
}
attack(grid)
return false
}
private fun attack(grid: Grid) {
val targets = grid.entities().filter(::isTarget)
val targetSquares = targets.map { it to grid.squaresFor(it) }.filter { it.second.isNotEmpty() }
.flatMap { it.second }
val inRange = targetSquares.filter { it.neighborsHv().contains(it) }.sorted()
val select = inRange.map { grid.entities[it]!! }.filter { it.type != type }.sortedBy { it.hitpoints }.sortedBy { it.pos }
if(select.isNotEmpty()) {
select.first().hitpoints -= power
}
}
fun isTarget(entity: Entity) = entity.hitpoints > 0 && entity.type != this.type
}
class Grid(val grid: CharMap, val entities: MutableMap<Point, Entity>) {
val points = grid.points()
val openPoints = points.filter { get(it) == '.' }.toSet()
override fun toString() = toString(emptySet())
fun toString(other: Set<Point>, otherChar: Char = ' '): String {
val build = StringBuilder(grid.width * grid.height)
for (y in 0 until grid.height) {
for (x in 0 until grid.width) {
val p = Point(x, y)
val c = if (other.contains(p)) {
otherChar
} else {
entities[p]?.type ?: get(p)
}
build.append(c)
}
build.append('\n')
}
return build.toString()
}
fun inBounds(p: Point) = grid.inBounds(p)
fun squaresFor(e: Entity) = e.pos.neighborsHv().filter { openPoints.contains(it) }.filterNot { entities.keys.contains(it) }
fun entities() = points.mapNotNull { entities[it] }
fun get(p: Point) = grid[p]
fun impassable(p: Point) = entities.keys.contains(p) || get(p) == '#'
fun move(e: Entity, to: Point) {
entities.remove(e.pos)
entities[to] = e
e.pos = to
}
fun search(from: Point, to: Point): List<Point> {
val frontier = mutableSetOf<Point>()
val cameFrom = mutableMapOf<Point, Point>()
frontier += from
while (frontier.isNotEmpty()) {
val current = frontier.firstOrNull()!!
frontier -= current
val next = current.neighborsHv()
.sorted()
.filter { inBounds(it) }
.filterNot { cameFrom.containsKey(it) }
.filterNot { impassable(it) }
frontier += next
next.forEach { cameFrom[it] = current }
if (cameFrom.containsKey(to)) {
break
}
}
if (!cameFrom.containsKey(to)) {
return listOf()
}
var current = to
val path = mutableListOf(to)
while (current != from) {
current = cameFrom[current]!!
path += current
}
path.reverse()
return path
}
}
fun read(input: List<String>): Grid {
val entities = input.mapIndexed { y, s ->
s.mapIndexed { x, c -> Point(x, y) to c }
.filter { it.second == 'E' || it.second == 'G' }
}
.flatten()
.map { Entity(it.second, it.first) }
val map = CharMap.from(input.map { it.map { if (it == 'G' || it == 'E') '.' else it }.joinToString("") })
return Grid(map, entities.map { it.pos to it }.toMap().toMutableMap())
}
override fun part1(): String {
val grid = read(Inputs.INPUT_4)
println(grid)
for(i in 1 .. 3) {
for(p in grid.points) {
grid.entities[p]?.turn(grid)
}
println(grid)
}
return ""
}
override fun part2(): Int {
return 0
}
}
fun main(args: Array<String>) {
println(Day15.part1())
}
object Inputs {
val INPUT_0 = """
#######
#E..G.#
#...#.#
#.G.#G#
#######
""".split("\n").filterNot { it.trim().isEmpty() }
val INPUT_1 = """
#######
#.E...#
#.....#
#...G.#
#######
""".split("\n").filterNot { it.trim().isEmpty() }
val INPUT_2 = """
#######
#G..#E#
#E#E.E#
#G.##.#
#...#E#
#...E.#
#######""".split("\n").filterNot { it.trim().isEmpty() }
val INPUT_4 = """
#########
#G..G..G#
#.......#
#.......#
#G..E..G#
#.......#
#.......#
#G..G..G#
#########
""".split("\n").filterNot { it.trim().isEmpty() }
} | 1 | Kotlin | 0 | 15 | b4221cdd75e07b2860abf6cdc27c165b979aa1c7 | 6,777 | adventofcode | MIT License |
src/main/kotlin/_2022/Day16.kt | novikmisha | 572,840,526 | false | {"Kotlin": 145780} | package _2022
import readInput
fun main() {
fun findDistances(
valveMap: Map<String, WaterNode>,
startNode: String,
toVisit: Set<String>
): Map<String, Int> {
if (toVisit.isEmpty()) {
return emptyMap()
}
val start = valveMap[startNode]!!
val queue = mutableListOf(start)
val distanceMap = mutableMapOf(start.name to 0)
while (queue.isNotEmpty()) {
val currentNode = queue.removeFirst()
val toVisitFromCurrent = currentNode.child
for (child in toVisitFromCurrent) {
val currentDistance = distanceMap.getOrDefault(child, Int.MAX_VALUE)
val newDistance = distanceMap[currentNode.name]!! + 1
if (newDistance < currentDistance) {
distanceMap[child] = newDistance
val childNode = valveMap[child]!!
queue.remove(childNode)
queue.add(childNode)
queue.sortBy { distanceMap[it.name]!! }
}
}
}
return distanceMap
}
fun buildValveMap(input: List<String>) = input.associate {
val (flowString, childStrings) = it.split(";")
val flowStringSplitted = flowString.split(" ")
val name = flowStringSplitted[1]
val flowRate = flowStringSplitted[4].replace("rate=", "").toInt()
val child = childStrings.replace("tunnels lead to valves", "")
.replace("tunnel leads to valve", "")
.split(",")
.map { str ->
str.trim()
}
name to WaterNode(name, flowRate, false, child)
}
fun dfs(
valveMap: Map<String, WaterNode>, stepsLeft: Int,
currentNode: String,
flowRate: Int,
results: MutableSet<Pair<Int, Set<String>>>,
toVisit: MutableSet<String>
) {
if (stepsLeft < 1) {
results.add(Pair(flowRate, toVisit))
return
}
var currentSteps = stepsLeft
var currentFlowRate = flowRate
val node = valveMap[currentNode]!!
if (node.flowRate > 0) {
currentSteps -= 1
val releasedPressure = (node.flowRate * currentSteps)
currentFlowRate += releasedPressure
}
toVisit.remove(node.name)
if (toVisit.isEmpty()) {
results.add(Pair(currentFlowRate, toVisit))
return
}
if (currentSteps < 1) {
results.add(Pair(currentFlowRate, toVisit))
return
}
val distanceMap = findDistances(valveMap, currentNode, toVisit)
for (nextNode in toVisit) {
val distance = distanceMap[nextNode]!!
if (distance >= currentSteps + 1) {
continue
}
dfs(
valveMap,
currentSteps - distance,
nextNode,
currentFlowRate,
results,
toVisit.toMutableSet()
)
}
}
fun part1(input: List<String>): Int {
val valveMap = buildValveMap(input)
val results = mutableSetOf<Pair<Int, Set<String>>>()
val toVisit = valveMap.filter { it.value.flowRate > 0 }.keys.toMutableSet()
dfs(valveMap, 30, "AA", 0, results, toVisit)
return results.maxBy { it.first }.first
}
fun part2(input: List<String>): Int {
val valveMap = buildValveMap(input)
var results = mutableSetOf<Pair<Int, Set<String>>>()
val toVisit = valveMap.filter { it.value.flowRate > 0 }.keys.toMutableSet()
dfs(valveMap, 26, "AA", 0, results, toVisit)
val resultList = results.toList()
var maxSize = 0
for (i in 0 until resultList.size - 1) {
for (j in i + 1 until resultList.size) {
val sum = resultList[i].first + resultList[j].first
if (sum > maxSize) {
val visitedHuman = toVisit.toMutableSet()
visitedHuman.removeAll(resultList[i].second)
val visitedElephans = toVisit.toMutableSet()
visitedElephans.removeAll(resultList[j].second)
if (visitedHuman.intersect(visitedElephans).isEmpty()) {
maxSize = sum
}
}
}
}
return maxSize
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day16_test")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day16")
println(part1(input))
println(part2(input))
}
data class WaterNode(
var name: String, var flowRate: Int, var isOpened: Boolean, val child: List<String>,
)
| 0 | Kotlin | 0 | 0 | 0c78596d46f3a8bf977bf356019ea9940ee04c88 | 4,854 | advent-of-code | Apache License 2.0 |
src/net/sheltem/aoc/y2023/Day24.kt | jtheegarten | 572,901,679 | false | {"Kotlin": 178521} | package net.sheltem.aoc.y2023
suspend fun main() {
Day24().run()
}
class Day24 : Day<Long>(0, 47) {
override suspend fun part1(input: List<String>) = input.map { it.toHailstone() }.intersections()
override suspend fun part2(input: List<String>) = input.map { it.toHailstone() }.findStone()
}
private fun List<Hailstone>.findStone(): Long {
val h1 = this@findStone[0]
val h2 = this@findStone[1]
val testSpeeds = 350 downTo -350L
testSpeeds.forEach { dx ->
testSpeeds.forEach { dy ->
testSpeeds.forEach { dz ->
if (dx != 0L && dy != 0L && dz != 0L) {
val A: Long = h1.pos.x
val a: Long = h1.speed.dx - dx
val B: Long = h1.pos.y
val b: Long = h1.speed.dy - dy
val C: Long = h2.pos.x
val c: Long = h2.speed.dx - dx
val D: Long = h2.pos.y
val d: Long = h2.speed.dy - dy
if (c != 0L && (a * d) - (b * c) != 0L) {
val t = (d * (C - A) - c * (D - B)) / ((a * d) - (b * c))
val x = h1.pos.x + h1.speed.dx * t - dx * t
val y = h1.pos.y + h1.speed.dy * t - dy * t
val z = h1.pos.z + h1.speed.dz * t - dz * t
val hitall = this@findStone.none { h ->
val u = when {
h.speed.dx.toLong() != dx -> (x - h.pos.x) / (h.speed.dx - dx)
h.speed.dy.toLong() != dy -> (y - h.pos.y) / (h.speed.dy - dy)
h.speed.dz.toLong() != dz -> (z - h.pos.z) / (h.speed.dz - dz)
else -> TODO()
}
(x + u * dx != h.pos.x + u * h.speed.dx)
|| (y + u * dy != h.pos.y + u * h.speed.dy)
|| (z + u * dz != h.pos.z + u * h.speed.dz)
}
if (hitall) return x + y + z
}
}
}
}
}
TODO()
}
private fun List<Hailstone>.intersections(minTime: Long = 200000000000000, maxTime: Long = 400000000000000): Long {
val checked = mutableSetOf<Hailstone>()
return this.sumOf { stone ->
checked.add(stone)
(this - checked).count { other ->
stone.intersects(other, minTime, maxTime)
}.toLong()
}
}
private fun String.toHailstone(): Hailstone = split(" @ ").let { (position, speed) ->
val pos = position.replace(" ", "").split(",").map { it.toLong() }.let { (x, y, z) -> Position3D(x, y, z) }
val vec = speed.replace(" ", "").split(",").map { it.toInt() }.let { (dx, dy, dz) -> Vector(dx, dy, dz) }
Hailstone(pos, vec)
}
data class Hailstone(val pos: Position3D, val speed: Vector) {
private val slope = speed.dy.toDouble() / speed.dx.toDouble()
fun intersects(other: Hailstone, minTime: Long, maxTime: Long): Boolean {
val stoneSlope = this.slope
val otherSlope = other.slope
val commonX = ((otherSlope * other.pos.x) - (stoneSlope * this.pos.x) + this.pos.y - other.pos.y) / (otherSlope - stoneSlope)
val commonY = (stoneSlope * (commonX - this.pos.x)) + this.pos.y
return commonX > minTime && commonX < maxTime && commonY > minTime && commonY < maxTime && this.project(commonX, commonY) && other.project(
commonX,
commonY
)
}
fun fullIntersects(other: Hailstone, minTime: Long, maxTime: Long): Boolean =
this.intersects(other, minTime, maxTime)
&& this.rotate().intersects(other.rotate(), minTime, maxTime)
&& this.rotate().rotate().intersects(other.rotate().rotate(), minTime, maxTime)
private fun rotate(): Hailstone = Hailstone(pos.rotate(), speed.rotate())
private fun project(futureX: Double, futureY: Double) =
!(speed.dx < 0 && pos.x < futureX
|| speed.dx > 0 && pos.x > futureX
|| speed.dy < 0 && pos.y < futureY
|| speed.dy > 0 && pos.y > futureY)
}
data class Position3D(val x: Long, val y: Long, val z: Long) {
constructor(x: Int, y: Int, z: Int) : this(x.toLong(), y.toLong(), z.toLong())
fun rotate(): Position3D = Position3D(z, x, y)
}
data class Vector(val dx: Int, val dy: Int, val dz: Int) {
fun rotate(): Vector = Vector(dz, dx, dy)
}
| 0 | Kotlin | 0 | 0 | ac280f156c284c23565fba5810483dd1cd8a931f | 4,538 | aoc | Apache License 2.0 |
codeforces/round614/c.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.round614
fun main() {
val n = readInt()
val nei = List(n) { mutableListOf<Int>() }
repeat(n - 1) {
val (a, b) = readInts().map { it - 1 }
nei[a].add(b); nei[b].add(a)
}
val par = List(n) { IntArray(n) { 0 } }
val count = List(n) { IntArray(n) { 1 } }
for (root in nei.indices) {
fun dfs(u: Int, p: Int) {
par[root][u] = p
for (v in nei[u]) if (v != p) {
dfs(v, u)
count[root][u] += count[root][v]
}
}
dfs(root, -1)
}
val a = List(n) { LongArray(n) { -1 } }
fun solve(u: Int, v: Int): Long {
if (u == v) return 0
if (a[u][v] == -1L) a[u][v] = maxOf(solve(par[v][u], v), solve(u, par[u][v])) + count[v][u] * count[u][v]
return a[u][v]
}
println(nei.indices.map { u -> nei.indices.maxOf { v -> solve(u, v) } }.maxOrNull())
}
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 | 971 | competitions | The Unlicense |
jvm/src/main/kotlin/io/prfxn/aoc2021/day12.kt | prfxn | 435,386,161 | false | {"Kotlin": 72820, "Python": 362} | // Passage Pathing (https://adventofcode.com/2021/day/12)
package io.prfxn.aoc2021
fun main() {
val connections = textResourceReader("input/12.txt").readLines().map { ln ->
with (ln.split("-")) {
first() to last()
}
}
fun getNumPaths(pathSoFar: MutableList<String>, destination: String, nextFilter: (List<String>, String) -> Boolean): Int {
val last = pathSoFar.last()
if (last == destination) return 1
return connections.asSequence()
.map { c ->
when (last) {
c.first -> c.second
c.second -> c.first
else -> null
}
}
.filterNotNull()
.filter { next -> nextFilter(pathSoFar, next) }
.sumOf { next ->
pathSoFar.add(next)
getNumPaths(pathSoFar, destination, nextFilter)
.also { pathSoFar.removeLast() }
}
}
fun getNumPaths(start: String, end: String, nextFilter: (List<String>, String) -> Boolean) =
getNumPaths(mutableListOf(start), end, nextFilter)
val answer1 =
getNumPaths("start", "end") { pathSoFar, next ->
when (next) {
next.lowercase() -> next !in pathSoFar
else -> true
}
}
val answer2 =
getNumPaths("start", "end") { pathSoFar, next ->
when (next) {
"start" -> false
next.lowercase() -> {
next !in pathSoFar ||
pathSoFar.filter { it.lowercase() == it }.groupBy { it }.all { it.value.size < 2 }
}
else -> true
}
}
sequenceOf(answer1, answer2).forEach(::println)
}
/** output
* 4304
* 118242
*/
| 0 | Kotlin | 0 | 0 | 148938cab8656d3fbfdfe6c68256fa5ba3b47b90 | 1,845 | aoc2021 | MIT License |
src/day10/Day10.kt | ayukatawago | 572,742,437 | false | {"Kotlin": 58880} | package day10
import readInput
import java.util.LinkedList
fun main() {
fun part1(instructions: List<Instruction>): Int {
var signalStrength = 0
var register = 1
var cycle = 0
val queue = LinkedList<Instruction>()
queue.addAll(instructions)
var nexeCheckCycle = 20
var storedInstruction: Instruction.AddX? = null
while (queue.isNotEmpty() || storedInstruction != null) {
cycle++
if (storedInstruction == null) {
val instruction = queue.removeFirst()
if (instruction is Instruction.AddX) {
storedInstruction = instruction
}
} else {
register += storedInstruction.value
storedInstruction = null
}
if (cycle == nexeCheckCycle - 1) {
val strength = nexeCheckCycle * register
println("### [$cycle] $nexeCheckCycle $register -> $strength")
signalStrength += nexeCheckCycle * register
nexeCheckCycle += 40
}
println("[$cycle] $register")
}
return signalStrength
}
fun part2(instructions: List<Instruction>): List<String> {
val answer = mutableListOf<String>()
var register = 1
var cycle = 0
val queue = LinkedList<Instruction>()
queue.addAll(instructions)
val row = CharArray(40) { '.' }
var storedInstruction: Instruction.AddX? = null
var spriteRange = IntRange(0, 2)
while (queue.isNotEmpty() || storedInstruction != null) {
cycle++
row[(cycle - 1) % 40] = if ((cycle - 1) % 40 in spriteRange) {
'#'
} else {
'.'
}
if (storedInstruction == null) {
val instruction = queue.removeFirst()
if (instruction is Instruction.AddX) {
storedInstruction = instruction
}
} else {
register += storedInstruction!!.value
spriteRange = IntRange(register - 1, register + 1)
storedInstruction = null
}
if (cycle % 40 == 0) {
answer.add(row.joinToString(""))
}
}
return answer
}
val testInput = readInput("day10/test")
val instructions = testInput.mapNotNull {
when {
it == "noop" -> Instruction.Noop
it.startsWith("addx") -> Instruction.AddX(it.replace("addx ", "").toInt())
else -> null
}
}
println(part1(instructions))
part2(instructions).forEach {
println(it)
}
}
private sealed class Instruction {
class AddX(val value: Int) : Instruction()
object Noop : Instruction()
}
| 0 | Kotlin | 0 | 0 | 923f08f3de3cdd7baae3cb19b5e9cf3e46745b51 | 2,861 | advent-of-code-2022 | Apache License 2.0 |
Minimum_Operations_to_Reduce_X_to_Zero_v2.kt | xiekch | 166,329,519 | false | {"C++": 165148, "Java": 103273, "Kotlin": 97031, "Go": 40017, "Python": 22302, "TypeScript": 17514, "Swift": 6748, "Rust": 6579, "JavaScript": 4244, "Makefile": 349} | import kotlin.math.max
// [[Java] Detailed Explanation - O(N) Prefix Sum/Map - Longest Target Sub-Array](https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/discuss/935935/Java-Detailed-Explanation-O(N)-Prefix-SumMap-Longest-Target-Sub-Array )
class Solution {
fun minOperations(nums: IntArray, x: Int): Int {
var prefixSum = 0
val map = HashMap<Int, Int>()
map[0] = -1
var maxLength = -1
val target = nums.sum() - x
for (i in nums.indices) {
prefixSum += nums[i]
map[prefixSum] = i
if (map.containsKey(prefixSum - target)) {
maxLength = max(maxLength, i - map[prefixSum - target]!!)
}
}
return if (maxLength == -1) -1 else nums.size - maxLength
}
}
class TestCase(val nums: IntArray, val x: Int)
fun main() {
val solution = Solution()
val testCases = arrayOf(TestCase(intArrayOf(1, 1, 4, 2, 3), 5),
TestCase(intArrayOf(5, 6, 7, 8, 9), 4), TestCase(intArrayOf(3, 2, 20, 1, 1, 3), 10),
TestCase(intArrayOf(5, 2, 3, 1, 1), 5),
TestCase(intArrayOf(8828, 9581, 49, 9818, 9974, 9869, 9991, 10000, 10000, 10000, 9999, 9993, 9904, 8819, 1231, 6309),
134365))
for (case in testCases) {
println(solution.minOperations(case.nums, case.x))
}
} | 0 | C++ | 0 | 0 | eb5b6814e8ba0847f0b36aec9ab63bcf1bbbc134 | 1,368 | leetcode | MIT License |
src/day1/Day01.kt | blundell | 572,916,256 | false | {"Kotlin": 38491} | package day1
import readInput
fun main() {
fun collectElvesCalories(input: List<String>): Map<Int, List<String>> {
val caloriesByTotal = mutableMapOf<Int, List<String>>()
var elvesCalories = mutableListOf<String>()
var runningTotal = 0
for (calories in input) {
if (calories.isBlank()) {
caloriesByTotal[runningTotal] = elvesCalories
elvesCalories = mutableListOf()
runningTotal = 0
continue
}
runningTotal += calories.toInt()
elvesCalories.add(calories)
}
return caloriesByTotal
}
/**
* This list represents the Calories of the food carried by five Elves.
*
* In case the Elves get hungry and need extra snacks, they need to know which Elf to ask:
* they'd like to know how many Calories are being carried by the Elf carrying the most Calories.
*
* Find the Elf carrying the most Calories. How many total Calories is that Elf carrying?
*/
fun part1(input: List<String>): Int {
return collectElvesCalories(input).keys.max()
}
/**
* Find the top three Elves carrying the most Calories. How many Calories are those Elves carrying in total?
*/
fun part2(input: List<String>): Int {
return collectElvesCalories(input).keys
.sortedDescending()
.take(3)
.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day01/Day01_test")
check(part1(testInput) == 1000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f41982912e3eb10b270061db1f7fe3dcc1931902 | 1,701 | kotlin-advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day05/Day05.kt | daniilsjb | 572,664,294 | false | {"Kotlin": 69004} | package day05
import java.io.File
fun main() {
val data = parse("src/main/kotlin/day05/Day05.txt")
val answer1 = part1(data)
val answer2 = part2(data)
println("🎄 Day 05 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private data class Move(
val count: Int,
val from: Int,
val to: Int,
)
private data class Instructions(
val stacks: List<List<Char>>,
val moves: List<Move>,
)
@Suppress("SameParameterValue")
private fun parse(path: String): Instructions =
File(path).readLines().let { lines ->
val crates = lines
.filter { it.contains('[') }
.map { line -> line.chunked(4).map { it[1] } }
val stackCount = crates[0].size
val stacks = (0 until stackCount).map { i ->
crates.asReversed()
.map { it[i] }
.filter { it.isLetter() }
}
val moves = lines
.filter { it.startsWith("move") }
.map { line ->
val (count, from, to) = line
.split("""\D+""".toRegex())
.drop(1)
.map(String::toInt)
Move(count, from - 1, to - 1)
}
Instructions(stacks, moves)
}
private fun solve(instructions: Instructions, reverse: Boolean): String {
val (_stacks, moves) = instructions
val stacks = _stacks.map { it.toMutableList() }
for ((count, source, target) in moves) {
val crates = stacks[source].takeLast(count)
stacks[target].addAll(if (reverse) crates.asReversed() else crates)
repeat(count) {
stacks[source].removeLast()
}
}
return stacks
.map(List<Char>::last)
.joinToString(separator = "")
}
private fun part1(instructions: Instructions): String =
solve(instructions, reverse = true)
private fun part2(instructions: Instructions): String =
solve(instructions, reverse = false)
| 0 | Kotlin | 0 | 0 | 6f0d373bdbbcf6536608464a17a34363ea343036 | 2,057 | advent-of-code-2022 | MIT License |
2023/src/main/kotlin/Day14.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | object Day14 {
fun part1(input: String): Int {
val grid = input.splitNewlines()
// Calculates total load *as if* it were tilted north
return grid[0].indices.sumOf { x ->
var totalLoad = 0
var nextLoad = grid.size
grid.indices.forEach { y ->
when (grid[y][x]) {
'#' -> nextLoad = grid.size - y - 1
'O' -> totalLoad += nextLoad--
}
}
return@sumOf totalLoad
}
}
fun part2(input: String): Int {
var grid = input.splitNewlines()
val memo = mutableMapOf<List<String>, Int>()
val repetitions = 1000000000
repeat(repetitions) { iteration ->
val startOfCycle = memo[grid]
if (startOfCycle != null) {
val cycleSize = memo.size - startOfCycle
val cycleSpot = (repetitions - startOfCycle) % cycleSize
val position = startOfCycle + cycleSpot
return calculateTotalLoad(memo.entries.find { it.value == position }!!.key)
}
memo[grid] = iteration
grid = spinCycle(grid)
}
throw IllegalStateException("Did not find a cycle!")
}
// Repetitive, but it runs faster than tilt north + rotate 4 times
private fun spinCycle(grid: List<String>): List<String> {
val mutableGrid = grid.map { it.toCharArray() }.toTypedArray()
// Tilt North
mutableGrid[0].indices.forEach { x ->
var nextY = 0
mutableGrid.indices.forEach { y ->
when (mutableGrid[y][x]) {
'#' -> nextY = y + 1
'O' -> {
mutableGrid[y][x] = '.'
mutableGrid[nextY++][x] = 'O'
}
}
}
}
// Tilt West
mutableGrid.indices.forEach { y ->
var nextX = 0
mutableGrid[0].indices.forEach { x ->
when (mutableGrid[y][x]) {
'#' -> nextX = x + 1
'O' -> {
mutableGrid[y][x] = '.'
mutableGrid[y][nextX++] = 'O'
}
}
}
}
// Tilt South
mutableGrid[0].indices.forEach { x ->
var nextY = mutableGrid.size - 1
mutableGrid.indices.reversed().forEach { y ->
when (mutableGrid[y][x]) {
'#' -> nextY = y - 1
'O' -> {
mutableGrid[y][x] = '.'
mutableGrid[nextY--][x] = 'O'
}
}
}
}
// Tilt East
mutableGrid.indices.forEach { y ->
var nextX = mutableGrid[0].size - 1
mutableGrid[0].indices.reversed().forEach { x ->
when (mutableGrid[y][x]) {
'#' -> nextX = x - 1
'O' -> {
mutableGrid[y][x] = '.'
mutableGrid[y][nextX--] = 'O'
}
}
}
}
return mutableGrid.map { String(it) }
}
private fun calculateTotalLoad(grid: List<String>): Int {
return grid[0].indices
.sumOf { x ->
grid.indices
.filter { y -> grid[y][x] == 'O' }
.sumOf { y -> grid.size - y }
}
}
} | 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 2,908 | advent-of-code | MIT License |
src/main/kotlin/ca/kiaira/advent2023/day7/Day7.kt | kiairatech | 728,913,965 | false | {"Kotlin": 78110} | package ca.kiaira.advent2023.day7
import ca.kiaira.advent2023.Puzzle
/**
* Solution for Day 7 of the Advent of Code challenge.
* This class extends the Puzzle class and is specialized in handling poker hands.
*
* @author <NAME> <<EMAIL>>
* @since December 8th, 2023
*/
object Day7 : Puzzle<List<Day7.Hand>>(7) {
/**
* Parses the input into a list of Hand objects.
* Each line of the input represents a hand of poker cards with a bid.
*
* @param input The input data as a sequence of strings.
* @return A list of Hand objects.
*/
override fun parse(input: Sequence<String>): List<Hand> {
return input.map { line ->
val (cards, bid) = line.split(" ")
Hand(cards, bid.toInt(), false)
}.toList()
}
/**
* Solves Part 1 of the Day 7 puzzle.
* Calculates the total score of the hands without adjusting for part 2 rules.
*
* @param input The parsed input data as a list of Hand objects.
* @return The total score as a Long.
*/
override fun solvePart1(input: List<Hand>): Long {
return calculateTotalScore(input)
}
/**
* Solves Part 2 of the Day 7 puzzle.
* Adjusts the hands for part 2 rules and then calculates the total score.
*
* @param input The parsed input data as a list of Hand objects.
* @return The total score as a Long.
*/
override fun solvePart2(input: List<Hand>): Long {
val adjustedInput = input.map { it.copy(adjustForPart2 = true) }
return calculateTotalScore(adjustedInput)
}
/**
* Calculates the total score of a list of hands.
* Sorts the hands based on their value and multiplies each hand's bid by its position.
*
* @param hands The list of Hand objects to calculate the score for.
* @return The total score as a Long.
*/
private fun calculateTotalScore(hands: List<Hand>): Long {
val sortedHands = hands.sortedWith(HandComparator)
return sortedHands.foldIndexed(0L) { index, acc, hand ->
acc + (index + 1) * hand.bid
}
}
/**
* Data class representing a poker hand.
* Contains information about the hand's cards, bid, and if it should adjust for Part 2 rules.
*
* @property cards String representation of the hand's cards.
* @property bid The bid associated with the hand.
* @property adjustForPart2 Flag to indicate if the hand should be adjusted for Part 2 rules.
*/
data class Hand(val cards: String, val bid: Int, val adjustForPart2: Boolean) {
val totalValue: String by lazy {
val cardsValue = cards.map {
if (adjustForPart2) weights2.indexOf(it).toString(16)
else weights.indexOf(it).toString(16)
}.joinToString("")
if (adjustForPart2 && cards.contains('J')) {
val maxTypeValue = replacements.map { r ->
getTypeValue(cards.replace('J', r))
}.max()
return@lazy maxTypeValue.toString() + cardsValue
}
getTypeValue(cards).toString() + cardsValue
}
companion object {
private val typeValue = mapOf(
"5" to 7,
"41" to 6,
"32" to 5,
"311" to 4,
"221" to 3,
"2111" to 2,
"11111" to 1
)
private const val weights = "23456789TJQKA"
private const val weights2 = "J23456789TQKA"
private const val replacements = "23456789TQKA"
fun getTypeValue(cards: String): Int {
val countMap = cards.groupingBy { it }.eachCount()
val sortedCounts = countMap.values.sortedDescending()
val key = sortedCounts.joinToString("")
return typeValue[key] ?: throw IllegalArgumentException("Invalid hand type")
}
}
}
/**
* Comparator for Hand objects.
* Compares two Hand objects based on their total value.
*/
object HandComparator : Comparator<Hand> {
override fun compare(o1: Hand, o2: Hand): Int {
return o1.totalValue.compareTo(o2.totalValue)
}
}
}
| 0 | Kotlin | 0 | 1 | 27ec8fe5ddef65934ae5577bbc86353d3a52bf89 | 3,710 | kAdvent-2023 | Apache License 2.0 |
src/adventofcode/blueschu/y2017/day19/solution.kt | blueschu | 112,979,855 | false | null | package adventofcode.blueschu.y2017.day19
import java.io.File
import kotlin.test.assertEquals
val input: List<String> by lazy {
File("resources/y2017/day19.txt")
.bufferedReader()
.use { it.readLines() }
}
fun main(args: Array<String>) {
assertEquals("ABCDEF" to 38, walkMap(listOf(
" | ",
" | +--+ ",
" A | C ",
" F---|----E|--+ ",
" | | | D ",
" +B-+ +--+ "))
)
val (chars, steps) = walkMap(input)
println("Part 1: $chars")
println("Part 2: $steps")
}
data class Point(var x: Int, var y: Int)
enum class Direction {
NORTH, EAST, SOUTH, WEST;
fun turnedLeft(): Direction = if (this === NORTH) WEST else values()[ordinal - 1]
fun turnedRight(): Direction = values()[(ordinal + 1) % values().size]
}
class MapWalker(val tubeMap: List<String>) {
var stepCount = 0
private set
var reachedEnd = false
private set
var facing = Direction.SOUTH
private set
val passedChars = mutableListOf<Char>()
val position = Point(tubeMap[0].indexOf('|'), 0)
fun walk() {
val nextChar = adjacentChar()
advance()
when (nextChar) {
'+' -> {
val left = facing.turnedLeft()
val right = facing.turnedRight()
facing = when {
adjacentChar(left) != ' ' -> left
adjacentChar(right) != ' ' -> right
else -> throw IllegalStateException(
"Map contains no viable path at $position")
}
}
' ' -> reachedEnd = true
in 'A'..'Z' -> {
passedChars.add(nextChar)
}
}
}
private fun adjacentChar(dir: Direction = facing) = when (dir) {
Direction.NORTH -> tubeMap[position.y - 1][position.x]
Direction.EAST -> tubeMap[position.y][position.x + 1]
Direction.SOUTH -> tubeMap[position.y + 1][position.x]
Direction.WEST -> tubeMap[position.y][position.x - 1]
}
private fun advance() {
stepCount++
when (facing) {
Direction.NORTH -> position.y--
Direction.EAST -> position.x++
Direction.SOUTH -> position.y++
Direction.WEST -> position.x--
}
}
}
fun walkMap(tubes: List<String>): Pair<String, Int> {
val walker = MapWalker(tubes.map { it.padEnd(201, ' ') })
while (!walker.reachedEnd) {
walker.walk()
}
return walker.passedChars.joinToString(separator = "") to walker.stepCount
}
| 0 | Kotlin | 0 | 0 | 9f2031b91cce4fe290d86d557ebef5a6efe109ed | 2,644 | Advent-Of-Code | MIT License |
src/Day15.kt | syncd010 | 324,790,559 | false | null | class Day15: Day {
private fun convert(input: List<String>) : List<Long> {
return input[0].split(",").map { it.toLong() }
}
data class Direction(val dir: Long, val opposite: Long, val posChange: Position)
val dirs = listOf(
Direction(1, 2, Position(0, -1)),
Direction(2, 1, Position(0, 1)),
Direction(3, 4, Position(-1, 0)),
Direction(4, 3, Position(1, 0)))
private fun mapMaze(computer: Intcode, initialPos: Position): Pair<List<Position>, Position> {
fun dfsMap(computer: Intcode,
currPos: Position,
visited: MutableList<Position>): Position? {
var goalPos: Position? = null
for (dir in dirs) {
val newPos = currPos + dir.posChange
if (newPos in visited) continue
val status = computer.execute(listOf(dir.dir))
if (status.first() == 0L) continue // Wall
visited.add(newPos)
if (status.first() == 2L) goalPos = newPos
val foundPos = dfsMap(computer, newPos, visited)
if (goalPos == null) goalPos = foundPos
computer.execute((listOf(dir.opposite)))
}
return goalPos
}
val visited = mutableListOf(initialPos)
val goalPos = dfsMap(computer, initialPos, visited)!!
return Pair(visited, goalPos)
}
private fun findPath(maze: List<Position>,
initialPos: Position,
finalPos: Position): List<Position> {
fun dfs(maze: List<Position>,
currPos: Position,
finalPos: Position,
visited: MutableList<Position>): MutableList<Position>? {
var bestPath: MutableList<Position>? = null
for (dir in dirs) {
val newPos = currPos + dir.posChange
if (newPos in visited || newPos !in maze) continue
if (newPos == finalPos) return mutableListOf(newPos)
visited.add(newPos)
val path = dfs(maze, newPos, finalPos, visited)?.apply { add(newPos) }
if (path != null && (bestPath == null || path.size < bestPath.size)) {
bestPath = path
}
}
// return the best path found
return bestPath
}
val visited = mutableListOf(initialPos)
return dfs(maze, initialPos, finalPos, visited)!!
}
private fun floodMaze(maze: List<Position>, initialPos: Position): Int {
var frontier = mutableListOf(initialPos)
var nextFrontier = mutableListOf<Position>()
val visited = mutableListOf(initialPos)
var count = 0
do {
while (frontier.isNotEmpty()) {
val currPos = frontier.removeAt(0)
visited.add(currPos)
for (dir in dirs) {
val nextPos = currPos + dir.posChange
if (nextPos !in visited && nextPos in maze)
nextFrontier.add(nextPos)
}
}
count++
frontier = nextFrontier.also { nextFrontier = frontier }
} while (frontier.isNotEmpty())
return count - 1
}
override fun solvePartOne(input: List<String>): Int {
val initialPos = Position(0, 0)
val (maze, finalPos) = mapMaze(Intcode(convert(input)), initialPos)
return findPath(maze, initialPos, finalPos).size
}
override fun solvePartTwo(input: List<String>): Int {
val initialPos = Position(0, 0)
val (maze, finalPos) = mapMaze(Intcode(convert(input)), initialPos)
return floodMaze(maze, finalPos)
}
} | 0 | Kotlin | 0 | 0 | 11c7c7d6ccd2488186dfc7841078d9db66beb01a | 3,900 | AoC2019 | Apache License 2.0 |
src/Day4.kt | sitamshrijal | 574,036,004 | false | {"Kotlin": 34366} | fun main() {
fun parse(input: List<String>): List<Pair<IntRange, IntRange>> {
return input.map {
val (section1, section2) = it.split(",")
section1.toRange("-") to section2.toRange("-")
}
}
fun part1(input: List<String>): Int {
val mapped = parse(input)
return mapped.count { (section1, section2) ->
val firstInSecond = section1.first in section2 && section1.last in section2
val secondInFirst = section2.first in section1 && section2.last in section1
firstInSecond || secondInFirst
}
}
fun part2(input: List<String>): Int {
val mapped = parse(input)
return mapped.count { (section1, section2) ->
section1.last in section2 || section2.last in section1
}
}
val input = readInput("input4")
println(part1(input))
println(part2(input))
}
fun String.toRange(delimiter: String): IntRange {
val (start, end) = split(delimiter).map(String::toInt)
return start..end
}
| 0 | Kotlin | 0 | 0 | fd55a6aa31ba5e3340be3ea0c9ef57d3fe9fd72d | 1,044 | advent-of-code-2022 | Apache License 2.0 |
src/Day12.kt | jvmusin | 572,685,421 | false | {"Kotlin": 86453} | fun main() {
val dx = intArrayOf(0, 1, 0, -1)
val dy = intArrayOf(1, 0, -1, 0)
fun part1(input: List<String>): Int {
val n = input.size
val m = input[0].length
fun inside(p: Pair<Int, Int>): Boolean {
val (x, y) = p
return x in 0 until n && y in 0 until m
}
val dist = Array(n) { IntArray(m) { -1 } }
fun find(c: Char): Pair<Int, Int> {
for (i in 0 until n) for (j in 0 until m) if (c == input[i][j]) return i to j
error("")
}
fun getCode(c: Char): Int = when (c) {
'S' -> getCode('a')
'E' -> getCode('z')
else -> c.code
}
val (x0, y0) = find('S')
dist[x0][y0] = 0
val q = ArrayDeque<Pair<Int, Int>>().apply { add(x0 to y0) }
while (!q.isEmpty()) {
val (x, y) = q.removeFirst()
if (input[x][y] == 'E') return dist[x][y]
for (d in 0 until 4) {
val nx = x + dx[d]
val ny = y + dy[d]
val inside = inside(nx to ny)
if (inside && getCode(input[nx][ny]) - getCode(input[x][y]) <= 1 && dist[nx][ny] == -1) {
dist[nx][ny] = dist[x][y] + 1
q += nx to ny
}
}
}
return -2
}
fun part2(input: List<String>): Int {
val n = input.size
val m = input[0].length
fun inside(p: Pair<Int, Int>): Boolean {
val (x, y) = p
return x in 0 until n && y in 0 until m
}
val dist = Array(n) { IntArray(m) { -1 } }
fun find(c: Char): Pair<Int, Int> {
for (i in 0 until n) for (j in 0 until m) if (c == input[i][j]) return i to j
error("")
}
fun getCode(c: Char): Int = when (c) {
'S' -> getCode('a')
'E' -> getCode('z')
else -> c.code
}
val (x0, y0) = find('E')
dist[x0][y0] = 0
val q = ArrayDeque<Pair<Int, Int>>().apply { add(x0 to y0) }
while (!q.isEmpty()) {
val (x, y) = q.removeFirst()
if (getCode(input[x][y]) == 'a'.code) return dist[x][y]
for (d in 0 until 4) {
val nx = x + dx[d]
val ny = y + dy[d]
val inside = inside(nx to ny)
if (inside && getCode(input[x][y]) - getCode(input[nx][ny]) <= 1 && dist[nx][ny] == -1) {
dist[nx][ny] = dist[x][y] + 1
q += nx to ny
}
}
}
return -2
}
@Suppress("DuplicatedCode")
run {
val day = String.format("%02d", 12)
val testInput = readInput("Day${day}_test")
val input = readInput("Day$day")
println("Part 1 test - " + part1(testInput))
println("Part 1 real - " + part1(input))
println("---")
println("Part 2 test - " + part2(testInput))
println("Part 2 real - " + part2(input))
}
}
| 1 | Kotlin | 0 | 0 | 4dd83724103617aa0e77eb145744bc3e8c988959 | 3,053 | advent-of-code-2022 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.