path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/Day05.kt | MisterTeatime | 561,848,263 | false | {"Kotlin": 20300} | fun main() {
val vowels = listOf('a', 'e', 'i', 'o', 'u')
val forbidden = listOf("ab", "cd", "pq", "xy")
fun part1(input: List<String>): Int {
return input
.filterNot { s -> s.windowed(2).any { forbidden.contains(it) } } //Filter "Verbotene Zeichenketten"
.filter { s -> s.count { vowels.contains(it) } >= 3 } //Filter "3 Vokale"
.filter { s -> s.windowed(2).any { it.take(1) == it.drop(1) } }//Filter "Doppelung"
.size
}
fun part2(input: List<String>): Int {
val repeatRegex = Regex("""(..).*\1""")
val spacedRegex = Regex("""(.).\1""")
return input
.filter { repeatRegex.containsMatchIn(it) } //Filter "Paarwiederholung"
.filter { spacedRegex.containsMatchIn(it) } //Filter "Dopplung mit Abstand"
.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == 2)
check(part2(testInput) == 2)
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d684bd252a9c6e93106bdd8b6f95a45c9924aed6 | 1,125 | AoC2015 | Apache License 2.0 |
2020/src/year2020/day08/Day08.kt | eburke56 | 436,742,568 | false | {"Kotlin": 61133} | package year2020.day08
import util.readAllLines
private data class Instruction(
val command: String,
val arg: Int,
var visited: Boolean = false
)
private fun loadProgram(filename: String): List<Instruction> =
readAllLines(filename).map { line ->
val (command, arg) = line.split(" ")
val argVal = (if (arg[0] == '-') -1 else 1) * arg.substring(1).toInt()
Instruction(command, argVal)
}
private fun run(program: List<Instruction>, jumpToNopIndex: Int = -1): Pair<Boolean, Int> {
var ip = 0
var acc = 0
program.forEach { it.visited = false }
while (ip < program.size) {
val instruction = program[ip]
if (instruction.visited) {
return Pair(false, acc)
}
var advance = 1
val command = if (ip == jumpToNopIndex && instruction.command == "jmp") "nop" else instruction.command
when (command) {
"acc" -> acc += instruction.arg
"jmp" -> advance = instruction.arg
}
instruction.visited = true
ip += advance
}
return Pair(true, acc)
}
private fun part1(filename: String): Int {
return run(loadProgram(filename)).second
}
private fun part2(filename: String): Int {
val program = loadProgram(filename)
program.mapIndexedNotNull { index, instruction ->
if (instruction.command == "jmp") index else null
}.forEach { jumpTestIndex ->
run(program, jumpTestIndex).let { (terminatedNormally, accumulator) ->
if (terminatedNormally) {
return accumulator
}
}
}
return -1
}
fun main() {
println("Test part 1 = ${part1("test.txt")}")
println("Real part 1 = ${part1("input.txt")}")
println("Test part 2 = ${part2("test.txt")}")
println("Real part 2 = ${part2("input.txt")}")
}
| 0 | Kotlin | 0 | 0 | 24ae0848d3ede32c9c4d8a4bf643bf67325a718e | 1,846 | adventofcode | MIT License |
src/Day03.kt | Flexicon | 576,933,699 | false | {"Kotlin": 5474} | fun main() {
fun String.splitInHalf(): List<String> = (length / 2).let {
listOf(substring(0, it), substring(it))
}
fun Char.priority(): Int = code - if (isLowerCase()) 96 else 38
fun part1(input: List<String>): Int = input
.map { it.splitInHalf() }
.sumOf { (left, right) ->
right.find { left.contains(it) }?.priority() ?: 0
}
fun part2(input: List<String>): Int = input.windowed(3, 3)
.sumOf { (first, second, third) ->
first.find { second.contains(it) && third.contains(it) }?.priority() ?: 0
}
val testInput = readInput("Day03_test")
val part1Result = part1(testInput)
val expected1 = 157
check(part1Result == expected1) { "Part 1: Expected $expected1, actual $part1Result" }
val part2Result = part2(testInput)
val expected2 = 70
check(part2Result == expected2) { "Part 2: Expected $expected2, actual $part2Result" }
val input = readInput("Day03")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 7109cf333c31999296e1990ce297aa2db3a622f2 | 1,038 | aoc-2022-in-kotlin | Apache License 2.0 |
2020/src/main/kotlin/de/skyrising/aoc2020/day7/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2020.day7
import de.skyrising.aoc.*
private fun readMap(lines: List<String>): Map<String, Set<Pair<String, Int>>> {
val map = mutableMapOf<String, MutableSet<Pair<String, Int>>>()
for (line in lines) {
val (bags, contain) = line.split(" bags contain ")
if (contain.startsWith("no other")) continue
val containList = contain.split(", ")
val set = map.computeIfAbsent(bags) { mutableSetOf() }
for (containItem in containList) {
val space = containItem.indexOf(' ')
val num = containItem.substring(0, space)
val type = containItem.substring(space + 1, containItem.indexOf(" bag"))
set.add(Pair(type, num.toInt()))
}
}
return map
}
private fun readGraph(lines: List<String>) = Graph.build<String, Nothing?> {
for (line in lines) {
val (bags, contain) = line.split(" bags contain ")
if (contain.startsWith("no other")) continue
val containList = contain.split(", ")
for (containItem in containList) {
val space = containItem.indexOf(' ')
val num = containItem.substring(0, space)
val type = containItem.substring(space + 1, containItem.indexOf(" bag"))
edge(bags, type, num.toInt(), null)
}
}
}
@PuzzleName("Handy Haversacks")
fun PuzzleInput.part1v0(): Any {
val set = mutableSetOf<String>()
var count = 0
var lastCount = -1
while (count > lastCount) {
for (line in lines) {
val (bags, contain) = line.split(" bags contain ")
if (contain.startsWith("no other")) continue
val containList = contain.split(", ")
for (containItem in containList) {
val space = containItem.indexOf(' ')
//val num = containItem.substring(0, space)
val type = containItem.substring(space + 1, containItem.indexOf(" bag"))
if (type == "shiny gold" || set.contains(type)) {
set.add(bags)
}
}
}
lastCount = count
count = set.size
}
return count
}
@PuzzleName("Handy Haversacks")
fun PuzzleInput.part1v1(): Any {
val graph = readGraph(lines)
val set = mutableSetOf("shiny gold")
var count = 0
while (set.size > count) {
count = set.size
val newSet = mutableSetOf<String>()
for (v in set) {
for ((from, _, weight, _) in graph.getIncoming(v)) {
newSet.add(from)
}
}
set.addAll(newSet)
}
return count - 1
}
fun PuzzleInput.part2v0(): Any {
val map = readMap(lines)
fun getContained(type: String): Int {
val set = map[type] ?: return 1
var sum = 1
for ((contained, num) in set) {
sum += num * getContained(contained)
}
return sum
}
return getContained("shiny gold") - 1
}
fun PuzzleInput.part2v1(): Any {
val graph = readGraph(lines)
fun getContained(type: String): Int {
var sum = 1
for ((_, contained, num, _) in graph.getOutgoing(type)) {
sum += num * getContained(contained)
}
return sum
}
return getContained("shiny gold") - 1
} | 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 3,284 | aoc | MIT License |
2015/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2015/day19/Day19.kt | sanderploegsma | 224,286,922 | false | {"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171} | package nl.sanderp.aoc.aoc2015.day19
import nl.sanderp.aoc.common.readResource
fun parse(input: List<String>): Pair<List<Pair<String, String>>, String> {
val replacements = input.takeWhile { it.isNotBlank() }
.map { it.split(" => ").let { (a, b) -> a to b } }
val molecule = input.drop(replacements.size + 1).first()
return replacements to molecule
}
fun candidates(rules: List<Pair<String, String>>, molecule: String) =
rules.flatMap { (find, replace) ->
Regex(find).findAll(molecule).map { match ->
molecule.replaceRange(match.range, replace)
}
}.toSet()
fun stepCount(rules: List<Pair<String, String>>, molecule: String): Int {
val reversedRules = rules.map { (a, b) -> b to a }
var steps = 0
var target = molecule
while (target != "e") {
for ((find, replace) in reversedRules) {
if (target.contains(find)) {
target = target.replaceFirst(find, replace)
steps++
}
}
}
return steps
}
fun main() {
val (replacements, molecule) = readResource("19.txt").lines().let(::parse)
println("Part one: ${candidates(replacements, molecule).size}")
println("Part two: ${stepCount(replacements, molecule)}")
}
| 0 | C# | 0 | 6 | 8e96dff21c23f08dcf665c68e9f3e60db821c1e5 | 1,271 | advent-of-code | MIT License |
src/Day05.kt | khongi | 572,983,386 | false | {"Kotlin": 24901} | import java.util.Stack
fun main() {
operator fun <E> List<E>.component2(): Int = this[1].toString().toInt()
operator fun <E> List<E>.component4(): Int = this[3].toString().toInt()
operator fun <E> List<E>.component6(): Int = this[5].toString().toInt()
fun buildStacks(
input: List<String>,
numberedLineIndex: Int
): List<Stack<Char>> {
val cols = input[numberedLineIndex].split(' ').last().toInt()
val stacks: MutableList<Stack<Char>> = mutableListOf()
repeat(cols) { stacks.add(Stack()) }
input.subList(0, numberedLineIndex).forEach { crateLevel ->
crateLevel.chunked(4).map { it[1] }.forEachIndexed { index, c ->
if (c.isLetter()) {
stacks[index].add(c)
}
}
}
stacks.forEach { it.reverse() }
return stacks
}
fun getTopCrates(stacks: List<Stack<Char>>) =
stacks.map { it.pop() }.joinToString(separator = "")
fun moveSingleCrates(
moveCount: Int,
stacks: List<Stack<Char>>,
to: Int,
from: Int
) {
repeat(moveCount) { stacks[to - 1].add(stacks[from - 1].pop()) }
}
fun moveMultipleCrates(
moveCount: Int,
stacks: List<Stack<Char>>,
to: Int,
from: Int
) {
val tempStack: Stack<Char> = Stack()
repeat(moveCount) { tempStack.add(stacks[from - 1].pop()) }
repeat(moveCount) { stacks[to - 1].add(tempStack.pop()) }
}
fun getNumberedLineIndex(input: List<String>) = input.indexOfFirst { it.contains('1') }
fun operateCrateMover(
input: List<String>,
move: (
moveCount: Int,
stacks: List<Stack<Char>>,
to: Int,
from: Int
) -> Unit
): String {
val numberedLineIndex = getNumberedLineIndex(input)
val stacks: List<Stack<Char>> = buildStacks(input, numberedLineIndex)
input.subList(numberedLineIndex + 2, input.size).forEach { command ->
val (_, moveCount, _, from, _, to) = command.split(' ')
move(moveCount, stacks, to, from)
}
return getTopCrates(stacks)
}
fun part1(input: List<String>): String {
return operateCrateMover(input, ::moveSingleCrates)
}
fun part2(input: List<String>): String {
return operateCrateMover(input, ::moveMultipleCrates)
}
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 | 9cc11bac157959f7934b031a941566d0daccdfbf | 2,651 | adventofcode2022 | Apache License 2.0 |
src/Utils.kt | thpz2210 | 575,577,457 | false | {"Kotlin": 50995} | import java.io.File
/**
* Reads lines from the given input txt file.
*/
fun readInput(name: String) = File("input", "$name.txt").readLines()
/**
* Holds a 2 dimensional grid
*/
class Grid2D<T>(initialItems: List<List<T>>) {
private val itemMap = initialItems.indices.flatMap { y ->
initialItems[y].indices.map { x -> Coordinate(x, y) to initialItems[y][x] }
}.toMap()
fun itemAt(coordinate: Coordinate) = itemMap[coordinate]!!
fun findFirstCoordinate(predicate: (T) -> Boolean) = itemMap.filterValues { predicate(it) }.map { it.key }.first()
fun orthogonalNeighborsOf(coordinate: Coordinate) = listOf(
Coordinate(coordinate.x, coordinate.y - 1),
Coordinate(coordinate.x, coordinate.y + 1),
Coordinate(coordinate.x - 1, coordinate.y),
Coordinate(coordinate.x + 1, coordinate.y)
).filter { itemMap.keys.contains(it) }.toSet()
}
/**
* Holds a 2 dimensional coordinate
*/
data class Coordinate(val x: Int = 0, val y: Int = 0) {
constructor(pair: Pair<Int, Int>) : this(pair.first, pair.second)
override fun toString() ="(x=$x, y=$y)"
}
/**
* Holds a 2 dimensional coordinate with mutable entries
*/
data class MutableCoordinate(var x: Int, var y: Int) {
override fun toString() ="(x=$x, y=$y)"
}
/**
* Returns the cartesian product of the given IntRanges
*/
fun IntRange.cartesianProduct(other: IntRange): List<Coordinate> = this.flatMap { s ->
List(other.count()) { s }.zip(other).map { Coordinate(it) }
}
| 0 | Kotlin | 0 | 0 | 69ed62889ed90692de2f40b42634b74245398633 | 1,515 | aoc-2022 | Apache License 2.0 |
jvm/src/main/kotlin/io/prfxn/aoc2021/day10.kt | prfxn | 435,386,161 | false | {"Kotlin": 72820, "Python": 362} | // Syntax Scoring (https://adventofcode.com/2021/day/10)
package io.prfxn.aoc2021
fun main() {
val lines = textResourceReader("input/10.txt").readLines()
val o2c = "()[]{}<>".chunked(2).associate { it.first() to it.last() }
val c2o = o2c.entries.associate { it.value to it.key }
val seS = ")]}>".asSequence().zip(sequenceOf(3, 57, 1197, 25137)).toMap()
val acS = "([{<".mapIndexed { i, c -> c to i + 1 }.toMap()
fun seScore(s: String): Int {
val stack = ArrayDeque<Char>()
for (c in s)
if (c in o2c.keys)
stack.add(c)
else if (c in c2o.keys)
if (stack.last() != c2o[c])
return seS[c]!!
else
stack.removeLast()
return 0
}
val answer1 = lines.sumOf(::seScore)
fun acScore(s: String): Long {
val stack = ArrayDeque<Char>()
for (c in s)
if (c in o2c.keys)
stack.add(c)
else if (c in c2o.keys)
if (stack.last() == c2o[c])
stack.removeLast()
else
fail("syntax error")
return stack.foldRight(0L) { c, acScore -> (acScore * 5) + acS[c]!! }
}
val answer2 =
lines
.filter { seScore(it) == 0 }
.map(::acScore)
.sorted()
.let { it[it.size / 2] }
sequenceOf(answer1, answer2).forEach(::println)
}
/** output
* 318099
* 2389738699
*/
| 0 | Kotlin | 0 | 0 | 148938cab8656d3fbfdfe6c68256fa5ba3b47b90 | 1,512 | aoc2021 | MIT License |
src/main/kotlin/endredeak/aoc2023/Day10.kt | edeak | 725,919,562 | false | {"Kotlin": 26575} | package endredeak.aoc2023
import kotlin.math.absoluteValue
enum class M { N, S, W, E }
operator fun Pair<Int, Int>.plus(move: M): Pair<Int, Int> = when (move) {
M.N -> first - 1 to second
M.S -> first + 1 to second
M.W -> first to second - 1
M.E -> first to second + 1
}
// first I did a BFS for part 1 and was lost on part 2
// then read Jakub's solution on actually counting the _moves_ which leads to complete the circle -> brilliant!
fun main() {
solve("Pipe Maze") {
operator fun List<String>.get(pos: Pair<Int, Int>): Char = getOrNull(pos.first)?.getOrNull(pos.second) ?: '.'
val input = run {
val start: Pair<Int, Int> = lines.indices.asSequence()
.flatMap { row -> lines[row].indices.map { row to it } }
.first { pos -> lines[pos] == 'S' }
val firstMove = when {
lines[start + M.N] in "7|F" -> M.N
lines[start + M.E] in "7-J" -> M.E
else -> M.S
}
generateSequence(start to firstMove) { (pos, move) ->
val nextPos = pos + move
if (nextPos != start) nextPos to when (lines[nextPos]) {
'|' -> if (move == M.N) M.N else M.S
'-' -> if (move == M.W) M.W else M.E
'L' -> if (move == M.S) M.E else M.N
'J' -> if (move == M.S) M.W else M.N
'F' -> if (move == M.N) M.E else M.S
'7' -> if (move == M.N) M.W else M.S
else -> error("$nextPos?")
}
else null
}
.map { it.second }
.toList()
}
part1(6682) {
input.count() / 2
}
part2(-1) {
input.fold(0 to 0) { (sum, d), move ->
when (move) {
M.N -> sum to d + 1
M.S -> sum to d - 1
M.W -> sum - d to d
M.E -> sum + d to d
}
}.first.absoluteValue - (input.size / 2) + 1
}
}
} | 0 | Kotlin | 0 | 0 | 92c684c42c8934e83ded7881da340222ff11e338 | 2,127 | AdventOfCode2023 | Do What The F*ck You Want To Public License |
src/aoc2023/Day9.kt | RobertMaged | 573,140,924 | false | {"Kotlin": 225650} | package aoc2023
import utils.checkEquals
import utils.readInput
fun main(): Unit = with(Day9) {
part1(testInput).checkEquals(114)
part1(input)
.checkEquals(1980437560)
// .sendAnswer(part = 1, day = "9", year = 2023)
part2(testInput).checkEquals(2)
part2(input)
.checkEquals(977)
// .sendAnswer(part = 2, day = "9", year = 2023)
}
object Day9 {
fun String.buildHistoryHierarchy(transform: (List<Long>) -> Long): List<Long> {
val sequence = this.split(' ').map { it.toLong() }
val history = mutableListOf<List<Long>>(sequence)
while (history.last().any { it != 0L }) {
val diff = history.last().zipWithNext { a, b -> b - a }
history.add(diff)
}
return history.map(transform)
}
fun part1(input: List<String>): Long = input.sumOf { line ->
val lastStepInHistoryHierarchy = line.buildHistoryHierarchy { it.last() }
return@sumOf lastStepInHistoryHierarchy.foldRight(0L) { acc, n ->
acc + n
}
}
fun part2(input: List<String>): Long = input.sumOf { line ->
val firstValueInEachHistory = line.buildHistoryHierarchy { it.first() }
return@sumOf firstValueInEachHistory.foldRight(0L) { acc, n ->
acc - n
}
}
val input
get() = readInput("Day9", "aoc2023")
val testInput
get() = readInput("Day9_test", "aoc2023")
}
| 0 | Kotlin | 0 | 0 | e2e012d6760a37cb90d2435e8059789941e038a5 | 1,453 | Kotlin-AOC-2023 | Apache License 2.0 |
src/Day01.kt | vivekpanchal | 572,801,707 | false | {"Kotlin": 11850} | import kotlin.math.max
fun main() {
fun part1(input: List<String>): Int {
//region using maps
// val elf = mutableMapOf<Int, Int>()
// var elfCount = 1
// var inventory = 0
// var isElf=true
// input.forEach {
// if (it.isNotEmpty()) {
// if (!isElf){
// isElf=true
// elfCount++
// }
// inventory += it.toInt()
// elf[elfCount] = inventory
// }else{
// inventory=0
// isElf=false
// }
// }
// elf.map { (key, value) -> println("$key = $value") }
// val maxInventory=elf.maxBy { it.value }
// println("max inventory ==${maxInventory.key} value : ${maxInventory.value}")
// return maxInventory.key
//endregion maps
//region simple max calculation
var maxCalorie = 0
var current = 0
for (s in input) {
if (s.isBlank()) {
maxCalorie = max(maxCalorie, current)
current = 0
} else {
current += s.toInt()
}
}
return max(maxCalorie, current)
//endregion
}
fun part2(input: List<String>): Int {
val listCalories = mutableListOf<Int>()
var current = 0;
for (s in input) {
if (s.isBlank()) {
listCalories.add(current)
current = 0
} else {
//iterating and adding the current calories stored by elf
current += s.toInt()
}
}
listCalories.sort()
var ans = 0
listCalories.takeLast(3).forEach {
ans += it
}
return ans
}
//region Optimised versions
fun part1(input: String): Int {
return input
.split("\n\n")
.maxOf {
it.split("\n").sumOf(String::toInt)
}
}
fun part2(input: String): Int{
return input
.split("\n\n")
.map { it.split("\n").sumOf(String::toInt) }
.sorted().takeLast(3).sum()
}
//endregion
val input = readInput("Day01")
val inputString = readInputAsText("Day01")
println(part1(input))
println(part1(inputString))
println(part2(input))
println(part2(inputString))
}
| 0 | Kotlin | 0 | 0 | f21a2dd08be66520e9c9de14611e50c14ea017f0 | 2,416 | Aoc-kotlin | Apache License 2.0 |
src/main/kotlin/com/jacobhyphenated/advent2023/day15/Day15.kt | jacobhyphenated | 725,928,124 | false | {"Kotlin": 121644} | package com.jacobhyphenated.advent2023.day15
import com.jacobhyphenated.advent2023.Day
/**
* Day 15: Lens Library
*
* The puzzle input is a set of instruction for focusing lenses.
* Use a custom ascii hash algorithm as part of the setup process
*/
class Day15: Day<String> {
override fun getInput(): String {
return readInputFile("15")
}
/**
* Part 1: Run the hash algorithm on each comma separated instruction and add the results
*/
override fun part1(input: String): Int {
return input.split(",").sumOf { asciiHash(it) }
}
/**
* Part 2: Each instruction is has either a '-' or an '=' (ex: rn=1 cm-)
*
* There are 256 boxes (0 - 255). Use the hash algorithm on the lens component of the instruction.
* The '-' operation removes that lens from the box.
* The '=' instruction adds that lens with the supplied focus value OR modifies the focus value if
* the lens is already in the box. If modifying, do not change the order of the lenses
*
* Calculate the score for each lens as:
* box number (1 indexed) * position in box (1 indexed) * focus value
*/
override fun part2(input: String): Int {
val boxes = mutableMapOf<Int, MutableList<Pair<String,Int>>>()
(0 until 256).forEach { boxes[it] = mutableListOf() }
input.split(",").forEach {instruction ->
if (instruction.endsWith("-")){
val lens = instruction.split("-")[0]
val hash = asciiHash(lens)
val box = boxes.getValue(hash)
val index = box.indexOfFirst { (l, _) -> l == lens }
if (index != -1) {
box.removeAt(index)
}
} else {
val (lens, focus) = instruction.split("=")
val hash = asciiHash(lens)
val box = boxes.getValue(hash)
val index = box.indexOfFirst { (l, _) -> l == lens }
if (index != -1) {
box[index] = Pair(lens, focus.toInt())
} else{
box.add(Pair(lens, focus.toInt()))
}
}
}
return (0 until 256).sumOf { index ->
boxes.getValue(index)
.mapIndexed{ i, (_, focus) -> (index+1) * (i+1) * focus }
.sum()
}
}
/**
* Hash function:
* start at 0
* Add the ascii code of the next character
* Multiply by 17 then mod 256
* Repeat for each character
*/
private fun asciiHash(input: String): Int {
return input.toCharArray().fold(0){ value, c ->
var output = value + c.code
output *= 17
output % 256
}
}
override fun warmup(input: String) {
part2(input)
}
}
fun main(@Suppress("UNUSED_PARAMETER") args: Array<String>) {
Day15().run()
}
| 0 | Kotlin | 0 | 0 | 90d8a95bf35cae5a88e8daf2cfc062a104fe08c1 | 2,624 | advent2023 | The Unlicense |
src/twentytwo/Day11.kt | Monkey-Matt | 572,710,626 | false | {"Kotlin": 73188} | package twentytwo
import java.util.*
fun main() {
println("Int max = ${Int.MAX_VALUE}")
println("Long max = ${Long.MAX_VALUE}")
println("Short max = ${Short.MAX_VALUE}")
println("Byte max = ${Byte.MAX_VALUE}")
println()
// test if implementation meets criteria from the description, like:
val testInput = readInputLines("Day11_test")
val part1 = part1(testInput)
println(part1)
check(part1 == 10605)
val part2 = part2(testInput)
println(part2)
check(part2 == 2713310158L)
println("---")
val input = readInputLines("Day11_input")
println(part1(input))
println(part2(input))
}
private data class Monkey(
val items: Queue<Long>,
val operation: (Long) -> Long,
val test: (Long) -> Boolean,
val testDivider: Long,
val trueThrowIndex: Int,
val falseThrowIndex: Int,
var inspections: Int = 0,
)
private fun List<String>.toMonkeys(): List<Monkey> {
return this.split("").map { monkeyInput ->
val items = monkeyInput[1]
.substringAfter(" Starting items: ")
.split(", ")
.map { it.toLong() }
val (operator, thing) = monkeyInput[2]
.substringAfter(" Operation: new = old ")
.split(" ")
val operation: (Long) -> Long = { old: Long ->
if (thing == "old") {
when (operator) {
"+" -> old + old
"-" -> 0L
"*" -> old * old
"/" -> old / old
else -> error("unexpected operator $operator")
}
} else {
val thing2 = thing.toLong()
when (operator) {
"+" -> old + thing2
"-" -> old - thing2
"*" -> old * thing2
"/" -> old / thing2
else -> error("unexpected operator $operator")
}
}
}
val testDivider = monkeyInput[3].substringAfter(" Test: divisible by ").toLong()
val test: (Long) -> Boolean = { value ->
value % testDivider == 0L
}
Monkey(
items = items.toQueue(),
operation = operation,
test = test,
testDivider = testDivider,
trueThrowIndex = monkeyInput[4].substringAfter(" If true: throw to monkey ").toInt(),
falseThrowIndex = monkeyInput[5].substringAfter(" If false: throw to monkey ").toInt()
)
}
}
private fun <T> List<T>.toQueue(): Queue<T> {
return LinkedList(this)
}
private fun Monkey.inspectNext(): Long {
val item = this.items.poll()
return this.operation(item)
}
private fun part1(input: List<String>): Int {
val monkeys = input.toMonkeys()
for (roundNum in 1 .. 20) {
monkeys.forEach { monkey ->
while (monkey.items.isNotEmpty()) {
val itemValue = monkey.inspectNext() / 3L
if (monkey.test(itemValue)) {
monkeys[monkey.trueThrowIndex].items.add(itemValue)
} else {
monkeys[monkey.falseThrowIndex].items.add(itemValue)
}
monkey.inspections++
}
}
}
val (a, b) = monkeys.sortedByDescending { it.inspections }.take(2)
return a.inspections * b.inspections
}
private fun part2(input: List<String>): Long {
val monkeys = input.toMonkeys()
// this common divider step I couldn't figure out myself, I had to look up others answers.
// It's required so that the items values don't get too big to calculate.
val commonDivider = monkeys.fold(1L) { a, monkey -> a * monkey.testDivider }
for (roundNum in 1 .. 10_000) {
monkeys.forEach { monkey ->
while (monkey.items.isNotEmpty()) {
val itemValue = (monkey.inspectNext()) % commonDivider
if (monkey.test(itemValue)) {
monkeys[monkey.trueThrowIndex].items.add(itemValue)
} else {
monkeys[monkey.falseThrowIndex].items.add(itemValue)
}
monkey.inspections++
}
}
}
val (a, b) = monkeys.sortedByDescending { it.inspections }.take(2)
return a.inspections.toLong() * b.inspections.toLong()
}
| 1 | Kotlin | 0 | 0 | 600237b66b8cd3145f103b5fab1978e407b19e4c | 4,359 | advent-of-code-solutions | Apache License 2.0 |
src/main/kotlin/com/github/michaelbull/advent2021/day15/ChitonCave.kt | michaelbull | 433,565,311 | false | {"Kotlin": 162839} | package com.github.michaelbull.advent2021.day15
import com.github.michaelbull.advent2021.math.Vector2
import com.github.michaelbull.advent2021.math.Vector2.Companion.CARDINAL_DIRECTIONS
import com.github.michaelbull.advent2021.math.Vector2IntMap
import com.github.michaelbull.advent2021.math.rem
import java.util.PriorityQueue
private val RISK_RANGE = 1..9
fun Sequence<String>.toChitonCave(): ChitonCave {
val map = buildMap {
for ((y, line) in this@toChitonCave.withIndex()) {
for ((x, char) in line.withIndex()) {
val position = Vector2(x, y)
val risk = char.digitToInt()
require(risk in RISK_RANGE) {
"risk at $position must be in range $RISK_RANGE, but was: $risk"
}
set(position, risk)
}
}
}
val width = map.keys.maxOf(Vector2::x) + 1
val height = map.keys.maxOf(Vector2::y) + 1
val riskLevels = Vector2IntMap(width, height, map::getValue)
return ChitonCave(riskLevels)
}
data class ChitonCave(
val riskLevels: Vector2IntMap
) {
val topLeft: Vector2
get() = Vector2.ZERO
val bottomRight: Vector2
get() = Vector2(riskLevels.width - 1, riskLevels.height - 1)
fun lowestTotalRisk(from: Vector2, to: Vector2): Int {
val lowestRiskLevels = Vector2IntMap(riskLevels.width, riskLevels.height) {
if (it == from) 0 else Int.MAX_VALUE
}
val queue = PriorityQueue(compareBy(lowestRiskLevels::get))
queue += from
while (queue.isNotEmpty()) {
val position = queue.poll()
val lowestRiskLevel = lowestRiskLevels[position]
if (position == to) {
return lowestRiskLevel
}
for ((adjacentPosition, adjacentRiskLevel) in adjacentRiskLevels(position)) {
val lowestAdjacentRiskLevel = lowestRiskLevels[adjacentPosition]
val cumulativeRiskLevel = lowestRiskLevel + adjacentRiskLevel
if (cumulativeRiskLevel < lowestAdjacentRiskLevel) {
lowestRiskLevels[adjacentPosition] = cumulativeRiskLevel
queue += adjacentPosition
}
}
}
throw IllegalArgumentException()
}
fun expand(times: Int): ChitonCave {
val width = riskLevels.width
val height = riskLevels.height
val expandedWidth = width * times
val expandedHeight = height * times
val expandedRiskLevels = Vector2IntMap(expandedWidth, expandedHeight) { position ->
val base = position / Vector2(width, height)
val local = position % Vector2(width, height)
val riskLevel = riskLevels[local]
(riskLevel + base.x + base.y) % RISK_RANGE
}
return copy(riskLevels = expandedRiskLevels)
}
private fun adjacentRiskLevels(position: Vector2): Map<Vector2, Int> {
return CARDINAL_DIRECTIONS
.map { position + it }
.filter { it in riskLevels }
.associateWith(riskLevels::get)
}
}
| 0 | Kotlin | 0 | 4 | 7cec2ac03705da007f227306ceb0e87f302e2e54 | 3,143 | advent-2021 | ISC License |
src/main/kotlin/io/undefined/AlienDictionary.kt | jffiorillo | 138,075,067 | false | {"Kotlin": 434399, "Java": 14529, "Shell": 465} | package io.undefined
import io.utils.runTests
import java.util.*
// https://leetcode.com/problems/alien-dictionary/
class AlienDictionary {
fun execute(input: Array<String>): String {
if (input.isEmpty()) return ""
val letters = input.fold(mutableSetOf<Char>()) { acc, word -> acc.apply { word.forEach { add(it) } } }
val maxSize = input.fold(0) { acc, word -> maxOf(acc, word.length) }
val result = mutableListOf<Char>()
var prefix = -1
val implications = mutableSetOf<Pair<Char, Char>>()
while (prefix < maxSize) {
input.groupByPrefix(prefix).forEach { list ->
var index = 0
if (index == list.lastIndex && result.isEmpty()) result.add(list.first())
while (index < list.lastIndex) {
val current = list[index]
val next = list[index + 1]
when {
result.contains(next) && result.contains(current) && result.indexOf(current) > result.indexOf(next) -> {
return ""
}
result.contains(next) && result.contains(current) -> {
}
result.contains(next) -> result.add(result.indexOf(next), current)
result.contains(current) -> result.add(result.indexOf(current) + 1, next)
result.isEmpty() -> {
result.add(current)
result.add(next)
}
else -> {
implications.add(current to next)
}
}
index++
}
}
prefix++
}
when {
implications.size == 1 -> {
implications.first().let { (current, next) ->
when {
result.contains(current) && result.contains(next) -> {
}
result.contains(next) -> result.add(result.indexOf(next), current)
result.contains(current) -> result.add(result.indexOf(current) + 1, next)
else -> {
result.add(current)
result.add(next)
}
}
}
}
implications.isNotEmpty() && result.size < letters.size -> {
var first = true
repeat(2) {
implications.forEach { (current, next) ->
when {
result.contains(current) && result.contains(next) && result.indexOf(current) + 1 != result.indexOf(next) -> {
return ""
}
result.contains(next) -> result.add(result.indexOf(next), current)
result.contains(current) -> result.add(result.indexOf(current) + 1, next)
!first -> {
result.add(current)
result.add(next)
}
}
}
first = false
}
}
}
if (result.size < letters.size) {
letters.filter { !result.contains(it) }.forEach { result.add(it) }
}
return result.joinToString(separator = "") { it.toString() }
}
// https://leetcode.com/problems/alien-dictionary/solution/
fun alienOrder(words: Array<String>): String? {
// Step 0: Create data structures and find all unique letters.
val adjList: MutableMap<Char, MutableList<Char>> = HashMap()
val counts: MutableMap<Char, Int> = HashMap()
for (word in words) {
for (c in word.toCharArray()) {
counts[c] = 0
adjList[c] = ArrayList()
}
}
// Step 1: Find all edges.
for (i in 0 until words.lastIndex) {
val word1 = words[i]
val word2 = words[i + 1]
// Check that word2 is not a prefix of word1.
if (word1.length > word2.length && word1.startsWith(word2)) return ""
// Find the first non match and insert the corresponding relation.
for (j in 0 until minOf(word1.length, word2.length)) {
if (word1[j] != word2[j]) {
adjList.getValue(word1[j]).add(word2[j])
counts[word2[j]] = counts.getValue(word2[j]) + 1
break
}
}
}
// Step 2: Breadth-first search.
val sb = StringBuilder()
val queue: Queue<Char> = LinkedList()
for (c in counts.keys) {
if (counts[c] == 0) {
queue.add(c)
}
}
while (!queue.isEmpty()) {
val c = queue.remove()
sb.append(c)
for (next in adjList.getValue(c)) {
counts[next] = counts.getValue(next) - 1
if (counts[next] == 0) {
queue.add(next)
}
}
}
return if (sb.length < counts.size) "" else sb.toString()
}
}
private fun Array<String>.groupByPrefix(prefixIndex: Int): List<List<Char>> = mutableListOf<MutableList<Char>>().let { result ->
if (this.isEmpty())
return result
var previousPrefix: String? = null
this.forEach { word ->
val range = 0..prefixIndex
when {
prefixIndex + 1 >= word.length -> {
}
previousPrefix == word.substring(range) && result.isNotEmpty() && result.last().last() == word[prefixIndex + 1] -> {
}
previousPrefix == word.substring(range) -> result.last().add(word[prefixIndex + 1])
else -> {
result.add(mutableListOf(word[prefixIndex + 1]))
previousPrefix = word.substring(range)
}
}
}
result
}
fun main() {
runTests(listOf(
arrayOf("wrt",
"wrf",
"er",
"ett",
"rftt") to "wertf",
arrayOf("z", "z") to "z",
arrayOf("zy", "zx") to "zyx",
arrayOf("ab", "adc") to "abdc",
arrayOf("aa","abb","aba") to "",
arrayOf("a", "b", "ca", "cc") to "abc",
arrayOf("za","zb","ca","cb") to "zcab"
)) { (input, value) -> value to AlienDictionary().execute(input) }
} | 0 | Kotlin | 0 | 0 | f093c2c19cd76c85fab87605ae4a3ea157325d43 | 5,553 | coding | MIT License |
src/main/aoc2018/Day12.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2018
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
class Day12(input: List<String>) {
private val initialState = input.first().substringAfter("initial state: ")
private val rules = parseRules(input.drop(2))
private fun parseRules(input: List<String>): Map<String, Char> {
return input.associate { it.substringBefore(" => ") to it.last() }
}
// #..#.#..##......###...###
// ??#..#.#..##......###...###??
private fun getRule(state: String, pos: Int): String {
val range = pos - 2..pos + 2
val numBeforeString = abs(min(range.first, 0))
val numAfterString = max(range.last - (state.length - 1), 0)
val rule = StringBuilder(range.count())
repeat(numBeforeString) {
rule.append('.')
}
rule.append(state.substring(max(0, range.first), min(range.last + 1, state.length)))
repeat(numAfterString) {
rule.append('.')
}
return rule.toString()
}
private fun nextState(state: String): String {
// The amount of pots with plants in can theoretically grow at most 2 in each direction
return Array(state.length + 4) {
rules.getOrDefault(getRule(state, it - 2), '.')
}.joinToString("")
}
private fun getValue(state: String, offset: Int): Int {
return state.withIndex().sumOf { if (it.value == '#') it.index - offset else 0 }
}
private fun grow(): Int {
val generations = 20
var currentState = initialState
var generation = 0
repeat(generations) {
currentState = nextState(currentState)
generation++
}
val offset = 2 * generations
return getValue(currentState, offset)
}
private data class StableGeneration(val generation: Int, val value: Int, val numPots: Int)
private fun findFirstStableGeneration(): StableGeneration {
var currentState = initialState
var generation = 0
var prevLength = 0
var firstOfCurrentLength = 0
var numSameLength = 0
val stable = Array(2) { "" }
while (true) {
currentState = nextState(currentState)
generation++
val length = currentState.substringAfter("#").substringBeforeLast("#").length
if (length == prevLength) {
numSameLength++
if (stable[1] == "") {
stable[1] = currentState
}
if (numSameLength >= 20) {
println("First stable: ${stable[0].substring(2 * firstOfCurrentLength, stable[0].indexOfLast { it == '#' } + 1)}")
println("Second stable: ${stable[1].substring(2 * (firstOfCurrentLength + 1), stable[1].indexOfLast { it == '#' } + 1)}")
// There are a series of pots with some empty spaces between each. For each next generation the pots
// are shifted 1 steps to the right ==> value increases with number of pots for each generation
val numPots = stable[0].count { c -> c == '#' }
val scoreOfFirstStable = getValue(stable[0], 2 * firstOfCurrentLength)
return StableGeneration(firstOfCurrentLength, scoreOfFirstStable, numPots)
}
} else {
firstOfCurrentLength = generation
numSameLength = 0
prevLength = length
stable[0] = currentState
stable[1] = ""
}
}
}
fun solvePart1(): Int {
return grow()
}
fun solvePart2(): Long {
val stable = findFirstStableGeneration()
return (50000000000 - stable.generation) * stable.numPots + stable.value
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 3,810 | aoc | MIT License |
src/Day05.kt | BenHopeITC | 573,352,155 | false | null | fun String.asCreateMove(): Triple<Int, Int, Int> {
val cratesToMove = this.substringAfter("move ").substringBefore(" from ").toInt()
val fromStack = this.substringAfter(" from ").substringBefore(" to ").toInt()
val toStack = this.substringAfter(" to ").toInt()
return Triple(cratesToMove, fromStack, toStack)
}
fun main() {
val day = "Day05"
fun populateStacksWithCrate(stacks: MutableMap<Int, MutableList<String>>, rowOfCrates: String) {
if (rowOfCrates.indexOf(("[")) == -1) return
rowOfCrates.toCharArray().toList().chunked(4).forEachIndexed { i, s ->
val columnId = i + 1
val stack = stacks.getOrDefault(columnId, mutableListOf())
if (s[1].toString() != " ") {
stack.add(0, s[1].toString())
stacks[columnId] = stack
}
}
}
fun moveCreatesOnStacksUsingMover9000(stacks: MutableMap<Int, MutableList<String>>, moveCrates: String) {
val (cratesToMove, fromStack, toStack) = moveCrates.asCreateMove()
val createsToMove = (1..cratesToMove).map { stacks[fromStack]!!.removeLast() }
stacks[toStack]!!.addAll(createsToMove)
// println(stacks)
}
fun moveCreatesOnStacksUsingMover9001(stacks: MutableMap<Int, MutableList<String>>, moveCrates: String) {
val (cratesToMove, fromStack, toStack) = moveCrates.asCreateMove()
val createsToMove = (1..cratesToMove).map { stacks[fromStack]!!.removeLast() }.reversed()
stacks[toStack]!!.addAll(createsToMove)
// println(stacks)
}
fun loadAndMoveCrates(input: List<String>, crateMover: (MutableMap<Int, MutableList<String>>, String) -> Unit): MutableMap<Int, MutableList<String>> {
var parsedCrates = false
val stacks = mutableMapOf<Int, MutableList<String>>()
input.forEach {
when (parsedCrates) {
false -> populateStacksWithCrate(stacks, it)
true -> crateMover(stacks, it) //
}
if (it.isNullOrBlank()) {
parsedCrates = true
}
}
return stacks
}
fun part1(input: List<String>): String {
val stacks = loadAndMoveCrates(input) { stacks, it ->
moveCreatesOnStacksUsingMover9000(stacks, it)
}
// println(stacks)
return stacks.keys.sorted().map { stacks[it]!!.last() }.joinToString("")
}
fun part2(input: List<String>): String {
val stacks = loadAndMoveCrates(input) { stacks, it ->
moveCreatesOnStacksUsingMover9001(stacks, it)
}
// println(stacks)
return stacks.keys.sorted().map { stacks[it]!!.last() }.joinToString("")
}
// test if implementation meets criteria from the description, like:
// val testInput = readInput("${day}_test")
// println(part1(testInput))
// check(part1(testInput) == "CMZ")
// test if implementation meets criteria from the description, like:
// val testInput2 = readInput("${day}_test")
// println(part2(testInput2))
// check(part2(testInput2) == "MCD")
val input = readInput(day)
println(part1(input))
println(part2(input))
check(part1(input) == "TPGVQPFDH")
check(part2(input) == "DMRDFRHHH")
}
| 0 | Kotlin | 0 | 0 | 851b9522d3a64840494b21ff31d83bf8470c9a03 | 3,272 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/g1601_1700/s1617_count_subtrees_with_max_distance_between_cities/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1601_1700.s1617_count_subtrees_with_max_distance_between_cities
// #Hard #Dynamic_Programming #Tree #Bit_Manipulation #Bitmask #Enumeration
// #2023_06_15_Time_297_ms_(100.00%)_Space_38.6_MB_(100.00%)
import kotlin.math.pow
class Solution {
private var ans = 0
private var vis = 0
fun countSubgraphsForEachDiameter(n: Int, edges: Array<IntArray>): IntArray {
ans = 0
vis = 0
val dist = IntArray(n - 1)
val graph: MutableMap<Int, MutableList<Int>> = HashMap()
for (i in edges) {
graph.computeIfAbsent(1 shl i[0] - 1) { initialCapacity: Int? ->
ArrayList(
initialCapacity!!
)
}.add(1 shl i[1] - 1)
graph.computeIfAbsent(1 shl i[1] - 1) { initialCapacity: Int? ->
ArrayList(
initialCapacity!!
)
}.add(1 shl i[0] - 1)
}
val ps = 2.0.pow(n.toDouble()).toInt() - 1
for (set in 3..ps) {
// is power of 2
val isp2 = set != 0 && set and set - 1 == 0
if (!isp2) {
ans = 0
vis = 0
dfs(graph, set, Integer.highestOneBit(set), -1)
if (vis == set) {
dist[ans - 1]++
}
}
}
return dist
}
private fun dfs(graph: Map<Int, MutableList<Int>>, set: Int, c: Int, p: Int): Int {
if (set and c == 0) {
return 0
}
vis = vis or c
var fdist = 0
var sdist = 0
for (i in graph[c]!!) {
if (i != p) {
val dist = dfs(graph, set, i, c)
if (dist > fdist) {
sdist = fdist
fdist = dist
} else {
sdist = sdist.coerceAtLeast(dist)
}
}
}
ans = ans.coerceAtLeast(fdist + sdist)
return 1 + fdist
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,009 | LeetCode-in-Kotlin | MIT License |
kotlin/src/katas/kotlin/leetcode/minimum_path_sum/MinPathSum.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.leetcode.minimum_path_sum
import datsok.shouldEqual
import org.junit.jupiter.api.Test
//
// Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right,
// which minimizes the sum of all numbers along its path.
// Note: You can only move either down or right at any point in time.
//
// m == grid.length
// n == grid[i].length
// 1 <= m, n <= 200
// 0 <= grid[i][j] <= 100
//
// https://leetcode.com/problems/minimum-path-sum ✅
//
class MinPathSum {
@Test fun `Example 1`() {
val grid = arrayOf(
intArrayOf(1, 3, 1),
intArrayOf(1, 5, 1),
intArrayOf(4, 2, 1)
)
findMinSumPath(grid) shouldEqual listOf(1, 3, 1, 1, 1)
minPathSum(grid) shouldEqual 7
}
@Test fun `Example 2`() {
val grid = arrayOf(
intArrayOf(1, 2, 3),
intArrayOf(4, 5, 6)
)
findMinSumPath(grid) shouldEqual listOf(1, 2, 3, 6)
minPathSum(grid) shouldEqual 12
}
@Test fun `empty grid`() {
findMinSumPath(grid = arrayOf()) shouldEqual emptyList()
}
@Test fun `single cell grid`() {
findMinSumPath(grid = arrayOf(intArrayOf(1))) shouldEqual listOf(1)
}
@Test fun `one row grid`() {
findMinSumPath(grid = arrayOf(
intArrayOf(1, 2, 3)
)) shouldEqual listOf(1, 2, 3)
}
@Test fun `one column grid`() {
findMinSumPath(grid = arrayOf(
intArrayOf(1),
intArrayOf(2),
intArrayOf(3),
)) shouldEqual listOf(1, 2, 3)
}
@Test fun `200x200 grid`() {
findMinSumPath(grid = Array(size = 200) {
IntArray(200) { 1 }
}) shouldEqual List(200 + 199) { 1 }
}
private fun minPathSum(grid: Array<IntArray>): Int = findMinSumPath(grid).sum()
private fun findMinSumPath(
grid: Array<IntArray>,
x: Int = 0,
y: Int = 0,
cache: HashMap<Pair<Int, Int>, List<Int>> = HashMap()
): List<Int> {
if (grid.isEmpty()) return emptyList()
if (cache[Pair(x, y)] != null) return cache[Pair(x, y)]!!
val maxX = grid.first().size - 1
val maxY = grid.size - 1
if (x == maxX && y == maxY) return listOf(grid[y][x])
val pathRight = if (x + 1 <= maxX) findMinSumPath(grid, x + 1, y, cache) else null
val pathDown = if (y + 1 <= maxY) findMinSumPath(grid, x, y + 1, cache) else null
val minPath = listOf(grid[y][x]) + listOfNotNull(pathRight, pathDown).minBy { it.sum() }
cache[Pair(x, y)] = minPath
return minPath
}
} | 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 2,632 | katas | The Unlicense |
src/main/kotlin/de/jball/aoc2022/day07/Day07.kt | fibsifan | 573,189,295 | false | {"Kotlin": 43681} | package de.jball.aoc2022.day07
import de.jball.aoc2022.Day
class Day07(test: Boolean = false): Day<Long>(test, 95437, 24933642) {
private val rootDir = Directory(mutableMapOf())
private val allDirs = mutableMapOf<String, Directory>()
private val rom = 70000000L
private val needed = 30000000L
init {
allDirs["/"] = rootDir
var currentPath = ""
var currentDirectory: Directory = rootDir
val listings = input.joinToString("|")
.split("|$ ls|")
.map { it.split("|") }
listings.forEach { listing ->
listing.forEach { line ->
if (line.startsWith("\$ cd")) {
val suffix = line.substringAfter("\$ cd ")
if (suffix == "..") {
currentPath = currentPath.substringBeforeLast("/").substringBeforeLast("/").plus("/")
currentDirectory = allDirs[currentPath]!!
} else {
val oldDirectory = allDirs[currentPath]
currentPath += if (suffix != "/") "${suffix}/" else suffix
currentDirectory = allDirs.computeIfAbsent(currentPath) { Directory(mutableMapOf()) }
oldDirectory?.contents?.put(suffix, currentDirectory)
}
} else if (!line.startsWith("dir")) {
val match = Regex("(\\d+) (.*)$").find(line)!!.groups.map { it!!.value }
val size = match[1].toLong()
val name = match[2]
currentDirectory.contents[name] = File(size)
}
}
}
}
override fun part1(): Long {
return allDirs.values.filter { it.getSize() <= 100000 }.sumOf { it.getSize() }
}
override fun part2(): Long {
val used = rootDir.getSize()
val unused = rom - used
val toFree = needed - unused
return allDirs.values.filter { it.getSize() >= toFree }.minOf { it.getSize() }
}
}
sealed interface Sized {
fun getSize(): Long
}
class File(private val size: Long): Sized {
override fun getSize(): Long {
return size
}
}
class Directory(val contents: MutableMap<String, Sized>): Sized {
override fun getSize(): Long {
return contents.values.sumOf { it.getSize() }
}
}
fun main() {
Day07().run()
}
| 0 | Kotlin | 0 | 3 | a6d01b73aca9b54add4546664831baf889e064fb | 2,403 | aoc-2022 | Apache License 2.0 |
src/day01/Day01.kt | ivanovmeya | 573,150,306 | false | {"Kotlin": 43768} | package day01
import readInput
fun main() {
fun computeElfCalories(
i: Int,
input: List<String>
): Pair<Int, Int> {
var i1 = i
var currentElfCalories = 0
while (i1 < input.size && input[i1].isNotEmpty() && input[i1].isNotBlank()) {
currentElfCalories += input[i1].toInt()
i1++
}
return currentElfCalories to i1
}
//O(n)
fun part1(input: List<String>): Int {
if (input.isEmpty()) return -1
var maxCalories = 0
var i = 0
while (i < input.size) {
val (currentElfCalories, iEnd) = computeElfCalories(i, input)
i = iEnd
if (currentElfCalories > maxCalories) {
maxCalories = currentElfCalories
}
i++
}
return maxCalories
}
//O(n)
fun part2(input: List<String>): Int {
if (input.isEmpty()) return -1
val topThreeMaxCalories = IntArray(3) { 0 }
var i = 0
while (i < input.size) {
val (currentElfCalories, iEnd) = computeElfCalories(i, input)
i = iEnd
when {
(currentElfCalories > topThreeMaxCalories[0]) -> {
topThreeMaxCalories[2] = topThreeMaxCalories[1]
topThreeMaxCalories[1] = topThreeMaxCalories[0]
topThreeMaxCalories[0] = currentElfCalories
}
(currentElfCalories > topThreeMaxCalories[1] && currentElfCalories != topThreeMaxCalories[0]) -> {
topThreeMaxCalories[2] = topThreeMaxCalories[1]
topThreeMaxCalories[1] = currentElfCalories
}
(currentElfCalories > topThreeMaxCalories[2] && currentElfCalories != topThreeMaxCalories[1]) -> {
topThreeMaxCalories[2] = currentElfCalories
}
}
i++
}
return topThreeMaxCalories.sum()
}
val testInput = readInput("day01/Day01_test")
val test1Result = part1(testInput)
val test2Result = part2(testInput)
println(test1Result)
println(test2Result)
check(test1Result == 24000)
check(test2Result == 45000)
val input = readInput("day01/day01")
check(part1(input) == 74198)
check(part2(input) == 209914)
} | 0 | Kotlin | 0 | 0 | 7530367fb453f012249f1dc37869f950bda018e0 | 2,351 | advent-of-code-2022 | Apache License 2.0 |
app/src/main/kotlin/aoc2019/day02/Day02.kt | dbubenheim | 499,817,652 | false | {"Kotlin": 20151} | package aoc2019.day02
import aoc2019.day02.Addresses.NOUN
import aoc2019.day02.Addresses.VERB
import aoc2019.day02.OpcCode.*
import aoc2019.toFile
/*
1,0,0,0,99 becomes 2,0,0,0,99 (1 + 1 = 2).
2,3,0,3,99 becomes 2,3,0,6,99 (3 * 2 = 6).
2,4,4,5,99,0 becomes 2,4,4,5,99,9801 (99 * 99 = 9801).
1,1,1,4,99,5,6,0,99 becomes 30,1,1,4,2,5,6,0,99.
*/
fun part1(): Int {
val numbers = "input-day02.txt".toFile()
.readLines()
.first()
.split(",")
.map { it.toInt() }
.toMutableList()
.apply { this[NOUN.value] = 12; this[VERB.value] = 2 }
println("numbers: $numbers")
val intCodes = numbers
.windowed(size = 4, step = 4)
.map { it.toIntCode() }
.takeWhile { it.calc(numbers) }
println("intCodes: $intCodes")
return numbers.first()
}
fun part2(): Int {
val numbers = "input-day02.txt".toFile()
.readLines()
.first()
.split(",")
.map { it.toInt() }
.toMutableList()
println("numbers: $numbers")
(0..99).forEach { noun ->
(0..99).forEach { verb ->
val list = numbers.toMutableList()
list.apply { this[NOUN.value] = noun; this[VERB.value] = verb }
.windowed(size = 4, step = 4)
.map { it.toIntCode() }
.takeWhile { it.calc(list) }
if (list.first() == 19690720) {
println("list: $list")
println("noun: $noun")
println("verb: $verb")
return 100 * noun + verb
}
}
}
return 0
}
fun main() {
val part1 = part1()
println("part1: $part1")
val part2 = part2()
println("part2: $part2")
}
fun List<Int>.toIntCode() = IntCode(opCode(), this[1], this[2], this[3])
private fun List<Int>.opCode() = OpcCode.fromInt(this[0])
data class IntCode(val opcode: OpcCode, val input1: Int, val input2: Int, val output: Int) {
fun calc(numbers: MutableList<Int>): Boolean {
return when (opcode) {
CODE_1 -> {
numbers[output] = numbers[input1] + numbers[input2]
true
}
CODE_2 -> {
numbers[output] = numbers[input1] * numbers[input2]
true
}
CODE_99 -> false
}
}
}
enum class OpcCode(val value: Int) {
CODE_1(1),
CODE_2(2),
CODE_99(99);
companion object {
fun fromInt(value: Int) = OpcCode.values().firstOrNull { it.value == value }
?: throw IllegalArgumentException("Illegal OpCode: $value")
}
}
enum class Addresses(val value: Int) {
NOUN(1),
VERB(2);
companion object {
fun fromInt(value: Int) = Addresses.values().firstOrNull { it.value == value }
?: throw IllegalArgumentException("Illegal Address: $value")
}
} | 8 | Kotlin | 0 | 0 | f761d923d8c7c317bd93336163a2d4f86bf16340 | 2,862 | advent-of-code-2019 | MIT License |
src/Day03.kt | bin-wang | 572,801,360 | false | {"Kotlin": 19395} | fun main() {
fun Char.toPriority() = when (this) {
in 'a'..'z' -> this - 'a' + 1
in 'A'..'Z' -> this - 'A' + 27
else -> error("unexpected input: $this")
}
fun part1(input: List<String>): Int {
return input.sumOf {
val item1 = it.slice(0 until it.length / 2)
val item2 = it.slice(it.length / 2 until it.length)
val commonItem = item1.toSet().intersect(item2.toSet()).first().toChar()
commonItem.toPriority()
}
}
fun part2(input: List<String>): Int {
return input.chunked(3).sumOf { elves ->
elves.map { it.toSet() }.reduce(Set<Char>::intersect).first().toPriority()
}
}
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 | dca2c4915594a4b4ca2791843b53b71fd068fe28 | 915 | aoc22-kt | Apache License 2.0 |
src/Day20.kt | fonglh | 573,269,990 | false | {"Kotlin": 48950, "Ruby": 1701} | fun main() {
data class InputNumber(val originalIndex: Int, val value: Long)
fun numberAt(input: List<InputNumber>, positionFromZero: Int): Long {
// find position of 0
var zeroIndex = 0
for (i in input.indices) {
if (input[i].value == 0.toLong()) {
zeroIndex = i
break
}
}
return input[(zeroIndex+positionFromZero)%input.size].value
}
fun part1(input: List<String>): Int {
val inputNumbers = input.mapIndexed { idx, value -> InputNumber(idx, value.toLong()) }
val inputSize = inputNumbers.size
var outputNumbers = inputNumbers.toMutableList()
inputNumbers.forEach {
val currIndex = outputNumbers.indexOf(it)
var newIndex = (currIndex + it.value)
if (newIndex <= 0) {
// quotient is negative
val quotient = newIndex / (inputSize-1)
newIndex += (-quotient+1) * (inputSize-1)
}
if (newIndex >= inputSize) {
newIndex %= (inputSize-1)
}
outputNumbers.removeAt(currIndex)
outputNumbers.add(newIndex.toInt(), it)
}
return (numberAt(outputNumbers, 1000) +
numberAt(outputNumbers, 2000) +
numberAt(outputNumbers, 3000)).toInt()
}
fun part2(input: List<String>): Long {
val inputNumbers = input.mapIndexed { idx, value -> InputNumber(idx, value.toLong() * 811589153.toLong()) }
val inputSize = inputNumbers.size
var outputNumbers = inputNumbers.toMutableList()
repeat(10) {
inputNumbers.forEach {
val currIndex = outputNumbers.indexOf(it)
var newIndex = (currIndex.toLong() + it.value)
if (newIndex <= 0) {
// quotient is negative
val quotient = newIndex / (inputSize-1).toLong()
newIndex += (-quotient+1.toLong()) * (inputSize-1).toLong()
}
if (newIndex >= inputSize) {
newIndex %= (inputSize-1).toLong()
}
outputNumbers.removeAt(currIndex)
outputNumbers.add(newIndex.toInt(), it)
}
}
return (numberAt(outputNumbers, 1000) +
numberAt(outputNumbers, 2000) +
numberAt(outputNumbers, 3000))
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day20_test")
check(part1(testInput) == 3)
check(part2(testInput) == 1623178306.toLong())
val input = readInput("Day20")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ef41300d53c604fcd0f4d4c1783cc16916ef879b | 2,757 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | cvb941 | 572,639,732 | false | {"Kotlin": 24794} | enum class Response {
ROCK, PAPER, SCISSORS;
fun score(): Int {
return when (this) {
ROCK -> 1
PAPER -> 2
SCISSORS -> 3
}
}
fun matchPointsAgainst(opponent: Response): Int {
return when (this) {
ROCK -> when (opponent) {
ROCK -> 3
PAPER -> 0
SCISSORS -> 6
}
PAPER -> {
when (opponent) {
ROCK -> 6
PAPER -> 3
SCISSORS -> 0
}
}
SCISSORS -> {
when (opponent) {
ROCK -> 0
PAPER -> 6
SCISSORS -> 3
}
}
}
}
companion object {
fun from(input: Char): Response {
return when (input) {
'A' -> ROCK
'B' -> PAPER
'C' -> SCISSORS
'X' -> ROCK
'Y' -> PAPER
'Z' -> SCISSORS
else -> throw IllegalArgumentException("Invalid input: $input")
}
}
}
fun responseAgainst(wantedResult: Char): Response {
return when (this) {
ROCK -> when (wantedResult) {
'X' -> SCISSORS
'Y' -> ROCK
'Z' -> PAPER
else -> throw IllegalArgumentException("Invalid input: $wantedResult")
}
PAPER -> {
when (wantedResult) {
'X' -> ROCK
'Y' -> PAPER
'Z' -> SCISSORS
else -> throw IllegalArgumentException("Invalid input: $wantedResult")
}
}
SCISSORS -> {
when (wantedResult) {
'X' -> PAPER
'Y' -> SCISSORS
'Z' -> ROCK
else -> throw IllegalArgumentException("Invalid input: $wantedResult")
}
}
}
}
}
fun main() {
fun part1(input: List<String>): Int {
return input.map {
val (them, you) = it.split(" ").map { Response.from(it.first()) }
you.score() + you.matchPointsAgainst(them)
}.sum()
}
fun part2(input: List<String>): Int {
return input.map {
val (themChar, youChar) = it.split(" ").map { it.first() }
val them = Response.from(themChar)
val you = them.responseAgainst(youChar)
you.score() + you.matchPointsAgainst(them)
}.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | fe145b3104535e8ce05d08f044cb2c54c8b17136 | 2,930 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day04.kt | slawa4s | 573,050,411 | false | {"Kotlin": 20679} | fun main() {
fun getPairFromInput(arg: String): Pair<Int, Int> {
val splitByTwo = arg.split('-')
return Pair(Integer.parseInt(splitByTwo[0]), Integer.parseInt(splitByTwo[1]))
}
fun checkOneRangeInsideAnother(firstRange: Pair<Int, Int>, secondRange: Pair<Int, Int>): Boolean =
(firstRange.first >= secondRange.first) and (firstRange.second <= secondRange.second) ||
(secondRange.first >= firstRange.first) and (secondRange.second <= firstRange.second)
fun checkOneRangeOverlapAnother(firstRange: Pair<Int, Int>, secondRange: Pair<Int, Int>): Boolean =
(firstRange.first >= secondRange.first) and (firstRange.first <= secondRange.second) ||
(firstRange.second >= secondRange.first) and (firstRange.second <= secondRange.second) ||
checkOneRangeInsideAnother(firstRange, secondRange)
fun part1(input: List<List<String>>): Int = input
.count {
checkOneRangeInsideAnother(getPairFromInput(it[0]), getPairFromInput(it[1]))
}
fun part2(input: List<List<String>>): Int = input
.count {
checkOneRangeOverlapAnother(getPairFromInput(it[0]), getPairFromInput(it[1]))
}
val input = readInput("Day04").map { it.split(",") }
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | cd8bbbb3a710dc542c2832959a6a03a0d2516866 | 1,312 | aoc-2022-in-kotlin | Apache License 2.0 |
y2020/src/main/kotlin/adventofcode/y2020/Day23.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2020
import adventofcode.io.AdventSolution
fun main() = Day23.solve()
object Day23 : AdventSolution(2020, 23, "Crab Cups")
{
override fun solvePartOne(input: String): Any
{
val nextCup = shuffle(parse(input), 9, 100)
return generateSequence(1) { nextCup[it] }.drop(1).takeWhile { it != 1 }.joinToString("")
}
override fun solvePartTwo(input: String): Any
{
val nextCup = shuffle(parse(input), 1_000_000, 10_000_000)
return nextCup[1].toLong() * nextCup[nextCup[1]].toLong()
}
private fun parse(input: String) = input.map(Char::toString).map(String::toInt)
private fun shuffle(input: List<Int>, size: Int, steps: Int): IntArray
{
val nextCup = IntArray(size + 1) { it + 1 }
nextCup[nextCup.lastIndex] = input[0]
for ((c, n) in input.zipWithNext()) nextCup[c] = n
nextCup[input.last()] = if (nextCup.lastIndex> input.size) input.size + 1 else input.first()
var current = input[0]
repeat(steps) {
val a = nextCup[current]
val b = nextCup[a]
val c = nextCup[b]
nextCup[current] = nextCup[c]
fun lower(i: Int) = if (i == 1) nextCup.lastIndex else i - 1
var target = lower(current)
while (target == a || target == b || target == c) target = lower(target)
nextCup[c] = nextCup[target]
nextCup[target] = a
current = nextCup[current]
}
return nextCup
}
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,535 | advent-of-code | MIT License |
src/Day01.kt | ElenaRgC | 572,898,962 | false | null | fun main() {
fun part1(input: List<String>): Int {
var suma = 0
var sumaMayor = 0
for (i in input) {
if (i == "") {
if (suma > sumaMayor) {
sumaMayor = suma
}
suma = 0
} else {
suma += i.toInt()
}
}
return sumaMayor
}
fun part2(input: List<String>): Int {
var nuevaSuma = 0
var sumaMayor = 0
var segundaMayor = 0
var terceraMayor = 0
for (i in input) {
if (i == "") {
if (nuevaSuma > sumaMayor) {
terceraMayor = segundaMayor
segundaMayor = sumaMayor
sumaMayor = nuevaSuma
} else if (nuevaSuma > segundaMayor) {
terceraMayor = segundaMayor
segundaMayor = nuevaSuma
} else if (nuevaSuma > terceraMayor) {
terceraMayor = nuevaSuma
}
nuevaSuma = 0
} else {
nuevaSuma += i.toInt()
}
}
return sumaMayor + segundaMayor + terceraMayor
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b7505e891429970c377f7b45bfa8b5157f85c457 | 1,466 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/github/pjozsef/randomtree/RandomTree.kt | pjozsef | 239,387,655 | false | null | package com.github.pjozsef.randomtree
import com.github.pjozsef.WeightedDie
import java.util.*
data class DicePoolNode<T>(
val dicePool: List<Number>,
val branches: List<RandomTree<T>>,
val random: Random = Random()
) : RandomTree<T> {
override val values: List<T>
get() = dicePool.mapIndexed { i, it ->
Roll(
i,
it.toInt(),
random.nextInt(it.toInt()) + 1
)
}.reduce { acc, curr ->
when {
curr.value > acc.value -> curr
curr.value == acc.value && curr.type > acc.type -> curr
else -> acc
}
}.let {
listOf(branches[it.index].value)
}
}
data class RandomNode<T>(
val weights: List<Number>,
val branches: List<RandomTree<T>>,
val random: Random = Random()
) : RandomTree<T> {
val weightedDie = WeightedDie(
this.branches,
this.weights,
this.random
)
override val values: List<T>
get() = listOf(weightedDie.roll().value)
}
data class RepeaterNode<T>(
val repeater: Repeater,
val node: RandomTree<T>
) : RandomTree<T> {
override val values: List<T>
get() = (1..repeater.getAmount()).map { node.value }
}
data class CompositeNode<T>(
val components: Map<String, RandomTree<T>>,
val combiner: (Map<String, T>) -> T
) : RandomTree<T> {
override val values: List<T>
get() = listOf(components.mapValues { (_, v) -> v.value }.let(combiner))
}
data class LeafNode<T>(val leafValue: T) : RandomTree<T> {
override val values: List<T>
get() = listOf(leafValue)
}
data class TreeCollection<T>(val trees: List<RandomTree<T>>) : RandomTree<T> {
override val values: List<T>
get() = trees.flatMap { it.values }
}
sealed interface RandomTree<T> {
val values: List<T>
val value: T
get() = values.first()
}
private data class Roll(
val index: Int,
val type: Int,
val value: Int
)
| 0 | Kotlin | 0 | 0 | 47a83a62ed1ad4c7e3ebe9d53c49521b8bacabfc | 2,021 | RandomTree | MIT License |
src/Day04.kt | wujingwe | 574,096,169 | false | null | fun main() {
infix fun IntRange.contains(other: IntRange): Boolean {
return this.first <= other.first && this.last >= other.last
}
fun part1(inputs: List<String>): Int {
return inputs.count { s ->
val (a, b) = s.split(",")
val (a1, a2) = a.split("-")
val (b1, b2) = b.split("-")
val range1 = a1.toInt()..a2.toInt()
val range2 = b1.toInt()..b2.toInt()
range1 contains range2 || range2 contains range1
}
}
fun part2(inputs: List<String>): Int {
return inputs.count { s ->
val (a, b) = s.split(",")
val (a1, a2) = a.split("-")
val (b1, b2) = b.split("-")
val range1 = a1.toInt()..a2.toInt()
val range2 = b1.toInt()..b2.toInt()
(range1 intersect range2).isNotEmpty()
}
}
val testInput = readInput("../data/Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("../data/Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a5777a67d234e33dde43589602dc248bc6411aee | 1,097 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/aoc2022/Day8.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2022
import Grid
import Pos
import kotlin.math.max
class Day8(input: List<String>) {
private val forrest = Grid.parse(input)
/**
* Get a list of 4 lists, one for each direction. Each list contains the positions
* of all the trees in the given direction, starting from closest to the star tree
* and ending with the tree the furthest away. Trees on the edge have at least one
* empty list (since there are no trees further out).
*/
private fun allTreesInAllDirections(fromTree: Pos): List<List<Pos>> {
return listOf(
(fromTree.y - 1 downTo 0).map { Pos(fromTree.x, it) }, // up
(fromTree.y + 1 until forrest.size).map { Pos(fromTree.x, it) }, //down
(fromTree.x - 1 downTo 0).map { Pos(it, fromTree.y) }, // left
(fromTree.x + 1 until forrest.size).map { Pos(it, fromTree.y) } // right
)
}
/**
* Return the number of trees that are visible in the given list. No trees beyond the
* first tree with a height larger or equal to the ownHeight is visible.
*/
private fun List<Pos>.numVisible(ownHeight: Char): Int {
var visible = 0
for (tree in this) {
val otherHeight = forrest[tree]
if (otherHeight < ownHeight) {
visible++
} else {
return visible + 1
}
}
return visible
}
fun solvePart1(): Int {
var visible = 0
for (tree in forrest.keys) {
// all on an empty list returns true, which means trees on the edge is visible
if (allTreesInAllDirections(tree).any { dir -> dir.all { forrest[tree] > forrest[it] } }) {
visible++
}
}
return visible
}
fun solvePart2(): Int {
var bestScore = 0
for (tree in forrest.keys) {
// Trees on the edge will have at least one empty list which results in a score of 0
bestScore = max(
bestScore,
allTreesInAllDirections(tree).fold(1) { acc, trees -> acc * trees.numVisible(forrest[tree]) })
}
return bestScore
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 2,191 | aoc | MIT License |
src/Day05.kt | arisaksen | 573,116,584 | false | {"Kotlin": 42887} | import org.assertj.core.api.Assertions.assertThat
// https://adventofcode.com/2022/day/5
fun main() {
fun part1(input: String): String {
val (stackData, moves) = input.split("\n\n")
val stacks: List<ArrayDeque<String>> = stackData.toStacks()
moves.lines().forEach {
val number = it.split(" ")[1].toInt()
val moveFrom = it.split(" ")[3].toInt() - 1
val moveTo = it.split(" ").last().toInt() - 1
for (i in 1..number) {
val poped = stacks[moveFrom].pop()
stacks[moveTo].push(poped)
}
}
stacks.forEach {
println("stack ${it.peek()}")
}
return stacks.map { it.peek()[1] }.joinToString("")
}
fun part2(input: String): String {
val (stackData, moves) = input.split("\n\n")
val stacks: List<ArrayDeque<String>> = stackData.toStacks()
moves.lines().forEach {
var numbers = """\d+\w""".toRegex() // hint: d1aagfgf alt+enter matches '1a'
var number = it.split(" ")[1].toInt() // use raw string """ """ for regex
val moveFrom = it.split(" ")[3].toInt() - 1
val moveTo = it.split(" ").last().toInt() - 1
val tmpStack = ArrayDeque<String>()
println("move $number from ${moveFrom + 1} to ${moveTo + 1}")
if (number == 1 && moveFrom == 6) {
println()
}
println("stack ${moveFrom + 1}: ${stacks[moveFrom]}")
println("stack ${moveTo + 1}: ${stacks[moveTo]}")
for (i in number downTo 1) {
tmpStack.push(stacks[moveFrom].pop())
if (tmpStack.size == number) {
println()
while (tmpStack.size > 0) {
stacks[moveTo].push(tmpStack.pop())
number--
}
println("stack ${moveFrom + 1}: ${stacks[moveFrom]}")
println("stack ${moveTo + 1}: ${stacks[moveTo]}")
}
}
repeat(20) { print(".") }
println()
}
return stacks.map { it.peek()[1] }.joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = readText("Day05_test")
assertThat(part1(testInput)).isEqualTo("CMZ")
assertThat(part2(testInput)).isEqualTo("MCD")
// print the puzzle answer
val input = readText("Day05")
println(part1(input))
println(part2(input))
}
fun String.toStacks(): List<ArrayDeque<String>> {
val cargo =
this
.lines()
.dropLast(1)
.reversed()
.map { it.chunked(4) }
val stacks = List(cargo.first().size) { ArrayDeque<String>() }
cargo.map {
it.forEachIndexed { index, element ->
if (element.isNotBlank())
stacks[index].add(element)
}
}
return stacks
}
fun ArrayDeque<String>.push(element: String) = this.addLast(element)
fun ArrayDeque<String>.pop() = this.removeLast()
fun ArrayDeque<String>.peek() = this.last()
| 0 | Kotlin | 0 | 0 | 85da7e06b3355f2aa92847280c6cb334578c2463 | 3,187 | aoc-2022-kotlin | Apache License 2.0 |
src/day09/Day09.kt | tobihein | 569,448,315 | false | {"Kotlin": 58721} | package day09
import readInput
class Day09 {
fun part1(): Int {
val readInput = readInput("day09/input")
return part1(readInput)
}
fun part2(): Int {
val readInput = readInput("day09/input")
return part2(readInput)
}
fun part1(input: List<String>): Int = calculateResult(input, 1)
fun part2(input: List<String>): Int = calculateResult(input, 9)
private fun calculateResult(input: List<String>, tailLength: Int): Int {
var head = Pair(0, 0)
val tails = initTails(tailLength)
val result = mutableSetOf<Pair<Int, Int>>(tails[tailLength - 1])
input.forEach {
val inputs = it.split(" ")
val direction = getDirection(inputs[0])
val times = inputs[1].toInt()
for (i in 0 until times) {
head = moveHead(head, direction)
var predecessor = head
for (idx in 0 until tails.size) {
tails[idx] = moveTail(tails[idx], predecessor)
predecessor = tails[idx]
}
if (!result.contains(tails[tailLength - 1])) {
result.add(tails[tailLength - 1])
}
}
}
return result.size
}
private fun initTails(tailLength: Int): Array<Pair<Int, Int>> {
return Array<Pair<Int, Int>>(tailLength) { Pair(0, 0) }
}
private fun getDirection(input: String): Pair<Int, Int> {
when (input) {
"U" -> return Pair(0, 1)
"D" -> return Pair(0, -1)
"R" -> return Pair(1, 0)
"L" -> return Pair(-1, 0)
}
throw IllegalArgumentException("Unknown direction $input")
}
private fun moveHead(head: Pair<Int, Int>, direction: Pair<Int, Int>): Pair<Int, Int> =
Pair(head.first + direction.first, head.second + direction.second)
private fun moveTail(tail: Pair<Int, Int>, head: Pair<Int, Int>): Pair<Int, Int> {
var newTail = tail
val distX = head.first - tail.first
val distY = head.second - tail.second
if (Math.abs(distX) == 2 || Math.abs(distY) == 2) {
var newX = tail.first + distX
var newY = tail.second + distY
if (distX == 2) {
newX = tail.first + 1
} else if (distX == -2) {
newX = tail.first - 1
}
if (distY == 2) {
newY = tail.second + 1
} else if (distY == -2) {
newY = tail.second - 1
}
newTail = Pair(newX, newY)
}
return newTail
}
}
| 0 | Kotlin | 0 | 0 | af8d851702e633eb8ff4020011f762156bfc136b | 2,659 | adventofcode-2022 | Apache License 2.0 |
src/main/java/challenges/educative_grokking_coding_interview/k_way_merge/_3/FindKPairs.kt | ShabanKamell | 342,007,920 | false | null | package challenges.educative_grokking_coding_interview.k_way_merge._3
import challenges.util.PrintHyphens
import java.util.Arrays
import java.util.PriorityQueue
import java.util.ArrayList
/**
Given two lists and an integer k, find k
pairs of numbers with the smallest sum so that in each pair, each list contributes one number to the pair.
https://www.educative.io/courses/grokking-coding-interview-patterns-java/3jrDWvArpgn
*/
internal class Pair(var sum: Int, var i: Int, var j: Int)
internal object FindKPairs {
private fun kSmallestPairs(list1: IntArray, list2: IntArray, k: Int): List<List<Int>> {
val pairs: MutableList<List<Int>> = ArrayList()
// storing the length of lists to use it in a loop later
val listLength = list1.size
// declaring a min-heap to keep track of the smallest sums
val minHeap = PriorityQueue { a: Pair, b: Pair -> a.sum - b.sum }
// iterate over the length of list 1
for (i in 0 until Math.min(k, listLength)) {
// computing sum of pairs all elements of list1 with first index
// of list2 and placing it in the min-heap
minHeap.add(Pair(list1[i] + list2[0], i, 0))
}
var counter = 1
// iterate over elements of min-heap and only go upto k
while (!minHeap.isEmpty() && counter <= k) {
// placing sum of the top element of min-heap
// and its corresponding pairs in i and j
val pair = minHeap.poll()
val i = pair.i
val j = pair.j
// add pairs with the smallest sum in the new list
pairs.add(Arrays.asList(list1[i], list2[j]))
// increment the index for 2nd list, as we've
// compared all possible pairs with the 1st index of list2
val nextElement = j + 1
// if next element is available for list2 then add it to the heap
if (list2.size > nextElement) {
minHeap.add(Pair(list1[i] + list2[nextElement], i, nextElement))
}
counter++
}
// return the pairs with the smallest sums
return pairs
}
@JvmStatic
fun main(args: Array<String>) {
val list1 = arrayOf(
intArrayOf(2, 8, 9),
intArrayOf(1, 2, 300),
intArrayOf(1, 1, 2),
intArrayOf(4, 6),
intArrayOf(4, 7, 9),
intArrayOf(1, 1, 2)
)
val list2 = arrayOf(
intArrayOf(1, 3, 6),
intArrayOf(1, 11, 20, 35, 300),
intArrayOf(1, 2, 3),
intArrayOf(2, 3),
intArrayOf(4, 7, 9),
intArrayOf(1)
)
val k = intArrayOf(9, 30, 1, 2, 5, 4)
for (i in k.indices) {
val result = kSmallestPairs(list1[i], list2[i], k[i])
print(i + 1)
println(".\tInput lists: " + Arrays.toString(list1[i]) + ", " + Arrays.toString(list2[i]))
println("\tK = " + k[i])
print("\tPairs with smallest sum are: $result")
println("\n")
System.out.println(PrintHyphens.repeat("-", 100))
}
}
} | 0 | Kotlin | 0 | 0 | ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70 | 3,164 | CodingChallenges | Apache License 2.0 |
src/main/kotlin/at/mpichler/aoc/solutions/year2021/Day08.kt | mpichler94 | 656,873,940 | false | {"Kotlin": 196457} | package at.mpichler.aoc.solutions.year2021
import at.mpichler.aoc.lib.Day
import at.mpichler.aoc.lib.PartSolution
open class Part8A : PartSolution() {
lateinit var signalPatterns: List<MutableList<String>>
lateinit var outputs: List<List<String>>
override fun parseInput(text: String) {
val lines = text.split("\n")
val signalPatterns = mutableListOf<MutableList<String>>()
val outputs = mutableListOf<List<String>>()
for (row in lines) {
val parts = row.split(" | ")
val patterns = parts[0].split(' ').map { it.toCharArray().sorted().joinToString(separator = "") }
val rowOutputs = parts[1].split(' ').map { it.toCharArray().sorted().joinToString(separator = "") }
signalPatterns.add(patterns.toMutableList())
outputs.add(rowOutputs)
}
this.signalPatterns = signalPatterns
this.outputs = outputs
}
override fun compute(): Int {
var count = 0
for (row in outputs) {
for (output in row) {
val length = output.length
if (length < 5 || length == 7) {
count += 1
}
}
}
return count
}
override fun getExampleAnswer(): Int {
return 26
}
override fun getExampleInput(): String? {
return """
be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe
edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc
fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef | cg cg fdcagb cbg
fbegcd cbd adcefb dageb afcb bc aefdc ecdab fgdeca fcdbega | efabcd cedba gadfec cb
aecbfdg fbg gf bafeg dbefa fcge gcbea fcaegb dgceab fcbdga | gecf egdcabf bgf bfgea
fgeab ca afcebg bdacfeg cfaedg gcfdb baec bfadeg bafgc acf | gebdcfa ecba ca fadegcb
dbcfg fgd bdegcaf fgec aegbdf ecdfab fbedc dacgb gdcebf gf | cefg dcbef fcge gbcadfe
bdfegc cbegaf gecbf dfcage bdacg ed bedf ced adcbefg gebcd | ed bcgafe cdgba cbgef
egadfb cdbfeg cegd fecab cgb gbdefca cg fgcdab egfdb bfceg | gbdfcae bgc cg cgb
gcafb gcf dcaebfg ecagb gf abcdeg gaef cafbge fdbac fegbdc | fgae cfgab fg bagce
""".trimIndent()
}
}
class Part8B : Part8A() {
override fun compute(): Int {
var outputSum = 0
for ((patterns, outputs) in signalPatterns.zip(outputs)) {
val digits = MutableList(10) { "" }
val tmp = findUnique(patterns)
digits[1] = tmp[0]
digits[4] = tmp[1]
digits[7] = tmp[2]
digits[8] = tmp[3]
digits[6] = find6(patterns, digits[1])
digits[9] = find9(patterns, digits[4])
digits[0] = find0(patterns, digits[6], digits[9])
digits[3] = find3(patterns, digits[1], digits[9])
digits[5] = find5(patterns, digits[6])
digits[2] = find2(patterns, digits[3], digits[5])
val lookup = digits.withIndex().associate { it.value to it.index.toString() }
val number = outputs.mapNotNull { lookup[it] }.joinToString(separator = "")
outputSum += number.toInt()
}
return outputSum
}
// find the digits that are unique and remove them from the patterns
private fun findUnique(patterns: MutableList<String>): List<String> {
var one = ""
var four = ""
var seven = ""
var eight = ""
for (pattern in patterns) {
when (pattern.length) {
2 -> one = pattern
3 -> seven = pattern
4 -> four = pattern
7 -> eight = pattern
}
}
patterns.remove(one)
patterns.remove(seven)
patterns.remove(four)
patterns.remove(eight)
return listOf(one, four, seven, eight)
}
private fun find6(patterns: MutableList<String>, one: String): String {
for (pattern in patterns) {
if (pattern.length != 6) {
continue
}
if (hasOne(one, pattern)) {
patterns.remove(pattern)
return pattern
}
}
return ""
}
private fun find9(patterns: MutableList<String>, four: String): String {
for (pattern in patterns) {
if (pattern.length != 6) {
continue
}
if (hasAll(four, pattern)) {
patterns.remove(pattern)
return pattern
}
}
return ""
}
private fun find0(patterns: MutableList<String>, six: String, nine: String): String {
for (pattern in patterns) {
if (pattern.length != 6) {
continue
}
if (pattern != six && pattern != nine) {
patterns.remove(pattern)
return pattern
}
}
return ""
}
private fun find3(patterns: MutableList<String>, one: String, nine: String): String {
for (pattern in patterns) {
if (pattern.length != 5) {
continue
}
if (hasAll(one, pattern) && hasAllButOne(nine, pattern)) {
patterns.remove(pattern)
return pattern
}
}
return ""
}
private fun find5(patterns: MutableList<String>, six: String): String {
for (pattern in patterns) {
if (pattern.length != 5) {
continue
}
if (hasAll(pattern, six)) {
patterns.remove(pattern)
return pattern
}
}
return ""
}
private fun find2(patterns: MutableList<String>, three: String, five: String): String {
for (pattern in patterns) {
if (pattern.length != 5) {
continue
}
if (pattern != three && pattern != five) {
patterns.remove(pattern)
return pattern
}
}
return ""
}
// Check if one and only one of chars is in pattern
private fun hasOne(chars: String, pattern: String): Boolean {
return chars.map { it in pattern }.count { it } == 1
}
// Check if all of chars is in pattern
private fun hasAll(chars: String, pattern: String): Boolean {
val checks = chars.map { it in pattern }
return checks.all { it }
}
// Check if all but one of chars is in pattern
private fun hasAllButOne(chars: String, pattern: String): Boolean {
val checks = chars.map { it !in pattern }
return checks.count { it } == 1
}
override fun getExampleAnswer(): Int {
return 61229
}
}
fun main() {
Day(2021, 8, Part8A(), Part8B())
} | 0 | Kotlin | 0 | 0 | 69a0748ed640cf80301d8d93f25fb23cc367819c | 6,944 | advent-of-code-kotlin | MIT License |
src/Day04.kt | MickyOR | 578,726,798 | false | {"Kotlin": 98785} | fun main() {
fun part1(input: List<String>): Int {
var sum = 0;
for (line in input) {
var (s1, s2) = line.split(",");
var (l1, r1) = s1.split("-").map { it.toInt() };
var (l2, r2) = s2.split("-").map { it.toInt() };
if (l1 <= l2 && r2 <= r1 || l2 <= l1 && r1 <= r2) {
sum += 1;
}
}
return sum;
}
fun part2(input: List<String>): Int {
var sum = 0;
for (line in input) {
var (s1, s2) = line.split(",");
var (l1, r1) = s1.split("-").map { it.toInt() };
var (l2, r2) = s2.split("-").map { it.toInt() };
if (l2 in l1..r1 || r2 in l1..r1 || l1 in l2..r2 || r1 in l2..r2) {
sum += 1;
}
}
return sum;
}
val input = readInput("Day04")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | c24e763a1adaf0a35ed2fad8ccc4c315259827f0 | 920 | advent-of-code-2022-kotlin | Apache License 2.0 |
2023/src/main/kotlin/day11.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Grid
import utils.Parser
import utils.Solution
import utils.Vec2l
import utils.pairs
fun main() {
Day11.run()
}
object Day11 : Solution<Grid<Char>>() {
override val name = "day11"
override val parser = Parser.charGrid
private fun expand(coord: Vec2l, expCols: List<Int>, expRows: List<Int>, times: Long = 1): Vec2l {
return coord + (Vec2l(
x = expCols.count { it < coord.x }.toLong(),
y = expRows.count { it < coord.y }.toLong(),
) * (times - 1))
}
private fun solve(expandFactor: Long = 2L): Long {
val expCols = input.columns.filter { it.cells.all { (_, c) -> c == '.' } }.map { it.x }
val expRows = input.rows.filter { it.cells.all { (_, c) -> c == '.' } }.map { it.y }
val galaxies = input.cells.filter { (_, c) -> c == '#' }.map { it.first.toVec2l() }
val galaxiesExpanded = galaxies.map { expand(it, expCols, expRows, expandFactor) }
return galaxiesExpanded.pairs.sumOf { (a, b) -> a.manhattanDistanceTo(b) }
}
override fun part1() = solve()
override fun part2() = solve(expandFactor = 1000000L)
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 1,082 | aoc_kotlin | MIT License |
src/Day03.kt | ostersc | 572,991,552 | false | {"Kotlin": 46059} | fun main() {
fun toPriority(c: Char) = if (c.isUpperCase()) c.code - 'A'.code + 26 + 1 else c.code - 'a'.code + 1
fun part1(input: List<String>): Int {
return input.sumOf {
val c = it.toCharArray(0, it.length / 2).intersect(
it.toCharArray(it.length / 2, it.length).toSet()
).first()
toPriority(c)
}
}
fun part2(input: List<String>): Int {
return input.chunked(3).sumOf {
val c = it[0].toCharArray().intersect(
it[1].toCharArray().toSet()
).intersect(
it[2].toCharArray().toSet()
).first()
toPriority(c)
}
}
// 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 | 1 | 3eb6b7e3400c2097cf0283f18b2dad84b7d5bcf9 | 972 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/g2001_2100/s2025_maximum_number_of_ways_to_partition_an_array/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2001_2100.s2025_maximum_number_of_ways_to_partition_an_array
// #Hard #Array #Hash_Table #Prefix_Sum #Counting #Enumeration
// #2023_06_23_Time_1163_ms_(100.00%)_Space_76_MB_(100.00%)
class Solution {
fun waysToPartition(nums: IntArray, k: Int): Int {
val n = nums.size
val ps = LongArray(n)
ps[0] = nums[0].toLong()
for (i in 1 until n) {
ps[i] = ps[i - 1] + nums[i]
}
val partDiffs: MutableMap<Long, ArrayList<Int>> = HashMap()
var maxWays = 0
for (i in 1 until n) {
val partL = ps[i - 1]
val partR = ps[n - 1] - partL
val partDiff = partR - partL
if (partDiff == 0L) {
maxWays++
}
val idxSet = partDiffs.computeIfAbsent(partDiff) { _: Long? -> ArrayList() }
idxSet.add(i)
}
for (j in 0 until n) {
var ways = 0
val newDiff = k.toLong() - nums[j]
val leftList = partDiffs[newDiff]
if (leftList != null) {
val i = upperBound(leftList, j)
ways += leftList.size - i
}
val rightList = partDiffs[-newDiff]
if (rightList != null) {
val i = upperBound(rightList, j)
ways += i
}
maxWays = Math.max(ways, maxWays)
}
return maxWays
}
private fun upperBound(arr: List<Int>, `val`: Int): Int {
var ans = -1
val n = arr.size
var l = 0
var r = n
while (l <= r) {
val mid = l + (r - l) / 2
if (mid == n) {
return n
}
if (arr[mid] > `val`) {
ans = mid
r = mid - 1
} else {
l = mid + 1
}
}
return ans
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,889 | LeetCode-in-Kotlin | MIT License |
src/day20/Day20.kt | kerchen | 573,125,453 | false | {"Kotlin": 137233} | package day20
import readInput
class Number(val value: Long)
fun parseInput(input: List<String>, factor: Long = 1): List<Number> {
var parsed = mutableListOf<Number>()
for (i in input) {
parsed.add(Number(i.toLong() * factor))
}
// There can be only one zero!
check(parsed.count {it.value == 0.toLong()} == 1)
return parsed
}
fun findIndex(value: Number, mixedFile: List<Number>): Int = mixedFile.indexOfFirst {it == value}
fun findGroveCoordinate(mixedFile: List<Number>, offset: Long): Long {
val pivot = findIndex(mixedFile.find {it.value == 0.toLong()}!!, mixedFile)
var index = ((pivot + offset) % mixedFile.size).toInt()
return mixedFile[index].value
}
fun mix(number: Number, mixedFile: MutableList<Number>) {
val oldIndex = findIndex(number, mixedFile)
val unboundedNewIndex = oldIndex + number.value
val newIndex: Int = (((unboundedNewIndex % (mixedFile.size - 1)) + mixedFile.size - 1) % (mixedFile.size - 1)).toInt()
if (oldIndex == newIndex) return
mixedFile.removeAt(oldIndex)
mixedFile.add(newIndex, number)
}
fun main() {
fun part1(input: List<String>): Long {
val original = parseInput(input)
var mixedFile = original.toMutableList()
for (d in original) {
mix(d, mixedFile)
}
val gc1 = findGroveCoordinate(mixedFile, 1000)
val gc2 = findGroveCoordinate(mixedFile, 2000)
val gc3 = findGroveCoordinate(mixedFile, 3000)
println("Coordinates: $gc1 $gc2 $gc3")
return gc1 + gc2 + gc3
}
fun part2(input: List<String>): Long {
val original = parseInput(input, 811589153)
var mixedFile = original.toMutableList()
for (round in IntRange(0, 9)) {
for (d in original) {
mix(d, mixedFile)
}
}
val gc1 = findGroveCoordinate(mixedFile, 1000)
val gc2 = findGroveCoordinate(mixedFile, 2000)
val gc3 = findGroveCoordinate(mixedFile, 3000)
println("Coordinates: $gc1 $gc2 $gc3")
return gc1 + gc2 + gc3
}
val testInput = readInput("Day20_test")
check(part1(testInput) == 3.toLong())
check(part2(testInput) == 1623178306.toLong())
val input = readInput("Day20")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | dc15640ff29ec5f9dceb4046adaf860af892c1a9 | 2,334 | AdventOfCode2022 | Apache License 2.0 |
src/AoC13.kt | Pi143 | 317,631,443 | false | null | import java.io.File
fun main() {
println("Starting Day 13 A Test 1")
calculateDay13PartA("Input/2020_Day13_A_Test1")
println("Starting Day 13 A Real")
calculateDay13PartA("Input/2020_Day13_A")
println("Starting Day 13 B Test 1")
calculateDay13PartB("Input/2020_Day13_A_Test1")
println("Starting Day 13 B Real")
calculateDay13PartB("Input/2020_Day13_A")
}
fun calculateDay13PartA(file: String): Int {
val Day13Data = readDay13Data(file)
val arrivalTime = Day13Data.first
val buslist = Day13Data.second
var minWaittime = Int.MAX_VALUE
var choosenBusLine = -1
for (bus in buslist) {
val waitTime = bus - (arrivalTime % bus)
if (waitTime < minWaittime) {
minWaittime = waitTime
choosenBusLine = bus
}
}
println("The minimal waiting time is $minWaittime with busline $choosenBusLine")
println("checksum: ${minWaittime * choosenBusLine}")
return minWaittime * choosenBusLine
}
fun calculateDay13PartB(file: String): Long {
val Day13Data = readDay13DataB(file)
val buslist = Day13Data
var currentTimestamp: Long = 0
var fullyValid = false
var stepSize = buslist[0]
while (!fullyValid && currentTimestamp < 3000000000000000000) {
currentTimestamp += stepSize
var valid = true
for (n in 0 until buslist.size) {
if((currentTimestamp + n) % buslist[n] != 0.toLong()){
valid = false
break
}else {
var tempStepSize: Long = 1
for(i in 0 until n){
tempStepSize *= buslist[i]
}
stepSize = tempStepSize
}
}
fullyValid = valid
}
println("first valid timestamp is : $currentTimestamp")
return currentTimestamp
}
fun readDay13Data(input: String): Pair<Int, MutableList<Int>> {
val buslist: MutableList<Int> = ArrayList()
var arrivalTime = 0
val lines = File(localdir + input).readLines()
arrivalTime = lines[0].toInt()
val buslines = lines[1].split(",").filter { it != "x" }
buslines.forEach { buslist.add(it.toInt()) }
return Pair(arrivalTime, buslist)
}
fun readDay13DataB(input: String): MutableList<Long> {
val buslist: MutableList<Long> = ArrayList()
val lines = File(localdir + input).readLines()
val buslines = lines[1].split(",").map {
if (it == "x") {
"1"
} else {
it
}
}
buslines.forEach { buslist.add(it.toLong()) }
return buslist
}
| 0 | Kotlin | 0 | 1 | fa21b7f0bd284319e60f964a48a60e1611ccd2c3 | 2,596 | AdventOfCode2020 | MIT License |
advent-of-code-2023/src/Day09.kt | osipxd | 572,825,805 | false | {"Kotlin": 141640, "Shell": 4083, "Scala": 693} | private const val DAY = "Day09"
fun main() {
fun testInput() = readInput("${DAY}_test")
fun input() = readInput(DAY)
"Part 1" {
part1(testInput()) shouldBe 114
measureAnswer { part1(input()) }
}
"Part 2" {
part2(testInput()) shouldBe 2
measureAnswer { part2(input()) }
}
}
private fun part1(input: List<List<Int>>): Int = input.sumOf { values ->
produceDiffs(values).sumOf { it.last() }
}
private fun part2(input: List<List<Int>>): Int = input.sumOf { values ->
produceDiffs(values).map { it.first() }.toList().reduceRight(Int::minus)
}
private fun produceDiffs(values: List<Int>): Sequence<List<Int>> {
return generateSequence(values) { currentValues ->
if (currentValues.any { it != 0 }) {
currentValues.windowed(2) { (left, right) -> right - left }
} else {
null
}
}
}
private fun readInput(name: String) = readLines(name) { it.splitInts() }
| 0 | Kotlin | 0 | 5 | 6a67946122abb759fddf33dae408db662213a072 | 972 | advent-of-code | Apache License 2.0 |
src/me/bytebeats/algo/kt/Solution3.kt | bytebeats | 251,234,289 | false | null | package me.bytebeats.algo.kt
import me.bytebeats.algs.ds.ListNode
import me.bytebeats.algs.ds.TreeNode
class Solution3 {
fun removeDuplicates(nums: IntArray): Int {
var size = nums.size
var k = 0
var j = 0
var num = 0
while (k < size) {
num = nums[k]
j = k + 1
while (j < size && num == nums[j]) {
j++
}
if (j - k > 1) {
for (h in j until size) {
nums[h - j + k + 2] = nums[h]
}
size -= (j - k - 2)
k += 2
} else {
k = j
}
}
return size
}
fun countLargestGroup(n: Int): Int {//1399
val map = HashMap<Int, ArrayList<Int>>()
for (i in 1..n) {
map.compute(getSum(i)) { k, v ->
if (v == null) {
val e = ArrayList<Int>()
e.add(i)
e
} else {
v.add(i)
v
}
}
}
val max = map.values.map { it.size }.maxOfOrNull { it }
return map.values.filter { it.size == max }.count()
}
private fun getSum(num: Int): Int {
var sum = 0
var n = num
while (n != 0) {
sum += n % 10
n /= 10
}
return sum
}
fun canConstruct(s: String, k: Int): Boolean {
if (s.length < k) {
return false
}
if (s.length == k) {
return true
}
val counts = IntArray(26)
for (c in s) {
counts[c - 'a']++
}
var oddCount = 0
for (ch in counts) {
if (ch > 0) {
if (ch and 1 == 1) {
oddCount++
}
}
}
return oddCount <= k
}
fun checkOverlap(radius: Int, x_center: Int, y_center: Int, x1: Int, y1: Int, x2: Int, y2: Int): Boolean {
val x = (x1.toDouble() + x2) / 2
val y = (y1.toDouble() + y2) / 2
val p = Math.sqrt(Math.pow((x1.toDouble() - x2) / 2, 2.0) + Math.pow((y1.toDouble() - y2) / 2, 2.0))
val q = Math.sqrt(Math.pow((x - x_center), 2.0) + Math.pow((y - y_center), 2.0))
return q - p <= radius
}
fun groupAnagrams(strs: Array<String>): List<List<String>> {
val map = mutableMapOf<String, MutableList<String>>()
strs.forEach {
val key = key(it)
if (map.containsKey(key)) {
map[key]?.add(it)
} else {
val list = arrayListOf<String>()
list.add(it)
map[key] = list
}
}
return map.values.toList()
}
private fun key(str: String): String {
val chars = IntArray(26)
str.forEach { chars[it - 'a'] += 1 }
val ans = StringBuilder()
chars.forEach {
ans.append(it)
ans.append(',')
}
return ans.toString()
}
fun containsNearbyAlmostDuplicate(nums: IntArray, k: Int, t: Int): Boolean {//220
val set = sortedSetOf<Int>()
for (i in nums.indices) {
val s = set.ceiling(nums[i])
if (s != null && s <= nums[i] + t) {
return true
}
val g = set.floor(nums[i])
if (g != null && nums[i] <= g + t) {
return true
}
set.add(nums[i])
if (set.size > k) {
set.remove(nums[i - k])
}
}
return false
}
fun deleteNode(head: ListNode?, `val`: Int): ListNode? {// 面试题18, 删除链表节点
if (head == null) {
return null
}
if (head.`val` == `val`) {
return head.next
}
var pre = head
var cur = head.next
while (cur != null && cur.`val` != `val`) {
pre = cur
cur = cur.next
}
pre?.next = cur?.next
return head
}
fun rotateRight(head: ListNode?, k: Int): ListNode? {//61
var size = 0
var p = head
while (p != null) {
size++
p = p.next
}
if (size == 0 || k % size == 0) {
return head
}
var d = size - k % size
p = head
var pre: ListNode? = null
while (d-- > 0) {
pre = p
p = p?.next
}
pre?.next = null
pre = p
while (p != null && p.next != null) {
p = p.next
}
p?.next = head
return pre
}
fun rotateRight1(head: ListNode?, k: Int): ListNode? {//61, 连接成环, 移动后再断开
if (head?.next == null || k == 0) {
return head
}
var size = 0
var p = head
var pre: ListNode? = null
while (p != null) {
size++
pre = p
p = p.next
}
if (k % size == 0) {
return head
}
pre?.next = head
var d = size - k % size
p = head
pre = null
while (d-- > 0) {
pre = p
p = p?.next
}
pre?.next = null
return p
}
fun superEggDrop(K: Int, N: Int): Int {//887
// Right now, dp[i] represents dp(1, i)
var dp = IntArray(N + 1)
for (i in 0..N) {
dp[i] = i
}
for (k in 2..K) {
// Now, we will develop dp2[i] = dp(k, i)
val dp2 = IntArray(N + 1)
var x = 1
for (n in 1..N) {
// Let's find dp2[n] = dp(k, n)
// Increase our optimal x while we can make our answer better.
// Notice max(dp[x-1], dp2[n-x]) > max(dp[x], dp2[n-x-1])
// is simply max(T1(x-1), T2(x-1)) > max(T1(x), T2(x)).
while (x < n && Math.max(dp[x - 1], dp2[n - x]) > Math.max(dp[x], dp2[n - x - 1])) {
x++
}
// The final answer happens at this x.
dp2[n] = 1 + Math.max(dp[x - 1], dp2[n - x])
}
dp = dp2
}
return dp[N]
}
fun wordPattern(pattern: String, str: String): Boolean {//290
if (pattern.isEmpty() || str.isEmpty() || pattern.length != str.split(" ").size) {
return false
}
val map = mutableMapOf<Char, String>()
val words = str.split(" ")
pattern.forEachIndexed { index, c ->
if (map.containsKey(c)) {
if (map[c] != words[index]) {
return false
}
} else if (map.containsValue(words[index])) {
return false
} else {
map[c] = words[index]
}
}
return true
}
fun suggestedProducts(products: Array<String>, searchWord: String): List<List<String>> {//1268
val ans = mutableListOf<List<String>>()
var pre = StringBuilder()
searchWord.forEach {
pre.append(it)
ans.add(products.filter { it.startsWith(pre) }.sorted().take(3))
}
return ans
}
fun stringMatching(words: Array<String>): List<String> {//1408
val set = mutableSetOf<String>()
val ans = mutableListOf<String>()
set.addAll(words)
words.forEach { word ->
if (set.filter { it.contains(word) && it != word }.count() > 0) {
ans.add(word)
}
}
return ans
}
fun processQueries(queries: IntArray, m: Int): IntArray {
val p = IntArray(m)
for (i in 1..m) {
p[i - 1] = i
}
queries.forEachIndexed { index, i ->
val position = p.indexOf(i)
for (j in position downTo 1) {
p[j] = p[j - 1]
}
p[0] = i
queries[index] = position
}
return queries
}
fun entityParser(text: String): String {
val map = mapOf(
""" to "\"",
"'" to "'",
"&" to "&",
">" to ">",
"<" to "<",
"⁄" to "/"
)
var ans = text
map.forEach { key, value -> ans = ans.replace(key, value) }
return ans
}
fun numOfWays(n: Int): Int {
var ans = 0
return ans
}
fun intersection(start1: IntArray, end1: IntArray, start2: IntArray, end2: IntArray): DoubleArray {//面试题16.03 相交
val ans = mutableListOf<Double>()
val x1 = start1[0]
val y1 = start1[1]
val x2 = end1[0]
val y2 = end1[1]
val x3 = start2[0]
val y3 = start2[1]
val x4 = end2[0]
val y4 = end2[1]
// 判断 (x1, y1)~(x2, y2) 和 (x3, y3)~(x4, y3) 是否平行
if ((y4 - y3) * (x2 - x1) == (y2 - y1) * (x4 - x3)) {
// 若平行,则判断 (x3, y3) 是否在「直线」(x1, y1)~(x2, y2) 上
if ((y2 - y1) * (x3 - x1) == (y3 - y1) * (x2 - x1)) {
// 判断 (x3, y3) 是否在「线段」(x1, y1)~(x2, y2) 上
if (inside(x1, y1, x2, y2, x3, y3)) {
update(ans, x3.toDouble(), y3.toDouble())
}
// 判断 (x4, y4) 是否在「线段」(x1, y1)~(x2, y2) 上
if (inside(x1, y1, x2, y2, x4, y4)) {
update(ans, x4.toDouble(), y4.toDouble())
}
// 判断 (x1, y1) 是否在「线段」(x3, y3)~(x4, y4) 上
if (inside(x3, y3, x4, y4, x1, y1)) {
update(ans, x1.toDouble(), y1.toDouble())
}
// 判断 (x2, y2) 是否在「线段」(x3, y3)~(x4, y4) 上
if (inside(x3, y3, x4, y4, x2, y2)) {
update(ans, x2.toDouble(), y2.toDouble())
}
}
// 在平行时,其余的所有情况都不会有交点
} else {
// 联立方程得到 t1 和 t2 的值
val t1 =
(x3.toDouble() * (y4 - y3) + y1 * (x4 - x3) - y3 * (x4 - x3) - x1 * (y4 - y3)) / ((x2 - x1) * (y4 - y3) - (x4 - x3) * (y2 - y1));
val t2 =
(x1.toDouble() * (y2 - y1) + y3 * (x2 - x1) - y1 * (x2 - x1) - x3 * (y2 - y1)) / ((x4 - x3) * (y2 - y1) - (x2 - x1) * (y4 - y3));
// 判断 t1 和 t2 是否均在 [0, 1] 之间
if (t1 in 0.0..1.0 && t2 in 0.0..1.0) {
ans.add(x1 + t1 * (x2 - x1))
ans.add(y1 + t1 * (y2 - y1))
}
}
return ans.toDoubleArray()
}
// 判断 (xk, yk) 是否在「线段」(x1, y1)~(x2, y2) 上
// 这里的前提是 (xk, yk) 一定在「直线」(x1, y1)~(x2, y2) 上
private fun inside(x1: Int, y1: Int, x2: Int, y2: Int, xk: Int, yk: Int): Boolean {
// 若与 x 轴平行,只需要判断 x 的部分
// 若与 y 轴平行,只需要判断 y 的部分
// 若为普通线段,则都要判断
return (x1 == x2 || xk >= Math.min(x1, x2) && xk <= Math.max(x1, x2))
&& (y1 == y2 || yk >= Math.min(y1, y2) && yk <= Math.max(y1, y2))
}
private fun update(ans: MutableList<Double>, xk: Double, yk: Double) {
if (ans.isEmpty()) {
ans.add(xk)
ans.add(yk)
} else if (xk < ans[0]) {
ans[0] = xk
ans[1] = yk
} else if (xk == ans[0] && yk < ans[1]) {
ans[0] = xk
ans[1] = yk
}
}
fun fizzBuzz(n: Int): List<String> {//412
val ans = mutableListOf<String>()
for (i in 1..n) {
if (i % 15 == 0) {
ans.add("FizzBuzz")
} else if (i % 5 == 0) {
ans.add("Buzz")
} else if (i % 3 == 0) {
ans.add("Fizz")
} else {
ans.add("$i")
}
}
return ans
}
fun thirdMax(nums: IntArray): Int {//414
var max = Long.MIN_VALUE
nums.forEach {
if (max < it) {
max = it.toLong()
}
}
var max2 = Long.MIN_VALUE
nums.forEach {
if (it < max && max2 < it) {
max2 = it.toLong()
}
}
var max3 = Long.MIN_VALUE
nums.forEach {
if (it < max2 && max3 < it) {
max3 = it.toLong()
}
}
if (max3 > Long.MIN_VALUE) {
return max3.toInt()
} else {
return max.toInt()
}
}
fun findMaxLength(nums: IntArray): Int {//525
val counts = IntArray(nums.size * 2 + 1) { -2 }
counts[nums.size] = -1
var max = 0
var count = 0
for (i in nums.indices) {
count += if (nums[i] == 0) -1 else 1
if (counts[count + nums.size] >= -1) {
if (max < i - counts[count + nums.size]) {
max = i - counts[count + nums.size]
}
} else {
counts[count + nums.size] = i
}
}
return max
}
fun pathSum(root: TreeNode?, sum: Int): Int {//437
if (root == null) {
return 0
}
return pathSumHelper(root, sum) + pathSum(root?.left, sum) + pathSum(root?.right, sum)
}
private fun pathSumHelper(node: TreeNode?, sum: Int): Int {
if (node == null) {
return 0
} else {
val nextSum = sum - node.`val`
return (if (nextSum == 0) 1 else 0) + pathSumHelper(node.left, nextSum) + pathSumHelper(node.right, nextSum)
}
}
fun pathSum1(root: TreeNode?, sum: Int): Int {//437
if (root == null) {
return 0
}
return pathSum1(root, sum, 0) + pathSum1(root?.left, sum) + pathSum1(root?.right, sum)
}
private fun pathSum1(node: TreeNode?, sum: Int, subSum: Int): Int {
if (node == null) {
return 0
} else {
var count = 0
val nextSum = subSum + node.`val`
if (nextSum == sum) {
count++
}
count += pathSum1(node.left, sum, nextSum)
count += pathSum1(node.right, sum, nextSum)
return count
}
}
fun stringShift(s: String, shift: Array<IntArray>): String {
val ans = s.toCharArray().toMutableList()
var ch = ' '
shift.forEach {
var bits = it[1] % ans.size
while (bits-- > 0) {
if (it[0] == 0) {
ch = ans.first()
ans.removeAt(0)
ans.add(ch)
} else {
ch = ans.last()
ans.removeAt(ans.lastIndex)
ans.add(0, ch)
}
}
}
return String(ans.toCharArray())
}
// fun groupStrings(strings: Array<String>): List<List<String>> {
// val ans = mutableMapOf<String, List<String>>()
// strings.forEach { str ->
// if (contains(ans.keys, str)) {
// ans[]
// } else {
// ans[str]
// }
// }
// return ans.values.toList()
// }
// private fun contains(keys: Set<String>, key: String): Boolean {
// var contains = false
// keys.filter { key.length == it.length }.forEach { str ->
// if (key.length == 1) {
// contains = true
// } else {
// val diff = key[0] - str[0]
// var same = true
// for (i in 1..key.lastIndex) {
// if (key[i] - str[i] != diff) {
// same = false
// }
// }
// contains = contains or same
// }
// }
// return contains
// }
// fun shiftGrid(grid: Array<IntArray>, k: Int): List<List<Int>> {
// val count = grid.size * grid[0].size
// val shift = k % count
//
// }
fun sumRootToLeaf(root: TreeNode?): Int {//1022
if (root == null) {
return 0
}
val binaryList = mutableListOf<String>()
sumRootToLeaf(root, binaryList, StringBuilder())
var ans = 0
binaryList.forEach { ans += it.toInt(2) }
return ans
}
fun sumRootToLeaf(root: TreeNode?, binaryList: MutableList<String>, seq: StringBuilder) {
if (root == null) {
return
} else if (root.left == null && root.right == null) {
seq.append(root.`val`)
binaryList.add(seq.toString())
} else {
val value = root.`val`
if (root.left != null) {
val newSeq = StringBuilder(seq)
newSeq.append(value)
sumRootToLeaf(root.left, binaryList, newSeq)
}
if (root.right != null) {
val newSeq = StringBuilder(seq)
newSeq.append(value)
sumRootToLeaf(root.right, binaryList, newSeq)
}
}
}
fun updateMatrix(matrix: Array<IntArray>): Array<IntArray> {//542
val row = matrix.size
val column = matrix[0].size
val dist = Array(row) { IntArray(column) { 0 } }
for (i in 0 until row) {
for (j in 0 until column) {
dist[i][j] = Int.MAX_VALUE - 10
if (matrix[i][j] == 0) {
dist[i][j] = 0
} else {
if (i > 0) {
dist[i][j] = min(dist[i][j], dist[i - 1][j] + 1)
}
if (j > 0) {
dist[i][j] = min(dist[i][j], dist[i][j - 1] + 1)
}
}
}
}
for (i in row - 1 downTo 0) {
for (j in column - 1 downTo 0) {
if (i < row - 1) {
dist[i][j] = min(dist[i][j], dist[i + 1][j] + 1)
}
if (j < column - 1) {
dist[i][j] = min(dist[i][j], dist[i][j + 1] + 1)
}
}
}
return dist
}
private fun min(x: Int, y: Int): Int = if (x > y) y else x
var closest = Double.MAX_VALUE
var value = 0
fun closestValue(root: TreeNode?, target: Double): Int {//270
closest = Double.MAX_VALUE
value = 0
preReversal(root, target)
return value
}
private fun preReversal(root: TreeNode?, target: Double) {
if (root == null) {
return
}
if (Math.abs(root.`val` - target) < closest) {
closest = Math.abs(root.`val` - target)
value = root.`val`
}
if (root.left != null) {
preReversal(root.left, target)
}
if (root.right != null) {
preReversal(root.right, target)
}
}
fun insertIntoBST(root: TreeNode?, `val`: Int): TreeNode? {//701
if (root == null) {
return TreeNode(`val`)
}
var p = root
while (p != null) {
if (p.`val` > `val`) {
if (p.left != null) {
p = p.left
} else {
p.left = TreeNode(`val`)
p = null
}
} else {
if (p.right != null) {
p = p.right
} else {
p.right = TreeNode(`val`)
p = null
}
}
}
return root
}
fun productExceptSelf1(nums: IntArray): IntArray {//238, 不使用除法
val ans = IntArray(nums.size) { 1 }
var tmp = 1
for (i in 1 until nums.size) {
tmp *= nums[i - 1]
ans[i] = tmp
}
tmp = nums.last()
for (i in nums.size - 2 downTo 0) {
ans[i] *= tmp
tmp *= nums[i]
}
return ans
}
fun productExceptSelf(nums: IntArray): IntArray {//238
var sum = 1
var count = 0 //count zero
nums.forEach {
if (it == 0) {
count++
} else {
sum *= it//multiply except 0s
}
}
nums.forEachIndexed { index, num ->
if (num == 0) {
if (count > 1) {
nums[index] = 0
} else {
nums[index] = sum
}
} else {
if (count > 0) {
nums[index] = 0
} else {
nums[index] = sum / num
}
}
}
return nums
}
fun maxProduct(nums: IntArray): Int {//152
var max = Int.MIN_VALUE
var imax = 1
var imin = 1
nums.forEach {
if (it < 0) {
val tmp = imax
imax = imin
imin = tmp
}
imax = Math.max(imax * it, it)
imin = Math.min(imin * it, it)
max = Math.max(imax, max)
}
return max
}
fun maximumProduct(nums: IntArray): Int {//628
nums.sort()
if (nums.first() >= 0 || nums.last() <= 0) {
val last = nums.lastIndex
return nums[last] * nums[last - 1] * nums[last - 2]
} else {
var index = 0
for (i in nums.indices) {
if (nums[i] >= 0) {
index = i - 1
break
}
}
if (index < 1) {
val filtered = nums.takeLast(3)
return filtered[0] * filtered[1] * filtered[2]
} else {
val p1 = nums[0] * nums[1] * nums.last()
val last = nums.lastIndex
val p2 = nums[last] * nums[last - 1] * nums[last - 2]
return if (p1 > p2) p1 else p2
}
}
}
fun merge(intervals: Array<IntArray>): Array<IntArray> {//56
val ans = mutableListOf<IntArray>()
if (intervals.isNotEmpty()) {
intervals.sortBy { it[0] }
var tmp = intervals[0]
for (i in 1 until intervals.size) {
if (tmp[1] >= intervals[i][0]) {
val newRange = IntArray(2)
newRange[0] = tmp[0]
newRange[1] = if (tmp[1] > intervals[i][1]) tmp[1] else intervals[i][1]
tmp = newRange
} else {
ans.add(tmp)
tmp = intervals[i]
}
}
ans.add(tmp)
}
return ans.toTypedArray()
}
fun canAttendMeetings(intervals: Array<IntArray>): Boolean {//252
val range = IntArray(2) { -1 }
if (intervals.isNotEmpty()) {
intervals.sortBy { it[0] }
range[0] = intervals[0][0]
range[1] = intervals[0][1]
for (i in 1 until intervals.size) {
if (range[1] < intervals[i][0]) {
range[0] = intervals[i][0]
range[1] = intervals[i][1]
} else {
return false
}
}
}
return true
}
fun minMeetingRooms(intervals: Array<IntArray>): Int {//253
intervals.sortBy { it[0] }
val intervalList = intervals.toMutableList()
val ans = mutableListOf<List<IntArray>>()
while (intervalList.isNotEmpty()) {
val room = mutableListOf<IntArray>()
room.add(intervalList[0])
var tmp = intervalList[0]
for (i in 1 until intervalList.size) {
if (tmp[1] <= intervalList[i][0]) {
room.add(intervalList[i])
tmp = intervalList[i]
}
}
ans.add(room)
room.forEach { intervalList.removeAt(intervalList.indexOf(it)) }
}
return ans.size
}
fun insert(intervals: Array<IntArray>, newInterval: IntArray): Array<IntArray> {//57
val ans = mutableListOf<IntArray>()
for (i in intervals.indices) {
if (intervals[i][1] < newInterval[0]) {
ans.add(intervals[i])
if (i == intervals.lastIndex) {
ans.add(newInterval)
}
} else if (intervals[i][0] > newInterval[1]) {
ans.add(newInterval)
for (j in i until intervals.size) {
ans.add(intervals[j])
}
break
} else {
newInterval[0] = Math.min(newInterval[0], intervals[i][0])
newInterval[1] = Math.max(newInterval[1], intervals[i][1])
if (i == intervals.lastIndex) {
ans.add(newInterval)
}
}
}
if (ans.isEmpty()) {
ans.add(newInterval)
}
return ans.toTypedArray()
}
fun intervalIntersection(A: Array<IntArray>, B: Array<IntArray>): Array<IntArray> {//986
val ans = mutableListOf<IntArray>()
var i = 0
var j = 0
var range: IntArray?
while (i < A.size && j < B.size) {
val l = Math.max(A[i][0], B[j][0])
val h = Math.min(A[i][1], B[j][1])
if (l <= h) {
range = IntArray(2)
range[0] = l
range[1] = h
ans.add(range)
}
if (A[i][1] < B[j][1]) {
i++
} else {
j++
}
}
return ans.toTypedArray()
}
fun canJump(nums: IntArray): Boolean {//55
var rightMost = 0
for (i in nums.indices) {
if (i <= rightMost) {
rightMost = Math.max(rightMost, i + nums[i])
if (rightMost >= nums.lastIndex) {
return true
}
}
}
return false
}
fun canReach(arr: IntArray, start: Int): Boolean {//1306
return canReach(arr, start, mutableSetOf())
}
fun canReach(arr: IntArray, start: Int, set: MutableSet<Int>): Boolean {//1306
if (start < 0 || start > arr.lastIndex) {
return false
} else if (arr[start] == 0) {
return true
} else {
if (set.contains(start)) {
return false
}
set.add(start)
return canReach(arr, start - arr[start], set) or canReach(arr, start + arr[start], set)
}
}
fun jump(nums: IntArray): Int {//45
var end = 0
var maxPos = 0
var steps = 0
for (i in 0 until nums.lastIndex) {
maxPos = Math.max(maxPos, i + nums[i])
if (i == end) {
end = maxPos
steps++
}
}
return steps
}
fun numIslands(grid: Array<CharArray>): Int {//200
if (grid.isEmpty() || grid[0].isEmpty()) {
return 0
}
var islands = 0
val row = grid.size
val column = grid[0].size
for (i in 0 until row) {
for (j in 0 until column) {
if (grid[i][j] == '1') {
dfs(grid, i, j)
islands++
}
}
}
return islands
}
private fun dfs(grid: Array<CharArray>, row: Int, column: Int) {
if (row < 0 || column < 0 || row > grid.lastIndex || column > grid[0].lastIndex || grid[row][column] == '0') {
return
}
grid[row][column] = '0'
dfs(grid, row - 1, column)
dfs(grid, row + 1, column)
dfs(grid, row, column - 1)
dfs(grid, row, column + 1)
}
fun minCount(coins: IntArray): Int {
var count = 0
coins.forEach {
if (it and 1 == 1) {
count += (it + 1) / 2
} else {
count += it / 2
}
}
return count
}
var count = 0
fun numWays(n: Int, relation: Array<IntArray>, k: Int): Int {
count = 0
val map = mutableMapOf<Int, MutableList<Int>>()
relation.forEach {
map.compute(it[0]) { _, v ->
if (v == null) {
val e = mutableListOf<Int>()
e.add(it[1])
e
} else {
v.add(it[1])
v
}
}
}
ways(0, n, map, k)
return count
}
private fun ways(index: Int, n: Int, map: Map<Int, MutableList<Int>>, k: Int) {
if (k < 1) {
return
} else if (k == 1) {
if (map.entries.filter { it.key == index }.map { it.value }.flatMap { it.asIterable() }.contains(n - 1)) {
count++
}
} else {
map.entries.filter { it.key == index }.map { it.value }.flatMap { it.asIterable() }
.forEach { ways(it, n, map, k - 1) }
}
}
fun getTriggerTime(increase: Array<IntArray>, requirements: Array<IntArray>): IntArray {
val ans = IntArray(requirements.size) { -1 }
val increases = IntArray(3) { 0 }
val set = mutableSetOf<Int>()
for (i in requirements.indices) {
set.add(i)
}
for (i in increase.indices) {
increases[0] += increase[i][0]
increases[1] += increase[i][1]
increases[2] += increase[i][2]
val tmp = mutableSetOf<Int>()
for (j in set) {
if (requirements[j][0] == 0 && requirements[j][1] == 0 && requirements[j][2] == 0) {
ans[j] = 0
tmp.add(j)
} else if (increases[0] >= requirements[j][0] && increases[1] >= requirements[j][1] && increases[2] >= requirements[j][2]) {
ans[j] = i + 1
tmp.add(j)
} else {
continue
}
}
if (tmp.isNotEmpty()) {
set.removeAll(tmp)
}
}
return ans
}
fun getTriggerTime1(increase: Array<IntArray>, requirements: Array<IntArray>): IntArray {
val ans = IntArray(requirements.size) { -1 }
val increases = IntArray(3) { 0 }
for (i in increase.indices) {
increases[0] += increase[i][0]
increases[1] += increase[i][1]
increases[2] += increase[i][2]
}
val tmp = IntArray(3) { 0 }
requirements.forEachIndexed { index, requirement ->
if (requirement[0] == 0 && requirement[1] == 0 && requirement[2] == 0) {
ans[index] = 0
} else {
if (increases[0] < requirement[0] || increases[1] < requirement[1] || increases[2] < requirement[2]) {
} else {
tmp[0] = 0
tmp[1] = 0
tmp[2] = 0
for (i in increase.indices) {
tmp[0] += increase[i][0]
tmp[1] += increase[i][1]
tmp[2] += increase[i][2]
if (tmp[0] >= requirement[0] || tmp[1] >= requirement[1] || tmp[2] >= requirement[2]) {
ans[index] = i + 1
break
}
}
}
}
}
return ans
}
fun minJump1(jump: IntArray): Int {//45
var end = 0
var maxPos = 0
var steps = 0
for (i in 0 until jump.lastIndex) {
maxPos = Math.max(maxPos, i + jump[i])
if (i == end) {
end = maxPos
steps++
}
}
return steps
}
fun reformat(s: String): String {//5388, 1417
if (s.length < 2) {
return s
}
val letters = StringBuilder()
val digits = StringBuilder()
s.forEach {
if (it in 'a'..'z') {
letters.append(it)
} else {
digits.append(it)
}
}
if (Math.abs(letters.length - digits.length) > 1) {
return ""
}
val ans = StringBuilder()
if (letters.length > digits.length) {
for (i in digits.indices) {
ans.append(letters[i])
ans.append(digits[i])
}
ans.append(letters.last())
} else if (letters.length == digits.length) {
for (i in digits.indices) {
ans.append(letters[i])
ans.append(digits[i])
}
} else {
for (i in letters.indices) {
ans.append(digits[i])
ans.append(letters[i])
}
ans.append(digits.last())
}
return ans.toString()
}
fun displayTable(orders: List<List<String>>): List<List<String>> {//5389
val ans = mutableListOf<MutableList<String>>()
val tables = orders.map { it[1].toInt() }.distinct().sorted()
val foods = orders.map { it[2] }.distinct().sorted()
val firstRow = mutableListOf<String>()
firstRow.add("Table")
firstRow.addAll(foods)
ans.add(firstRow)
tables.forEach { table ->
val tableFoods = orders.filter { it[1] == table.toString() }.map { it[2] }.groupBy { it }
val row = mutableListOf<String>()
row.add(table.toString())
foods.forEach { food ->
if (tableFoods.containsKey(food)) {
row.add(tableFoods[food]!!.size.toString())
} else {
row.add("0")
}
}
ans.add(row)
}
return ans
}
fun minNumberOfFrogs(croakOfFrogs: String): Int {//4390
val croat = "croak"
var croaked = 0
val croatings = mutableListOf<String>()
croakOfFrogs.forEach { ch ->
if (ch in croat) {
if (ch == 'c') {
croatings.add(ch.toString())
if (croatings.contains(croat)) {
croaked++
}
} else {
val croating = croat.substring(0, croat.indexOf(ch))
if (croatings.contains(croating)) {
croatings[croatings.indexOf(croating)] = "$croating$ch"
} else {
croatings.add(ch.toString())
}
}
} else {
return -1
}
}
if (croatings.all { it == croat }) {
return croatings.size - croaked
} else {
return -1
}
}
} | 0 | Kotlin | 0 | 1 | 7cf372d9acb3274003bb782c51d608e5db6fa743 | 35,300 | Algorithms | MIT License |
src/Day07.kt | MwBoesgaard | 572,857,083 | false | {"Kotlin": 40623} | fun main() {
class Folder(val name: String, var parent: Folder?, val children: MutableList<Folder>, var size: Long) {
fun getTotalSize(): Long {
var totalSize: Long = this.size
for (child in children) {
totalSize += child.getTotalSize()
}
return totalSize
}
}
class FileSystem {
val root: Folder = Folder("/", null, mutableListOf(), 0)
val setOfAllFolders: HashSet<Folder> = hashSetOf()
var currentDirectory: Folder
val totalDiskSpace = 70_000_000
init {
setOfAllFolders.add(root)
currentDirectory = root
}
fun getCurrentDiskSpaceAvailable(): Long {
return totalDiskSpace - root.getTotalSize()
}
fun generateFileSystemFromInput(input: List<String>) {
for (line in input) {
val splitLine = line.split(" ")
if (splitLine[0] == "$" && splitLine[1] == "cd") {
currentDirectory = changeDirectory(splitLine[2], currentDirectory, root)
setOfAllFolders.add(currentDirectory)
} else if (splitLine[0] != "$") {
if (splitLine[0] == "dir") {
currentDirectory.children.add(Folder(splitLine[1], currentDirectory, mutableListOf(), 0))
} else {
currentDirectory.size += splitLine[0].toInt()
}
}
}
}
fun changeDirectory(arg: String, currentDirectory: Folder, root: Folder): Folder {
return when (arg) {
"/" -> root
".." -> currentDirectory.parent ?: root
else -> currentDirectory.children.find { it.name == arg }!!
}
}
}
fun part1(input: List<String>): Long {
val fileSystem = FileSystem()
fileSystem.generateFileSystemFromInput(input)
return fileSystem.setOfAllFolders
.map { it.getTotalSize() }
.filter { it <= 100000 }
.sum()
}
fun part2(input: List<String>): Long {
val fileSystem = FileSystem()
fileSystem.generateFileSystemFromInput(input)
return fileSystem.setOfAllFolders
.toList()
.map { it.getTotalSize() }
.filter { fileSystem.getCurrentDiskSpaceAvailable() + it >= 30_000_000 }
.min()
}
printSolutionFromInputLines("Day07", ::part1)
printSolutionFromInputLines("Day07", ::part2)
}
| 0 | Kotlin | 0 | 0 | 3bfa51af6e5e2095600bdea74b4b7eba68dc5f83 | 2,580 | advent_of_code_2022 | Apache License 2.0 |
kotlin/change/src/main/kotlin/ChangeCalculator.kt | colintheshots | 117,450,747 | false | null | class ChangeCalculator (list: List<Int>) {
private val sortedList = list.sortedDescending()
fun computeMostEfficientChange(total : Int) : List<Int> {
require(total >= 0) {"Negative totals are not allowed."}
if (total == 0) return emptyList() // no coins make zero change
val trimmed = sortedList.dropWhile { it > total } // drop useless values
var pairs = pairsOf(trimmed, total)
while(pairs.isNotEmpty() && pairs.none { it.first == total }) { // stop if no pairs remain or found match
pairs = pairsOf(trimmed, total, pairs)
}
if (pairs.isEmpty())
throw IllegalArgumentException("The total $total cannot be represented in the given currency.")
else return pairs.filter { it.first == total }
.minBy { it.second.size }?.second
?.reversed() ?: throw IllegalArgumentException("No minimum found")
}
// Memoize sums of lists to reduce problem complexity, i.e. dynamic programming
private fun pairsOf(left: Collection<Int>,
total: Int,
pairs: List<Pair<Int, List<Int>>> = listOf()): List<Pair<Int, List<Int>>> {
return if (pairs.isEmpty()) { // build up initial list with all pairs including single coins
left.flatMap { first ->
left.filter { it <= first }
.plus(0) // handle single coins by pairing values with zero
.map { second -> Pair(first + second, listOf(first, second)) }
.filter { it.first <= total }
.map { Pair(it.first, it.second.filter { it>0 }) } // filter out zeroes
}
} else { // add remaining candidate coins to each remaining pair
pairs.flatMap { pair ->
left.filter { it <= pair.second.last() }
.map { second -> Pair(pair.first + second, pair.second + second) }
.filter { it.first <= total }
}
}
}
} | 0 | Kotlin | 0 | 0 | f284aecd7f017c3fd972c1dcf9d1c4b25866d614 | 2,055 | ExercismKotlin | Apache License 2.0 |
2021/kotlin/src/main/kotlin/com/codelicia/advent2021/Day13.kt | codelicia | 627,407,402 | false | {"Kotlin": 49578, "PHP": 554, "Makefile": 293} | package com.codelicia.advent2021
import kotlin.math.max
class Day13(val input: String) {
fun solve(folds: Int): Int {
val (dots, fold) = input.split("\n\n")
val xs = dots.split("\n").map { it.split(",").map { s -> s.toInt() } }
val xMax = xs.maxOf { it[0] }
val yMax = xs.maxOf { it[1] }
var grid = Array(yMax + 1) { IntArray(xMax + 1) { 0 } }
for ((x, y) in xs) {
grid[y][x] = 1;
}
val foldInstructions = fold.split("\n").map { it.split(" ").last().split("=") }
foldInstructions.forEachIndexed { loop, inst ->
if (loop >= folds) return@forEachIndexed
val (direction, value) = inst
// Fold Y
if (direction == "y") {
val stay = grid.filterIndexed { k, _ -> k < value.toInt() }
val fold = grid.filterIndexed { k, _ -> k > value.toInt() }.reversed()
repeat(stay.size) { index ->
grid[index] = stay[index].mapIndexed { i, v -> max(fold[index][i], v) }.toIntArray()
}
grid = grid.copyOfRange(0, stay.lastIndex + 1)
}
// Fold X
if (direction == "x") {
val stay = grid.map { it.filterIndexed { k, _ -> k < value.toInt() } }
val fold = grid.map { it.filterIndexed { k, _ -> k > value.toInt() }.reversed() }
repeat(stay.size) { index ->
grid[index] = stay[index].mapIndexed { i, v -> max(fold[index][i], v) }.toIntArray()
}
}
}
return grid.sumOf { row -> row.sum() }
}
} | 2 | Kotlin | 0 | 0 | df0cfd5c559d9726663412c0dec52dbfd5fa54b0 | 1,662 | adventofcode | MIT License |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[128]最长连续序列.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | //给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
//
// 请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
//
//
//
// 示例 1:
//
//
//输入:nums = [100,4,200,1,3,2]
//输出:4
//解释:最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。
//
// 示例 2:
//
//
//输入:nums = [0,3,7,2,5,8,4,6,0,1]
//输出:9
//
//
//
//
// 提示:
//
//
// 0 <= nums.length <= 105
// -109 <= nums[i] <= 109
//
// Related Topics 并查集 数组 哈希表
// 👍 984 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun longestConsecutive(nums: IntArray): Int {
//使用HashSet 处理数组元素
//时间复杂度 O(n)
var hashset = HashSet<Int>()
nums.forEach { hashset.add(it) }
var res = 0 //返回值
var removes = 0 //删除次数
var index1 = 0 //指针1 代表当前元素
var index2 = 0 //指针2代表加一元素
nums.forEach {
//不存在
if (!hashset.contains(it)) return@forEach
//重置参数
removes = 0
index1 = it
index2 = it+1
while (hashset.contains(index1)){
removes++
hashset.remove(index1)
index1--
}
while (hashset.contains(index2)){
removes++
hashset.remove(index2)
index2++
}
res = if (removes>res) removes else res
}
return res
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 1,748 | MyLeetCode | Apache License 2.0 |
src/Day01.kt | fasfsfgs | 573,562,215 | false | {"Kotlin": 52546} | fun getElves(input: List<String>):List<Int> {
return input
.joinToString { it.ifBlank { "*" } }
.split('*')
.map { it.split(',') }
.map { getIntList(it) }
.map { it.sum() }
}
fun getIntList(strList: List<String>): List<Int> {
return strList
.map { it.trim() }
.filter { it.isNotEmpty() }
.map { it.toInt() }
}
fun main() {
fun part1(input: List<String>): Int {
return getElves(input)
.max()
}
fun part2(input: List<String>): Int {
return getElves(input)
.sortedDescending()
.take(3)
.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 17cfd7ff4c1c48295021213e5a53cf09607b7144 | 892 | advent-of-code-2022 | Apache License 2.0 |
src/year2023/day04/Day.kt | tiagoabrito | 573,609,974 | false | {"Kotlin": 73752} | package year2023.day04
import kotlin.math.pow
import year2023.solveIt
fun main() {
val day = "04"
val expectedTest1 = 13L
val expectedTest2 = 30L
fun readCard(it: String): List<Set<String>> = it.substring(it.indexOf(":")).split("|").map { Regex("\\d+").findAll(it).map { it.value }.toSet() }
fun getCardResult(it: String): Int {
val (card, values) = readCard(it)
return when (val matching = card.intersect(values).size) {
0 -> 0
else -> 2.toDouble().pow(matching - 1).toInt()
}
}
fun part1(input: List<String>): Long {
return input.sumOf { getCardResult(it) }.toLong()
}
fun part2(input: List<String>): Long {
val receivableCards = input.map {
val (card, values) = readCard(it)
card.intersect(values).size
}
val received = MutableList(input.size){0}
for(i in receivableCards.size - 1 downTo 0){
received[i] = receivableCards[i] + received.subList(i+1, i+1+receivableCards[i]).sum()
}
return received.sum()+input.size.toLong()
}
solveIt(day, ::part1, expectedTest1, ::part2, expectedTest2)
}
| 0 | Kotlin | 0 | 0 | 1f9becde3cbf5dcb345659a23cf9ff52718bbaf9 | 1,194 | adventOfCode | Apache License 2.0 |
src/array/BestTimeToBuyAStock.kt | develNerd | 456,702,818 | false | {"Kotlin": 37635, "Java": 5892} | package array
/**
*
* You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Example 2:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.
Constraints:
1 <= prices.length <= 105
0 <= prices[i] <= 104
*
*
* */
/**
* Solution 1 : Brute Force
*
* With this approach the Time complexity is O(n2) and space complexity of O(1), we will implement a much better approach in the next solution
* Taking each of the numbers we iterate through and compare with each of the other numbers in the array with increasing index
* since to calculate for the profit we need the buying price to be of a lower index that the selling price.
* so outer loop with starts with an index of (i) and inner loop (i + 1) .
* Buy on day 2(price = 1) and sell on day 5 (price = 6) maxProfit = 6-1 = 5
* */
fun main(){
println(maxProfit2(intArrayOf(6,0,-1,1,10)))
}
fun maxProfit(prices: IntArray): Int {
/**
* We set the max profit as zero -> (Taking care of the edge case for returning 0)
* */
var maxprofit = 0
for (i in 0 until prices.size - 1) {
/**
* We start the inner loop from an index i+1 since the buying price has to be of a lower index
*d
* */
for (j in i + 1 until prices.size) {
/**
* Calculate the profit by substracting the buying price from the selling price
* and set the currentMaxProfit if it is greater
* */
val profit = prices[j] - prices[i]
if (profit > maxprofit) maxprofit = profit
}
}
return maxprofit
}
/**
Taking this array - [7, 1, 5, 3, 6, 4]
* Let's look at a better solution with O(n) time complexity
* If we plot the numbers of the given array on a graph, we get:
if we plot the solution on a graph we buy at the lowest point on the graph and sell at
the highest point
|
|
|
-> 7 *
|
-> 6 *
|
-> 5 *
Prices |
-> 4
|
-> 3 *
|
-> 2
|
-> 1 *
|__ __ 1 __ 2 __ 3 __ 4 __ 5 __ 6 __
Days
From the graph we buy at day 2 (the most minimum point on the graph) and sell on day 5 (th highest point on the graph after we buy -- reference the main question)
*/
fun maxProfit2(prices: IntArray): Int {
/**
* [7, 1, 5, 3, 6, 4]
* We first assign the minprice a very large value
* */
var minprice = Int.MAX_VALUE // very large value
var maxprofit = 0
for (i in prices.indices) {
/**
* At this point we check if the current price[i] is less than the min price
* to keep track of the lowest value on the graph as we go......
* */
if (prices[i] < minprice)
{
minprice = prices[i] // | 7 || 1 ||| 1 |||| 1
}
/**
* We then keep track of the largest value on the graph in the same loop
* to keep track of the maximum profit that could be attained on the graph above
* as we proceed
*
*
* */
else if (prices[i] - minprice > maxprofit)
{
maxprofit = prices[i] - minprice // ||| 4 |||| 4 ||||| 5
}
}
return maxprofit
}
/**
* Conclusion : The algorithm has a time complexity of O(n) and a space
* complexity of O(1), since the number of variables does not grow with
* corresponding array size
*
* */ | 0 | Kotlin | 0 | 0 | 4e6cc8b4bee83361057c8e1bbeb427a43622b511 | 4,229 | Blind75InKotlin | MIT License |
src/main/kotlin/se/saidaspen/aoc/aoc2022/Day07.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2022
import se.saidaspen.aoc.util.Day
import se.saidaspen.aoc.util.ints
import se.saidaspen.aoc.util.removeFirst
fun main() = Day07.run()
object Day07 : Day(2022, 7) {
data class Dir (
val name: String,
val path : String = "",
val parent: Dir?,
val subs: MutableList<Dir> = mutableListOf(),
var files: Int = 0,
)
private val sizes = mutableMapOf<String, Int>()
init {
val root = Dir("/", path = "/", parent = null)
var current = root
input.lines().drop(1).forEach {
if (it.startsWith("$ cd ..")) {
current = current.parent!!
} else if (it.startsWith("$ cd")) {
val name = it.drop(5)
val newDir = Dir(name, path = current.path + name + "/", parent = current)
current.subs.add(newDir)
current = newDir
} else if (it[0].isDigit()) {
val size = it.split(" ")[0].toInt()
current.files += size
}
}
mapSizes(root, sizes)
}
override fun part1(): Any {
return sizes.entries.filter { it.value < 100000 }.sumOf { it.value }
}
private fun mapSizes(curr: Dir, visited: MutableMap<String, Int>) {
visited[curr.path] = sizeOf(curr)
curr.subs.forEach { mapSizes(it, visited) }
}
private fun sizeOf(dir: Dir) : Int {
val fsize = dir.files
val subsizes = dir.subs.sumOf { sizeOf(it) }
return subsizes + fsize
}
override fun part2(): Any {
val currentUsed = sizes["/"]!!
val unused = 70000000 - currentUsed
val toDelete = 30000000 - unused
return sizes.entries.sortedBy { it.value }.first { it.value > toDelete }.value
}
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 1,820 | adventofkotlin | MIT License |
src/day05/Day05.kt | pnavais | 574,712,395 | false | {"Kotlin": 54079} | package day05
import readInput
import java.util.*
import kotlin.collections.ArrayDeque
val pattern = Regex("^move (\\d+) from (\\d+) to (\\d+)$")
interface CrateMover {
fun moveCrates(line: String, stacks: MutableList<ArrayDeque<Char>>)
}
private class CrateMover9000 : CrateMover {
override fun moveCrates(line: String, stacks: MutableList<ArrayDeque<Char>>) {
val triple = parseMove(line)
var numMoves = triple.first
val srcStack = stacks[triple.second!! - 1]
val targetStack = stacks[triple.third!! - 1]
while (numMoves!! > 0) {
val elem = srcStack.removeFirst()
targetStack.addFirst(elem)
numMoves--
}
}
}
private class CrateMover9001 : CrateMover {
override fun moveCrates(line: String, stacks: MutableList<ArrayDeque<Char>>) {
val triple = parseMove(line)
var numMoves = triple.first
val srcStack = stacks[triple.second!! - 1]
val targetStack = stacks[triple.third!! - 1]
val tempStack = Stack<Char>()
while (numMoves!! > 0) {
val elem = srcStack.removeFirst()
tempStack.push(elem)
numMoves--
}
while (!tempStack.isEmpty()) {
targetStack.addFirst(tempStack.pop())
}
}
}
private fun parseMove(line: String): Triple<Int?, Int?, Int?> {
val m = pattern.find(line)
return Triple(m?.groups?.get(1)?.value?.toInt(),
m?.groups?.get(2)?.value?.toInt(),
m?.groups?.get(3)?.value?.toInt())
}
fun rearrangeCrates(input: List<String>, crateMover: CrateMover): String {
val stacks = mutableListOf<ArrayDeque<Char>>()
for (line in input) {
if (!line.startsWith("move")) {
createStack(line, stacks)
} else {
crateMover.moveCrates(line, stacks)
}
}
printStacks(stacks)
val builder = StringBuilder()
for (stack in stacks) {
builder.append(stack.first())
}
return builder.toString()
}
private fun printStacks(stacks: MutableList<ArrayDeque<Char>>) {
println("---")
println("Stacks ")
for ((index, stack) in stacks.withIndex()) {
print("Stack #${index + 1} (size: ${stack.size}):")
for (item in stack.indices.reversed()) {
print(" ${stack[item]}")
}
println()
}
}
private fun createStack(line: String, stacks: MutableList<ArrayDeque<Char>>) {
var index: Int = line.indexOf("[")
while (index >= 0) {
while (stacks.size < ((index / 4) + 1)) {
stacks.add(ArrayDeque())
}
stacks[index / 4].add(line[index + 1])
index = line.indexOf("[", index + 1)
}
}
fun part1(input: List<String>): String {
return rearrangeCrates(input, CrateMover9000())
}
fun part2(input: List<String>): String {
return rearrangeCrates(input, CrateMover9001())
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05/Day05_test")
println(part1(testInput))
println(part2(testInput))
}
| 0 | Kotlin | 0 | 0 | ed5f521ef2124f84327d3f6c64fdfa0d35872095 | 3,202 | advent-of-code-2k2 | Apache License 2.0 |
src/Day05.kt | strindberg | 572,685,170 | false | {"Kotlin": 15804} | fun main() {
fun createStacks(input: List<String>): Array<ArrayDeque<Char>> =
Array(9) { ArrayDeque<Char>() }.apply {
input.forEach { line ->
if (line.contains("[")) {
for ((index, char) in line.withIndex()) {
if (char == '[') {
this[index / 4].addLast(line[index + 1])
}
}
} else {
return this
}
}
}
fun interpret(line: String): Triple<Int, Int, Int> =
line.split(" ").let {
Triple(it[1].toInt(), it[3].toInt() - 1, it[5].toInt() - 1)
}
fun moveCrates1(input: List<String>, stacks: Array<ArrayDeque<Char>>): String {
input.forEach { line ->
if (line.startsWith("move")) {
val (amount, from, to) = interpret(line)
for (i in 0 until amount) {
stacks[to].addFirst(stacks[from].removeFirst())
}
}
}
return String(stacks.map { it.first() }.toCharArray())
}
fun moveCrates2(input: List<String>, stacks: Array<ArrayDeque<Char>>): String {
input.forEach { line ->
if (line.startsWith("move")) {
val (amount, from, to) = interpret(line)
mutableListOf<Char>().let { temp ->
for (i in 0 until amount) {
temp.add(stacks[from].removeFirst())
}
for (element in temp.reversed()) {
stacks[to].addFirst(element)
}
}
}
}
return String(stacks.map { it.first() }.toCharArray())
}
fun part1(input: List<String>): String = moveCrates1(input, createStacks(input))
fun part2(input: List<String>): String = moveCrates2(input, createStacks(input))
val input = readInput("Day05")
println(part1(input))
check(part1(input) == "QPJPLMNNR")
println(part2(input))
check(part2(input) == "BQDNWJPVJ")
}
| 0 | Kotlin | 0 | 0 | c5d26b5bdc320ca2aeb39eba8c776fcfc50ea6c8 | 2,186 | aoc-2022 | Apache License 2.0 |
src/Day02.kt | ktrom | 573,216,321 | false | {"Kotlin": 19490, "Rich Text Format": 2301} | import java.util.NoSuchElementException
fun main() {
fun part1(matchups: List<List<Shape>>): Int {
// aggregates points earned from all matchups
val score: List<Int> = matchups.map { matchup ->
val opponentShape: Shape = matchup[0]
val myShape: Shape = matchup[1]
// get score earned for using our shape!
val shapeScore: Int = ShapeScore.score[myShape]!!
// get score based on outcome of the round
val outcome: Outcome = RoundOutcomes.roundOutcomes[myShape]!![opponentShape]!!
val outcomeScore: Int = OutcomeScore.score[outcome]!!
// add our two scores to determine our total score for the round
shapeScore + outcomeScore
}
return score.sum()
}
fun part1(input: List<String>): Int {
// parses string input into a list of competing shapes
val roundMatchups: List<List<Shape>> =
input.map { matchup -> matchup.split(" ").map { getShapeAssociatedWithLetter(it) } }
return part1(roundMatchups)
}
fun part2(input: List<String>): Int {
val opposingShapesToDesiredOutcomes: List<Pair<Shape, Outcome>> =
input.map { matchup ->
val matchupInputs: List<String> = matchup.split(" ")
Pair(
getShapeAssociatedWithLetter(matchupInputs.get(0)),
getOutcomeAssociatedWithLetter(matchupInputs.get(1))
)
}
val matchups: List<List<Shape>> = opposingShapesToDesiredOutcomes.map { opposingShapeToDesiredOutcome ->
val opposingShape: Shape = opposingShapeToDesiredOutcome.first
val desiredOutcome: Outcome = opposingShapeToDesiredOutcome.second
val desiredOutcomeForOpponent = getDesiredOutcomeForOpponent(desiredOutcome)
val opponentOutcomes = RoundOutcomes.roundOutcomes[opposingShape]!!
// filter to get the Pair<Shape, Outcome> which has our desired Outcome for the opponent's Shape, then use the key for our shape
val ourShapeToEnemyOutcome =
opponentOutcomes.entries.stream().filter { entry -> entry.value == desiredOutcomeForOpponent }
.findFirst().orElseThrow { NoSuchElementException() }
val shapeToUse = ourShapeToEnemyOutcome.key
listOf(opposingShape, shapeToUse)
}
// aggregate score for all matchups
return part1(matchups)
}
// test if implementation meets criteria from the description
val testInput = readInput("Day02_test")
println(part1(testInput) == 15)
println(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
// returns the RPS Shape associated with letters in the Secret Strategy Guide!
private fun getShapeAssociatedWithLetter(letter: String): Shape {
if (letter == "A" || letter == "X") {
return Shape.ROCK
}
if (letter == "B" || letter == "Y") {
return Shape.PAPER
}
if (letter == "C" || letter == "Z") {
return Shape.SCISSORS
}
throw IllegalArgumentException(letter + " is not a valid entry for competition")
}
private fun getOutcomeAssociatedWithLetter(letter: String): Outcome {
if (letter == "X") {
return Outcome.LOSE
}
if (letter == "Y") {
return Outcome.TIE
}
if (letter == "Z") {
return Outcome.WIN
}
throw IllegalArgumentException(letter + " is not a valid entry for competition")
}
// given the desired outcome for the player, returns our desired outcome for the opponent
private fun getDesiredOutcomeForOpponent(desiredOutcome: Outcome): Outcome {
if (desiredOutcome == Outcome.LOSE) {
return Outcome.WIN
}
if (desiredOutcome == Outcome.WIN) {
return Outcome.LOSE
}
return Outcome.TIE
}
private enum class Shape {
ROCK,
PAPER,
SCISSORS
}
private enum class Outcome {
LOSE,
TIE,
WIN
}
/**
* This class can be used to determine the outcome of a Rock-Paper-Scissors round given the player's [Shape] and the enemy's [Shape]
*/
private class RoundOutcomes {
companion object {
private val rockOutcomes: Map<Shape, Outcome> =
mapOf(Shape.ROCK to Outcome.TIE, Shape.PAPER to Outcome.LOSE, Shape.SCISSORS to Outcome.WIN)
private val paperOutcomes: Map<Shape, Outcome> =
mapOf(Shape.ROCK to Outcome.WIN, Shape.PAPER to Outcome.TIE, Shape.SCISSORS to Outcome.LOSE)
private val scissorsOutcomes: Map<Shape, Outcome> =
mapOf(Shape.ROCK to Outcome.LOSE, Shape.PAPER to Outcome.WIN, Shape.SCISSORS to Outcome.TIE)
// To get the outcome of a Rock-Paper-Scissors round, call roundOutcomes.get(<Player's Shape>).get(<Opponent's Shape>)
val roundOutcomes: Map<Shape, Map<Shape, Outcome>> =
mapOf(Shape.ROCK to rockOutcomes, Shape.PAPER to paperOutcomes, Shape.SCISSORS to scissorsOutcomes)
}
}
private class ShapeScore {
companion object {
// Maps shapes to the score earned when used
val score: Map<Shape, Int> = mapOf(Shape.ROCK to 1, Shape.PAPER to 2, Shape.SCISSORS to 3)
}
}
private class OutcomeScore {
// Maps outcomes to the resulting score earned
companion object {
val score: Map<Outcome, Int> = mapOf(Outcome.LOSE to 0, Outcome.TIE to 3, Outcome.WIN to 6)
}
}
| 0 | Kotlin | 0 | 0 | 6940ff5a3a04a29cfa927d0bbc093cd5df15cbcd | 4,895 | kotlin-advent-of-code | Apache License 2.0 |
src/Day08.kt | stevefranchak | 573,628,312 | false | {"Kotlin": 34220} | class TreeGrid(private val grid: List<List<Int>>) : List<List<Int>> by grid {
private val height
get() = this.size
// Assumption: all rows have the same length
private val width
get() = this[0].size
private fun goUpFrom(rowIndex: Int, columnIndex: Int) =
if (rowIndex == 0) emptyList()
else (rowIndex - 1 downTo 0).map { this[it][columnIndex] }
private fun goDownFrom(rowIndex: Int, columnIndex: Int) =
if (rowIndex == height - 1) emptyList()
else (rowIndex + 1 until height).map { this[it][columnIndex] }
private fun goLeftFrom(rowIndex: Int, columnIndex: Int) =
if (columnIndex == 0) emptyList()
else (columnIndex - 1 downTo 0).map { this[rowIndex][it] }
private fun goRightFrom(rowIndex: Int, columnIndex: Int) =
if (columnIndex == width - 1) emptyList()
else (columnIndex + 1 until width).map { this[rowIndex][it] }
fun isTreeAtPositionVisible(rowIndex: Int, columnIndex: Int): Boolean {
if (isPositionOnEdge(rowIndex, columnIndex)) return true
val treeHeightAtPosition = this[rowIndex][columnIndex]
if (goLeftFrom(rowIndex, columnIndex).all { it < treeHeightAtPosition }) return true
if (goRightFrom(rowIndex, columnIndex).all { it < treeHeightAtPosition }) return true
if (goUpFrom(rowIndex, columnIndex).all { it < treeHeightAtPosition }) return true
if (goDownFrom(rowIndex, columnIndex).all { it < treeHeightAtPosition }) return true
return false
}
private fun isPositionOnEdge(rowIndex: Int, columnIndex: Int) =
rowIndex == 0 || columnIndex == 0 || rowIndex == height - 1 || columnIndex == width - 1
fun getScenicScoreAtPosition(rowIndex: Int, columnIndex: Int): Int {
// If at least one viewing distance is 0, and each viewing distance is a factor in the multiplication,
// then the score will be 0
if (isPositionOnEdge(rowIndex, columnIndex)) return 0
val treeHeightAtPosition = this[rowIndex][columnIndex]
val leftViewingDistance = calculateViewingDistance(goLeftFrom(rowIndex, columnIndex), treeHeightAtPosition)
val rightViewingDistance = calculateViewingDistance(goRightFrom(rowIndex, columnIndex), treeHeightAtPosition)
val upViewingDistance = calculateViewingDistance(goUpFrom(rowIndex, columnIndex), treeHeightAtPosition)
val downViewingDistance = calculateViewingDistance(goDownFrom(rowIndex, columnIndex), treeHeightAtPosition)
return leftViewingDistance * rightViewingDistance * upViewingDistance * downViewingDistance
}
companion object {
fun fromInput(input: List<String>) =
TreeGrid(
input
.filter(String::isNotBlank)
.map { row -> row.toList().map(Char::digitToInt) }
.toList()
)
private fun calculateViewingDistance(treeHeights: List<Int>, heightOfCurrentTree: Int): Int {
var count = 0
for (treeHeight in treeHeights) {
count++
if (treeHeight >= heightOfCurrentTree) {
break
}
}
return count
}
}
override fun toString(): String {
return "TreeGrid[height=$height, width=$width, grid=$grid]"
}
}
fun main() {
fun Boolean.toInt() =
if (this) 1 else 0
fun part1(grid: TreeGrid) =
grid.mapIndexed { rowIndex, row ->
List(row.size) { columnIndex ->
grid.isTreeAtPositionVisible(rowIndex, columnIndex).toInt()
}.sum()
}.sum()
fun part2(grid: TreeGrid) =
grid.mapIndexed { rowIndex, row ->
List(row.size) { columnIndex ->
grid.getScenicScoreAtPosition(rowIndex, columnIndex)
}.max()
}.max()
readInput("Day08_test").also { input ->
val grid = TreeGrid.fromInput(input)
val part1TestOutput = part1(grid)
val part1ExpectedOutput = 21
check(part1TestOutput == part1ExpectedOutput) { "$part1TestOutput != $part1ExpectedOutput" }
val part2TestOutput = part2(grid)
val part2ExpectedOutput = 8
check(part2TestOutput == part2ExpectedOutput) { "$part2TestOutput != $part2ExpectedOutput" }
}
readInput("Day08").also { input ->
val grid = TreeGrid.fromInput(input)
println(part1(grid))
println(part2(grid))
}
}
| 0 | Kotlin | 0 | 0 | 22a0b0544773a6c84285d381d6c21b4b1efe6b8d | 4,491 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/Day05.kt | arosenf | 726,114,493 | false | {"Kotlin": 40487} | import kotlin.math.min
import kotlin.system.exitProcess
fun main(args: Array<String>) {
if (args.isEmpty() or (args.size < 2)) {
println("Almanac not specified")
exitProcess(1)
}
val fileName = args.first()
println("Reading $fileName")
val lines = readLines(fileName)
val result =
if (args[1] == "part1") {
Day05().findLowestLocation1(lines)
} else {
Day05().findLowestLocation2(lines)
}
println("Result: $result")
}
class Day05 {
fun findLowestLocation1(lines: Sequence<String>): Long {
val almanac = readAlmanac(lines)
return processAlmanac(almanac)
}
fun findLowestLocation2(lines: Sequence<String>): Long {
val almanac = expandSeeds(readAlmanac(lines))
return processAlmanac(almanac)
}
private fun processAlmanac(almanac: Almanac): Long {
var result = Long.MAX_VALUE
almanac.seeds.forEach { seed ->
var finalSeed = seed
almanac.maps.forEach { map ->
finalSeed = propagateSeed(finalSeed, map.ranges)
}
result = min(result, finalSeed)
}
return result
}
// We read everything and keep it in memory. No need to do stream processing, we got RAM! 💾
private fun readAlmanac(lines: Sequence<String>): Almanac {
var seeds: Sequence<Long> = emptySequence()
val almanacMaps: List<AlmanacMap> = arrayListOf()
var currentRanges: List<Range> = arrayListOf()
for (line in lines) {
if (line.isEmpty()) {
continue
} else if (line.startsWith("seeds: ")) {
seeds = line.substringAfter(':')
.trim()
.splitToSequence(' ')
.map(String::toLong)
} else if (line.endsWith("map:")) {
almanacMaps.addLast(AlmanacMap(currentRanges.asSequence()))
currentRanges = arrayListOf()
} else {
val parsedRange = line.splitToSequence(' ')
.map(String::toLong)
.toList()
currentRanges.addLast(Range(parsedRange[0], parsedRange[1], parsedRange[2]))
}
}
almanacMaps.addLast(AlmanacMap(currentRanges.asSequence()))
return Almanac(seeds, almanacMaps.asSequence())
}
private fun propagateSeed(seed: Long, ranges: Sequence<Range>): Long {
ranges.forEach {
if (seed >= it.sourceRangeStart && seed < it.sourceRangeStart + it.rangeLength) {
return it.destinationRangeStart + (seed - it.sourceRangeStart)
}
}
return seed
}
private fun expandSeeds(almanac: Almanac): Almanac {
return Almanac(
almanac.seeds
.chunked(2)
.map { it ->
generateSequence(it.first()) { it + 1 }
.take(it.last().toInt())
}
.flatten(),
almanac.maps
)
}
data class Almanac(val seeds: Sequence<Long>, val maps: Sequence<AlmanacMap>)
data class AlmanacMap(val ranges: Sequence<Range>)
data class Range(val destinationRangeStart: Long, val sourceRangeStart: Long, val rangeLength: Long)
}
| 0 | Kotlin | 0 | 0 | d9ce83ee89db7081cf7c14bcad09e1348d9059cb | 3,337 | adventofcode2023 | MIT License |
src/year2023/05/Day05.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2023.`05`
import readInput
import utils.printlnDebug
private const val CURRENT_DAY = "05"
data class RangeMap(
val input: LongRange,
val delta: Long,
)
data class Mapper(
val inputRanges: List<RangeMap>,
)
private fun parseIntoGroups(input: List<String>): List<List<String>> {
val listOfLists: MutableList<List<String>> = mutableListOf()
var currentList = mutableListOf<String>()
input.forEach {
if (it.isBlank()) {
listOfLists.add(currentList)
currentList = mutableListOf()
} else {
currentList.add(it)
}
}
if (currentList.isNotEmpty()) {
listOfLists.add(currentList)
}
return listOfLists
}
private fun parseGroupIntoMapper(group: List<String>): Mapper {
val ranges = group.drop(1)
.map { inputLine -> parseLineIntoSeeds(inputLine) }
.map { (dest, source, delta) ->
RangeMap(
input = source..<source + delta,
delta = dest - source,
)
}
return Mapper(ranges)
}
private fun parseLineIntoSeeds(line: String): Triple<Long, Long, Long> {
val res = line.split(" ")
.mapNotNull { it.toLongOrNull() }
val first = res.first()
val second = res[1]
val third = runCatching { res[2] }
.onFailure { error("Failed on line $line - ${it.message}") }
.getOrThrow()
return Triple(first, second, third)
}
private fun processMappers(
seeds: List<Long>,
mappers: List<Mapper>,
): Long {
val resListLocations = seeds
.asSequence()
.map {
mappers.fold(it) { cur, mapper ->
mapSeedFromInputToOutput(cur, mapper)
}
}
.min()
return resListLocations
}
private fun mapSeedFromInputToOutput(
seed: Long,
mappers: Mapper,
): Long {
val realMapRange = mappers.inputRanges.find {
it.input.contains(seed)
}
return if (realMapRange != null) {
seed + realMapRange.delta
} else {
seed
}
}
fun main() {
fun part1(input: List<String>): Long {
val seeds = input.first().split(" ")
.mapNotNull { it.toLongOrNull() }
val mappers = parseIntoGroups(input).map { parseGroupIntoMapper(it) }
val result = processMappers(seeds, mappers)
printlnDebug { "result : $result" }
return result
}
fun part2(input: List<String>): Long {
val mappers = parseIntoGroups(input).map { parseGroupIntoMapper(it) }
val seedRanges = input.first().split(" ")
.mapNotNull { it.toLongOrNull() }
.windowed(2, 2, false)
.map {
check(it.size == 2)
val first = it.first()
val second = it[1]
(first..<first + second)
}
.also { printlnDebug { "SIZE = ${it.size}" } }
.minOf { sedRange ->
printlnDebug { "Ranges seeds = $sedRange" }
sedRange.minOf { seedItem ->
val mappedValueLocation = mappers.fold(seedItem) { cur, mapper ->
mapSeedFromInputToOutput(
cur,
mapper
)
}
mappedValueLocation
}.also {
printlnDebug { "Counted Ranges seeds = $sedRange min = $it" }
}
}
return seedRanges
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${CURRENT_DAY}_test")
val part1Test = part1(testInput)
println(part1Test)
check(part1Test == 35L)
val part2Test = part2(testInput)
println(part2Test)
check(part2Test == 46L)
val input = readInput("Day$CURRENT_DAY")
// Part 1
val part1 = part1(input)
println(part1)
check(part1 == 910845529L)
// Part 2
val part2 = part2(input)
println(part2)
check(part2 == 77435348L)
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 4,057 | KotlinAdventOfCode | Apache License 2.0 |
src/day15/Day15.kt | henrikrtfm | 570,719,195 | false | {"Kotlin": 31473} | package day15
import utils.Resources.resourceAsListOfString
import kotlin.math.absoluteValue
typealias Point = Pair<Int,Int>
typealias SensorBeacon = Pair<Point,Point>
private const val MAX = 4000000
private const val MIN = 0
fun main(){
val input = resourceAsListOfString("src/day15/Day15.txt").map { parsePair(it) }
fun part1(row: Int): Int{
return input.filter { validSensor(row,it) }.flatMap { it.calculatePlaces(row) }.toSet().size-1
}
fun part2(rows: IntRange): Int{
for(row in rows){
val test = input.filter { validSensor(row,it) }
.flatMap { it.calculatePlaces(row) }
.toSet()
.filter { it.first in MIN..MAX }
.map { it.first }
.toSet()
when(test.size-1 < MAX){
true -> return (MIN..MAX).toSet().subtract(test).first()*4000000+row
else -> {}
}
}
return 0
}
println(part1(11))
println(part2(MIN..MAX))
}
fun getSensorY(item: SensorBeacon): Int = item.first.second
fun SensorBeacon.getSensor(): Point = this.first
fun manhattanDistance(item: SensorBeacon): Int{
return (item.first.first-item.second.first).absoluteValue+(item.first.second-item.second.second).absoluteValue
}
fun SensorBeacon.calculatePlaces(row: Int): Set<Point> {
return when (row > getSensorY(this)) {
true -> {
val offsetY = row - getSensorY(this)
val offsetX = manhattanDistance(this) - offsetY
val counter = offsetX * 2 + 1
addToResultSet(this.getSensor(), offsetX, offsetY, counter)
}
else -> {
val offsetY = (getSensorY(this) - row)
val offsetX = (manhattanDistance(this) - offsetY)
val counter = offsetX * 2 + 1
addToResultSet(this.getSensor(), offsetX, -offsetY, counter)
}
}
}
fun addToResultSet(sensor: Point, offsetX: Int, offsetY: Int, counter: Int): Set<Point>{
val resultSet = mutableSetOf<Point>()
for(x in 0 until counter){
resultSet.add(sensor+Point(-offsetX+x,offsetY))
}
return resultSet
}
fun validSensor(row: Int, item: SensorBeacon): Boolean {
val md = manhattanDistance(item)
val range = getSensorY(item) - md..getSensorY(item) + md
return row in range
}
fun parsePair(line: String):SensorBeacon {
val sensorX = line.substringAfter("x=").substringBefore(",").toInt()
val sensorY = line.substringAfter("y=").substringBefore(":").toInt()
val beaconX = line.substringAfterLast("x=").substringBeforeLast(",").toInt()
val beaconY = line.substringAfterLast("y=").trim().toInt()
return Pair(Point(sensorX,sensorY), Point(beaconX,beaconY))
}
private operator fun Point.plus(that: Point): Point =
Point(this.first + that.first, this.second + that.second)
| 0 | Kotlin | 0 | 0 | 20c5112594141788c9839061cb0de259f242fb1c | 2,862 | aoc2022 | Apache License 2.0 |
src/Day05.kt | Derrick-Mwendwa | 573,947,669 | false | {"Kotlin": 8707} | fun main() {
// NOTE: This will not work for stacks exceeding 9
fun getStacks(input: List<String>): Pair<List<MutableList<Char>>, Int> {
val regex = Regex("""([0-9])+""")
var stacks = 0
var limit = 0
for ((index, line) in input.withIndex()) {
val text = line.filter { !it.isWhitespace() }
if(regex.matches(text)) {
stacks = text.last().digitToInt()
limit = index
break
}
}
val temp = List(stacks) {
mutableListOf<Char>()
}
return temp to limit
}
fun part1(input: List<String>): String {
val stacks = getStacks(input)
var start = 1
for (x in stacks.first) {
for (index in stacks.second - 1 downTo 0) {
if (start < input[index].length && !input[index].elementAt(start).isWhitespace()) x.add(input[index].elementAt(start))
}
start += 4
}
val regexForCmd = Regex("""move ([0-9]+) from ([0-9]+) to ([0-9]+)""")
input.forEach {
if (it.startsWith("move")) {
val (count, from, to) = regexForCmd.matchEntire(it)!!.destructured
repeat(count.toInt()) {
val tmp2 = stacks.first[from.toInt() - 1].removeLast()
stacks.first[to.toInt() - 1].add(tmp2)
}
}
}
return stacks.first.map {
it.last()
}.joinToString("")
}
fun part2(input: List<String>): String {
val stacks = getStacks(input)
var start = 1
for (x in stacks.first) {
for (index in stacks.second - 1 downTo 0) {
if (start < input[index].length && !input[index].elementAt(start).isWhitespace()) x.add(input[index].elementAt(start))
}
start += 4
}
val regexForCmd = Regex("""move ([0-9]+) from ([0-9]+) to ([0-9]+)""")
input.forEach {
if (it.startsWith("move")) {
val (count, from, to) = regexForCmd.matchEntire(it)!!.destructured
val temp3 = mutableListOf<Char>()
repeat(count.toInt()) {
val tmp2 = stacks.first[from.toInt() - 1].removeLast()
temp3.add(tmp2)
}
temp3.reverse()
stacks.first[to.toInt() - 1].addAll(temp3)
}
}
return stacks.first.map {
it.last()
}.joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 7870800afa54c831c143b5cec84af97e079612a3 | 2,807 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day09.kt | kenyee | 573,186,108 | false | {"Kotlin": 57550} |
import kotlin.math.sign
fun main() { // ktlint-disable filename
val knots = mutableListOf<Position>()
val visited = mutableSetOf<Position>()
fun moveRope(dir: Direction, distance: Int) {
val tailIndex = knots.size - 1
val indexPairs = knots.indices.windowed(size = 2, step = 1)
repeat(distance) {
knots[0] = knots[0] + dir
for ((head, tail) in indexPairs) {
if (!knots[tail].isAdjacent(knots[head])) {
knots[tail] = Position(
knots[tail].x + (knots[head].x - knots[tail].x).sign,
knots[tail].y + (knots[head].y - knots[tail].y).sign
)
}
if (tail == tailIndex) {
visited.add(knots[tail])
}
}
}
}
fun parseCommands(input: List<String>) {
for (line in input) {
val tokens = line.split(" ")
val cmd = tokens[0]
val distance = tokens[1].toInt()
when (cmd) {
"R" -> moveRope(Direction.Right, distance)
"L" -> moveRope(Direction.Left, distance)
"U" -> moveRope(Direction.Up, distance)
"D" -> moveRope(Direction.Down, distance)
}
}
}
fun reset() {
visited.clear()
visited.add(Position(0, 0))
knots.clear()
}
fun part1(input: List<String>): Int {
reset()
repeat(2) { knots.add(Position(0, 0)) }
parseCommands(input)
return visited.size
}
fun part2(input: List<String>): Int {
reset()
repeat(10) { knots.add(Position(0, 0)) }
parseCommands(input)
return visited.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
println("Test total# tail positions: ${part1(testInput)}")
check(part1(testInput) == 13)
println("Test total# long tail positions: ${part2(testInput)}")
check(part2(testInput) == 1)
val input = readInput("Day09_input")
println("Total# of tail positions: ${part1(input)}")
println("Total# of long tail positions: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 814f08b314ae0cbf8e5ae842a8ba82ca2171809d | 2,265 | KotlinAdventOfCode2022 | Apache License 2.0 |
src/Day07.kt | Soykaa | 576,055,206 | false | {"Kotlin": 14045} | data class Node(var isDir: Boolean, var size: Int, val parent: Node?) {
var children: MutableMap<String, Node> = mutableMapOf()
}
private val root = Node(true, 0, null)
private fun createFileOrDir(parameter: String, parent: Node?): Node = if (parameter == "dir")
Node(true, 0, parent)
else {
Node(false, parameter.toInt(), parent)
}
private fun processCd(cdArg: String, currentNode: Node): Node = when (cdArg) {
"/" -> root
".." -> currentNode.parent ?: currentNode
else -> currentNode.children[cdArg]!!
}
private fun processFilesAndDirs(arguments: List<String>, currentNode: Node) {
currentNode.children.putIfAbsent(arguments[1], createFileOrDir(arguments[0], currentNode))
}
private fun calcSize(currentNode: Node): Int {
for (child in currentNode.children) currentNode.size += calcSize(child.value)
return currentNode.size
}
private fun init(input: List<String>) {
var currentNode = root
for (line in input) when {
line.contains("\$ cd") -> currentNode = processCd(line.split(" ")[2], currentNode)
!line.contains("\$ ls") -> processFilesAndDirs(line.split(" "), currentNode)
else -> {}
}
calcSize(root)
}
private fun allDirs(currentNode: Node, sizeSet: MutableSet<Int>): Set<Int> {
if (currentNode.isDir) sizeSet += currentNode.size
for (child in currentNode.children.values) sizeSet += allDirs(child, sizeSet)
return sizeSet
}
private fun totalMost(currentNode: Node, size: Int): Int {
var currentSize = 0
if (currentNode.isDir && currentNode.size <= size) currentSize = currentNode.size
for (child in currentNode.children.values) currentSize += totalMost(child, size)
return currentSize
}
fun main() {
fun part1(): Int = totalMost(root, 100000)
fun part2(): Int =
allDirs(root, mutableSetOf()).filter { it >= 30000000 - (70000000 - root.size) }.min()
val input = readInput("Day07")
init(input)
println(part1())
// println(allDirs(root, mutableSetOf()))
println(part2())
} | 0 | Kotlin | 0 | 0 | 1e30571c475da4db99e5643933c5341aa6c72c59 | 2,025 | advent-of-kotlin-2022 | Apache License 2.0 |
aoc/src/main/kotlin/com/bloidonia/aoc2023/day01/Main.kt | timyates | 725,647,758 | false | {"Kotlin": 45518, "Groovy": 202} | package com.bloidonia.aoc2023.day01
import com.bloidonia.aoc2023.lines
private val example = """1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet""".lines()
private val example2 = """two1nine
eightwothree
abcone2threexyz
xtwone3four
4nineeightseven2
zoneight234
7pqrstsixteen""".lines()
private fun firstLast(s: String) = s.filter { it.isDigit() }.let {
"${it.first()}${it.last()}".toInt()
}
private val words = mapOf(
// Conjoined numbers first
"oneight" to 18,
"twone" to 21,
"threeight" to 38,
"fiveight" to 58,
"sevenine" to 79,
"eightwo" to 82,
"eighthree" to 83,
"nineight" to 98,
"one" to 1,
"two" to 2,
"three" to 3,
"four" to 4,
"five" to 5,
"six" to 6,
"seven" to 7,
"eight" to 8,
"nine" to 9
)
private fun replacement(s: String): String {
var str = s
for (word in words.keys) {
str = str.replace(word, words[word].toString())
}
return str
}
fun main() {
val example = example.sumOf(::firstLast)
println("example: $example")
val lines = lines("/day01.input")
val part1 = lines.sumOf(::firstLast)
println("$part1")
println("replacement: ${replacement("one")}")
val example2 = example2
.map(::replacement)
.sumOf(::firstLast)
println("example2: $example2")
val part2 = lines.map(::replacement).sumOf(::firstLast)
println("$part2")
}
| 0 | Kotlin | 0 | 0 | 158162b1034e3998445a4f5e3f476f3ebf1dc952 | 1,401 | aoc-2023 | MIT License |
src/cn/leetcode/codes/simple111/Simple111.kt | shishoufengwise1234 | 258,793,407 | false | {"Java": 771296, "Kotlin": 68641} | package cn.leetcode.codes.simple111
import cn.leetcode.codes.common.TreeNode
import cn.leetcode.codes.createTreeNode
import cn.leetcode.codes.out
import java.util.*
import kotlin.math.min
fun main() {
val nums = arrayOf<Int?>(3, 9, 20, 15, 7)
val treeNode = createTreeNode(nums)
val re = minDepth(treeNode)
val re2 = minDepth2(treeNode)
out("re = $re")
out("re2 = $re2")
}
/*
111. 二叉树的最小深度
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:2
示例 2:
输入:root = [2,null,3,null,4,null,5,null,6]
输出:5
提示:
树中节点数的范围在 [0, 105] 内
-1000 <= Node.val <= 1000
*/
fun minDepth(root: TreeNode?): Int {
if (root == null) return 0
//遍历到底部了
if (root.left == null && root.right == null) {
return 1
}
var minValue = Int.MAX_VALUE
//遍历左子树
if (root.left != null) {
minValue = min(minValue, minDepth(root.left))
}
//递归右子树
if (root.right != null) {
minValue = min(minValue, minDepth(root.right))
}
//加上根节点层数据
return minValue + 1
}
//定义查询节点
class QueueNode(var node: TreeNode,var death: Int = 0)
//迭代解法 广度搜索
fun minDepth2(root: TreeNode?):Int{
if (root == null) return 0
val deque = LinkedList<QueueNode>()
deque.add(QueueNode(root,1))
while (!deque.isEmpty()){
val queue = deque.poll()
val node = queue.node
val death = queue.death
//到达第一个 左右节点都是null 情况 说明找到了最小的深度
if (node.left == null && node.right == null){
return death
}
//继续将左右子树压入栈内 进行遍历
if (node.left != null){
deque.add(QueueNode(node.left,death + 1))
}
if (node.right != null){
deque.add(QueueNode(node.right,death + 1))
}
}
//没有找到
return 0
}
//fun minDepth2(root: TreeNode?): Int {
// if (root == null) return 0
//
// var node = root
// val deque = LinkedList<TreeNode>()
// deque.add(node)
// var ans = 0
// while (!deque.isEmpty()) {
// var size = deque.size
// while (size > 0) {
// node = deque.poll()
// if (node.left != null) {
// deque.add(node.left)
// }
// if (node.right != null) {
// deque.add(node.right)
// }
// size--
// }
// ans++
// }
// return ans
//}
| 0 | Java | 0 | 0 | f917a262bcfae8cd973be83c427944deb5352575 | 2,761 | LeetCodeSimple | Apache License 2.0 |
src/main/java/com/booknara/problem/math/ConsecutiveNumbersSum.kt | booknara | 226,968,158 | false | {"Java": 1128390, "Kotlin": 177761} | package com.booknara.problem.math
/**
* 829. Consecutive Numbers Sum (Hard)
* https://leetcode.com/problems/consecutive-numbers-sum/
*/
class Solution {
// T:O(n), S:(1)
fun consecutiveNumbersSum(N: Int): Int {
var res = 1 // start with 1 because of N itself
for (i in 2..N) {
val sum = i * (i + 1) / 2
if (N - sum < 0) break
if (((N - sum) % i) == 0) res++
}
return res
}
}
/*
the number of consecutive number (n)
1 + 2 + 3 + .. + n => n (n + 1) / 2
2 + 3 + 4 + ...+ n + 1 -> 1 + 2 + 3 + .. + n + n => n (n + 1) / 2 + n
3 + 4 + 5 + ...+ n + 1 + n + 2 -> 1 + 2 + 3 + .. + n + n + n => n (n + 1) / 2 + 2n
k + ... + n + k - 1 -> 1 + 2 + 3 + .. + n + n + n => n (n + 1) / 2 + (k - 1) * n
N - n (n + 1) / 2 = (k - 1) * n
N - n (n + 1) / 2 mod n == 0 -> answer
*/ | 0 | Java | 1 | 1 | 04dcf500ee9789cf10c488a25647f25359b37a53 | 847 | playground | MIT License |
src/main/kotlin/de/mbdevelopment/adventofcode/year2021/solvers/day5/Day5Puzzle.kt | Any1s | 433,954,562 | false | {"Kotlin": 96683} | package de.mbdevelopment.adventofcode.year2021.solvers.day5
import de.mbdevelopment.adventofcode.year2021.solvers.PuzzleSolver
abstract class Day5Puzzle : PuzzleSolver {
companion object {
private val INPUT_PATTERN = "(\\d+),(\\d+) -> (\\d+),(\\d+)".toPattern()
}
abstract fun solve(lines: List<Line>, map: List<IntArray>): Int
final override fun solve(inputLines: Sequence<String>): String {
val lines = inputLines.toLines()
val map = emptyMapOf(lines)
return solve(lines, map).toString()
}
private fun Sequence<String>.toLines() = filter { it.isNotBlank() }
.map { it.toLine() }
.toList()
private fun String.toLine() = INPUT_PATTERN.matcher(this).let {
if (!it.matches()) throw IllegalArgumentException("'$this' cannot be converted to line")
val from = Point(it.group(1).toInt(), it.group(2).toInt())
val to = Point(it.group(3).toInt(), it.group(4).toInt())
Line(from, to)
}
private fun emptyMapOf(lines: List<Line>): List<IntArray> {
val furthestPoint = lines.fold(Point(0, 0)) { a, b ->
val maxX = listOf(a.x, b.from.x, b.to.x).maxOrNull() ?: 0
val maxY = listOf(a.y, b.from.y, b.to.y).maxOrNull() ?: 0
Point(maxX, maxY)
}
return List(furthestPoint.x + 1) { IntArray(furthestPoint.y + 1) { 0 } }
}
}
data class Point(val x: Int, val y: Int)
data class Line(val from: Point, val to: Point) {
fun points(): List<Point> {
val rangeX = (if (from.x <= to.x) from.x..to.x else from.x.downTo(to.x)).toList()
val rangeY = (if (from.y <= to.y) from.y..to.y else from.y.downTo(to.y)).toList()
return if (rangeX.size > 1 && rangeY.size > 1) {
rangeX.mapIndexed { index, x -> Point(x, rangeY[index]) }
} else if (rangeX.size > 1) {
rangeX.map { Point(it, from.y) }
} else if (rangeY.size > 1) {
rangeY.map { Point(from.x, it) }
} else {
emptyList()
}
}
} | 0 | Kotlin | 0 | 0 | 21d3a0e69d39a643ca1fe22771099144e580f30e | 2,049 | AdventOfCode2021 | Apache License 2.0 |
tools/intellij.tools.ide.metrics.collector/src/com/intellij/tools/ide/metrics/collector/metrics/collectionExtension.kt | JetBrains | 2,489,216 | false | null | package com.intellij.tools.ide.metrics.collector.metrics
import kotlin.math.pow
import kotlin.math.sqrt
/** @see medianValue */
fun Iterable<Long>.median(): Long {
val size = this.count()
require(size > 0) { "Cannot calculate median value because collection is empty" }
val sortedList = this.sorted()
// odd collection size
return if (size % 2 == 1) {
sortedList[size / 2]
}
// even collection size
else {
(sortedList[size / 2 - 1] + sortedList[size / 2]) / 2
}
}
/** Returns median (NOT an average) value of a collection */
fun Iterable<PerformanceMetrics.Metric>.medianValue(): Long = this.map { it.value }.median()
/**
* Calculates the standard deviation (std) - a measure of how spread out numbers are.
* A low std indicates that the values tend to be close to the mean, while a high std indicates that the values are spread out over a wider range.
*
* [Standard Deviation](https://en.wikipedia.org/wiki/Standard_deviation)
*/
fun <T : Number> Iterable<T>.standardDeviation(): Long {
val mean = this.map { it.toDouble() }.average()
return sqrt(this.map { (it.toDouble() - mean).pow(2) }.average()).toLong()
}
/** @see standardDeviation */
fun Iterable<PerformanceMetrics.Metric>.standardDeviationValue(): Long = this.map { it.value }.standardDeviation()
/** @see rangeValue */
fun Iterable<Long>.range(): Long {
val sorted = this.sorted()
return sorted.last() - sorted.first()
}
/** Difference between the smallest and the largest values */
fun Iterable<PerformanceMetrics.Metric>.rangeValue(): Long = this.map { it.value }.range()
| 251 | null | 5,079 | 16,158 | 831d1a4524048aebf64173c1f0b26e04b61c6880 | 1,585 | intellij-community | Apache License 2.0 |
src/Day07.kt | MerickBao | 572,842,983 | false | {"Kotlin": 28200} | fun main() {
// build a file tree
fun build(input: List<String>): Node {
val root = Node("/")
var curr: Node = root
val parent = HashMap<Node, Node>()
var i = 0
while (i < input.size) {
var now = input[i].split(" ")
if (now[1] == "cd") { // cd dir
if (now[2] == "/") curr = root // cd /
else if (now[2] == "..") curr = parent[curr]!! // cd ..
else curr = curr.child[now[2]]!! // cd subDir
} else {
// show the file of the dir
var j = i + 1
while (j < input.size && input[j][0] != '$') {
now = input[j].split(" ")
if (now[0] == "dir") {
val dir = Node(now[1])
dir.isDir = true
parent[dir] = curr
curr.child[now[1]] = dir
} else {
val file = Node(now[1])
file.size = now[0].toInt()
parent[file] = curr
curr.child[now[1]] = file
}
j++
}
i = j - 1
}
i++
}
return root
}
var tot = 0
var minDeletedSpace = Int.MAX_VALUE
fun dfs(root: Node, limit: Int, need: Int): Int {
var cnt = root.size
for (next in root.child.values) {
cnt += dfs(next, limit, need)
}
if (root.isDir && cnt <= limit) {
tot += cnt
}
if (root.isDir && cnt >= need) {
minDeletedSpace = Math.min(minDeletedSpace, cnt)
}
return cnt
}
fun part(input: List<String>) {
val root = build(input)
// in my input:
// total used space = 48008081
// left space = 70000000 - 48008081 = 21991919
// in order to get space 30000000, we need delete used space at least 30000000 - 21991919 = 8008081
dfs(root, 100000, 8008081)
println(tot)
println(minDeletedSpace)
}
val input = readInput("Day07")
part(input)
}
class Node(var name: String) {
var size: Int = 0
var isDir: Boolean = false
var child: HashMap<String, Node> = HashMap()
} | 0 | Kotlin | 0 | 0 | 70a4a52aa5164f541a8dd544c2e3231436410f4b | 2,339 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day07.kt | jordan-thirus | 573,476,470 | false | {"Kotlin": 41711} | fun main() {
fun parse(input: List<String>): Directory {
val que : ArrayDeque<Directory> = ArrayDeque()
val root = Directory("/")
que.addLast(root)
for(line in input.subList(1, input.size)){
val instructions = line.split(' ')
when(instructions[0]){
"$" -> {
when(instructions[1]){
"cd" -> {
//println("changing to ${instructions[2]}")
when(instructions[2]){
".." -> que.removeLast()
else -> que.addLast(que.last().getSubdirectory(instructions[2]))
}
}
"ls" -> {
//println("next will be directory list")
continue
}
}
}
"dir" -> {
//println("adding directory ${instructions[1]}")
que.last().addContent(Directory(instructions[1]))
}
else -> {
//println("adding file ${instructions[1]}")
que.last().addContent(File(instructions[1], instructions[0].toInt()))
}
}
}
print(root.buildDirectoryStructure())
return root
}
fun getTotalSizeOfDirsUnderSize(root: Directory, size: Int): Int {
var totalSize = 0
val que : ArrayDeque<Directory> = ArrayDeque()
que.add(root)
while(!que.isEmpty()){
val dir = que.removeFirst()
if(dir.size <= size) totalSize += dir.size
que.addAll(dir.getSubdirectories())
}
return totalSize
}
fun part1(input: List<String>): Int {
val root = parse(input)
return getTotalSizeOfDirsUnderSize(root, 100000)
}
fun getSmallestDirOverSize(root: Directory, size: Int): Directory {
var smallestDir = root
val que : ArrayDeque<Directory> = ArrayDeque()
que.add(root)
while(!que.isEmpty()){
val dir = que.removeFirst()
if(dir.size in size..smallestDir.size) {
smallestDir = dir
}
if(dir.size > size){
que.addAll(dir.getSubdirectories())
}
}
return smallestDir
}
fun part2(input: List<String>): Int {
val root = parse(input)
val requiredSpace = 30000000
val totalSpace = 70000000
val neededSpace = root.size - (totalSpace - requiredSpace)
val dir = getSmallestDirOverSize(root, neededSpace)
println("Smallest directory is $dir")
return dir.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
interface Content {
val type: ContentType
val name: String
val size: Int
}
class File(override val name: String, override val size: Int): Content {
override val type: ContentType = ContentType.FILE
override fun toString(): String {
return "- $name (file, size=$size)\n"
}
}
class Directory(override val name: String): Content {
override val type: ContentType = ContentType.DIRECTORY
private val contents: MutableList<Content> = mutableListOf()
override val size: Int
get() = contents.sumOf { c -> c.size }
fun addContent(content: Content) = contents.add(content)
fun getSubdirectory(name: String): Directory
= getSubdirectories().first() { c -> c.name == name }
fun getSubdirectories(): List<Directory> = contents.filterIsInstance<Directory>()
fun buildDirectoryStructure(prefix: String = ""): StringBuilder {
val sb = java.lang.StringBuilder()
val newPrefix = prefix + "\t"
sb.append("$prefix$this")
contents.forEach{c ->
when(c.type){
ContentType.FILE -> sb.append("$newPrefix$c")
ContentType.DIRECTORY -> sb.append((c as Directory).buildDirectoryStructure(newPrefix))
}
}
return sb
}
override fun toString(): String {
return "- $name (dir)\n"
}
}
enum class ContentType {
FILE, DIRECTORY
} | 0 | Kotlin | 0 | 0 | 59b0054fe4d3a9aecb1c9ccebd7d5daa7a98362e | 4,495 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/_2022/Day05.kt | novikmisha | 572,840,526 | false | {"Kotlin": 145780} | package _2022
import readGroupedInput
fun main() {
fun processCargo(input: List<List<String>>, itemSort: (items: List<String>) -> List<String>): String {
val (cargo, commands) = input
val numberOfColumns = cargo.last().split(" ")
.filter(String::isNotEmpty)
.maxOf { it.toInt() }
val stacks = List<ArrayDeque<String>>(numberOfColumns) { ArrayDeque() }
cargo.reversed().drop(1).forEach { items ->
items.replace("[", " ").replace("]", " ")
.split(" ")
.forEachIndexed { itemColumn, item ->
if (item.isNotEmpty()) {
stacks[itemColumn].addLast(item.trim())
}
}
}
for (command in commands) {
command
.split(" ")
.mapNotNull(String::toIntOrNull)
.let { (itemCount, from, to) ->
val lastItems = stacks[from - 1].takeLast(itemCount)
repeat(itemCount) { stacks[from - 1].removeLast() }
stacks[to - 1].addAll(itemSort(lastItems))
}
}
return stacks.joinToString("") { it.last() }
}
fun part1(input: List<List<String>>): String {
return processCargo(input) { it.reversed() }
}
fun part2(input: List<List<String>>): String {
return processCargo(input) { it }
}
// test if implementation meets criteria from the description, like:
val testInput = readGroupedInput("Day05_test")
println(part1(testInput))
println(part2(testInput))
val input = readGroupedInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 0c78596d46f3a8bf977bf356019ea9940ee04c88 | 1,730 | advent-of-code | Apache License 2.0 |
src/Day03.kt | JCampbell8 | 572,669,444 | false | {"Kotlin": 10115} | fun main() {
val lowerCaseLettersSet: Set<Char> = "abcdefghijklmnopqrstuvwxyz".toSet()
val upperCaseLettersSet: Set<Char> = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toSet()
fun convertLetterToNumber(letter: Char): Int {
var number = lowerCaseLettersSet.indexOf(letter)
if (number != -1)
number += 1
else {
number = upperCaseLettersSet.indexOf(letter)
number += 27
}
return number
}
fun part1(input: List<String>): Int {
return input.map { it.chunked(it.length / 2) }
.map { it[0].first { it2 -> it[1].contains(it2) } }
.map(::convertLetterToNumber)
.sum()
}
fun part2(input: List<String>): Int {
return input.windowed(3, 3)
.map { it[0].first { it2 -> it[1].contains(it2) && it[2].contains(it2) } }
.map(::convertLetterToNumber)
.sum()
}
// 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 | 1 | 0bac6b866e769d0ac6906456aefc58d4dd9688ad | 1,203 | advent-of-code-2022 | Apache License 2.0 |
src/Day13.kt | hrach | 572,585,537 | false | {"Kotlin": 32838} | fun main() {
@Suppress("UNCHECKED_CAST")
fun n(a: Any): List<Any> =
if (a is List<*>) a as List<Any> else listOf(a)
fun inOrder(li: Any, ri: Any): Boolean? {
val ll = n(li).toMutableList()
val rr = n(ri).toMutableList()
while (ll.isNotEmpty() || rr.isNotEmpty()) {
val l = ll.removeFirstOrNull() ?: return true
val r = rr.removeFirstOrNull() ?: return false
if (l is Int && r is Int) {
if (l < r) return true
if (l > r) return false
} else {
val inOrder = inOrder(l, r)
if (inOrder != null) return inOrder
}
}
return null
}
fun parseLine(line: String): Any {
var i = 0
val lists = mutableListOf<MutableList<Any>>()
var current = mutableListOf<Any>()
while (i < line.length) {
when (line[i]) {
'[' -> {
current = mutableListOf()
lists.lastOrNull()?.add(current)
lists.add(current)
i += 1
}
']' -> {
lists.removeLast()
if (lists.isEmpty()) return current
current = lists.last()
i += 1
}
',' -> {
i += 1
}
else -> {
val chars = line.substring(i).takeWhile { it != ',' && it != ']' }
i += chars.length
current.add(chars.toInt())
}
}
}
error("wrong structure")
}
fun parse(input: List<String>): List<Pair<Any, Any>> {
return input.chunked(3).map {
parseLine(it[0]) to parseLine(it[1])
}
}
fun part1(input: List<String>): Int {
val inputs = parse(input)
var sums = 0
inputs.forEachIndexed { index, (l, r) ->
val inOrder = inOrder(l, r)!!
if (inOrder) sums += index + 1
}
return sums
}
fun part2(input: List<String>): Int {
val inputs = input
.filter { it.isNotBlank() }
.map { parseLine(it) } +
listOf(listOf(listOf(2)), listOf(listOf(6)))
val sorted = inputs.sortedWith { l, r ->
when (inOrder(l, r)) {
null -> 0
true -> -1
false -> 1
}
}
val indexA = sorted.indexOf(listOf(listOf(2))) + 1
val indexB = sorted.indexOf(listOf(listOf(6))) + 1
return indexA * indexB
}
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 | 1 | 40b341a527060c23ff44ebfe9a7e5443f76eadf3 | 2,176 | aoc-2022 | Apache License 2.0 |
src/questions/LongestPalindrome.kt | realpacific | 234,499,820 | false | null | package questions
import _utils.UseCommentAsDocumentation
import utils.shouldBe
/**
* Given a string s which consists of lowercase or uppercase letters,
* return the length of the longest palindrome that can be built with those letters.
*
* Letters are case sensitive, for example, "Aa" is not considered a palindrome here.
*
* [Source](https://leetcode.com/problems/longest-palindrome/)
*/
@UseCommentAsDocumentation
private fun longestPalindrome(s: String): Int {
if (s.length == 1) return 1
val charCount = mutableMapOf<Char, Int>()
var result = 0
for (i in s) {
charCount[i] = charCount.getOrDefault(i, 0) + 1
// A letter can be used in palindrome iff there are 2 of them i.e one on each side (eg: level)
if (charCount[i]!! % 2 == 0) {
result += 2 // increment the count
charCount.remove(i) // remove it to make [charCount] loops efficient
}
}
for (i in charCount.values) {
if (i == 1) {
// See if there is an element in the map with count of 1
// this can be the letter in middle of the palindrome (eg: v in level)
result += 1
break
}
}
return result
}
fun main() {
longestPalindrome(s = "Aa") shouldBe 1
longestPalindrome(s = "abccccdd") shouldBe 7 // dccaccd
longestPalindrome(s = "a") shouldBe 1
longestPalindrome(s = "bb") shouldBe 2
}
| 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 1,423 | algorithms | MIT License |
day16/src/main/kotlin/Main.kt | rstockbridge | 159,586,951 | false | null | import java.io.File
fun main() {
val samples = parseInputPartI(readInputFilePartI())
println("Part I: the solution is ${solvePartI(samples)}.")
val instructions = parseInputPartII(readInputFilePartII())
println("Part II: the solution is ${solvePartII(samples, instructions)}.")
}
fun readInputFilePartI(): List<String> {
return File(ClassLoader.getSystemResource("inputPartI.txt").file).readLines()
}
fun parseInputPartI(input: List<String>): List<Sample> {
val beforeRegex = "Before:\\s+\\[(\\d), (\\d), (\\d), (\\d)]".toRegex()
val instructionRegex = "(\\d+) (\\d) (\\d) (\\d)".toRegex()
val afterRegex = "After:\\s+\\[(\\d), (\\d), (\\d), (\\d)]".toRegex()
return input
.chunked(4)
.map { sampleInput ->
val before = beforeRegex.matchEntire(sampleInput[0])!!.destructured
.toList()
.map(String::toInt)
val instruction = Instruction.fromList((instructionRegex.matchEntire(sampleInput[1])!!
.destructured
.toList()
.map(String::toInt)))
val after = afterRegex.matchEntire(sampleInput[2])!!
.destructured
.toList()
.map(String::toInt)
Sample(before, instruction, after)
}
}
fun solvePartI(samples: List<Sample>): Int {
return samples
.count { sample ->
Opcode.values()
.count { opcode ->
opcode.isConsistent(sample)
} >= 3
}
}
fun readInputFilePartII(): List<String> {
return File(ClassLoader.getSystemResource("inputPartII.txt").file).readLines()
}
fun parseInputPartII(input: List<String>): List<Instruction> {
val instructionRegex = "(\\d+) (\\d) (\\d) (\\d)".toRegex()
return input.map { line ->
Instruction.fromList(
instructionRegex.matchEntire(line)!!
.destructured
.toList()
.map(String::toInt)
)
}
}
fun solvePartII(samples: List<Sample>, instructions: List<Instruction>): Int {
val mapFromOpcodeIdToOpcode = matchOpcodesToOpcodeIds(calculatePossibleOpcodes(samples))
var registers = listOf(0, 0, 0, 0)
instructions.forEach { instruction ->
val opcode = mapFromOpcodeIdToOpcode[instruction.opcodeId]
registers = opcode!!.applyTo(registers, instruction.a, instruction.b, instruction.c)
}
return registers[0]
}
fun calculatePossibleOpcodes(samples: List<Sample>): Map<Int, Set<Opcode>> {
val result = mutableMapOf<Int, Set<Opcode>>()
for (opcodeId in 0..15) {
val possibleOpcodes = mutableSetOf<Opcode>()
samples
.filter { sample -> sample.instruction.opcodeId == opcodeId }
.forEach { sample ->
Opcode.values()
.forEach { opcode ->
if (opcode.isConsistent(sample)) {
possibleOpcodes.add(opcode)
}
}
}
result[opcodeId] = possibleOpcodes
}
return result
}
fun matchOpcodesToOpcodeIds(possibleOpcodes: Map<Int, Set<Opcode>>): MutableMap<Int, Opcode> {
val mutablePossibleOpcodes = mutableMapOf<Int, MutableSet<Opcode>>()
possibleOpcodes.forEach { mutablePossibleOpcodes[it.key] = it.value.toMutableSet() }
val result = mutableMapOf<Int, Opcode>()
var keepGoing = true
while (keepGoing) {
for (opcodeId in 0..15) {
if (mutablePossibleOpcodes[opcodeId]!!.size == 1) {
val opcode = mutablePossibleOpcodes[opcodeId]!!.first()
result[opcodeId] = opcode
for (opCodeId in 0..15) {
mutablePossibleOpcodes[opCodeId]!!.remove(opcode)
}
}
}
keepGoing = mutablePossibleOpcodes.any { it.value.isNotEmpty() }
}
return result
}
data class Sample(val before: List<Int>, val instruction: Instruction, val after: List<Int>)
data class Instruction(val opcodeId: Int, val a: Int, val b: Int, val c: Int) {
companion object {
fun fromList(ints: List<Int>): Instruction {
return Instruction(
opcodeId = ints[0],
a = ints[1],
b = ints[2],
c = ints[3]
)
}
}
}
| 0 | Kotlin | 0 | 0 | c404f1c47c9dee266b2330ecae98471e19056549 | 4,624 | AdventOfCode2018 | MIT License |
src/Day05.kt | afranken | 572,923,112 | false | {"Kotlin": 15538} | fun main() {
fun part1(input: List<String>, stackSize: Int, moveDrop: Int): String {
val stacks = mutableMapOf<Int, ArrayDeque<Char>>()
for (i in 0 until stackSize) {
stacks[i] = ArrayDeque()
}
input
.take(stackSize)
.filterNot(String::isBlank)
.map {
it
.chunkedSequence(4)
.forEachIndexed { index: Int, s: String ->
if (s.contains("[")) {
stacks[index]!!.addFirst(s.elementAt(s.indexOf("[")+1))
}
}
}
input.drop(moveDrop)
.map {
Move(it)
}.forEach {
for(i in 0 until it.count) {
stacks[it.to]!!.add(stacks[it.from]!!.removeLast())
}
}
val chars = stacks.values.map {
it.removeLast()
}.toCharArray()
val message = String(chars)
println(
message
)
return message
}
fun part2(input: List<String>, stackSize: Int, moveDrop: Int): String {
val stacks = mutableMapOf<Int, ArrayDeque<Char>>()
for (i in 0 until stackSize) {
stacks[i] = ArrayDeque()
}
input
.take(stackSize)
.filterNot(String::isBlank)
.map {
it
.chunkedSequence(4)
.forEachIndexed { index: Int, s: String ->
if (s.contains("[")) {
stacks[index]!!.addFirst(s.elementAt(s.indexOf("[")+1))
}
}
}
input.drop(moveDrop)
.map {
Move(it)
}.forEach {
val deque = ArrayDeque<Char>()
for(i in 0 until it.count) {
deque.addFirst(stacks[it.from]!!.removeLast())
}
stacks[it.to]!!.addAll(deque)
}
val chars = stacks.values.map {
it.removeLast()
}.toCharArray()
val message = String(chars)
println(
message
)
return message
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput, 3, 5) == "CMZ")
check(part2(testInput, 3, 5) == "MCD")
val input = readInput("Day05")
check(part1(input, 9, 10) == "VQZNJMWTR")
check(part2(input, 9, 10) == "NLCDCLVMQ")
}
//move 7 from 3 to 9
class Move(s: String) {
val count: Int
val from: Int
val to: Int
init {
//0 1 2 3 4 5
//move 7 from 3 to 9
val split = s.split(" ")
count = split[1].toInt()
//access starts at 0, not 1
from = split[3].toInt() - 1
to = split[5].toInt() - 1
}
}
| 0 | Kotlin | 0 | 0 | f047d34dc2a22286134dc4705b5a7c2558bad9e7 | 2,967 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day01.kt | proggler23 | 573,129,757 | false | {"Kotlin": 27990} | fun List<String>.partitionBy(separator: String): List<List<String>> {
return buildList {
val list = mutableListOf<String>()
for (value in this@partitionBy) {
if (value == separator) {
add(list.toList())
list.clear()
} else {
list.add(value)
}
}
add(list.toList())
}.filter { it.isNotEmpty() }
}
fun main() {
fun part1(input: List<String>): Int {
return input.partitionBy("").maxOf {
it.sumOf { line -> line.toInt() }
}
}
fun part2(input: List<String>): Int {
return input.partitionBy("").map {
it.sumOf { line -> line.toInt() }
}.sortedDescending().take(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 584fa4d73f8589bc17ef56c8e1864d64a23483c8 | 1,045 | advent-of-code-2022 | Apache License 2.0 |
src/Day01.kt | bananer | 434,885,332 | false | {"Kotlin": 36979} | fun main() {
fun part1(input: List<String>): Int {
return input.map { Integer.parseInt(it) }
.fold(Pair(Integer.MAX_VALUE, 0)) { (prev, count), next ->
Pair(
next,
if (next > prev) {
count + 1
} else {
count
}
)
}
.second
}
fun part2(input: List<String>): Int {
val numbers = input.map { it.toInt() }
return (3 until numbers.size).count { i ->
val prev = numbers.subList(i - 3, i).sum()
val curr = numbers.subList(i - 2, i + 1).sum()
curr > prev
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
val testOutput1 = part1(testInput)
check(testOutput1 == 7)
val testOutput2 = part2(testInput)
check(testOutput2 == 5)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 98f7d6b3dd9eefebef5fa3179ca331fef5ed975b | 1,074 | advent-of-code-2021 | Apache License 2.0 |
src/main/kotlin/y2023/day07/Day07.kt | TimWestmark | 571,510,211 | false | {"Kotlin": 97942, "Shell": 1067} | package y2023.day07
fun main() {
AoCGenerics.printAndMeasureResults(
part1 = { part1() },
part2 = { part2() }
)
}
typealias Hand = String
data class Game(
val bidValue: Int,
val hand: Hand
)
enum class HandType {
FIVE,
FOUR,
FULL_HOUSE,
THREE,
TWO_PAIR,
PAIR,
HIGH_CARD
}
fun input(): List<Game> {
return AoCGenerics.getInputLines("/y2023/day07/input.txt").map {
Game(
hand = it.split(" ")[0].trim(),
bidValue = it.split(" ")[1].trim().toInt()
)
}
}
fun Hand.getType1(): HandType {
val occurrencesMap = mutableMapOf<Char, Int>()
for (c in this) {
occurrencesMap.putIfAbsent(c, 0)
occurrencesMap[c] = occurrencesMap[c]!! + 1
}
return when {
occurrencesMap.values.contains(5) -> HandType.FIVE
occurrencesMap.values.contains(4) -> HandType.FOUR
occurrencesMap.values.containsAll(listOf(3,2)) -> HandType.FULL_HOUSE
occurrencesMap.values.contains(3) -> HandType.THREE
occurrencesMap.values.count { it == 2 } == 2 -> HandType.TWO_PAIR
occurrencesMap.values.count { it == 2 } == 1 -> HandType.PAIR
else -> HandType.HIGH_CARD
}
}
fun Hand.getType2(): HandType {
if (this.contains('J')) {
val numberOfJokers = count{it == 'J'}
if (numberOfJokers == 5) return HandType.FIVE
val stringWithoutJokers = filter { it != 'J' }
val occurrencesMapWithoutJokers = mutableMapOf<Char, Int>()
stringWithoutJokers.forEach { c ->
occurrencesMapWithoutJokers.putIfAbsent(c, 0)
occurrencesMapWithoutJokers[c] = occurrencesMapWithoutJokers[c]!! + 1
}
return when {
occurrencesMapWithoutJokers.values.maxOrNull()!! + numberOfJokers == 5 -> HandType.FIVE
occurrencesMapWithoutJokers.values.maxOrNull()!! + numberOfJokers == 4 -> HandType.FOUR
occurrencesMapWithoutJokers.values.count { it == 2 } == 2 -> HandType.FULL_HOUSE
occurrencesMapWithoutJokers.values.maxOrNull()!! + numberOfJokers == 3 -> HandType.THREE
else -> HandType.PAIR
}
} else {
val occurrencesMap = mutableMapOf<Char, Int>()
forEach { c ->
occurrencesMap.putIfAbsent(c, 0)
occurrencesMap[c] = occurrencesMap[c]!! + 1
}
return when {
occurrencesMap.values.contains(5) -> HandType.FIVE
occurrencesMap.values.contains(4) -> HandType.FOUR
occurrencesMap.values.containsAll(listOf(3,2)) -> HandType.FULL_HOUSE
occurrencesMap.values.contains(3) -> HandType.THREE
occurrencesMap.values.count { it == 2 } == 2 -> HandType.TWO_PAIR
occurrencesMap.values.count { it == 2 } == 1 -> HandType.PAIR
else -> HandType.HIGH_CARD
}
}
}
fun Game.compareToOther1(other: Game): Int {
val thisType = this.hand.getType1()
val otherType = other.hand.getType1()
if (thisType < otherType) return 1
if (thisType > otherType) return -1
this.hand.forEachIndexed { index, thisChar ->
val otherChar = other.hand[index]
if (thisChar == otherChar) return@forEachIndexed
if (thisChar.toValue1() > otherChar.toValue1()) return 1
if (thisChar.toValue1() < otherChar.toValue1()) return -1
}
return 0
}
fun Game.compareToOther2(other: Game): Int {
val thisType = this.hand.getType2()
val otherType = other.hand.getType2()
if (thisType < otherType) return 1
if (thisType > otherType) return -1
this.hand.forEachIndexed { index, thisChar ->
val otherChar = other.hand[index]
if (thisChar == otherChar) return@forEachIndexed
if (thisChar.toValue2() > otherChar.toValue2()) return 1
if (thisChar.toValue2() < otherChar.toValue2()) return -1
}
return 0
}
fun Char.toValue1(): Int {
return when {
this.isDigit() -> this.digitToInt()
this == 'T' -> 10
this == 'J' -> 11
this == 'Q' -> 12
this == 'K' -> 13
else -> 14
}
}
fun Char.toValue2(): Int {
return when {
this.isDigit() -> this.digitToInt()
this == 'T' -> 10
this == 'J' -> 1
this == 'Q' -> 11
this == 'K' -> 12
else -> 13
}
}
fun part1(): Int {
val games = input()
val sortedGames = games.sortedWith { game1, game2 ->
game1.compareToOther1(game2)
}
var result = 0
sortedGames.forEachIndexed { index, game ->
result += (index+1) * game.bidValue
}
return result
}
fun part2(): Int {
val games = input()
val sortedGames = games.sortedWith { game1, game2 ->
game1.compareToOther2(game2)
}
var result = 0
sortedGames.forEachIndexed { index, game ->
result += (index+1) * game.bidValue
}
return result
}
| 0 | Kotlin | 0 | 0 | 23b3edf887e31bef5eed3f00c1826261b9a4bd30 | 4,930 | AdventOfCode | MIT License |
src/main/kotlin/com/ginsberg/advent2021/Day16.kt | tginsberg | 432,766,033 | false | {"Kotlin": 92813} | /*
* Copyright (c) 2021 by <NAME>
*/
/**
* Advent of Code 2021, Day 16 - Packet Decoder
* Problem Description: http://adventofcode.com/2021/day/16
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2021/day16/
*/
package com.ginsberg.advent2021
class Day16(input: String) {
private val binaryInput: Iterator<Char> = hexToBinary(input).iterator()
fun solvePart1(): Int =
BITSPacket.of(binaryInput).allVersions().sum()
fun solvePart2(): Long =
BITSPacket.of(binaryInput).value
private fun hexToBinary(input: String): List<Char> =
input.map { it.digitToInt(16).toString(2).padStart(4, '0') }.flatMap { it.toList() }
private sealed class BITSPacket(val version: Int) {
abstract val value: Long
companion object {
fun of(input: Iterator<Char>): BITSPacket {
val version = input.nextInt(3)
return when (val packetType = input.nextInt(3)) {
4 -> BITSLiteral.of(version, input)
else -> BITSOperator.of(version, packetType, input)
}
}
}
abstract fun allVersions(): List<Int>
}
private class BITSLiteral(version: Int, override val value: Long) : BITSPacket(version) {
override fun allVersions(): List<Int> = listOf(version)
companion object {
fun of(version: Int, input: Iterator<Char>): BITSLiteral =
BITSLiteral(version, parseLiteralValue(input))
private fun parseLiteralValue(input: Iterator<Char>): Long =
input.nextUntilFirst(5) { it.startsWith('0') }.map { it.drop(1) }.joinToString("").toLong(2)
}
}
private class BITSOperator(version: Int, type: Int, val subPackets: List<BITSPacket>) : BITSPacket(version) {
override fun allVersions(): List<Int> =
listOf(version) + subPackets.flatMap { it.allVersions() }
override val value: Long = when (type) {
0 -> subPackets.sumOf { it.value }
1 -> subPackets.fold(1) { acc, next -> acc * next.value }
2 -> subPackets.minOf { it.value }
3 -> subPackets.maxOf { it.value }
5 -> if (subPackets.first().value > subPackets.last().value) 1 else 0
6 -> if (subPackets.first().value < subPackets.last().value) 1 else 0
7 -> if (subPackets.first().value == subPackets.last().value) 1 else 0
else -> error("Invalid Operator type")
}
companion object {
fun of(version: Int, type: Int, input: Iterator<Char>): BITSOperator {
return when (input.nextInt(1)) { // Length Type
0 -> {
val subPacketLength = input.nextInt(15)
val subPacketIterator = input.next(subPacketLength).iterator()
val subPackets = subPacketIterator.executeUntilEmpty { of(it) }
BITSOperator(version, type, subPackets)
}
1 -> {
val numberOfPackets = input.nextInt(11)
val subPackets = (1..numberOfPackets).map { of(input) }
BITSOperator(version, type, subPackets)
}
else -> error("Invalid Operator length type")
}
}
}
}
}
| 0 | Kotlin | 2 | 34 | 8e57e75c4d64005c18ecab96cc54a3b397c89723 | 3,424 | advent-2021-kotlin | Apache License 2.0 |
src/day8/Day8.kt | davidcurrie | 579,636,994 | false | {"Kotlin": 52697} | package day8
import java.io.File
fun main() {
val lines = File("src/day8/input.txt").readLines()
val trees = mutableMapOf<Pair<Int, Int>, Int>()
for (j in lines.indices) {
for (i in 0 until lines[j].length) {
trees[Pair(i, j)] = lines[j][i].toString().toInt()
}
}
val visible = mutableSetOf<Pair<Int, Int>>()
for (j in lines.indices) {
visible.addAll(visible(trees, Pair(0, j), Pair(1, 0)))
visible.addAll(visible(trees, Pair(lines[j].length - 1, j), Pair(-1, 0)))
}
for (i in 0 until lines[0].length) {
visible.addAll(visible(trees, Pair(i, 0), Pair(0, 1)))
visible.addAll(visible(trees, Pair(i, lines.size - 1), Pair(0, -1)))
}
println(visible.size)
println(trees.keys.maxOfOrNull { scenicScore(trees, it) })
}
fun scenicScore(trees: Map<Pair<Int, Int>, Int>, tree: Pair<Int, Int>): Int {
val deltas = listOf(Pair(0, 1), Pair(1, 0), Pair(-1, 0), Pair(0, -1))
var total = 1
for (delta in deltas) {
var coord = tree
var score = 0
while (true) {
coord = Pair(coord.first + delta.first, coord.second + delta.second)
if (coord in trees.keys) {
if (trees[coord]!! < trees[tree]!!) {
score++
} else {
score++
break
}
} else {
break
}
}
total *= score
}
return total
}
fun visible(trees: Map<Pair<Int, Int>, Int>, start: Pair<Int, Int>, delta: Pair<Int, Int>) : Set<Pair<Int, Int>> {
val visible = mutableSetOf<Pair<Int, Int>>()
visible.add(start)
var height = trees[start]!!
var coord = start
while (true) {
coord = Pair(coord.first + delta.first, coord.second + delta.second)
if (coord !in trees.keys) {
break
}
if (trees[coord]!! > height) {
height = trees[coord]!!
visible.add(coord)
}
}
return visible
} | 0 | Kotlin | 0 | 0 | 0e0cae3b9a97c6019c219563621b43b0eb0fc9db | 2,049 | advent-of-code-2022 | MIT License |
src/Day05.kt | fedochet | 573,033,793 | false | {"Kotlin": 77129} | import kotlin.text.StringBuilder
fun main() {
fun parseCargoLine(line: String): List<Char?> = buildList {
var currentIdx = 0
while (currentIdx < line.length) {
val cargo = line.substring(currentIdx, currentIdx + 3)
val cargoLetter = if (cargo.isNotBlank()) {
cargo.removeSurrounding("[", "]").single()
} else {
null
}
add(cargoLetter)
currentIdx += 4
}
}
fun parseCargoSetup(setup: List<String>): List<StringBuilder> {
val cargoLines = setup.dropLast(1).asReversed()
val cargoLevels = cargoLines.map { level -> parseCargoLine(level) }
val result = MutableList(cargoLevels.first().size) { StringBuilder() }
cargoLevels.forEach { cargoLevel ->
cargoLevel.forEachIndexed { idx, cargo ->
if (cargo != null) {
result[idx].append(cargo)
}
}
}
return result
}
data class MoveCommand(val from: Int, val to: Int, val count: Int)
fun parseCommand(command: String): MoveCommand {
val (count, from, to) = command
.replace("move ", "")
.replace("from ", "")
.replace("to ", "")
.split(" ", limit = 3)
.map { it.toInt() }
return MoveCommand(from - 1, to - 1, count)
}
fun StringBuilder.removeLast(count: Int): String {
require(length >= count)
val tail = takeLast(count).toString()
setLength(length - count)
return tail
}
fun parseInput(input: List<String>): Pair<List<StringBuilder>, List<MoveCommand>> {
val separatorPosition = input.indexOfFirst { it.isBlank() }
val crates = parseCargoSetup(input.take(separatorPosition))
val commands = input.drop(separatorPosition + 1).map { parseCommand(it) }
return crates to commands
}
fun crateMover9000(crates: List<StringBuilder>, command: MoveCommand) {
val from = crates[command.from]
val to = crates[command.to]
val toMove = from.removeLast(command.count)
to.append(toMove.reversed())
}
fun topLevelCrates(crates: List<StringBuilder>): String =
crates.joinToString("") { it.last().toString() }
fun part1(input: List<String>): String {
val (crates, commands) = parseInput(input)
commands.forEach { crateMover9000(crates, it) }
return topLevelCrates(crates)
}
fun crateMover9001(crates: List<StringBuilder>, command: MoveCommand) {
val from = crates[command.from]
val to = crates[command.to]
val toMove = from.removeLast(command.count)
to.append(toMove)
}
fun part2(input: List<String>): String {
val (crates, commands) = parseInput(input)
commands.forEach { crateMover9001(crates, it) }
return topLevelCrates(crates)
}
// 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 | 1 | 975362ac7b1f1522818fc87cf2505aedc087738d | 3,253 | aoc2022 | Apache License 2.0 |
src/main/kotlin/com/uber/tagir/advent2018/day04/day04.kt | groz | 159,977,575 | false | null | package com.uber.tagir.advent2018.day04
import com.uber.tagir.advent2018.utils.resourceAsString
fun main(args: Array<String>) {
with(Day04()) {
strategy1()
strategy2()
}
}
class Day04 {
private val input = resourceAsString("input.txt").lines().sorted()
private val schedule = parseSchedule(input)
private fun parseSchedule(lines: Collection<String>): Map<Int, Map<Int, Int>> {
// output type: {guardId -> {minute -> count}}
val entry = """\[(\d{4}-\d{2}-\d{2}) \d{2}:(\d{2})] (.*)""".toRegex()
val beginShift = """Guard #(\d+) begins shift""".toRegex()
val fallsAsleep = "falls asleep"
val wakesUp = "wakes up"
var currentGuardId: Int? = null
val schedule = mutableMapOf<Int, MutableMap<Int, Int>>()
var asleepFrom: Int? = null
// imperative nightmare :(
for (line in lines) {
val (date, time, event) = entry.matchEntire(line)!!.destructured
val nextGuardId: Int? = beginShift.matchEntire(event)?.groups?.get(1)?.value?.toInt()
if (currentGuardId == null) {
currentGuardId = nextGuardId
asleepFrom = null
continue
}
if (event == fallsAsleep) {
asleepFrom = time.toInt()
continue
}
if (asleepFrom != null) {
val asleepUntil: Int = if (event == wakesUp) time.toInt() else 59
val guardsSchedule = schedule.getOrDefault(currentGuardId, mutableMapOf())
for (minute in asleepFrom until asleepUntil) {
guardsSchedule[minute] = guardsSchedule.getOrDefault(minute, 0) + 1
}
schedule[currentGuardId] = guardsSchedule
if (event == wakesUp) {
asleepFrom = null
}
}
if (nextGuardId != null) {
currentGuardId = nextGuardId
asleepFrom = null
}
}
return schedule
}
private fun choiceHash(guardId: Int, sleepMap: Map<Int, Int>): Int? {
return sleepMap.maxBy { (minute, count) -> count }?.let { (minute, count) -> guardId * minute }
}
fun strategy1() {
val maxByTotalSleepTime = schedule.maxBy { (_, sleepMap) -> sleepMap.values.sum() }
val result = maxByTotalSleepTime?.let { (guardId, sleepMap) -> choiceHash(guardId, sleepMap) }
println(result)
}
fun strategy2() {
val maxByMinute = schedule.maxBy { (_, sleepMap) -> sleepMap.values.max() ?: 0 }
val result = maxByMinute?.let { (guardId, sleepMap) -> choiceHash(guardId, sleepMap) }
println(result)
}
}
| 0 | Kotlin | 0 | 0 | 19b5a5b86c9a3d2803192b8c6786a25151b5144f | 2,762 | advent2018 | MIT License |
src/com/ncorti/aoc2023/Day04.kt | cortinico | 723,409,155 | false | {"Kotlin": 76642} | package com.ncorti.aoc2023
data class ScratchCard(val winningNumbers: List<Int>, val playerNumbers: List<Int>, var count: Int = 1) {
companion object {
fun from(input: String) = ScratchCard(
winningNumbers = input.substringAfter(":").substringBefore("|").split(" ").filter(String::isNotBlank)
.map(String::toInt),
playerNumbers = input.substringAfter("|").split(" ").filter(String::isNotBlank).map(String::toInt),
)
}
fun scoreV1(): Int {
var score = 0
playerNumbers.forEach { number ->
if (number in winningNumbers && score == 0) {
score = 1
} else if (number in winningNumbers) {
score *= 2
}
}
return score
}
fun countMatching(): Int = playerNumbers.count { it in winningNumbers }
}
fun main() {
fun part1(): Int {
return getInputAsText("04") {
split("\n").filter(String::isNotBlank).map { ScratchCard.from(it) }
}.sumOf { it.scoreV1() }
}
fun part2(): Int {
val cards = getInputAsText("04") {
split("\n").filter(String::isNotBlank).map { ScratchCard.from(it) }
}
for (i in cards.indices) {
val winnings = cards[i].countMatching()
val originalCount = cards[i].count
for (j in 1..winnings) {
cards[i + j].count += originalCount
}
}
return cards.sumOf { it.count }
}
println(part1())
println(part2())
}
| 1 | Kotlin | 0 | 1 | 84e06f0cb0350a1eed17317a762359e9c9543ae5 | 1,555 | adventofcode-2023 | MIT License |
src/main/kotlin/com/groundsfam/advent/y2023/d05/Day05.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2023.d05
import com.groundsfam.advent.DATAPATH
import com.groundsfam.advent.except
import com.groundsfam.advent.rangeIntersect
import com.groundsfam.advent.timed
import kotlin.io.path.div
import kotlin.io.path.useLines
// Models the mapping specified by a single row of the input.
//
// seed-to-soil map:
// 50 98 2
// 52 50 48
//
// corresponds to listOf(
// FarmMapEntry(sourceNums=98..99, diff=-48),
// FarmMapEntry(sourceNums=50..97, diff=2)
// )
data class FarmMapEntry(val sourceNums: LongRange, val diff: Long)
typealias FarmMap = List<FarmMapEntry>
fun mapSeedToLocation(seedNum: Long, maps: List<FarmMap>): Long =
maps.fold(seedNum) { elementNum, farmMap ->
val diff = farmMap
.firstOrNull { elementNum in it.sourceNums }
?.diff
?: 0
elementNum + diff
}
fun mapElementRange(elementRange: LongRange, map: FarmMap): List<LongRange> {
val mapped = mutableListOf<LongRange>()
val notMapped = map.fold(listOf(elementRange)) { ranges, (sourceNums, diff) ->
ranges.flatMap { range ->
// find the part of this range which is mapped by this FarmMapEntry
// apply the mapping and add it to the mapped list
range.rangeIntersect(sourceNums)?.also {
mapped.add((it.first + diff)..(it.last + diff))
}
// find the part(s) of this range which are not mapped by this FarmMapEntry
// and pass them along to be mapped by the next FarmMapEntry
range.except(sourceNums)
}
}
mapped.addAll(notMapped)
return mapped
}
fun main() = timed {
val seedNums = mutableListOf<Long>()
val maps = mutableListOf<FarmMap>()
(DATAPATH / "2023/day05.txt").useLines { lines ->
val iter = lines.iterator()
iter.next()
.split(" ")
.drop(1) // remove the "seeds:" prefix
.forEach { seedNums.add(it.toLong()) }
iter.next() // remove blank line following seed numbers
var map = mutableListOf<FarmMapEntry>()
iter.forEach { line ->
when {
line.isBlank() -> {
// previous FarmMap is now complete
maps.add(map)
map = mutableListOf()
}
line[0].isDigit() -> {
val (destFrom, sourceFrom, rangeLength) = line.split(" ").map(String::toLong)
FarmMapEntry(
sourceNums = sourceFrom until (sourceFrom + rangeLength),
diff = destFrom - sourceFrom
).also {
map.add(it)
}
}
else -> {
// otherwise this line is a "X-to-Y map:" header, ignore
}
}
}
// add the last FarmMap
maps.add(map)
}
seedNums
.minOf { mapSeedToLocation(it, maps) }
.also { println("Part one: $it") }
seedNums
.chunked(2) { (start, length) -> start until (start + length) }
.let { seedRanges ->
maps.fold(seedRanges) { ranges, map ->
ranges.flatMap { mapElementRange(it, map) }
}
}
.minOf { it.first }
.also { println("Part two: $it") }
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 3,378 | advent-of-code | MIT License |
src/main/kotlin/nl/dirkgroot/adventofcode/year2021/Day24.kt | dirkgroot | 317,968,017 | false | {"Kotlin": 187862} | package nl.dirkgroot.adventofcode.year2021
import nl.dirkgroot.adventofcode.util.Puzzle
import kotlin.math.pow
class Day24 : Puzzle() {
private val functions = listOf(
1L, 13L, 8L, 1L, 12L, 13L, 1L, 12L, 8L, 1L, 10L, 10L, 26L, -11L, 12L, 26L, -13L, 1L, 1L, 15L, 13L,
1L, 10L, 5L, 26L, -2L, 10L, 26L, -6L, 3L, 1L, 14L, 2L, 26L, 0L, 2L, 26L, -15L, 12L, 26L, -4L, 7L,
).windowed(3, 3).map { (p1, p2, p3) -> function(p1, p2, p3) }
private val functions1 = functions.take(6)
private val functions2 = functions.drop(6).take(4)
private val functions3 = functions.drop(10)
private fun function(p1: Long, p2: Long, p3: Long) =
{ input: Long, z: Long ->
if ((z % 26) + p2 == input) { // 0L else 1L
z / p1
} else {
z / p1 * 26 + input + p3
}
}
override fun part1() = findFirstValid(false)
override fun part2() = findFirstValid(true)
private fun findFirstValid(upTo: Boolean): Long {
var minZ = 99999999999999L
val step1Cache = mutableSetOf<Long>()
var step1Hits = 0L
val step2Cache = mutableSetOf<Long>()
var step2Hits = 0L
return findZs(functions1, 0L, upTo)
.flatMap { (z1, c1) ->
if (!step1Cache.contains(z1)) {
step1Cache.add(z1)
findZs(functions2, z1, upTo).flatMap { (z2, c2) ->
if (!step2Cache.contains(z2)) {
step2Cache.add(z2)
findZs(functions3, z2, upTo).map { (z3, c3) ->
z3 to (c1 * 100000000L) + (c2 * 10000) + c3
}
} else emptySequence<Pair<Long, Long>>().also { step1Hits++ }
}
} else emptySequence<Pair<Long, Long>>().also { step2Hits++ }
}
.onEach { (z, c) ->
if (z < minZ) {
minZ = z
println("New min: [c: $c, z: $z]")
}
}
.filter { (z, _) -> z == 0L }
.map { (_, c) -> c }
.first()
.also {
println("cache1: ${step1Cache.size}")
println("hits1: $step1Hits")
println("cache2: ${step2Cache.size}")
println("hits2: $step2Hits")
}
}
private fun findZs(fs: List<(Long, Long) -> Long>, initialZ: Long, upTo: Boolean): Sequence<Pair<Long, Long>> {
val range = if (upTo) createUpToRange(fs.size) else createDownToRange(fs.size)
return range.asSequence().filter { noZeroes(it) }
.map {
val input = toLongList(it, fs.size)
it to fs.foldIndexed(initialZ) { index, acc, f -> f(input[index], acc) }
}
.groupBy { (_, z) -> z }
.map { (z, cs) -> z to if (upTo) cs.minOf { (c, _) -> c } else cs.maxOf { (c, _) -> c } }
.asSequence()
.let {
if (upTo) it.sortedBy { (_, c) -> c }
else it.sortedByDescending { (_, c) -> c }
}
}
private fun createUpToRange(digits: Int): LongProgression {
val start = (1..digits).fold(0L) { acc, _ -> acc * 10 + 1L }
val end = (1..digits).fold(0L) { acc, _ -> acc * 10 + 9L }
return start..end
}
private fun createDownToRange(digits: Int): LongProgression {
val start = (1..digits).fold(0L) { acc, _ -> acc * 10 + 9L }
val end = (1..digits).fold(0L) { acc, _ -> acc * 10 + 1L }
return start downTo end
}
private fun noZeroes(number: Long) = generateSequence(number) { it / 10 }
.takeWhile { it > 0 }
.filter { it % 10L == 0L }
.none()
private fun toLongList(n: Long, digitCount: Int): List<Long> =
generateSequence(10.0.pow(digitCount - 1).toLong()) { it / 10 }
.map { if (it == 0L) n % 10 else n / it % 10 }
.take(digitCount)
.toList()
}
| 1 | Kotlin | 1 | 1 | ffdffedc8659aa3deea3216d6a9a1fd4e02ec128 | 4,070 | adventofcode-kotlin | MIT License |
y2023/src/main/kotlin/adventofcode/y2023/Day11.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2023
import adventofcode.io.AdventSolution
import adventofcode.util.collections.combinations
import adventofcode.util.vector.Vec2
fun main() {
Day11.solve()
}
object Day11 : AdventSolution(2023, 11, "Cosmic Expansion") {
override fun solvePartOne(input: String) = solve(input, expansion = 2)
override fun solvePartTwo(input: String) = solve(input, expansion = 1_000_000)
fun solve(input: String, expansion: Int): Long {
val stars = parse(input)
val expanded = expandSpace(stars, expansion)
return expanded.combinations(Vec2::distance).sumOf(Int::toLong)
}
private fun parse(input: String): Set<Vec2> = input.lines()
.flatMapIndexed { y, line ->
line.withIndex()
.filter { it.value == '#' }
.map { (x) -> Vec2(x, y) }
}
.toSet()
private fun expandSpace(stars: Set<Vec2>, expansion: Int): List<Vec2> {
val nonEmptyColumns = stars.map { it.x }.toSet()
val nonEmptyRows = stars.map { it.y }.toSet()
val expandedX = (0..nonEmptyColumns.max()).scan(0) { x, col -> x + if (col in nonEmptyColumns) 1 else expansion }
val expandedY = (0..nonEmptyRows.max()).scan(0) { y, row -> y + if (row in nonEmptyRows) 1 else expansion }
return stars.map { Vec2(expandedX[it.x], expandedY[it.y]) }
}
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,377 | advent-of-code | MIT License |
src/Day01.kt | roxspring | 573,123,316 | false | {"Kotlin": 9291} | fun main() {
fun part1(input: List<String>): Int = input.chunkedByBlank()
.map { lines -> lines.sumOf { it.toInt() } }
.max()
fun part2(input: List<String>): Int = input.chunkedByBlank()
.map { lines -> lines.sumOf { it.toInt() } }
.sortedDescending()
.take(3)
.sum()
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
val input = readInput("Day01")
println(part1(input))
check(part2(testInput) == 45000)
println(part2(input))
}
/**
* Splits the list into chunks delimited by blank lines.
*
* @return a sequence of lists of non-blank lines.
*/
fun List<String>.chunkedByBlank(): Sequence<List<String>> = sequence {
var start = 0
forEachIndexed { index, line ->
if (line.isEmpty()) {
yield(subList(start, index))
start = index + 1
}
}
yield(subList(start, size))
}
| 0 | Kotlin | 0 | 0 | 535beea93bf84e650d8640f1c635a430b38c169b | 1,006 | advent-of-code-2022 | Apache License 2.0 |
src/aoc2022/Day07.kt | FluxCapacitor2 | 573,641,929 | false | {"Kotlin": 56956} | package aoc2022
import Day
object Day07 : Day(2022, 7) {
data class Node(val name: String, val size: Int) {
var parent: Node? = null
private val children = mutableListOf<Node>()
fun addChild(name: String, size: Int) {
Node(name, size).let {
children.add(it)
it.parent = this
}
}
// Get the total size of this node and all of its children, recursively
fun totalSize(): Int = allChildren().sumOf { it.size }
// Find directories (zero size) containing children with a size that add up to be less than 100,000
fun matches(): List<Node> = allChildren().filter { it.size == 0 && it.totalSize() <= 100_000 }
fun findOrCreate(name: String, size: Int): Node {
children.find { it.name == name && it.size == size }?.let {
return it
}
// If the node does not already exist, create it and add it as a child
Node(name, size).let {
children.add(it)
it.parent = this
return it
}
}
override fun toString(): String {
return toString(0)
}
private fun toString(depth: Int): String {
if (children.isEmpty()) return "\t".repeat(depth) + name + " (" + size + ")"
return "\t".repeat(depth) + "$name: ${totalSize()} total\n" + children.joinToString("\n") {
it.toString(depth + 1)
}
}
fun allChildren(): List<Node> {
return children.flatMap { it.allChildren() } + this
}
}
private val tree: Node
init {
// Prepare the input
var currentNode = Node("/", 0)
for (line in lines) {
if (line.startsWith("$ ")) {
val fullCommand = line.substring(2)
when (val cmd = fullCommand.substringBefore(' ')) {
"cd" -> {
val path = fullCommand.substringAfter(' ')
if (path == "..") {
// Go up 1 directory
currentNode = currentNode.parent!!
} else if (path == "/") {
// Go up to the root of the tree
while (currentNode.parent != null) currentNode = currentNode.parent!!
} else {
currentNode = currentNode.findOrCreate(path, 0)
}
}
"ls" -> continue
else -> error("Unknown command: $cmd")
}
} else if (line.startsWith("dir ")) {
currentNode.findOrCreate(line.substringAfter("dir "), 0)
} else {
val split = line.split(" ")
val size = split.first().toInt()
val name = split.last()
currentNode.addChild(name, size)
}
}
// Go all the way back up to the root of the tree
while (currentNode.parent != null)
currentNode = currentNode.parent!!
tree = currentNode
}
override fun part1() {
val matches = tree.matches()
val result = matches.sumOf { it.totalSize() }
println("Part 1 result: $result")
}
override fun part2() {
val total = 70_000_000
val minimum = 30_000_000
val used = tree.totalSize()
val free = total - used
val mustFree = minimum - free
val smallest = tree.allChildren().filter {
it.size == 0 && it.totalSize() > mustFree
}.minBy {
it.totalSize() - mustFree
}
val result = smallest.totalSize()
println("Part 2 result: $result")
}
} | 0 | Kotlin | 0 | 0 | a48d13763db7684ee9f9129ee84cb2f2f02a6ce4 | 3,845 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day20/Day20.kt | qnox | 575,581,183 | false | {"Kotlin": 66677} | package day20
import readInput
fun main() {
fun mix(numbers: IntArray, decryptionKey: Int = 1, repeatCount: Int = 1): List<Long> {
val actualNumbers = numbers.map { it.toLong() * decryptionKey }.withIndex()
val mixed = actualNumbers.toMutableList()
repeat(repeatCount) {
actualNumbers.forEach { number ->
val index = mixed.indexOf(number)
val item = mixed.removeAt(index)
mixed.add((index + number.value).mod(mixed.size), item)
}
}
return mixed.map { it.value }
}
fun part1(input: List<String>): Long {
val list = input.map { it.toInt() }.toIntArray()
val result = mix(list)
val start = result.indexOf(0)
return listOf(1000, 2000, 3000).sumOf { result[(start + it) % result.size] }
}
fun part2(input: List<String>): Long {
val list = input.map { it.toInt() }.toIntArray()
val result = mix(list, decryptionKey = 811589153, repeatCount = 10)
val start = result.indexOf(0)
return listOf(1000, 2000, 3000).sumOf { result[(start + it) % result.size] }
}
val testInput = readInput("day20", "test")
val input = readInput("day20", "input")
val part1 = part1(testInput)
println(part1)
check(part1 == 3L)
println(part1(input))
val part2 = part2(testInput)
println(part2)
check(part2 == 1623178306L)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 727ca335d32000c3de2b750d23248a1364ba03e4 | 1,463 | aoc2022 | Apache License 2.0 |
app/src/main/kotlin/io/github/andrewfitzy/day04/Task02.kt | andrewfitzy | 747,793,365 | false | {"Kotlin": 60159, "Shell": 1211} | package io.github.andrewfitzy.day04
private const val LETTERS_IN_ALPHABET = 26
private const val LOWER_Z_VALUE = 122
private const val LOWER_A_VALUE = 96
class Task02(puzzleInput: List<String>) {
private val input: List<String> = puzzleInput
fun solve(targetRoom: String): Int {
var targetSectorId = 0
for (entry in input) {
val splits = entry.split("-")
val nameSplits = splits.subList(0, splits.size - 1)
val name = nameSplits.joinToString(separator = "")
val lastItem = splits[splits.size - 1]
val sectorId = lastItem.substring(0, lastItem.indexOf("[")).toInt()
val checksum = lastItem.substring(lastItem.indexOf("[") + 1, lastItem.indexOf("]"))
if (isValidInput(name, checksum)) {
val decryptedName = decrypt(nameSplits, sectorId)
if (targetRoom == decryptedName) {
targetSectorId = sectorId
break
}
}
}
return targetSectorId
}
private fun isValidInput(
name: String,
checksum: String,
): Boolean {
val charCount = name.groupingBy { it }.eachCount()
val entries = ArrayList(charCount.entries)
val sortedList =
entries.sortedWith { a, b ->
when {
a.value < b.value -> 1
a.value > b.value -> -1
a.value == b.value && a.key > b.key -> 1
a.value == b.value && a.key < b.key -> -1
else -> 0
}
}
return checksum == sortedList.subList(0, checksum.length).joinToString(separator = "") { it.key.toString() }
}
private fun decrypt(
nameWords: List<String>,
sectorId: Int,
): String {
val shift = sectorId % LETTERS_IN_ALPHABET
val nameSplits = nameWords.map { name -> decryptName(name, shift) }
return nameSplits.joinToString(separator = " ")
}
private fun decryptName(
name: String,
shift: Int,
): String {
val builder = StringBuilder()
for (letter in name.toCharArray()) {
var newLetterCode = letter.code + shift
if (newLetterCode > LOWER_Z_VALUE) {
newLetterCode = LOWER_A_VALUE + (newLetterCode - LOWER_Z_VALUE)
}
builder.append(newLetterCode.toChar())
}
return builder.toString()
}
}
| 0 | Kotlin | 0 | 0 | 15ac072a14b83666da095b9ed66da2fd912f5e65 | 2,513 | 2016-advent-of-code | Creative Commons Zero v1.0 Universal |
src/pl/shockah/aoc/y2021/Day8.kt | Shockah | 159,919,224 | false | null | package pl.shockah.aoc.y2021
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import pl.shockah.aoc.AdventTask
import java.util.*
class Day8: AdventTask<List<Day8.Input>, Int, Int>(2021, 8) {
companion object {
const val segmentCount = 7
val digits = listOf(
BitSet(segmentCount).apply { listOf(0, 1, 2, 4, 5, 6).forEach { set(it) } }, // 0
BitSet(segmentCount).apply { listOf(2, 5).forEach { set(it) } }, // 1
BitSet(segmentCount).apply { listOf(0, 2, 3, 4, 6).forEach { set(it) } }, // 2
BitSet(segmentCount).apply { listOf(0, 2, 3, 5, 6).forEach { set(it) } }, // 3
BitSet(segmentCount).apply { listOf(1, 2, 3, 5).forEach { set(it) } }, // 4
BitSet(segmentCount).apply { listOf(0, 1, 3, 5, 6).forEach { set(it) } }, // 5
BitSet(segmentCount).apply { listOf(0, 1, 3, 4, 5, 6).forEach { set(it) } }, // 6
BitSet(segmentCount).apply { listOf(0, 2, 5).forEach { set(it) } }, // 7
BitSet(segmentCount).apply { listOf(0, 1, 2, 3, 4, 5, 6).forEach { set(it) } }, // 8
BitSet(segmentCount).apply { listOf(0, 1, 2, 3, 5, 6).forEach { set(it) } } // 9
)
}
data class Input(
val patterns: List<BitSet>,
val value: List<BitSet>
)
override fun parseInput(rawInput: String): List<Input> {
return rawInput.trim().lines().map {
val split = it.split('|').map { it.trim() }
val splitPatterns = split[0].split(' ').map { it.trim() }
val patterns = splitPatterns.map { pattern -> BitSet(segmentCount).apply { (0 until segmentCount).map { set(it, pattern.contains('a' + it)) } } }
val splitValue = split[1].split(' ').map { it.trim() }
val value = splitValue.map { pattern -> BitSet(segmentCount).apply { (0 until segmentCount).map { set(it, pattern.contains('a' + it)) } } }
return@map Input(patterns, value)
}
}
private fun BitSet.getBitsSet(): Set<Int> {
return (0 until size()).filter { this[it] }.toSet()
}
override fun part1(input: List<Input>): Int {
val uniqueCardinality = digits.groupBy { it.cardinality() }.filter { it.value.size == 1 }.values.flatten().map { it.cardinality() }
return input.sumOf { it.value.count { it.cardinality() in uniqueCardinality } }
}
override fun part2(input: List<Input>): Int {
val uniqueCardinality = digits.groupBy { it.cardinality() }.filter { it.value.size == 1 }.values.flatten().map { it.cardinality() }.filter { it < segmentCount }
val uniqueCardinalityDigits = digits.mapIndexed { index, bitSet -> index to bitSet }.filter { it.second.cardinality() in uniqueCardinality }.toMap().mapKeys { it.value.cardinality() }
val uniqueSegmentTotals = (0 until segmentCount).groupBy { segment -> digits.count { it[segment] } }.filter { it.value.size == 1 }.mapValues { it.value.single() }.map { it.value to it.key }.toMap()
return input.sumOf { entry ->
val segmentPossibilities = mutableMapOf<Int, Set<Int>>().apply {
(0 until segmentCount).forEach { this[it] = (0 until segmentCount).toSet() }
}
// filtering out candidates by finding distinct segment totals digits (1: 2 segments, 4: 4 segments, 7: 3 segments, 8: 7 segments)
val uniqueCardinalityEntryDigits = entry.patterns.filter { it.cardinality() in uniqueCardinality }.map { it to uniqueCardinalityDigits[it.cardinality()]!! }
uniqueCardinalityEntryDigits.forEach { (entrySegments, realSegments) ->
realSegments.getBitsSet().forEach { segment ->
segmentPossibilities[segment] = segmentPossibilities[segment]!!.intersect(entrySegments.getBitsSet())
}
}
// filtering out candidates by finding distinct occurence totals across the whole pattern (e: 4x, f: 9x, b: 6x)
uniqueSegmentTotals.forEach { (segment, total) ->
val entrySegment = (0 until segmentCount).first { entrySegment -> entry.patterns.count { it[entrySegment] } == total }
segmentPossibilities[segment] = setOf(entrySegment)
}
// filtering out candidates which have definite picks
if (segmentPossibilities.values.any { it.size == 1 }) {
while (true) {
val oldCounts = segmentPossibilities.map { it.value.size }
val ones = segmentPossibilities.filter { it.value.size == 1 }.values.map { it.single() }
for (segment in segmentPossibilities.keys) {
val current = segmentPossibilities[segment]!!
if (current.size == 1 && current.single() in ones)
continue
segmentPossibilities[segment] = current - ones
}
if (segmentPossibilities.map { it.value.size } == oldCounts)
break
if (segmentPossibilities.values.all { it.size == 1 })
break
}
}
require(segmentPossibilities.all { it.value.size == 1 }) { "Could not figure out all segments." }
val usedSegments = segmentPossibilities.mapValues { it.value.single() }
val entryDigits = entry.value.map { entryDigit -> BitSet().apply { (0 until segmentCount).forEach { this[it] = entryDigit[usedSegments[it]!!] } } }
val mappedDigits = entryDigits.map { digits.indexOf(it) }
return@sumOf mappedDigits.joinToString("").toInt()
}
}
class Tests {
private val task = Day8()
private val rawInput = """
be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe
edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc
fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef | cg cg fdcagb cbg
fbegcd cbd adcefb dageb afcb bc aefdc ecdab fgdeca fcdbega | efabcd cedba gadfec cb
aecbfdg fbg gf bafeg dbefa fcge gcbea fcaegb dgceab fcbdga | gecf egdcabf bgf bfgea
fgeab ca afcebg bdacfeg cfaedg gcfdb baec bfadeg bafgc acf | gebdcfa ecba ca fadegcb
dbcfg fgd bdegcaf fgec aegbdf ecdfab fbedc dacgb gdcebf gf | cefg dcbef fcge gbcadfe
bdfegc cbegaf gecbf dfcage bdacg ed bedf ced adcbefg gebcd | ed bcgafe cdgba cbgef
egadfb cdbfeg cegd fecab cgb gbdefca cg fgcdab egfdb bfceg | gbdfcae bgc cg cgb
gcafb gcf dcaebfg ecagb gf abcdeg gaef cafbge fdbac fegbdc | fgae cfgab fg bagce
""".trimIndent()
@Test
fun part1() {
val input = task.parseInput(rawInput)
Assertions.assertEquals(26, task.part1(input))
}
@Test
fun part2() {
val input = task.parseInput(rawInput)
Assertions.assertEquals(61229, task.part2(input))
}
}
} | 0 | Kotlin | 0 | 0 | 9abb1e3db1cad329cfe1e3d6deae2d6b7456c785 | 6,179 | Advent-of-Code | Apache License 2.0 |
src/main/kotlin/dev/bogwalk/batch1/Problem15.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch1
import dev.bogwalk.util.combinatorics.binomialCoefficient
import java.math.BigInteger
/**
* Problem 15: Lattice Paths
*
* https://projecteuler.net/problem=15
*
* Goal: Find the number of routes through an NxM grid, starting at (0,0) & ending at (n,m),
* while only being able to move right or down.
*
* Constraints: 1 <= N <= 500, 1 <= M <= 500
*
* e.g.: N = 2, M = 2
* routes = 6 -> {RRDD, RDRD, RDDR, DRRD, DRDR, DDRR}
*/
class LatticePaths {
private val mod = 1_000_000_007
/**
* Calculates distinct permutations with identical items.
*
* Solution is based on the formula:
*
* x! / Pi(i!)
*
* where x is the number of items to be combined & i represents the groups of
* indistinguishable items to undergo product notation.
*
* Note that, if the lattice was assured to be square, the number of routes would be equal to
* the central binomial coefficient C(2n, n) found as the midline number in the (2n)th row
* of Pascal's triangle.
*
* The formula for a rectangular grid with C(n+m, n) becomes:
*
* (n + m)! / n!m!
*
* since grid dimensions determine the number of steps taken & there is a deterministic
* proportion of R vs D steps.
*
* @return number of valid routes scaled down to modulo (1e9 + 7).
*/
fun latticePathRoutes(n: Int, m: Int): BigInteger {
val routes = binomialCoefficient(n + m, m)
return routes % mod.toBigInteger()
}
/**
* Solution uses breadth-first search summation to generate a graph that contains all counts
* of possible paths from the start node (0, 0 or top left corner) to the node at index[n][m].
*
* The original lattice is converted to a graph representation of its points (nodes) instead
* of its edges. For example, exploring each node at each depth results in the following
* cumulative count:
*
* given N = 2, M = 2
* 1
* 1 1
* 1 2 1
* 3 3
* 6 -> total count of paths to bottom right corner
*/
fun latticePathRoutesBFS(n: Int, m: Int): Array<LongArray> {
// goal is bottom right (outer) corner, so an extra node exists for each outer edge
val lattice = Array(n + 1) { LongArray(m + 1) }.apply {
// path from root to itself
this[0][0] = 1L
}
// create queue to keep track of encountered but unexplored adjacent nodes
val unvisited = ArrayDeque(listOf(1 to 0, 0 to 1))
while (!unvisited.isEmpty()) {
val (row, col) = unvisited.removeFirst()
// already explored paths from root to this node
if (lattice[row][col] != 0L) continue
var routes = 0L
if (row > 0) {
routes += lattice[row - 1][col]
}
if (col > 0) {
routes += lattice[row][col - 1]
}
routes %= mod
lattice[row][col] = routes
// queue next 2 adjacent nodes (down & right) if they exist
if (row < n) {
unvisited.add(row + 1 to col)
}
if (col < m) {
unvisited.add(row to col + 1)
}
}
return lattice
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 3,349 | project-euler-kotlin | MIT License |
advent-of-code-2022/src/Day13.kt | osipxd | 572,825,805 | false | {"Kotlin": 141640, "Shell": 4083, "Scala": 693} | fun main() {
val testInput = readInput("Day13_test")
val input = readInput("Day13")
"Part 1" {
part1(testInput) shouldBe 13
answer(part1(input))
}
"Part 2" {
part2(testInput) shouldBe 140
answer(part2(input))
}
}
private fun part1(packets: List<Packet>): Int {
var i = 0
var sum = 0
packets.chunked(2) { (left, right) ->
i++
if (left <= right) sum += i
}
return sum
}
private fun part2(packets: List<Packet>): Int {
// Shorthand to create divider item in form [[$value]]
fun divider(value: Int) = Packet.Complex(Packet.Complex(Packet.Simple(value)))
val dividerA = divider(2)
val dividerB = divider(6)
return (packets.count { it < dividerA } + 1) * (packets.count { it < dividerB } + 2)
}
private fun readInput(name: String) = readLines(name).filter(String::isNotEmpty).map(::eval)
// Sad joke. We have no eval, so let's parse lists!
private fun eval(line: String): Packet {
val number = StringBuilder()
val stack = ArrayDeque<Packet?>()
fun pushNumber() {
if (number.isNotEmpty()) {
stack.addFirst(Packet.Simple(number.toString().toInt()))
number.clear()
}
}
fun pushComplexPacket() {
val nested = ArrayDeque<Packet>()
var current = stack.removeFirst()
// Remove elements until list start
while (current != null) {
nested.addFirst(current)
current = stack.removeFirst()
}
// Push back nested list
stack.addFirst(Packet.Complex(nested))
}
for (char in line) {
when (char) {
// We will use `null` as a marker of list start
'[' -> stack.addFirst(null)
',' -> pushNumber()
']' -> {
pushNumber()
pushComplexPacket()
}
else -> number.append(char)
}
}
return checkNotNull(stack.single())
}
private sealed interface Packet : Comparable<Packet> {
class Simple(val value: Int) : Packet {
override fun toString(): String = value.toString()
override fun compareTo(other: Packet): Int = when (other) {
is Simple -> value compareTo other.value
is Complex -> Complex(this) compareTo other
}
}
class Complex(val values: List<Packet>) : Packet {
constructor(value: Packet) : this(listOf(value))
override fun toString(): String = values.toString()
override fun compareTo(other: Packet): Int {
val left = this
val right = if (other is Complex) other else Complex(other)
for (i in 0 until minOf(left.values.size, right.values.size)) {
val result = left.values[i] compareTo right.values[i]
if (result != 0) return result
}
return left.values.size compareTo right.values.size
}
}
}
| 0 | Kotlin | 0 | 5 | 6a67946122abb759fddf33dae408db662213a072 | 2,962 | advent-of-code | Apache License 2.0 |
year2021/src/main/kotlin/net/olegg/aoc/year2021/day17/Day17.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2021.day17
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.Vector2D
import net.olegg.aoc.year2021.DayOf2021
import kotlin.math.sign
/**
* See [Year 2021, Day 17](https://adventofcode.com/2021/day/17)
*/
object Day17 : DayOf2021(17) {
private val PATTERN = "target area: x=(-?\\d+)\\.\\.(-?\\d+), y=(-?\\d+)\\.\\.(-?\\d+)".toRegex()
override fun first(): Any? {
val (fromX, toX, fromY, toY) = PATTERN.find(data)?.groupValues.orEmpty().drop(1).map { it.toInt() }
var best = fromY
(0..toX).forEach { x ->
(-100..100).forEach { y ->
val positions = generateSequence(Vector2D(0, 0) to Vector2D(x, y)) { (pos, speed) ->
val nextPos = pos + speed
val nextSpeed = Vector2D(
x = speed.x - speed.x.sign,
y = speed.y - 1,
)
when {
speed.x == 0 && pos.y < fromY -> null
else -> nextPos to nextSpeed
}
}.map { it.first }.toList()
if (positions.any { it.x in fromX..toX && it.y in fromY..toY }) {
best = maxOf(best, positions.maxOf { it.y })
}
}
}
return best
}
override fun second(): Any? {
val (fromX, toX, fromY, toY) = PATTERN.find(data)?.groupValues.orEmpty().drop(1).map { it.toInt() }
return (0..toX).sumOf { x ->
(-100..100).sumOf { y ->
val positions = generateSequence(Vector2D(0, 0) to Vector2D(x, y)) { (pos, speed) ->
val nextPos = pos + speed
val nextSpeed = Vector2D(
x = speed.x - speed.x.sign,
y = speed.y - 1,
)
when {
speed.x == 0 && pos.y < fromY -> null
else -> nextPos to nextSpeed
}
}.map { it.first }.toList()
if (positions.any { it.x in fromX..toX && it.y in fromY..toY }) {
1L
} else {
0L
}
}
}
}
}
fun main() = SomeDay.mainify(Day17)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,964 | adventofcode | MIT License |
src/Day02.kt | nielsz | 573,185,386 | false | {"Kotlin": 12807} | fun main() {
fun getBasicScore(their: Char, mine: Char): Int {
return if (their != mine) {
when {
their == 'A' && mine == 'B' -> 6
their == 'B' && mine == 'C' -> 6
their == 'C' && mine == 'A' -> 6
else -> 0
}
} else 3
}
fun getScorePart1(their: Char, mine: Char): Int {
return mine - 'A' + 1 + getBasicScore(their, mine)
}
fun part1(input: List<String>): Int {
var totalScore = 0
for (line in input) {
totalScore += getScorePart1(line[0], Char(line[2].code - 23))
}
return totalScore
}
fun getScorePart2(their: Char, mine: Char): Int {
return when (mine) {
'X' -> when (their) {
'A' -> 3
'B' -> 1
else -> 2
}
'Y' -> 3 + when (their) {
'A' -> 1
'B' -> 2
else -> 3
}
else -> 6 + when (their) {
'A' -> 2
'B' -> 3
else -> 1
}
}
}
fun part2(input: List<String>): Int {
var totalScore = 0
for (line in input) {
totalScore += getScorePart2(line[0], line[2])
}
return totalScore
}
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 05aa7540a950191a8ee32482d1848674a82a0c71 | 1,445 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/no/chriswk/aoc2019/Day10.kt | chriswk | 317,863,220 | false | {"Kotlin": 481061} | package no.chriswk.aoc2019
import kotlin.math.PI
import kotlin.math.atan2
import kotlin.math.hypot
class Day10 {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val day10 = Day10()
report { day10.part1() }
report { day10.part2() }
}
}
fun parseInput(input: List<String>): List<Point> {
return input.withIndex()
.flatMap { (y, row) -> row.withIndex().filter { it.value == '#' }.map { Point(it.index, y) } }
}
fun part1(): Int {
val input = "day10.txt".fileToLines()
val asteroids = parseInput(input)
return visible(asteroids).max() ?: -1
}
fun part2(): Int {
val input = "day10.txt".fileToLines()
val asteroids = parseInput(input)
val station = findStation(asteroids)!!
val other = (asteroids - station)
val twohundrethTarget = shoot(station, other).drop(199).first()
return twohundrethTarget.part2()
}
fun shoot(station: Point, other: List<Point>): Sequence<Point> {
val remaining = other.toMutableList()
var angle = -PI / 2
var firstTarget = true
return generateSequence {
val asteroidsByAngle = remaining.groupBy { atan2(it.dy(station).toDouble(), it.dx(station).toDouble()) }
val nextAngleTargets = asteroidsByAngle
.filter { if (firstTarget) it.key >= angle else it.key > angle }
.minBy { it.key }
?: asteroidsByAngle.minBy { it.key }!!
angle = nextAngleTargets.key
firstTarget = false
val target =
nextAngleTargets.value.minBy { hypot(it.dx(station).toDouble(), it.dy(station).toDouble()) }!!
remaining.remove(target)
target
}
}
fun findStation(points: List<Point>): Point? {
return points.maxBy { asteroid ->
points.filter { it != asteroid }
.map { atan2(it.dy(asteroid).toDouble(), it.dx(asteroid).toDouble()) }
.distinct()
.count()
}
}
fun visible(points: List<Point>): List<Int> {
return points.map { asteroid ->
points.filter { it != asteroid }
.map { atan2(it.dy(asteroid).toDouble(), it.dx(asteroid).toDouble()) }
.distinct()
.count()
}
}
}
fun Point.part2() = this.x * 100 + this.y
| 116 | Kotlin | 0 | 0 | 69fa3dfed62d5cb7d961fe16924066cb7f9f5985 | 2,467 | adventofcode2019 | MIT License |
src/Day08.kt | cerberus97 | 579,910,396 | false | {"Kotlin": 11722} | import kotlin.math.max
fun main() {
class Forest(val grid: List<String>) {
val n = grid.size
val m = grid[0].length
fun inRange(i: Int, j: Int): Boolean =
(i in 0 until n) && (j in 0 until m)
tailrec fun visible(i: Int, j: Int, di: Int, dj: Int, height: Int): Boolean {
val ni = i + di
val nj = j + dj
if (!inRange(ni, nj)) return true
if (grid[ni][nj].digitToInt() >= height) return false
return visible(ni, nj, di, dj, height)
}
fun countVisible(i: Int, j: Int, di: Int, dj: Int, height: Int): Int {
val ni = i + di
val nj = j + dj
if (!inRange(ni, nj)) return 0
if (grid[ni][nj].digitToInt() >= height) return 1
return 1 + countVisible(ni, nj, di, dj, height)
}
}
fun part1(input: List<String>): Int {
val forest = Forest(input)
var ans = 0
for (i in 0 until forest.n) {
for (j in 0 until forest.m) {
val height = input[i][j].digitToInt()
if (forest.visible(i, j, 0, -1, height)
|| forest.visible(i, j, 0, 1, height)
|| forest.visible(i, j, -1, 0, height)
|| forest.visible(i, j, 1, 0, height)
) {
++ans
}
}
}
return ans
}
fun part2(input: List<String>): Int {
val forest = Forest(input)
var ans = 0
for (i in 0 until forest.n) {
for (j in 0 until forest.m) {
val height = input[i][j].digitToInt()
ans = max(ans, (
forest.countVisible(i, j, 0, -1, height)
* forest.countVisible(i, j, 0, 1, height)
* forest.countVisible(i, j, -1, 0, height)
* forest.countVisible(i, j, 1, 0, height)
))
}
}
return ans
}
val input = readInput("in")
part1(input).println()
part2(input).println()
} | 0 | Kotlin | 0 | 0 | ed7b5bd7ad90bfa85e868fa2a2cdefead087d710 | 1,808 | advent-of-code-2022-kotlin | Apache License 2.0 |
kotlin/Dijkstra.kt | indy256 | 1,493,359 | false | {"Java": 545116, "C++": 266009, "Python": 59511, "Kotlin": 28391, "Rust": 4682, "CMake": 571} | object Dijkstra {
data class Edge(val target: Int, val cost: Int)
data class ShortestPaths(val dist: IntArray, val pred: IntArray)
fun shortestPaths(graph: Array<out List<Edge>>, s: Int): ShortestPaths {
val n = graph.size
val dist = IntArray(n) { Int.MAX_VALUE }
dist[s] = 0
val pred = IntArray(n) { -1 }
val visited = BooleanArray(n)
for (i in 0 until n) {
var u = -1
for (j in 0 until n) {
if (!visited[j] && (u == -1 || dist[u] > dist[j]))
u = j
}
if (dist[u] == Int.MAX_VALUE)
break
visited[u] = true
for (e in graph[u]) {
val v = e.target
val nprio = dist[u] + e.cost
if (dist[v] > nprio) {
dist[v] = nprio
pred[v] = u
}
}
}
return ShortestPaths(dist, pred)
}
// Usage example
@JvmStatic
fun main(args: Array<String>) {
val cost = arrayOf(intArrayOf(0, 3, 2), intArrayOf(0, 0, -2), intArrayOf(0, 0, 0))
val n = cost.size
val graph = (1..n).map { arrayListOf<Edge>() }.toTypedArray()
for (i in 0 until n) {
for (j in 0 until n) {
if (cost[i][j] != 0) {
graph[i].add(Edge(j, cost[i][j]))
}
}
}
println(graph.contentToString())
val (dist, pred) = shortestPaths(graph, 0)
println(0 == dist[0])
println(3 == dist[1])
println(1 == dist[2])
println(-1 == pred[0])
println(0 == pred[1])
println(1 == pred[2])
}
}
| 97 | Java | 561 | 1,806 | 405552617ba1cd4a74010da38470d44f1c2e4ae3 | 1,731 | codelibrary | The Unlicense |
src/day14/Day14.kt | kerchen | 573,125,453 | false | {"Kotlin": 137233} | package day14
import readInput
data class Point(var x: Int, var y: Int)
enum class Occupier {
ROCK,
SAND
}
class Cave(rockPaths: List<String>) {
var occupiedCells = HashMap<Point, Occupier>()
var maxDepth = 0
init {
for (path in rockPaths) {
val endPoints = path.split(Regex("->"))
var lastPoint: Point? = null
for (pt in endPoints) {
val coords = pt.split(",")
val point = Point(coords[0].trim().toInt(), coords[1].trim().toInt())
if (lastPoint == null) {
lastPoint = point
} else {
if (lastPoint.x == point.x) {
for (y in IntRange(minOf(lastPoint.y, point.y), maxOf(lastPoint.y, point.y)))
occupiedCells[Point(point.x, y)] = Occupier.ROCK
} else {
for (x in IntRange(minOf(lastPoint.x, point.x), maxOf(lastPoint.x, point.x)))
occupiedCells[Point(x, point.y)] = Occupier.ROCK
}
lastPoint = point
}
if (lastPoint.y > maxDepth) {
maxDepth = lastPoint.y
}
}
}
}
enum class DIRECTION {
DOWN,
LEFT,
RIGHT
}
fun dropSand(dropPoint: Point, floorOffset: Int = 0): Boolean {
var direction = DIRECTION.DOWN
var testPoint = dropPoint.copy(y=dropPoint.y+1)
if (occupiedCells.containsKey(dropPoint)) {
return false
}
while(testPoint.y <= maxDepth + floorOffset) {
if (floorOffset > 0)
{
if (testPoint.y == maxDepth + floorOffset - 1){
for (x in IntRange(testPoint.x-1, testPoint.x+1))
occupiedCells[Point(x, testPoint.y + 1)] = Occupier.ROCK
}
}
if (occupiedCells.containsKey(testPoint)) {
when(direction) {
DIRECTION.DOWN -> {
direction = DIRECTION.LEFT
testPoint.x -= 1
}
DIRECTION.LEFT -> {
direction = DIRECTION.RIGHT
testPoint.x += 2
}
DIRECTION.RIGHT -> {
occupiedCells[Point(testPoint.x-1, testPoint.y-1)] = Occupier.SAND
return true
}
}
} else {
testPoint.y += 1
direction = DIRECTION.DOWN
}
}
return false
}
}
fun main() {
fun part1(input: List<String>): Int {
val cave = Cave(input)
var sandUnits = 0
while(cave.dropSand(Point(500, 0))) {
sandUnits += 1
}
println(sandUnits)
return sandUnits
}
fun part2(input: List<String>): Int {
val cave = Cave(input)
var sandUnits = 0
while(cave.dropSand(Point(500, 0), 2)) {
sandUnits += 1
}
println(sandUnits)
return sandUnits
}
val testInput = readInput("Day14_test")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | dc15640ff29ec5f9dceb4046adaf860af892c1a9 | 3,424 | AdventOfCode2022 | Apache License 2.0 |
src/Day04.kt | akunowski | 573,109,101 | false | {"Kotlin": 5413} | fun main() {
fun toRange(s: List<String>): IntRange = s[0].toInt()..s[1].toInt()
fun isOverlapping(first: IntRange, second: IntRange): Boolean {
val union = first union second
return union == first.toSet() || union == second.toSet()
}
fun part1(input: List<String>): Int =
input
.map { it.split(",") }
.map { it[0].split("-") to it[1].split("-") }
.map { toRange(it.first) to toRange(it.second) }
.count { isOverlapping(it.first, it.second) }
fun part2(input: List<String>): Int =
input
.map { it.split(",") }
.map { it[0].split("-") to it[1].split("-") }
.map { toRange(it.first) to toRange(it.second) }
.map { it.first intersect it.second }
.count { it.isNotEmpty() }
val input = readInput("inputs/day4")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b306b779386c793f5bf9d8a86a59a7d0755c6159 | 930 | aoc-2022 | Apache License 2.0 |
src/Day07.kt | sungi55 | 574,867,031 | false | {"Kotlin": 23985} | private const val CD = "$ cd "
private const val LS = "$ ls"
private const val DIR = "dir"
fun main() {
val day = "Day07"
val directorySizes: MutableList<Int> = mutableListOf()
fun getRootNode(input: List<String>): Node {
val root = Node("/", null)
var current = root
input.forEach { command ->
when {
command.startsWith(CD) -> {
current = when {
command.endsWith("/") -> root
command.endsWith("..") -> current.parent!!
else -> current.children.first {
it.name == command.substringAfter(CD)
}
}
}
command.startsWith(LS) -> {
}
command.startsWith(DIR) -> current.children.add(
Node(command.substringAfter(" "), current)
)
else -> current.size += command.substringBefore(" ").toInt()
}
}
return root
}
fun recursiveSizes(node: Node): Int {
directorySizes.add(node.size + node.children.sumOf(::recursiveSizes))
return directorySizes.last()
}
fun part1(input: List<String>): Int {
val root = getRootNode(input)
recursiveSizes(root)
return directorySizes.filter { it <= 100000 }.sum().also {
directorySizes.clear()
}
}
fun part2(input: List<String>): Int {
val root = getRootNode(input)
recursiveSizes(root)
val max = directorySizes.max()
val available = 70000000
val unused = 30000000
val required = unused - (available - max)
return directorySizes.filter { it >= required }.min().also {
directorySizes.clear()
}
}
val testInput = readInput(name = "${day}_test")
val input = readInput(name = day)
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
println(part1(input))
println(part2(input))
}
data class Node(
val name: String,
val parent: Node?,
) {
var size: Int = 0
var children: MutableList<Node> = mutableListOf()
} | 0 | Kotlin | 0 | 0 | 2a9276b52ed42e0c80e85844c75c1e5e70b383ee | 2,225 | aoc-2022 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.