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
2023/src/main/kotlin/Day12.kt
dlew
498,498,097
false
{"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262}
object Day12 { fun part1(input: String) = parseInput(input).sumOf(::numConfigurations) fun part2(input: String) = parseInput(input) .map { it.unfold() } .sumOf(::numConfigurations) private enum class State { OPERATIONAL, DAMAGED, UNKNOWN } private data class Record(val springs: List<State>, val groups: List<Int>) private val memos = mutableMapOf<Record, Long>() private fun numConfigurations(record: Record): Long { memos[record]?.let { return it } if (record.groups.isEmpty()) { return if (State.DAMAGED !in record.springs) 1 else 0 } // Find all possible places we could put the next damage group within the record val spots = possibleSpotsForDamage(record) // Filter out any places where the next space is DAMAGED (since that would meld with the current group otherwise) val filteredSpots = spots.filter { val next = it.last + 1 return@filter if (next in record.springs.indices) record.springs[next] != State.DAMAGED else true } // Create a new set of records by tossing out the consumed springs & groups val nextSprings = filteredSpots .map { record.springs.subList(minOf(it.last + 2, record.springs.size), record.springs.size) } val nextGroups = record.groups.subList(1, record.groups.size) val result = nextSprings .map { Record(it, nextGroups) } .sumOf { numConfigurations(it) } memos[record] = result return result } private fun possibleSpotsForDamage(record: Record): List<IntRange> { val springs = record.springs val nextGroupSize = record.groups[0] val totalDamageRemaining = record.groups.sum() val spots = mutableListOf<IntRange>() var unknowns = 0 var damage = 0 springs.forEachIndexed { index, state -> when (state) { State.OPERATIONAL -> { if (damage != 0) { return spots } unknowns = 0 } State.DAMAGED -> { unknowns++ damage++ } State.UNKNOWN -> { unknowns++ // If we've seen damage, we MUST continue adding damage if (damage != 0) { damage++ } } } if (unknowns >= nextGroupSize) { spots.add(index - nextGroupSize + 1..index) } if (damage == nextGroupSize) { return spots } // Heuristic exit if there's no way we could fill up the remaining spots with damage if (springs.size - index < totalDamageRemaining - nextGroupSize) { return spots } } return spots } private fun parseInput(input: String): List<Record> { return input.splitNewlines().map { line -> val (springs, groups) = line.splitWhitespace() Record( springs = springs.map { when (it) { '.' -> State.OPERATIONAL '#' -> State.DAMAGED else -> State.UNKNOWN } }, groups = groups.splitCommas().toIntList() ) } } private fun Record.unfold() = Record( Array(5) { listOf(State.UNKNOWN) + springs }.flatMap { it }.drop(1), Array(5) { groups }.flatMap { it } ) }
0
Kotlin
0
0
6972f6e3addae03ec1090b64fa1dcecac3bc275c
3,171
advent-of-code
MIT License
src/main/kotlin/com/groundsfam/advent/y2021/d09/Day09.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2021.d09 import com.groundsfam.advent.DATAPATH import com.groundsfam.advent.grids.Grid import com.groundsfam.advent.grids.containsPoint import com.groundsfam.advent.points.Point import com.groundsfam.advent.points.down import com.groundsfam.advent.points.left import com.groundsfam.advent.points.right import com.groundsfam.advent.points.up import com.groundsfam.advent.grids.readGrid import com.groundsfam.advent.timed import kotlin.io.path.div class Solution(private val heightMap: Grid<Int>) { private val lowPoints = heightMap.pointIndices.filter { p -> listOf(p.left, p.right, p.up, p.down).all { n -> !heightMap.containsPoint(n) || heightMap[n] > heightMap[p] } } fun lowPointRiskLevel(): Int = lowPoints .sumOf { heightMap[it] + 1 } private fun basinSize(lowPoint: Point): Long { val visited = mutableSetOf<Point>() val queue = ArrayDeque<Point>() queue.add(lowPoint) var basinSize: Long = 0 while (queue.isNotEmpty()) { val p = queue.removeFirst() if (visited.add(p)) { basinSize++ listOf(p.left, p.right, p.up, p.down).forEach { n -> if (heightMap.containsPoint(n) && heightMap[n] in (heightMap[p] + 1 until 9)) { queue.add(n) } } } } return basinSize } fun basinSizeProduct(): Long = lowPoints .map(::basinSize) .sorted() .takeLast(3) .reduce { a, b -> a * b } } fun main() = timed { val solution = (DATAPATH / "2021/day09.txt") .readGrid(Char::digitToInt) .let(::Solution) println("Part one: ${solution.lowPointRiskLevel()}") println("Part two: ${solution.basinSizeProduct()}") }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
1,891
advent-of-code
MIT License
src/year2021/day04/Day04.kt
kingdongus
573,014,376
false
{"Kotlin": 100767}
package year2021.day04 import readInputFileByYearAndDay import readTestFileByYearAndDay fun main() { // Stores the board data redundantly as lists of lists of strings, // one per column and row. // this eases the mental model // rawRows: // "1 2" // "3 4" // // becomes // rows: [["1", "2"], ["3","4"]] // columns: [["1", "3"], ["2","4"]] class Board(rawRows: List<String>) { val rows = mutableListOf<MutableList<String>>() val columns = mutableListOf<MutableList<String>>() init { // parse the input according to the description from above rawRows.forEach { rows.add(it.split(" ").filter { it.isNotBlank() }.toMutableList()) } rawRows.indices.forEach { columns.add( rawRows.map { row -> row.split(" ").filter { substring -> substring.isNotBlank() } } .map { c -> c[it] }.toMutableList() ) } } fun mark(n: String) { rows.forEach { it.remove(n) } columns.forEach { it.remove(n) } } fun isCleared(): Boolean = rows.any { it.isEmpty() } || columns.any { it.isEmpty() } fun calculateScore(): Int = rows.flatten().sumOf { it.toInt() } } fun parseBoards(input: List<String>): MutableList<Board> { val boards = mutableListOf<Board>() val buffer = mutableListOf<String>() input.forEach { if (it.isBlank()) { boards.add(Board(buffer)) buffer.clear() } else buffer.add(it) } // dangling board boards.add(Board(buffer)) return boards } fun part1(input: List<String>): Int { val boards = parseBoards(input.drop(2)) val moves = input.first().split(",") moves.forEach { for (b in boards) { b.mark(it) if (b.isCleared()) return b.calculateScore() * it.toInt() } } return -1 } // looks like trash, a good solution would probably include a 'counting trie' data structure // (e.g. a trie that counts the number of children at each node) fun part2(input: List<String>): Int { val boards = parseBoards(input.drop(2)) val moves = input.first().split(",") val winningBoards = mutableListOf<Board>() var lastCalled = "-1" moves.forEach { for (b in boards) { b.mark(it) if (b.isCleared()) { winningBoards.add(b) lastCalled = it } } boards.removeAll(winningBoards) } return winningBoards.last().calculateScore() * lastCalled.toInt() } val testInput = readTestFileByYearAndDay(2021, 4) check(part1(testInput) == 4512) check(part2(testInput) == 1924) val input = readInputFileByYearAndDay(2021, 4) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
aa8da2591310beb4a0d2eef81ad2417ff0341384
3,058
advent-of-code-kotlin
Apache License 2.0
src/commonMain/kotlin/com/marcoeckstein/klib/algorithm/NumberSearch.kt
marco-eckstein
344,286,939
false
null
package com.marcoeckstein.klib.algorithm import com.marcoeckstein.klib.kotlin.ranges.binarySearch import kotlin.math.absoluteValue import kotlin.math.sqrt fun findNumber(isNumberInRange: (IntRange) -> Boolean): Int? { val bounds = findNumberBounds(isNumberInRange) ?: return null return bounds.binarySearch { candidate -> if (isNumberInRange(candidate..bounds.last)) if (candidate < Int.MAX_VALUE && isNumberInRange((candidate + 1)..bounds.last)) -1 // candidate is too small else 0 // found number else 1 // candidate is too large } } fun findNumberBounds(isNumberInRange: (IntRange) -> Boolean): IntRange? = findNumberBounds(0..0, isNumberInRange) private fun findNumberBounds(candidate: IntRange, isNumberInRange: (IntRange) -> Boolean): IntRange? { require(candidate.first <= 0) { "candidate.first must be <= 0, but was ${candidate.first}." } require(candidate.last >= 0) { "candidate.last must be >= 0, but was ${candidate.last}." } return if (isNumberInRange(candidate)) candidate else { val nextCandidate = nextRangeInExponentialSequence(candidate) ?: return null findNumberBounds(nextCandidate, isNumberInRange) } } // Note that Int.MIN_VALUE == (Int.MAX_VALUE * -1) - 1 private fun nextRangeInExponentialSequence(range: IntRange): IntRange? { return when (range.first) { Int.MIN_VALUE -> null Int.MIN_VALUE + 1 -> { require(range.last == Int.MAX_VALUE) Int.MIN_VALUE..Int.MAX_VALUE } else -> { val nextFirst = nextNumberInExponentialSequence(range.first, sign = -1) ?: return null val nextLast = nextNumberInExponentialSequence(range.last, sign = 1) ?: return null nextFirst..nextLast } } } // Note that Int.MIN_VALUE.absoluteValue == Int.MIN_VALUE due to an overflow private fun nextNumberInExponentialSequence(i: Int, sign: Int): Int? { require(sign in setOf(1, -1)) require(i != Int.MIN_VALUE) val abs = i.absoluteValue return when { abs < 2 -> abs + 1 abs <= sqrt(Int.MAX_VALUE.toDouble()) -> abs * abs abs < Int.MAX_VALUE -> Int.MAX_VALUE else -> null }?.let { it * sign } }
0
Kotlin
0
3
b28b28b76f04c245951dd8d02e3531818f9b6c57
2,299
kotlin-lib
MIT License
aoc-2023/src/main/kotlin/aoc/aoc6.kts
triathematician
576,590,518
false
{"Kotlin": 615974}
import aoc.AocParser.Companion.parselines import aoc.* import aoc.util.getDayInput import kotlin.math.ceil import kotlin.math.floor import kotlin.math.sqrt val testInput = """ Time: 7 15 30 Distance: 9 40 200 """.parselines class Race(val time: Long, val dist: Long) { fun numToBeat(): Long { val firstBeat = (0L..time).first { it * (time - it) > dist } return time - 2*firstBeat + 1 } fun numToBeat_Solved(): Long { val t0 = .5*(time - sqrt(time*time - 4.0*dist)) val t1 = .5*(time + sqrt(time*time - 4.0*dist)) return (floor(t1) - ceil(t0)).toLong() + 1 } } fun List<String>.parse(): List<Race> { val line0 = get(0).substringAfter(":").trim().split("\\s+".toRegex()) val line1 = get(1).substringAfter(":").trim().split("\\s+".toRegex()) return line0.indices.map { Race(line0[it].toLong(), line1[it].toLong()) } } // part 1 fun List<String>.part1() = parse() .map { it.numToBeat_Solved() } .reduce { a, b -> a*b } // part 2 fun List<String>.part2() = map { it.replace(" ", "") } .parse() .map { it.numToBeat_Solved() } .reduce { a, b -> a*b } // calculate answers val day = 6 val input = getDayInput(day, 2023) val testResult = testInput.part1() val testResult2 = testInput.part2() val answer1 = input.part1().also { it.print } val answer2 = input.part2().also { it.print } // print results AocRunner(day, test = { "$testResult, $testResult2" }, part1 = { answer1 }, part2 = { answer2 } ).run()
0
Kotlin
0
0
7b1b1542c4bdcd4329289c06763ce50db7a75a2d
1,530
advent-of-code
Apache License 2.0
src/Day07.kt
dcbertelsen
573,210,061
false
{"Kotlin": 29052}
import java.io.File import java.util.Dictionary fun main() { fun buildFilesystem(data: List<String>): Directory { val root = Directory("/", null) var cwd = root data.forEachIndexed { i, line -> val curr = line.split(" ") when { curr[1] == "cd" -> cwd = if (curr[2] == "/") root else if (curr[2] == "..") cwd.parent ?: cwd else cwd.contents.firstOrNull { it.name == curr[2] } as? Directory ?: Directory(curr[2], cwd).also { cwd.contents.add(it) } curr[0] == "dir" -> cwd.contents.firstOrNull { it.name == curr[1] } ?: cwd.contents.add(Directory(curr[1], cwd)) curr[1] == "ls" -> {} curr[0].matches(Regex("\\d+")) -> cwd.contents.firstOrNull { it.name == curr[1] } ?: cwd.contents.add(Data(curr[1], curr[0].toInt(), cwd)) } } return root } fun part1(input: List<String>): Int { val fs = buildFilesystem(input) // fs.filetree().forEach { println(it) } val bigdirs = fs.listAll().filter { it is Directory && it.size <= 100000 } return bigdirs.sumOf { it.size } } fun part2(input: List<String>): Int { val fs = buildFilesystem(input) val dirs = fs.listAll().filterIsInstance<Directory>() val target = fs.size - 4e7 return dirs.filter { it.size >= target }.minBy { it.size }.size } val testInput = listOf<String>( "$ cd /", "$ ls", "dir a", "14848514 b.txt", "8504156 c.dat", "dir d", "$ cd a", "$ ls", "dir e", "29116 f", "2557 g", "62596 h.lst", "$ cd e", "$ ls", "584 i", "$ cd ..", "$ cd ..", "$ cd d", "$ ls", "4060174 j", "8033020 d.log", "5626152 d.ext", "7214296 k", ) // test if implementation meets criteria from the description, like: check(part1(testInput) == 95437) // check(part2(testInput) == 42) val input = File("./src/resources/Day07.txt").readLines() println(part1(input)) println(part2(input)) } sealed class FsNode(val name: String, val parent: Directory?) { abstract val size: Int abstract fun listAll() : List<FsNode> } class Directory( name: String, parent: Directory?, val contents: MutableList<FsNode> = mutableListOf() ) : FsNode(name, parent) { override val size get() = contents.sumOf { it.size } override fun toString(): String { return "- $name (dir, size = $size)" //\n " + contents.sortedBy { it.name }.joinToString("\n ") } fun filetree() : List<String> { return listOf("$this") + contents.flatMap { (it as? Directory)?.filetree() ?: listOf("$it") }.map { " $it" } } override fun listAll() : List<FsNode> = listOf(this) + contents.flatMap { it.listAll() } } class Data(name: String, override val size: Int, parent: Directory) : FsNode(name, parent) { override fun toString(): String { return "- $name (file, size = $size)" } override fun listAll() : List<FsNode> = listOf(this) }
0
Kotlin
0
0
9d22341bd031ffbfb82e7349c5684bc461b3c5f7
3,236
advent-of-code-2022-kotlin
Apache License 2.0
src/Day07.kt
msernheim
573,937,826
false
{"Kotlin": 32820}
fun main() { fun findNextCommand(input: List<String>, cursor: Int): Int { return when (val indexOfNextCommand = input.subList(cursor, input.size - 1).indexOfFirst { line -> line.startsWith("$ ") }) { -1 -> input.size - 1 else -> indexOfNextCommand + cursor } } fun increaseSizeBackToRoot(size: Int, currentDir: Item?) { var current = currentDir while (current!!.parent != null) { current.size += size current = current.parent } current.size += size } fun parseListDir( nextCommand: Int, i: Int, input: List<String>, currentDir: Item? ) { if (nextCommand > i) { for (j in i + 1 until nextCommand) { val words = input[j].split(" ") var item: Item if (words[0].toIntOrNull() != null) { item = Item(words[1], Type.FILE, words[0].toInt(), mutableListOf(), currentDir) increaseSizeBackToRoot(item.size, currentDir) } else { item = Item(words[1], Type.DIRECTORY, 0, mutableListOf(), currentDir) } currentDir!!.contents.add(item) } } } fun sumSmallSizeDirs(item: Item?): Int { if (item == null) return 0 return if (item.type == Type.DIRECTORY) { if (item.size <= 100000) { item.size + item.contents.sumOf { containingItem -> sumSmallSizeDirs(containingItem) } } else { item.contents.sumOf { containingItem -> sumSmallSizeDirs(containingItem) } } } else { 0 } } fun getRoot(item: Item?): Item? { var current = item while (current!!.parent != null) { current = current!!.parent } return current } fun isTargetInContents(contents: List<Item>, target: String) = contents.filter { item -> item.name == target }.isNotEmpty() fun parseCommands(input: List<String>): Item? { var current: Item? = null for (i in input.indices) { val line = input[i] when { line.contains("$ cd") -> { val target = line.removePrefix("$ cd ") when (target) { ".." -> { current = current!!.parent } else -> { if (current != null && isTargetInContents(current!!.contents, target)) { current = current!!.contents.first { item -> item.name == target } } else if (current == null) { val newDir = Item(target, Type.DIRECTORY, 0, mutableListOf(), current) current = newDir } else println("Could not execute: $line") } } } line.contains("$ ls") -> { val nextCommand = findNextCommand(input, i + 1) parseListDir(nextCommand, i, input, current) } } } return current } fun part1(input: List<String>): String { var currentDir: Item? = parseCommands(input) currentDir = getRoot(currentDir) return sumSmallSizeDirs(currentDir).toString() } fun findBestCleaningSize(root: Item, amountToFree: Int): Int { var currentBest = root.size var currentDir = root while (currentDir.contents.isNotEmpty()) { val bestChild = currentDir.contents.filter { child -> IntRange(amountToFree, currentBest).contains(child.size) } .sortedByDescending { item -> item.size }.lastOrNull() ?: return currentBest currentBest = bestChild.size currentDir = bestChild } return currentBest } fun part2(input: List<String>): String { var currentDir: Item? = parseCommands(input) val root = getRoot(currentDir) val amountToFree = 30000000 - (70000000 - root!!.size) val sizeToFree = findBestCleaningSize(root, amountToFree) return sizeToFree.toString() } val input = readInput("Day07") val part1 = part1(input) val part2 = part2(input) println("Result part1: $part1") println("Result part2: $part2") } class Item( val name: String, val type: Type, var size: Int, val contents: MutableList<Item> = mutableListOf(), val parent: Item? ) { override fun toString(): String { return "Item( $name, size: $size contents: ${contents.size})" } } enum class Type { FILE, DIRECTORY }
0
Kotlin
0
3
54cfa08a65cc039a45a51696e11b22e94293cc5b
4,859
AoC2022
Apache License 2.0
src/Day11.kt
Akhunzaada
573,119,655
false
{"Kotlin": 23755}
import java.io.File data class Monkey( private val items: MutableList<Long>, private val operation: String, private val divBy: Int, private val throwToMonkey: Int, private val elseThrowToMonkey: Int ) { private var worryLevel: Long = 0 var inspections: Long = 0 fun divBy() = divBy fun hasItems() = items.isNotEmpty() fun inspect(): Monkey { inspections++ worryLevel = items.removeFirst() return this } fun operate(): Monkey { operation.split(' ').let { val operator = it.component2() val operand2 = it.component3().let { if (it == "old") worryLevel else it.toLong() } worryLevel = when(operator) { "*" -> worryLevel * operand2 "+" -> worryLevel + operand2 else -> worryLevel } } return this } fun bored(manageWorryLevel: (worryLevel: Long) -> Long): Monkey { worryLevel = manageWorryLevel(worryLevel) return this } fun throwAway(): Pair<Long, Int> { val monkey = if (worryLevel % divBy == 0.toLong()) throwToMonkey else elseThrowToMonkey return Pair(worryLevel, monkey) } fun catchItem(item: Long) { items.add(item) } } fun main() { fun String.parseInput(): List<Monkey> { val monkeys = mutableListOf<Monkey>() split("\n\n").map { it.lines().drop(1).let { val items = it.component1().substringAfter(": ").split(", ").map { it.toLong() } val op = it.component2().substringAfter("= ") val divBy = it.component3().substringAfterLast(' ').toInt() val throwToMonkey = it.component4().substringAfterLast(' ').toInt() val elseThrowToMonkey = it.component5().substringAfterLast(' ').toInt() monkeys.add(Monkey(items.toMutableList(), op, divBy, throwToMonkey, elseThrowToMonkey)) } } return monkeys } fun List<Monkey>.rounds(times: Int, manageWorryLevel: (worryLevel: Long) -> Long): Long { repeat(times) { forEach { monkey -> while (monkey.hasItems()) { monkey.inspect().operate().bored(manageWorryLevel).throwAway().let { (item, toMonkey) -> get(toMonkey).catchItem(item) } } } } return sortedByDescending { it.inspections } .let { it.component1().inspections * it.component2().inspections } } fun part1(input: List<Monkey>): Long = input.rounds(20) { it / 3 } fun part2(input: List<Monkey>): Long { val mod = input.map { it.divBy().toLong() }.reduce(Long::times) return input.rounds(10_000) { it % mod } } // test if implementation meets criteria from the description, like: val testInput = File("src", "Day11_test.txt").readText() check(part1(testInput.parseInput()) == 10605L) check(part2(testInput.parseInput()) == 2713310158L) val input = File("src", "Day11.txt").readText() println(part1(input.parseInput())) println(part2(input.parseInput())) }
0
Kotlin
0
0
b2754454080989d9579ab39782fd1d18552394f0
3,231
advent-of-code-2022
Apache License 2.0
src/day25/Day25.kt
Oktosha
573,139,677
false
{"Kotlin": 110908}
package day25 import kotlin.math.max import readInput const val BASE = 5 enum class SNAFUDigit(val value: Int, val symbol: Char) { DOUBLE_MINUS(-2, '='), MINUS(-1, '-'), ZERO(0, '0'), ONE(1, '1'), TWO(2, '2'); companion object { private val charToDigit = SNAFUDigit.values().associateBy { it.symbol } fun fromValue(value: Int): SNAFUDigit { return SNAFUDigit.values()[value + 2] } fun fromChar(value: Char): SNAFUDigit { return charToDigit[value]!! } } } class SNAFUNumber(val value: List<SNAFUDigit>) { companion object { fun fromString(input: String): SNAFUNumber { return SNAFUNumber(input.map(SNAFUDigit.Companion::fromChar).reversed()) } } operator fun plus(other: SNAFUNumber): SNAFUNumber { val ans = mutableListOf<SNAFUDigit>() var carry = 0 for (i in 0..max(this.value.size, other.value.size) + 2) { val sum = carry + this.digitOrZero(i).value + other.digitOrZero(i).value val rawResult = (BASE + sum) % BASE val result = if (rawResult <= 2) { rawResult } else { rawResult - 5 } ans.add(SNAFUDigit.fromValue(result)) carry = if (sum >= 3) { 1 }else if (sum <= -3) { -1 } else { 0 } print(":${SNAFUDigit.fromValue(result).symbol}") } println() return SNAFUNumber(ans.dropLastWhile { it == SNAFUDigit.ZERO }) } private fun digitOrZero(pos: Int): SNAFUDigit { return value.elementAtOrNull(pos) ?: SNAFUDigit.ZERO } override fun toString(): String { return value.reversed().map { x -> x.symbol }.joinToString("", "", "") } } fun part1(input: List<String>): String { return input.map(SNAFUNumber.Companion::fromString).reduce{x, y -> x + y}.toString() } fun main() { println("Day 25") val input = readInput("Day25") var num = SNAFUNumber.fromString("1") for (i in 1 .. 1000) { num = SNAFUNumber.fromString("1") + num println(num) } println("part 1: ${part1(input)}") }
0
Kotlin
0
0
e53eea61440f7de4f2284eb811d355f2f4a25f8c
2,253
aoc-2022
Apache License 2.0
codeforces/round584/e1.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.round584 private fun solve() { val (n, m) = readInts() val a = List(n) { readInts() } val b = List(m) { i -> a.map { it[i] } }.sortedByDescending { it.maxOrNull() }.take(n) println(solve(b, 1, b[0])) } private fun solve(b: List<List<Int>>, x: Int, best: List<Int>): Int { val bestInit = best.sum() if (x == b.size) return bestInit return best.indices.mapNotNull { i -> val newBest = List(best.size) { maxOf(best[it], b[x][(it + i) % best.size]) } if (newBest.sum() > bestInit) solve(b, x + 1, newBest) else null }.maxOrNull() ?: solve(b, x + 1, best) } fun main() = repeat(readInt()) { solve() } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
814
competitions
The Unlicense
advent2022/src/main/kotlin/year2022/Day12.kt
bulldog98
572,838,866
false
{"Kotlin": 132847}
package year2022 import AdventDay import graph.AdjacencyListGraph import graph.Graph import graph.dijkstra private typealias Coordinate = Pair<Int, Int> private typealias Terrain = Graph<Coordinate> private fun List<String>.atPoint(point: Coordinate) = when (this[point.second][point.first]) { 'S' -> 'a' 'E' -> 'z' else -> this[point.second][point.first] } private fun Terrain(input: List<String>): Terrain { val nodes = input[0].indices.flatMap { x -> (input.indices).map { y -> x to y } } val connections = buildMap { input[0].indices.forEach { x -> input.indices.forEach { y -> val ownHeight = input.atPoint(x to y) val reachableNeighbors = listOf(x - 1 to y, x + 1 to y, x to y - 1, x to y + 1).filter { (a, b) -> a in input[0].indices && b in input.indices && ownHeight + 1 >= input.atPoint(a to b) } this[x to y] = reachableNeighbors } } } return AdjacencyListGraph(nodes, connections::getValue) } class Day12 : AdventDay(2022, 12) { private fun computeCostFunction(input: List<String>): (Coordinate, Coordinate) -> Long { return { u, v -> if (input.atPoint(u) + 1 >= input.atPoint(v)) 1 else Long.MAX_VALUE } } override fun part1(input: List<String>): Long { val graph = Terrain(input) var from = -1 to -1 var to = -1 to -1 input[0].indices.forEach { x -> input.indices.forEach { y -> val c = input[y][x] if (c == 'S') { from = x to y } if (c == 'E') { to = x to y } } } val (dist, _) = graph.dijkstra(from, computeCostFunction(input)) return dist(to) ?: Long.MAX_VALUE } override fun part2(input: List<String>): Long { val graph = Terrain(input) var to = -1 to -1 val startingPoints = mutableListOf<Pair<Int, Int>>() input[0].indices.forEach { x -> input.indices.forEach { y -> val c = input[y][x] if (c == 'a' || c == 'S') { startingPoints += x to y } if (c == 'E') { to = x to y } } } return startingPoints.fold(Long.MAX_VALUE) { curMin, from -> val (dist, _) = graph.dijkstra(from, computeCostFunction(input)) listOf(curMin, dist(to) ?: Long.MAX_VALUE).min() } } } fun main() = Day12().run()
0
Kotlin
0
0
02ce17f15aa78e953a480f1de7aa4821b55b8977
2,660
advent-of-code
Apache License 2.0
src/main/kotlin/biz/koziolek/adventofcode/year2023/day22/day22.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2023.day22 import biz.koziolek.adventofcode.Coord import biz.koziolek.adventofcode.Coord3d import biz.koziolek.adventofcode.findInput import kotlin.math.max import kotlin.math.min fun main() { val inputFile = findInput(object {}) val bricks = parseBricks(inputFile.bufferedReader().readLines()) println("${findSafeToDisintegrate(bricks).size} are safe to disintegrate") println("${countBricksThatWouldFall(bricks).values.sum()} other bricks would fall when removing each brick") } data class Brick(val from: Coord3d, val to: Coord3d) { val bottomZ = min(from.z, to.z) val topZ = max(from.z, to.z) val crossSection = CrossSection( from = Coord( x = min(from.x, to.x), y = min(from.y, to.y), ), to = Coord( x = max(from.x, to.x), y = max(from.y, to.y), ), ) fun moveToBottomZ(z: Int): Brick = copy( from = from.copy(z = z), to = to.copy(z = z + (to.z - from.z)) ) } data class CrossSection(val from: Coord, val to: Coord) { fun overlaps(other: CrossSection): Boolean = this.from.x <= other.to.x && this.to.x >= other.from.x && this.from.y <= other.to.y && this.to.y >= other.from.y } data class StationaryBrick(val original: Brick, val fallen: Brick) fun parseBricks(lines: Iterable<String>): List<Brick> = lines.map { line -> val (coord1, coord2) = line.split('~') Brick( from = Coord3d.fromString(coord1), to = Coord3d.fromString(coord2), ) } fun findSafeToDisintegrate(bricks: Collection<Brick>): Set<StationaryBrick> { val fallen = fallAll(bricks) val (supportingMap, supportedByMap) = buildSupportMaps(fallen) return fallen.filter { isSafeToDisintegrate(it, supportingMap, supportedByMap) }.toSet() } fun fallAll(bricks: Collection<Brick>): List<StationaryBrick> { val sortedByZ = bricks.sortedBy { it.bottomZ } val stationaryBricks = mutableListOf<StationaryBrick>() for (brick in sortedByZ) { var newZ = brick.bottomZ while (newZ > 1) { val anyOverlaps = stationaryBricks .filter { it.fallen.topZ == newZ - 1 } .any { it.fallen.crossSection.overlaps(brick.crossSection) } if (anyOverlaps) { break } newZ-- } stationaryBricks.add( StationaryBrick( original = brick, fallen = brick.moveToBottomZ(newZ) ) ) } return stationaryBricks } fun getSupportedBricks(brick: StationaryBrick, bricks: Collection<StationaryBrick>): List<StationaryBrick> = bricks.filter { it.fallen.bottomZ == brick.fallen.topZ + 1 && it.fallen.crossSection.overlaps(brick.fallen.crossSection) } fun countBricksThatWouldFall(bricks: Collection<Brick>): Map<StationaryBrick, Int> { val fallen = fallAll(bricks) val sortedByZ = fallen.sortedByDescending { it.fallen.bottomZ } val (supportingMap, supportedByMap) = buildSupportMaps(fallen) val counts = mutableMapOf<StationaryBrick, Int>() for (brick in sortedByZ) { val disintegrated = mutableSetOf(brick) val toCheck = mutableListOf(brick) while (toCheck.isNotEmpty()) { val b = toCheck.removeFirst() val orphans = supportingMap[b]!! .filter { supported -> supportedByMap[supported]!!.all { it in disintegrated } } disintegrated.addAll(orphans) toCheck.addAll(orphans) } counts[brick] = disintegrated.size - 1 } return counts } private fun buildSupportMaps(fallen: List<StationaryBrick>, debug: Boolean = false): Pair<Map<StationaryBrick, List<StationaryBrick>>, Map<StationaryBrick, List<StationaryBrick>>> { val supportingMap = fallen.associateWith { getSupportedBricks(it, fallen) } val supportedByMap = supportingMap.entries .flatMap { supporting -> supporting.value.map { supported -> supported to supporting.key } } .groupBy { it.first } .mapValues { entry -> entry.value.map { it.second } } if (debug) { println("Supporting map:") supportingMap.forEach { (supporting, supportedList) -> println(" $supporting a.k.a. ${getFriendlyName(supporting)} supports:") supportedList.forEach { supported -> println(" $supported a.k.a. ${getFriendlyName(supported)}") } println() } println("Supported by map:") supportedByMap.forEach { (supported, supportingList) -> println(" $supported a.k.a. ${getFriendlyName(supported)} is supported by:") supportingList.forEach { supporting -> println(" $supporting a.k.a. ${getFriendlyName(supporting)}") } println() } } return supportingMap to supportedByMap } private fun isSafeToDisintegrate(brick: StationaryBrick, supportingMap: Map<StationaryBrick, List<StationaryBrick>>, supportedByMap: Map<StationaryBrick, List<StationaryBrick>>): Boolean = supportingMap[brick]!!.all { supported -> supportedByMap[supported]!!.size > 1 } internal fun getFriendlyName(stationaryBrick: StationaryBrick): String = when (stationaryBrick.original) { Brick(from = Coord3d(1, 0, 1), to = Coord3d(1, 2, 1)) -> "A" Brick(from = Coord3d(0, 0, 2), to = Coord3d(2, 0, 2)) -> "B" Brick(from = Coord3d(0, 2, 3), to = Coord3d(2, 2, 3)) -> "C" Brick(from = Coord3d(0, 0, 4), to = Coord3d(0, 2, 4)) -> "D" Brick(from = Coord3d(2, 0, 5), to = Coord3d(2, 2, 5)) -> "E" Brick(from = Coord3d(0, 1, 6), to = Coord3d(2, 1, 6)) -> "F" Brick(from = Coord3d(1, 1, 8), to = Coord3d(1, 1, 9)) -> "G" else -> "UNKNOWN" }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
6,113
advent-of-code
MIT License
src/main/kotlin/day24/Day24.kt
jakubgwozdz
571,298,326
false
{"Kotlin": 85100}
package day24 import Queue import execute import readAllText import kotlin.math.absoluteValue typealias Pos = Pair<Int, Int> typealias Blizzard = Pair<Pos, Dir> enum class Dir(val v: Pos) { N(-1 to 0), W(0 to -1), E(0 to 1), S(1 to 0), } operator fun Pos.plus(o: Pos) = first + o.first to second + o.second operator fun Pos.plus(o: Dir) = this + o.v private fun Int.keepIn(intRange: IntRange): Int = when { this > intRange.last -> intRange.first this < intRange.first -> intRange.last else -> this } private fun Pos.manhattan(dest: Pos) = (first - dest.first).absoluteValue + (second - dest.second).absoluteValue data class Valley( val rows: IntRange, val cols: IntRange, val enter: Pos, val exit: Pos, val blizzards: List<Blizzard>, ) { val lcm = with(rows.count() to cols.count()) { // hackaton style when (this) { (4 to 6) -> 12 // test input (25 to 120) -> 600 // real input else -> TODO(this.toString()) } } private val blizzardsByTime: Map<Int, Set<Pos>> = buildMap { var s = blizzards repeat(lcm) { time -> put(time, s.map { it.first }.toHashSet()) s = s.map { (p, dir) -> val r = (p.first + dir.v.first).keepIn(rows) val c = (p.second + dir.v.second).keepIn(cols) Blizzard(r to c, dir) } } } fun blizzardsAt(time: Int) = blizzardsByTime[time % lcm]!! } data class State(val pos: Pos, val timeElapsed: Int = 0) fun State.trimmed(valley: Valley) = copy(timeElapsed = timeElapsed % valley.lcm) fun State.goTo(valley: Valley, exit: Pos): State { val queue = Queue(this) val visited = mutableSetOf<State>() while (true) { val state = queue.poll() val trimmed = state.trimmed(valley) if (trimmed !in visited) state.next(valley) .forEach { if (it.pos == exit) return it if (it.trimmed(valley) !in visited) queue.offer(it) } .also { visited += trimmed } } } fun part1(input: String): Int { val valley = parseValley(input) return State(valley.enter) .goTo(valley, valley.exit) .timeElapsed } fun part2(input: String): Int { val valley = parseValley(input) return State(valley.enter) .goTo(valley, valley.exit) .goTo(valley, valley.enter) .goTo(valley, valley.exit) .timeElapsed } private fun State.next(valley: Valley): List<State> { val t = timeElapsed + 1 val occupied = valley.blizzardsAt(t) val possibleMoves = (Dir.values().map { pos + it } + pos) .filter { p: Pos -> (p.first in valley.rows && p.second in valley.cols || p == valley.exit || p == valley.enter) && p !in occupied } return possibleMoves.map { State(it, t) } .sortedBy { it.pos.manhattan(valley.exit) } } private fun parseValley(input: String): Valley { val lines = input.trimEnd().lines() val enter = 0 to lines.first().indexOf('.') val exit = lines.indices.last to lines.last().indexOf('.') val rows = 1 until lines.indices.last val cols = 1 until lines.first().indices.last val blizzards = buildList { rows.forEach { r -> cols.forEach { c -> when (lines[r][c]) { '^' -> add(Blizzard(r to c, Dir.N)) 'v' -> add(Blizzard(r to c, Dir.S)) '<' -> add(Blizzard(r to c, Dir.W)) '>' -> add(Blizzard(r to c, Dir.E)) } } } } return Valley(rows, cols, enter, exit, blizzards) } fun main() { val input = readAllText("local/day24_input.txt") val test = """ #.###### #>>.<^<# #.<..<<# #>v.><># #<^v^^># ######.# """.trimIndent() execute(::part1, test, 18) execute(::part1, input, 264) execute(::part2, test, 54) execute(::part2, input) }
0
Kotlin
0
0
7589942906f9f524018c130b0be8976c824c4c2a
4,069
advent-of-code-2022
MIT License
src/nativeMain/kotlin/xyz/justinhorton/aoc2022/Day13.kt
justinhorton
573,614,839
false
{"Kotlin": 39759, "Shell": 611}
package xyz.justinhorton.aoc2022 /** * https://adventofcode.com/2022/day/13 */ class Day13(override val input: String) : Day() { override fun part1(): String { return input.split("\n\n") .map { val lines = it.lines() parseList(lines[0].asTokenDeque()) to parseList(lines[1].asTokenDeque()) }.mapIndexedNotNull { index, pair -> if (pairsInRightOrder(pair.first, pair.second)) { index + 1 } else { null } }.sum().toString() } private fun pairsInRightOrder(p1: List<*>, p2: List<*>): Boolean { val inOrder = inRightOrder(p1, p2) requireNotNull(inOrder) { "Comparison of input pair should not be null" } return inOrder } private fun inRightOrder(p1: List<*>, p2: List<*>): Boolean? { for ((item1, item2) in p1.zip(p2)) { if (item1 is Int && item2 is Int) { when { item1 < item2 -> return true item1 > item2 -> return false } } else { val l = (item1 as? List<*>) ?: listOf(item1) val r = (item2 as? List<*>) ?: listOf(item2) inRightOrder(l, r).let { if (it != null) return it } } } // ran out...was left or right shorter? return if (p1.size != p2.size) p1.size < p2.size else null } private fun String.asTokenDeque() = ArrayDeque<Char>().apply { this@asTokenDeque.forEach { add(it) } } override fun part2(): String { val sorted = input.trim() .lineSequence() .filter { it.isNotBlank() } .mapTo(mutableListOf()) { parseList(it.asTokenDeque()) } .also { it.addAll(dividerPackets) } .sortedWith { a, b -> when (inRightOrder(a, b)) { true -> -1 false -> 1 null -> 0 } } val two = sorted.indexOf(dividerPackets.first()) + 1 val six = sorted.indexOf(dividerPackets.last()) + 1 return (two * six).toString() } private fun parseList(q: ArrayDeque<Char>): List<Any> { require(q.removeFirst() == '[') { "Not the start of a list" } val resultList = mutableListOf<Any>() var nextCh: Char while (q.isNotEmpty()) { nextCh = q.removeFirst() when { nextCh.isDigit() -> { var digitStr = "$nextCh" while (q.isNotEmpty() && q.first().isDigit()) { digitStr = "$digitStr${q.removeFirst()}" } resultList.add(digitStr.toInt()) } nextCh == '[' -> { q.addFirst(nextCh) // put back the '[' resultList.add(parseList(q)) } nextCh == ',' -> continue else -> { // nextCh == '] return resultList } } } return resultList } } private val dividerPackets = listOf(listOf(listOf(2)), listOf(listOf(6)))
0
Kotlin
0
1
bf5dd4b7df78d7357291c7ed8b90d1721de89e59
3,255
adventofcode2022
MIT License
src/Day12.kt
pavlo-dh
572,882,309
false
{"Kotlin": 39999}
fun main() { data class Point(val y: Int, val x: Int) val deltas = listOf(-1 to 0, 1 to 0, 0 to -1, 0 to 1) fun mapElevation(c: Char) = when (c) { 'S' -> 'a' 'E' -> 'z' else -> c } fun MutableMap<Point, MutableList<Point>>.addEdge(from: Point, to: Point) { val fromEdges = computeIfAbsent(from) { mutableListOf() } fromEdges.add(to) } fun MutableMap<Point, MutableList<Point>>.bfs(start: Point, end: Point): Int? { val visited = mutableSetOf(start) val queue = ArrayDeque<Point>() queue.addLast(start) val depths = mutableMapOf(start to 0) while (queue.isNotEmpty()) { val v = queue.removeFirst() if (v == end) { return depths[end] } get(v)?.forEach { to -> if (!visited.contains(to)) { visited.add(to) queue.addLast(to) depths[to] = depths[v]!! + 1 } } } return null } fun findFewestStepsNumber(input: List<String>, isStartingPoint: (elevation: Char) -> Boolean): Int { val startingPoints = mutableListOf<Point>() lateinit var end: Point val graph = mutableMapOf<Point, MutableList<Point>>() input.forEachIndexed { i, row -> row.forEachIndexed { j, elevation -> val point = Point(i, j) if (isStartingPoint(elevation)) { startingPoints.add(point) } else if (elevation == 'E') { end = point } for ((deltaY, deltaX) in deltas) { val k = i + deltaY val l = j + deltaX if (k in 0..input.lastIndex && l in 0..row.lastIndex) { val pointElevation = mapElevation(elevation) val neighbourElevation = mapElevation(input[k][l]) if (pointElevation.code - neighbourElevation.code >= -1) { graph.addEdge(point, Point(k, l)) } } } } } return startingPoints.mapNotNull { graph.bfs(it, end) }.min() } fun part1(input: List<String>): Int = findFewestStepsNumber(input) { elevation -> elevation == 'S' } fun part2(input: List<String>): Int = findFewestStepsNumber(input) { elevation -> elevation == 'S' || elevation == 'a' } // test if implementation meets criteria from the description, like: val testInput = readInput("Day12_test") check(part1(testInput) == 31) check(part2(testInput) == 29) val input = readInput("Day12") println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
c10b0e1ce2c7c04fbb1ad34cbada104e3b99c992
2,837
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/days/Day4.kt
VictorWinberg
433,748,855
false
{"Kotlin": 26228}
package days class Day4 : Day(4) { override fun partOne(): Any { return winners().first() } override fun partTwo(): Any { return winners().last() } private fun winners(): List<Int> { val list = inputList.filter { it.isNotEmpty() } val numbers = list.first().split(",").map { it.toInt() } val size = 5 val boards = list.drop(1).map { it.trim().split(Regex("\\s+")).map { it.toInt() } }.chunked(size) val marked = Array(boards.size) { Array(size) { BooleanArray(size) { false } } } return winners(numbers, boards, marked) } private fun winners( numbers: List<Int>, boards: List<List<List<Int>>>, booleans: Array<Array<BooleanArray>> ): List<Int> { val winnerBoards = HashMap<Int, Pair<Int, Int>>() numbers.forEachIndexed { round, number -> boards.forEachIndexed { index, board -> val marked = booleans[index] board.forEachIndexed { y, row -> val x = row.indexOf(number) if (x > -1) marked[y][x] = true } if (hasBingo(marked)) { val unmarked = board.flatten().zip(marked.map { it.toList() }.flatten()).filter { !it.second } winnerBoards.putIfAbsent(index, Pair(round, unmarked.sumOf { it.first } * number)) } } } return winnerBoards.values.sortedBy { it.first }.map { it.second } } private fun hasBingo(booleans: Array<BooleanArray>): Boolean { booleans.forEach { row -> if (row.all { it }) return true } transpose(booleans).forEach { col -> if (col.all { it }) return true } return false } private fun transpose(A: Array<BooleanArray>): List<List<Boolean>> { return A.indices.map { i -> A.indices.map { j -> A[j][i] } } } }
0
Kotlin
0
0
d61c76eb431fa7b7b66be5b8549d4685a8dd86da
1,919
advent-of-code-kotlin
Creative Commons Zero v1.0 Universal
jk/src/main/kotlin/common/Trees.kt
lchang199x
431,924,215
false
{"Kotlin": 86230, "Java": 23581}
@file:JvmName("Trees") package common import java.util.* class KTreeNode(val data: Int, var left: KTreeNode? = null, var right: KTreeNode? = null) class TrieNode(var isWord: Boolean = false, val children: Array<TrieNode?> = arrayOfNulls(26)) /** * 二叉树的最大深度 * [](https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/) */ fun maxDepth(root: KTreeNode?): Int { return if (root == null) 0 else (1 + maxOf(maxDepth(root.left), maxDepth(root.right))) } /** * 二叉树的最小深度 * [](https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/) * 注意 left 为null时,最小深度不是 1 + 0,而是 1 + minDepth(right) */ fun minDepth(root: KTreeNode?): Int { if (root == null) return 0 return if (root.left == null) minDepth(root.right) + 1 else if (root.right == null) minDepth(root.left) + 1 else 1 + minOf(minDepth(root.left), minDepth(root.right)) } fun KTreeNode?.printPretty() { if (this == null) return println("NULL_TREE!") show() } /** * 二叉树反序列化:Recursion * * 输入为前序遍历的结果 [3,9,null,null,20,15,null,null,7,null,null] * * 3 * / \ * 9 20 * / \ * 15 7 */ fun buildBinaryTree2(arr: Array<Int?>?): KTreeNode { if (arr.isNullOrEmpty()) return KTreeNode(-1) val i = intArrayOf(0) return deserialize(arr, i)!! } private fun deserialize(arr: Array<Int?>, i: IntArray): KTreeNode? { // i[0]要每次迭代都更新,即使return null // 只有用带个元素的数组记录下标,这里return掉之后还能传递给下一轮迭代中的i val value = arr[i[0]++] ?: return null val node = KTreeNode(value) node.left = deserialize(arr, i) node.right = deserialize(arr, i) return node } /** * 二叉树反序列化 * * 输入为层序遍历的结果 [3,9,20,null,null,15,7] * * 3 * / \ * 9 20 * / \ * 15 7 */ fun buildBinaryTree(arr: Array<Int?>?): KTreeNode { if (arr.isNullOrEmpty()) return KTreeNode(-1) val root = KTreeNode(arr[0]!!) val queue: Queue<KTreeNode> = LinkedList() queue.offer(root) var count = 1 while (!queue.isEmpty()) { val node = queue.poll() if (count < arr.size) { arr[count++]?.let { node.left = KTreeNode(it) queue.offer(node.left) } } if (count < arr.size) { arr[count++]?.let { node.right = KTreeNode(it) queue.offer(node.right) } } } return root } /** * 二叉树的前序遍历: Recursion * [](https://leetcode-cn.com/problems/binary-tree-preorder-traversal/) */ fun preorderTraversal(root: KTreeNode?): List<Int> { if (root == null) return emptyList() val result = mutableListOf<Int>() preorder(root, result) return result } /** * 二叉树的前序遍历:Iteration * [](https://leetcode-cn.com/problems/binary-tree-preorder-traversal/) */ fun preorderTraversal2(root: KTreeNode?): List<Int> { if (root == null) return emptyList() val result = mutableListOf<Int>() var cur = root val stack = Stack<KTreeNode>() while (cur != null || !stack.isEmpty()) { while (cur != null) { result.add(cur.data) stack.push(cur) cur = cur.left } cur = stack.pop() cur = cur.right } return result } private fun preorder(root: KTreeNode?, list: MutableList<Int>) { if (root == null) return list.add(root.data) preorder(root.left, list) preorder(root.right, list) } /** * 二叉树的中序遍历: Recursion * [](https://leetcode-cn.com/problems/binary-tree-inorder-traversal/) */ fun inorderTraversal(root: KTreeNode?): List<Int> { if (root == null) return emptyList() val result = mutableListOf<Int>() inorder(root, result) return result } /** * 二叉树的中序遍历: Iteration * [](https://leetcode-cn.com/problems/binary-tree-inorder-traversal/) */ fun inorderTraversal2(root: KTreeNode?): List<Int> { if (root == null) return emptyList() val result = mutableListOf<Int>() var cur = root val stack = Stack<KTreeNode>() // cur为空时表示上一轮cur.right为空,stack里面还是有的 while (cur != null || !stack.isEmpty()) { while (cur != null) { stack.push(cur) cur = cur.left } cur = stack.pop() // 每轮循环只遍历这一个节点 result.add(cur.data) cur = cur.right } return result } private fun inorder(root: KTreeNode?, list: MutableList<Int>) { if (root == null) return inorder(root.left, list) list.add(root.data) inorder(root.right, list) } /** * 二叉树的后序遍历: Recursion * [](https://leetcode-cn.com/problems/binary-tree-postorder-traversal/) */ fun postorderTraversal(root: KTreeNode?): List<Int> { if (root == null) return emptyList() val result = mutableListOf<Int>() postorder(root, result) return result } /** * 二叉树的后序遍历: Iteration * [](https://leetcode-cn.com/problems/binary-tree-postorder-traversal/) */ fun postorderTraversal2(root: KTreeNode?): List<Int> { if (root == null) return emptyList() val result = mutableListOf<Int>() var cur = root // var pre = null as KTreeNode? var pre: KTreeNode? = null val stack = Stack<KTreeNode>() while (cur != null || !stack.isEmpty()) { while (cur != null) { stack.push(cur) cur = cur.left } // peek vs pop cur = stack.peek() // 到达一个节点时先检查它的右子树有没有遍历过 if (cur.right != null && cur.right != pre) { cur = cur.right } else { stack.pop() result.add(cur.data) pre = cur cur = null } } return result } private fun postorder(root: KTreeNode?, list: MutableList<Int>) { if (root == null) return inorder(root.left, list) inorder(root.right, list) list.add(root.data) } /** * 二叉树的层序遍历,广度优先遍历 bfs: breadth first search * 用队列,按节点输出 */ fun levelOrderTraversal2(root: KTreeNode?): List<Int> { val queue: Queue<KTreeNode> = LinkedList() queue.offer(root ?: return emptyList()) val result = mutableListOf<Int>() while (!queue.isEmpty()) { val temp = queue.poll() result.add(temp.data) temp.left?.let { queue.offer(it) } temp.right?.let { queue.offer(it) } } return result } /** * 二叉树的层序遍历,广度优先遍历 bfs: breadth first search * [](https://leetcode-cn.com/problems/binary-tree-level-order-traversal/) * 用队列,按层输出 */ fun levelOrderTraversal(root: KTreeNode?): List<List<Int>> { val queue: Queue<KTreeNode> = LinkedList() queue.offer(root ?: return emptyList()) val result = mutableListOf<List<Int>>() while (!queue.isEmpty()) { // 想用clear? 每次add到result时ArrayList(list)包装一下就行了 val list = mutableListOf<Int>() for (i in queue.indices) { val node = queue.poll() list.add(node.data) node.left?.let { queue.offer(it) } node.right?.let { queue.offer(it) } } result.add(list) } return result } /** * 二叉树锯齿形层序遍历 * [](https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/) * 控制list顺序,而不是控制queue顺序 */ fun zigzagLevelOrderTraversal(root: KTreeNode?): List<List<Int>> { if (root == null) return emptyList() val queue: Queue<KTreeNode> = LinkedList() queue.offer(root) val result = mutableListOf<List<Int>>() var leftToRight = true while (!queue.isEmpty()) { val list = LinkedList<Int>() for (i in queue.indices) { val node = queue.poll() node.left?.let { queue.offer(it) } node.right?.let { queue.offer(it) } if (leftToRight) { list.offerLast(node.data) } else { list.offerFirst(node.data) } } result.add(list) leftToRight = !leftToRight } return result } @JvmField val NULL_TREE: KTreeNode? = null fun main() { NULL_TREE.printPretty() tree1.printPretty() tree2.printPretty() tree3.printPretty() println("\nlevel order:") println(levelOrderTraversal(tree1)) println(levelOrderTraversal(tree2)) println(levelOrderTraversal(tree3)) println("\nzigzag level order:") println(zigzagLevelOrderTraversal(tree1)) println(zigzagLevelOrderTraversal(tree2)) println(zigzagLevelOrderTraversal(tree3)) println("\npre order:") println(preorderTraversal(tree1)) println(preorderTraversal(tree2)) println(preorderTraversal(tree3)) println("\nin order:") println(inorderTraversal(tree1)) println(inorderTraversal(tree2)) println(inorderTraversal(tree3)) println("\npost order:") // println(postorderTraversal(NULL_TREE)) println(postorderTraversal(tree1)) println(postorderTraversal(tree2)) println(postorderTraversal(tree3)) println("\nmax depth:") println(maxDepth(tree1)) println(maxDepth(tree2)) println(maxDepth(tree3)) println("\nmin depth:") println(minDepth(tree1)) println(minDepth(tree2)) println(minDepth(tree3)) }
0
Kotlin
0
0
52a008325dd54fed75679f3e43921fcaffd2fa31
9,562
Codelabs
Apache License 2.0
src/Day09.kt
jimmymorales
572,156,554
false
{"Kotlin": 33914}
fun main() { fun part1(input: List<String>, knotsCount: Int = 2): Int = buildSet { val knots = Array(knotsCount) { 0 to 0 } input.map { line -> line.split(' ').let { it[0] to it[1].toInt() } } .forEach { move -> repeat(move.second) { knots[0] = knots[0].let { when (move.first) { "R" -> (it.first + 1) to it.second "L" -> (it.first - 1) to it.second "U" -> it.first to (it.second + 1) else -> it.first to (it.second - 1) } } for (i in 0 until knots.lastIndex) { val (headX, headY) = knots[i] var (tailX, tailY) = knots[i + 1] if (tailX in headX - 1..headX + 1 && tailY in headY - 1..headY + 1) { continue } if (headY == tailY) { tailX += if (headX > tailX) 1 else -1 } else if (headX == tailX) { tailY += if (headY > tailY) 1 else -1 } else { tailX += if (headX > tailX) 1 else -1 tailY += if (headY > tailY) 1 else -1 } knots[i + 1] = tailX to tailY } add(knots.last()) } } }.count() fun part2(input: List<String>): Int = part1(input, knotsCount = 10) // test if implementation meets criteria from the description, like: val testInput = readInput("Day09_test") check(part1(testInput) == 88) val input = readInput("Day09") println(part1(input)) // part 2 check(part2(testInput) == 36) println(part2(input)) }
0
Kotlin
0
0
fb72806e163055c2a562702d10a19028cab43188
1,946
advent-of-code-2022
Apache License 2.0
src/main/kotlin/d19/D19_1.kt
MTender
734,007,442
false
{"Kotlin": 108628}
package d19 import d13.split import input.Input data class Part( val x: Int, val m: Int, val a: Int, val s: Int ) { constructor(values: List<Int>) : this(values[0], values[1], values[2], values[3]) fun getTotal(): Int { return x + m + a + s } } fun parseWorkflows(lines: List<String>): Map<String, List<Pair<(Part) -> Boolean, String>>> { return lines.map { line -> val parts = line.split("{", "}") val name = parts[0] val workflow = parts[1] val rules: List<Pair<(Part) -> Boolean, String>> = workflow.split(",").map rules@{ ruleStr -> val conditionAndTarget = ruleStr.split(":") if (conditionAndTarget.size == 1) { val target = conditionAndTarget[0] val condition = { _: Part -> true } return@rules Pair(condition, target) } val conditionStr = conditionAndTarget[0] val target = conditionAndTarget[1] val condition = when (conditionStr[1]) { '>' -> { when (conditionStr[0]) { 'x' -> { part: Part -> part.x > conditionStr.substring(2).toInt() } 'm' -> { part: Part -> part.m > conditionStr.substring(2).toInt() } 'a' -> { part: Part -> part.a > conditionStr.substring(2).toInt() } 's' -> { part: Part -> part.s > conditionStr.substring(2).toInt() } else -> throw RuntimeException("unknown field") } } '<' -> { when (conditionStr[0]) { 'x' -> { part: Part -> part.x < conditionStr.substring(2).toInt() } 'm' -> { part: Part -> part.m < conditionStr.substring(2).toInt() } 'a' -> { part: Part -> part.a < conditionStr.substring(2).toInt() } 's' -> { part: Part -> part.s < conditionStr.substring(2).toInt() } else -> throw RuntimeException("unknown field") } } else -> throw RuntimeException("unknown operation") } return@rules Pair(condition, target) } Pair(name, rules) }.toMap() } fun parseParts(lines: List<String>): List<Part> { return lines .map { it.replace("[\\p{Alpha}{}=]".toRegex(), "") } .map { line -> Part(line.split(",").map { it.toInt() }) } } fun applyWorkflow( part: Part, workflowLabel: String, workflows: Map<String, List<Pair<(Part) -> Boolean, String>>> ): Int { val workflow = workflows[workflowLabel]!! for (rule in workflow) { if (rule.first.invoke(part)) { return when (rule.second) { "A" -> part.getTotal() "R" -> 0 else -> applyWorkflow(part, rule.second, workflows) } } } throw RuntimeException("all rules were rejected") } fun main() { val lines = Input.read("input.txt") val workflowsAndParts = lines.split { it.isEmpty() } val workflows = parseWorkflows(workflowsAndParts[0]) val parts = parseParts(workflowsAndParts[1]) var sum = 0 for (part in parts) { val partSum = applyWorkflow(part, "in", workflows) sum += partSum } println(sum) }
0
Kotlin
0
0
a6eec4168b4a98b73d4496c9d610854a0165dbeb
3,450
aoc2023-kotlin
MIT License
src/Day04.kt
KristianAN
571,726,775
false
{"Kotlin": 9011}
fun List<String>.rangeToList(): List<Int> = this.map {num -> num.toInt()}.let { (it[0]..it[1]).toList() } fun List<List<Int>>.overlaps(): Boolean = this[0].intersect(this[1].toSet()).let { it.size == this[0].size || it.size == this[1].size } fun List<List<Int>>.containsItem(): Boolean = this[0].intersect(this[1].toSet()).isNotEmpty() fun main() { fun part1(input: List<String>): Int = input.fold(0) { acc, s -> if (s.split(",").map { it.split("-").rangeToList() }.overlaps()) acc + 1 else acc } fun part2(input: List<String>): Int = input.fold(0) { acc, s -> if (s.split(",").map { it.split("-").rangeToList() }.containsItem()) acc + 1 else acc } val input = readInput("day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
3a3af6e99794259217bd31b3c4fd0538eb797941
823
AoC2022Kt
Apache License 2.0
src/day07/Code.kt
fcolasuonno
572,734,674
false
{"Kotlin": 63451, "Dockerfile": 1340}
package day07 import readInput sealed class Day06Node { abstract val size: Int } private class File(override val size: Int) : Day06Node() private class Dir( val fileContents: MutableMap<String, File> = mutableMapOf(), val dirContents: MutableMap<String, Dir> = mutableMapOf(), val parent: Dir? = null ) : Day06Node(), Iterable<Dir> { override val size: Int by lazy { fileContents.values.sumOf { it.size } + dirContents.values.sumOf { it.size } } override fun iterator() = iterator { yield(this@Dir) dirContents.values.forEach { yieldAll(it) } } } fun main() { fun parse(input: List<String>) = Dir().apply { -> input.filter { it != "$ ls" } //ls is useLS .drop(1) //already created root node .map { it.split(" ") } .fold(this) { cwd, command -> if (command[0] == "$" && command[1] == "cd") { val newDir = command[2] requireNotNull(if (newDir == "..") cwd.parent else cwd.dirContents[newDir]) //new cwd } else { cwd.apply { val name = command[1] if (command[0] == "dir") { dirContents[name] = Dir(parent = cwd) } else { fileContents[name] = File(command[0].toInt()) } } } } } fun part1(input: Dir) = input.map { it.size }.filter { it < 100000 }.sumOf { it } fun part2(input: Dir): Int { val total = 70000000 val free = total - input.size val required = 30000000 - free return input.map { it.size }.filter { it >= required }.minOf { it } } val input = parse(readInput(::main.javaClass.packageName)) println("Part1=\n" + part1(input)) println("Part2=\n" + part2(input)) }
0
Kotlin
0
0
9cb653bd6a5abb214a9310f7cac3d0a5a478a71a
1,949
AOC2022
Apache License 2.0
src/Day13.kt
szymon-kaczorowski
572,839,642
false
{"Kotlin": 45324}
fun main() { data class ListOrInt(var children: MutableList<ListOrInt> = mutableListOf(), var value: Int? = null) : Comparable<ListOrInt> { var parent: ListOrInt? = null override fun compareTo(other: ListOrInt): Int { if (this.value != null) { if (other.value != null) { return value!! - other.value!! } else return ListOrInt(children = mutableListOf(this)).compareTo(other) } else { if (other.value != null) { return this.compareTo(ListOrInt(children = mutableListOf(other))) } else { for (i in 0..maxOf(this.children.lastIndex, other.children.lastIndex)) { if (i > this.children.lastIndex) return -1 if (i > other.children.lastIndex) return 1 val compareTo = this.children[i].compareTo(other.children[i]) if (compareTo != 0) { return compareTo } } return 0 } } } } fun String.parse(): ListOrInt { val asChars = this.toCharArray() var currentElement = ListOrInt() val root = currentElement asChars.forEach { char -> if (char == '[') { currentElement.children.add(ListOrInt()) val parent = currentElement currentElement = currentElement.children.last() currentElement.parent = parent } if (char == ']') { currentElement = currentElement.parent!! } if (char.isDigit()) { if (currentElement.value != null) { currentElement.value = currentElement.value!! * 10 + char.digitToInt() } else { currentElement.value = char.digitToInt() } } if (char == ',') { currentElement.parent!!.children.add(ListOrInt()) val parent = currentElement.parent!! currentElement = parent.children.last() currentElement.parent = parent } } return root } fun part1(input: List<String>): Int { var max = 0; var index = 0 for (signal in input.indices step 3) { index++ val left = input[signal].parse() val right = input[signal + 1].parse() if (left < right) { max += index } } return max } fun part2(input: List<String>): Int { val first = "[2]".parse() val second = "[6]".parse() var mult = 1 val newInput = input + listOf("[2]", "[6]") val map = newInput.filterNot { it.isBlank() }.map { it.parse() }.sorted() map.forEachIndexed { index, list -> if (list == first || list == second) { mult *= index + 1 } } return mult } // test if implementation meets criteria from the description, like: val testInput = readInput("Day13_test") check(part1(testInput) == 13) check(part2(testInput) == 140) val input = readInput("Day13") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1d7ab334f38a9e260c72725d3f583228acb6aa0e
3,421
advent-2022
Apache License 2.0
src/Day03.kt
Frendzel
573,198,577
false
{"Kotlin": 5336}
fun String.intersectedItems(): Set<Char> = listOf( substring(0..length / 2), substring(length / 2) ).intersectedItems() fun Char.priority(): Int = when (this) { in 'a'..'z' -> (this.code - 97) + 1 in 'A'..'Z' -> (this.code - 65) + 27 else -> throw IllegalArgumentException("Letter in wrong range: $this") } fun List<String>.intersectedItems(): Set<Char> = map { it.toSet() } .reduce { left, right -> left intersect right } fun main() { fun part1(input: List<String>): Int = input.sumOf { it.intersectedItems().map(Char::priority).first() } fun part2(input: List<String>): Int = input.chunked(3).sumOf { it -> it.intersectedItems().sumOf { it.priority() } } val testInput = readInput("Day03_test") val part1 = part1(testInput) println(part1) check(part1 == 7845) val part2 = part2(testInput) println(part2) check(part2 == 2790) }
0
Kotlin
0
0
a8320504be93dfba1f634413a50e7240d16ba6d9
1,020
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/dev/bogwalk/batch7/Problem72.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch7 import kotlin.math.sqrt /** * Problem 72: Counting Fractions * * https://projecteuler.net/problem=72 * * Goal: Count the elements in a set of reduced proper fractions for d <= N, i.e. order N. * * Constraints: 2 <= N <= 1e6 * * Reduced Proper Fraction: A fraction n/d, where n & d are positive integers, n < d, and * gcd(n, d) == 1. * * Farey Sequence: A sequence of completely reduced fractions, either between 0 and 1, or which * when in reduced terms have denominators <= N, arranged in order of increasing size. * * e.g. if d <= 8, the Farey sequence would be -> * 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, * 4/5, 5/6, 6/7, 7/8 * * e.g.: N = 8 * size = 21 */ class CountingFractions { /** * Solution based on the following Farey sequence properties: * * - The middle term of a sequence is always 1/2 for n > 1. * * - A sequence F(n) contains all elements of the previous sequence F(n-1) as well as an * additional fraction for each number < n & co-prime to n. e.g. F(6) consists of F(5) as * well as 1/6 & 5/6. * * Using Euler's totient (phi) function, the relationship between lengths becomes: * * F(n).size = F(n-1).size + phi(n) * * F(n).size = 0.5 * (3 + ({n}Sigma{d=1} mobius() * floor(n/d)^2)) * * F(n).size = 0.5n(n + 3) - ({n}Sigma{d=2} F(n/d).size) * * N.B. This solution does not count left & right ancestors of F(1), namely {0/1, 1/0}, so * these should be removed from the resulting length. * * SPEED (WORST) 67.85ms for N = 1e6 */ fun fareySequenceLengthFormula(order: Int): Long { val fCache = LongArray(order + 1).apply { this[1] = 2 } fun getLength(n: Int): Long { if (fCache[n] != 0L) return fCache[n] var length = (0.5 * n * (n + 3)).toLong() for (d in 2..n) { val next = n / d length -= if (fCache[next] != 0L) { fCache[next] } else { val newLength = getLength(next) fCache[next] = newLength newLength } } fCache[n] = length return length } return getLength(order) - 2 } /** * Solution uses Euler's product formula: * * Phi(n) = n * Pi(1 - (1/p)), with p being distinct prime factors of n. * * If prime factorisation means n = Pi(p_i^a_i), the above formula becomes: * * Phi(n) = Pi((p_i - 1) * p_i^(a_i - 1)) * * if m = n/p, then Phi(n) = Phi(m)p, if p divides m, else, Phi(m)(p - 1) * * This quickly calculates totients by first sieving the smallest prime factors & checking if * they are a multiple factor of n. * * Only odd numbers are included in the sieve, as all even numbers are handled together based * on the following where k > 0 and n is odd: * * {m}Pi{k=0}(Phi(n2^k)) = (1 + {m}Pi{k=1}(2^(k-1)) * Phi(n) = 2^m * Phi(n)) * * SPEED (BEST) 14.11ms for N = 1e6 */ fun fareySequenceLengthSieve(limit: Int): Long { val sieveLimit = (sqrt(1.0 * limit).toInt() - 1) / 2 val maxI = (limit - 1) / 2 val cache = IntArray(maxI + 1) for (n in 1..sieveLimit) { // sieve the smallest prime factors if (cache[n] == 0) { // 2n + 1 is prime val p = 2 * n + 1 for (k in (2 * n * (n + 1)..maxI) step p) { if (cache[k] == 0) { cache[k] = p } } } } // find largest multiplier (m) where 2^m * n <= N, i.e. the largest power of 2 var multiplier = 1 while (multiplier <= limit) { multiplier *= 2 } multiplier /= 2 // num of reduced proper fractions whose denominator is power of 2 var count = 1L * multiplier - 1 // decrement to exclude fraction 1/1 multiplier /= 2 // set to 2^(m-1) // the smallest index such that (2n + 1) * 2^(m-1) > N var stepI = (limit / multiplier + 1) / 2 for (n in 1..maxI) { if (n == stepI) { multiplier /= 2 // set to next smallest power of 2 stepI = (limit / multiplier + 1) / 2 // this maintains the invariant: (2n + 1)m <= N < (2n + 1)2m } if (cache[n] == 0) { cache[n] = 2 * n } else { val p = cache[n] val cofactor = (2 * n + 1) / p // calculate Phi(2n + 1) val factor = if (cofactor % p == 0) p else p - 1 cache[n] = factor * cache[cofactor/2] } // add sum of totients of all 2^k * (2n + 1) < N count += multiplier * cache[n] } return count } /** * Solution still uses a sieve, as in the above solution, but the sieve calculates the * totient of all k multiples of primes <= [limit] based on the following: * * current Phi(p_k) = previous Phi(p_k) * (1 - (1/p)) * * current Phi(p_k) = previous Phi(p_k) - previous Phi(p_k)/p * * Then the size of each sequence order is cached based on: * * F(n).size = F(n-1).size + phi(n) * * SPEED (BETTER) 60.13ms for N = 1e6 * * @return array of Farey sequence lengths for every index = order N. */ fun generateAllFareyLengths(limit: Int): LongArray { val phiCache = IntArray(limit + 1) { it } for (n in 2..limit) { if (phiCache[n] == n) { // n is prime // calculate Phi of all multiples of n for (k in n..limit step n) { phiCache[k] -= phiCache[k] / n } } } val counts = LongArray(limit + 1) for (n in 2..limit) { counts[n] = counts[n-1] + phiCache[n] } return counts } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
6,179
project-euler-kotlin
MIT License
src/Day10.kt
mkfsn
573,042,358
false
{"Kotlin": 29625}
fun main() { data class Instruction(val operator: String, val value: Int) class Solution(input: List<String>) { val instructions: List<Instruction> init { this.instructions = input.map { it.split(" ").run { Instruction(this[0], if (this.size == 1) 0 else this[1].toInt()) } } } fun calculateSignalStrengths(): Int { fun addSignalStrengths(signalStrengths: MutableList<Int>, cycle: Int, register: Int) { if ((cycle - 20) % 40 == 0) signalStrengths.add(cycle * register) } var (cycle, register) = listOf(1, 1) return this.instructions.fold(mutableListOf<Int>()) { signalStrengths, instruction -> addSignalStrengths(signalStrengths, cycle, register) when (instruction.operator) { "noop" -> cycle += 1 "addx" -> { cycle += 1 addSignalStrengths(signalStrengths, cycle, register) register += instruction.value cycle += 1 } } signalStrengths }.sum() } fun render(): String { fun addPixel(pixels: MutableList<Char>, cycle: Int, register: Int) = pixels.add(if ((cycle - 1) % 40 in register - 1..register + 1) '#' else '.') var (cycle, register) = listOf(1, 1) return this.instructions.fold(mutableListOf<Char>()) { pixels, instruction -> addPixel(pixels, cycle, register) when (instruction.operator) { "noop" -> cycle += 1 "addx" -> { cycle += 1 addPixel(pixels, cycle, register) register += instruction.value cycle += 1 } } pixels }.chunked(40).joinToString("\n") { it.joinToString("") } } } fun part1(input: List<String>): Int = Solution(input).calculateSignalStrengths() fun part2(input: List<String>): String = Solution(input).render() // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput) == 13140) check(part2(testInput) == """ ##..##..##..##..##..##..##..##..##..##.. ###...###...###...###...###...###...###. ####....####....####....####....####.... #####.....#####.....#####.....#####..... ######......######......######......#### #######.......#######.......#######..... """.trimIndent() ) val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
8c7bdd66f8550a82030127aa36c2a6a4262592cd
2,791
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/de/pgebert/aoc/days/Day17.kt
pgebert
724,032,034
false
{"Kotlin": 65831}
package de.pgebert.aoc.days import de.pgebert.aoc.Day import java.util.* class Day17(input: String? = null) : Day(17, "Day17", input) { data class Node(val x: Int, val y: Int, val direction: Direction, val directionCount: Int) enum class Direction { NORTH, SOUTH, EAST, WEST } private val map = inputList.map { line -> line.map { it.digitToInt() } } override fun partOne() = findPathOfMinimalLoss(maxConsecutiveBlocks = 3) override fun partTwo() = findPathOfMinimalLoss(minConsecutiveBlocks = 4, maxConsecutiveBlocks = 10) private fun findPathOfMinimalLoss( minConsecutiveBlocks: Int = 0, maxConsecutiveBlocks: Int = Int.MAX_VALUE ): Int { val losses = mutableMapOf<Node, Int>().withDefault { Int.MAX_VALUE } val predecessors = mutableMapOf<Node, Node>() val compareByLoss: Comparator<Node> = compareBy { losses.getValue(it) } val queue = PriorityQueue<Node>(compareByLoss) listOf( Node(0, 0, Direction.EAST, 1), Node(0, 0, Direction.SOUTH, 1) ).forEach { losses[it] = 0 queue += it } while (queue.isNotEmpty()) { val current = queue.remove() val neighbours = buildList { if (current.directionCount < minConsecutiveBlocks) { current.moveInto(current.direction)?.also { add(it) } } else { Direction.values().forEach { direction -> current.moveInto(direction) ?.takeIf { it.directionCount <= maxConsecutiveBlocks } ?.also { add(it) } } } } neighbours.forEach { neighbour -> val alternative = losses.getValue(current) + map[neighbour.x][neighbour.y] if (alternative < losses.getValue(neighbour)) { losses[neighbour] = alternative predecessors[neighbour] = current queue.add(neighbour) } } } return losses.filterKeys { it.x == map.size - 1 && it.y == map[map.size - 1].size - 1 }.minOf { it.value } } private fun Node.moveInto(direction: Direction): Node? { val isOppositeDirection = when (direction) { Direction.NORTH -> this.direction == Direction.SOUTH Direction.SOUTH -> this.direction == Direction.NORTH Direction.EAST -> this.direction == Direction.WEST Direction.WEST -> this.direction == Direction.EAST } if (isOppositeDirection) return null val (newX, newY) = when (direction) { Direction.NORTH -> Pair(x - 1, y) Direction.SOUTH -> Pair(x + 1, y) Direction.EAST -> Pair(x, y + 1) Direction.WEST -> Pair(x, y - 1) } if (newX !in map.indices || newY !in map[newX].indices) return null val newDirectionCount = if (direction == this.direction) directionCount + 1 else 1 return Node(newX, newY, direction, newDirectionCount) } }
0
Kotlin
1
0
a30d3987f1976889b8d143f0843bbf95ff51bad2
3,153
advent-of-code-2023
MIT License
src/main/kotlin/de/tek/adventofcode/y2022/day02/RockPaperScissors.kt
Thumas
576,671,911
false
{"Kotlin": 192328}
package de.tek.adventofcode.y2022.day02 import de.tek.adventofcode.y2022.util.readInputLines enum class Result(val score: Int) { Win(6), Lose(0), Draw(3); fun invert(): Result = when (this) { Win -> Lose Lose -> Win Draw -> Draw } } enum class Choice(val score: Int) { Rock(1), Paper(2), Scissors(3); private fun getInferior(): Choice = when (this) { Rock -> Scissors Paper -> Rock Scissors -> Paper } private fun getSuperior(): Choice = when (this) { Rock -> Paper Paper -> Scissors Scissors -> Rock } infix fun playAgainst(other: Choice) = when (other) { this -> { Result.Draw } this.getSuperior() -> { Result.Lose } else -> { Result.Win } } fun choiceToResultIn(result: Result) = when (result) { Result.Draw -> this Result.Lose -> this.getSuperior() Result.Win -> this.getInferior() } } fun Char.toChoice() = with(this.uppercaseChar()) { when (this) { 'A' -> Choice.Rock 'X' -> Choice.Rock 'B' -> Choice.Paper 'Y' -> Choice.Paper 'C' -> Choice.Scissors 'Z' -> Choice.Scissors else -> throw IllegalArgumentException("$this is not a valid encoding for a choice.") } } fun Char.toResult() = with(this.uppercaseChar()) { when (this) { 'X' -> Result.Lose 'Y' -> Result.Draw 'Z' -> Result.Win else -> throw IllegalArgumentException("$this is not a valid encoding for a result.") } } typealias Move = Pair<Choice, Choice> fun String.toMove(): Move { val choices = this.split(' ').map { it[0] }.map { it.toChoice() } return Move(choices[0], choices[1]) } fun String.toAlternativeMove(): Move { val input = this.split(' ').map { it[0] } val otherChoice = input[0].toChoice() val expectedResultForYou = input[1].toResult() val expectedResultForOther = expectedResultForYou.invert() val yourMove = otherChoice.choiceToResultIn(expectedResultForOther) return Move(otherChoice, yourMove) } class Game { var otherScore = 0 private set var yourScore = 0 private set fun play(move: Move): Game { return play(move.first, move.second) } private fun play(yourChoice: Choice, otherChoice: Choice): Game { otherScore += yourChoice.score + (yourChoice playAgainst otherChoice).score yourScore += otherChoice.score + (otherChoice playAgainst yourChoice).score return this } } fun List<Move>.play() = this.fold(Game()) { game, move -> game.play(move) } fun main() { val input = readInputLines(Game::class) val finalScore = input.map { it.toMove() }.play().yourScore println("The final score using the first encoding would be $finalScore.") val alternativeScore = input.map { it.toAlternativeMove() }.play().yourScore println("The final score using the alternative encoding would be $alternativeScore.") }
0
Kotlin
0
0
551069a21a45690c80c8d96bce3bb095b5982bf0
3,334
advent-of-code-2022
Apache License 2.0
year2019/src/main/kotlin/net/olegg/aoc/year2019/day10/Day10.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2019.day10 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.Vector2D import net.olegg.aoc.utils.gcd import net.olegg.aoc.year2019.DayOf2019 import kotlin.math.atan2 import kotlin.math.sign /** * See [Year 2019, Day 10](https://adventofcode.com/2019/day/10) */ object Day10 : DayOf2019(10) { override fun first(): Any? { val asteroids = lines .flatMapIndexed { y, line -> line.mapIndexedNotNull { x, c -> if (c == '#') Vector2D(x, y) else null } } val visible = asteroids.map { base -> asteroids.filter { it != base } .map { base.direction(it) } .distinct() .count() } return visible.max() } override fun second(): Any? { val asteroids = lines .flatMapIndexed { y, line -> line.mapIndexedNotNull { x, c -> if (c == '#') Vector2D(x, y) else null } } val base = asteroids.maxBy { curr: Vector2D -> asteroids.filter { it != curr } .map { curr.direction(it) } .distinct() .count() } val lines = (asteroids - base) .groupBy { other -> base.direction(other) } .mapValues { (_, line) -> line.sortedBy { (it - base).length2() } } .toList() .map { (dir, list) -> atan2(-dir.y.toDouble(), dir.x.toDouble()) to list } .sortedByDescending { it.first } val linesFromTop = (lines.dropWhile { it.first > atan2(1.0, 0.0) } + lines.takeWhile { it.first > atan2(1.0, 0.0) }) .map { it.second } val maxLength = linesFromTop.maxOf { it.size } val ordered = (0..<maxLength).flatMap { pos -> linesFromTop.mapNotNull { line -> line.getOrNull(pos) } } return ordered[199].let { it.x * 100 + it.y } } private fun Vector2D.direction(other: Vector2D): Vector2D { val diff = other - this return when { diff.x == 0 -> Vector2D(0, diff.y.sign) diff.y == 0 -> Vector2D(diff.x.sign, 0) else -> Vector2D(diff.x / gcd(diff.x, diff.y), diff.y / gcd(diff.x, diff.y)) } } } fun main() = SomeDay.mainify(Day10)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
2,064
adventofcode
MIT License
src/Day08.kt
psabata
573,777,105
false
{"Kotlin": 19953}
import kotlin.math.max fun main() { val testInput = Day08.Forrest(InputHelper("Day08_test.txt").readLines()) check(testInput.part1() == 21) check(testInput.part2() == 8) val input = Day08.Forrest(InputHelper("Day08.txt").readLines()) println("Part 1: ${input.part1()}") println("Part 2: ${input.part2()}") } object Day08 { class Forrest(input: List<String>) { private val trees: List<List<Int>> = input.map { line -> line.map { it.digitToInt() } } fun part1(): Int { var visibleTrees = 0 trees.forEachIndexed { y, row -> row.forEachIndexed { x, _ -> if (trees.isVisible(x, y)) visibleTrees++ } } return visibleTrees } fun part2(): Int { var scenicScore = 0 trees.forEachIndexed { y, row -> row.forEachIndexed { x, _ -> scenicScore = max(trees.scenicScore(x, y), scenicScore) } } return scenicScore } } private fun List<List<Int>>.scenicScore(x: Int, y: Int): Int { val scenicScore = scenicScore(x, y, Direction.UP) * scenicScore(x, y, Direction.DOWN) * scenicScore(x, y, Direction.LEFT) * scenicScore(x, y, Direction.RIGHT) // println("x: $x, y: $y, tree: ${this[y][x]}, scenicScore: $scenicScore") return scenicScore } private fun List<List<Int>>.isVisible(x: Int, y: Int): Boolean { val isVisible = isVisible(x, y, Direction.UP) || isVisible(x, y, Direction.DOWN) || isVisible(x, y, Direction.LEFT) || isVisible(x, y, Direction.RIGHT) // println("x: $x, y: $y, tree: ${this[y][x]}, visible: $isVisible") return isVisible } private fun List<List<Int>>.isVisible( x: Int, y: Int, direction: Direction, ): Boolean { var newX = x var newY = y do { newX += direction.dx newY += direction.dy if (newY in indices && newX in this[newY].indices) { if (this[newY][newX] >= this[y][x]) return false } else { return true } } while (true) } private fun List<List<Int>>.scenicScore( x: Int, y: Int, direction: Direction, ): Int { var newX = x var newY = y var scenicScore = 0 do { newX += direction.dx newY += direction.dy if (newY in indices && newX in this[newY].indices) { scenicScore++ if (this[newY][newX] >= this[y][x]) return scenicScore } else { return scenicScore } } while (true) } private enum class Direction(val dx: Int, val dy: Int) { UP(0, -1), DOWN(0, 1), LEFT(-1, 0), RIGHT(1, 0) } }
0
Kotlin
0
0
c0d2c21c5feb4ba2aeda4f421cb7b34ba3d97936
3,023
advent-of-code-2022
Apache License 2.0
src/Day03.kt
virtualprodigy
572,945,370
false
{"Kotlin": 8043}
fun main() { fun convertToPriorityPoint(item: Char): Int { //convert to Ascii val asciiVal = item.code return if (asciiVal < 97) { //upper case convert // println("converting $item upper $asciiVal -> ${asciiVal-38}") // 65 - 90 A - Z -> 27 - 52 asciiVal - 38 } else { // lower case convert // 97 - 123 a - z -> 1 - 26 // println("converting $item lower $asciiVal -> ${asciiVal-96}") asciiVal - 96 } } fun part1(input: List<String>): Int { val compartment1 = hashSetOf<Char>() var total = 0 for (rucksack in input) { compartment1.clear() val midpoint = rucksack.length / 2 rucksack.forEachIndexed { index, item -> if (index < midpoint) { // compartment 1 compartment1.add(item) } else { // compartment 2 if (compartment1.contains(item)) { total += convertToPriorityPoint(item) //remove from list 1, that item type has been marked already compartment1.remove(item) } } } } // println("Total is $total") return total } fun part2(input: List<String>): Int { val compartment1 = hashSetOf<Char>() var total = 0 // println("part2 ****") input.windowed(3, 3){ window -> val intersections = window[0].toSet() .intersect(window[1].toSet()) .intersect(window[2].toSet()) total += convertToPriorityPoint(intersections.first()) } return total } // 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
025f3ae611f71a00e9134f0e2ba4b602432eea93
2,034
advent-code-code-kotlin-jetbrains-2022
Apache License 2.0
09/part_one.kt
ivanilos
433,620,308
false
{"Kotlin": 97993}
import java.io.File fun readInput() : HeightMap { val inputLines = File("input.txt") .readLines() .map { line -> line.split("") .filter { it.isNotEmpty() } .map{ it.toInt() }} return HeightMap(inputLines) } class HeightMap(inputLines : List<List<Int>>) { companion object { val NEIGHBORS_DELTA = listOf(Pair(0, 1), Pair(1, 0), Pair(0, -1), Pair(-1, 0)) } val rows = inputLines.size val cols = inputLines[0].size val heights = inputLines fun getNeighbors(x : Int, y : Int) : List<Int> { val result = mutableListOf<Int>() for (delta in NEIGHBORS_DELTA) { val neighborX = x + delta.first val neighborY = y + delta.second if (isIn(neighborX, neighborY)) { result.add(heights[neighborX][neighborY]) } } return result.toList() } fun isIn(x : Int, y : Int) : Boolean { return x in 0 until rows && y in 0 until cols } fun isLowPoint(x : Int, y : Int) : Boolean { val height = heights[x][y] val neighbors = getNeighbors(x, y) return neighbors.none { it <= height } } } fun solve(heightMap : HeightMap) : Int { var result = 0 for (i in 0 until heightMap.rows) { for (j in 0 until heightMap.cols) { if (heightMap.isLowPoint(i, j)) { result += heightMap.heights[i][j] + 1 } } } return result } fun main() { val heightMap = readInput() val ans = solve(heightMap) println(ans) }
0
Kotlin
0
3
a24b6f7e8968e513767dfd7e21b935f9fdfb6d72
1,714
advent-of-code-2021
MIT License
src/Day02-2.kt
casslabath
573,177,204
false
{"Kotlin": 27085}
fun main() { val moves = mapOf( "A" to Move.ROCK, "X" to Move.ROCK, "B" to Move.PAPER, "Y" to Move.PAPER, "C" to Move.SCISSORS, "Z" to Move.SCISSORS) val movePoints = mapOf(Move.ROCK to 1, Move.PAPER to 2, Move.SCISSORS to 3) val winsAgainst = mapOf(Move.ROCK to Move.SCISSORS, Move.PAPER to Move.ROCK, Move.SCISSORS to Move.PAPER) val losesTo = mapOf(Move.ROCK to Move.PAPER, Move.PAPER to Move.SCISSORS, Move.SCISSORS to Move.ROCK) val gameResults = mapOf("X" to Result.LOSE, "Y" to Result.DRAW, "Z" to Result.WIN) val gameResultPoints = mapOf(Result.LOSE to 0, Result.DRAW to 3, Result.WIN to 6) /** * Calculate the result of the game and return the respective points. * Win = 6 pts * Draw = 3 pts * Lose = 0 pts */ fun calculateGameResultPoints(yourMove: Move?, opponentMove: Move?): Int { if (winsAgainst[yourMove] == opponentMove) { return 6 } else if (yourMove == opponentMove) { return 3 } return 0 } /** * Rules: * Rock = A or X 1pt * Paper = B or Y 2pt * Scissors = C or Z 3pt * * AX beats CZ * BY beats AX * CZ beats BY */ fun part1(input: List<String>): Int { var total = 0 input.map { val results = it.split(" ") // OpponentMove and yourMove will either be ROCK, PAPER or SCISSORS. val opponentMove = moves[results[0]] val yourMove = moves[results[1]] total += movePoints[yourMove]!! total += calculateGameResultPoints(yourMove, opponentMove) } return total } /** * Calculate what your move is from the game result and opponent move * and return the resulting points. */ fun calculateYourMovePoints(gameResult: Result?, opponentMove: Move?): Int { if (gameResult == Result.WIN) { return movePoints[losesTo[opponentMove]]!! } else if (gameResult == Result.DRAW) { return movePoints[opponentMove]!! } return movePoints[winsAgainst[opponentMove]]!! } /** * Rules: * Rock = A 1pt * Paper = B 2pt * Scissors = C 3pt * * X Lose 0pt * Y Draw 3pt * Z Win 6pt */ fun part2(input: List<String>): Int { var total = 0 input.map { val results = it.split(" ") // OpponentMove will be either ROCK, PAPER or SCISSORS. val opponentMove = moves[results[0]] // GameResult will be either LOSE, DRAW or WIN val gameResult = gameResults[results[1]] total += gameResultPoints[gameResult]!! total += calculateYourMovePoints(gameResult, opponentMove) } return total } val input = readInput("Day02") println(part1(input)) println(part2(input)) } enum class Move { ROCK, PAPER, SCISSORS } enum class Result { LOSE, DRAW, WIN }
0
Kotlin
0
0
5f7305e45f41a6893b6e12c8d92db7607723425e
3,044
KotlinAdvent2022
Apache License 2.0
src/Day07.kt
PauliusRap
573,434,850
false
{"Kotlin": 20299}
private const val COMMAND_CHANGE_DIR = "$ cd " private const val MOVE_BACK = ".." private const val PREFIX_DIRECTORY = "dir " fun main() { fun parseSystemFolderSizes(input: List<String>): List<Long> { val system = mutableMapOf<String, DirectoryInfo>() val fileRegex = "(\\d+) (\\D+)".toRegex() val fileLocation: MutableList<String> = mutableListOf() input.forEach { line -> if (line.startsWith(COMMAND_CHANGE_DIR)) { val directory = line.substringAfter(COMMAND_CHANGE_DIR) if (directory == MOVE_BACK) { fileLocation.removeLast() } else { fileLocation.add(directory) system.putIfAbsent(fileLocation.toString(), DirectoryInfo()) } } else if (line.matches(fileRegex)) { fileRegex.find(line)?.groups?.get(1)?.let { system[fileLocation.toString()]!!.size += it.value.toInt() system.forEach { (name, directoryInfo) -> if (directoryInfo.contains.contains(fileLocation.toString())) { system[name]!!.size += it.value.toInt() } } } } else if (line.startsWith(PREFIX_DIRECTORY)) { val dirName = line.substringAfter(PREFIX_DIRECTORY) system[fileLocation.toString()]!!.contains += (fileLocation + dirName).toString() system.forEach { (name, directoryInfo) -> if (directoryInfo.contains.contains(fileLocation.toString())) { system[name]!!.contains += (fileLocation + dirName).toString() } } } } return system.values.map { it.size } } fun part1(input: List<String>) = parseSystemFolderSizes(input).filter { it <= 100000 }.sum() fun part2(input: List<String>): Long { val system = parseSystemFolderSizes(input) val occupiedSpace = system.max() return system.filter { it >= 30_000_000L - (70_000_000L - occupiedSpace) }.min() } // test if implementation meets criteria from the description: val testInput = readInput("Day07_test") check(part1(testInput) == 95437L) check(part2(testInput) == 24933642L) val input = readInput("Day07") println(part1(input)) println(part2(input)) } data class DirectoryInfo( val contains: MutableList<String> = mutableListOf(), var size: Long = 0, )
0
Kotlin
0
0
df510c3afb104c03add6cf2597c433b34b3f7dc7
2,575
advent-of-coding-2022
Apache License 2.0
src/Day03.kt
esp-er
573,196,902
false
{"Kotlin": 29675}
package patriker.day03 import patriker.utils.* val Char.priority get(): Int{ if(this.isUpperCase()){ return this.code - 'A'.code + 27 } return this.code - 'a'.code + 1 } fun main() { val testInput = readInput("Day03_test") val input = readInput("Day03_input") println(solvePart1(testInput)) println(solvePart1(input)) check(solvePart2(testInput) == 70) println(solvePart2(input)) } fun solvePart1(input: List<String>): Int{ val overlapList = input.map{ contents -> val firstCompartment = contents.slice(0 until contents.length/2) val secondCompartment = contents.slice(contents.length/2 until contents.length) val overlap = firstCompartment .asSequence() .distinct() .filter{secondCompartment.contains(it)} overlap.sumOf(Char::priority) } return overlapList.sum() } fun solvePart2(input: List<String>): Int{ val commonItemScores = input.chunked(3){group -> val groupSet = group.map(String::toSet) val (ruck1, ruck2, ruck3) = groupSet val commonItem = ruck1 intersect ruck2 intersect ruck3 commonItem.sumOf(Char::priority) } return commonItemScores.sum() }
0
Kotlin
0
0
f46d09934c33d6e5bbbe27faaf2cdf14c2ba0362
1,257
aoc2022
Apache License 2.0
src/problems/day6/part1/part1.kt
klnusbaum
733,782,662
false
{"Kotlin": 43060}
package problems.day6.part1 import java.io.File import kotlin.math.ceil import kotlin.math.floor import kotlin.math.sqrt private const val inputFile = "input/day6/input.txt" //private const val testFile = "input/day6/test.txt" fun main() { val productOfNumBeats = File(inputFile).bufferedReader().useLines { multiplyNumBeats(it) } println("Product of number of ways to beat all races: $productOfNumBeats") } private fun multiplyNumBeats(lines: Sequence<String>): Int { val iterator = lines.iterator() val times = iterator.next().toTimes() val maxes = iterator.next().toMaxes() val races = times.zip(maxes) { time, max -> Race(time, max) } return races.map { it.numBeats() }.fold(1) { acc, next -> next * acc } } private fun String.toTimes(): List<Int> { return this.substringAfter("Time: ") .trim() .split("\\s+".toRegex()) .map { it.toInt() } } private fun String.toMaxes(): List<Int> { return this.substringAfter("Distance: ") .trim() .split("\\s+".toRegex()) .map { it.toInt() } } private data class Race(val time: Int, val currentMax: Int) { fun numBeats(): Int { val a = -1 val b = time val c = -currentMax val discriminant = sqrt(((b * b) - (4.0 * a * c))) val low = (-b + discriminant) / (2 * a) val high = (-b - discriminant) / (2 * a) val flooredHigh = floor(high) val ceiledLow = ceil(low) var numBeats = (flooredHigh - ceiledLow).toInt() + 1 if (flooredHigh == high) { numBeats-- } if (ceiledLow == low) { numBeats-- } return numBeats } }
0
Kotlin
0
0
d30db2441acfc5b12b52b4d56f6dee9247a6f3ed
1,687
aoc2023
MIT License
src/day21/day.kt
LostMekka
574,697,945
false
{"Kotlin": 92218}
package day21 import day21.Operation.Add import day21.Operation.Divide import day21.Operation.Multiply import day21.Operation.Subtract import util.readInput import util.shouldBe fun main() { val testInput = readInput(Input::class, testInput = true).parseInput() testInput.part1() shouldBe 152 testInput.part2() shouldBe 301 val input = readInput(Input::class).parseInput() println("output for part1: ${input.part1()}") println("output for part2: ${input.part2()}") } private enum class Operation(private val op: (Long, Long) -> Long) { Add({ a, b -> a + b }), Subtract({ a, b -> a - b }), Multiply({ a, b -> a * b }), Divide({ a, b -> a / b }), ; operator fun invoke(a: Long, b: Long) = op(a, b) } private sealed interface Node { val result: Long } private class Leaf( override val result: Long, ) : Node private class Branch( left: () -> Node, right: () -> Node, val operation: Operation, ) : Node { val left by lazy(left) val right by lazy(right) override val result by lazy { operation(this.left.result, this.right.result) } } private class Input( val root: Node, val human: Node, ) private fun List<String>.parseInput(): Input { val monkeysByName = buildMap { for (line in this@parseInput) { val parts = line.split(" ") val name = parts.first().removeSuffix(":") val monkey = when (parts.size) { 2 -> Leaf(parts.last().toLong()) 4 -> Branch( left = { this.getValue(parts[1]) }, right = { this.getValue(parts[3]) }, operation = when (parts[2]) { "+" -> Add "-" -> Subtract "*" -> Multiply "/" -> Divide else -> error("unknown operator in line: $line") } ) else -> error("could not parse line: $line") } put(name, monkey) } } return Input( root = monkeysByName["root"] ?: error("root monkey not found in input"), human = monkeysByName["humn"] ?: error("human not found in input"), ) } private fun Input.part1(): Long { return root.result } private data class PathSegment( val operation: Operation, val humanIsLeft: Boolean, val otherValue: Long, ) private fun Node.findPathTo(target: Node): List<PathSegment>? { if (this === target) return emptyList() when (this) { is Leaf -> return null is Branch -> { val leftResult = left.findPathTo(target) if (leftResult != null) return leftResult + PathSegment(operation, true, right.result) val rightResult = right.findPathTo(target) if (rightResult != null) return rightResult + PathSegment(operation, false, left.result) return null } } } private fun Input.part2(): Long { val path = root.findPathTo(human)?.toMutableList() ?: error("cannot reach human from root") var number = path.removeLast().otherValue while (path.isNotEmpty()) { val (operation, humanIsLeft, otherValue) = path.removeLast() when (operation) { Add -> number -= otherValue Subtract -> number = if (humanIsLeft) otherValue + number else otherValue - number Multiply -> number /= otherValue Divide -> number = if (humanIsLeft) otherValue * number else otherValue / number } } return number }
0
Kotlin
0
0
58d92387825cf6b3d6b7567a9e6578684963b578
3,583
advent-of-code-2022
Apache License 2.0
src/Day14.kt
maewCP
579,203,172
false
{"Kotlin": 59412}
fun main() { fun prepareInput(input: List<String>) : Pair<MutableMap<Pair<Int, Int>, Char>, Int> { val map = mutableMapOf<Pair<Int, Int>, Char>() var maxDepth = 0 map.clear() input.forEach { line -> val points = line.split(" -> ").map { point -> val (x, y) = point.split(",").map { it.toInt() } maxDepth = maxDepth.coerceAtLeast(y) Pair(x, y) }.toMutableList() (1 until points.size).forEach { i -> if (points[i].first == points[i - 1].first) { val range = if (points[i].second < points[i - 1].second) (points[i].second..points[i - 1].second) else (points[i].second downTo points[i - 1].second) range.forEach { y -> map[Pair(points[i].first, y)] = '#' } } else { val range = if (points[i].first < points[i - 1].first) (points[i].first..points[i - 1].first) else (points[i].first downTo points[i - 1].first) range.forEach { x -> map[Pair(x, points[i].second)] = '#' } } } } return Pair(map, maxDepth) } fun part1(input: List<String>): Int { val (map, maxDepth) = prepareInput(input) var x = 500 var y = 0 var sandCount = 0 while (y < maxDepth) { if (map[Pair(x, y + 1)] == null) { y++ } else { if (map[Pair(x - 1, y + 1)] == null) { x-- y++ } else if (map[Pair(x + 1, y + 1)] == null) { x++ y++ } else { map[Pair(x, y)] = 'O' sandCount++ x = 500 y = 0 } } } return sandCount } fun part2(input: List<String>): Int { val (map, maxDepth) = prepareInput(input) var x = 500 var y = 0 var sandCount = 0 var rested = false while (!rested) { if (y == maxDepth + 1) { map[Pair(x, y)] = 'O' sandCount++ x = 500 y = 0 } if (map[Pair(x, y + 1)] == null) { y++ } else { if (map[Pair(x - 1, y + 1)] == null) { x-- y++ } else if (map[Pair(x + 1, y + 1)] == null) { x++ y++ } else { map[Pair(x, y)] = 'O' sandCount++ if (x == 500 && y == 0) rested = true x = 500 y = 0 } } } return sandCount } // test if implementation meets criteria from the description, like: val testInput = readInput("Day14_test") check(part1(testInput) == 24) check(part2(testInput) == 93) val input = readInput("Day14") part1(input).println() part2(input).println() }
0
Kotlin
0
0
8924a6d913e2c15876c52acd2e1dc986cd162693
3,136
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/com/colinodell/advent2022/Day16.kt
colinodell
572,710,708
false
{"Kotlin": 105421}
package com.colinodell.advent2022 import kotlin.math.max import kotlin.math.min class Day16(input: List<String>) { private val regex = Regex("Valve (\\w+) has flow rate=(\\d+); tunnels? leads? to valves? (.+)") private val allValves = input.map { regex.find(it)!!.destructured.let { (name, flowRate, tunnels) -> Valve(name, flowRate.toInt(), tunnels.split(", ")) } } // The valves we really want to visit private val goalValves = allValves.filter { it.rate > 0 || it.name == "AA" } // Pre-computed matrix of distances between all valves private val graph = calculateDistanceMatrix(allValves) private fun timeBetween(a: Valve, b: Valve) = graph[allValves.indexOf(a)][allValves.indexOf(b)] fun solvePart1() = solve(30).values.max() fun solvePart2(): Int { // Find the optimal solutions we can do ourselves in 26 minutes val bestPaths = solve(26) val bestFlows = mutableMapOf<Int, Int>().withDefault { 0 } for ((candidate, flow) in bestPaths) { bestFlows[candidate.visited] = max(bestFlows.getValue(candidate.visited), flow) } var highestFlow = 0 // For each possible set of valves we could visit... for (mask in 0 until (1 shl goalValves.size)) { // Invert/flip all bits to find what the elephant should visit val elephantVisited = ((1 shl goalValves.size) - 1) xor mask // What's the best we could do here? highestFlow = max(highestFlow, bestFlows.getValue(elephantVisited)) var weVisited = mask while (weVisited > 0) { highestFlow = max(highestFlow, bestFlows.getValue(elephantVisited) + bestFlows.getValue(weVisited)) weVisited = (weVisited - 1) and mask } } return highestFlow } private data class Path(val goalValveIndex: Int, val visited: Int, val timeRemaining: Int) private data class SearchState(val goalValveIndex: Int, val visited: Int, val timeRemaining: Int, val totalFlow: Int) private fun solve(maxTime: Int): Map<Path, Int> { val queue = ArrayDeque<SearchState>() val bestFlowsByPath = mutableMapOf<Path, Int>().withDefault { -1 } fun enqueue(state: SearchState) { val candidate = Path(state.goalValveIndex, state.visited, state.timeRemaining) if (state.timeRemaining >= 0 && bestFlowsByPath.getValue(candidate) < state.totalFlow) { bestFlowsByPath[candidate] = state.totalFlow queue.add(state) } } enqueue(SearchState(goalValves.indexOfFirst { it.name == "AA" }, 0, maxTime, 0)) while (queue.isNotEmpty()) { val state = queue.removeFirst() // If we haven't visited this valve yet and time remains, maybe we can visit it if ((state.visited and (1 shl state.goalValveIndex) == 0) && state.timeRemaining > 0) { val flowHere = (state.timeRemaining - 1) * goalValves[state.goalValveIndex].rate enqueue(SearchState(state.goalValveIndex, state.visited or (1 shl state.goalValveIndex), state.timeRemaining - 1, state.totalFlow + flowHere)) } for (next in goalValves) { val travelTime = timeBetween(goalValves[state.goalValveIndex], next) if (travelTime <= state.timeRemaining) { enqueue(SearchState(goalValves.indexOf(next), state.visited, state.timeRemaining - travelTime, state.totalFlow)) } } } return bestFlowsByPath } private fun calculateDistanceMatrix(nodes: List<Valve>): Array<Array<Int>> { val maximum = Int.MAX_VALUE / 10 val distances = Array(nodes.size) { Array(nodes.size) { maximum } } // Set the distance from a node to itself to 0 for (i in nodes.indices) { distances[i][i] = 0 } // Set the distance between adjacent nodes to 1 for (i in nodes.indices) { for (adjacent in nodes[i].connectsTo) { val j = nodes.indexOfFirst { it.name == adjacent } distances[i][j] = min(distances[i][j], 1) } } // Run the Floyd–Warshall algorithm for (i in nodes.indices) { for (j in nodes.indices) { for (k in nodes.indices) { distances[j][k] = min(distances[j][k], distances[j][i] + distances[i][k]) } } } return distances } private data class Valve(val name: String, val rate: Int, val connectsTo: List<String>) }
0
Kotlin
0
1
32da24a888ddb8e8da122fa3e3a08fc2d4829180
4,698
advent-2022
MIT License
src/Day03.kt
burtz
573,411,717
false
{"Kotlin": 10999}
fun main() { fun listOfDups(firstComp: List<Char>,secondComp: List<Char>) : List<Char> { var listOfDupes = listOf<Char>() firstComp.forEach { first -> secondComp.forEach { second -> if (first == second) { listOfDupes += first } } } return listOfDupes.distinct() } fun sumList(input: List<Char>) : Int { var sum = 0 input.forEach{ sum += if(it.code > 96) it.code - 96 else it.code - 38 } return sum } fun part1(input: List<String>): Int { var listOfDupes = listOf<Char>() input.forEach{ var len = it.length var bag = it.toList() var firstComp = bag.subList(0,len/2) var secondComp = bag.subList(len/2,len) listOfDupes += listOfDups(firstComp,secondComp) } return sumList(listOfDupes) } fun part2(input: List<String>): Int { var listOfBadges = listOf<Char>() for (i in 0..input.size-3 step 3) { var bag1 = input.get(i).toSet() var bag2 = input.get(i+1).toSet() var bag3 = input.get(i+2).toSet() var matchingBadges = bag1.intersect(bag2.intersect(bag3)) listOfBadges += matchingBadges } return sumList(listOfBadges) } // 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
daac7f91e1069d1490e905ffe7b7f11b5935af06
1,690
adventOfCode2022
Apache License 2.0
src/main/kotlin/days/Day16.kt
jgrgt
575,475,683
false
{"Kotlin": 94368}
package days import itertools.combinations import util.MutableMatrix import util.Point class Day16 : Day(16) { override fun partOne(): Any { // return Game16(inputList).solve() return 0 } override fun partTwo(): Any { return Game16(inputList).solve2() } } class Game16(lines: List<String>) { val valves = lines.map { Day16Valve.from(it) }.associateBy { it.name } fun solve(): Int { // Plan: first figure out the most efficient ways to go from 1 (useful) valve to another. // Then use that to iterate all efficient possibilities and find the best one // First part: pathfinding, depth first, no loops val valvesWithRatesAndStartValve = valves.filter { it.value.flowRate > 0 || it.key == "AA" } val valvesWithRatesAndStartValueNames = valvesWithRatesAndStartValve.keys.toList().sorted() // sorted because easier for me val pathLengths = MutableMatrix.from(valvesWithRatesAndStartValve.size, valvesWithRatesAndStartValve.size) { 0 } // iterate all combinations valvesWithRatesAndStartValueNames.forEachIndexed { indexFrom, valveNameFrom -> valvesWithRatesAndStartValueNames.forEachIndexed { indexTo, valveNameTo -> if (indexFrom < indexTo) { check(valveNameFrom != valveNameTo) val p = Point(indexFrom, indexTo) val current = pathLengths.get(p) check(current == 0) val length = findShortestLength(valveNameFrom, valveNameTo) pathLengths.set(p, length) pathLengths.set(Point(indexTo, indexFrom), length) } } } pathLengths.printSep(", ") // now we have the lengths, let's find the best combination val valveRates = valvesWithRatesAndStartValueNames.map { valves[it]!!.flowRate } // val nonZeroValveNames = valves.filter { it.value.flowRate > 0 } // val valveNameSplits = generateSplits(nonZeroValveNames) val size = valvesWithRatesAndStartValueNames.size val actualValveIndices = (1..size).toList() return (1 until size) .flatMap { actualValveIndices.combinations(it) } .map { myValveIndices -> val elephantValveIndices = actualValveIndices.minus(myValveIndices.toSet()) // hacky way to make sure val myScore = calculateBestScoreRecursive(path = elephantValveIndices + 0, valveRates, pathLengths, timeLeft = 30) val elephantScore = calculateBestScoreRecursive(path = myValveIndices + 0, valveRates, pathLengths, timeLeft = 30) myScore + elephantScore }.min() } // // private fun generateSplits(valves: Map<String, Day16Valve>): List<List<String>> { // val originalSet = valves.keys // return (1 until valves.size).toList().flatMap { // originalSet.combinations(it).toList() // } // } private fun calculateBestScoreRecursive( path: List<Int>, valveRates: List<Int>, pathLengths: MutableMatrix<Int>, timeLeft: Int ): Int { check(path.isNotEmpty()) if (timeLeft <= 0) { return 0 } val currentValve = path.last() val currentValveScore = timeLeft * valveRates[currentValve] val candidates = pathLengths.items.indices.toSet().minus(path.toSet()) return currentValveScore + (candidates.maxOfOrNull { nextValve -> val distance = pathLengths.get(Point(currentValve, nextValve)) val newTimeLeft = timeLeft - distance - 1 // 1 for opening the valve calculateBestScoreRecursive(path + nextValve, valveRates, pathLengths, newTimeLeft) } ?: 0) } private fun findShortestLength( valveNameFrom: String, valveNameTo: String, visited: List<String> = emptyList() ): Int { if (valveNameFrom == valveNameTo) { return 0 } val currentValve = valves[valveNameFrom]!! // below check not needed because of first check above here val nextValveNames = currentValve.next if (nextValveNames.contains(valveNameTo)) { return 1 } // recursion... return (nextValveNames .filter { !visited.contains(it) } .minOfOrNull { findShortestLength(it, valveNameTo, visited + valveNameFrom) } ?: 10000 ) + 1 } fun solve2(): Int { // Plan: first figure out the most efficient ways to go from 1 (useful) valve to another. // Then use that to iterate all efficient possibilities and find the best one // First part: pathfinding, depth first, no loops val valvesWithRatesAndStartValve = valves.filter { it.value.flowRate > 0 || it.key == "AA" } val valvesWithRatesAndStartValueNames = valvesWithRatesAndStartValve.keys.toList().sorted() // sorted because easier for me val pathLengths = MutableMatrix.from(valvesWithRatesAndStartValve.size, valvesWithRatesAndStartValve.size) { 0 } // iterate all combinations valvesWithRatesAndStartValueNames.forEachIndexed { indexFrom, valveNameFrom -> valvesWithRatesAndStartValueNames.forEachIndexed { indexTo, valveNameTo -> if (indexFrom < indexTo) { check(valveNameFrom != valveNameTo) val p = Point(indexFrom, indexTo) val current = pathLengths.get(p) check(current == 0) val length = findShortestLength(valveNameFrom, valveNameTo) pathLengths.set(p, length) pathLengths.set(Point(indexTo, indexFrom), length) } } } pathLengths.printSep(", ") // now we have the lengths, let's find the best combination val valveRates = valvesWithRatesAndStartValueNames.map { valves[it]!!.flowRate } // val nonZeroValveNames = valves.filter { it.value.flowRate > 0 } // val valveNameSplits = generateSplits(nonZeroValveNames) val size = valvesWithRatesAndStartValueNames.size val actualValveIndices = (1 until size).toList() val m = (1 until size) .flatMap { actualValveIndices.combinations(it) } // println((valvesWithRatesAndStartValueNames.mapIndexed { i, name -> "$i: $name" }).joinToString(", ")) // val m = listOf(listOf(1, 2, 6)) .map { myValveIndices -> val elephantValveIndices = actualValveIndices.minus(myValveIndices.toSet()) // hacky way to make sure val myScore = calculateBestScoreRecursive(path = elephantValveIndices + 0, valveRates, pathLengths, timeLeft = 26) val elephantScore = calculateBestScoreRecursive(path = myValveIndices + 0, valveRates, pathLengths, timeLeft = 26) (myScore + elephantScore) to myValveIndices }.maxBy { it.first } println("Score ${m.first}: ${m.second.map { valvesWithRatesAndStartValueNames[it] }}") return m.first } } data class Day16Valve(val name: String, val flowRate: Int, val next: List<String>) { companion object { fun from(line: String): Day16Valve { val parts = line.trim().split(" ", limit = 10) val name = parts[1] val rate = parts[4].trim(';').split("=")[1].toInt() val nextStrings = parts[9].split(", ") return Day16Valve(name, rate, nextStrings) } } }
0
Kotlin
0
0
5174262b5a9fc0ee4c1da9f8fca6fb86860188f4
7,738
aoc2022
Creative Commons Zero v1.0 Universal
kotlin/src/x2023/Day02.kt
freeformz
573,924,591
false
{"Kotlin": 43093, "Go": 7781}
package x2023 data class Dice(var color: String, var count: Int) fun List<Dice>.possible(set: List<Dice>): Boolean { return set.all { die -> this.any { d -> d.color == die.color && d.count >= die.count } } } open class Day02AExample { open val inputLines: List<String> = read2023Input("day02a-example") open val expected = 8 open val allDice = listOf(Dice("red", 12), Dice("green", 13), Dice("blue", 14)) open var answer: Int = 0 fun run() { answer = inputLines.sumOf { line -> val p1 = line.split(":") // game number vs input val game = p1.first().split(" ").last().toInt() // game number when (val possible = p1.last().split(";").map { set -> // split into sets of dice set.trim().split(",").map { die -> // split into individual dice and map to Dice class val p2 = die.trim().split(" ") Dice(p2.last(), p2.first().toInt()) } }.map { it -> allDice.possible(it) }.all { it }) { // determine if possible true -> game false -> 0 } } } fun check() { println(this.javaClass.name) println("answer: $answer") println("expected: $expected") assert(answer == expected) println() } } class Day02A : Day02AExample() { override val inputLines: List<String> = read2023Input("day02a") override val expected = 1734 } fun List<Dice>.minimumRequired(set: List<Dice>): List<Dice> { return this.map { die -> val other = set.singleOrNull { d -> d.color == die.color } when (other) { null -> die else -> { listOf(die, other).maxBy(Dice::count) } } } } open class Day02BExample { open val inputLines: List<String> = read2023Input("day02b-example") open val expected = 2286 open var answer: Int = 0 fun run() { answer = inputLines.fold(0) { acc, line -> val p1 = line.split(":") // game number vs input val game = p1.first().split(" ").last().toInt() // game number val p = p1.last().split(";").map { set -> // split into sets of dice set.trim().split(",").map { die -> // split into individual dice and map to Dice class val p2 = die.trim().split(" ") Dice(p2.last(), p2.first().toInt()) } }.fold(listOf(Dice("red", 0), Dice("green", 0), Dice("blue", 0))) { g, set -> g.minimumRequired(set) }.fold(1) { mul, die -> mul * die.count } acc + p } } fun check() { println(this.javaClass.name) println("answer: $answer") println("expected: $expected") assert(answer == expected) println() } } class Day02B : Day02BExample() { override val inputLines: List<String> = read2023Input("day02b") override val expected = 70387 } fun main() { Day02AExample().also { it.run() it.check() } Day02A().also { it.run() it.check() } Day02BExample().also { it.run() it.check() } Day02B().also { it.run() it.check() } }
0
Kotlin
0
0
5110fe86387d9323eeb40abd6798ae98e65ab240
3,347
adventOfCode
Apache License 2.0
src/main/kotlin/de/niemeyer/aoc2022/Day18.kt
stefanniemeyer
572,897,543
false
{"Kotlin": 175820, "Shell": 133}
/** * Advent of Code 2022, Day 18: Boiling Boulders * Problem Description: https://adventofcode.com/2022/day/18 */ package de.niemeyer.aoc2022 import de.niemeyer.aoc.points.Point3D import de.niemeyer.aoc.utils.Resources.resourceAsList import de.niemeyer.aoc.utils.getClassName fun main() { val name = getClassName() val testInput = resourceAsList(fileName = "${name}_test.txt").map { Point3D.of(it) }.toSet() val puzzleInput = resourceAsList(fileName = "${name}.txt").map { Point3D.of(it) }.toSet() check(Pond(testInput).solvePart1() == 64) val puzzleResultPart1 = Pond(puzzleInput).solvePart1() println(puzzleResultPart1) check(puzzleResultPart1 == 3_498) check(Pond(testInput).solvePart2() == 58) val puzzleResultPart2 = Pond(puzzleInput).solvePart2() println(puzzleResultPart2) check(puzzleResultPart2 == 2_008) } class Pond(private val lava: Set<Point3D>) { private val cache = mutableMapOf<Point3D, Boolean>() private val maxPoint = Point3D(lava.maxOf { it.x }, lava.maxOf { it.y }, lava.maxOf { it.z }) private val minPoint = Point3D(lava.minOf { it.x }, lava.minOf { it.y }, lava.minOf { it.z }) fun solvePart1(): Int = lava.sumOf { validNeighbors(it).count() } fun solvePart2(): Int = lava.sumOf { validNeighbors(it).count { cand -> !cand.isAir() } } private fun Point3D.isAir(): Boolean { cache[this]?.let { return it } val outside = ArrayDeque(listOf(this)) val visited = mutableSetOf<Point3D>() while (!outside.isEmpty()) { val p = outside.removeFirst() if (p in visited) { continue } visited.add(p) if (p in cache) { return addToCache(visited, cache.getValue(p)) // Point is in cache } else if (p.isOutsidePod()) { return addToCache(visited, isAir = false) // Point is outside pond and cannot be air though } else { outside.addAll(validNeighbors(p)) // check valid neighbors } } return addToCache(visited, isAir = true) } private fun addToCache(points: Iterable<Point3D>, isAir: Boolean): Boolean { points.forEach { cache[it] = isAir } return isAir } private fun Point3D.isOutsidePod(): Boolean = x < minPoint.x || y < minPoint.y || z < minPoint.z || x > maxPoint.x || y > maxPoint.y || z > maxPoint.z private fun validNeighbors(p: Point3D): List<Point3D> = listOf( Point3D(p.x - 1, p.y, p.z), Point3D(p.x + 1, p.y, p.z), Point3D(p.x, p.y - 1, p.z), Point3D(p.x, p.y + 1, p.z), Point3D(p.x, p.y, p.z - 1), Point3D(p.x, p.y, p.z + 1), ).filter { it !in lava } }
0
Kotlin
0
0
ed762a391d63d345df5d142aa623bff34b794511
2,855
AoC-2022
Apache License 2.0
src/poyea/aoc/mmxxii/day17/Day17.kt
poyea
572,895,010
false
{"Kotlin": 68491}
package poyea.aoc.mmxxii.day17 import poyea.aoc.utils.readInput data class Point(val x: Int, val y: Int) { operator fun plus(other: Point) = Point(x + other.x, y + other.y) } data class Shape(val points: List<Point>) { fun push(jet: Char) = when (jet) { '>' -> copy(points = points.map { it.copy(x = it.x + 1) }) '<' -> copy(points = points.map { it.copy(x = it.x - 1) }) else -> copy(points) } fun fall() = copy(points = points.map { it.copy(y = it.y - 1) }) companion object { fun generate(order: Long): Shape = Shape( when (order) { 0L -> listOf(Point(2, 0), Point(3, 0), Point(4, 0), Point(5, 0)) 1L -> listOf(Point(3, 0), Point(2, 1), Point(3, 1), Point(4, 1), Point(3, 2)) 2L -> listOf(Point(2, 0), Point(3, 0), Point(4, 0), Point(4, 1), Point(4, 2)) 3L -> listOf(Point(2, 0), Point(2, 1), Point(2, 2), Point(2, 3)) 4L -> listOf(Point(2, 0), Point(2, 1), Point(3, 0), Point(3, 1)) else -> listOf() } ) } } data class State(val top: List<Int>, val jetIndex: Int, val shapeIndex: Long) class Cave(private val jets: String) { private val points = (0..6).map { Point(it, -1) }.toMutableSet() private var currentJet = 0 set(value) { field = value % jets.length } private var currentShape = 0L set(value) { field = value % 5 } fun height() = points.maxOf { it.y + 1 } fun addOne() { var shape = nextShape() while (true) { val pushed = shape.push(jets[currentJet++]) if (!pushed.hit()) shape = pushed val fallen = shape.fall() if (fallen.hit()) break else shape = fallen } points += shape.points } fun currentState() = State( top = points .groupBy { it.x } .entries .sortedBy { it.key } .map { it.value.maxBy { point -> point.y } } .let { points -> points.map { point -> point.y - height() } }, jetIndex = currentJet, shapeIndex = currentShape ) private fun nextShape(): Shape { val shape = Shape.generate(currentShape++) val bottom = (points.maxOfOrNull { p -> p.y } ?: -1) + 4 return shape.copy(points = shape.points.map { it + Point(0, bottom) }) } private fun Shape.hit() = points.intersect(this@Cave.points).isNotEmpty() || points.any { it.x !in (0..6) } } fun simulate(jets: String, numberOfRocks: Long): Long { val cave = Cave(jets) val cache = mutableMapOf<State, Pair<Long, Int>>() for (r in 0..numberOfRocks) { cave.addOne() val state = cave.currentState() if (state in cache) { val (prevRocks, prevHeight) = cache.getValue(state) val diffRocks = numberOfRocks - r val totalRocks = r - prevRocks val loopsRemaining = diffRocks / totalRocks val rocksRemaining = diffRocks % totalRocks val heightRemaining = cache.values.first { (r, _) -> r == prevRocks + (rocksRemaining - 1) }.second - prevHeight val height = (cave.height() - prevHeight) return cave.height() + loopsRemaining * height + heightRemaining } cache[state] = Pair(r, cave.height()) } return -1 } fun part1(input: String): Long { return simulate(input, 2022) } fun part2(input: String): Long { return simulate(input, 1_000_000_000_000) } fun main() { println(part1(readInput("Day17"))) println(part2(readInput("Day17"))) }
0
Kotlin
0
1
fd3c96e99e3e786d358d807368c2a4a6085edb2e
3,709
aoc-mmxxii
MIT License
src/main/kotlin/dev/bogwalk/batch0/Problem4.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch0 import dev.bogwalk.util.maths.primeFactors import dev.bogwalk.util.strings.isPalindrome import kotlin.math.sqrt /** * Problem 4: Largest Palindrome Product * * https://projecteuler.net/problem=4 * * Goal: Find the largest palindrome less than N that is made from the product of two 3-digit * numbers. * * Constraints: 101_101 < N < 1e6 * * e.g.: N = 800_000 * 869 * 913 = 793_397 */ class LargestPalindromeProduct { /** * Brute iteration through all products of 3-digit numbers while storing the largest * confirmed palindrome product so far. * * SPEED (WORST) 2.20ms for N = 999_999 * */ fun largestPalindromeProductBrute(n: Int): Int { var largest = 0 for (x in 101..999) { inner@for (y in x..999) { val product = x * y if (product >= n) break@inner if (product > largest && product.toString().isPalindrome()) { largest = product } } } return largest } /** * Brute iteration through all products of 3-digit numbers starting with the largest numbers * and terminating the inner loop early if product starts to get too small. * * SPEED (BETTER) 1.8e+05ns for N = 999_999 */ fun largestPalindromeProductBruteBackwards(n: Int): Int { var largest = 0 outer@for (x in 999 downTo 101) { inner@for (y in 999 downTo x) { val product = x * y // combo will be too small to pursue further if (product <= largest) continue@outer if (product < n && product.toString().isPalindrome()) { largest = product break@inner } } } return largest } /** * A palindrome of the product of two 3-digit integers can be at most 6-digits long & one of the * integers must have a factor of 11, based on the following algebra: * * P = 100_000x + 10_000y + 1000z + 100z + 10y + x * * P = 100_001x + 10_010y + 1100z * * P = 11*(9091x + 910y + 100z) * * Rather than stepping down to each palindrome & searching for a valid product, this * solution tries all product combos that involve one of the integers being a multiple of 11. * * SPEED (BETTER) 1.3e+05ns for N = 999_999 */ fun largestPalindromeProduct(n: Int): Int { var largest = 0 for (x in 990 downTo 110 step 11) { for (y in 999 downTo 101) { val product = x * y // combo will be too small to pursue further if (product <= largest) break if (product < n && product.toString().isPalindrome()) { largest = product break } } } return largest } /** * Brute iteration through all palindromes less than [n] checks if each palindrome could * be a valid product of two 3-digit numbers. * * SPEED (BEST) 1.9e+04ns for N = 999_999 [using fast helper function] */ fun largestPalindromeProductAlt(n: Int): Int { var num = if ((n / 1000).toPalindrome() > n) n / 1000 - 1 else n / 1000 while (num > 101) { val palindrome = num.toPalindrome() if (palindrome.is3DigProductFast()) { return palindrome } num-- } return 101_101 } /** * Converts a 3-digit integer to a 6-digit palindrome. */ private fun Int.toPalindrome(): Int { return this * 1000 + this % 10 * 100 + this / 10 % 10 * 10 + this / 100 } private fun Int.is3DigProductFast(): Boolean { for (factor1 in 999 downTo sqrt(1.0 * this).toInt()) { if (this % factor1 == 0 && this / factor1 in 101..999) return true } return false } /** * Determines if [this], an Int palindrome, can be a product of two 3-digit numbers by finding * all 3-digit multiples of [this]'s prime factors. */ private fun Int.is3DigProductSlow(): Boolean { val range = 101..999 val distinctPrimes: Set<Long> val primeFactors: List<Long> = primeFactors(this.toLong()).also { distinctPrimes = it.keys }.flatMap { (k, v) -> List(v) { k } } val validFactors = distinctPrimes.filter { it in range } for (p1 in distinctPrimes) { inner@for (p2 in primeFactors) { if (p2 <= p1) continue@inner val multiple = p1 * p2 if (multiple in range) { if (this / multiple in range) { return true } } } } return validFactors.any { this / it in range } } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
4,996
project-euler-kotlin
MIT License
solutions/src/NetworkDelayTime.kt
JustAnotherSoftwareDeveloper
139,743,481
false
{"Kotlin": 305071, "Java": 14982}
import java.util.* import kotlin.collections.HashSet //https://leetcode.com/problems/network-delay-time/ class NetworkDelayTime { fun networkDelayTime(times: Array<IntArray>, N: Int, K: Int): Int { val graph = createGraph(times) val distances : MutableMap<Int,Node> = mutableMapOf() val explored: MutableSet<Int> = HashSet() for (i in 1..N) { val node = if (i == K) { Node(i, 0) } else { Node(i) } distances[i] = node } val unexplored = distances.values.sortedBy { it.distance }.toMutableList() while (unexplored.isNotEmpty()) { val current = unexplored.removeAt(0) graph.getOrDefault(current.id, listOf()) .filter { !explored.contains(it.to) } .forEach { var node = distances[it.to]!! var tmpDistance = current.distance + it.cost if (tmpDistance < node.distance) { node.distance = tmpDistance unexplored.sortBy { node -> node.distance } } } explored.add(current.id) } return if (distances.values.any { it.distance == Int.MAX_VALUE }) { -1 } else { return distances.values.map { it.distance }.max()!! } } fun createGraph(times: Array<IntArray>): Map<Int, List<Edge>> { return times.map { Edge(it[0], it[1], it[2]) }.groupBy { it.from } } data class Edge(val from: Int, val to: Int, val cost: Int) data class Node(val id: Int, var distance: Int = Int.MAX_VALUE) }
0
Kotlin
0
0
fa4a9089be4af420a4ad51938a276657b2e4301f
1,819
leetcode-solutions
MIT License
src/main/kotlin/bk70/Problem3.kt
yvelianyk
405,919,452
false
{"Kotlin": 147854, "Java": 610}
package bk70 import java.util.* // [[0,2,0]] // [2,2] // [0,1] // 1 fun main() { val res = Problem3().highestRankedKItems( arrayOf( intArrayOf(0, 2, 0), ), intArrayOf(2, 2), intArrayOf(0, 1), 1 ) println(res) } class Problem3 { private lateinit var grid: Array<IntArray> private lateinit var pricing: IntArray private var visitedPoints = mutableListOf<Point>() fun highestRankedKItems(grid: Array<IntArray>, pricing: IntArray, start: IntArray, k: Int): List<List<Int>> { this.grid = grid this.pricing = pricing bfs(start[0], start[1]) return visitedPoints .filter { it.`val` != 1 && it.`val` >= pricing[0] && it.`val` <= pricing[1] } .sortedWith( compareBy<Point> { it.dist } .thenBy { it.`val` } .thenBy { it.x } .thenBy { it.y } ) .map { listOf(it.x, it.y) } .take(k) } private fun bfs(i: Int, j: Int) { val queue: Queue<Point> = LinkedList<Point>() val visited = Array(grid.size) { BooleanArray( grid[0].size ) } val directions = arrayOf(intArrayOf(1, 0), intArrayOf(0, 1), intArrayOf(-1, 0), intArrayOf(0, -1)) val first = Point(i, j, 0, grid[i][j]) queue.add(first) visitedPoints.add(first) visited[first.x][first.y] = true var distance = 0 while (!queue.isEmpty()) { distance++ val size = queue.size for (i in 0 until size) { val curr: Point = queue.poll() for (direction in directions) { val newPoint = Point( curr.x + direction[0], curr.y + direction[1], distance, 0 ) if (newPoint.x >= 0 && newPoint.x < grid.size && newPoint.y >= 0 && newPoint.y < grid[0].size && !visited[newPoint.x][newPoint.y] && grid[newPoint.x][newPoint.y] != 0 ) { newPoint.`val` = grid[newPoint.x][newPoint.y] visited[newPoint.x][newPoint.y] = true queue.add(newPoint) visitedPoints.add(newPoint) } } } } } internal class Point(var x: Int, var y: Int, var dist: Int, var `val`: Int) }
0
Kotlin
0
0
780d6597d0f29154b3c2fb7850a8b1b8c7ee4bcd
2,738
leetcode-kotlin
MIT License
src/main/kotlin/aoc2018/ModeMaze.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2018 import komu.adventofcode.utils.Point import utils.shortestPathWithCost import java.util.* fun modeMaze1(depth: Int, target: Point) = CaveSystem(depth, target).riskLevel() fun modeMaze2(depth: Int, target: Point) = CaveSystem(depth, target).fastestRoute() private class CaveSystem(private val depth: Int, private val target: Point) { private val geologicIndexCache = mutableMapOf<Point, Int>() private fun geologicIndex(p: Point): Int = geologicIndexCache.getOrPut(p) { when { p == Point.ORIGIN -> 0 p == target -> 0 p.y == 0 -> p.x * 16807 p.x == 0 -> p.y * 48271 else -> erosionLevel(Point(p.x - 1, p.y)) * erosionLevel(Point(p.x, p.y - 1)) } } private fun erosionLevel(p: Point): Int = (geologicIndex(p) + depth) % 20183 private fun regionType(p: Point) = RegionType.forErosionLevel(erosionLevel(p)) fun riskLevel(): Int { var level = 0 for (y in 0..target.y) for (x in 0..target.x) level += regionType(Point(x, y)).riskLevel return level } fun fastestRoute(): Int { val initial = MazeState(Point.ORIGIN, Tool.TORCH) val goal = MazeState(target, Tool.TORCH) return shortestPathWithCost(initial, { it == goal }, this::transitions)!!.second } private fun isCandidate(p: Point) = p.x in 0..target.x + 40 && p.y in 0..target.y + 40 private fun transitions(state: MazeState): List<Pair<MazeState, Int>> { val result = mutableListOf<Pair<MazeState, Int>>() for (n in state.position.neighbors) if (isCandidate(n) && state.tool in regionType(n).allowedTools) result += Pair(MazeState(n, state.tool), 1) for (tool in regionType(state.position).allowedTools) if (tool != state.tool) result += Pair(MazeState(state.position, tool), 7) return result } } private data class MazeState(val position: Point, val tool: Tool) private enum class Tool { TORCH, CLIMBING_GEAR, NEITHER } private enum class RegionType(val riskLevel: Int, val allowedTools: EnumSet<Tool>) { ROCKY(riskLevel = 0, EnumSet.of(Tool.TORCH, Tool.CLIMBING_GEAR)), WET(riskLevel = 1, EnumSet.of(Tool.CLIMBING_GEAR, Tool.NEITHER)), NARROW(riskLevel = 2, EnumSet.of(Tool.TORCH, Tool.NEITHER)); companion object { fun forErosionLevel(level: Int) = when (level % 3) { 0 -> ROCKY 1 -> WET 2 -> NARROW else -> error("invalid level: $level") } } }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
2,659
advent-of-code
MIT License
year2023/src/main/kotlin/net/olegg/aoc/year2023/day13/Day13.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2023.day13 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.year2023.DayOf2023 /** * See [Year 2023, Day 13](https://adventofcode.com/2023/day/13) */ object Day13 : DayOf2023(13) { override fun first(): Any? { val patterns = data.split("\n\n").map { pattern -> pattern.lines().map { it.toList() } } val transposed = patterns.map { it.transpose() } return transposed.sumOf { it.rowsBeforeReflection() } + 100 * patterns.sumOf { it.rowsBeforeReflection() } } override fun second(): Any? { val patterns = data.split("\n\n").map { pattern -> pattern.lines().map { it.toList() } } val transposed = patterns.map { it.transpose() } return transposed.sumOf { it.rowsBeforeSmudge() } + 100 * patterns.sumOf { it.rowsBeforeSmudge() } } private fun List<List<Char>>.transpose(): List<List<Char>> { return List(first().size) { row -> List(size) { column -> this[column][row] } } } private fun List<List<Char>>.rowsBeforeReflection(): Int { val rev = asReversed() for (i in 1..<size) { val below = drop(i) val above = rev.takeLast(i) if (above.zip(below).all { (a, b) -> a == b }) { return i } } return 0 } private fun List<List<Char>>.rowsBeforeSmudge(): Int { val rev = asReversed() for (i in 1..<size) { val below = drop(i) val above = rev.takeLast(i) if (above.zip(below).sumOf { (a, b) -> a.zip(b).count { (ca, cb) -> ca != cb } } == 1) { return i } } return 0 } } fun main() = SomeDay.mainify(Day13)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,595
adventofcode
MIT License
src/Day13.kt
Flame239
570,094,570
false
{"Kotlin": 60685}
private fun packets(): List<Packet> { return readInput("Day13").filter { it.isNotBlank() }.map { parsePacket(it) } } private fun parsePacket(s: String): Packet = ListData().also { parseListData(it, s, 0) } private fun parseListData(curList: ListData, s: String, start: Int): Int { var cur = start + 1 while (s[cur] != ']') { if (s[cur].isDigit()) { var curInt = s[cur].digitToInt() cur++ if (s[cur].isDigit()) { curInt = curInt * 10 + s[cur].digitToInt() cur++ } curList.add(IntData(curInt)) } if (s[cur] == '[') { val newList = ListData() curList.add(newList) cur = parseListData(newList, s, cur) + 1 } if (s[cur] == ',') cur++ } return cur } private fun part1(packets: List<Packet>): Int { return packets.chunked(2).withIndex().sumOf { (index, pair) -> if (pair[0] < pair[1]) index + 1 else 0 } } private fun part2(packets: List<Packet>): Int { val div1 = ListData(ListData(IntData(2))) val div2 = ListData(ListData(IntData(6))) val allPacketsSorted = (packets + div1 + div2).sorted() return (allPacketsSorted.indexOf(div1) + 1) * (allPacketsSorted.indexOf(div2) + 1) } fun main() { println(part1(packets())) println(part2(packets())) } typealias Packet = ListData sealed interface PacketData : Comparable<PacketData> { override operator fun compareTo(other: PacketData): Int } data class IntData(val value: Int) : PacketData { override operator fun compareTo(other: PacketData): Int { return when (other) { is IntData -> value.compareTo(other.value) is ListData -> ListData(this).compareTo(other) } } } data class ListData(val list: MutableList<PacketData>) : PacketData { constructor() : this(mutableListOf()) constructor(data: PacketData) : this(mutableListOf(data)) fun add(data: PacketData) { list.add(data) } private fun compareToList(right: ListData): Int { var i = 0 while (i < list.size && i < right.list.size) { val comp = list[i].compareTo(right.list[i]) if (comp != 0) return comp i++ } if (i == list.size && i < right.list.size) return -1 if (i == right.list.size && i < list.size) return 1 return 0 } override operator fun compareTo(other: PacketData): Int { return when (other) { is IntData -> compareToList(ListData(other)) is ListData -> compareToList(other) } } }
0
Kotlin
0
0
27f3133e4cd24b33767e18777187f09e1ed3c214
2,631
advent-of-code-2022
Apache License 2.0
src/Day14.kt
Fedannie
572,872,414
false
{"Kotlin": 64631}
import java.lang.StringBuilder enum class State { FINISHED, ADDED, BLOCKED; fun completed(): Boolean { return this != BLOCKED } } class Field() { private var snowCoordinate: Coordinate = Coordinate(500, 0) private var left: Int = 1000000 private var right: Int = 0 private var floor: Int = 0 private val fieldMap = HashSet<Coordinate>() fun addStone(point: Coordinate): Boolean { fieldMap.add(point) left = left.coerceAtMost(point.x) right = right.coerceAtLeast(point.x) floor = floor.coerceAtLeast(point.y) return false } fun Coordinate.next() = listOf(Coordinate(this.x, this.y + 1), Coordinate(x - 1, y + 1), Coordinate(x + 1, y + 1)) fun addSnow(coordinate: Coordinate = snowCoordinate, withFloor: Boolean = false): State { if (fieldMap.contains(coordinate)) return State.BLOCKED if (!withFloor && (coordinate.y > floor || coordinate.x !in left .. right)) return State.FINISHED if (withFloor && coordinate.y == floor + 2) return State.BLOCKED for (next in coordinate.next()) { val res = addSnow(next, withFloor) if (res.completed()) return res } fieldMap.add(coordinate) return State.ADDED } override fun toString(): String { val result = StringBuilder() for (y in 0 .. floor + 3) { for (x in fieldMap.toList().minOf { it.x } - 3 .. fieldMap.toList().maxOf { it.x } + 3) { result.append(if (fieldMap.contains(Coordinate(x, y))) "o" else ".") } result.append("\n") } return result.toString() } } fun main() { fun parseInput(input: List<String>): Field { val field = Field() input.forEach { line -> line .split(" -> ") .map { pair -> val intPair = pair.split(",").map { it.toInt() } Coordinate(intPair[0], intPair[1]) } .windowed(2) .forEach { pair -> for (x in pair[0].x.coerceAtMost(pair[1].x)..pair[0].x.coerceAtLeast(pair[1].x)) { for (y in pair[0].y.coerceAtMost(pair[1].y)..pair[0].y.coerceAtLeast(pair[1].y)) { field.addStone(Coordinate(x, y)) } } } } return field } fun process(input: List<String>, withFloor: Boolean): Int { val field = parseInput(input) var counter = 0 while (field.addSnow(withFloor = withFloor) == State.ADDED) counter++ return counter } fun part1(input: List<String>): Int = process(input, false) fun part2(input: List<String>): Int = process(input, true) val testInput = readInputLines("Day14_test") check(part1(testInput) == 24) check(part2(testInput) == 93) val input = readInputLines(14) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1d5ac01d3d2f4be58c3d199bf15b1637fd6bcd6f
3,045
Advent-of-Code-2022-in-Kotlin
Apache License 2.0
src/main/kotlin/twentytwentytwo/Day22.kt
JanGroot
317,476,637
false
{"Kotlin": 80906}
package twentytwentytwo import kotlin.math.sqrt fun main() { val input = {}.javaClass.getResource("input-22.txt")!!.readText().split("\n\n"); val tinput = {}.javaClass.getResource("input-22-1.txt")!!.readText().split("\n\n"); val test = Day22(tinput) val day = Day22(input) //val testResult1 = test.part1() //println((testResult1.first.first * 4) + (testResult1.first.second * 1000) + Day22.directions.indexOf(testResult1.second)) //val result1 = day.part1() //println((result1.first.first * 4) + (result1.first.second * 1000) + Day22.directions.indexOf(result1.second)) var result2 = day.part2() println(result2) println((result2.first.first * 4) + (result2.first.second * 1000) + Day22.directions.indexOf(result2.second)) } class Day22(val input: List<String>) { val land: List<Pair<Pair<Int, Int>, Char>> = input[0].lines().mapIndexed { y, row -> row.mapIndexed { x, s -> x + 1 to y + 1 to s } }.flatten().filter { p -> p.second != ' ' } val path = "([R|L])|(\\d+)".toRegex().findAll(input[1]).map { it.value }.toList() var direction = "R" val edges: List<Pair<Int, Pair<IntRange, IntRange>>> lateinit var position: Pair<Int, Int> init { val size = (land.size / 6).toDouble() val sides = (sqrt(size)).toInt() /*input[0].lines().windowed(1, sides, true).flatten().mapIndexed { indexY, s -> s.windowed(sides, sides).mapIndexed { index, s -> indexY to index + 1 to s }.filter { it.second.none { it == ' ' } }.also { println(it) } }.flatten().mapIndexed { index, pair -> val yfact = pair.first.second val xfact = pair.first.first index to ((1 + (xfact * sides))..((xfact + 1) * sides) to (1 + (yfact * sides))..((yfact + 1) * sides)) }.also { println(it) } (1..size.toInt()).map { x -> val points = land.filter { it.first.first == x } points.map { it to points.size / sides + (x - 1 / sides) // let's try to slice it in a cube } }.flatten()*/ val side1 = 1 to (51..100 to 1..50) val side2 = 2 to (101..150 to 1..50) val side3 = 3 to (51..100 to 51..100) val side4 = 4 to (1..50 to 101..150) val side5 = 5 to (51..100 to 101..150) val side6 = 6 to (1..50 to 151..200) edges = listOf(side6, side1, side2, side3, side4, side5) } fun part1(): Pair<Pair<Int, Int>, String> { position = land.first().first path.forEach { step -> print("${position} next ${step}") when (step) { "R" -> direction = rotate("R") "L" -> direction = rotate("L") else -> { position = move(position, step.toInt()) } } //println(currentDirection) } return position to direction } fun part2(): Pair<Pair<Int, Int>, String> { position = 51 to 1 direction = "R" path.forEach { step -> print("${position} next ${step}") when (step) { "R" -> direction = rotate("R") "L" -> direction = rotate("L") else -> { position = move2(position, step.toInt()) } } //println(currentDirection) } return position to direction } fun move(position: Pair<Int, Int>, steps: Int): Pair<Int, Int> { if (steps == 0) return position var next = move(position) var found = land.firstOrNull { p -> p.first == next } ?: when (direction) { "D" -> land.first { p -> p.first.first == next.first } "U" -> land.last { p -> p.first.first == next.first } "L" -> land.last { p -> p.first.second == next.second } "R" -> land.first { p -> p.first.second == next.second } else -> { error("noooo!") } } //println(found) if (found.second == '#') return position return move(found.first, steps - 1) } fun move(position: Pair<Int, Int>): Pair<Int, Int> { return when (direction) { "U" -> position.first to position.second - 1 "D" -> position.first to position.second + 1 "L" -> position.first - 1 to position.second "R" -> position.first + 1 to position.second else -> { position } } } fun move2(position: Pair<Int, Int>, steps: Int): Pair<Int, Int> { if (steps == 0) return position println("$position + $direction") var next = move2(position) val side = position.getSide() var found = land.firstOrNull { p -> p.first == next } ?: when (direction) { "D" -> land.first { p -> p.first.first == next.first } "U" -> land.last { p -> p.first.first == next.first } "L" -> land.last { p -> p.first.second == next.second } "R" -> land.first { p -> p.first.second == next.second } else -> { error("noooo!") } } val nextSide = next.getSide() if (side != nextSide) { /* val side1 = 1 to (51..100 to 1..50) val side2 = 2 to (101..150 to 1..50) val side3 = 3 to (51..100 to 51..100) val side4 = 4 to (1..50 to 101..150) val side5 = 5 to (51..100 to 101..150) val side6 = 6 to (1..50 to 151..200)*/ var nextSet: Pair<String, Pair<Int, Int>> = when (side to direction) { 1 to "U" -> { // to 6 "R" to (1 to position.first + 100) //ok } 1 to "L" -> { //to 4 "R" to (1 to 151 - position.second) //ok } 2 to "U" -> { // to 6 "U" to (position.first - 100 to 200) //ok } 2 to "R" -> {// to 5 "L" to (100 to 151 - position.second) } 2 to "D" -> { // to 3 "L" to (100 to position.first - 50) } 3 to "R" -> { "U" to (position.second + 50 to 50) } 3 to "L" -> { "D" to (position.second - 50 to 101)//ok } 4 to "L" -> { "R" to (51 to 151 - position.second) } 4 to "U" -> { "R" to (51 to position.first + 50) } 5 to "R" -> { "L" to (150 to 151 - position.second) } 5 to "D" -> { "L" to (50 to position.first + 100) } 6 to "D" -> { "D" to (position.first + 100 to 1) } 6 to "R" -> { "U" to (position.second - 100 to 150) } 6 to "L" -> { "D" to (position.second - 100 to 1) } else -> { direction to next } } found = land.firstOrNull { p -> p.first == nextSet.second }!! if (found.second == '#') { return position } direction = nextSet.first } //println(found) if (found.second == '#') return position return move2(found.first, steps - 1) } fun move2(position: Pair<Int, Int>): Pair<Int, Int> { return when (direction) { "U" -> position.first to position.second - 1 "D" -> position.first to position.second + 1 "L" -> position.first - 1 to position.second "R" -> position.first + 1 to position.second else -> { position } } } fun rotate(newDirection: String): String { return when (newDirection) { "R" -> directions[(directions.indexOf(direction) + 1).mod(4)] "L" -> directions[(directions.indexOf(direction) - 1).mod(4)] else -> { error("Cant move there") } } } companion object { val directions = arrayOf("R", "D", "L", "U") } fun Pair<Int, Int>.getSide(): Int { return edges.find { val (xr, yr) = it.second (this.first in xr && this.second in yr) }?.first ?: -1 } }
0
Kotlin
0
0
04a9531285e22cc81e6478dc89708bcf6407910b
8,703
aoc202xkotlin
The Unlicense
src/Day12.kt
Fedannie
572,872,414
false
{"Kotlin": 64631}
fun main() { class Field { val field = MutableList(0) { List(0) { 0 } } var start = Coordinate(0, 0) var end = Coordinate(0, 0) var canStep: (Coordinate, Coordinate) -> Boolean = { from, to -> field.at(from) + 1 >= field.at(to) } fun neighbours(current: Coordinate): List<Coordinate> { val result = MutableList(0) { Coordinate(0, 0) } for (dx in -1 .. 1) { for (dy in -1 .. 1) { if (dx == 0 && dy == 0) continue if (dx != 0 && dy != 0) continue val next = Coordinate(current.x + dx, current.y + dy) if (next.x in 0 until field.size && next.y in 0 until field[0].size && canStep(current, next)) result.add(next) } } return result } fun bfs( start: Coordinate = this.start, isFinal: (Coordinate) -> Boolean = { x -> x == end } ): Int { val visited = List(field.size) { MutableList(field[0].size) { false } } visited.set(start, true) val queue = MutableList(1) { start to 0 } while (queue.isNotEmpty()) { val (current, dist) = queue.removeFirst() for (next in neighbours(current)) { if (isFinal(next)) return dist + 1 if (visited.at(next)) continue queue.add(next to dist + 1) visited.set(next, true) } } return -1 } } fun parseInput(input: List<String>): Field { val field = Field() field.field.addAll(input.mapIndexed { i, value -> value.toList().mapIndexed { j, char -> when (char) { 'S' -> { field.start = Coordinate(i, j) 'a' - 'a' } 'E' -> { field.end = Coordinate(i, j) 'z' - 'a' } else -> char - 'a' } } }) return field } fun part1(input: List<String>): Int { val field = parseInput(input) return field.bfs() } fun part2(input: List<String>): Int { val field = parseInput(input) field.canStep = { from, to -> field.field.at(to) >= field.field.at(from) - 1 } return field.bfs(field.end) { x -> field.field.at(x) == 0 } } val testInput = readInputLines("Day12_test") check(part1(testInput) == 31) check(part2(testInput) == 29) val input = readInputLines(12) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1d5ac01d3d2f4be58c3d199bf15b1637fd6bcd6f
2,346
Advent-of-Code-2022-in-Kotlin
Apache License 2.0
src/Day07.kt
Fenfax
573,898,130
false
{"Kotlin": 30582}
fun main() { fun handleCommand(command: String, currentDir: CommandDir): CommandDir { if (command.contains("$ ls")) return currentDir val parsedCommand: String = command.split(" ").last() if (parsedCommand == "/"){ var returnDir = currentDir do { returnDir = returnDir.getParent() }while (returnDir.getParent() != returnDir) return returnDir } if (parsedCommand == "..") return currentDir.getParent() return currentDir.dirs.first { it.name == parsedCommand } } fun handleLsDir(list: String, currentDir: CommandDir){ currentDir.dirs.add(CommandDir(name = list.split(" ").last(), parentDir = currentDir)) } fun handleLsFile(list: String, currentDir: CommandDir){ val listFile = list.split(" ") currentDir.files.add(CommandFile(name = listFile.last(), size = listFile.first().toInt())) } fun handleLs(list: String, currentDir: CommandDir): CommandDir { when(list.startsWith("dir")){ true -> handleLsDir(list, currentDir) false -> handleLsFile(list, currentDir) } return currentDir } fun parseInput(input: List<String>): CommandDir { val root = CommandDir("/") var currentDir = root for (command in input) { currentDir = when (command.startsWith("$")) { true -> handleCommand(command, currentDir) false -> handleLs(command, currentDir) } } return root } fun part1(commandDir: CommandDir, currentSize: Int): Int { val newSize = if (commandDir.getSize() <= 100_000) commandDir.getSize() else 0 return newSize + commandDir.dirs.sumOf{ part1(it,currentSize + newSize) } } fun part2(commandDir: CommandDir, currentMin: Int, sizeNeeded: Int): Int{ val newSize = if (commandDir.getSize() >= sizeNeeded) commandDir.getSize() else return currentMin if (commandDir.dirs.size == 0) return newSize return if (newSize <= currentMin ) commandDir.dirs.minOf { part2(it, newSize, sizeNeeded) } else currentMin } val input = readInput("Day07") val rootDir = parseInput(input) println(part1(rootDir, 0)) println(part2(rootDir, rootDir.getSize(), 30_000_000 - 70_000_000 + rootDir.getSize())) } data class CommandFile(val name: String, val size: Int) data class CommandDir( val name: String, val dirs: MutableList<CommandDir> = mutableListOf(), val files: MutableList<CommandFile> = mutableListOf(), val parentDir: CommandDir? = null ) { fun getParent(): CommandDir { return this.parentDir ?: this } fun getSize(): Int { return files.sumOf { it.size } + dirs.sumOf { it.getSize() } } override fun toString(): String { return "CommandDir(name='$name')" } }
0
Kotlin
0
0
28af8fc212c802c35264021ff25005c704c45699
2,963
AdventOfCode2022
Apache License 2.0
9_nine/FallingBlocks.kt
thalees
250,902,664
false
null
import java.util.* private class Block(val l: Int, val r: Int) : Comparable<Block> { fun cover(c: Block) = l <= c.l && r >= c.r override fun compareTo(other: Block): Int = l.compareTo(other.l) } fun main() { val (n, d) = readLine()!!.split(" ").map { it.toInt() } val bh = arrayOfNulls<TreeSet<Block>>(n + 1) // blocks by height // Segment tree val tt = BooleanArray(4 * d) // terminal(leaf) node in segment tree val th = IntArray(4 * d) // max height in this segment tt[0] = true // Segment tree functions fun findMax(b: Block, i: Int, tl: Int, tr: Int): Int { if (tt[i] || b.l <= tl && b.r >= tr) return th[i] val tm = (tl + tr) / 2 return maxOf( if (b.l <= tm) findMax(b, 2 * i + 1, tl, tm) else 0, if (b.r > tm) findMax(b, 2 * i + 2, tm + 1, tr) else 0 ) } fun setLeaf(i: Int, h: Int) { tt[i] = true th[i] = h } fun place(b: Block, h: Int, i: Int, tl: Int, tr: Int) { if (b.l <= tl && b.r >= tr) return setLeaf(i, h) val tm = (tl + tr) / 2 val j1 = 2 * i + 1 val j2 = 2 * i + 2 if (tt[i]) { // split node tt[i] = false setLeaf(j1, th[i]) setLeaf(j2, th[i]) } if (b.l <= tm) place(b, h, j1, tl, tm) if (b.r > tm) place(b, h, j2, tm + 1, tr) th[i] = maxOf(th[j1], th[j2]) } // Simulate each incoming block & print answer var bc = 0 repeat(n) { val b = readLine()!!.split(" ").map { it.toInt() }.let{ (l, r) -> Block(l, r) } var maxH = findMax(b, 0, 1, d) while (true) { val bs = bh[maxH] ?: break var floor = bs.floor(b) if (floor != null && floor.r < b.l) floor = bs.higher(floor) if (floor == null) floor = bs.first() check(floor.l <= b.r) val list = bs.tailSet(floor).takeWhile { it.l <= b.r } if (!b.cover(list.first()) || !b.cover(list.last())) break for (c in list) bs -= c // don't use bs.removeAll(list) bc -= list.size maxH-- } val h = maxH + 1 place(b, h, 0, 1, d) val bs = bh[h] ?: run { TreeSet<Block>().also { bh[h] = it } } bs += b println(++bc) } }
0
Kotlin
0
0
3b499d207d366450c7b2facbd99a345c86b6eff8
2,316
kotlin-code-challenges
MIT License
src/main/kotlin/days_2021/Day8.kt
BasKiers
434,124,805
false
{"Kotlin": 40804}
package days_2021 import util.Day import kotlin.math.pow class Day8 : Day(8) { val input = inputList.map { it.split(" | ") }.map { (examples, answer) -> examples.split(" ").map(String::toCharArray).map(CharArray::toSet) to answer.split(" ").map(String::toCharArray).map(CharArray::toSet) } class SevenSegmentDisplay(mapping: Map<Int, Set<Char>>, words: List<Set<Char>>) { val values: List<Int> val value: Int init { values = words.map { word -> mapping.toList().first { (_, charSet) -> charSet == word }.first } value = values.reversed().reduceIndexed { index, acc, it -> acc + (it * (10F.pow(index))).toInt() } } companion object { fun from(examples: List<Set<Char>>, words: List<Set<Char>>): SevenSegmentDisplay { val numberToSegmentMapping: MutableMap<Int, Set<Char>> = mutableMapOf(); for (number in listOf(2, 3, 4, 7, 6, 5)) { for (example in examples.filter { it.size == number }) { when (example.size) { 2 -> numberToSegmentMapping[1] = example 3 -> numberToSegmentMapping[7] = example 4 -> numberToSegmentMapping[4] = example 7 -> numberToSegmentMapping[8] = example 6 -> { // 6 9 0 val overlaps7 = numberToSegmentMapping[7]!!.all { char -> example.contains(char) } val overlaps4 = numberToSegmentMapping[4]!!.all { char -> example.contains(char) } if (overlaps7 && overlaps4) { numberToSegmentMapping[9] = example } else if (overlaps7) { numberToSegmentMapping[0] = example } else { numberToSegmentMapping[6] = example } } 5 -> { // 2, 5, 3 val overlaps7 = numberToSegmentMapping[7]!!.all { char -> example.contains(char) } val rightTop = numberToSegmentMapping[1]!!.filter { char -> !numberToSegmentMapping[6]!!.contains(char) } val overlapsRightTop = rightTop.all { char -> example.contains(char) } if (overlaps7) { numberToSegmentMapping[3] = example } else if (overlapsRightTop) { numberToSegmentMapping[2] = example } else { numberToSegmentMapping[5] = example } } } } } return SevenSegmentDisplay(numberToSegmentMapping, words) } } } override fun partOne(): Any { return input.sumOf { (examples, words) -> SevenSegmentDisplay.from(examples, words).values.filter { listOf( 1, 4, 7, 8 ).contains(it) }.size } } override fun partTwo(): Any { return input.sumOf { (examples, words) -> SevenSegmentDisplay.from(examples, words).value } } }
0
Kotlin
0
0
870715c172f595b731ee6de275687c2d77caf2f3
3,633
advent-of-code-2021
Creative Commons Zero v1.0 Universal
7_seven/MNumbers.kt
thalees
250,902,664
false
null
fun main() { val (m, k) = readLine()!!.split(" ").map { it.toInt() } val f = factor(m) ?: run { println(-1) return } val dp = HashMap<Long,Long>() val dig = IntArray(100_000) fun count(nd: Int, p: Long = -1): Long { val e = f[0] + (f[1] shl 5) + (f[2] shl 10) + (f[3] shl 15) + (nd.toLong() shl 20) if (nd == 0) return if (e == 0L) 1 else 0 if (p == -1L) dp[e]?.let { return it } var cnt = 0L for (d in 1..9) { dig[nd - 1] = d val df = factors[d] for (i in 0..3) f[i] -= df[i] if (f.all { it >= 0 }) { val nc = count(nd - 1) if (p >= 0 && cnt + nc > p) return count(nd - 1, p - cnt) cnt += nc } for (i in 0..3) f[i] += df[i] } dp[e] = cnt return cnt } var num = 1L var nd = 1 while (count(nd) <= k - num) num += count(nd++) check(count(nd, k - num) == 1L) println(dig.take(nd).reversed().joinToString("")) } private val pr = listOf(2, 3, 5, 7) private val factors = Array(10) { factor(it)!! } private fun factor(m: Int): IntArray? { val f = IntArray(4) if (m <= 1) return f var rem = m for ((i, p) in pr.withIndex()) { while (rem % p == 0) { rem /= p f[i]++ } } return f.takeIf { rem == 1 } }
0
Kotlin
0
0
3b499d207d366450c7b2facbd99a345c86b6eff8
1,407
kotlin-code-challenges
MIT License
src/Day03.kt
tbilou
572,829,933
false
{"Kotlin": 40925}
fun main() { fun part1(input: List<String>): Int { // "abcdaf" -> [[a,b,c],[d,a,f]] -> [a] -> [1] return input.map { it.toList().chunked(it.length/2) } .flatMap { e -> e.first().toSet().intersect(e.last().toSet()) } .sumOf { e -> getAsciiValue(e) } } fun part2(input: List<String>): Int { // [line1, line2, line3] -> [[a]] -> [a] -> [1] return input.map { it.toSet() } .windowed(3, 3) { it[0].intersect(it[1]).intersect(it[2]) } .flatten() .sumOf { getAsciiValue(it) } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) // test if implementation meets criteria from the description, like: val testInput2 = readInput("Day03_test") check(part2(testInput2) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) } fun getAsciiValue(c: Char): Int { return when { c.isUpperCase() -> c.code - 38 c.isLowerCase() -> c.code - 96 else -> -1 } } // var res = mutableListOf<Char>() // input.forEach { // val splitList = it.toList().chunked(it.toList().size / 2) // res.add(splitList.first().intersect(splitList.last()).first()) // } // val nums = res.map { it -> getAsciiValue(it) } // // return nums.sum()
0
Kotlin
0
0
de480bb94785492a27f020a9e56f9ccf89f648b7
1,456
advent-of-code-2022
Apache License 2.0
src/day09/Day09.kt
EndzeitBegins
573,569,126
false
{"Kotlin": 111428}
package day09 import readInput import readTestInput import kotlin.math.absoluteValue private data class Position(val x: Int, val y: Int) private fun List<String>.asSteps(): List<Char> = flatMap { command -> List(size = command.substring(2).toInt()) { command.first() } } private fun generateRope(size: Int): List<Position> = List(size = size) { Position(x = 0, y = 0) } private fun Position.take(step: Char): Position { return when (step) { 'L' -> copy(x = x - 1) 'R' -> copy(x = x + 1) 'U' -> copy(y = y + 1) 'D' -> copy(y = y - 1) else -> error("Invalid step '$step'!") } } private fun Position.follow(other: Position): Position { val xOffset = this.x - other.x val yOffset = this.y - other.y return if (xOffset.absoluteValue >= 2 || yOffset.absoluteValue >= 2) { val adjustXBy = when { xOffset < 0 -> 1 xOffset > 0 -> -1 else -> 0 } val adjustYBy = when { yOffset < 0 -> 1 yOffset > 0 -> -1 else -> 0 } Position(x = x + adjustXBy, y = y + adjustYBy) } else this } private fun List<Position>.simulate(steps: List<Char>): Set<Position> { val simulatedRope = this.toMutableList() val tailPositions = mutableSetOf(simulatedRope.last()) for (step in steps) { simulatedRope[0] = simulatedRope[0].take(step) for (i in simulatedRope.indices.drop(1)) { simulatedRope[i] = simulatedRope[i].follow(simulatedRope[i - 1]) } tailPositions += simulatedRope.last() } return tailPositions } private fun part1(input: List<String>): Int { val steps = input.asSteps() val rope = generateRope(size = 2) val tailPositions = rope.simulate(steps = steps) return tailPositions.size } private fun part2(input: List<String>): Int { val steps = input.asSteps() val rope = generateRope(size = 10) val tailPositions = rope.simulate(steps = steps) return tailPositions.size } fun main() { // test if implementation meets criteria from the description, like: val testInput = readTestInput("Day09") check(part1(testInput) == 13) check(part2(testInput) == 1) val input = readInput("Day09") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ebebdf13cfe58ae3e01c52686f2a715ace069dab
2,345
advent-of-code-kotlin-2022
Apache License 2.0
src/Day05.kt
iartemiev
573,038,071
false
{"Kotlin": 21075}
import java.util.* fun makeMoves(moves: List<List<Int>>, stacks: List<MutableList<Char>>): List<MutableList<Char>> { for (move in moves) { val (quantity, source, destination) = move for (i in 1..quantity) { val crate = stacks[source-1].last() stacks[source-1].removeLast() stacks[destination-1].add(crate) } } return stacks } fun makeMoves2(moves: List<List<Int>>, stacks: List<MutableList<Char>>): List<MutableList<Char>> { for (move in moves) { val (quantity, source, destination) = move val crates = stacks[source-1].takeLast(quantity) stacks[destination-1].addAll(crates) for (i in 1..quantity) { stacks[source - 1].removeLast() } } return stacks } fun parseInput(input: List<String>): Pair<MutableList<List<Int>>, List<MutableList<Char>>> { val moves: MutableList<List<Int>> = mutableListOf() val rows: MutableList<List<Char>> = mutableListOf() fun parseLine(line: String): List<Char> { var idx = 1 val offset = 4 val list: MutableList<Char> = mutableListOf() while (idx < line.length) { val char = if (line[idx] != ' ') line[idx] else '0' list.add(char) idx += offset } return list } fun transposeRows(rows: List<List<Char>>): List<MutableList<Char>> { val listSize = rows.last().size val matrix: List<MutableList<Char>> = List(listSize){mutableListOf()} for (row in rows) { row.forEachIndexed{index, char -> if (char != '0') { matrix[index].add(0, char) } } } return matrix } for (line in input) { if (line.startsWith("move")) { val move = line.split(" ").filter{ it.toDoubleOrNull() != null }.map{ it.toInt() } moves.add(move) } else if (line.contains('[')) { val row = parseLine(line) rows.add(row) } } val stacks = transposeRows((rows)) return Pair(moves, stacks) } fun main() { fun part1(input: List<String>): String { val (moves, stacks) = parseInput(input); return makeMoves(moves, stacks).fold("") {acc, stack -> acc + stack.last() } } fun part2(input: List<String>): String { val (moves, stacks) = parseInput(input); return makeMoves2(moves, stacks).fold("") {acc, stack -> acc + stack.last() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8d2b7a974c2736903a9def65282be91fbb104ffd
2,549
advent-of-code
Apache License 2.0
src/main/aoc2015/Day15.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2015 import kotlin.math.max class Day15(input: List<String>) { // List of ingredients, each entry is a list of parameters describing the ingredient (last is calories) private val ingredients = parseInput(input) private fun parseInput(input: List<String>): List<List<Int>> { return input.map { line -> line.split(" ").let { listOf(it[2].dropLast(1).toInt(), it[4].dropLast(1).toInt(), it[6].dropLast(1).toInt(), it[8].dropLast(1).toInt(), it[10].toInt() ) } } } private fun score(amounts: List<Int>): Int { val scores = MutableList(4) { 0 } for (property in 0..3) { for ((index, ingredient) in ingredients.withIndex()) { scores[property] += amounts[index] * ingredient[property] } } return scores .map { if (it < 0) 0 else it } .fold(1) { total, item -> item * total } } private fun calories(amounts: List<Int>): Int { return ingredients.withIndex().fold(0) { total, item -> total + amounts[item.index] * item.value.last() } } private fun allCombinations(num: Int, calorieLimit: Boolean = false): Int { var best = 0 if (num == 4) { for (i in 0..100) { for (j in 0..100 - i) { for (k in 0..100 - i - j) { val amounts = listOf(i, j, k, 100 - i - j - k) if (!calorieLimit || calories(amounts) == 500) { best = max(best, score(amounts)) } } } } } else if (num == 2) { for (i in 0..100) { val amounts = listOf(i, 100 - i) if (!calorieLimit || calories(amounts) == 500) { best = max(best, score(amounts)) } } } return best } fun solvePart1(): Int { return allCombinations(ingredients.size) } fun solvePart2(): Int { return allCombinations(ingredients.size, true) } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
2,259
aoc
MIT License
src/Day07.kt
ka1eka
574,248,838
false
{"Kotlin": 36739}
fun main() { abstract class Entry(val name: String, val children: MutableList<Entry>? = null) { abstract val size: Long override fun toString(): String = name } class Directory(name: String) : Entry(name, mutableListOf()) { override val size: Long get() = children!!.sumOf { it.size } } class File(name: String, override val size: Long) : Entry(name) fun cd(pwd: Directory, target: String): Directory { return pwd.children!!.find { it.name == target } as Directory } fun parseOutput(root: Directory, dirs: MutableList<Directory>, input: List<String>) { val path = ArrayDeque<Directory>() var listing = false for (line in input) { if (listing) { if (line.startsWith("\$")) { listing = false } else { if (line.startsWith("dir ")) { val dirName = line.substring(4) if (path.first().children?.find { it.name == dirName } == null) { val dir = Directory(dirName) path.first().children!!.add(dir) dirs.add(dir) } } else { line.split(' ') .run { val fileName = this[1] if (path.first().children?.find { it.name == fileName } == null) { val file = File(fileName, this[0].toLong()) path.first().children!!.add(file) } } } } } if (!listing) { if (line == "\$ cd /") { path.clear() path.addFirst(root) } else if (line == "\$ cd ..") { path.removeFirst() } else if (line.startsWith("\$ cd ")) { val pwd = cd(path.first(), line.substring(5)) path.addFirst(pwd) }else if (line == "\$ ls") { listing = true } } } } fun part1(input: List<String>): Long { val root = Directory("/") val dirs: MutableList<Directory> = mutableListOf() parseOutput(root, dirs, input) return dirs .asSequence() .filter { it.size <= 100000 } .sumOf { it.size } } fun part2(input: List<String>): Long { val root = Directory("/") val dirs: MutableList<Directory> = mutableListOf() parseOutput(root, dirs, input) val remainingSpace = 70000000 - root.size val requiredSpace = 30000000 - remainingSpace return dirs .asSequence() .filter { it.size >= requiredSpace } .minOf { it.size } } val testInput = readInput("Day07_test") check(part1(testInput) == 95437L) check(part2(testInput) == 24933642L) val input = readInput("Day07") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
4f7893448db92a313c48693b64b3b2998c744f3b
3,225
advent-of-code-2022
Apache License 2.0
src/main/kotlin/dev/tasso/adventofcode/_2021/day14/Day14.kt
AndrewTasso
433,656,563
false
{"Kotlin": 75030}
package dev.tasso.adventofcode._2021.day14 import dev.tasso.adventofcode.Solution import java.math.BigInteger class Day14 : Solution<BigInteger> { override fun part1(input: List<String>): BigInteger { return runPolymerization(input, 10) } override fun part2(input: List<String>): BigInteger { return runPolymerization(input, 40) } } fun runPolymerization(input: List<String>, numIterations: Int) : BigInteger { var polymerPairMap = input[0].windowed(2) .groupingBy { it } .eachCount() .map{Pair(it.key, it.value.toBigInteger())} .toMap() .toMutableMap() val pairInsertionMap = input.subList(2, input.size) .map { it.split(" -> ") } .associate { Pair(it[0], it[1]) } for(i in 1..numIterations) { val tempMap = mutableMapOf<String, BigInteger>() polymerPairMap.forEach { (originalPair, pairTotal) -> val insertPolymer = pairInsertionMap[originalPair] val firstNewPair = originalPair[0] + insertPolymer!! val secondNewPair = insertPolymer + originalPair[1] tempMap[firstNewPair] = tempMap.getOrElse(firstNewPair){BigInteger.valueOf(0)} + pairTotal tempMap[secondNewPair] = tempMap.getOrElse(secondNewPair){BigInteger.valueOf(0)} + pairTotal } polymerPairMap = tempMap.toMutableMap() } val polymerToCountMap = pairInsertionMap.map { it.value } .associateWith { polymer -> polymerPairMap.filter { it.key.startsWith(polymer) }.map{it.value}.sum() } .toMutableMap() //After the mapping, we can't easily tell what the last character is. Since we're expanding pairs, the last //character of the input is the last character of our resultant String //be tacked onto the totals later polymerToCountMap[input[0].last().toString()] = polymerToCountMap[input[0].last().toString()]!! + BigInteger.valueOf(1) return polymerToCountMap.maxOf { it.value } - polymerToCountMap.minOf { it.value } } fun Iterable<BigInteger>.sum(): BigInteger { var sum: BigInteger = BigInteger.ZERO for (element in this) { sum += element } return sum }
0
Kotlin
0
0
daee918ba3df94dc2a3d6dd55a69366363b4d46c
2,389
advent-of-code
MIT License
src/main/kotlin/dev/pankowski/garcon/domain/Texts.kt
apankowski
360,267,645
false
{"Kotlin": 194512, "Dockerfile": 725, "Shell": 201}
package dev.pankowski.garcon.domain import java.text.BreakIterator import java.util.* import java.util.Collections.unmodifiableList /** * Calculates [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) * between given char sequences. */ fun levenshtein(a: CharSequence, b: CharSequence): Int { val aLength = a.length val bLength = b.length var cost = IntArray(aLength + 1) { it } var newCost = IntArray(aLength + 1) { 0 } for (j in 1..bLength) { newCost[0] = j for (i in 1..aLength) { val insertCost = cost[i] + 1 val deleteCost = newCost[i - 1] + 1 val replaceCost = cost[i - 1] + if (a[i - 1] == b[j - 1]) 0 else 1 newCost[i] = minOf(insertCost, deleteCost, replaceCost) } run { val temp = cost; cost = newCost; newCost = temp } // Or: cost = newCost.also { newCost = cost } } return cost[aLength] } /** * Calculates [Damerau-Levenshtein distance](https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance) * between given char sequences. */ fun damerauLevenshtein(a: CharSequence, b: CharSequence): Int { fun distance(a: CharSequence, b: CharSequence): Int { assert(a.length >= 2) assert(b.length >= 2) fun levenshteinCost(cost0: IntArray, cost1: IntArray, i: Int, j: Int): Int { val insertCost = cost0[i] + 1 val deleteCost = cost1[i - 1] + 1 val replaceCost = cost0[i - 1] + if (a[i - 1] == b[j - 1]) 0 else 1 return minOf(insertCost, deleteCost, replaceCost) } fun damerauCost(cost0: IntArray, cost1: IntArray, cost2: IntArray, i: Int, j: Int): Int { val levenshteinCost = levenshteinCost(cost1, cost2, i, j) if (a[i - 1] == b[j - 2] && a[i - 2] == b[j - 1]) { val transpositionCost = cost0[i - 2] + 1 return minOf(levenshteinCost, transpositionCost) } return levenshteinCost } val aLength = a.length val bLength = b.length // First seed row, corresponding to j = 0 val cost0 = IntArray(aLength + 1) { it } // Second seed row, corresponding to j = 1 val cost1 = IntArray(aLength + 1) cost1[0] = 1 for (i in 1..aLength) cost1[i] = levenshteinCost(cost0, cost1, i, 1) val cost2 = IntArray(aLength + 1) tailrec fun cost(cost0: IntArray, cost1: IntArray, cost2: IntArray, j: Int): Int { cost2[0] = j cost2[1] = levenshteinCost(cost1, cost2, 1, j) for (i in 2..aLength) cost2[i] = damerauCost(cost0, cost1, cost2, i, j) return if (j == bLength) cost2[aLength] else cost(cost1, cost2, cost0, j + 1) } return cost(cost0, cost1, cost2, 2) } // Analyze input and eliminate simple cases: // - Order strings by length, so that we have longer (l) and shorter (s). // - Exit early when shorter string has zero or one character. // This leaves us with l.length >= s.length >= 2. val (l, s) = if (a.length >= b.length) Pair(a, b) else Pair(b, a) return when { s.isEmpty() -> l.length s.length == 1 -> if (l.contains(s[0])) l.length - 1 else l.length else -> distance(l, s) } } fun String.extractWords(locale: Locale): List<String> { val it = BreakIterator.getWordInstance(locale) it.setText(this) tailrec fun collectWords(start: Int, end: Int, words: List<String>): List<String> { if (end == BreakIterator.DONE) return words val word = this.substring(start, end) val newWords = if (Character.isLetterOrDigit(word[0])) words + word else words return collectWords(end, it.next(), newWords) } return unmodifiableList(collectWords(it.first(), it.next(), emptyList())) } fun CharSequence.ellipsize(at: Int) = when { length <= at -> this else -> substring(0, at) + Typography.ellipsis } fun CharSequence.oneLinePreview(maxLength: Int) = replace("\\s*\\n+\\s*".toRegex(), " ").ellipsize(maxLength)
6
Kotlin
0
2
10f5126bc0c2e09f88bae19035bad64b1fbcd7ca
3,849
garcon
Apache License 2.0
src/main/kotlin/com/anahoret/aoc2022/day24/main.kt
mikhalchenko-alexander
584,735,440
false
null
package com.anahoret.aoc2022.day24 import com.anahoret.aoc2022.ManhattanDistanceAware import java.io.File import java.util.PriorityQueue import kotlin.system.measureTimeMillis enum class Direction { LEFT, RIGHT, UP, DOWN } data class Blizzard(val row: Int, val col: Int, val direction: Direction) operator fun List<Blizzard>.contains(position: Position): Boolean { return any { b -> b.row == position.row && b.col == position.col } } class Valley(private val width: Int, private val height: Int, private val blizzards: List<Blizzard>) { val start = Position(0, 1) val finish = Position(height - 1, width - 2) private val blizzardHashes = blizzards.map { it.row * width + it.col }.toSet() fun tick(): Valley { val nextBlizzards = blizzards.map { blizzard -> when (blizzard.direction) { Direction.LEFT -> if (blizzard.col > 1) blizzard.copy(col = blizzard.col - 1) else blizzard.copy(col = width - 2) Direction.RIGHT -> if (blizzard.col < width - 2) blizzard.copy(col = blizzard.col + 1) else blizzard.copy( col = 1 ) Direction.UP -> if (blizzard.row > 1) blizzard.copy(row = blizzard.row - 1) else blizzard.copy(row = height - 2) Direction.DOWN -> if (blizzard.row < height - 2) blizzard.copy(row = blizzard.row + 1) else blizzard.copy( row = 1 ) } } return Valley(width, height, nextBlizzards) } fun walkable(position: Position): Boolean { return position in this && position.row * width + position.col !in blizzardHashes } operator fun contains(position: Position): Boolean { return position == start || position == finish || ( position.row > 0 && position.row < height - 1 && position.col > 0 && position.col < width - 1 ) } } fun parseValley(input: String): Valley { val lines = input.lines() val width = lines.first().length val height = lines.size val blizzards = lines.flatMapIndexed { rowIdx, row -> row.toList().mapIndexedNotNull { colIdx, col -> when (col) { '<' -> Blizzard(rowIdx, colIdx, Direction.LEFT) '>' -> Blizzard(rowIdx, colIdx, Direction.RIGHT) 'v' -> Blizzard(rowIdx, colIdx, Direction.DOWN) '^' -> Blizzard(rowIdx, colIdx, Direction.UP) else -> null } } } return Valley(width, height, blizzards) } data class Position(val row: Int, val col: Int) : ManhattanDistanceAware { override val x: Int = col override val y: Int = row val neighbours by lazy { listOf( Position(row - 1, col), Position(row + 1, col), Position(row, col - 1), Position(row, col + 1) ) } } fun main() { val input = File("src/main/kotlin/com/anahoret/aoc2022/day24/input.txt") .readText() .trim() val valley = parseValley(input) // Part 1 part1(valley).also { println("P1: ${it}ms") } // Part 2 part2(valley).also { println("P2: ${it}ms") } } private fun part1(initialValley: Valley) = measureTimeMillis { println(timeToTrip(initialValley, initialValley.start, initialValley.finish).first) } private fun part2(initialValley: Valley) = measureTimeMillis { val (timeToGoToFinish, valleyAtFinish) = timeToTrip(initialValley, initialValley.start, initialValley.finish) val (timeToGoBackToStart, valleyAtBackToStart) = timeToTrip(valleyAtFinish, initialValley.finish, initialValley.start) val (timeToGoBackToFinish, _) = timeToTrip(valleyAtBackToStart, initialValley.start, initialValley.finish) println(timeToGoToFinish + timeToGoBackToStart + timeToGoBackToFinish) } private fun timeToTrip(initialValley: Valley, start: Position, finish: Position): Pair<Int, Valley> { val valleySteps = mutableMapOf<Int, Valley>() valleySteps[0] = initialValley fun getValleyStep(step: Int): Valley { return valleySteps.getOrPut(step) { getValleyStep(step - 1).tick() } } var finishSteps = Int.MAX_VALUE val queue = PriorityQueue { p1: Pair<Position, Int>, p2: Pair<Position, Int> -> p1.first.manhattanDistance(finish).compareTo(p2.first.manhattanDistance(finish)) .takeIf { it != 0 } ?: p1.second.compareTo(p2.second) } queue.add(start to 0) val observed = mutableSetOf<Pair<Position, Int>>() while (queue.isNotEmpty()) { val poll = queue.poll() val (position, step) = poll if (step >= finishSteps || poll in observed) continue observed.add(poll) if (position == finish) { finishSteps = step queue.removeIf { it.second >= finishSteps || it.second + it.first.manhattanDistance(finish) >= finishSteps } } val nextStep = step + 1 if (nextStep < finishSteps) { val nextValley = getValleyStep(nextStep) (position.neighbours + position) .forEach { val newPair = it to nextStep if ( newPair !in observed && nextStep + it.manhattanDistance(finish) < finishSteps && nextValley.walkable(it) ) { queue.add(newPair) } } } } return finishSteps to valleySteps.getValue(finishSteps) }
0
Kotlin
0
0
b8f30b055f8ca9360faf0baf854e4a3f31615081
5,621
advent-of-code-2022
Apache License 2.0
src/Day08.kt
rbraeunlich
573,282,138
false
{"Kotlin": 63724}
fun main() { fun isVisibleInRow(columnIndex: Int,rowIndex: Int, row: IntArray): Boolean { // check left side val left = 0 until columnIndex val fromLeft = left.map { leftIndex -> if (row[leftIndex] >= row[columnIndex]) { // println("Tree ${row[rowIndex]} column $columnIndex and row $rowIndex is not visible in left row") false } else { true } }.reduce { acc, b -> acc && b } // check right side val right = (columnIndex + 1) .. (row.size-1) val fromRight = right.map { rightIndex -> if (row[rightIndex] >= row[columnIndex]) { // println("Tree ${row[rowIndex]} column $columnIndex and row $rowIndex is not visible in right row") false } else { true } }.reduce { acc, b -> acc && b } return (fromLeft || fromRight) } fun isVisibleInColumn(columnIndex: Int, rowIndex: Int, treeGrid: Array<IntArray?>): Boolean { // check top val top = 0 until rowIndex val fromTop = top.map { topIndex -> if(treeGrid[topIndex]!![columnIndex] >= treeGrid[rowIndex]!![columnIndex]) { // println("Tree column $columnIndex and row $rowIndex is not visible in column") false } else { true } }.reduce { acc, b -> acc && b } // check bottom val bottom = (rowIndex+1) .. (treeGrid.size-1) val fromBottom = bottom.map { bottomIndex -> if(treeGrid[bottomIndex]!![columnIndex] >= treeGrid[rowIndex]!![columnIndex]) { // println("Tree column $columnIndex and row $rowIndex is not visible in column") false } else { true } }.fold(true) { acc, b -> acc && b } return (fromTop || fromBottom) } fun isTreeVisible(columnIndex: Int, rowIndex: Int, tree: Int, rowSize: Int, treeGrid: Array<IntArray?>): Boolean { // trees on the edge if (columnIndex == 0 || rowIndex == 0) { return true } else if (columnIndex == (rowSize - 1) || rowIndex == (rowSize - 1)) { return true } else { val visibleInRow = isVisibleInRow(columnIndex, rowIndex, treeGrid[rowIndex]!!) val visibleInColumn = isVisibleInColumn( columnIndex, rowIndex, treeGrid ) val result = visibleInRow || visibleInColumn return result } } fun part1(input: List<String>): Int { val treeGrid = arrayOfNulls<IntArray>(input.size) input.forEachIndexed { index, row -> val currentRow = row.map { it.toString().toInt() }.toIntArray() treeGrid[index] = currentRow } var visibleTreeCounter = 0 treeGrid.forEachIndexed { rowIndex, treeRow -> treeRow!!.forEachIndexed { columnIndex, tree -> if (isTreeVisible(columnIndex, rowIndex, tree, treeRow.size, treeGrid)) { visibleTreeCounter++ } } } return visibleTreeCounter } fun part2(input: List<String>): Int { return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_test") println(part1(testInput)) check(part1(testInput) == 21) val testInput2 = readInput("Day08_test2") check(part1(testInput2) == 43) val testInput3 = readInput("Day08_test3") check(part1(testInput3) == 40) val testInput4 = readInput("Day08_test4") check(part1(testInput4) == 49) // 2169 too high val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
3c7e46ddfb933281be34e58933b84870c6607acd
3,882
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/groundsfam/advent/y2023/d03/Day03.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2023.d03 import com.groundsfam.advent.DATAPATH import com.groundsfam.advent.timed import kotlin.io.path.div import kotlin.io.path.useLines fun partNumbers(lines: List<String>): List<Int> { val ret = mutableListOf<Int>() lines.forEachIndexed { y, line -> var x = 0 while (x < line.length) { var numEnd = x // exclusive while (numEnd < line.length && line[numEnd].isDigit()) { numEnd++ } if (numEnd == x) { // (x,y) is not part of a number x++ } else { val symbolAdjacent = (x - 1..numEnd).any { x1 -> x1 in line.indices && (y - 1..y + 1).any { y1 -> y1 in lines.indices && lines[y1][x1].let { c -> !c.isDigit() && c != '.' } } } if (symbolAdjacent) { ret.add(line.substring(x until numEnd).toInt()) } x = numEnd } } } return ret } fun gearRatios(lines: List<String>): List<Long> { val ret = mutableListOf<Long>() lines.forEachIndexed { y, line -> line.mapIndexedNotNull { x, c -> if (c == '*') { x } else { null } }.forEach { x -> val adjacentNumbers = mutableSetOf<Pair<Int, Int>>() (y - 1..y + 1).forEach { y1 -> (x - 1..x + 1).forEach { x1 -> if (y1 in lines.indices && x1 in lines[y1].indices && lines[y1][x1].isDigit()) { if (x1 == x - 1 || x1 - 1 !in lines[y1].indices || !lines[y1][x1 - 1].isDigit()) { adjacentNumbers.add(x1 to y1) } } } } if (adjacentNumbers.size == 2) { adjacentNumbers.map { (x1, y1) -> val line1 = lines[y1] var numStart = x1 while (numStart in line1.indices && line1[numStart].isDigit()) { numStart-- } var numEnd = x1 while (numEnd in line1.indices && line1[numEnd].isDigit()) { numEnd++ } line1.substring((numStart + 1..<numEnd)).toLong() } .reduce { a, b -> a * b } .also { ret.add(it) } } } } return ret } fun main() = timed { val lines = (DATAPATH / "2023/day03.txt").useLines { it.toList() } partNumbers(lines) .sum() .also { println("Part one: $it") } gearRatios(lines) .sum() .also { println("Part two: $it") } }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
2,902
advent-of-code
MIT License
2021/src/main/kotlin/day14_fast.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parser import utils.Solution fun main() { Day14Fast.run() } object Day14All { @JvmStatic fun main(args: Array<String>) { mapOf("func" to Day14Func, "imp" to Day14Imp, "fast" to Day14Fast).forEach { (header, solution) -> solution.run(header = header, skipPart1 = false, skipTest = false, printParseTime = false) } } } object Day14Fast : Solution<Pair<Day14Fast.Polymer, IntArray>>() { private val elements = "HKFVNSBCPO" private val sz = elements.length private val psh = generateSequence(1) { it * 2 }.indexOfFirst { it > sz } private val psz = 1 shl psh private val Char.int: Int get() { return elements.indexOf(this).takeIf { it >= 0 } ?: throw IllegalArgumentException("Bad input char '$this'") } override val name = "day14" override val parser = Parser { input -> val (polymer, ruleLines) = input.split("\n\n") val p = Polymer(LongArray(psz * psz) { 0 }, LongArray(sz) { 0 }) val r = IntArray(psz * psz) { -1 } p.chars[polymer.first().int]++ for (i in 0 until polymer.length - 1) { val c1 = polymer[i].int val c2 = polymer[i + 1].int p.pairs[(c1 shl psh) + c2]++ p.chars[c2]++ } ruleLines.lines().filter { it.isNotBlank() }.forEach { line -> val (pair, replace) = line.split(" -> ").map { it.trim() } r[(pair[0].int shl psh) + pair[1].int] = replace[0].int } return@Parser p to r } class Polymer(val pairs: LongArray, val chars: LongArray) fun solve(polymer: Polymer, rules: IntArray, days: Int): Long { val pairs = polymer.pairs.clone() val chars = polymer.chars.clone() val pairDeltas = LongArray(pairs.size) { 0 } val charDeltas = LongArray(chars.size) { 0 } repeat(days) { pairDeltas.fill(0) charDeltas.fill(0) for (c1 in 0 until sz) { for (c2 in 0 until sz) { val pair = (c1 shl psh) + c2 val char = rules[pair] if (char == -1) continue val count = pairs[pair] pairDeltas[pair] -= count pairDeltas[(pair and ((psz - 1) shl psh)) or char] += count pairDeltas[(char shl psh) or (pair and (psz - 1))] += count charDeltas[char] += count } } for (c1 in 0 until sz) { for (c2 in 0 until sz) { val index = (c1 shl psh) or c2 pairs[index] += pairDeltas[index] } } charDeltas.forEachIndexed { i, v -> chars[i] += v } } var maxChar = Long.MIN_VALUE var minChar = Long.MAX_VALUE for (count in chars) { if (count == 0L) continue if (count > maxChar) maxChar = count if (count < minChar) minChar = count } return maxChar - minChar } override fun part1(input: Pair<Polymer, IntArray>): Long { return solve(input.first, input.second, 10) } override fun part2(input: Pair<Polymer, IntArray>): Long { return solve(input.first, input.second, 40) } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
2,954
aoc_kotlin
MIT License
src/day13/Solution.kt
chipnesh
572,700,723
false
{"Kotlin": 48016}
package day13 import readInput sealed interface Element : Comparable<Element> @JvmInline value class IntElement(val value: Int) : Element { override fun compareTo(other: Element): Int = when (other) { is IntElement -> compareValues(value, other.value) is ListElement -> compareValues(ListElement(this), other) } } @JvmInline value class ListElement(val value: MutableList<Element>) : Element { constructor(vararg elements: Element) : this(mutableListOf(*elements)) override fun compareTo(other: Element): Int = when (other) { is IntElement -> compareValues(this, ListElement(other)) is ListElement -> value.zip(other.value, Element::compareTo) .firstOrNull { it != 0 } ?: value.size.compareTo(other.value.size) } } fun toItem(string: String): ListElement = buildList<ListElement> { add(ListElement()) for (s in string.split(',')) { var token = s while (token.isNotEmpty()) { var drop = 1 when (token.take(1)) { "[" -> add(ListElement()) "]" -> removeLast().let { last().value.add(it) } else -> { val number = token.takeWhile(Char::isDigit) drop = number.length last().value.add(IntElement(number.toInt())) } } token = token.drop(drop) } } }.last() fun List<String>.toItemList() = filter(String::isNotBlank).map(::toItem) fun main() { fun part1(input: List<String>): Int { return input .toItemList() .chunked(2) .withIndex() .filter { it.value.reduce(::compareValues) == -1 } .sumOf { it.index + 1 } } fun part2(input: List<String>): Int { val dividers = setOf( ListElement(ListElement(IntElement(2))), ListElement(ListElement(IntElement(6))) ) return input .toItemList() .plus(dividers) .sorted() .mapIndexedNotNull { i, e -> if (e in dividers) i + 1 else null } .reduce(Int::times) } //val input = readInput("test") val input = readInput("prod") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
2d0482102ccc3f0d8ec8e191adffcfe7475874f5
2,299
AoC-2022
Apache License 2.0
2022/src/main/kotlin/day5_func.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Grid import utils.Parse import utils.Parser import utils.Solution import utils.badInput import utils.mapItems fun main() { Day5Func.run() } typealias Day5Input = Pair<List<List<Char>>, List<Insn>> val stackParser: Parser<List<List<Char>>> = Grid.chars().map { grid -> val stackCount = (grid.width + 1) / 4 List(stackCount) { i -> grid[1 + i * 4].values .filter { !it.isWhitespace() } .dropLast(1) .reversed() } } val insnParser = Parser.lines.mapItems(::parseInsn) .mapItems { (from, to, count) -> Insn(from - 1, to - 1, count) } @Parse("move {count} from {from} to {to}") data class Insn( val from: Int, val to: Int, val count: Int, ) object Day5Func : Solution<Day5Input>() { override val name = "day5" override val parser = Parser.compound(stackParser, insnParser) override fun part1(input: Day5Input): String { return solve(input, false) } override fun part2(input: Day5Input): String { return solve(input, true) } private fun solve(input: Day5Input, crateMover9001: Boolean): String { val (stacks, insns) = input val stacked = insns.fold(stacks) { s, insn -> simulate(s, insn, crateMover9001) } return stacked.map { it.last() }.joinToString("") } private fun simulate(stacks: List<List<Char>>, insn: Insn, crateMover9001: Boolean): List<List<Char>> { if (stacks[insn.from].size < insn.count) { badInput() } val crane = stacks[insn.from].takeLast(insn.count).let { if (crateMover9001) it else it.reversed() } return stacks.mapIndexed { i, stack -> when (i) { insn.from -> stack.dropLast(insn.count) insn.to -> stack + crane else -> stack } } } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,724
aoc_kotlin
MIT License
leetcode/src/daily/mid/Q870.kt
zhangweizhe
387,808,774
false
null
package daily.mid import java.util.* import kotlin.Comparator fun main() { // 870. 优势洗牌 // https://leetcode.cn/problems/advantage-shuffle/ println(advantageCount(intArrayOf(2,7,11,15), intArrayOf(1,10,4,11)).contentToString()) } fun advantageCount(nums1: IntArray, nums2: IntArray): IntArray { // 数组长度 val n = nums1.size // nums1 从小到大排序 nums1.sort() val indices = Array<Int>(n) { it } // 排序之后,indices[0] 就是 nums2 最小值的下标,indices[n-1] 就是 nums2 最大值的下标 Arrays.sort(indices, object : Comparator<Int> { override fun compare(o1: Int?, o2: Int?): Int { if (o1 == null || o2 == null) { return 0 } return nums2[o1] - nums2[o2] } }) // 排序之后,indices[left] 就是 nums2 最小值的下标,indices[right] 就是 nums2 最大值的下标 var left = 0 var right = n - 1 val ans = IntArray(n) // nums1 已经排过序,从左到右遍历 nums1 // 如果 nums1[i] > nums2[indices[left]], // 那 nums1[i] 就是 nums1 中,比 nums[indices[left]] 大,且是大得最少的,那 nums1[i] 就可以填充到 ans[indices[left]] 中 // 如果 nums1[i] <= nums2[indices[left]], // 那 nums1[i] 就用不上了,用 nums[i] 和 nums2 的最大值,也就是 nums2[indices[right]] 碰掉(nums[i] 填充到 ans[indices[right]]) for (i in nums1.indices) { // ans 的下标和 nums2 是同步的 if (nums1[i] > nums2[indices[left]]) { ans[indices[left]] = nums1[i] left++ }else { ans[indices[right]] = nums1[i] right-- } } return ans } fun advantageCount1(nums1: IntArray, nums2: IntArray): IntArray { // 用田忌赛马的思想,用 nums1 的最小值 min1,去试探 nums2 的最小值 min2,如果 min1 > min2,则优势+1 // 如果 min1 <= min2,则用 min1 去碰掉 nums2 的最大值 max2 // 因为要保持 nums2 的顺序,所以不能直接对 nums2 排序,可以定义一个新的数组 indices,初始化 indices[i] = i // 根据 nums2 对 indices 排序,这样依赖,indices[0] 就是 nums2 最小元素的下标,indices[indices.size-1] 就是 nums2 最大元素的下标 // 先对 nums1 排序 nums1.sort() // 定义 indices 数组,初始化 indices[i]=i val indices = Array(nums2.size) { it } // 根据 nums2 对 indices 排序,这样依赖,indices[0] 就是 nums2 最小元素的下标,indices[indices.size-1] 就是 nums2 最大元素的下标 Arrays.sort(indices) {i1, i2 -> nums2[i1].compareTo(nums2[i2]) } val result = IntArray(nums1.size) // 指向 indices 的左右指针 var left = 0 var right = indices.size - 1 for (i in nums1.indices) { if (nums1[i] > nums2[indices[left]]) { // nums1[i] 是优势的 result[indices[left]] = nums1[i] left++ }else { // nums[i] 是劣势的,碰掉 nums2 的最大值 result[indices[right]] = nums1[i] right-- } } return result }
0
Kotlin
0
0
1d213b6162dd8b065d6ca06ac961c7873c65bcdc
3,229
kotlin-study
MIT License
src/main/kotlin/com/dmc/advent2022/Day13.kt
dorienmc
576,916,728
false
{"Kotlin": 86239}
//--- Day 13: Distress Signal --- package com.dmc.advent2022 class Day13 : Day<Int> { override val index = 13 override fun part1(input: List<String>): Int { val packets = input.filter { it.isNotEmpty() }.map{ it.toPacket() } return packets.chunked(2).withIndex().filter { it.value[0] < it.value[1] // left should be smaller than right }.sumOf { it.index + 1 // first pair has index 1 } } override fun part2(input: List<String>): Int { val packets = input.filter { it.isNotEmpty() }.map{ it.toPacket() }.toMutableList() //Add divider packets val divider2 = "[[2]]".toPacket() val divider6 = "[[6]]".toPacket() // Sort and find indices of dividers val sorted = (packets + divider2 + divider6).sorted() return (sorted.indexOf(divider2) + 1) * (sorted.indexOf(divider6) + 1) } sealed class Packet : Comparable<Packet> { open fun size() : Int { return 1 } companion object { fun of(input: Iterator<String>) : Packet { val packets = mutableListOf<Packet>() while(input.hasNext()) { when (val elem = input.next()) { "[" -> packets.add(of(input)) "]" -> return ListPacket(packets) ",", "" -> {/*skip*/} else -> { if (elem.isNumeric()) { packets += IntPacket(elem.toInt()) } } } } return ListPacket(packets).first() //need the first() otherwise it is packages twice } } } data class IntPacket(val value: Int) : Packet() { fun asList(): Packet = ListPacket(mutableListOf(this)) override fun compareTo(other: Packet): Int = when (other) { is IntPacket -> this.value.compareTo(other.value) is ListPacket -> this.asList().compareTo(other) } override fun toString(): String = value.toString() } class ListPacket(private val packet: MutableList<Packet> = mutableListOf()) : Packet(), Iterable<Packet> { override fun size() : Int { return packet.size } override fun compareTo(other: Packet): Int { // println("Compare $this to $other") return when (other) { is IntPacket -> this.compareTo(other.asList()) is ListPacket -> { return this.packet.zip(other.packet).map { it.first.compareTo(it.second) }.firstOrNull { it != 0 } ?: this.size().compareTo(other.size()) } } } override fun toString(): String { return packet.toString() } override fun iterator(): Iterator<Packet> { return packet.iterator() } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as ListPacket if (packet != other.packet) return false return true } override fun hashCode(): Int { return packet.hashCode() } } } fun String.toPacket() : Day13.Packet { return Day13.Packet.of(this.split("""((?<=[\[\],])|(?=[\[\],]))""".toRegex()).iterator()) } fun String.isNumeric(): Boolean { return this.all { char -> char.isDigit() } } fun main() { val day = Day13() // test if implementation meets criteria from the description, like: val testInput = readInput(day.index, true) check(day.part1(testInput) == 13) val input = readInput(day.index) day.part1(input).println() day.part2(testInput) day.part2(input).println() }
0
Kotlin
0
0
207c47b47e743ec7849aea38ac6aab6c4a7d4e79
3,975
aoc-2022-kotlin
Apache License 2.0
neetcode/src/main/java/org/slidingwindow/SlidingWindowNeet.kt
gouthamhusky
682,822,938
false
{"Kotlin": 24242, "Java": 24233}
package org.slidingwindow import kotlin.math.abs // https://leetcode.com/problems/minimum-size-subarray-sum/ fun minSubArrayLen(target: Int, nums: IntArray): Int { var i = 0; var j = 0; var sum = 0; var min = Int.MAX_VALUE while (j < nums.size){ sum += nums[j] if (sum >= target){ while (sum >= target){ min = Math.min(min, j - i + 1) sum -= nums[i] i++ } } j++ } return if (min == Int.MAX_VALUE) 0 else min } fun findClosestElements(arr: IntArray, k: Int, x: Int): List<Int> { var i = 0; var j = 0 // create map with key as diff and value as list of elements val map = sortedMapOf<Int, MutableList<Int>>() while(j < arr.size){ val diff = Math.abs(arr[j] - x) if (map.containsKey(diff)){ map[diff]?.add(arr[j]) } else{ map.put(diff, mutableListOf(arr[j])) } j++ } var rem = k val ans = mutableListOf<Int>() for (key in map.keys){ while (rem > 0){ map[key]?.let { it -> if (it.size > 1){ ans.add(it.removeAt(0)) rem-- } } } } return ans.sorted() } fun containsNearbyDuplicate(nums: IntArray, k: Int): Boolean { var i = 0; var j = 0 val set = mutableSetOf<Int>() while (j < nums.size){ if (set.contains(nums[j])) return true set.add(nums[j]) if (j - i + 1> k){ set.remove(nums[i]) i++ } j++ } return false } fun checkInclusion(s1: String, s2: String): Boolean { val mapForS1 = hashMapOf<Char, Int>() val mapForS2 = hashMapOf<Char, Int>() val k = s1.length for (c in s1.toCharArray()) mapForS1[c] = mapForS1.getOrDefault(c, 0) + 1 var count = mapForS1.size var i = 0 var j = 0 while (j < s2.length){ val current = s2[j] mapForS2.put(current, mapForS2.getOrDefault(current, 0) + 1) if (j -i + 1 < k) j++ else if (j - i + 1 == k){ if(compareMaps(mapForS1, mapForS2)) return true else{ mapForS2.put(s2[i], mapForS2.get(s2[i])!! - 1) if(mapForS2.get(s2[i]) == 0) mapForS2.remove(s2[i]) i++ j++ } } } return false } private fun compareMaps(map1 : Map<Char, Int>, map2: Map<Char, Int>): Boolean { for (key in map1.keys){ if (! (map2.containsKey(key) && map2.get(key) == map1.get(key))) return false } return true } fun main() { checkInclusion("adc", "dcda") }
0
Kotlin
0
0
a0e158c8f9df8b2e1f84660d5b0721af97593920
2,778
leetcode-journey
MIT License
solutions/aockt/y2023/Y2023D05.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.y2023 import aockt.util.parse import io.github.jadarma.aockt.core.Solution object Y2023D05 : Solution { /** Returns true if there are any values that are contained in both ranges. */ private infix fun LongRange.overlaps(other: LongRange): Boolean = last >= other.first && first <= other.last /** Returns true if there are no values contained in the [other] range, which are not also contained in this. */ private infix fun LongRange.fullyContains(other: LongRange): Boolean = first <= other.first && other.last <= last /** Returns the range between the next after last element in this range, and before the first of the [other], or `null` */ private infix fun LongRange.bridgeTo(other: LongRange): LongRange? = when { last >= other.first - 1 -> null else -> last.inc()..<other.first } /** * Splits a range into one or more ranges, at the splitting points defined by the [chunks]. * Assumptions of [chunks]: They do not overlap, and are sorted. * * Examples: * - Splitting `55..67` by `[50..97, 98..99]` returns `[55..67]`. * - Splitting `57..69` by `[0..6, 7..10, 11..52, 53..60]` returns `[57..60, 61..69]`. * - Splitting `68..80` by `[0..68, 69..69]` returns `[68..68, 69..69, 70..80]`. * - Splitting `74..87` by `[45..63, 64..76, 77..99]` returns `[74..76, 77..87]`. */ private fun LongRange.splitBy(chunks: List<LongRange>): List<LongRange> { val ranges = chunks .filter { it overlaps this } .map { it.first.coerceAtLeast(first)..it.last.coerceAtMost(last) } .windowed(2, partialWindows = false) .flatMap { window -> when (window.size) { 1 -> window 2 -> listOfNotNull(window.first(), window[0] bridgeTo window[1]) else -> error("Impossible state.") } } .ifEmpty { return listOf(this) } val rangeMinimum = ranges.first().first val rangeMaximum = ranges.last().last return buildList { if (first < rangeMinimum) add(first..<rangeMinimum) addAll(ranges) if (last > rangeMaximum) add(rangeMaximum.inc()..last) } } /** * Converts between a value based on the [ranges]. * @property ranges A list of range definitions based on which to convert values. */ private class EntryMap(val ranges: List<RangeMap>) { /** Map the [value] to another one. If no mapping rules apply, returns the same value. */ operator fun get(value: Long): Long = ranges .firstNotNullOfOrNull { it[value] } ?: value /** Map a [range] of values in "parallel", returning all output ranges. */ operator fun get(range: LongRange): List<LongRange> = range .splitBy(ranges.map { it.source }) .map { split -> ranges.firstNotNullOfOrNull { it[split] } ?: split } /** * Defines a range mapping between * @property source The range to map from. * @property destination The range to map to. Must be of same size with [source]. */ data class RangeMap(val source: LongRange, val destination: LongRange) { /** Map a single [value] to its destination, or `null` if it is not contained in the source. */ operator fun get(value: Long): Long? = when (value in source) { true -> destination.first + (value - source.first) false -> null } /** Map an entire [range] of values to its destination, or `null` if it is not contained in the source. */ operator fun get(range: LongRange): LongRange? = when (source fullyContains range) { true -> (destination.first - source.first).let { delta -> (range.first + delta)..(range.last + delta) } else -> null } } } /** An elvish Almanac, specialized for gardening and food production. */ private class Almanac(val seeds: List<Long>, private val maps: List<EntryMap>) { /** Interprets seeds as ranges instead of individual values. */ fun seedsAsRanges(): List<LongRange> = seeds.chunked(2) { (start, size) -> start..<start + size } /** Given a single [value], applies all conversion steps and returns the answer. */ fun process(value: Long): Long = maps.fold(value) { acc, em -> em[acc] } /** Given a list of value [ranges], applies all conversion steps "in parallel" and returns all output ranges. */ fun process(ranges: List<LongRange>): List<LongRange> = maps.fold(ranges) { acc, em -> acc.flatMap { em[it] } } } /** Parse the [input] and return an [Almanac]. */ private fun parseInput(input: String): Almanac = parse { val mappingSteps = listOf("seed", "soil", "fertilizer", "water", "light", "temperature", "humidity", "location") val mapTypeRegex = Regex("""^([a-z]+)-to-([a-z]+) map:$""") fun parseEntryMap(entryIndex: Int, input: String): EntryMap { val lines = input.lines() val (source, destination) = mapTypeRegex.matchEntire(lines.first())!!.destructured check(source == mappingSteps[entryIndex]) { "Almanac records not in expected order." } check(destination == mappingSteps[entryIndex + 1]) { "Almanac mappings don't map in expected steps." } return lines .drop(1) .map { line -> val (destinationStart, sourceStart, size) = line.split(' ').map(String::toLong) EntryMap.RangeMap( source = sourceStart..<sourceStart + size, destination = destinationStart..<destinationStart + size, ) } .sortedBy { it.source.first } .let(::EntryMap) } val parts = input.split("\n\n") val seeds = parts .first() .removePrefix("seeds: ") .split(' ') .also { check(it.size % 2 == 0) { "Seed numbers did not come in pairs!" } } .map(String::toLong) val stages = parts .drop(1) .mapIndexed(::parseEntryMap) .also { check(it.size == mappingSteps.size - 1) { "Some mapping stages missing." } } Almanac(seeds, stages) } override fun partOne(input: String) = parseInput(input).run { seeds.minOf(this::process) } override fun partTwo(input: String) = parseInput(input).run { process(seedsAsRanges()).minOf(LongRange::first) } }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
6,713
advent-of-code-kotlin-solutions
The Unlicense
src/Day20.kt
shepard8
573,449,602
false
{"Kotlin": 73637}
fun main() { data class Number(val value: Long, val originalIndex: Int) fun mix(numbers: MutableList<Number>) { val n = numbers.size for (i in 0 until n) { val nextIndexToMove = numbers.indexOfFirst { it.originalIndex == i } val number = numbers.removeAt(nextIndexToMove) val newPosition = (((nextIndexToMove + number.value) % (n - 1)) + (n - 1)) % (n - 1) numbers.add(newPosition.toInt(), number) } } fun sumCoordinates(numbers: List<Number>): Long { val n = numbers.count() val startIndex = numbers.indexOfFirst { it.value == 0L } val after1000 = numbers[(startIndex + 1000) % n].value val after2000 = numbers[(startIndex + 2000) % n].value val after3000 = numbers[(startIndex + 3000) % n].value return after1000 + after2000 + after3000 } fun part1(numbers: List<Int>): Long { val newList = numbers.mapIndexed { index, value -> Number(value.toLong(), index) }.toMutableList() mix(newList) return sumCoordinates(newList) } fun part2(numbers: List<Int>): Long { val newList = numbers.mapIndexed { index, value -> Number(value.toLong() * 811589153L, index) }.toMutableList() repeat(10) { mix(newList) } return sumCoordinates(newList) } val numbers = readInput("Day20").map { line -> line.toInt() } // println(part1(listOf(1, 2, -3, 3, -2, 0, 4))) println(part1(numbers)) println(part2(numbers)) }
0
Kotlin
0
1
81382d722718efcffdda9b76df1a4ea4e1491b3c
1,520
aoc2022-kotlin
Apache License 2.0
kotlin/1631-path-with-minimum-effort.kt
neetcode-gh
331,360,188
false
{"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750}
//dijkstra class Solution { fun minimumEffortPath(h: Array<IntArray>): Int { val minHeap = PriorityQueue<IntArray> { a, b -> a[2] - b[2] } val dirs = intArrayOf(0, 1, 0, -1, 0) val n = h.size val m = h[0].size val visited = Array (n) { BooleanArray (m) } fun isValid(x: Int, y: Int) = x in (0 until n) && y in (0 until m) minHeap.add(intArrayOf(0, 0, 0)) while (minHeap.isNotEmpty()) { val (i, j, e) = minHeap.poll() if (i == n - 1 && j == m - 1) return e visited[i][j] = true for (k in 0..3) { val i2 = i + dirs[k] val j2 = j + dirs[k + 1] if (isValid(i2, j2) && !visited[i2][j2]) { val e2 = Math.abs(h[i][j] - h[i2][j2]) minHeap.add(intArrayOf(i2, j2, maxOf(e, e2))) } } } return 0 } } // binary search + dfs to find min effort to reach end from start class Solution { fun minimumEffortPath(h: Array<IntArray>): Int { val dirs = intArrayOf(0, 1, 0, -1, 0) val n = h.size val m = h[0].size var visited = Array (n) { BooleanArray (m) } fun isValid(x: Int, y: Int) = x in (0 until n) && y in (0 until m) fun dfs(x: Int, y: Int, k: Int): Boolean { if (x == n - 1 && y == m - 1) return true visited[x][y] = true for (i in 0..3) { val x2 = x + dirs[i] val y2 = y + dirs[i + 1] if (isValid(x2, y2) && !visited[x2][y2] && Math.abs(h[x][y] - h[x2][y2]) <= k) { if (dfs(x2, y2, k)) return true } } return false } var left = 0 var right = 1000000 var res = right while (left <= right) { val mid = (right + left) / 2 visited = Array (n) { BooleanArray (m) } if (dfs(0, 0, mid)) { res = mid right = mid - 1 } else { left = mid + 1 } } return res } } //MST with kruskals algorith (using DSU) class Solution { fun minimumEffortPath(h: Array<IntArray>): Int { val n = h.size val m = h[0].size val dsu = DSU(n * m) val edges = mutableListOf<IntArray>() fun c(x: Int, y: Int) = x * m + y for (i in 0 until n) { for (j in 0 until m) { if (i + 1 < n) { val e = Math.abs(h[i][j] - h[i + 1][j]) edges.add(intArrayOf(c(i, j), c(i + 1, j), e)) } if (j + 1 < m) { val e = Math.abs(h[i][j] - h[i][j + 1]) edges.add(intArrayOf(c(i, j), c(i, j + 1), e)) } } } edges.sortWith { a, b -> a[2] - b[2] } for ((u, v, e) in edges) { if (dsu.union(u, v)) { if (dsu.find(c(0, 0)) == dsu.find(c(n - 1, m - 1))) { return e } } } return 0 } } class DSU(val n: Int) { val parent = IntArray (n) { it } val size = IntArray (n) { 1 } fun find(x: Int): Int { if (parent[x] != x) parent[x] = find(parent[x]) return parent[x] } fun union(x: Int, y: Int): Boolean { val p1 = find(x) val p2 = find(y) if (p1 == p2) return false if (size[p1] > size[p2]) { parent[p2] = p1 size[p1] += size[p2] } else { parent[p1] = p2 size[p2] += size[p1] } return true } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
3,782
leetcode
MIT License
src/day4/Day4.kt
jorgensta
573,824,365
false
{"Kotlin": 31676}
package day4 import readInput fun main() { val day = "day4" val filename = "Day04" class Section(val intRange: IntRange) { fun containedBy(other: Section): Boolean { return intRange.intersect(other.intRange).size == intRange.toList().size } fun overlappedBy(other: Section): Boolean { return intRange.intersect(other.intRange).isNotEmpty() } } fun part1(input: List<String>): Int { return input.count { val pair = it.split(",") val sectionPair = pair.map { val range = it.split("-").first().toInt()..it.split("-").last().toInt() Section(range) } val first = sectionPair.first() val second = sectionPair.last() first.containedBy(second) || second.containedBy(first) } } fun part2(input: List<String>): Int { return input.count { val pair = it.split(",") val sectionPair = pair.map { val range = it.split("-").first().toInt()..it.split("-").last().toInt() Section(range) } val first = sectionPair.first() val second = sectionPair.last() first.overlappedBy(second) || second.overlappedBy(first) } } // test if implementation meets criteria from the description, like: val testInput = readInput("/$day/${filename}_test") val input = readInput("/$day/$filename") val partOneTest = part1(testInput) check(partOneTest == 2) println("Part one: ${part1(input)}") val partTwoTest = part2(testInput) check(partTwoTest == 4) println("Part two: ${part2(input)}") }
0
Kotlin
0
0
7243e32351a926c3a269f1e37c1689dfaf9484de
1,728
AoC2022
Apache License 2.0
2018/kotlin/day20p1/src/main.kt
sgravrock
47,810,570
false
{"Rust": 1263100, "Swift": 1167766, "Ruby": 641843, "C++": 529504, "Kotlin": 466600, "Haskell": 339813, "Racket": 264679, "HTML": 200276, "OpenEdge ABL": 165979, "C": 89974, "Objective-C": 50086, "JavaScript": 40960, "Shell": 33315, "Python": 29781, "Elm": 22980, "Perl": 10662, "BASIC": 9264, "Io": 8122, "Awk": 5701, "Raku": 5532, "Rez": 4380, "Makefile": 1241, "Objective-C++": 1229, "Tcl": 488}
import java.util.* import kotlin.math.min fun main(args: Array<String>) { val start = Date() println(answerForPuzzleInput()) println("in ${Date().time - start.time}ms") } fun answerForPuzzleInput(): Int { val classLoader = RoomExParser::class.java.classLoader val input = classLoader.getResource("input.txt").readText() return shortestPathToFarthestRoom(input) } data class Coord(val x: Int, val y: Int) { fun neighbor(dir: Dir): Coord { return when (dir) { Dir.N -> Coord(x, y - 1) Dir.S -> Coord(x, y + 1) Dir.W -> Coord(x - 1, y) Dir.E -> Coord(x + 1, y) } } } enum class Dir { N, E, W, S; companion object { fun fromChar(c: Char): Dir { return when(c) { 'N' -> Dir.N 'E' -> Dir.E 'S' -> Dir.S 'W' -> Dir.W else -> throw Exception("Invalid direction char: $c") } } } } fun shortestPathToFarthestRoom(input: String): Int { val world = RoomExParser.parse(input) val distancesToRooms = mutableMapOf<Coord, Int>() world.paths { dest, len -> distancesToRooms[dest] = min( len, distancesToRooms.getOrDefault(dest, Int.MAX_VALUE) ) } return distancesToRooms.values.max()!! } enum class Tile { Room, Wall, Hdoor, Vdoor } class World(private val grid: Map<Coord, Tile>) { fun paths(emit: (Coord, Int) -> Unit) { dfs(mutableListOf(Coord(0, 0)), emit) } private fun dfs(rooms: MutableList<Coord>, emit: (Coord, Int) -> Unit) { for (d in Dir.values()) { val doorCoord = rooms.last().neighbor(d) when (grid.getOrDefault(doorCoord, Tile.Wall)) { Tile.Hdoor, Tile.Vdoor -> { val nextRoomCoord = doorCoord.neighbor(d) if (!rooms.contains(nextRoomCoord)) { rooms.add(nextRoomCoord) emit(rooms.last(), rooms.size - 1) dfs(rooms, emit) rooms.removeAt(rooms.size - 1) } } Tile.Wall -> {} Tile.Room -> throw Exception("Can't happen: two adjacent rooms") } } } override fun toString(): String { val minX = grid.keys.asSequence().map { it.x }.min()!! - 1 val maxX = grid.keys.asSequence().map { it.x }.max()!! + 1 val minY = grid.keys.asSequence().map { it.y }.min()!! - 1 val maxY = grid.keys.asSequence().map { it.y }.max()!! + 1 return (minY..maxY).map { y -> (minX..maxX).map { x -> when (grid.getOrDefault(Coord(x, y), Tile.Wall)) { Tile.Room -> if (y == 0 && x == 0) 'X' else '.' Tile.Wall -> '#' Tile.Vdoor -> '|' Tile.Hdoor -> '-' } }.joinToString("") }.joinToString("\n") } } class RoomExParser(private val input: String) { companion object { fun parse(input: String): World { val parser = RoomExParser(input) parser.require('^') parser.parse(setOf(Coord(0, 0))) parser.require('$') return World(parser.tiles) } } private var i = 0 private val tiles = mutableMapOf(Coord(0, 0) to Tile.Room) private fun parse(starts: Set<Coord>): Set<Coord> { var positions = starts val previousOptions = mutableSetOf<Coord>() loop@ while (input[i] != '$') { val c = input[i++] when (c) { 'N', 'S', 'E', 'W' -> { val dir = Dir.fromChar(c) val doorType = when (dir) { Dir.N, Dir.S -> Tile.Hdoor Dir.E, Dir.W -> Tile.Vdoor } positions = positions.map { pos -> val doorCoord = pos.neighbor(dir) tiles[doorCoord] = doorType val roomCoord = doorCoord.neighbor(dir) tiles[roomCoord] = Tile.Room roomCoord }.toSet() } '(' -> { positions = parse(positions) } '|' -> { previousOptions.addAll(positions) positions = starts } ')' -> { previousOptions.addAll(positions) positions = previousOptions break@loop } else -> throw Error("Unexpected '$c'") } } return positions } private fun require(expected: Char) { val actual = input[i++] if (actual != expected) { throw Error("Expected $expected but got $actual") } } }
0
Rust
0
0
ea44adeb128cf1e3b29a2f0c8a12f37bb6d19bf3
5,044
adventofcode
MIT License
src/main/kotlin/adventofcode2017/Day07RecursiveCircus.kt
n81ur3
484,801,748
false
{"Kotlin": 476844, "Java": 275}
package adventofcode2017 class Day07RecursiveCircus data class RCProgram(val name: String, val weight: Int, val dependants: List<String>) data class WeightedChild( val name: String, val parent: String, val weight: Int, val dependants: List<String>, val dependantsWeight: Int ) class RCTower(val programms: List<RCProgram>) { val childWeights = mutableListOf<WeightedChild>() var childsInequality = 0 companion object { fun fromLines(input: List<String>): RCTower { return RCTower(input.map { parseInputLine(it) }) } private fun parseInputLine(line: String): RCProgram { // sample: fbmhsy (58) -> lqggzbu, xwete, vdarulb, rkobinu, ztoyd, vozjzra val name = line.substringBefore(" ") val weight = line.substringAfter("(").substringBefore(")").toInt() val dependants = when { line.contains("->") -> line.substringAfter("-> ").split(", ") else -> emptyList() } return RCProgram(name, weight, dependants) } } fun getDependantsCount(programname: String): Int { val program = programms.find { it.name == programname } program?.let { if (program.dependants.isEmpty()) { return 1 } else { return program.dependants.sumOf { getDependantsCount(it) } } } return 0 } fun getDependantsWeightSum(programname: String) = getDependantsWeights(programname).sum() fun getDependantsWeights(programname: String): List<Int> { val program = programms.find { it.name == programname } program?.dependants?.let { if (program.dependants.isEmpty()) { return listOf(program.weight) } else { val childrenWeights = program.dependants.flatMap { getDependantsWeights(it) } return listOf(program.weight) + childrenWeights } } return listOf() } fun checkChildsForEqualWeight(programname: String): Int { buildWeightedChildList() val program = programms.find { it.name == programname } program?.dependants?.let { if (program.dependants.isNotEmpty()) { program.dependants.forEach { checkChildsForEquality(it) } } return childsInequality } return childsInequality } fun checkChildsForEquality(programname: String): Int { val program = programms.find { it.name == programname } program?.dependants?.let { if (program.dependants.isNotEmpty()) { val children = program.dependants.map { childWeights.find { child -> child.name == it } } .sortedBy { it?.dependantsWeight } val distinct = children.last() val others = children.first() distinct?.let { others?.let { val difference = Math.abs(distinct.dependantsWeight - others.dependantsWeight) if (difference != 0) { childsInequality = distinct.weight - difference } } } } program.dependants.forEach { checkChildsForEquality(it) } } return childsInequality } fun findRoot(): String = programms.maxByOrNull { program -> getDependantsCount(program.name) }?.name ?: "" private fun buildWeightedChildList() { val root = findRoot() addToWeightedChildList(root) } private fun addToWeightedChildList(programname: String) { val program = programms.find { it.name == programname } program?.dependants?.let { if (program.dependants.isEmpty()) return for (childname in program.dependants) { val child = programms.find { it.name == childname } childWeights.add( WeightedChild( child!!.name, programname, child.weight, child.dependants, getDependantsWeightSum(child.name) ) ) addToWeightedChildList(childname) } } } }
0
Kotlin
0
0
fdc59410c717ac4876d53d8688d03b9b044c1b7e
4,409
kotlin-coding-challenges
MIT License
p02/src/main/kotlin/InventoryManagementSystem.kt
jcavanagh
159,918,838
false
null
package p02 import common.file.readLines fun hamming(str1: String, str2: String): Int { if(str1 !== str2) { // Hamming distance val zipped = str1.asIterable().zip(str2.asIterable()) return zipped.sumBy { if (it.first == it.second) 0 else 1 } } return -1 } /** * Returns id1, id2, and the common characters as a List */ fun similarId(ids: List<String>): List<String> { fun find(): List<String> { ids.forEach { id1 -> ids.forEach { id2 -> if (hamming(id1, id2) == 1) { return listOf(id1, id2) } } } return listOf("", "") } val (first, second) = find() var common = first.asIterable().filterIndexed { idx, chr -> second[idx] == chr }.joinToString("") return listOf(first, second, common) } fun checksum(ids: List<String>): Int { var twos = 0 var threes = 0 ids.forEach { val counts = it.groupingBy { it }.eachCount() val values = counts.values if(values.contains(2)) { twos++ } if(values.contains(3)) { threes++ } } return twos * threes } fun main(args: Array<String>) { val lines = readLines("input.txt") val checksum = checksum(lines) val (id1, id2, common) = similarId(lines) println("Checksum: $checksum") println("Similar ID: $id1 (${id1.length}), $id2 (${id2.length}) -> $common (${common.length})") }
0
Kotlin
0
0
289511d067492de1ad0ceb7aa91d0ef7b07163c0
1,360
advent2018
MIT License
src/Day06.kt
seana-zr
725,858,211
false
{"Kotlin": 28265}
import java.util.regex.Pattern fun main() { fun part1(input: List<String>): Int { val result: Int val waysPerRace = mutableListOf<Int>() val timesToBeat = input[0] .dropWhile { !it.isDigit() } .split(Pattern.compile("\\s+")) .map { it.toInt() } val distances = input[1] .dropWhile { !it.isDigit() } .split(Pattern.compile("\\s+")) .map { it.toInt() } val races = timesToBeat.zip(distances) println("races: $races") for ((timeToBeat, raceDistance) in races) { var ways = 0 println("timeToBeat: $timeToBeat | raceDistance: $raceDistance") for (chargeTime in 0..<timeToBeat) { val timeLeftAfterCharge = timeToBeat - chargeTime val distanceTraveled = timeLeftAfterCharge * chargeTime if (distanceTraveled > raceDistance) { print("$chargeTime | ") ways++ } } waysPerRace.add(ways) println("ways: $ways") } result = waysPerRace.reduce(Int::times) println("RESULT: $result") return result } fun part2(input: List<String>): Long { var result = 0.toLong() val timeToBeat = input[0] .filter { it.isDigit() } .toLong() val raceDistance = input[1] .filter { it.isDigit() } .toLong() for (chargeTime in 1..<timeToBeat) { val timeLeftAfterCharge = timeToBeat - chargeTime val distanceTraveled = timeLeftAfterCharge * chargeTime if (distanceTraveled > raceDistance) { result++ } } println("RESULT: $result") return result } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") check(part2(testInput) == 71503.toLong()) val input = readInput("Day06") // part1(input).println() part2(input).println() }
0
Kotlin
0
0
da17a5de6e782e06accd3a3cbeeeeb4f1844e427
2,090
advent-of-code-kotlin-template
Apache License 2.0
src/main/aoc2023/Day12.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2023 class Day12(input: List<String>) { private data class Row(val springs: String, val groups: List<Int>) private val springs = input.map { line -> Row(line.substringBefore(" "), line.substringAfter(" ").split(",").map { it.toInt() }) } /** * The current state of the processing. * @param groupOffset How far into the group that's currently being processed we've come * @param processedGroups How many complete groups have been processed * @param permutations The number of different permutations have come to this state */ private data class State(val groupOffset: Int, val processedGroups: Int, val permutations: Long) /** * Calculate all permutations by processing one character at a time and store all valid combinations so far * in a list. Then process the next character for all entries in the list. Only valid states are saved, * invalid are discarded as soon as they are found. * Actions to take on each symbol that results in valid states * - '.': Either continue when there is no group or finish a group of correct length * - '#': Start processing a new group, or continue processing a group that is not finished yet * - '?': Do the same as for both . and #. May lead to splitting one state into two for the next round. * * After every time a character has been processed for all states, we combine the states that has the same * amount of processed groups and the same group offset. Reduces the amount of states needed to be processed * greatly. */ private fun calculatePermutations(row: Row): Long { val current = mutableListOf(State(0, 0, 1L)) // Add a trailing . to the row of springs to finish any groups that might end at the end of the row. row.springs.let { "$it." }.forEach { ch -> val next = mutableListOf<State>() current.forEach { current -> val nextGroupSize = row.groups.drop(current.processedGroups).firstOrNull() ?: 0 when { ch == '.' && current.groupOffset == 0 -> next.add(current) ch == '.' && current.groupOffset == nextGroupSize -> { // Group finished next.add(State(0, current.processedGroups + 1, current.permutations)) } ch == '#' && current.groupOffset < nextGroupSize -> { // Extend a group next.add(State(current.groupOffset + 1, current.processedGroups, current.permutations)) } ch == '?' -> { // Add the case for . when (current.groupOffset) { 0 -> next.add(current) nextGroupSize -> { next.add(State(0, current.processedGroups + 1, current.permutations)) } } // And add the case for # if (current.groupOffset < nextGroupSize) { next.add(State(current.groupOffset + 1, current.processedGroups, current.permutations)) } } } } current.clear() // combine all common states (shared group offset and processed groups) to reduce the // number of states to handle when processing the next character next.groupBy { it.groupOffset to it.processedGroups } .forEach { (key, value) -> current.add(State(key.first, key.second, value.sumOf { it.permutations })) } } return current.filter { it.processedGroups == row.groups.size }.sumOf { it.permutations } } private val springs2 = input.map { line -> val springs = line.substringBefore(" ") val unfoldedSprings = List(5) { springs }.joinToString("?") val unfoldedGroups = List(5) { line.substringAfter(" ") }.joinToString(",") Row(unfoldedSprings, unfoldedGroups.split(",").map { it.toInt() }) } fun solvePart1(): Long { return springs.sumOf { calculatePermutations(it) } } fun solvePart2(): Long { return springs2.sumOf { calculatePermutations(it) } } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
4,356
aoc
MIT License
src/main/day17/Part1.kt
ollehagner
572,141,655
false
{"Kotlin": 80353}
package day17 import LoopingIterator import common.Direction import common.Direction.* import common.Grid import common.Point import readInput fun main() { val result = solve(2022, "day17/testinput.txt") println("Day 17 part 1. Highest point: ${result}") } fun solve(iterations: Int, jetsFile: String): Int { val rocks = Rock.rockSequence() val jets = Jet.parse(jetsFile) var grid = Grid(Floor.start().points, "-") rocks .take(iterations) .forEach { rock -> val state = dropRock(startPositionRelativeToFloor(rock, grid.max().y), grid, jets) state.rock.parts.forEach { grid.set(it, "#") } } return grid.max().y } fun dropRock(rock: Rock, grid: Grid<String>, directions: LoopingIterator<Jet>): State { var movingRock = rock while(true) { val nextJet = directions.next() movingRock = movingRock.move(nextJet.direction, grid) if(movingRock.move(DOWN, grid).parts.any { grid.hasValue(it) }) { return State(nextJet, movingRock, Floor(grid)) } movingRock = movingRock.move(DOWN, grid) } } fun startPositionRelativeToFloor(rock: Rock, maxY: Int): Rock { return Rock(rock.id, rock.parts.map { (x, y) -> Point(x + 2, y + maxY + 4) }) } data class State(val jet: Jet, val rock: Rock, val floor: Floor) data class Jet(val id: Int, val direction: Direction) { companion object { fun parse(jetsFile: String): LoopingIterator<Jet> { return LoopingIterator(readInput(jetsFile).first().mapIndexed { index, value -> if(value == '<') Jet(index, LEFT) else Jet(index, RIGHT)}) } } }
0
Kotlin
0
0
6e12af1ff2609f6ef5b1bfb2a970d0e1aec578a1
1,651
aoc2022
Apache License 2.0
src/main/kotlin/biz/koziolek/adventofcode/year2022/day15/day15.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2022.day15 import biz.koziolek.adventofcode.Coord import biz.koziolek.adventofcode.findInput fun main() { val inputFile = findInput(object {}) val sensors = parseSensors(inputFile.bufferedReader().readLines()) println("Positions with y=2000000 without beacons: ${countPositionsWithoutBeacons(sensors, y = 2000000)}") val distressBeacon = findDistressBeacon(sensors, maxX = 4000000, maxY = 4000000) val tuningFrequency = getTuningFrequency(distressBeacon) println("Distress beacon is located at $distressBeacon with tuning frequency: $tuningFrequency") } data class Sensor( val location: Coord, val beacon: Beacon, ) { val distanceToBeacon = location.manhattanDistanceTo(beacon.location) } data class Beacon( val location: Coord, ) fun parseSensors(lines: Iterable<String>): List<Sensor> = lines.map { line -> Regex("Sensor at x=([0-9-]+), y=([0-9-]+): closest beacon is at x=([0-9-]+), y=([0-9-]+)") .find(line) .takeIf { it != null } .let { it as MatchResult } .let { result -> Sensor( location = Coord( x = result.groups[1]!!.value.toInt(), y = result.groups[2]!!.value.toInt(), ), beacon = Beacon( location = Coord( x = result.groups[3]!!.value.toInt(), y = result.groups[4]!!.value.toInt(), ), ), ) } } fun countPositionsWithoutBeacons(sensors: List<Sensor>, y: Int): Int { val allCoords = sensors.flatMap { listOf(it.location, it.beacon.location) } val minX = allCoords.minOf { it.x } val maxX = allCoords.maxOf { it.x } val maxBeaconDistance = sensors.maxOf { it.distanceToBeacon } return ((minX - maxBeaconDistance)..(maxX + maxBeaconDistance)) .count { x -> val coord = Coord(x, y) sensors.all { sensor -> coord != sensor.beacon.location } && !canBeBeacon(coord, sensors) } } fun findDistressBeacon(sensors: List<Sensor>, minX: Int = 0, maxX: Int = Int.MAX_VALUE, minY: Int = 0, maxY: Int = Int.MAX_VALUE): Coord = sensors.asSequence() .flatMap { getPointsAtDistance(it.location, it.distanceToBeacon + 1) } .filter { it.x in minX..maxX && it.y in minY..maxY } .distinct() .single { canBeBeacon(it, sensors) } fun canBeBeacon(coord: Coord, sensors: List<Sensor>): Boolean = sensors.all { sensor -> coord.manhattanDistanceTo(sensor.location) > sensor.distanceToBeacon } class CoordIterator( xRange: Iterable<Int>, yRange: Iterable<Int> ) : Iterator<Coord> { private val xIter1 = xRange.iterator() private val yIter1 = yRange.iterator() override fun hasNext() = xIter1.hasNext() && yIter1.hasNext() override fun next() = Coord(xIter1.next(), yIter1.next()) } fun getPointsAtDistance(from: Coord, distance: Int): Sequence<Coord> = sequence { yieldAll( CoordIterator( xRange = from.x..from.x + distance, yRange = from.y + distance downTo from.y, ) ) yieldAll( CoordIterator( xRange = from.x + distance downTo from.x, yRange = from.y downTo from.y - distance, ) ) yieldAll( CoordIterator( xRange = from.x downTo from.x - distance, yRange = from.y - distance..from.y, ) ) yieldAll( CoordIterator( xRange = from.x - distance..from.x, yRange = from.y..from.y + distance, ) ) } fun getTuningFrequency(coord: Coord): Long = coord.x * 4000000L + coord.y
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
3,978
advent-of-code
MIT License
solutions/src/MaximumSubArraySum.kt
JustAnotherSoftwareDeveloper
139,743,481
false
{"Kotlin": 305071, "Java": 14982}
import kotlin.test.currentStackTrace /** * https://leetcode.com/problems/k-concatenation-maximum-sum/ */ class MaximumSubArraySum { fun kConcatenationMaxSum(arr: IntArray, k: Int): Int { val MOD = 1000000007 if (arr.none { it < 0 }) { return ((arr.sum()*k.toLong()) % MOD).toInt() } if (arr.none{ it > 0}) { return 0 } val sumsFromAsc = LongArray(arr.size) sumsFromAsc[0] = arr[0].toLong() for (i in 1 until arr.size) { sumsFromAsc[i] = arr[i]+sumsFromAsc[i-1] } val sumsFromDesc = LongArray(arr.size) sumsFromDesc[arr.lastIndex] = arr[arr.lastIndex].toLong() for( i in arr.lastIndex-1 downTo 0) { sumsFromDesc[i] = arr[i]+sumsFromDesc[i+1] } var ascMaxSum = Pair(0L,-1) var descMaxSum = Pair(0L,-1); for (i in arr.indices) { if (ascMaxSum.first <= sumsFromAsc[i]) { ascMaxSum = Pair(sumsFromAsc[i],i) } if (descMaxSum.first <= sumsFromDesc[i]) { descMaxSum = Pair(sumsFromDesc[i],i) } } val maxSubArray = maxSum(arr) val arraySum = arr.map { it.toLong() }.sum() when { k == 1 -> { return (maxSubArray % MOD).toInt() } arraySum > 0 -> { var sum = (arraySum*(k-2)); if (descMaxSum.second >= 0) { sum+= descMaxSum.first } if (ascMaxSum.second >= 0) { sum+= ascMaxSum.first } return (sum % MOD).toInt() } else -> { return (maxOf(maxSubArray,ascMaxSum.first+descMaxSum.first) % MOD).toInt() } } } private fun maxSum(A: IntArray) : Long { var curMax = 0L var maxEncountered = 0L A.forEach { if (curMax < 0) { curMax = it.toLong() } else { curMax+=it } maxEncountered = maxOf(maxEncountered,curMax) } return maxEncountered } }
0
Kotlin
0
0
fa4a9089be4af420a4ad51938a276657b2e4301f
2,209
leetcode-solutions
MIT License
src/Day03.kt
maxonof
572,454,805
false
{"Kotlin": 5967}
fun main() { val input = readInput("input03") val uppercase = 'A' until '[' val lowercase = 'a' until '{' val values = (lowercase + uppercase).zip(1 until 53).toMap() println(part1(input, values)) println(part2(input, values)) } fun findCommon(line: String): Char { val mid = line.length / 2 val intersection = (0 until mid).map { line[it] }.toSet() intersect (mid until line.length).map { line[it] }.toSet() return intersection.last() } fun part1(input: List<String>, values: Map<Char, Int>): Int { return input.sumOf { l -> values.getOrDefault(findCommon(l), 0) } } fun part2(input: List<String>, values: Map<Char, Int>): Int { return input.chunked(3).sumOf { c -> values.getOrDefault( c.map { it.toSet() }.reduce { a, b -> a intersect b }.last(), 0 ) } }
0
Kotlin
0
0
ef03fc65dcd429d919eb12d054ce7c052780d7d7
851
aoc-2022-in-kotlin
Apache License 2.0
solutions/aockt/y2023/Y2023D03.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.y2023 import aockt.util.spacial.Point import aockt.util.spacial.Area import aockt.util.spacial.coerceIn import aockt.util.parse import io.github.jadarma.aockt.core.Solution object Y2023D03 : Solution { /** A part number label in the engine schematics, drawn at [coords] with a numeric [value]. */ private data class PartNumber(val coords: Area, val value: Int) /** A symbol in the engine schematics, drawn at [coords] with the symbol [value]. */ private data class Symbol(val coords: Point, val value: Char) /** Parse the [input] and build a representation of the engine schematics, mapping each symbol to adjacent parts. */ private fun parseInput(input: String): Map<Symbol, List<PartNumber>> = parse { val lines: Array<String> = input.lines().toTypedArray().also { require(it.isNotEmpty()) require(it.all { line -> line.length == it.first().length }) } val bounds = Area(0..<lines.first().length, lines.indices) fun adjacentSymbolOrNull(part: PartNumber): Symbol? { val searchSpace = with(part.coords) { Area( xRange = xRange.run { first - 1..last + 1 }, yRange = yRange.run { first - 1..last + 1 }, ) }.coerceIn(bounds) for (point in searchSpace) { val value = lines[point.y.toInt()][point.x.toInt()] if (value != '.' && value.isLetterOrDigit().not()) { return Symbol(point, value) } } return null } buildMap<Symbol, MutableList<PartNumber>> { val numberRegex = Regex("""[1-9]\d*""") lines.forEachIndexed { y, row -> numberRegex.replace(row) { label -> val part = PartNumber(Area(label.range, y..y), label.value.toInt()) adjacentSymbolOrNull(part)?.let { symbol -> getOrPut(symbol) { mutableListOf() }.add(part) } "" } } } } override fun partOne(input: String) = parseInput(input) .values .sumOf { parts -> parts.sumOf { it.value } } override fun partTwo(input: String) = parseInput(input) .filterKeys { it.value == '*' } .filterValues { it.size == 2 } .values .sumOf { (l, r) -> l.value * r.value } }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
2,462
advent-of-code-kotlin-solutions
The Unlicense
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2015/2015-19.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2015 import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputText import kotlin.math.min fun main() { val input = readInputText(2015, "19-input") val test1 = readInputText(2015, "19-test1") val test2 = readInputText(2015, "19-test2") println("Part1:") part1(test1).println() part1(input).println() println() println("Part2:") part2(test2).println() part2(input).println() } private fun part1(input: String): Int { val (rules, initial) = parse(input) val replacements = initial.doReplacements(rules).toSet() return replacements.size } private fun part2(input: String): Int { val (rules, target) = parse(input) val cnfRules = rules.toCnf() val cache = mutableMapOf<CacheKey, Int>() for (s in target.indices) { cache[CacheKey(1, s, target[s])] = 0 } for (l in 2 .. target.size) { // length of span for (s in 0 .. target.size - l) { // start of span for (p in 1 until l) { // partition of span cnfRules.forEach { rule -> val left = CacheKey(p, s, rule.right[0]) val right = CacheKey(l - p, s + p, rule.right[1]) if (left in cache && right in cache) { val newKey = CacheKey(l, s, rule.left) val existing = cache.getOrDefault(newKey, Int.MAX_VALUE) val newSteps = cache[left]!! + cache[right]!! + rule.steps cache[newKey] = min(existing, newSteps) } } } } } val result = cache[CacheKey(target.size, 0, "e")] require(result != null) return result } private data class CacheKey(val length: Int, val start: Int, val nonTerminal: String) private fun Map<String, List<Molecule>>.toCnf(): MutableList<CnfRule> { var nextChar = 'A' val artificial = mutableListOf<CnfRule>() forEach { (key, list) -> list.forEach { if (it.size <= 2) { artificial += CnfRule(key, it, 1) } else { val char = nextChar++ artificial += CnfRule(key, listOf(it.first(), char + "1"), 1) for (i in 1 until it.size - 2) { artificial += CnfRule(char + i.toString(), listOf(it[i], char + (i + 1).toString()), 0) } artificial += CnfRule(char + (it.size - 2).toString(), listOf(it[it.lastIndex - 1], it.last()), 0) } } } while (true) { val unit = artificial.firstOrNull { it.right.size == 1 } ?: break artificial.remove(unit) val sub = artificial.filter { it.left == unit.right.single() } sub.forEach { artificial += CnfRule(unit.left, it.right, it.steps + 1) } } return artificial } private data class CnfRule(val left: String, val right: List<String>, val steps: Int) private fun Molecule.doReplacements(rules: Map<String, List<Molecule>>): List<Molecule> { return flatMapIndexed { index, element -> rules.getOrDefault(element, emptyList()).map { subList(0, index) + it + subList(index + 1, size) } } } private typealias Molecule = List<String> private fun parse(input: String): Pair<Map<String, List<Molecule>>, Molecule> { val regex = """(?=[A-Z][a-z]?)(?<=[A-Za-z])""".toRegex() val (rules, target) = input.split("\n\n") val map: Map<String, List<Molecule>> = rules.lines() .map { val (source, product) = it.split(" => ") source to product.split(regex) }.groupBy { it.first } .mapValues { it.value.map { it.second } } val targetList = target.split(regex) return map to targetList }
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
3,849
advent-of-code
MIT License
src/year2020/day03/Day03.kt
fadi426
433,496,346
false
{"Kotlin": 44622}
package year2020.day03 import java.awt.Dimension import java.awt.Point import java.math.BigDecimal import util.assertTrue import util.read2020DayInput fun main() { val input = read2020DayInput("Day03") assertTrue(task01(input) == 242) assertTrue(task02(input) == BigDecimal.valueOf(2265549792)) } private fun task02(input: List<String>): BigDecimal { val journeys = listOf( createJourney(input, Dimension(1,1)), createJourney(input, Dimension(3,1)), createJourney(input, Dimension(5,1)), createJourney(input, Dimension(7,1)), createJourney(input, Dimension(1,2)) ) journeys.forEach { it.start() } return journeys.map { it.treeCount.toBigDecimal() } .reduce { acc, count -> acc * count} } private fun task01(input: List<String>): Int { val journey = createJourney(input, Dimension(3,1)) journey.start() return journey.treeCount } private fun createJourney(input: List<String>, slopeDimension: Dimension): Journey { val journey = Journey( Dimension(input[0].length, input.size), slopeDimension ) input.forEachIndexed { y, column -> column.forEachIndexed { x, geology -> if (geology == '#') journey.plantTree(x, y) } } return journey } private data class Journey(val startingAreaDimension: Dimension, val slopeDimension: Dimension) { val area = MutableList(startingAreaDimension.height) { MutableList(startingAreaDimension.width) { "." } } val startingArea = MutableList(startingAreaDimension.height) { MutableList(startingAreaDimension.width) { "." } } val position = Point(0, 0) var treeCount = 0 private fun treeFound() = area[position.y][position.x] == "#" private fun increaseAreaWidth() { area.forEachIndexed { i, r -> r.addAll(startingArea[i]) } } private fun goalReached() = position.y >= startingAreaDimension.height fun plantTree(x: Int, y: Int) { area[y][x] = "#" startingArea[y][x] = "#" } fun move(xMove: Int, yMove: Int) { val newX = position.x + xMove if (newX >= area[0].size) { increaseAreaWidth() } position.x += xMove position.y += yMove } fun start() { while (!goalReached()) { if (treeFound()) { treeCount += 1 } move(slopeDimension.width, slopeDimension.height) } } }
0
Kotlin
0
0
acf8b6db03edd5ff72ee8cbde0372113824833b6
2,473
advent-of-code-kotlin-template
Apache License 2.0
src/day12/Day12.kt
idle-code
572,642,410
false
{"Kotlin": 79612}
package day12 import Position import log import logEnabled import logln import readInput private const val DAY_NUMBER = 12 typealias Height = Char private const val NOT_VISITED = -1 fun main() { fun parseMap(rawInput: List<String>): Triple<Array<Array<Height>>, Position, Position> { val heightMap = Array(rawInput.size) { Array(rawInput[0].length) { 'a' } } var start = Position(0, 0) var end = Position(0, 0) for (y in 0..rawInput.lastIndex) { heightMap[y] = rawInput[y].toCharArray().toTypedArray() for (x in 0..heightMap[y].lastIndex) { if (heightMap[y][x] == 'S') { start = Position(x, y) heightMap[y][x] = 'a' } else if (heightMap[y][x] == 'E') { end = Position(x, y) heightMap[y][x] = 'z' } } } return Triple(heightMap, start, end) } fun allNeighboursOf(stepsMap: Array<Array<Int>>, pos: Position): List<Position> { val positions = listOf( Position(pos.x - 1, pos.y), Position(pos.x + 1, pos.y), Position(pos.x, pos.y - 1), Position(pos.x, pos.y + 1), ) val width = stepsMap[0].size val height = stepsMap.size return positions.filter { pos -> pos.x >= 0 && pos.y >= 0 && pos.x < width && pos.y < height } } fun printStepMap(stepsMap: Array<Array<Int>>) { val width = stepsMap[0].size val height = stepsMap.size for (y in 0 until height) { for (x in 0 until width) { if (stepsMap[y][x] < 0) log(".") else log("${stepsMap[y][x] % 10}") } logln("") } logln("--------------------------------------------------") } fun findWay( heightMap: Array<Array<Height>>, start: Position, pathExists: (Height, Height) -> Boolean ): Array<Array<Int>> { val stepsMap = Array(heightMap.size) { Array(heightMap[0].size) { NOT_VISITED } } stepsMap[start.y][start.x] = 0 val candidates = ArrayDeque<Position>() candidates.addAll(allNeighboursOf(stepsMap, start)) while (candidates.isNotEmpty()) { val current = candidates.removeFirst() val currentSteps = stepsMap[current.y][current.x] if (currentSteps != NOT_VISITED) continue val currentHeight = heightMap[current.y][current.x] // Add neighbours for further processing val allNeighbours = allNeighboursOf(stepsMap, current) val neighboursReachableFromCurrent = allNeighbours.filter { val neighbourHeight = heightMap[it.y][it.x] pathExists(currentHeight, neighbourHeight) }.filter { val neighbourSteps = stepsMap[it.y][it.x] neighbourSteps == NOT_VISITED }.filter { it !in candidates } candidates.addAll(neighboursReachableFromCurrent) // Update current distance val sourceNeighbours = allNeighbours.filter { val neighbourHeight = heightMap[it.y][it.x] pathExists(neighbourHeight, currentHeight) }.filter { val neighbourSteps = stepsMap[it.y][it.x] neighbourSteps != NOT_VISITED } val minNeighbourSteps = sourceNeighbours.minOfOrNull { stepsMap[it.y][it.x] } if (minNeighbourSteps != null) stepsMap[current.y][current.x] = minNeighbourSteps + 1 } printStepMap(stepsMap) return stepsMap } fun part1(rawInput: List<String>): Int { val (heightMap, start, end) = parseMap(rawInput) val stepMap = findWay(heightMap, start) { from, to -> (from + 1) >= to } return stepMap[end.y][end.x] } fun part2(rawInput: List<String>): Int { val (heightMap, start, end) = parseMap(rawInput) val stepMap = findWay(heightMap, end) { from, to -> from <= (to + 1) } var minStepsToA = stepMap[start.y][start.x] for (y in 0..heightMap.lastIndex) { for (x in 0..heightMap[0].lastIndex) { if (heightMap[y][x] != 'a' || stepMap[y][x] == NOT_VISITED) continue minStepsToA = kotlin.math.min(minStepsToA, stepMap[y][x]) } } return minStepsToA } val sampleInput = readInput("sample_data", DAY_NUMBER) val mainInput = readInput("main_data", DAY_NUMBER) logEnabled = false val part1SampleResult = part1(sampleInput) println(part1SampleResult) check(part1SampleResult == 31) val part1MainResult = part1(mainInput) println(part1MainResult) check(part1MainResult == 370) val part2SampleResult = part2(sampleInput) println(part2SampleResult) check(part2SampleResult == 29) val part2MainResult = part2(mainInput) println(part2MainResult) check(part2MainResult == 363) }
0
Kotlin
0
0
1b261c399a0a84c333cf16f1031b4b1f18b651c7
5,188
advent-of-code-2022
Apache License 2.0
src/Day07.kt
phamobic
572,925,492
false
{"Kotlin": 12697}
private const val ROOT = "/" private const val PARENT_DIRECTORY = ".." private const val MARK_DIRECTORY = "dir" private const val FILE_SIZE_DELIMITER = " " private const val COMMAND_CHANGE_DIRECTORY = "$ cd " private const val COMMAND_LIST_DIRECTORY = "$ ls" private const val MAX_DIRECTORY_SIZE = 100000 private const val MAX_DISK_SPACE = 70000000 private const val MIN_SPACE_FOR_UPDATE = 30000000 data class File( val name: String, val size: Long, ) data class Directory( val name: String, val parentDirectory: Directory? = null, ) { private val _directories = mutableListOf<Directory>() private val _files = mutableListOf<File>() fun addFile(file: File) { if (_files.none { it.name == file.name }) { _files.add(file) } } fun addSubDirectory(directory: Directory) { if (_directories.none { it.name == directory.name }) { _directories.add(directory) } } fun findSubdirectory(name: String): Directory? = _directories.find { it.name == name } fun getSubDirectorySizes(): List<Long> { val sizes = mutableListOf<Long>() var directSubDirectoriesSum = 0L _directories.forEach { directory -> val subSizes = directory.getSubDirectorySizes() sizes.addAll(subSizes) directSubDirectoriesSum += subSizes.last() } val filesSize = _files.sumOf { it.size } sizes.add(directSubDirectoriesSum + filesSize) return sizes } override fun toString(): String = "Name: $name, directories: $_directories, files: $_files" } fun main() { fun getFilesTree(input: List<String>): Directory { val rootDirectory = Directory(ROOT) var currentDirectory = rootDirectory input.forEachIndexed { index, line -> when { line.startsWith(COMMAND_CHANGE_DIRECTORY) -> { val directoryName = line.removePrefix(COMMAND_CHANGE_DIRECTORY) currentDirectory = when (directoryName) { ROOT -> rootDirectory PARENT_DIRECTORY -> currentDirectory.parentDirectory else -> currentDirectory.findSubdirectory(directoryName) } ?: throw IllegalArgumentException() } line.startsWith(COMMAND_LIST_DIRECTORY) -> { // Do nothing } else -> { val data = line.split(FILE_SIZE_DELIMITER) val info = data.first() val name = data.last() if (info == MARK_DIRECTORY) { currentDirectory.addSubDirectory( Directory( name = name, parentDirectory = currentDirectory ) ) } else { currentDirectory.addFile( File( name = name, size = info.toLong() ) ) } } } } return rootDirectory } fun part1(input: List<String>): Long { val rootDirectory = getFilesTree(input) val directorySizes = rootDirectory.getSubDirectorySizes() return directorySizes.filter { it <= MAX_DIRECTORY_SIZE }.sum() } fun part2(input: List<String>): Long { val rootDirectory = getFilesTree(input) val directorySizes = rootDirectory.getSubDirectorySizes() val usedSpace = directorySizes.last() val spaceToDelete = MIN_SPACE_FOR_UPDATE - (MAX_DISK_SPACE - usedSpace) return directorySizes.filter { it >= spaceToDelete }.min() } val testInput1 = readInput("Day07_test") check(part1(testInput1) == 95437L) check(part2(testInput1) == 24933642L) }
1
Kotlin
0
0
34b2603470c8325d7cdf80cd5182378a4e822616
4,067
aoc-2022
Apache License 2.0
src/Day11.kt
lonskiTomasz
573,032,074
false
{"Kotlin": 22055}
fun main() { data class Monkey( val id: String, val items: MutableList<Long>, val inspection: (Long) -> Long, val test: Int, val ifTrue: String, val ifFalse: String ) { var inspectedItems = 0L fun inspectItems(afterInspection: (Long) -> Long): List<Pair<String, Long>> { return items.map { item -> inspect(item, afterInspection) }.also { inspectedItems += items.size items.clear() } } private fun inspect(item: Long, afterInspection: (Long) -> Long): Pair<String, Long> { val worryLevel: Long = afterInspection(inspection(item)) return (if ((worryLevel % test) == 0L) ifTrue else ifFalse) to worryLevel } } fun List<String>.toMonkey(): Monkey { val id: String = get(0).removePrefix("Monkey ").dropLast(1) val items: MutableList<Long> = get(1) .removePrefix(" Starting items: ") .split(", ") .map { it.toLong() } .toMutableList() val operation: (Long) -> Long = get(2) .removePrefix(" Operation: new = old ") .split(' ') .let { (operator, n) -> when { n == "old" -> { old -> old * old } operator == "*" -> { old -> old * n.toLong() } operator == "+" -> { old -> old + n.toLong() } else -> error("") } } val denominator: Int = get(3).removePrefix(" Test: divisible by ").toInt() val ifTrue: String = get(4).removePrefix(" If true: throw to monkey ") val ifFalse: String = get(5).removePrefix(" If false: throw to monkey ") return Monkey(id, items, operation, denominator, ifTrue, ifFalse) } fun List<String>.toMonkeys(): List<Monkey> = chunked(7).map { it.toMonkey() } fun round(monkeys: List<Monkey>, afterInspection: (Long) -> Long): List<Monkey> { val iterator = monkeys.iterator() while (iterator.hasNext()) { iterator.next().inspectItems(afterInspection).forEach { (id, item) -> monkeys.find { it.id == id }?.items?.add(item) } } return monkeys } fun List<Monkey>.getResult() { val result = map { it.inspectedItems }.sortedDescending().take(2) println(result) println(result[0] * result[1]) } fun part1(input: List<String>) { var monkeys = input.toMonkeys() repeat(20) { monkeys = round(monkeys, afterInspection = { it / 3 }) } monkeys.getResult() } fun part2(input: List<String>) { var monkeys = input.toMonkeys() val mod = monkeys.map { it.test }.reduce { acc, i -> acc * i } repeat(10000) { monkeys = round(monkeys, afterInspection = { it % mod }) } monkeys.getResult() } val inputTest = readInput("day11/input_test") val input = readInput("day11/input") println(part1(inputTest)) println(part1(input)) println(part2(inputTest)) println(part2(input)) }
0
Kotlin
0
0
9e758788759515049df48fb4b0bced424fb87a30
3,145
advent-of-code-kotlin-2022
Apache License 2.0
src/Day05.kt
davidkna
572,439,882
false
{"Kotlin": 79526}
import kotlin.collections.ArrayDeque fun main() { fun solution(input: List<String>, part2: Boolean): String { val stacks: List<ArrayDeque<Char>> = (0 until ((input[0].length + 1) / 4)) .map { return@map ArrayDeque<Char>() } .toList() val initial = input.takeWhile { l -> l.isNotEmpty() } initial.forEach { l -> stacks.indices .asSequence() .filter { l[it * 4] == '[' } .forEach { stacks[it].addFirst(l[it * 4 + 1]) } } input.filter { l -> l.startsWith("move") }.forEach { l -> // move n from x to y val s = l.split(" ") val n = s[1].toInt() val x = s[3].toInt() - 1 val y = s[5].toInt() - 1 if (part2 && n != 1) { val t = ArrayDeque<Char>() for (i in 0 until n) { t.addFirst(stacks[x].removeLast()) } stacks[y].addAll(t) } else { for (i in 0 until n) { stacks[y].addLast(stacks[x].removeLast()) } } } return stacks.filter { s -> s.isNotEmpty() }.map { s -> s.removeLast() }.joinToString("") } val testInput = readInput("Day05_test") check(solution(testInput, false) == "CMZ") check(solution(testInput, true) == "MCD") val input = readInput("Day05") println(solution(input, false)) println(solution(input, true)) }
0
Kotlin
0
0
ccd666cc12312537fec6e0c7ca904f5d9ebf75a3
1,520
aoc-2022
Apache License 2.0
2022/main/day_12/Main.kt
Bluesy1
572,214,020
false
{"Rust": 280861, "Kotlin": 94178, "Shell": 996}
package day_12_2022 import java.io.File fun Pair<Int, Int>.directNeighbors(): MutableList<Pair<Int, Int>> { val list = mutableListOf<Pair<Int, Int>>() for (yOff in -1..1) { for (xOff in -1..1) { //if not diagonal or self if ((xOff == 0) xor (yOff == 0)) { list.add(Pair(this.first + xOff, this.second + yOff)) } } } return list } fun part1(input: String) { val heights = mutableMapOf<Pair<Int, Int>?, Int>() val lines = input.split("\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() var start: Pair<Int, Int>? = null var end: Pair<Int, Int>? = null //go over input, populating heights and noting start and end for (y in lines.indices) { val line = lines[y] for (x in line.indices) { if (line[x] == 'S') start = x to y else if (line[x] == 'E') end = x to y else heights[x to y] = line[x].code } } heights[start] = 'a'.code heights[end] = 'z'.code print("The shortest path contains ${pathfinder(start!!, end!!, heights)} moves") } fun pathfinder(start: Pair<Int, Int>, end: Pair<Int, Int>, heights: MutableMap<Pair<Int, Int>?, Int>): Int { val gCost = mutableMapOf<Pair<Int, Int>?, Int>() val parent = mutableMapOf<Pair<Int, Int>?, Pair<Int, Int>?>() val queue = mutableListOf<Pair<Int, Int>>() gCost[start] = 0 queue.add(start) while (queue.size > 0) { var cur: Pair<Int, Int>? = queue.removeAt(0) if (cur == end) { val path: ArrayList<Pair<Int, Int>?> = ArrayList() while (parent.containsKey(cur)) { path.add(cur) cur = parent[cur] } return path.size } for (c in cur!!.directNeighbors()) { //skip if outside bounds or if height is more than one above current if (!heights.containsKey(c) || heights[c]!! > heights[cur]!! + 1) continue val tentativeG = gCost[cur]!! + 1 if (tentativeG < gCost.getOrDefault(c, Int.MAX_VALUE)) { gCost[c] = tentativeG parent[c] = cur queue.add(c) } } } return Int.MAX_VALUE } fun part2(input: String) { val heights = mutableMapOf<Pair<Int, Int>?, Int>() val lines = input.split("\n") lateinit var start: Pair<Int, Int> lateinit var end: Pair<Int, Int> for (y in lines.indices) { val line = lines[y] for (x in line.indices) { if (line[x] == 'S') start = x to y else if (line[x] == 'E') end = x to y else heights[x to y] = line[x].code } } heights[start] = 'a'.code heights[end] = 'z'.code //now, go over all possible locations - if location is an 'a', // the shortest path is minimum of existing shortest and fastest path from cur to end var shortest = Int.MAX_VALUE for (c in heights.keys) { if (heights[c] == 'a'.code) shortest = shortest.coerceAtMost(pathfinder(c!!, end, heights)) } print("The shortest path contains $shortest moves") } fun main(){ val inputFile = File("2022/inputs/Day_12.txt") print("\n----- Part 1 -----\n") part1(inputFile.readText()) print("\n----- Part 2 -----\n") part2(inputFile.readText()) }
0
Rust
0
0
537497bdb2fc0c75f7281186abe52985b600cbfb
3,531
AdventofCode
MIT License
2022/Day11/problems.kt
moozzyk
317,429,068
false
{"Rust": 102403, "C++": 88189, "Python": 75787, "Kotlin": 72672, "OCaml": 60373, "Haskell": 53307, "JavaScript": 51984, "Go": 49768, "Scala": 46794}
import java.io.File import java.util.ArrayDeque class Monkey( var items: ArrayDeque<Long>, val operation: Char, val operand: String, val divisor: Int, val targetIfTrue: Int, val targetIfFalse: Int ) { var timesInspected = 0 fun getItem(): Long { timesInspected++ return items.removeFirst() } fun computeNewWorryLevel(oldVal: Long): Long { val value = if (operand == "old") { oldVal } else { operand.toLong() } return if (operation == '*') { oldVal * value } else { oldVal + value } } fun nextMonkey(worryLevel: Long): Int { return if (worryLevel % divisor == 0L) { targetIfTrue } else { targetIfFalse } } } fun main(args: Array<String>) { val lines = File(args[0]).readLines() println(problem1(lines.windowed(7, 7).map { parse(it) })) println(problem2(lines.windowed(7, 7).map { parse(it) })) } fun parse(lines: List<String>): Monkey { val regex = """(\d+)""".toRegex() val items = regex.findAll(lines[1]).map { it.value.toLong() } val (operation, operand) = """old (.) (old|\d+)""".toRegex().find(lines[2])!!.destructured val (divisor) = regex.find(lines[3])!!.destructured val (targetIfTrue) = regex.find(lines[4])!!.destructured val (targetIfFalse) = regex.find(lines[5])!!.destructured return Monkey( ArrayDeque(items.toList()), operation.first(), operand, divisor.toInt(), targetIfTrue.toInt(), targetIfFalse.toInt() ) } fun solve(monkeys: List<Monkey>, rounds: Int, reductionFactor: Int): Long { val mod = monkeys.map { it.divisor }.reduce { a, e -> a * e } for (i in 1..rounds) { for (m in monkeys) { while (!m.items.isEmpty()) { var worryLevel = m.getItem() worryLevel = (m.computeNewWorryLevel(worryLevel) / reductionFactor) % mod val targetMonkey = m.nextMonkey(worryLevel) monkeys[targetMonkey].items.addLast(worryLevel) } } } println(monkeys.map { it.timesInspected.toLong() }) var topInspected = monkeys.map { it.timesInspected.toLong() }.sortedDescending().take(2) return topInspected.reduce { acc, el -> acc * el } } fun problem1(monkeys: List<Monkey>): Long = solve(monkeys, 20, 3) fun problem2(monkeys: List<Monkey>): Long = solve(monkeys, 10000, 1)
0
Rust
0
0
c265f4c0bddb0357fe90b6a9e6abdc3bee59f585
2,606
AdventOfCode
MIT License
src/aoc2023/Day14.kt
dayanruben
433,250,590
false
{"Kotlin": 79134}
package aoc2023 import checkValue import readInput fun main() { val (year, day) = "2023" to "Day14" fun loadSum(input: List<String>, maxCycles: Int): Int { var state = PlatformState(input.map { it.toCharArray() }.toTypedArray()) var totalLoad: Int? = null when (maxCycles) { 0 -> state = state.tilt() else -> { val cycleForState = mutableMapOf(state to 0) val stateForCycle = mutableMapOf(0 to state) val loadForState = mutableMapOf(state to 0) for (currentCycle in 1..maxCycles) { repeat(4) { state = state.tilt().rotate() } if (state in cycleForState) { val repeatedCycle = cycleForState.getValue(state) val finalCycle = repeatedCycle - 1 + (maxCycles - currentCycle + 1) % (currentCycle - repeatedCycle) val finalState = stateForCycle.getValue(finalCycle) totalLoad = finalState.totalLoad() break } else { cycleForState[state] = currentCycle stateForCycle[currentCycle] = state loadForState[state] = state.totalLoad() } } } } return totalLoad ?: state.totalLoad() } fun part1(input: List<String>) = loadSum(input, maxCycles = 0) fun part2(input: List<String>) = loadSum(input, maxCycles = 1_000_000_000) val testInput = readInput(name = "${day}_test", year = year) val input = readInput(name = day, year = year) checkValue(part1(testInput), 136) println(part1(input)) checkValue(part2(testInput), 64) println(part2(input)) } data class PlatformState(val state: Array<CharArray>) { fun tilt(): PlatformState { val state = this.state val numRows = state.size val numCols = state[0].size val cols = state.first().indices.map { colIndex -> state.mapIndexed { rowIndex, row -> row[colIndex] to rowIndex }.filter { it.first != '.' } } val newState = Array(numRows) { CharArray(numCols) { '.' } } cols.forEachIndexed { colIndex, col -> var row = 0 for ((cell, rowIndex) in col) { when (cell) { '#' -> { newState[rowIndex][colIndex] = '#' row = rowIndex + 1 } else -> { newState[row][colIndex] = 'O' row++ } } } } return PlatformState(newState) } fun rotate(): PlatformState { val state = this.state val numRows = state.size val numCols = state[0].size val newState = Array(numCols) { CharArray(numRows) } for (row in 0 until numRows) { for (col in 0 until numCols) { newState[col][numRows - 1 - row] = state[row][col] } } return PlatformState(newState) } fun totalLoad(): Int = state.mapIndexed { index, row -> row.count { it == 'O' } * (state.size - index) }.sum() override fun equals(other: Any?): Boolean = (other as? PlatformState)?.state.contentDeepEquals(state) override fun hashCode(): Int = state.contentDeepHashCode() override fun toString() = state.map { it.joinToString("") }.joinToString("\n") }
1
Kotlin
2
30
df1f04b90e81fbb9078a30f528d52295689f7de7
3,659
aoc-kotlin
Apache License 2.0
src/Day04.kt
Lonexera
573,177,106
false
null
fun main() { fun String.mapToElvesSections(): Pair<List<Int>, List<Int>> { val sections = split(",") .map { sections -> val (start, end) = sections .split("-") .map { it.toInt() } .zipWithNext() .first() (start..end).toList() } return sections[0] to sections[1] } fun part1(input: List<String>): Int { return input.sumOf { elvesSection -> val (firstSection, secondSection) = elvesSection.mapToElvesSections() when { firstSection.containsAll(secondSection) -> 1 secondSection.containsAll(firstSection) -> 1 else -> 0 } .toInt() } } fun part2(input: List<String>): Int { return input.sumOf { elvesSection -> val (firstSection, secondSection) = elvesSection.mapToElvesSections() when { firstSection.any { secondSection.contains(it) } -> 1 else -> 0 } .toInt() } } val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c06d394cd98818ec66ba9c0311c815f620fafccb
1,306
kotlin-advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2023/2023-09.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2023 import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines fun main() { val input = readInputLines(2023, "09-input") val test1 = readInputLines(2023, "09-test1") println("Part1:") part1(test1).println() part1(input).println() println() println("Part2:") part2(test1).println() part2(input).println() } private fun part1(input: List<String>): Long { val sequences = input.map { it.split(" ").map(String::toLong) } return sequences.sumOf { nextNumber(it) } } private fun part2(input: List<String>): Long { val sequences = input.map { it.split(" ").map(String::toLong) } return sequences.sumOf { previousNumber(it) } } private fun nextNumber(sequence: List<Long>): Long { val sequences = buildStepDiffs(sequence) return sequences.sumOf { it.last() } } private fun previousNumber(sequence: List<Long>): Long { val sequences = buildStepDiffs(sequence) return sequences.foldRight(0) { list, acc -> list.first() - acc } } private fun buildStepDiffs(sequence: List<Long>): List<List<Long>> = buildList { this += sequence repeat(sequence.size - 1) { val last = last() this += List(last.size - 1) { last[it + 1] - last[it] } } }
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
1,319
advent-of-code
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinCost.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 java.util.PriorityQueue /** * 1928. Minimum Cost to Reach Destination in Time * @see <a href="https://leetcode.com/problems/minimum-cost-to-reach-destination-in-time/">Source</a> */ fun interface MinCost { operator fun invoke(maxTime: Int, edges: Array<IntArray>, passingFees: IntArray): Int } class MinCostQueue : MinCost { override operator fun invoke(maxTime: Int, edges: Array<IntArray>, passingFees: IntArray): Int { val map: MutableMap<Int, MutableList<IntArray>> = HashMap() for (e in edges) { val from = e[0] val to = e[1] val time = e[2] map.putIfAbsent(from, ArrayList()) map.putIfAbsent(to, ArrayList()) map[from]?.add(intArrayOf(to, time)) map[to]?.add(intArrayOf(from, time)) } val pq: PriorityQueue<IntArray> = PriorityQueue<IntArray> { a, b -> if (a[1] == b[1]) a[2] - b[2] else a[1] - b[1] } pq.add(intArrayOf(0, passingFees[0], 0)) // node cost time val n = passingFees.size val dist = IntArray(n) { Int.MAX_VALUE } val times = IntArray(n) { Int.MAX_VALUE } dist[0] = 0 times[0] = 0 while (pq.isNotEmpty()) { val curr: IntArray = pq.poll() val node = curr[0] val cost = curr[1] val time = curr[2] if (time > maxTime) { continue } if (node == n - 1) return cost for (nei in map.getOrDefault(node, emptyList())) { val neiNode = nei[0] val neiCost = passingFees[neiNode] if (cost + neiCost < dist[neiNode]) { dist[neiNode] = cost + neiCost pq.add(intArrayOf(neiNode, cost + neiCost, time + nei[1])) times[neiNode] = time + nei[1] } else if (time + nei[1] < times[neiNode]) { pq.add(intArrayOf(neiNode, cost + neiCost, time + nei[1])) times[neiNode] = time + nei[1] } } } return if (dist[n - 1] == Int.MAX_VALUE || times[n - 1] > maxTime) -1 else dist[n - 1] } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,854
kotlab
Apache License 2.0
src/Day07.kt
tbilou
572,829,933
false
{"Kotlin": 40925}
fun main() { val day = "Day07" fun buildFSTree(input: List<String>): FSTree { val fsTree = FSTree("/") var currentDirectory = fsTree input.drop(1) // skip the first one. It's manually created above .forEach { line -> when { line.isMoveOutOfCurrentDirectory() -> currentDirectory = currentDirectory.parent!! line.isFile() -> currentDirectory.size += line.substringBefore(" ").toInt() line.isChangeDirectory() -> { val dirName = line.substringAfter("cd ") val newDirectory = FSTree(dirName) currentDirectory.addChild(newDirectory) currentDirectory = newDirectory } } } return fsTree } fun part1(fsTree: FSTree): Int { val results = mutableListOf<Int>() getDirectorySizes(fsTree, results) return results.filter { it < 100000 }.sumOf { it } } fun part2(fsTree: FSTree): Int { val results = mutableListOf<Int>() getDirectorySizes(fsTree, results) return results.filter { it > 30000000 - (70000000 - results.max()) }.min() } // test if implementation meets criteria from the description, like: val testInput = readInput("${day}_test") // check((parseInput(testInput)) == 95437) check(part1(buildFSTree(testInput)) == 95437) check(part2(buildFSTree(testInput)) == 24933642) val input = readInput("$day") println(part1(buildFSTree(input))) println(part2(buildFSTree(input))) } // Filesystem Tree that represent a directory, it's sub-directories and size private data class FSTree(val directoryName: String) { var size = 0 var parent: FSTree? = null var subDirectories: MutableList<FSTree> = mutableListOf() fun addChild(node: FSTree) { subDirectories.add(node) node.parent = this } // Debug override fun toString(): String { var s = "$directoryName $size \n" if (!subDirectories.isEmpty()) { s += "\t" + subDirectories.map { it.toString() } + "\n" } return s } } private fun getDirectorySizes(directory: FSTree, results: MutableList<Int>): Int { if (!directory.subDirectories.isEmpty()) { val sumOfChildren = directory.subDirectories.sumOf { getDirectorySizes(it, results) } val totalSize = directory.size + sumOfChildren results.add(totalSize) return totalSize } else { // End condition results.add(directory.size) return directory.size } } private fun String.isFile(): Boolean { return """[0-9]+ .*""".toRegex().matches(this) } private fun String.isChangeDirectory():Boolean{ return """\$ cd .+""".toRegex().matches(this) } private fun String.isMoveOutOfCurrentDirectory(): Boolean { return this == "\$ cd .." }
0
Kotlin
0
0
de480bb94785492a27f020a9e56f9ccf89f648b7
2,966
advent-of-code-2022
Apache License 2.0
year2023/src/main/kotlin/net/olegg/aoc/year2023/day25/Day25.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2023.day25 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.UnionFind import net.olegg.aoc.utils.toPair import net.olegg.aoc.year2023.DayOf2023 /** * See [Year 2023, Day 25](https://adventofcode.com/2023/day/25) */ object Day25 : DayOf2023(25) { override fun first(): Any? { val edges = lines.flatMap { line -> line.substringAfter(": ").split(" ").map { listOf(line.substringBefore(": "), it).sorted().toPair() } } val nodeNames = buildSet { edges.forEach { add(it.first) add(it.second) } } val nodeIndex = nodeNames.withIndex().associate { it.value to it.index } var bestEdges = edges.size * edges.size var bestResult = -1 while (bestEdges != 3) { val (currEdges, currResult) = minCut(edges, nodeIndex) if (currEdges < bestEdges) { bestEdges = currEdges bestResult = currResult } } return bestResult } private fun minCut( startEdges: List<Pair<String, String>>, startNodes: Map<String, Int>, ): Pair<Int, Int> { val adjList = mutableMapOf<Int, MutableList<Int>>() startEdges.forEach { (a, b) -> adjList.getOrPut(startNodes.getValue(a)) { mutableListOf() } .add(startNodes.getValue(b)) adjList.getOrPut(startNodes.getValue(b)) { mutableListOf() } .add(startNodes.getValue(a)) } val vertices = startNodes.values.sorted().toMutableList() val unionFind = UnionFind(vertices.size) while (vertices.size > 2) { val edges = buildEdges(adjList, vertices) val edge = edges.random() val (vertex1, vertex2) = edge unionFind.union(vertex1, vertex2) val valuesV1 = adjList[vertex1]!! val valuesV2 = adjList[vertex2]!! valuesV1.addAll(valuesV2) vertices.removeAt(vertices.indexOf(vertex2)) adjList.remove(vertex2) vertices.forEach { vertex -> val values = adjList[vertex]!! values.forEachIndexed { index, value -> if (value == vertex2) { values[index] = vertex1 } } } adjList[vertex1]!!.removeIf { it == vertex1 } } return adjList[vertices[0]]!!.size to startNodes.values .groupingBy { unionFind.root(it) } .eachCount() .values .reduce(Int::times) } private fun buildEdges( adjList: Map<Int, List<Int>>, vertices: List<Int> ): List<IntArray> { return vertices.flatMap { from -> val vector = adjList[from]!! vector.map { to -> intArrayOf(from, to) } } } } fun main() = SomeDay.mainify(Day25)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
2,640
adventofcode
MIT License