path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxProductOfTwoElementsInArray.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max /** * 1464. Maximum Product of Two Elements in an Array * @see <a href="https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array">Source</a> */ fun interface MaxProductOfTwoElementsInArray { operator fun invoke(nums: IntArray): Int } class MaxProductOfTwoElementsInArrayBF : MaxProductOfTwoElementsInArray { override fun invoke(nums: IntArray): Int { var ans = 0 for (i in nums.indices) { for (j in i + 1 until nums.size) { ans = max(ans, (nums[i] - 1) * (nums[j] - 1)) } } return ans } } class MaxProductOfTwoElementsInArraySort : MaxProductOfTwoElementsInArray { override fun invoke(nums: IntArray): Int { nums.sort() val x = nums[nums.size - 1] val y = nums[nums.size - 2] return (x - 1) * (y - 1) } } class TrackSecondBiggest : MaxProductOfTwoElementsInArray { override fun invoke(nums: IntArray): Int { var biggest = 0 var secondBiggest = 0 for (num in nums) { if (num > biggest) { secondBiggest = biggest biggest = num } else { secondBiggest = max(secondBiggest.toDouble(), num.toDouble()).toInt() } } return (biggest - 1) * (secondBiggest - 1) } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,002
kotlab
Apache License 2.0
year2023/src/main/kotlin/net/olegg/aoc/year2023/day11/Day11.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2023.day11 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.Vector2D import net.olegg.aoc.utils.pairs import net.olegg.aoc.year2023.DayOf2023 /** * See [Year 2023, Day 11](https://adventofcode.com/2023/day/11) */ object Day11 : DayOf2023(11) { override fun first(): Any? { return solve(2) } override fun second(): Any? { return solve(1000000) } private fun solve(add: Long): Long { val emptyRows = matrix.mapIndexedNotNull { index, row -> index.takeIf { row.all { it == '.' } } } val emptyColumns = matrix.first().indices .filter { column -> matrix.all { it[column] == '.' } } val galaxies = matrix.flatMapIndexed { y, row -> row.mapIndexedNotNull { x, c -> if (c == '#') { Vector2D(x, y) } else { null } } } return galaxies.pairs() .map { val dx = (minOf(it.first.x, it.second.x)..<maxOf(it.first.x, it.second.x)) .sumOf { x -> if (x in emptyColumns) add else 1 } val dy = (minOf(it.first.y, it.second.y)..<maxOf(it.first.y, it.second.y)) .sumOf { y -> if (y in emptyRows) add else 1 } dx + dy } .sum() } } fun main() = SomeDay.mainify(Day11)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,328
adventofcode
MIT License
src/Day04.kt
KorneliuszBarwinski
572,677,168
false
{"Kotlin": 6042}
fun main() { fun calculateRanges(input: String) = input.split("\r\n").map { element -> element.split(",").map { pairs -> val (first, second) = pairs.split("-").map { it.toInt() } first..second } } fun part1(input: String): Int = calculateRanges(input).count { (firstRange, secondRange) -> (firstRange.first in secondRange && firstRange.last in secondRange) || (secondRange.first in firstRange && secondRange.last in firstRange) } fun part2(input: String): Int = calculateRanges(input).count { (firstRange, secondRange) -> firstRange.first in secondRange || firstRange.last in secondRange || secondRange.first in firstRange || secondRange.last in firstRange } val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d90175134e0c6482986fcf3c144282f189abc875
865
AoC_2022
Apache License 2.0
src/Day05.kt
Advice-Dog
436,116,275
true
{"Kotlin": 25836}
import kotlin.math.abs fun main() { fun part1(input: List<String>, print: Boolean = false): Int { val map = input.flatMap { it.toPointsList(skipDiagonal = true) } val group = map.groupBy { it }.map { it.key to it.value.size } var find = map.filter { it.x == 466 && it.y == 235 } println("$find -> ${find.size}") var find2 = map.groupBy { it }.entries.find { it.key.x == 466 && it.key.y == 235 } println("$find2 -> ${find2?.value?.size}") val sorted = group.sortedWith(compareBy({ it.first.x }, { it.first.y })) val xMax = group.maxOf { it.first.x } val yMax = group.maxOf { it.first.y } if (print) { val builder = StringBuilder() //println(sorted) for (y in 0..yMax) { for (x in 0..xMax) { val element = group.find { it.first.x == x && it.first.y == y } val character = element?.second ?: "." // print(character) builder.append(character) } builder.appendLine() //println() // print(y) } println(builder.toString()) // File("C:\\Users\\disen\\Documents\\GitHub\\advent-of-code-kotlin-template\\src\\day_05_result.txt").writeText(builder.toString()) } // for (point in Point(0, 0)..Point(9, 9)) { // if (point.y == 0) // println() // // val element = map.find { it.first == point } // if (element != null) // print(element.second) // else // print(".") // } val frequencyMap: MutableMap<String, Int> = HashMap() // val count = group.count { it.second > 1 } // println("Count: $count") // // var count2 = 0 // for (y in 0..yMax) { for (x in 0..xMax) { val s = "$x,$y" // println("BEFORE; ${frequencyMap[s]}") val get = frequencyMap[s] if (get != null) { // println("NOT NULL: $get") frequencyMap[s] = get + 1 } else { frequencyMap[s] = map.count { it.x == x && it.y == y } } println("$s -> ${frequencyMap[s]}") //val element = map.filter { it.x == x && it.y == y } // val element = map.count { it.x == x && it.y == y } // if(element > 1) { // count2++ // println(count2) // } // println(s) } } // // println("FINAL: " + count2) val count = frequencyMap.entries.count { it.value > 1 } println("FINAL: $count") return count } fun part2(input: List<String>): Int { val map = input.flatMap { it.toPointsList(skipDiagonal = false) } val xMax = map.maxOf { it.x } val yMax = map.maxOf { it.y } val frequencyMap: MutableMap<String, Int> = HashMap() // val count = group.count { it.second > 1 } // println("Count: $count") // // var count2 = 0 // for (y in 0..yMax) { for (x in 0..xMax) { val s = "$x,$y" // println("BEFORE; ${frequencyMap[s]}") val get = frequencyMap[s] if (get != null) { // println("NOT NULL: $get") frequencyMap[s] = get + 1 } else { frequencyMap[s] = map.count { it.x == x && it.y == y } } println("$s -> ${frequencyMap[s]}") //val element = map.filter { it.x == x && it.y == y } // val element = map.count { it.x == x && it.y == y } // if(element > 1) { // count2++ // println(count2) // } // println(s) } } // // println("FINAL: " + count2) val count = frequencyMap.entries.count { it.value > 1 } println("FINAL: " + count) return count } // test if implementation meets criteria from the description, like: val testInput = getTestData("Day05") check(part1(testInput, print = true) == 5) check(part2(testInput) == 12) val input = getData("Day05") // println(part1(input, print = false)) //println(part1_alt(input)) println(part2(input)) } fun String.toPointsList(skipDiagonal: Boolean = false): List<Point> { val (first, last) = split("->").map { it.toPoint() } // Skip any diagonal lines if (skipDiagonal && first.x != last.x && first.y != last.y) return emptyList() val points = listOf(first) + (first..last).toList() val expectedX = abs(first.x - last.x) val expectedY = abs(first.y - last.y) if (points.size - 1 != expectedX && points.size - 1 != expectedY) { println(points) println("$expectedX, $expectedY") error("$first to $last generated wrong number of points: ${points.size}") } return points } fun String.toPoint(): Point { val list = split(",").map { it.trim().toInt() } return Point(list.first(), list.last()) } class PointProgression( override val start: Point, override val endInclusive: Point, private val step: Int = 1 ) : Iterable<Point>, ClosedRange<Point> { override fun iterator(): Iterator<Point> = PointIterator(start, endInclusive, step) infix fun step(step: Int) = PointProgression(start, endInclusive, step) } class PointIterator(startPoint: Point, private val endPointInclusive: Point, step: Int) : Iterator<Point> { private var x = 0 private var y = 0 private var currentPoint = startPoint init { x = when { endPointInclusive.x > startPoint.x -> step endPointInclusive.x < startPoint.x -> -step else -> 0 } y = when { endPointInclusive.y > startPoint.y -> step endPointInclusive.y < startPoint.y -> -step else -> 0 } } override fun hasNext(): Boolean { return currentPoint != endPointInclusive } override fun next(): Point { val next = currentPoint.next(x, y) currentPoint = next return next } } data class Point(val x: Int, val y: Int, var id: Int = index++) : Comparable<Point> { companion object { var index = 0 } override fun compareTo(other: Point): Int { if (x < other.x || y < other.y) return -1 if (x > other.x || y > other.y) return 1 return 0 } operator fun rangeTo(other: Point) = PointProgression(this, other) override fun equals(other: Any?): Boolean { if (other is Point) return x == other.x && y == other.y return false } override fun hashCode(): Int { var result = x result = 31 * result + y return result } } fun Point.next(x: Int, y: Int) = Point(this.x + x, this.y + y)
0
Kotlin
0
0
2a2a4767e7f0976dba548d039be148074dce85ce
7,226
advent-of-code-kotlin-template
Apache License 2.0
src/Day03.kt
adamgaafar
572,629,287
false
{"Kotlin": 12429}
fun main() { var scoreMap = mapOf<Char,Int>( 'a' to 1, 'b' to 2, 'c' to 3, 'd' to 4, 'e' to 5, 'f' to 6, 'g' to 7, 'h' to 8, 'i' to 9, 'j' to 10, 'k' to 11, 'l' to 12, 'm' to 13, 'n' to 14, 'o' to 15, 'p' to 16, 'q' to 17, 'r' to 18, 's' to 19, 't' to 20, 'u' to 21, 'v' to 22, 'w' to 23, 'x' to 24, 'y' to 25, 'z' to 26, 'A' to 27, 'B' to 28, 'C' to 29, 'D' to 30, 'E' to 31, 'F' to 32, 'G' to 33, 'H' to 34, 'I' to 35, 'J' to 36, 'K' to 37, 'L' to 38, 'M' to 39, 'N' to 40, 'O' to 41, 'P' to 42, 'Q' to 43, 'R' to 44, 'S' to 45, 'T' to 46, 'U' to 47, 'V' to 48, 'W' to 49, 'X' to 50, 'Y' to 51, 'Z' to 52, ) fun part1(input: List<String>): Int { var score = 0 var compartments:MutableList<Pair<MutableList<Char>,MutableList<Char>>> = mutableListOf() var commonList = mutableListOf<Char>() for(i in input){ compartments.add(i.splitAtIndex(i.length / 2)) } compartments.forEach { pair -> var letters = 'a' pair.second.forEach { letter -> if (pair.first.contains(letter)){ letters = letter } } commonList.add(letters) } commonList.forEach { c -> score += scoreMap.getValue(c) } return score } fun part2(input: List<String>): Int { var triplets = mutableListOf<String>() var firstThree = mutableListOf<MutableList<String>>() var firstCompTriple = mutableListOf<Char>() var score = 0 var oo = 0 for (i in input){ oo += 1 triplets.add(i) if (oo >= 3){ firstThree.add(triplets.toMutableList()) oo = 0 triplets.clear() } } for(t in 0 until firstThree.size){ firstCompTriple.add(commonChars(firstThree[t]).first().toCharArray().first()) score += scoreMap.getValue(commonChars(firstThree[t]).first().toCharArray().first()) } return score } // test if implementation meets criteria from the description, like: /* val testInput = readInput("Day01_test") check(part1(testInput) == 1)*/ val input = readInput("Day03") println(part1(input)) println(part2(input)) } fun commonChars(wordList: MutableList<String>): List<String> { val res = mutableListOf<String>() if(wordList.isEmpty()) { return res } val lettersMap = Array(wordList.size) { mutableMapOf<Char, Int>() } for(i in wordList.indices) { for(letter in wordList[i]) { val letterCount = lettersMap[i].get(letter) ?: 0 lettersMap[i].put(letter, letterCount + 1) } } //iterate over the first word for(letterEntry in lettersMap[0]){ var count = letterEntry.value //check if the letter appears in each word i (!= 0) loop@for(i in 1 until wordList.size) { var letterCount = lettersMap[i].get(letterEntry.key) if(letterCount == null) { //it means that the letter doesn't appear any word count = 0 break@loop //break inner loop and move to next iteration } else { //update to minimum appearances (in case of duplicates letters in word) count = count.coerceAtMost(letterCount) } } for(i in 1..count) { res.add(letterEntry.key.toString()) } } return res }
0
Kotlin
0
0
5c7c9a2e819618b7f87c5d2c7bb6e6ce415ee41e
3,944
AOCK
Apache License 2.0
src/main/kotlin/Day20.kt
todynskyi
573,152,718
false
{"Kotlin": 47697}
fun main() { val positions = listOf(1000, 2000, 3000) fun decrypt(input: List<Int>, key: Long = 1, times: Int = 1): Long { val (initialPositions, encryptedData) = input.mapIndexed { index, i -> index to i * key } .let { it to it.toMutableList() } repeat(times) { initialPositions.forEach { p -> val index = encryptedData.indexOf(p) encryptedData.removeAt(index) encryptedData.add((index + p.second).mod(encryptedData.size), p) } } val index = encryptedData.indexOfFirst { it.second == 0L } return positions.sumOf { position -> encryptedData[(index + position) % input.size].second } } fun part1(input: List<Int>): Long = decrypt(input) fun part2(input: List<Int>): Long = decrypt(input, 811589153, 10) // test if implementation meets criteria from the description, like: val testInput = readInput("Day20_test").map { it.toInt() } check(part1(testInput) == 3L) println(part2(testInput)) val input = readInput("Day20").map { it.toInt() } println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5f9d9037544e0ac4d5f900f57458cc4155488f2a
1,161
KotlinAdventOfCode2022
Apache License 2.0
advent-of-code-2021/src/main/kotlin/eu/janvdb/aoc2021/day02/Day02.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2021.day02 import eu.janvdb.aocutil.kotlin.readLines const val FILENAME = "input02.txt" fun main() { runPart(Position1(0, 0)) runPart(Position2(0, 0, 0)) } private fun <T : Position<T>> runPart(start: T) { val result = readLines(2021, FILENAME) .map { Instruction.parse(it) } .fold(start) { position, instruction -> position.move(instruction) } println("(${result.horizontal}, ${result.vertical}) => ${result.score}") } enum class Direction { DOWN, UP, FORWARD } data class Instruction(val direction: Direction, val amount: Long) { companion object { fun parse(line: String): Instruction { val parts = line.split(" ") return Instruction( Direction.valueOf(parts[0].uppercase()), parts[1].toLong() ) } } } abstract class Position<T : Position<T>>(val horizontal: Long, val vertical: Long) { val score: Long get() = horizontal * vertical abstract fun move(instruction: Instruction): T } class Position1(horizontal: Long, vertical: Long) : Position<Position1>(horizontal, vertical) { override fun move(instruction: Instruction): Position1 { return when (instruction.direction) { Direction.DOWN -> Position1(horizontal, vertical + instruction.amount) Direction.UP -> Position1(horizontal, vertical - instruction.amount) Direction.FORWARD -> Position1(horizontal + instruction.amount, vertical) } } } class Position2(horizontal: Long, vertical: Long, private val aim: Long) : Position<Position2>(horizontal, vertical) { override fun move(instruction: Instruction): Position2 { return when (instruction.direction) { Direction.DOWN -> Position2(horizontal, vertical, aim + instruction.amount) Direction.UP -> Position2(horizontal, vertical, aim - instruction.amount) Direction.FORWARD -> Position2(horizontal + instruction.amount, vertical + aim * instruction.amount, aim) } } }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
1,869
advent-of-code
Apache License 2.0
app/src/main/kotlin/day21/Day21.kt
W3D3
572,447,546
false
{"Kotlin": 159335}
package day21 import common.InputRepo import common.readSessionCookie import common.solve fun main(args: Array<String>) { val day = 21 val input = InputRepo(args.readSessionCookie()).get(day = day) solve(day, input, ::solveDay21Part1, ::solveDay21Part2) } fun solveDay21Part1(input: List<String>): Long { val expressions = input.map { parseJob(it) }.associateBy { it.name } val eval = expressions["root"]!!.eval(expressions) return eval } abstract class Expression(val name: String) { abstract fun eval(expressions: Map<String, Expression>): Long abstract fun print(expressions: Map<String, Expression>): String } class OperationExpression(name: String, val param1: String, val op: Char, val param2: String) : Expression(name) { override fun eval(expressions: Map<String, Expression>): Long { val expr1 = expressions[param1]!!.eval(expressions) val expr2 = expressions[param2]!!.eval(expressions) return when (op) { '+' -> expr1 + expr2 '-' -> expr1 - expr2 '/' -> expr1 / expr2 '*' -> expr1 * expr2 else -> throw IllegalArgumentException("aaaa") } } override fun print(expressions: Map<String, Expression>): String { val expr1 = expressions[param1]!!.print(expressions) val expr2 = expressions[param2]!!.print(expressions) return when (op) { '+' -> """($expr1 + $expr2)""" '-' -> """($expr1 - $expr2)""" '/' -> """($expr1 / $expr2)""" '*' -> """($expr1 * $expr2)""" '=' -> """($expr1) = ($expr2)""" else -> throw IllegalArgumentException("aaaa") } } } class LiteralExpression(name: String, private val literal: Long) : Expression(name) { override fun eval(expressions: Map<String, Expression>): Long { return literal } override fun print(expressions: Map<String, Expression>): String { return if (this.name == "humn") { "x" } else { literal.toString() } } } fun parseJob(line: String): Expression { val moveRegex = """^(\w+): (?:(\w+) ([+-/*]) (\w+)|(\d+))$""".toRegex() return moveRegex.matchEntire(line) ?.destructured ?.let { (name, param1, op, param2, literal) -> if (literal.isEmpty()) { OperationExpression(name, param1, op.first(), param2) } else { LiteralExpression(name, literal.toLong()) } } ?: throw IllegalArgumentException("Bad input '$line'") } fun solveDay21Part2(input: List<String>): Int { val expressions = input.map { parseJob(it) }.associateBy { it.name }.toMutableMap() val root = expressions["root"] as OperationExpression expressions["root"] = OperationExpression(root.name, root.param1, '=', root.param2) val eval = expressions["root"]!!.print(expressions) println(eval) // TODO solve the equation in code // i just used https://www.mathpapa.com/algebra-calculator.html return -1 }
0
Kotlin
0
0
34437876bf5c391aa064e42f5c984c7014a9f46d
3,079
AdventOfCode2022
Apache License 2.0
src/main/kotlin/day18.kt
Gitvert
725,292,325
false
{"Kotlin": 97000}
import java.util.* const val X_SIZE = 340 const val Y_SIZE = 270 fun day18 (lines: List<String>) { val instructions = parseDigInstructions(lines) val trenchMap: Array<Array<Char>> = Array(Y_SIZE) { Array(X_SIZE) {'.'} } digTrench(instructions, trenchMap) bfs(trenchMap) val trenchSize = trenchMap.flatten().count { it == '.' || it == '#' } println("Day 18 part 1: $trenchSize") println("Day 18 part 2: ") println() } fun digTrench(instructions: List<DigInstruction>, trenchMap: Array<Array<Char>>) { var currentPos = Pos(130, 240) instructions.forEach { instruction -> val direction = when(instruction.dir) { 'U' -> { Pos(0, -1) } 'D' -> { Pos(0, 1) } 'L' -> { Pos(-1, 0) } else -> { Pos(1, 0) } } for (i in 1..instruction.length) { currentPos = Pos(currentPos.x + direction.x, currentPos.y + direction.y) trenchMap[currentPos.y][currentPos.x] = '#' } } } fun bfs(trenchMap: Array<Array<Char>>) { val start = Pos(0,0) val queue: Queue<Pos> = LinkedList() trenchMap[start.y][start.x] = '*' val visited = mutableListOf(start) queue.add(start) while(queue.isNotEmpty()) { val current = queue.peek() queue.remove() for (i in 0..3) { val posToCheck = Pos(current.x + D_ROW[i], current.y + D_COL[i]) if (isValid(trenchMap, posToCheck, visited)) { visited.add(posToCheck) queue.add(posToCheck) trenchMap[posToCheck.y][posToCheck.x] = '*' } } } } fun isValid(trenchMap: Array<Array<Char>>, pos: Pos, visited: List<Pos>): Boolean { if (pos.x < 0 || pos.y < 0 || pos.x >= trenchMap[0].size || pos.y >= trenchMap.size) { return false } if (visited.contains(pos)) { return false } if (trenchMap[pos.y][pos.x] == '#') { return false } return true } fun parseDigInstructions(lines: List<String>): List<DigInstruction> { return lines.map { DigInstruction(it.split(" ")[0][0], Integer.parseInt(it.split(" ")[1]), it.split(" ")[2]) } } data class DigInstruction(val dir: Char, val length: Int, val color: String)
0
Kotlin
0
0
f204f09c94528f5cd83ce0149a254c4b0ca3bc91
2,308
advent_of_code_2023
MIT License
advent-of-code-2021/src/code/day15/Main.kt
Conor-Moran
288,265,415
false
{"Kotlin": 53347, "Java": 14161, "JavaScript": 10111, "Python": 6625, "HTML": 733}
package code.day15 import code.common.twoDimIterate import java.io.File fun main() { doIt("Day 15 Part 1: Test Input", "src/code/day15/test.input", part1) doIt("Day 15 Part 1: Real Input", "src/code/day15/part1.input", part1) doIt("Day 15 Part 2: Test Input", "src/code/day15/test.input", part2) doIt("Day 15 Part 2: Real Input", "src/code/day15/part1.input", part2) } fun doIt(msg: String, input: String, calc: (nums: List<String>) -> Long) { val lines = arrayListOf<String>() File(input).forEachLine { lines.add(it) } println(String.format("%s: Ans: %d", msg , calc(lines))) } val part1: (List<String>) -> Long = { lines -> val data = parse(lines) //dump(data) findMinPathDistDijkstra(data, Point(0, 0), Point(data.lastIndex, data[0].lastIndex)) } val part2: (List<String>) -> Long = { lines -> val origData = parse(lines) //dump(data) val data = tile(origData) findMinPathDistDijkstra(data, Point(0, 0), Point(data.lastIndex, data[0].lastIndex)) } fun tile(data: Data): Data { val magFactor = 5 val tiledData = Array<Array<Int>>(magFactor * data.size) { Array<Int>(magFactor * data[0].size) {0} } var dataToUse = data for (i in 0 until 5) { for (j in 0 until 5) { twoDimIterate(dataToUse) { v, _, ii, jj -> tiledData[i * dataToUse.size + ii][j * dataToUse[0].size + jj] = v } dataToUse = incTile(dataToUse) } dataToUse = data for(x in 0 until i + 1) dataToUse = incTile(dataToUse) } return tiledData } fun incTile(data: Data): Data { val incData = Array<Array<Int>>(data.size) { Array<Int>(data[0].size) {0} } twoDimIterate(data) { v, _, i, j -> incData[i][j] = if (v == 9) 1 else v + 1 } return incData } /* * https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm * Notes: * - Dropped prev, no need to know the path * - Could make this more OO * - Added activeDists as performance was poor when we didn't prune removed vertices */ fun findMinPathDistDijkstra(data: Array<Array<Int>>, from: Point, to: Point): Long { val allDists = mutableMapOf<Point, Long>() val activeDists = mutableMapOf<Point, Long>() val vertices = mutableSetOf<Point>() twoDimIterate(data) { _, _, i, j -> val v = Point(i, j) vertices.add(v) } activeDists[from] = 0L allDists[from] = 0L while(vertices.isNotEmpty()) { val u = vertWithMinDistance(activeDists, vertices) val distU = allDists[u]!! vertices.remove(u) val neighbours = neighbours(u, vertices) if (u == to) { break } for (neighbour in neighbours) { val alt = distU + data[neighbour.x][neighbour.y] if (alt < activeDists.getOrDefault(neighbour, Long.MAX_VALUE)) { activeDists[neighbour] = alt allDists[neighbour] = alt } } //if (vertices.size % 100 == 0) println(vertices.size) } return allDists[to]!! } fun neighbours(p: Point, vertices: Set<Point>): Set<Point> { val ret = mutableSetOf<Point>() if (p.x > 0) { val left = Point(p.x - 1, p.y) if (vertices.contains(left)) { ret.add(left) } } if (p.y > 0) { val up = Point(p.x, p.y - 1) if (vertices.contains(up)) { ret.add(up) } } val right = Point(p.x + 1, p.y) if (vertices.contains(right)) { ret.add(right) } val down = Point(p.x, p.y + 1) if (vertices.contains(down)) { ret.add(down) } return ret } fun vertWithMinDistance(distMap: MutableMap<Point, Long>, vertices: Set<Point>): Point { val toRemove = mutableSetOf<Point>() var minDist = Long.MAX_VALUE var minSoFar: Point? = null for (e in distMap) { if (!vertices.contains(e.key)) { toRemove.add(e.key) } if (e.value < minDist) { minSoFar = e.key minDist = e.value } } toRemove.forEach { distMap.remove(it) } return minSoFar!! } fun parse(lines: List<String>): Array<Array<Int>> { val data = Array(lines.size) { Array( lines[0].length) { 0 } } lines.forEachIndexed { i, str -> for(j in str.indices) { data[i][j] = str[j].digitToInt() } } return data } fun dump(data: Data) { twoDimIterate(data) { i, isNewLine, _, _ -> if (isNewLine) println() print(i) } println() return } typealias Data = Array<Array<Int>> data class Point(val x: Int, val y: Int) class Input(val x: String, val replacements: Map<String, Char>)
0
Kotlin
0
0
ec8bcc6257a171afb2ff3a732704b3e7768483be
4,709
misc-dev
MIT License
src/main/kotlin/de/mbdevelopment/adventofcode/year2021/solvers/day14/Day14Puzzle2.kt
Any1s
433,954,562
false
{"Kotlin": 96683}
package de.mbdevelopment.adventofcode.year2021.solvers.day14 import de.mbdevelopment.adventofcode.year2021.solvers.PuzzleSolver class Day14Puzzle2 : PuzzleSolver { override fun solve(inputLines: Sequence<String>) = highestMinusLowestQuantity(inputLines.toList()).toString() private fun highestMinusLowestQuantity(polymerInstructions: List<String>): Long { val polymerTemplate = polymerInstructions.first() val pairInsertionRules = polymerInstructions .asSequence() .drop(1) .filter { it.isNotBlank() } .map { it.split(" -> ") } .map { it[0] to it[1] } .toMap() var pairCounts = polymerTemplate .windowed(2) .groupingBy { it } .fold(0L) { accumulator: Long, _: String -> accumulator + 1 } val elementCounts = polymerTemplate .groupingBy { it } .fold(0L) { accumulator, _ -> accumulator + 1 } .toMutableMap() repeat(40) { val roundPairCounts = mutableMapOf<String, Long>() pairCounts.keys.forEach { val newElement = pairInsertionRules[it] if (newElement != null) { roundPairCounts.merge(it[0] + newElement, pairCounts[it]!!, Long::plus) roundPairCounts.merge(newElement + it[1], pairCounts[it]!!, Long::plus) elementCounts.merge(newElement[0], pairCounts[it]!!, Long::plus) } } pairCounts = roundPairCounts } return elementCounts.values.sorted().let { it.last() - it.first() } } }
0
Kotlin
0
0
21d3a0e69d39a643ca1fe22771099144e580f30e
1,655
AdventOfCode2021
Apache License 2.0
src/main/kotlin/aoc2021/day13/Foldception.kt
arnab
75,525,311
false
null
package aoc2021.day13 object Foldception { data class Loc(val x: Int, val y: Int) enum class FoldDirection() { X, Y, } data class Fold(val dir: FoldDirection, val amount: Int) fun parse(data: String): Pair<Set<Loc>, List<Fold>> { val (locationLines, foldLines) = data.split("\n\n").take(2) val locations = locationLines.split("\n").map { line -> val (x, y) = line.split(",").take(2).map { it.toInt() } Loc(x, y) }.toSet() val folds = foldLines.split("\n") .map { it.replace("fold along ", "") } .map { val (dir, amount) = it.split("=").take(2) when( dir.toLowerCase() ) { "y" -> Fold(FoldDirection.Y, amount.toInt()) "x" -> Fold(FoldDirection.X, amount.toInt()) else -> throw IllegalArgumentException("Don't know direction for fold: $it") } } return Pair(locations, folds) } fun fold(initLocations: Set<Loc>, folds: List<Fold>, debug: Boolean = false): Set<Loc> { return folds.fold(initLocations) { locations, fold -> printLocations(debug, locations, fold) when (fold.dir) { FoldDirection.Y -> locations.filter { it.y > fold.amount } .map { it.copy(y = 2 * fold.amount - it.y) } .toSet() + locations.filter { it.y < fold.amount } FoldDirection.X -> locations.filter { it.x > fold.amount } .map { it.copy(x = 2 * fold.amount - it.x) } .toSet() + locations.filter { it.x < fold.amount } } } } fun printLocations(debug: Boolean, locations: Set<Loc>, fold: Fold? = null) { if (!debug) return val maxX = locations.map { it.x }.maxOf { it } val maxY = locations.map { it.y }.maxOf { it } println("=========================================================================================") (0..maxY).forEach { j -> println() (0..maxX).forEach { i -> val marker = if (locations.contains(Loc(i, j))) "#" else "." print(marker) } } println() if (fold != null) println("Applying: $fold") println("=========================================================================================") } fun countMarkedSpots(locations: Set<Loc>) = locations.count() }
0
Kotlin
0
0
1d9f6bc569f361e37ccb461bd564efa3e1fccdbd
2,508
adventofcode
MIT License
src/main/kotlin/com/jaspervanmerle/aoc2021/day/Day15.kt
jmerle
434,010,865
false
{"Kotlin": 60581}
package com.jaspervanmerle.aoc2021.day import java.util.* class Day15 : Day("748", "3045") { private data class Node( val x: Int, val y: Int, val riskLevel: Int, val neighbors: MutableList<Node> = mutableListOf() ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Node if (x != other.x) return false if (y != other.y) return false if (riskLevel != other.riskLevel) return false return true } override fun hashCode(): Int { var result = x result = 31 * result + y result = 31 * result + riskLevel return result } } private val partialRiskLevels = input .lines() .map { line -> line.toCharArray().map { it.digitToInt() }.toIntArray() } .toTypedArray() override fun solvePartOne(): Any { return getLowestTotalRisk(partialRiskLevels) } override fun solvePartTwo(): Any { val partialWidth = partialRiskLevels[0].size val partialHeight = partialRiskLevels.size val allRiskLevels = Array(partialHeight * 5) { y -> IntArray(partialWidth * 5) { x -> val distance = x / partialWidth + y / partialHeight val originalRiskLevel = partialRiskLevels[y % partialHeight][x % partialWidth] val newRiskLevel = originalRiskLevel + distance if (newRiskLevel > 9) newRiskLevel - 9 else newRiskLevel } } return getLowestTotalRisk(allRiskLevels) } private fun createNodes(riskLevels: Array<IntArray>): Array<Array<Node>> { val width = riskLevels[0].size val height = riskLevels.size val nodes = Array(height) { y -> Array(width) { x -> Node(x, y, riskLevels[y][x]) } } for (y in 0 until height) { for (x in 0 until width) { val node = nodes[y][x] if (x > 0) { node.neighbors.add(nodes[y][x - 1]) } if (x < width - 1) { node.neighbors.add(nodes[y][x + 1]) } if (y > 0) { node.neighbors.add(nodes[y - 1][x]) } if (y < height - 1) { node.neighbors.add(nodes[y + 1][x]) } } } return nodes } private fun getLowestTotalRisk(riskLevels: Array<IntArray>): Int { val nodes = createNodes(riskLevels).flatten() val source = nodes[0] val target = nodes.last() val distances = nodes.associateWith { Int.MAX_VALUE }.toMutableMap() distances[source] = 0 val nodesToProcess = PriorityQueue<Node>(Comparator.comparingInt { distances[it]!! }) nodesToProcess.add(source) while (nodesToProcess.isNotEmpty()) { val node = nodesToProcess.remove() if (node == target) { return distances[node]!! } for (neighbor in node.neighbors) { val newDistance = distances[node]!! + neighbor.riskLevel if (newDistance < distances[neighbor]!!) { distances[neighbor] = newDistance nodesToProcess.add(neighbor) } } } throw IllegalArgumentException("There is no path from source to target") } }
0
Kotlin
0
0
dcac2ac9121f9bfacf07b160e8bd03a7c6732e4e
3,638
advent-of-code-2021
MIT License
calendar/day16/Day16.kt
maartenh
572,433,648
false
{"Kotlin": 50914}
package day16 import Day import Lines import tools.* import kotlin.math.min class Day16 : Day() { override fun part1(input: Lines): Any { val tunnelMap = parseMap(input) val openableValves = tunnelMap.values.filter { it.flowRate > 0 } val reducedTunnelMap = reduceMap(map = tunnelMap, toNodes = openableValves, startNode = tunnelMap["AA"]!!) val bestVentActions = findMaxVent( listOf(Path("AA", 0)), tunnelMap = reducedTunnelMap, openableValves = openableValves.map { it.name }.toSet(), openedValves = setOf(), minutesLeft = 30, bestFound = 0, maxFlow = totalFlow(openableValves) ) return if (bestVentActions != null) { println(bestVentActions.second.reversed().joinToString("\n")) bestVentActions.first } else { -1 } } override fun part2(input: Lines): Any { val tunnelMap = parseMap(input) val openableValves = tunnelMap.values.filter { it.flowRate > 0 } val reducedTunnelMap = reduceMap(map = tunnelMap, toNodes = openableValves, startNode = tunnelMap["AA"]!!) val bestVentActions = findMaxVent( listOf(Path("AA", 0), Path("AA", 0)), tunnelMap = reducedTunnelMap, openableValves = openableValves.map { it.name }.toSet(), openedValves = setOf(), minutesLeft = 26, bestFound = 0, maxFlow = totalFlow(openableValves) ) return if (bestVentActions != null) { println(bestVentActions.second.reversed().joinToString("\n")) bestVentActions.first } else { -1 } } private fun reduceMap(map: Map<String, Valve>, toNodes: List<Valve>, startNode: Valve): Map<String, Valve> { val targetNodes = toNodes.toSet() val updatedNodes = (toNodes + startNode).map { fromNode -> val visitedNodes = mutableSetOf(fromNode) visitedNodes.remove(startNode) var currentNodes = setOf(fromNode) val newPaths = mutableSetOf<Path>() var steps = 1 while (!visitedNodes.containsAll(toNodes)) { val nextNodes = currentNodes .flatMap { node -> node.pathsTo.map { path -> map[path.destination]!! } } .filter { it !in visitedNodes && it !in currentNodes } .toSet() nextNodes .filter { it in targetNodes } .forEach { target -> newPaths.add(Path(target.name, steps)) } visitedNodes.addAll(nextNodes) currentNodes = nextNodes steps += 1 } fromNode.copy(pathsTo = newPaths.toList()) } return updatedNodes.associateBy { it.name } } private fun findMaxVent( currentMoves: List<Path>, tunnelMap: Map<String, Valve>, openableValves: Set<String>, openedValves: Set<String>, minutesLeft: Int, bestFound: Int, maxFlow: Int ): Pair<Int, List<String>>? { if (minutesLeft <= 0) { return null } if (maxFlow * minutesLeft < bestFound) { return null } var bestResult: Pair<Int, List<String>>? = null val currentMove = currentMoves.first { it.length == 0 } val otherMoves = currentMoves - currentMove val currentValve = tunnelMap[currentMove.destination]!! val newOpenedValuves = openedValves + currentValve.name val newOpenableValves = openableValves - currentValve.name val currentFlow = totalFlow(newOpenedValuves.map { tunnelMap[it]!! }) if (newOpenableValves.isEmpty()) { return (minutesLeft * currentFlow) to listOf("Wait $minutesLeft minutes with flow = $currentFlow") } currentValve.pathsTo .filter { it.destination in newOpenableValves } .forEach { tunnelPath -> val nextEventTime = min(tunnelPath.length + 1, otherMoves.minOfOrNull { it.length } ?: Int.MAX_VALUE) val flowDuringMove = currentFlow * nextEventTime val newMoves = (otherMoves + tunnelPath.copy(length = tunnelPath.length + 1)).map { it.copy(length = it.length - nextEventTime) } if (nextEventTime < minutesLeft) { val moveResult = findMaxVent( newMoves, tunnelMap, newOpenableValves, newOpenedValuves, minutesLeft - nextEventTime, (bestResult?.first ?: bestFound) - flowDuringMove, maxFlow ) if (moveResult != null && moveResult.first + flowDuringMove > (bestResult?.first ?: bestFound)) { bestResult = (moveResult.first + flowDuringMove) to (moveResult.second.plusElement("Opened ${currentValve.name}, moving to ${tunnelPath.destination}, duration = ${tunnelPath.length + 1} flow = $currentFlow")) } } else { val timeoutFlow = currentFlow * minutesLeft if (timeoutFlow > (bestResult?.first ?: bestFound)) { bestResult = currentFlow * minutesLeft to listOf("Out of time moving to valve ${tunnelPath.destination}, duration = $minutesLeft, flow = $currentFlow") } } } return bestResult } private fun totalFlow(valves: List<Valve>): Int = valves.sumOf { it.flowRate } private fun parseMap(input: Lines): Map<String, Valve> { return input.map { runParser(valve(), it) }.associateBy { valve -> valve.name } } data class Valve(val name: String, val flowRate: Int, val pathsTo: List<Path>) data class Path(val destination: String, val length: Int) private fun valve(): Parser<Valve> { val name = (string("Valve ") seq string(2)).map { it.second } val flow = (string(" has flow rate=") seq int()).map { it.second } val tunnel = (string("; tunnel leads to valve ") seq string(2)).map { listOf(Path(it.second, 1)) } val tunnels = (string("; tunnels lead to valves ") seq (string(2).map { Path( it, 1 ) }).list(string(", "))).map { it.second } return (name seq flow seq (tunnel or { tunnels })).map { Valve(it.first.first, it.first.second, it.second) } } }
0
Kotlin
0
0
4297aa0d7addcdc9077f86ad572f72d8e1f90fe8
6,824
advent-of-code-2022
Apache License 2.0
app/src/main/kotlin/day07/Day07.kt
W3D3
572,447,546
false
{"Kotlin": 159335}
package day07 import common.InputRepo import common.readSessionCookie import common.solve import util.selectRecursive import util.splitIntoPair fun main(args: Array<String>) { val day = 7 val input = InputRepo(args.readSessionCookie()).get(day = day) solve(day, input, ::solveDay07Part1, ::solveDay07Part2) } fun solveDay07Part1(input: List<String>): Int { val root = FileNode("/", null) executeCommands(root, input) println(root.toTreeString()) val allNodes = listOf(root).asSequence().selectRecursive { children.asSequence() } return allNodes.filter { it.isDirectory } .filter { it.size < 100_000 } .sumOf { it.size } } fun solveDay07Part2(input: List<String>): Int { val totalDiskSpace = 70_000_000 val minimumFreeDiskSpace = 30_000_000 val root = FileNode("/", null) executeCommands(root, input) val freeSpace = totalDiskSpace - root.size val spaceToFree = minimumFreeDiskSpace - freeSpace val allNodes = listOf(root).asSequence().selectRecursive { children.asSequence() } return allNodes.filter { it.isDirectory } .filter { it.size >= spaceToFree } .minOf { it.size } } fun executeCommand(cmd: String, arg: String, currentDir: FileNode<String>, root: FileNode<String>): FileNode<String> { when (cmd) { "cd" -> { return cd(arg, root, currentDir) } "ls" -> { val (info, name) = arg.splitIntoPair(" ") if (name.isBlank()) { return currentDir } ls(info, currentDir, name) } } return currentDir } private fun ls(info: String, currentDir: FileNode<String>, name: String) { if (info == "dir") { currentDir.children.add(FileNode(name, currentDir)) } else { val file = FileNode(name, currentDir, isDirectory = false) file.size = info.toInt() currentDir.children.add(file) } } private fun cd( arg: String, root: FileNode<String>, currentDir: FileNode<String> ): FileNode<String> { return when (arg) { "/" -> { root } ".." -> { currentDir.parent!! } else -> { currentDir.moveIntoChildren(arg) } } } private fun executeCommands(root: FileNode<String>, input: List<String>) { var currentCommand = "" var currentDir = root for (line in input) { if (line.startsWith("$")) { currentCommand = line.removePrefix("$").trim() val (cmd, arg) = currentCommand.splitIntoPair(" ") currentDir = executeCommand(cmd, arg, currentDir, root) } else { val (cmd, _) = currentCommand.splitIntoPair(" ") currentDir = executeCommand(cmd, line, currentDir, root) } } }
0
Kotlin
0
0
34437876bf5c391aa064e42f5c984c7014a9f46d
2,825
AdventOfCode2022
Apache License 2.0
src/main/kotlin/de/huddeldaddel/euler/Problem387.kt
huddeldaddel
171,357,298
false
null
package de.huddeldaddel.euler import de.huddeldaddel.euler.extensions.isPrime import de.huddeldaddel.euler.extensions.sumOfDigits import java.math.BigInteger import kotlin.system.measureTimeMillis /** * Solution for https://projecteuler.net/problem=387 */ class Problem387(private val upperBorder: BigInteger) { var result: BigInteger = BigInteger.ZERO fun compute(): BigInteger { result = BigInteger.ZERO (1..9).forEach { i -> buildNumbers(i.toBigInteger()) } return result } private fun buildNumbers(input: BigInteger) { (0..9).forEach { i -> val extended = BigInteger("$input$i") if(extended.isHarshad()) { if(extended.isStrong()) handlePrimeCandidate(extended) if(extended < upperBorder / BigInteger.TEN) buildNumbers(extended) } } } private fun handlePrimeCandidate(input: BigInteger) { (0..9).forEach { i -> val extended = BigInteger("$input$i") if((extended < upperBorder) && extended.isPrime()) result += extended } } } fun main() { println("Finished in ${measureTimeMillis { println(Problem387(BigInteger.TEN.pow(14)).compute()) }} milliseconds") } fun BigInteger.isHarshad(): Boolean { return BigInteger.ZERO == this.mod(this.sumOfDigits().toBigInteger()) } fun BigInteger.isStrong(): Boolean { return (this / sumOfDigits().toBigInteger()).isPrime() }
0
Kotlin
1
0
df514adde8c62481d59e78a44060dc80703b8f9f
1,518
euler
MIT License
src/Day07.kt
karlwalsh
573,854,263
false
{"Kotlin": 32685}
fun main() { fun part1(input: List<String>): Long = input.toFileSystem() .allSubDirectories() .map { it.size() } .filter { it <= 100000 } .sum() fun part2(input: List<String>): Long { val fileSystem = input.toFileSystem() val totalDiskSize = 70_000_000 val requiredDiskSpace = 30_000_000 val availableDiskSpace = totalDiskSize - fileSystem.size() return fileSystem.allSubDirectories() .map { it.size() } .sorted() .first { availableDiskSpace + it >= requiredDiskSpace } } val input = readInput("Day07") with(::part1) { val exampleResult = this(example()) check(exampleResult == 95437L) { "Part 1 result was $exampleResult" } println("Part 1: ${this(input)}") } with(::part2) { val exampleResult = this(example()) check(exampleResult == 24933642L) { "Part 2 result was $exampleResult" } println("Part 2: ${this(input)}") } } private class Directory(private val parent: Directory? = null) { private val directories: MutableList<Directory> = mutableListOf() private var filesize: Long = 0 fun parent(): Directory? = parent fun newDirectory(): Directory { val newDirectory = Directory(this) directories.add(newDirectory) return newDirectory } fun newFile(filesize: Long) { this.filesize += filesize } fun allSubDirectories(): List<Directory> { return directories + directories.flatMap { it.allSubDirectories() } } fun size(): Long = filesize + directories.sumOf { it.size() } } private fun List<String>.toFileSystem(): Directory { //Always start with a root directory val root = Directory() //current working directory var cwd = root val fileParser = FileParser() for (line in this) { when { // Ignore cd into root, we already have a root directory line.startsWith("$ cd /") -> continue // Ignore the ls command because we can pick up directory and file listings without it line.startsWith("$ ls") -> continue //Set cwd to parent line.startsWith("$ cd ..") -> cwd = cwd.parent() ?: cwd //Add directory to the cwd, and set cwd to the new directory line.startsWith("$ cd ") -> cwd = cwd.newDirectory() //Directory listing - Add directory to cwd line.startsWith("dir ") -> cwd.newDirectory() //File listing - Add file to cwd fileParser.matches(line) -> cwd.newFile(fileParser.filesize(line)) } } return root } private class FileParser() { companion object { val filenameRegex = """(?<size>\d+).+""".toRegex() } fun matches(listing: String): Boolean = filenameRegex.matches(listing) fun filesize(listing: String): Long { val match = filenameRegex.matchEntire(listing) ?: throw IllegalArgumentException("Not a file listing '$listing'") return match.groups["size"]!!.value.toLong() } } private fun example() = """ ${'$'} cd / ${'$'} ls dir a 14848514 b.txt 8504156 c.dat dir d ${'$'} cd a ${'$'} ls dir e 29116 f 2557 g 62596 h.lst ${'$'} cd e ${'$'} ls 584 i ${'$'} cd .. ${'$'} cd .. ${'$'} cd d ${'$'} ls 4060174 j 8033020 d.log 5626152 d.ext 7214296 k """.trimIndent().lines()
0
Kotlin
0
0
f5ff9432f1908575cd23df192a7cb1afdd507cee
3,604
advent-of-code-2022
Apache License 2.0
src/day10/solution.kt
bohdandan
729,357,703
false
{"Kotlin": 80367}
package day10 import println import readInput import java.lang.Exception enum class Directions(val vector: Position) { UP(Position(-1, 0)), DOWN(Position(1, 0)), LEFT(Position(0, -1)), RIGHT(Position(0, 1)); } class Route(val from: Directions, val to: Directions, val region1: List<Directions>, val region2: List<Directions>) enum class TileType(val char: Char, val routes: List<Route>) { VERTICAL('|', listOf( Route(Directions.UP, Directions.DOWN, listOf(Directions.RIGHT), listOf(Directions.LEFT)), Route(Directions.DOWN, Directions.UP, listOf(Directions.LEFT), listOf(Directions.RIGHT)) )), HORIZONTAL('-', listOf( Route(Directions.LEFT, Directions.RIGHT, listOf(Directions.UP), listOf(Directions.DOWN)), Route(Directions.RIGHT, Directions.LEFT, listOf(Directions.DOWN), listOf(Directions.UP)) )), L_SHAPE('L', listOf( Route(Directions.UP, Directions.RIGHT, listOf(), listOf(Directions.LEFT, Directions.DOWN)), Route(Directions.RIGHT, Directions.UP, listOf(Directions.LEFT, Directions.DOWN), listOf()), )), J_SHAPE('J', listOf( Route(Directions.UP, Directions.LEFT, listOf(Directions.RIGHT, Directions.DOWN), listOf()), Route(Directions.LEFT, Directions.UP, listOf(), listOf(Directions.RIGHT, Directions.DOWN)), )), SEVEN_SHAPE('7', listOf( Route(Directions.LEFT, Directions.DOWN, listOf(Directions.UP, Directions.RIGHT), listOf()), Route(Directions.DOWN, Directions.LEFT, listOf(), listOf(Directions.UP, Directions.RIGHT)), )), F_SHAPE('F', listOf( Route(Directions.DOWN, Directions.RIGHT, listOf(Directions.LEFT, Directions.UP), listOf()), Route(Directions.RIGHT, Directions.DOWN, listOf(), listOf(Directions.LEFT, Directions.UP)), )), EMPTY('.', listOf()), START('S', listOf()), REGION1('1', listOf()), REGION2('2', listOf()), } class Position(val row: Int, val column: Int) { fun move(vector: Position): Position { return Position(row + vector.row,column + vector.column) } fun move(to: Directions): Position { return move(to.vector) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Position) return false return row == other.row && column == other.column } } class Tile(val position: Position, val type: TileType) class TileWithRoute(val position: Position, val type: TileType, val route: Route) fun main() { class Puzzle(val map: List<CharArray>) { val OPPOSITES = mapOf( Directions.UP to Directions.DOWN, Directions.DOWN to Directions.UP, Directions.LEFT to Directions.RIGHT, Directions.RIGHT to Directions.LEFT ) private fun findStartPosition(): Position { for (rowNumber in map.indices) { for (columnNumber in map[rowNumber].indices) { if (map[rowNumber][columnNumber] == TileType.START.char) { return Position(rowNumber, columnNumber) } } } throw Exception("Can't find initial position") } fun getTile(map: List<CharArray>, position: Position): Tile? { if (position.row > map.lastIndex || position.row < 0) return null if (position.column > map[position.row].lastIndex || position.column < 0) return null var type = TileType.values().find { it.char == map[position.row][position.column]} if (type == null) { return null } else { return Tile(position, type) } } fun getTile(position: Position): Tile? { return getTile(map, position) } fun findStartingDirection(startingPosition: Position): Directions? { for (opposite in OPPOSITES.entries) { var tile = getTile(startingPosition.move(opposite.key)) ?: continue if(tile.type.routes.any{ it.from == opposite.value }) { return opposite.key } } throw Exception("Can't find initial direction") } private fun calculateLoop(): List<TileWithRoute> { var start = findStartPosition() var startDirection = findStartingDirection(start) var currentPosition = start var currentDirection: Directions? = startDirection val loopTiles = emptyList<TileWithRoute>().toMutableList() do { var tile = getTile(currentPosition.move(currentDirection!!))!! if (tile.type != TileType.START) { currentPosition = tile.position var route = tile.type.routes.find { it.from == OPPOSITES[currentDirection] }!! loopTiles += TileWithRoute(tile.position, tile.type, route) currentDirection = route.to } } while (tile.type != TileType.START) var startTileType = TileType.values().find {type -> type.routes.any{it.from == startDirection && it.to == OPPOSITES[currentDirection]} }!! loopTiles += TileWithRoute(start, startTileType, startTileType.routes.find { it.from == startDirection}!!) return loopTiles } fun getDistanceToFarthestPoint(): Int { return calculateLoop().size / 2 } fun getSizeOfAreaEnclosedByTheLoop(): Int { var loopTiles = calculateLoop() var loopMap = map.map { str -> ".".repeat(str.size).toCharArray() } loopTiles.forEach { loopMap[it.position.row][it.position.column] = it.type.char } loopMap.forEach { String(it).println() } var uncoloredTotal = loopMap.sumOf { row -> row.count { it == TileType.EMPTY.char } } uncoloredTotal.println() do { for (rowNumber in loopMap.indices) { for (columnNumber in loopMap[rowNumber].indices) { if (loopMap[rowNumber][columnNumber] != TileType.EMPTY.char) continue var position = Position(rowNumber, columnNumber) for (direction in OPPOSITES.entries) { var neighbourPosition = position.move(direction.key) var neighbourTile = getTile(loopMap, neighbourPosition) ?: continue if (neighbourTile.type in listOf(TileType.REGION1, TileType.REGION2)) { loopMap[rowNumber][columnNumber] = neighbourTile.type.char break } if (neighbourTile.type.routes.isNotEmpty()) { var tileWithRoute = loopTiles.find { it.position == neighbourPosition}!! if (tileWithRoute.route.region1.contains(direction.value)) { loopMap[rowNumber][columnNumber] = TileType.REGION1.char } else if (tileWithRoute.route.region2.contains(direction.value)) { loopMap[rowNumber][columnNumber] = TileType.REGION2.char } } } } } loopMap.forEach { String(it).println() } uncoloredTotal = loopMap.sumOf { row -> row.count { it == TileType.EMPTY.char } } uncoloredTotal.println() } while (uncoloredTotal > 0) var isRegion1 = false; for (tile in loopTiles) { if (tile.position.row == 0) { if (tile.route.region1.contains(Directions.UP)) { isRegion1 = false break } if (tile.route.region2.contains(Directions.UP)) { isRegion1 = true break } } } var charToFind = if (isRegion1) TileType.REGION1.char else TileType.REGION2.char charToFind.println() var result = loopMap.sumOf { row -> row.count { it == charToFind } } result.println() return result } } var testPuzzle1 = Puzzle(readInput("day10/test1").map { it.toCharArray() }) check(testPuzzle1.getDistanceToFarthestPoint() == 8) var puzzle = Puzzle(readInput("day10/input").map { it.toCharArray() }) puzzle.getDistanceToFarthestPoint().println() var testPuzzle2 = Puzzle(readInput("day10/test2").map { it.toCharArray() }) check(testPuzzle2.getSizeOfAreaEnclosedByTheLoop() == 8) var testPuzzle3 = Puzzle(readInput("day10/test3").map { it.toCharArray() }) check(testPuzzle3.getSizeOfAreaEnclosedByTheLoop() == 10) puzzle.getSizeOfAreaEnclosedByTheLoop().println() }
0
Kotlin
0
0
92735c19035b87af79aba57ce5fae5d96dde3788
9,175
advent-of-code-2023
Apache License 2.0
src/main/kotlin/org/cafejojo/schaapi/miningpipeline/patterndetector/spam/Spam.kt
cafejojo
138,387,851
false
{"Kotlin": 7207}
package org.cafejojo.schaapi.miningpipeline.patterndetector.spam import org.cafejojo.schaapi.models.CustomEqualsHashSet import org.cafejojo.schaapi.models.GeneralizedNodeComparator import org.cafejojo.schaapi.models.Node import org.cafejojo.schaapi.models.NodeSequenceUtil /** * Finds frequent sequences of [Node]s in the given collection of sequences, using the SPAM algorithm by Ayres et al. * * @property sequences all sequences in which patterns should be detected. Each sequence is a list of [Node]s. * @property minimumSupport the minimum amount of times a node must appear in [sequences] for it to be considered a * frequent node. * @property nodeComparator the nodeComparator used to determine whether two [Node]s are equal */ internal class Spam<N : Node>( private val sequences: Collection<List<N>>, private val minimumSupport: Int, private val nodeComparator: GeneralizedNodeComparator<N> ) { private val nodeSequenceUtil = NodeSequenceUtil<N>() private val frequentPatterns = mutableListOf<Pattern<N>>() private val frequentItems = CustomEqualsHashSet<N>(Node.Companion::equiv, Node::equivHashCode) /** * Finds frequent sequences in [sequences], using the SPAM algorithm by Ayres et al. (2002). * * @return frequent sequences in [sequences] */ internal fun findFrequentPatterns(): List<Pattern<N>> { frequentItems.addAll(nodeSequenceUtil.findFrequentNodesInSequences(sequences, minimumSupport).keys) frequentItems.forEach { runAlgorithm(listOf(it), frequentItems) } return frequentPatterns } /** * Creates a mapping from the found frequent [Pattern]s to [sequences] which contain said sequence. * * If [findFrequentPatterns] has not been run before, the resulting map will not contain any keys. * * @return a mapping from the frequent patterns to sequences which contain said sequence */ internal fun mapFrequentPatternsToSequences(): Map<Pattern<N>, List<List<N>>> = frequentPatterns.map { sequence -> sequence to sequences.filter { nodeSequenceUtil.sequenceContainsSubSequence(it, sequence, nodeComparator) } }.toMap() private fun runAlgorithm(pattern: List<N>, extensions: Set<N>) { frequentPatterns.add(pattern) val frequentExtensions = extensions.mapNotNull { extension -> val extendedPattern = pattern.toMutableList().apply { add(extension) } val support = sequences.count { sequence -> nodeSequenceUtil.sequenceContainsSubSequence(sequence, extendedPattern, nodeComparator) } if (support >= minimumSupport) extension else null }.toSet() frequentExtensions.forEach { runAlgorithm(pattern.toMutableList().apply { add(it) }, frequentExtensions) } } }
0
Kotlin
0
0
6e19a84cc67ed55a26aee30cf05aa75cfeb42592
2,845
spam-pattern-detector
MIT License
kotlin/src/2022/Day09_2022.kt
regob
575,917,627
false
{"Kotlin": 50757, "Python": 46520, "Shell": 430}
import kotlin.math.abs import kotlin.math.max private fun sign(a: Int, b: Int) = if (b > a) 1 else -1 private fun newPos(head: Pair<Int, Int>, tail: Pair<Int, Int>): Pair<Int, Int> { val (tx, ty) = tail val (xDiff, yDiff) = abs(head.first - tx) to abs(head.second - ty) if (max(xDiff, yDiff) <= 1) return tail if (xDiff == 0) return tx to ty + sign(ty, head.second) if (yDiff == 0) return tx + sign(tx, head.first) to ty return tx + sign(tx, head.first) to ty + sign(ty, head.second) } private fun direction(ch: Char) = when (ch) { 'U' -> 0 to -1 'D' -> 0 to 1 'L' -> -1 to 0 'R' -> 1 to 0 else -> throw IllegalArgumentException() } fun main() { val input = readInput(9).trim().lines() val inputPairs = input.map { val p = it.split(" ") p[0][0] to p[1].toInt() } // part1 var h = 0 to 0 var t = 0 to 0 val fields = mutableSetOf(t) for ((ch, cnt) in inputPairs) { val diff = direction(ch) repeat(cnt) { h = h.first + diff.first to h.second + diff.second t = newPos(h, t) fields.add(t) } } println(fields.size) // part2 val xs = MutableList(10) {0 to 0} fields.clear() for ((ch, cnt) in inputPairs) { val diff = direction(ch) repeat(cnt) { xs[0] = xs[0].first + diff.first to xs[0].second + diff.second var prev = xs[0] for (i in 1 until xs.size) { xs[i] = newPos(prev, xs[i]) prev = xs[i] } fields.add(xs.last()) } } println(fields.size) }
0
Kotlin
0
0
cf49abe24c1242e23e96719cc71ed471e77b3154
1,644
adventofcode
Apache License 2.0
src/main/kotlin/days/Day02.kt
irmakcelebi
573,174,392
false
{"Kotlin": 6258}
import java.lang.Exception fun main() { val day = Day02() day.run() day.test1(15) day.test2(12) } class Day02: Day() { override fun solve1(lines: List<String>): Int = lines .map { it.split(" ") } .sumOf { (x,y) -> val me = Hand.fromCharacter(y) val opponent = Hand.fromCharacter(x) me.score + me.play(opponent).score } override fun solve2(lines: List<String>): Int = lines .map { it.split(" ") } .sumOf { (x, y) -> val opponent = Hand.fromCharacter(x) val score = Score.fromCharacter(y) opponent.playForScore(score).score + score.score } } enum class Hand(val score: Int) { ROCK(1), PAPER(2), SCISSOR(3); companion object { fun fromCharacter(char: String) : Hand { return when(char) { "A", "X" -> ROCK "B", "Y" -> PAPER "C", "Z" -> SCISSOR else -> throw Exception() } } } fun play(opponent: Hand) : Score { return when (opponent to this) { ROCK to ROCK, SCISSOR to SCISSOR, PAPER to PAPER -> Score.DRAW ROCK to SCISSOR, SCISSOR to PAPER, PAPER to ROCK -> Score.LOSE else -> Score.WIN } } fun playForScore(expectedScore: Score) = values().first { it.play(this) == expectedScore } } enum class Score(val score: Int) { WIN(6), DRAW(3), LOSE(0); companion object { fun fromCharacter(char: String): Score { return when(char) { "X" -> LOSE "Y" -> DRAW "Z" -> WIN else -> throw Exception() } } } }
0
Kotlin
0
0
fe20c7fd574c505423a9d9be449a42427775ec76
1,835
AdventOfCode2022
Apache License 2.0
src/main/kotlin/leetcode/Problem1462.kt
fredyw
28,460,187
false
{"Java": 1280840, "Rust": 363472, "Kotlin": 148898, "Shell": 604}
package leetcode /** * https://leetcode.com/problems/course-schedule-iv/ */ class Problem1462 { fun checkIfPrerequisite(numCourses: Int, prerequisites: Array<IntArray>, queries: Array<IntArray>): List<Boolean> { val adjList = buildAdjList(prerequisites) val dependencyMap = mutableMapOf<Int, MutableSet<Int>>() for (course in 0 until numCourses) { val dependencies = mutableSetOf<Int>() dfs(adjList, BooleanArray(numCourses), dependencies, course) dependencyMap[course] = dependencies } val answer = mutableListOf<Boolean>() for (query in queries) { answer += query[1] in dependencyMap[query[0]]!! } return answer } private fun buildAdjList(prerequisites: Array<IntArray>): Map<Int, List<Int>> { val adjList = mutableMapOf<Int, MutableList<Int>>() for (prerequisite in prerequisites) { val from = prerequisite[0] val to = prerequisite[1] val list = adjList[from] ?: mutableListOf() list += to adjList[from] = list } return adjList } private fun dfs(adjList: Map<Int, List<Int>>, visited: BooleanArray, dependencies: MutableSet<Int>, course: Int) { visited[course] = true for (adj in (adjList[course] ?: listOf())) { if (!visited[adj]) { dfs(adjList, visited, dependencies, adj) } } dependencies += course } }
0
Java
1
4
a59d77c4fd00674426a5f4f7b9b009d9b8321d6d
1,562
leetcode
MIT License
day16.kt
anurudhp
433,699,953
false
{"Haskell": 8155, "PureScript": 7026, "Coq": 5078, "Rust": 4302, "Makefile": 2844, "Kotlin": 2509, "C#": 2506, "F#": 2402, "JavaScript": 2333, "Lean": 2085, "Pascal": 2028, "Zig": 2014, "C++": 1940, "Julia": 1558, "Java": 1384, "Scala": 1247, "MATLAB": 1227, "PHP": 1224, "D": 1193, "Clojure": 1101, "Go": 1075, "Brainfuck": 994, "Lua": 805, "Fortran": 657, "Ruby": 597, "Dhall": 368, "R": 277, "APL": 242}
package quick.start enum class Op(val i: Int) { Sum(0), Prod(1), Min(2), Max(3), Lit(4), Gt(5), Lt(6), Eq(7); companion object { fun fromInt(i: Int) = Op.values().first { it.i == i } } } class Packet(version: Int, op: Op, lit: Long, children: List<Packet>) { val version = version val op = op val children = children val lit = lit // literal constructor(v: Int, l: Long) : this(v, Op.Lit, l, emptyList()) {} // recursive constructor(v: Int, op: Op, ch: List<Packet>) : this(v, op, 0, ch) {} fun versionTotal(): Int { return version + children.map { it.versionTotal() }.sum() } fun eval(): Long { if (this.op == Op.Lit) return this.lit val res = children.map { it.eval() } if (op == Op.Sum) return res.sum() if (op == Op.Prod) return res.reduce(Long::times) if (op == Op.Min) return res.minOrNull()!! if (op == Op.Max) return res.maxOrNull()!! val (lhs, rhs) = res var cond = false if (op == Op.Gt) cond = lhs > rhs if (op == Op.Lt) cond = lhs < rhs if (op == Op.Eq) cond = lhs == rhs return if (cond) 1 else 0 } } fun parseLit(s: String): Pair<Long, String> { var s = s var res = 0L var done = false while (!done) { res = res * 16 + s.substring(1, 5).toLong(2) done = s[0] == '0' s = s.substring(5) } return Pair(res, s) } fun parsePacket(s: String): Pair<Packet, String> { val v = s.substring(0, 3).toInt(2) val ty = Op.fromInt(s.substring(3, 6).toInt(2)) val s = s.substring(6) if (ty == Op.Lit) { val (l, s) = parseLit(s) return Pair(Packet(v, l), s) } if (s[0] == '0') { // length of packets val len = s.substring(1, 16).toInt(2) val ss = s.substring(16 + len) var s = s.substring(16, 16 + len) var ps = mutableListOf<Packet>() while (!s.isEmpty()) { val (p, ss) = parsePacket(s) s = ss ps.add(p) } return Pair(Packet(v, ty, ps), ss) } else { // num. packets val num = s.substring(1, 12).toInt(2) var s = s.substring(12) var ps = mutableListOf<Packet>() for (i in 1..num) { val (p, ss) = parsePacket(s) s = ss ps.add(p) } return Pair(Packet(v, ty, ps), s) } } fun parseFull(s: String): Packet { val (p, s) = parsePacket(s) assert(s.all { it == '0' }) return p } fun main() { val inp = readLine()!! val data = ('1' + inp).toBigInteger(16).toString(2).drop(1) val packet = parseFull(data) println(packet.versionTotal()) println(packet.eval()) }
0
Haskell
0
2
ed497f854bbc57680126b5ef70e4cff6707a98e8
2,509
aoc2021
MIT License
src/Day02.kt
arnoutvw
572,860,930
false
{"Kotlin": 33036}
import java.lang.IllegalArgumentException fun main() { fun part1(input: List<String>): Int { var score = 0 input.forEach { val split = it.split(" ") val oppenent = Hand.getHand(split.get(0)) val own = Hand.getHand(split.get(1)) score += own.waarde + outcome(oppenent, own) } return score } fun part2(input: List<String>): Int { var score = 0 input.forEach { val split = it.split(" ") val oppenent = Hand.getHand(split.get(0)) val choice = outcomePart2(oppenent, split.get(1)) score += choice.waarde + outcome(oppenent, choice) } return score } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") println("Test") println(part1(testInput)) println(part2(testInput)) check(part1(testInput) == 15) check(part2(testInput) == 12) println("Waarde") val input = readInput("Day02") println(part1(input)) println(part2(input)) } enum class Hand { ROCK { override val beats: Hand get() = SCISSORS override val waarde: Int get() = 1 }, PAPER { override val beats: Hand get() = ROCK override val waarde: Int get() = 2 }, SCISSORS { override val beats: Hand get() = PAPER override val waarde: Int get() = 3 }; abstract val beats: Hand abstract val waarde: Int companion object { fun getHand(waarde: String): Hand { return when(waarde) { "A" -> ROCK "B" -> PAPER "C" -> SCISSORS "X" -> ROCK "Y" -> PAPER "Z" -> SCISSORS else -> throw IllegalAccessException("Onbekend: $waarde") } } } } fun outcome(p1: Hand, p2: Hand): Int { if(p1 == p2) { return 3; } if(p2.beats == p1) { return 6; } return 0; } fun outcomePart2(p1: Hand, p2: String): Hand { return when (p2) { "X" -> { p1.beats } "Y" -> { p1 } else -> { when (p1) { Hand.ROCK -> Hand.PAPER Hand.PAPER -> Hand.SCISSORS Hand.SCISSORS -> Hand.ROCK } } } }
0
Kotlin
0
0
0cee3a9249fcfbe358bffdf86756bf9b5c16bfe4
2,408
aoc-2022-in-kotlin
Apache License 2.0
src/Day05.kt
KliminV
573,758,839
false
{"Kotlin": 19586}
import kotlin.collections.ArrayList fun main() { fun part1(input: String): String { val parsedSplit = input.split("\n") val splitIndex = parsedSplit.indexOfFirst(String::isBlank) val map = parsedSplit.filterIndexed { index, _ -> index < splitIndex }.toList() val steps = parsedSplit.filterIndexed { index, _ -> index > splitIndex }.toList() val inputCols = arrayListOf<ArrayList<Char>>() val literalFinder = "\\[.]\\s?".toRegex() val numberFinder = "^move (\\d+) from (\\d+) to (\\d+)\\r?$".toRegex() map .reversed() .map { row -> row .windowed(4, 4, true) .mapIndexed { i, maybeLetter -> if (i >= inputCols.size) inputCols.add(ArrayList()) if (maybeLetter.matches(literalFinder)) { inputCols[i].add(maybeLetter[1]) } } } steps .map { command -> val numbers = mutableListOf<Int>() if (numberFinder.matches(command)) { val matchResult = numberFinder.find(command) matchResult!!.groupValues.mapIndexed { i, group -> if (i != 0) numbers.add(group.toInt()) } } if (numbers.size > 0) { val numOfElementsToMove = numbers[0] - 1 val wasCol = numbers[1] - 1 val nowCol = numbers[2] - 1 for (i in inputCols[wasCol].size - 1 downTo inputCols[wasCol].size - 1 - numOfElementsToMove) { inputCols[nowCol].add(inputCols[wasCol][i]) inputCols[wasCol].removeAt(i) } } } return inputCols.map { if (it.size > 0) it[it.size - 1] else "" }.joinToString("", "", "") } fun part2(input: String): String { val parsedSplit = input.split("\n") val splitIndex = parsedSplit.indexOfFirst(String::isBlank) val map = parsedSplit.filterIndexed { index, _ -> index < splitIndex }.toList() val steps = parsedSplit.filterIndexed { index, _ -> index > splitIndex }.toList() val inputCols = arrayListOf<ArrayList<Char>>() val literalFinder = "\\[.]\\s?".toRegex() val numberFinder = "^move (\\d+) from (\\d+) to (\\d+)\\r?$".toRegex() map .reversed() .map { row -> row .windowed(4, 4, true) .mapIndexed { i, maybeLetter -> if (i >= inputCols.size) inputCols.add(ArrayList()) if (maybeLetter.matches(literalFinder)) { inputCols[i].add(maybeLetter[1]) } } } steps .map { command -> val numbers = mutableListOf<Int>() if (numberFinder.matches(command)) { val matchResult = numberFinder.find(command) matchResult!!.groupValues.mapIndexed { i, group -> if (i != 0) numbers.add(group.toInt()) } } if (numbers.size > 0) { val numOfElementsToMove = numbers[0] - 1 val wasCol = numbers[1] - 1 val nowCol = numbers[2] - 1 for (i in inputCols[wasCol].size - 1 - numOfElementsToMove until inputCols[wasCol].size) { inputCols[nowCol].add(inputCols[wasCol][i]) } for (i in inputCols[wasCol].size - 1 downTo inputCols[wasCol].size - 1 - numOfElementsToMove) { inputCols[wasCol].removeAt(i) } } } return inputCols.map { if (it.size > 0) it[it.size - 1] else "" }.joinToString("", "", "") } // test if implementation meets criteria from the description, like: val testInput = read("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = read("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
542991741cf37481515900894480304d52a989ae
4,329
AOC-2022-in-kotlin
Apache License 2.0
src/main/kotlin/days/Day7.kt
nuudles
316,314,995
false
null
package days class Day7 : Day(7) { data class Rule( val container: String, val contains: List<Pair<String, Int>> ) fun parseRules(): List<Rule> = inputList .map { line -> line .split("contain") .let { components -> Rule( container = components[0].replace(" bags ", ""), contains = components[1] .split(",") .mapNotNull { contains -> Regex("""(\d) (.*) bag[s]*""") .find(contains) ?.let { result -> val (count, descriptor) = result.destructured descriptor to count.toInt() } } ) } } override fun partOne(): Any { val rules = parseRules() val containedBy = mutableMapOf<String, Set<String>>() rules .forEach { rule -> rule.contains.forEach { containedBy[it.first] = (containedBy[it.first] ?: setOf()) + rule.container } } val visited = mutableSetOf<String>() fun containCount(container: String): Int { if (visited.contains(container)) { return 0 } visited.add(container) return (containedBy[container]?.sumBy { containCount(it) } ?: 0) + 1 } return containCount("shiny gold") - 1 } override fun partTwo(): Any { val contains = parseRules() .fold(mutableMapOf<String, List<Pair<String, Int>>>()) { map, rule -> map[rule.container] = rule.contains map } fun containCount(container: String): Int { return ( contains[container] ?.map { it.second * containCount(it.first) } ?.sum() ?: 0 ) + 1 } return containCount("shiny gold") - 1 } }
0
Kotlin
0
0
5ac4aac0b6c1e79392701b588b07f57079af4b03
2,340
advent-of-code-2020
Creative Commons Zero v1.0 Universal
src/Day05.kt
dominiquejb
572,656,769
false
{"Kotlin": 10603}
fun main() { fun unpackLetter(boxedLetter: String): String { return boxedLetter.trim().removePrefix("[").removeSuffix("]") } fun part1(input: String): String { val (stacksSection, movesSection) = input.split("\n\n") // Part 1 - Parse stacks val stacksLines = stacksSection.split("\n").dropLast(1) val cratesRows = stacksLines.map { line -> line.chunked(4).map { box -> unpackLetter(box) } } // Turn rows into vertical stacks val crateStacks = List(cratesRows.first().size) { mutableListOf<String>() } cratesRows.forEach { row -> row.forEachIndexed { i, crate -> if (crate.isNotBlank()) { crateStacks[i].add(crate) } } } // Part 2 - Parse and execute moves val moveLines = movesSection.split("\n") moveLines.forEach { moveLine -> val moveSegments = moveLine.split(" ") val moveAmount = moveSegments[1].trim().toInt() val moveFromIdx = moveSegments[3].trim().toInt() - 1 val moveToIdx = moveSegments[5].trim().toInt() - 1 println("Moving $moveAmount crates from idx $moveFromIdx to idx $moveToIdx") val selectedCrates = crateStacks[moveFromIdx].take(moveAmount) selectedCrates.forEach { crate -> crateStacks[moveToIdx].add(0, crate) crateStacks[moveFromIdx].remove(crate) } } // Part 3 - Take first letters of each stack val letters = crateStacks.mapNotNull { stack -> stack.firstOrNull() }.joinToString("") return letters } fun part2(input: String): String { val (stacksSection, movesSection) = input.split("\n\n") // Part 1 - Parse stacks val stacksLines = stacksSection.split("\n").dropLast(1) val cratesRows = stacksLines.map { line -> line.chunked(4).map { box -> unpackLetter(box) } } // Turn rows into vertical stacks val crateStacks = List(cratesRows.first().size) { mutableListOf<String>() } cratesRows.forEach { row -> row.forEachIndexed { i, crate -> if (crate.isNotBlank()) { crateStacks[i].add(crate) } } } println(crateStacks) // Part 2 - Parse and execute moves val moveLines = movesSection.split("\n") moveLines.forEach { moveLine -> val moveSegments = moveLine.split(" ") val moveAmount = moveSegments[1].trim().toInt() val moveFromIdx = moveSegments[3].trim().toInt() - 1 val moveToIdx = moveSegments[5].trim().toInt() - 1 // println("Moving $moveAmount crates from idx $moveFromIdx to idx $moveToIdx") val selectedCrates = crateStacks[moveFromIdx].take(moveAmount) crateStacks[moveToIdx].addAll(0, selectedCrates) selectedCrates.forEach { _ -> crateStacks[moveFromIdx].removeFirst() } } // println(crateStacks) // Part 3 - Take first letters of each stack val letters = crateStacks.mapNotNull { stack -> stack.firstOrNull() }.joinToString("") return letters return "a" } val inputString = readInput("input.05") println(part1(inputString)) println(part2(inputString)) }
0
Kotlin
0
0
f4f75f9fc0b5c6c81759357e9dcccb8759486f3a
3,568
advent-of-code-2022
Apache License 2.0
src/day10/Day10.kt
dkoval
572,138,985
false
{"Kotlin": 86889}
package day10 import readInput private const val DAY_ID = "10" fun main() { fun solve(input: List<String>, onCycle: (cycle: Int, x: Int) -> Boolean) { var x = 1 var cycle = 1 for (line in input) { // noop var delta = 0 var cycleToComplete = 1 // addx <delta> if (line.startsWith("addx")) { delta = line.removePrefix("addx ").toInt() cycleToComplete = 2 } // execute instruction repeat(cycleToComplete) { if (onCycle(cycle++, x)) { // early termination return } } // finish execution by updating the state of the X register (only relevant for `addx`) x += delta } } fun part1(input: List<String>): Int { val cycles = setOf(20, 60, 100, 140, 180, 220) val signalStrengths = mutableListOf<Int>() solve(input) { cycle, x -> if (cycle in cycles) { signalStrengths += x * cycle } // condition for early termination signalStrengths.size == cycles.size } return signalStrengths.sum() } fun part2(input: List<String>): String { val width = 40 val height = 6 val screen = Array(height) { CharArray(width) { '.' } } solve(input) { cycle, x -> val row = (cycle - 1) / width val col = (cycle - 1) % width // if the sprite is positioned such that one of its three pixels is the pixel currently being drawn, // the screen produces a lit pixel if (col in (x - 1)..(x + 1)) { screen[row][col] = '@' } // no condition for early termination, process the input till the end false } return screen.joinToString(separator = "\n") { it.joinToString(separator = " ") } } // test if implementation meets criteria from the description, like: val testInput = readInput("day${DAY_ID}/Day${DAY_ID}_test") check(part1(testInput) == 13140) val input = readInput("day${DAY_ID}/Day$DAY_ID") println(part1(input)) // answer = 14340 println(part2(input)) // answer = PAPJCBHP }
0
Kotlin
1
0
791dd54a4e23f937d5fc16d46d85577d91b1507a
2,334
aoc-2022-in-kotlin
Apache License 2.0
aoc-2021/src/main/kotlin/nerok/aoc/aoc2021/day07/Day07.kt
nerok
572,862,875
false
{"Kotlin": 113337}
package nerok.aoc.aoc2021.day07 import nerok.aoc.utils.Input import kotlin.math.abs import kotlin.math.nextDown import kotlin.time.DurationUnit import kotlin.time.measureTime fun main() { fun calculateFuelCosts(positions: MutableList<Long>, selectedPosition: Long): Long { var cost = 0L positions.forEach { cost += abs(it - selectedPosition) } return cost } fun calculateProgressiveFuelCosts(positions: MutableList<Long>, selectedPosition: Long): Long { var cost = 0L positions.forEach { cost += LongRange(0, abs(it - selectedPosition)).sum() } return cost } fun part1(input: List<String>): Long { val longs = input.first().split(",").map { it.toLong() }.toMutableList() return calculateFuelCosts(longs, longs.sorted()[(longs.size/2)]) } // Broken fun part2(input: List<String>): Long { val longs = input.first().split(",").map { it.toLong() }.toMutableList() val average = longs.average().nextDown().toLong() return calculateProgressiveFuelCosts(longs, average) } // test if implementation meets criteria from the description, like: val testInput = Input.readInput("Day07_test") check(part1(testInput) == 37L) //check(part2(testInput) == 168L) val input = Input.readInput("Day07") println(measureTime { println(part1(input)) }.toString(DurationUnit.SECONDS, 3)) println(measureTime { println(part2(input)) }.toString(DurationUnit.SECONDS, 3)) }
0
Kotlin
0
0
7553c28ac9053a70706c6af98b954fbdda6fb5d2
1,545
AOC
Apache License 2.0
src/main/kotlin/day7/Aoc.kt
widarlein
225,589,345
false
null
package day7 fun main(args: Array<String>) { if (args.size < 1) { println("Must provide input program") System.exit(0) } val inputProgram = args[0].split(",").map { it.toInt() }.toIntArray() val highestOutput = bruteForceThrusters(inputProgram) println("Highest part 1 output found: $highestOutput") val highestPart2Output = bruteForcePart2Thrusters(inputProgram) println("Highest part 2 output found: $highestPart2Output") } internal fun bruteForceThrusters(thrusterProgram: IntArray): Int { val permutations = getAllPhasePermutations() var highestOutput = 0 permutations.forEach {permutation -> var lastOutput = listOf(0) for (amplifier in 0..4) { lastOutput = runProgram(thrusterProgram.copyOf(), listOf(permutation[amplifier], lastOutput.first())) } if (lastOutput.first() > highestOutput) { highestOutput = lastOutput.first() } } return highestOutput } internal fun bruteForcePart2Thrusters(thrusterProgram: IntArray): Int { val permutations = getPart2PhasePermutations() var highestOutput = 0 permutations.forEach {permutation -> val amplifiers = permutation.map { phaseSetting -> Amplifier(thrusterProgram.copyOf(), phaseSetting) } var amp4Output = 0 amplifiers[0].onOutput = { output -> amplifiers[1].addInput(output)} amplifiers[1].onOutput = { output -> amplifiers[2].addInput(output)} amplifiers[2].onOutput = { output -> amplifiers[3].addInput(output)} amplifiers[3].onOutput = { output -> amplifiers[4].addInput(output)} amplifiers[4].onOutput = { output -> println("LAST AMP OUTPUT") amp4Output = output if (amplifiers[4].isRunning) { amplifiers[0].addInput(output) } } amplifiers.forEach { it.run() } amplifiers[0].addInput(0) while (amplifiers.any { it.isRunning }) { Thread.sleep(2) } if (amp4Output > highestOutput) { highestOutput = amp4Output } } return highestOutput } internal fun getAllPhasePermutations(): MutableList<IntArray> { val permutations = mutableListOf<IntArray>() for (a in 0..4) { for (b in 0..4) { if (b == a) continue for (c in 0..4) { if (c == a || c == b) continue for (d in 0..4) { if (d == a || d == b || d == c) continue for (e in 0..4) { if (e == a || e == b || e == c || e == d) continue permutations.add(intArrayOf(a, b, c, d, e)) } } } } } return permutations } internal fun getPart2PhasePermutations(): MutableList<IntArray> { val permutations = mutableListOf<IntArray>() for (a in 5..9) { for (b in 5..9) { if (b == a) continue for (c in 5..9) { if (c == a || c == b) continue for (d in 5..9) { if (d == a || d == b || d == c) continue for (e in 5..9) { if (e == a || e == b || e == c || e == d) continue permutations.add(intArrayOf(a, b, c, d, e)) } } } } } return permutations } internal fun runProgram(memory: IntArray, inputs: List<Int>): MutableList<Int> { val mutableInputs = inputs.toMutableList() val mutableOutputs = mutableListOf<Int>() var pointer = 0 while (memory[pointer] != 99 || pointer > memory.size) { val (opcode, parameterModes) = memory[pointer].toOpCodeAndParameterModes() debug(opcode, parameterModes, memory, pointer) pointer = when(opcode) { 1 -> add(pointer + 1, pointer + 2, pointer + 3, memory, parameterModes) 2 -> multiply(pointer + 1, pointer + 2, pointer + 3, memory, parameterModes) 3 -> storeInput(pointer + 1, readNextInput(mutableInputs), memory) 4 -> output(pointer + 1, memory, parameterModes, mutableOutputs) 5 -> jumpIfTrue(pointer +1, pointer +2, memory, parameterModes) 6 -> jumpIfFalse(pointer +1, pointer +2, memory, parameterModes) 7 -> lessThan(pointer +1, pointer +2, pointer +3, memory, parameterModes) 8 -> equals(pointer +1, pointer +2, pointer +3, memory, parameterModes) else -> throw IllegalArgumentException("Unsupported Opcode found at position $pointer: $opcode") } } if (pointer > memory.size) { println("Program ran out without exit opcode 99.") } //println("Execution ended. Program state:\n${memory.joinToString(",")}") return mutableOutputs } internal fun add(firstPos: Int, secondPos: Int, resultPos: Int, memory: IntArray, parameterModes: Int): Int { val (first, second) = parameterValues(parameterModes, memory, memory[firstPos], memory[secondPos]) memory[memory[resultPos]] = first + second return firstPos - 1 + 4 // hack since we know pointer is firstPost - 1 } internal fun multiply(firstPos: Int, secondPos: Int, resultPos: Int, memory: IntArray, parameterModes: Int): Int { val (first, second) = parameterValues(parameterModes, memory, memory[firstPos], memory[secondPos]) memory[memory[resultPos]] = first * second return firstPos - 1 + 4 // hack since we know pointer is firstPost - 1 } internal fun storeInput(storePos: Int, input: Int, memory: IntArray): Int { memory[memory[storePos]] = input return storePos - 1 + 2 // hack since we know pointer is storePos - 1 } internal fun output( readPos: Int, memory: IntArray, parameterModes: Int, mutableOutputs: MutableList<Int> ): Int { val (first) = parameterValues(parameterModes, memory, memory[readPos]) mutableOutputs.add(first) println(first) return readPos - 1 + 2 // hack since we know pointer is storePos - 1 } internal fun jumpIfTrue(guardPos: Int, pointerValPos: Int, memory: IntArray, parameterModes: Int): Int { val (guard, pointerVal) = parameterValues(parameterModes, memory, memory[guardPos], memory[pointerValPos]) if (guard != 0) { return pointerVal } return guardPos - 1 + 3 // hack since we know pointer is guardPos - 1 } internal fun jumpIfFalse(guardPos: Int, pointerValPos: Int, memory: IntArray, parameterModes: Int): Int { val (guard, pointerVal) = parameterValues(parameterModes, memory, memory[guardPos], memory[pointerValPos]) if (guard == 0) { return pointerVal } return guardPos - 1 + 3 // hack since we know pointer is guardPos - 1 } internal fun lessThan(firstPos: Int, secondPos: Int, resultPos: Int, memory: IntArray, parameterModes: Int): Int { val (first, second) = parameterValues(parameterModes, memory, memory[firstPos], memory[secondPos]) memory[memory[resultPos]] = if (first < second) 1 else 0 return firstPos - 1 + 4 // hack since we know pointer is firstPos - 1 } internal fun equals(firstPos: Int, secondPos: Int, resultPos: Int, memory: IntArray, parameterModes: Int): Int { val (first, second) = parameterValues(parameterModes, memory, memory[firstPos], memory[secondPos]) memory[memory[resultPos]] = if (first == second) 1 else 0 return firstPos - 1 + 4 // hack since we know pointer is firstPos - 1 } internal fun parameterValues(parameterModes: Int, memory: IntArray, vararg parameters: Int): List<Int> { var paramModes = parameterModes return parameters.map { val mode = paramModes % 10 paramModes /= 10 when (mode) { 0 -> memory[it] 1 -> it else -> throw IllegalArgumentException("No such parameter mode $it") } } } internal fun readNextInput(inputs: MutableList<Int>): Int { val input = inputs.first() inputs.removeAt(0) return input } internal fun requestInput(): Int { var input: Int? = null do { print("Enter input: ") val inputText = readLine()!! try { input = inputText.toInt() } catch (e: NumberFormatException) { println("Illegal input format. Input should be an integer") continue } } while (input == null) return input } internal fun Int.toOpCodeAndParameterModes(): Pair<Int, Int> { val opcode = this % 100 val parameterModes = this / 100 return opcode to parameterModes }
0
Kotlin
0
0
b4977e4a97ad61177977b8eeb1dcf298067e8ab4
8,554
AdventOfCode2019
MIT License
2017/src/main/java/p10/Problem10.kt
ununhexium
113,359,669
false
null
package p10 import com.google.common.collect.Lists import more.CircularList import more.formattedHexadecimal class Assembly(val lengths: List<Int>, val chainLength: Int, val rounds: Int) val inputs = listOf( Assembly(listOf(3, 4, 1, 5), 5, 1), Assembly( listOf( 102, 255, 99, 252, 200, 24, 219, 57, 103, 2, 226, 254, 1, 0, 69, 216 ), 256, 1 ) ) fun asciiToInt(input: String) = input.map { it.toInt() } private fun knotHash(assembly: Assembly): CircularList<Int> { val list = CircularList((0 until assembly.chainLength).toList()) var current = 0 var skipSize = 0 (1..assembly.rounds).forEach { assembly.lengths.forEach { length -> list.swap(current, length) current += length + skipSize skipSize++ } } return list } fun denseHash(list: List<Int>) = Lists.partition(list, 16).map { it.reduce { a, b -> a xor b }!! } fun addTail(list: List<Int>) = list.toMutableList().also { it.addAll(listOf(17, 31, 73, 47, 23)) } fun hexHash(input: String): String { return denseHash( knotHash( Assembly( addTail(input.map { it.toInt() }), 256, 64 ) ) ).joinToString(separator = "") { it.formattedHexadecimal(2) } } fun main(args: Array<String>) { inputs.forEach { input -> val list = knotHash(input) println(list) println(list[0] * list[1]) } println(hexHash(more.Input.getFor("p10"))) }
6
Kotlin
0
0
d5c38e55b9574137ed6b351a64f80d764e7e61a9
1,663
adventofcode
The Unlicense
src/Day01.kt
xuejingao
573,076,407
false
null
import java.util.Collections import java.util.PriorityQueue import kotlin.math.max fun main() { fun part1(input: List<String>): Int { var mostCalories = 0 var currentCount = 0 for (calorie in input) { currentCount = if (calorie.isBlank()) 0 else currentCount + calorie.toInt() mostCalories = max(mostCalories, currentCount) } return mostCalories } fun part2(input: List<String>): Int { val maxheap = PriorityQueue<Int>(Collections.reverseOrder()) var currentCount = 0 for (calorie in input) { currentCount = if (calorie.isBlank()) { maxheap.add(currentCount) 0 } else currentCount + calorie.toInt() } maxheap.add(currentCount) // For the Last Element var top3Sum = 0 for ( i in 1..3) { top3Sum += maxheap.remove() } return top3Sum } // 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("Part 1:" + part1(input)) println("Part 2:" + part2(input)) }
0
Kotlin
0
0
e438c3527ff7c69c13985dcd7c55145336d4f9ca
1,265
aoc-kotlin-2022
Apache License 2.0
app/src/main/java/org/simple/clinic/patient/filter/SortByWeightedNameParts.kt
eco4ndly
244,967,563
true
{"Kotlin": 3192656, "Java": 8206, "Shell": 2340}
package org.simple.clinic.patient.filter import kotlin.math.max /** * This is a comparator that is used to sort [PatientSearchContext] objects by prioritizing matches * which have the same number of words as the search term while still providing good * results when the search term and the name do not have the same number of words. * * It works by generating an overall score for a match based on a weighted function that * multiples the edit distance for a particular part with a multiplier which is decided * based on the position of the term in the word. * * Variations in words are penalized in a progressively decreasing manner from left to * right. Names with more matching words get a better score. **/ class SortByWeightedNameParts : Comparator<PatientSearchContext> { override fun compare(first: PatientSearchContext, second: PatientSearchContext): Int { val scoreOfFirst = computeScore(first) val scoreOfSecond = computeScore(second) return scoreOfFirst.compareTo(scoreOfSecond) } private fun computeScore(searchInfo: PatientSearchContext): Double { val maximumWordParts = max(searchInfo.nameParts.size, searchInfo.searchParts.size) // Generate decreasing multipliers based on the position of the // term. i.e, if the maximum number of parts is 3, the multipliers are // 3, 2, 1 for positions 0, 1, 2 respectively. val penaltiesForPositions: List<Int> = (1..maximumWordParts).map { it }.reversed() // Generate weighted scores for each position by assigning a default value, // one divided by the max parts in this case, and multiplying that value with // the position multipliers generated previously. val triedAndTestedArbitraryValue = 1 / maximumWordParts.toDouble() val positionBasedDefaultWeights = penaltiesForPositions.map { penalty -> penalty * triedAndTestedArbitraryValue } val editDistances = searchInfo.editDistances.map { it.editDistance } return positionBasedDefaultWeights .mapIndexed { index, weightedScore -> weightedScore * editDistances.getOrElse(index) { 1.0 } } .sum() } }
0
null
1
1
c0bb3139dada4f34206928ec81f1e5f6f056134b
2,126
simple-android
MIT License
src/Day06.kt
bananer
434,885,332
false
{"Kotlin": 36979}
fun main() { fun fishGrowth(input: List<String>, days: Int): Long { var state = mutableMapOf<Int, Long>() (0..8).forEach { state[it] = 0 } input[0].split(",") .map { it.toInt() } .forEach { state.compute(it) { _, count -> count!! + 1 } } (0 until days).forEach { _ -> val newState = mutableMapOf<Int, Long>() newState[8] = state[0]!! (7 downTo 0).forEach { newState[it] = state[it + 1]!! } newState[6] = newState[6]!! + state[0]!! state = newState } return state.values.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") val testOutput1 = fishGrowth(testInput, 80) println("test output1: $testOutput1") check(testOutput1 == 5934L) val testOutput2 = fishGrowth(testInput, 256) println("test output2: $testOutput2") check(testOutput2 == 26984457539) val input = readInput("Day06") println("output part1: ${fishGrowth(input, 80)}") println("output part2: ${fishGrowth(input, 256)}") }
0
Kotlin
0
0
98f7d6b3dd9eefebef5fa3179ca331fef5ed975b
1,197
advent-of-code-2021
Apache License 2.0
src/com/kingsleyadio/adventofcode/y2023/Day01.kt
kingsleyadio
435,430,807
false
{"Kotlin": 134666, "JavaScript": 5423}
package com.kingsleyadio.adventofcode.y2023 import com.kingsleyadio.adventofcode.util.readInput fun main() { part1() part2() } private fun part1() { var sum = 0 readInput(2023, 1).forEachLine { line -> val first = line.first { it.isDigit() }.digitToInt() val last = line.last { it.isDigit() }.digitToInt() sum += first * 10 + last } println(sum) } private fun part2() { var sum = 0 readInput(2023, 1).forEachLine { line -> val first = findNumber(line, reversed = false) val last = findNumber(line, reversed = true) sum += first * 10 + last } println(sum) } private val NUMBERS = listOf("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine") private fun findNumber(line: String, reversed: Boolean): Int { val progression = line.indices.run { if (reversed) reversed() else this } for (i in progression) { val char = line[i] if (char.isDigit()) return char.digitToInt() NUMBERS.forEachIndexed { index, num -> if (line.startsWith(num, i)) return index } } error("Not found") }
0
Kotlin
0
1
9abda490a7b4e3d9e6113a0d99d4695fcfb36422
1,131
adventofcode
Apache License 2.0
src/test/kotlin/ch/ranil/aoc/aoc2022/Day15.kt
stravag
572,872,641
false
{"Kotlin": 234222}
package ch.ranil.aoc.aoc2022 import ch.ranil.aoc.AbstractDay import org.junit.jupiter.api.Test import kotlin.math.abs import kotlin.math.max import kotlin.math.min import kotlin.test.assertEquals object Day15 : AbstractDay() { @Test fun part1Test() { assertEquals(26, compute1(testInput, 10)) } @Test fun part1() { assertEquals(5394423, compute1(puzzleInput, 2000000)) } @Test fun part2Test() { assertEquals(56000011L, compute2(testInput, 20)) } @Test fun part2() { assertEquals(11840879211051L, compute2(puzzleInput, 4000000)) } private fun compute1(input: List<String>, row: Int): Int { return parse(input).noBeaconsPositions(row).count() } private fun compute2(input: List<String>, space: Int): Long { val beacon = parse(input).findBeacon(space) return beacon.x * 4000000L + beacon.y } private fun parse(input: List<String>): Map { val regex = "Sensor at x=([\\-0-9]+), y=([\\-0-9]+): closest beacon is at x=([\\-0-9]+), y=([\\-0-9]+)" .toRegex() val pairs = input.map { val matches = regex.find(it) ?: throw IllegalArgumentException("Unexpected input: $it") val sX = matches.groupValues[1].toInt() val sY = matches.groupValues[2].toInt() val bX = matches.groupValues[3].toInt() val bY = matches.groupValues[4].toInt() Signal(P(sX, sY), P(bX, bY)) } return Map(pairs) } data class Signal(val s: P, val b: P) { fun noBeaconPoints(row: Int): List<P> { val searchRadius = searchRadius(this) val yDiffToRow = abs(row - s.y) return if (yDiffToRow > searchRadius) { emptyList() } else { val xDiffOnRow = abs(searchRadius - yDiffToRow) val xRangeOnRow = (s.x - xDiffOnRow)..(s.x + xDiffOnRow) val pointsOnRow = xRangeOnRow.map { x -> P(x, row) } pointsOnRow - s - b } } } fun searchRadius(signal: Signal) = searchRadius(signal.s, signal.b) fun searchRadius(p1: P, p2: P) = abs(p1.x - p2.x) + abs(p1.y - p2.y) data class P(val x: Int, val y: Int) class Map( private val pairs: List<Signal>, ) { fun noBeaconsPositions(row: Int): Set<P> { return pairs .fold(mutableSetOf()) { acc, it -> acc.addAll(it.noBeaconPoints(row)) acc } } fun findBeacon(space: Int): P { pairs.forEach { pair -> val sensor = pair.s val radius = searchRadius(pair) val xEdgeLeft = max(0, sensor.x - radius - 1) val xEdgeRight = min(space, sensor.x + radius + 1) for (x in xEdgeLeft..xEdgeRight) { val diffX = abs(x - sensor.x) val yEdgeTop = max(0, min(space, sensor.y - (radius - diffX) - 1)) val yEdgeBottom = max(0, min(space, sensor.y + (radius - diffX) + 1)) listOf(yEdgeTop, yEdgeBottom).forEach { y -> val possibleBeacon = P(x, y) val notInRanges = pairs.none { otherPair -> val otherSensor = otherPair.s val otherRadius = searchRadius(otherPair) searchRadius(possibleBeacon, otherSensor) <= otherRadius } if (notInRanges) return possibleBeacon } } } throw IllegalArgumentException("Couldn't find beacon") } } }
0
Kotlin
1
0
dbd25877071cbb015f8da161afb30cf1968249a8
3,768
aoc
Apache License 2.0
src/main/kotlin/leetcode/kotlin/dp/63. Unique Paths II.kt
sandeep549
251,593,168
false
null
package leetcode.kotlin.dp fun main() { println( uniquePathsWithObstacles2( arrayOf( intArrayOf(0, 0, 0), intArrayOf(0, 1, 0), intArrayOf(0, 0, 0) ) ) ) } /** * dp, top-down * f(r,c) = f(r,c-1) + f(r-1, c) * f(r,c) = no of ways to reach at location (r,c) * f(r,c-1) = no of ways to reach at location (r,c-1), i.e. from left side * f(r-1,c) = no of ways to reach at location (r-1,c), i.e. from up side */ private fun uniquePathsWithObstacles(m: Array<IntArray>): Int { var dp = Array(m.size) { IntArray(m.first().size) { 0 } } fun waystoReach(r: Int, c: Int): Int { // finds no of ways to reach at location (r, c) if (r < 0 || c < 0 || m[r][c] == 1) return 0 if (r == 0 && c == 0) return 1 // we reach at origin, base case if (dp[r][c] == 0) dp[r][c] = waystoReach(r, c - 1) + waystoReach(r - 1, c) return dp[r][c] } return waystoReach(m.size - 1, m.first().size - 1) } // dp, bottom-up private fun uniquePathsWithObstacles2(m: Array<IntArray>): Int { fun ways(r: Int, c: Int): Int = if (r < 0 || c < 0) 0 else m[r][c] for (r in m.indices) { for (c in m.first().indices) { if (r == 0 && c == 0 && m[r][c] == 0) m[r][c] = 1 else m[r][c] = if (m[r][c] == 0) ways(r - 1, c) + ways(r, c - 1) else 0 } } return m[m.size - 1][m.first().size - 1] }
0
Kotlin
0
0
9cf6b013e21d0874ec9a6ffed4ae47d71b0b6c7b
1,450
kotlinmaster
Apache License 2.0
src/main/kotlin/com/jaspervanmerle/aoc2021/day/Day13.kt
jmerle
434,010,865
false
{"Kotlin": 60581}
package com.jaspervanmerle.aoc2021.day class Day13 : Day("765", "RZKZLPGH") { private data class Dot(val x: Int, val y: Int) private enum class FoldDirection { UP, LEFT } private data class Fold(val direction: FoldDirection, val location: Int) private val dots = input .split("\n\n")[0] .lines() .map { it.split(",") } .map { Dot(it[0].toInt(), it[1].toInt()) } private val folds = input .split("\n\n")[1] .lines() .map { it.split("=") } .map { Fold(if (it[0].endsWith('y')) FoldDirection.UP else FoldDirection.LEFT, it[1].toInt()) } override fun solvePartOne(): Any { return getDotsAfterFolds(folds.take(1)).size } override fun solvePartTwo(): Any { val finalDots = getDotsAfterFolds(folds) val minX = finalDots.minOf { it.x } val maxX = finalDots.maxOf { it.x } val minY = finalDots.minOf { it.y } val maxY = finalDots.maxOf { it.y } for (y in minY..maxY) { for (x in minX..maxX) { if (finalDots.any { it.x == x && it.y == y }) { print('#') } else { print(' ') } } println() } return "RZKZLPGH" } private fun getDotsAfterFolds(foldsToApply: List<Fold>): List<Dot> { var currentDots = dots for (fold in foldsToApply) { currentDots = currentDots.map { if (fold.direction == FoldDirection.UP) { if (it.y < fold.location) { it } else { Dot(it.x, fold.location - (it.y - fold.location)) } } else { if (it.x < fold.location) { it } else { Dot(fold.location - (it.x - fold.location), it.y) } } }.distinct() } return currentDots } }
0
Kotlin
0
0
dcac2ac9121f9bfacf07b160e8bd03a7c6732e4e
2,063
advent-of-code-2021
MIT License
day01.kt
kannix68
430,389,568
false
{"Jupyter Notebook": 82946, "Python": 17016, "Kotlin": 1365}
/** * Advent of Code 2021 Day 1 solution. * This is currently a fairly minimalistic code. */ import java.io.File val testin = """ 199 200 208 210 200 207 240 269 260 263 """.trimIndent() /** * Get diff of List "as series", first element will be null. */ private fun diff(ints: List<Int>): List<Int?> { val diffs = ints.mapIndexed { idx, elem -> if (idx == 0) null else elem - ints[idx - 1] } return diffs } private fun getIncsCount(inp: String): Int { //val ints = listOf(1, 2, 3, 2, 1) val ints = inp.split("\n").map { it.toInt() }; val diffs = diff(ints) val incs = diffs.filterNotNull().filter { it > 0 }.size //println(ints) //println(diffs) return incs } private fun getIncs3Count(inp: String): Int { //val ints = listOf(1, 2, 3, 2, 1) var ints = inp.split("\n").map{ it.toInt() }; //println(ints.windowed(3)) //println(ints.windowed(3).map{it.sum()}) ints = ints.windowed(3).map{it.sum()} val diffs = diff(ints) val incs = diffs.filterNotNull().filter{ it > 0 }.size //println(ints) //println(diffs) return incs } fun main(args: Array<String>){ var incs = getIncsCount(testin) println("rc=$incs") val inp = File("./in/day01.in").readText().trim() incs = getIncsCount(inp) println("rc=$incs") incs = getIncs3Count(testin) println("rc=$incs") incs = getIncs3Count(inp) println("rc=$incs") }
0
Jupyter Notebook
0
0
fc9889457caaa2c3d1a7b32f5a6f69cc70293adb
1,365
advent_of_code_2021
MIT License
2022/src/Day15.kt
Saydemr
573,086,273
false
{"Kotlin": 35583, "Python": 3913}
package src import kotlin.math.abs val manhattanDistance = { x1 :Long, y1: Long, x2: Long, y2: Long -> abs(x1 - x2) + abs(y1 - y2) } fun main() { val row = 2_000_000L val banned = mutableSetOf<Pair<Long,Long>>() val beacons = mutableSetOf<Pair<Long,Long>>() val sensorBeaconList = readInput("input15") .map { it.trim().split("x=", "y=", " ", ",", ":") } .map { it.filter { it2 -> it2.trim(); val regex = "-?[0-9]+(\\.[0-9]+)?".toRegex(); regex.matches(it2) } } .map { ; it.map { it2 -> it2.toLong() } } .map { val cDistance = manhattanDistance(it[0], it[1], it[2], it[3]) beacons.add(Pair(it[2],it[3])) val yDiff = abs(row - it[1]) val leftRightSpan = abs(cDistance - yDiff) // it0 x1, it1 y1, // it2 x2, it3 y2 if ( cDistance >= yDiff) { banned.addAll((it[0] - leftRightSpan ..it[0] + leftRightSpan) .map { it2 -> Pair(it2, row) }) } it// yeah man I'm just gonna leave this here. Best coding practice ever. } banned.removeAll(beacons) // println(banned.size) // part2 // just more badder KEKW val pointsToCheck = mutableSetOf<Pair<Long,Long>>() sensorBeaconList.map { Triple(it[0], it[1], manhattanDistance(it[0], it[1], it[2], it[3])) } .forEach{ val xPlus = it.first + it.third val xMinus = it.first - it.third val yPlus = it.second + it.third val yMinus = it.second - it.third // from topTop to leftLeft val allX = (xMinus - 1 .. it.first).toList() val allY = (it.second .. yPlus + 1).toList() // zip them together val beforeCheck = allX.zip(allY).filter { point -> val values = sensorBeaconList.map { it2 -> Triple(it2[0], it2[1], manhattanDistance(it2[0], it2[1], it2[2], it2[3])) }; values.filter { it3 -> manhattanDistance(it3.first, it3.second, point.first, point.second) == it3.third + 1 }.size > 3 && point.first in 0L..4_000_000L && point.second in 0L..4_000_000L } pointsToCheck.addAll(beforeCheck) val allX2 = (it.first .. xPlus + 1).toList() val allY2 = (it.second .. yPlus + 1).toList() // zip them together val beforeCheck2 = allX2.zip(allY2).filter { point -> val values = sensorBeaconList.map { it2 -> Triple(it2[0], it2[1], manhattanDistance(it2[0], it2[1], it2[2], it2[3])) }; values.filter { it3 -> manhattanDistance(it3.first, it3.second, point.first, point.second) == it3.third + 1 }.size > 3 && point.first in 0L..4_000_000L && point.second in 0L..4_000_000L } pointsToCheck.addAll(beforeCheck2) // from bottomBottom to leftLeft val allX3 = (xMinus - 1 .. it.first).toList() val allY3 = (yMinus - 1 .. it.second).toList() // zip them together val beforeCheck3 = allX3.zip(allY3).filter { point -> val values = sensorBeaconList.map { it2 -> Triple(it2[0], it2[1], manhattanDistance(it2[0], it2[1], it2[2], it2[3])) }; values.filter { it3 -> manhattanDistance(it3.first, it3.second, point.first, point.second) == it3.third + 1 }.size > 3 && point.first in 0L..4_000_000L && point.second in 0L..4_000_000L } pointsToCheck.addAll(beforeCheck3) // from bottomBottom to rightRight val allX4 = (it.first .. xPlus + 1).toList() val allY4 = (yMinus - 1 .. it.second).toList() // zip them together val beforeCheck4 = allX4.zip(allY4).filter { point -> val values = sensorBeaconList.map { it2 -> Triple(it2[0], it2[1], manhattanDistance(it2[0], it2[1], it2[2], it2[3])) }; values.filter { it3 -> manhattanDistance(it3.first, it3.second, point.first, point.second) == it3.third + 1 }.size > 3 && point.first in 0L..4_000_000L && point.second in 0L..4_000_000L } pointsToCheck.addAll(beforeCheck4) } pointsToCheck.forEach { println(it.first * 4_000_000L + it.second) } /** * This is hilarious. I'm just gonna leave this here. I will update this after the competition is over. */ }
0
Kotlin
0
1
25b287d90d70951093391e7dcd148ab5174a6fbc
4,585
AoC
Apache License 2.0
src/main/kotlin/com/jacobhyphenated/advent2023/day13/Day13.kt
jacobhyphenated
725,928,124
false
{"Kotlin": 121644}
package com.jacobhyphenated.advent2023.day13 import com.jacobhyphenated.advent2023.Day import kotlin.math.min /** * Day 13: Point of Incidence * * The puzzle input is a grid of rocks and empty spaces. * But a mirror reflects the rocks. The reelection point can be * along a row or a column. If the reflection goes off the edge of the rock formation, * a row/col might not have a corresponding reflected row/col (reflections do not need to be in the middle) */ class Day13: Day<List<List<List<Char>>>> { override fun getInput(): List<List<List<Char>>> { return readInputFile("13").split("\n\n").map { rocks -> rocks.lines().map { it.toCharArray().toList() } } } /** * Part 1: count the rows above a horizontal reflection and multiply by 100 * or count the number of columns to the left of a vertical reflection line. * return the sum for each rock formation */ override fun part1(input: List<List<List<Char>>>): Int { return input.sumOf { calculateRockMirrorReflection(it)!! } } /** * Part 2: There is actually a smudge on the mirror. * A single space is actually a reverse character. * * Find the new score created by the only possible smudged space that creates a new reflection. * The old reflection may or may not still be valid, but only use the new reflection */ override fun part2(input: List<List<List<Char>>>): Int { return input.sumOf { findSmudge(it) } } /** * Brute force. Try each and every space in the grid. * Change the value and see if that gives a new reflection point */ private fun findSmudge(rocks: List<List<Char>>): Int { val originalScore = calculateRockMirrorReflection(rocks) for (r in rocks.indices) { for (c in rocks[r].indices) { val smudge = rocks.toMutableList().map { it.toMutableList() } smudge[r][c] = when(smudge[r][c]) { '.' -> '#' '#' -> '.' else -> throw IllegalArgumentException("weird rock") } val score = calculateRockMirrorReflection(smudge, originalScore!!) if (score != null && score != originalScore) { return score } } } return 0 } /** * Find the reflection point. First go down the rows, then go down the columns. * Stop once we've found a valid reflection * * @param exclude is used for part 2. If we find a reflection with the same score as [exclude] * then continue searching until we find a different reflection */ private fun calculateRockMirrorReflection(rocks: List<List<Char>>, exclude: Int = 0): Int? { reflectionPoint@ for (r in (1 until rocks.size)) { val toEnd = rocks.size - 1 - r val toBeginning = r - 1 for (distance in 0..min(toEnd, toBeginning)) { if (rocks[r - 1 - distance] != rocks[r + distance]) { continue@reflectionPoint } } if(r * 100 != exclude) { return r * 100 } } reflectionPointC@ for (c in 1 until rocks[0].size) { val toEnd = rocks[0].size - 1 - c val toBeginning = c - 1 for (distance in 0 .. min(toEnd, toBeginning)) { if (rocks.map { row -> row[c - 1 - distance] } != rocks.map { row -> row[c + distance] }){ continue@reflectionPointC } } if (c != exclude) { return c } } return null } override fun warmup(input: List<List<List<Char>>>) { part2(input) } } fun main(@Suppress("UNUSED_PARAMETER") args: Array<String>) { Day13().run() }
0
Kotlin
0
0
90d8a95bf35cae5a88e8daf2cfc062a104fe08c1
3,521
advent2023
The Unlicense
src/main/kotlin/day10.kt
Arch-vile
572,557,390
false
{"Kotlin": 132454}
package day10 import aoc.utils.* fun part1(): Int { val valueByCycle = valuesByCycle("day10-input.txt") return (20..220).step(40) .map { valueByCycle[it - 1] } .sumOf { value -> value.first * value.second } } fun part2(): String { val valuesByCycle = valuesByCycle("day10-input.txt") var crt = "" valuesByCycle.map { it.second }.forEachIndexed { i, value -> if (closedRange(value - 1, value + 1).contains(i % 40)) { crt += "#" } else crt += "." } return crt.windowed(40, 40).joinToString("") { "$it\n" } } private fun valuesByCycle(file: String): List<Pair<Int, Int>> { var registerX = MutableInt(1) // Try with reduce also val registerValues = readInput(file).flatMap { if (it.firstPart() == "noop") { listOf(registerX.value) } else { listOf( registerX.value, registerX.plus(it.secondAsInt()) ) } } return listOf(Pair(1, 1)) + registerValues.mapIndexed { index, value -> Pair(index + 2, value) } }
0
Kotlin
0
0
e737bf3112e97b2221403fef6f77e994f331b7e9
1,074
adventOfCode2022
Apache License 2.0
2021/src/day04/day04.kt
scrubskip
160,313,272
false
{"Kotlin": 198319, "Python": 114888, "Dart": 86314}
package day04 import java.io.File fun main() { val input = File("src/day04","/day4input.txt").bufferedReader() // Numbers val numbers: List<Int> = input.readLine().split(",").map {it.toInt()} input.readLine() // Now get the boards var boards: List<BingoBoard> = input.readLines() .windowed(5, 6) .map{ BingoBoard.from(it) } var result: Pair<Set<Int>, BingoBoard>? = runGame(numbers, boards) if (result != null) { println(result.second.getUnmarkedValue(result.first) * result.first.last()) } result = runLosingGame(numbers,boards) if (result != null) { println(result.second.getUnmarkedValue(result.first) * result.first.last()) } } fun runGame(numbers: List<Int>, boards: List<BingoBoard>) : Pair<Set<Int>, BingoBoard>? { var numbersSeen : MutableSet<Int> = mutableSetOf() for (value in numbers) { numbersSeen.add(value) for (board in boards) { if (board.checkBingo(value, numbersSeen)) { return Pair(numbersSeen, board) } } } return null } fun runLosingGame(numbers: List<Int>, boards: List<BingoBoard>) : Pair<Set<Int>, BingoBoard> { var numbersSeen : MutableSet<Int> = mutableSetOf() var boardsWon: MutableSet<BingoBoard> = mutableSetOf() for (value in numbers) { numbersSeen.add(value) for (board in boards.filterNot { boardsWon.contains(it) }) { if (board.checkBingo(value, numbersSeen)) { boardsWon.add(board) } } if (boardsWon.size == boards.size) { break } } return Pair(numbersSeen, boardsWon.last()) } data class BingoBoard(val board: Array<IntArray>) { companion object { fun from(rows: List<String>) : BingoBoard { return BingoBoard(rows.map { row -> row.trim().split("\\s+".toRegex()).map {it.toInt() }.toIntArray()}.toTypedArray()) } } /** * Checks a given board for a bingo. * Find the number in the board. If it's there, check the row and col against the previously seen value * @return true if this board is a bingo */ fun checkBingo(newValue: Int, seenValues: Set<Int>): Boolean { for (rowIndex in board.indices) { for (colIndex in board[rowIndex].indices) { if (board[rowIndex][colIndex] == newValue) { return board[rowIndex].all { value -> seenValues.contains(value) } || board.all { row -> seenValues.contains( row.getOrNull(colIndex) ) } } } } return false } fun getUnmarkedValue(seenValues: Set<Int>) : Int { return board.fold(0) { acc, ints -> acc + ints.filterNot { element -> seenValues.contains(element) }.sum() } } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as BingoBoard if (!board.contentDeepEquals(other.board)) return false return true } override fun hashCode(): Int { return board.contentDeepHashCode() } }
0
Kotlin
0
0
a5b7f69b43ad02b9356d19c15ce478866e6c38a1
3,294
adventofcode
Apache License 2.0
src/main/kotlin/org/example/adventofcode/puzzle/Day02.kt
wcchristian
712,668,434
false
{"Kotlin": 5484}
package org.example.adventofcode.puzzle import org.example.adventofcode.util.FileLoader object Day02 { /* ---------- PARTS ---------- */ fun part1(filePath: String): Int { val fileLines = FileLoader.loadFromFile<String>(filePath) return fileLines .map { parseGameFromString(it) } .filter { isGamePossible(it) } .sumOf { it.id } } fun part2(filePath: String): Int { val fileLines = FileLoader.loadFromFile<String>(filePath) return fileLines .map { parseGameFromString(it) } .map { findMinCubeCountToMakeGamePossible(it) } .sumOf { it.blue * it.red * it.green } } /* ---------- FUNCTIONS ---------- */ private fun parseGameFromString(line: String): Game { return Game( id = Regex("Game (\\d*):").find(line)!!.groupValues[1].toInt(), cubeCounts = line.split(";").map { handString -> CubeCount( blue = Regex("(\\d*) blue").find(handString)?.groupValues?.get(1)?.toInt() ?: 0, red = Regex("(\\d*) red").find(handString)?.groupValues?.get(1)?.toInt() ?: 0, green = Regex("(\\d*) green").find(handString)?.groupValues?.get(1)?.toInt() ?: 0, ) } ) } private fun isGamePossible(game: Game): Boolean { game.cubeCounts.forEach { if(it.blue > 14 || it.green > 13 || it.red > 12) { return false } } return true } private fun findMinCubeCountToMakeGamePossible(game: Game): CubeCount { val cubeCount = CubeCount(red = 0, blue = 0, green = 0) game.cubeCounts.forEach { if (it.red >= cubeCount.red) cubeCount.red = it.red if (it.blue >= cubeCount.blue) cubeCount.blue = it.blue if (it.green >= cubeCount.green) cubeCount.green = it.green } return cubeCount } /* ---------- DATA STRUCTURES ---------- */ data class Game( val id: Int, val cubeCounts: List<CubeCount> ) data class CubeCount( var blue: Int = 0, var red: Int = 0, var green: Int = 0 ) } /* ---------- MAIN ---------- */ fun main() { println("Part 1 example solution is: ${Day02.part1("/day02_example.txt")}") println("Part 1 main solution is: ${Day02.part1("/day02.txt")}") println("Part 2 example solution is: ${Day02.part2("/day02_example.txt")}") println("Part 2 main solution is: ${Day02.part2("/day02.txt")}") }
0
Kotlin
0
0
8485b440dcd10b0399acbe9d6ae3ee9cf7f4d6ae
2,574
advent-of-code-2023
MIT License
howto-dapp/src/main/java/de/timolia/howto/rank/RankConversion.kt
TimoliaDE
579,343,701
false
{"Kotlin": 45480, "Dockerfile": 956}
package de.timolia.howto.rank import java.util.* import java.util.function.Function import java.util.stream.Collectors object RankConversion { fun getRank(text: String): Rank? { return Arrays.stream(Rank.values()) .collect(Collectors.toMap(Function.identity()) { rank -> getSimilarity(text, rank.getFemale()).coerceAtLeast(getSimilarity(text, rank.male)) }) .entries .stream() .max(Comparator.comparingDouble { (_, value) -> value }) .filter { e -> e.value > 0.1 } .map { (key, _) -> key } .orElse(null) } /** * Calculates the similarity (a number within 0 and 1) between two strings. */ private fun getSimilarity(s1: String, s2: String): Double { var longer = s1 var shorter = s2 if (s1.length < s2.length) { // longer should always have greater length longer = s2 shorter = s1 } val longerLength = longer.length return if (longerLength == 0) { 1.0 /* both strings are zero length */ } else (longerLength - editDistance(longer, shorter)) / longerLength.toDouble() } // Example implementation of the Levenshtein Edit Distance // See http://rosettacode.org/wiki/Levenshtein_distance#Java private fun editDistance(s1: String, s2: String): Int { var s1 = s1 var s2 = s2 s1 = s1.lowercase(Locale.getDefault()) s2 = s2.lowercase(Locale.getDefault()) val costs = IntArray(s2.length + 1) for (i in 0..s1.length) { var lastValue = i for (j in 0..s2.length) { if (i == 0) costs[j] = j else { if (j > 0) { var newValue = costs[j - 1] if (s1[i - 1] != s2[j - 1]) newValue = newValue.coerceAtMost(lastValue).coerceAtMost(costs[j]) + 1 costs[j - 1] = lastValue lastValue = newValue } } } if (i > 0) costs[s2.length] = lastValue } return costs[s2.length] } }
3
Kotlin
7
0
212eadc654159f6001c01ac2e1669346af9e86b2
2,187
HowTo
MIT License
leetcode/regular-expression-matching/main.kt
seirion
17,619,607
false
{"C++": 801740, "HTML": 42242, "Kotlin": 37689, "Python": 21759, "C": 3798, "JavaScript": 294}
// https://leetcode.com/problems/regular-expression-matching class Solution { fun isMatch(s: String, p: String): Boolean { return isMatch(s, 0, p, 0) } private fun isMatch(s: String, sIndex: Int, p: String, pIndex: Int): Boolean { if (s.length == sIndex && p.length == pIndex) return true if (p.length == pIndex) return false val star = (pIndex + 1 < p.length && p[pIndex + 1] == '*') if (star) { if (p[pIndex] == '.') { return (sIndex .. s.length).any { isMatch(s, it, p, pIndex + 2) } } else { return (sIndex .. s.length) .takeWhile { it == sIndex || s[it - 1] == p[pIndex] } .any { isMatch(s, it, p, pIndex + 2) } } } else { if (s.length == sIndex) return false if (p[pIndex] == '.' || s[sIndex] == p[pIndex]) { return isMatch(s, sIndex + 1, p, pIndex + 1) } } return false } } fun main(args: Array<String>) { println(Solution().isMatch("aa", "a")) // false println(Solution().isMatch("aa", "a*")) // true println(Solution().isMatch("ab", ".*")) // true println(Solution().isMatch("aab", "c*a*b")) // true println(Solution().isMatch("mississippi", "mis*is*p*.")) // false println(Solution().isMatch("ab", ".*c")) // false }
0
C++
4
4
a59df98712c7eeceabc98f6535f7814d3a1c2c9f
1,544
code
Apache License 2.0
2016/main/day_04/Main.kt
Bluesy1
572,214,020
false
{"Rust": 280861, "Kotlin": 94178, "Shell": 996}
package day_04_2016 import java.io.File fun part1(input: List<String>) { input.stream().mapToInt { val chars = it.substringBeforeLast("[") .split("-") .dropLast(1) .joinToString("") val sectorId = it.substringBeforeLast("[") .split("-") .last() .toInt() val checksum = it.substringAfterLast("[") .substringBeforeLast("]") val charCount = chars.groupingBy { it1 -> it1 } .eachCount() .toSortedMap() var flag = true for (i in 0 until 5){ val max = charCount.maxBy { it2 -> it2.value } if (max.key !in checksum) { flag = false break } charCount.remove(max.key) } if (flag) sectorId else 0 }.sum().let { print("The sum of valid sector IDs is $it") } } fun part2(input: List<String>) { input.stream().map { val chars = it.substringBeforeLast("[") .split("-") .dropLast(1) .joinToString("") val sectorId = it.substringBeforeLast("[") .split("-") .last() .toInt() val checksum = it.substringAfterLast("[") .substringBeforeLast("]") val charCount = chars.groupingBy { it1 -> it1 } .eachCount() .toSortedMap() var flag = true for (i in 0 until 5){ val max = charCount.maxBy { it2 -> it2.value } if (max.key !in checksum) { flag = false break } charCount.remove(max.key) } if (flag) { val encryptedName = it.substringBeforeLast("[") .split("-") .dropLast(1) .joinToString(" ") encryptedName.toCharArray().map { it1 -> if (it1 == ' ') ' ' else (((it1.code + sectorId - 'a'.code) % 26) + 'a'.code).toChar() }.joinToString("") to sectorId } else Pair("", 0) } .filter { it.first == "northpole object storage" } .findFirst() .let { print("The sector ID of the room where North Pole objects are stored is ${it.get().second}") } } fun main(){ val inputFile = File("2016/inputs/Day_04.txt") print("\n----- Part 1 -----\n") part1(inputFile.readLines()) print("\n----- Part 2 -----\n") part2(inputFile.readLines()) }
0
Rust
0
0
537497bdb2fc0c75f7281186abe52985b600cbfb
2,484
AdventofCode
MIT License
src/net/sheltem/aoc/y2023/Day21.kt
jtheegarten
572,901,679
false
{"Kotlin": 178521}
package net.sheltem.aoc.y2023 import net.sheltem.common.PositionInt import net.sheltem.common.neighbours suspend fun main() { Day21().run() } class Day21 : Day<Long>(2665, 394693535848011) { override suspend fun part1(input: List<String>): Long = input.steps(64) override suspend fun part2(input: List<String>): Long = input.steps2(26501365) } private fun List<String>.steps(repeats: Int): Long { var positions = setOf(mapIndexedNotNull { index, line -> if (line.contains("S")) line.indexOf("S") to index else null }.first()) repeat(repeats) { positions = calculateNewPositions(positions) } return positions.count().toLong() } private fun List<String>.calculateNewPositions(positions: Set<Pair<Int, Int>>): Set<PositionInt> { return positions.flatMap { position -> position .neighbours() .toSet() .filter { this[((it.second % this.size) + this.size) % this.size][((it.first % this.size) + this.size) % this.size] != '#' } }.toSet() } private fun List<String>.steps2(repeats: Long): Long { var positions = setOf(mapIndexedNotNull { index, line -> if (line.contains("S")) line.indexOf("S") to index else null }.first()) val grids = repeats / size val remainder = repeats % size val counts = mutableListOf<Int>() var steps = 0L // Because the grid is a square and the S line and column are free, we can expect a quadratic result (ax^2 + bx + c): // grids * repeats + remainder = steps => remainder + (remainder + gridsize) + (remainder + 2 * gridsize) + ... // We get the first three steps the old way... for (i in 0..2) { while (steps < ((i * size) + remainder)) { positions = calculateNewPositions(positions) steps++ } counts.add(positions.size) } // ... then calculate a, b and c from them val c = counts[0] val aPlusB = counts[1] - c val twoA = counts[2] - c - (2 * aPlusB) val a = twoA / 2 val b = aPlusB - a return a * (grids * grids) + b * grids + c } //this@steps.forEachIndexed { y, line -> // line.forEachIndexed { x, char -> // if (positions.contains(x to y)) print('O') else print(char) // } // println() //}
0
Kotlin
0
0
ac280f156c284c23565fba5810483dd1cd8a931f
2,242
aoc
Apache License 2.0
src/main/aoc2015/Day19.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2015 import MutableMultiMap class Day19(input: List<String>) { private val molecule = parseMolecule(input.last()) private val replacements = parseReplacements(input) private fun parseReplacements(input: List<String>) = input.dropLast(2) .map { line -> line.split(" => ").let { it.first() to it.last() } }.let { replacements -> MutableMultiMap<String, String>().apply { replacements.forEach { add(it.first, it.second) } } } private fun parseMolecule(molecule: String): List<String> { val atoms = mutableListOf<String>() var curr = "" var i = 0 do { curr += molecule[i] if (i + 1 == molecule.length || molecule[i + 1].isUpperCase()) { atoms.add(curr) curr = "" } } while (++i < molecule.length) return atoms } private fun calibrate(): Int { val distinct = mutableSetOf<String>() for (i in molecule.indices) { replacements[molecule[i]]?.let { substituteList -> for (substitute in substituteList) { val current = molecule.mapIndexed { index, s -> if (index == i) { substitute } else { s } }.joinToString("") distinct.add(current) } } } return distinct.size } private fun fabricate(): Int { // There is no need to actually create the molecule, all that's needed is to know how many combinations // are required to create the molecule. We can safely assume that it is possible to find a way to // generate the molecule somehow. // // If carefully looking at the input it's possible to see that there are a couple of different kinds // of combinations: // 1. X ==> ** // 2. X ==> *Rn*Ar // 3. X ==> *Rn*Y*Ar // 4. X ==> *Rn*Y*Y*Ar // (note: this only work with the actual puzzle input and not the test examples since the examples // have different kinds of rules like X ==> *) // Starting with the target molecule and running the correct combinations backward would finally // end up with a molecule containing only 'e'. // // Combination 1. reduces two atoms into one per iteration, so amount of required steps // are molecule.length - 1 // // Combination 2. also reduces two atoms into one with the addition that it also removes both // Rn and Ar. So amount of steps are molecule.length - count(Rn, Ar) - 1 // // Combination 3. and 4. are similar to combination 2 but with the addition that it also removes the // Y and one additional atom. So amount of steps are molecule.length - count(Rn, Ar) - 2 * count(Y) - 1 // The final generic formula can be used on all types of molecules and calculates the amount of steps // needed to create that molecule without exactly knowing which exact steps are needed. return molecule.size - molecule.count { it in listOf("Rn", "Ar") } - 2 * molecule.count { it == "Y" } - 1 } fun solvePart1(): Int { return calibrate() } fun solvePart2(): Int { return fabricate() } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
3,457
aoc
MIT License
src/utils/GpsUtils.kt
Arch-vile
162,448,942
false
null
package utils import model.Location import model.Route import model.SLEIGHT_CAPACITY fun km(value: Int) = value * 1000 /** * Distance in meters */ fun distance(location1: Location, location2: Location): Double { val lat1 = location1.lat val lng1 = location1.lon val lat2 = location2.lat val lng2 = location2.lon val earthRadius = 6378000.0 val dLat = Math.toRadians(lat2 - lat1) val dLng = Math.toRadians(lng2 - lng1) val a = Math.sin(dLat / 2.0) * Math.sin(dLat / 2.0) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.sin(dLng / 2.0) * Math.sin(dLng / 2.0) val c = 2.0 * Math.atan2(Math.sqrt(a), Math.sqrt(1.0 - a)) return (earthRadius * c) } fun circularArea(locations: List<Location>, center: Location, radius: Int): List<Location> { return locations .filter { distance(center, it) <= radius } } fun closestCircularArea(Locationren: List<Location>, count: Int): List<Location> { return findCircularArea(Locationren, count, findClosest(KORVATUNTURI, Locationren)) } fun furthestCircularArea(Locationren: List<Location>, count: Int): List<Location> { return findCircularArea(Locationren, count, findFurthest(KORVATUNTURI, Locationren)) } fun findCircularArea(Locationren: List<Location>, count: Int, center: Location): List<Location> { var radius = km(10) var area = circularArea(Locationren, center, radius) while (area.size < count && area.size != Locationren.size) { radius += km(10) area = circularArea(Locationren, center, radius) } if (area.size > 200) { throw Exception("Too large area: ${area.size} with radius: ${radius}") } return area } fun findFurthest(location: Location, Locationren: List<Location>): Location = findByDistance(location, Locationren) { current, best -> current > best } fun findClosest(location: Location, Locationren: List<Location>): Location = findByDistance(location, Locationren) { current, best -> current < best } private fun findByDistance(location: Location, Locationren: List<Location>, comparator: (Double, Double) -> Boolean): Location { var bestMatch = Locationren[0] var bestDistance = distance(location, bestMatch) for (Location in Locationren) { val distance = distance(location, Location) if (comparator(distance, bestDistance)) { bestDistance = distance bestMatch = Location } } return bestMatch } fun routeLength(solution: List<Route>): Double { return solution .map { routeLength(it) } .fold(0.0) { acc, d -> acc + d } } fun routeLength(route: Route): Double { val locations = route.stops var length = 0.0 var current = locations[0] for (location in locations.subList(1, locations.size)) { length += distance(current, location) current = location } return length } fun averageCapacityPercent(solution: List<Route>): Double { return solution .map { (it.stops.map { it.weight }.sum().toDouble()) / SLEIGHT_CAPACITY } .average() } fun getById(locations: List<Location>, id: Int): Location { return locations.filter { it.id == id }.get(0) }
0
Kotlin
0
0
03160a5ea318082a0995b08ba1f70b8101215ed7
3,271
santasLittleHelper
Apache License 2.0
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions7.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.special import com.qiaoyuang.algorithm.round0.quickSort fun test7() { printlnResult(intArrayOf(-1, 0, 1, 2, -1, -4)) printlnResult(intArrayOf(-2, 0, -2, 1, -1, 2, 3, 4)) } /** * Questions 7: Find all the three numbers in an IntArray that theirs sum is 0. */ private fun IntArray.findThreeNumbers(): List<Triple<Int, Int, Int>> { require(size > 2) { "The size of the IntArray must greater than 2" } quickSort() val array = this return buildList { var pointer0 = 0 while (pointer0 <= array.lastIndex - 2) { var pointer1 = pointer0 + 1 var pointer2 = array.lastIndex while (pointer1 < pointer2) { val sum = array[pointer0] + array[pointer1] + array[pointer2] when { sum > 0 -> { val current = array[pointer2--] while (current == array[pointer2]) pointer2-- } sum < 0 -> { val current = array[pointer1++] while (current == array[pointer1]) pointer1++ } else -> { add(Triple(array[pointer0], array[pointer1], array[pointer2])) val current2 = array[pointer2--] while (current2 == array[pointer2]) pointer2-- val current1 = array[pointer1++] while (current1 == array[pointer1]) pointer1++ } } } val current = array[pointer0++] while (current == array[pointer0]) pointer0++ } } } private fun printlnResult(array: IntArray) { println("The all of the three numbers in IntArray: ${array.toList()} are:") println("(${array.findThreeNumbers()})") println("That theirs sum is 0.") }
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
2,055
Algorithm
Apache License 2.0
src/main/kotlin/com/colinodell/advent2023/Day04.kt
colinodell
726,073,391
false
{"Kotlin": 114923}
package com.colinodell.advent2023 class Day04(input: List<String>) { private val scratchcards = input.map { Scratchcard.parse(it) } private data class Scratchcard(val id: Int, val winningNumbers: Set<Int>, val numbersYouHave: Set<Int>) { val matchingNumbers get() = winningNumbers.intersect(numbersYouHave).size companion object { private val scratchcardParser = Regex("""Card\s+(\d+):\s+((?:\d+\s*)+)\s+\|\s+((?:\d+\s*)+)""") private val spaces = Regex("""\s+""") fun parse(input: String) = scratchcardParser .matchEntire(input) .let { requireNotNull(it) { "Invalid scratchcard: $input" } } .let { Scratchcard( id = it.groupValues[1].toInt(), winningNumbers = it.groupValues[2].split(spaces).map { it.toInt() }.toSet(), numbersYouHave = it.groupValues[3].split(spaces).map { it.toInt() }.toSet() ) } } } fun solvePart1() = scratchcards .map { it.matchingNumbers } .sumOf { if (it == 0) 0 else 2.pow(it - 1) } fun solvePart2() = MutableList(scratchcards.size) { 1 } .apply { scratchcards.map { it.matchingNumbers }.forEachIndexed { i, matches -> for (j in 0 until matches) { this[i + j + 1] += this[i] } } } .sum() }
0
Kotlin
0
0
97e36330a24b30ef750b16f3887d30c92f3a0e83
1,495
advent-2023
MIT License
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[111]二叉树的最小深度.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
import kotlin.math.min //给定一个二叉树,找出其最小深度。 // // 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。 // // 说明:叶子节点是指没有子节点的节点。 // // // // 示例 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 // // Related Topics 树 深度优先搜索 广度优先搜索 二叉树 // 👍 617 👎 0 //leetcode submit region begin(Prohibit modification and deletion) /** * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { fun minDepth(root: TreeNode?): Int { //递归 //递归结束条件 if (root == null) return 0 //逻辑处理进入下层循环 //分别获取左右子树深度 var leftlen = minDepth(root.left) var rightlen = minDepth(root.right) //如果有一个子树深度为零 说明最小深度则为当前有深度子树的深度 if (leftlen == 0 || rightlen == 0){ return Math.max(leftlen,rightlen)+1 }else{ //否则返回当前较小深度 return Math.min(leftlen,rightlen)+1 } //数据reverse } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,610
MyLeetCode
Apache License 2.0
src/questions/SearchInsertPosition.kt
realpacific
234,499,820
false
null
package questions import algorithmdesignmanualbook.print import kotlin.math.max import kotlin.test.assertEquals /** * Given a sorted array of distinct integers and a target value, * return the index if the target is found. If not, return the index where it would be if it were inserted in order. * You must write an algorithm with O(log n) runtime complexity. * * [Source](https://leetcode.com/problems/search-insert-position/) */ fun searchInsertPosition(nums: IntArray, target: Int): Int { if (nums.isEmpty()) { return 0 } val resultIndex = binarySearch(nums, 0, nums.size, target) return if (resultIndex.second) { // if [target] is found resultIndex.first } else { // if not found, then try to find the position it would have been in val index = resultIndex.first if (index > nums.lastIndex) { return nums.lastIndex + 1 } val result = if (target < nums[index]) index else index + 1 return max(0, result) } } /** * @return [Pair] of the best index to true if found */ private fun binarySearch(nums: IntArray, low: Int, high: Int, target: Int): Pair<Int, Boolean> { if (low == high && low < nums.lastIndex) { return low to (nums[low] == target) } if (low >= high) { return low to false } val mid = (low + high) / 2 return if (nums[mid] == target) { mid to true } else if (target < nums[mid]) { binarySearch(nums, low, mid - 1, target) } else { binarySearch(nums, mid + 1, high, target) } } fun main() { assertEquals(0, searchInsertPosition(nums = intArrayOf(1, 3), target = 1).print()) assertEquals(1, searchInsertPosition(nums = intArrayOf(1, 3, 5, 6), target = 2).print()) assertEquals(1, searchInsertPosition(nums = intArrayOf(1, 3), target = 2).print()) assertEquals(3, searchInsertPosition(nums = intArrayOf(4, 5, 6), target = 7).print()) assertEquals(0, searchInsertPosition(nums = intArrayOf(1), target = 1).print()) assertEquals(2, searchInsertPosition(nums = intArrayOf(1, 3, 5, 6), target = 5).print()) assertEquals(0, searchInsertPosition(nums = intArrayOf(1, 3, 5, 6), target = 0).print()) assertEquals(1, searchInsertPosition(nums = intArrayOf(1), target = 5).print()) assertEquals(0, searchInsertPosition(nums = intArrayOf(), target = 5).print()) assertEquals(1, searchInsertPosition(nums = intArrayOf(1, 3, 4), target = 2).print()) }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
2,489
algorithms
MIT License
leetcode/src/stack/Q496.kt
zhangweizhe
387,808,774
false
null
package stack import java.util.* import kotlin.collections.HashMap fun main() { // 496. 下一个更大元素 I // https://leetcode-cn.com/problems/next-greater-element-i/ println(nextGreaterElement1(intArrayOf(2,4), intArrayOf(1,2,3,4)).contentToString()) } fun nextGreaterElement(nums1: IntArray, nums2: IntArray): IntArray { nums2.reverse() val ret = IntArray(nums1.size) { -1 } for (i1 in nums1.indices) { for (i2 in nums2) { if (i2 > nums1[i1]) { ret[i1] = i2 }else if (i2 == nums1[i1]) { break } } } return ret } /** * 单调栈,遍历 nums2,依次加入栈中; * 如果 i 小于等于栈顶元素,则将 i 加入栈中,此时从栈底到栈顶是递减的; * 如果 i 大于栈顶元素,则将栈中元素全部出栈,栈中元素的下一个最大值即为 i */ fun nextGreaterElement1(nums1: IntArray, nums2: IntArray): IntArray { val map = HashMap<Int, Int>(nums2.size) val stack = LinkedList<Int>() for (i in nums2) { while (stack.isNotEmpty() && i > stack.peek()) { map[stack.pop()] = i } stack.push(i) } val ret = IntArray(nums1.size) for (i in nums1.indices) { if (map.containsKey(nums1[i])) { ret[i] = map[nums1[i]]!! }else { ret[i] = -1 } } return ret }
0
Kotlin
0
0
1d213b6162dd8b065d6ca06ac961c7873c65bcdc
1,506
kotlin-study
MIT License
src/main/kotlin/day10/main.kt
janneri
572,969,955
false
{"Kotlin": 99028}
package day10 import util.readTestInput open class Command(val endCycle: Int) data class Add(val amount: Int, val startCycle: Int): Command(startCycle + 1) data class Noop(val startCycle: Int): Command(startCycle) fun parseCommands(inputLines: List<String>): List<Command> { val commands = mutableListOf<Command>() inputLines.forEachIndexed { index, cmdStr -> val prevCommand = commands.getOrNull(index - 1) val nextStart = if (prevCommand != null) prevCommand.endCycle + 1 else index + 1 val command = when { cmdStr.startsWith("addx") -> Add(cmdStr.substringAfter(" ").toInt(), startCycle = nextStart) else -> Noop(startCycle = nextStart) } commands.add(command) } return commands } class VideoSystem(private var cycle: Int = 1, private var x: Int = 1, val commands: List<Command>) { private fun endingCommands(): List<Command> = commands.filter { it.endCycle == cycle } private fun lastCycle(): Int = commands.maxOfOrNull { it.endCycle }!! private val signalStrenghtCycles = listOf(20, 60, 100, 140, 180, 220) private fun isSpriteVisible(): Boolean { // the sprite is 3 pixels wide, and the X register sets the horizontal position of the middle of that sprite val drawPosition = (cycle - 1) % 40 return drawPosition - 1 <= x && x <= drawPosition + 1 } private fun drawPixel() { val pixel = if (isSpriteVisible()) '#' else '.' print(pixel) if (cycle % 40 == 0) println() } private fun runCommands(commands: List<Command>) { commands.forEach { if (it is Add && it.endCycle == cycle) { x += it.amount } } } private fun playCycle() { if (cycle in signalStrenghtCycles) { signalStrenths.add(cycle * x) } drawPixel() runCommands(endingCommands()) cycle += 1 } val signalStrenths = mutableListOf<Int>() fun playCycles() { for (cycle in 1..lastCycle()) { playCycle() } } } fun main() { // Solution for https://adventofcode.com/2022/day/10 // Downloaded the input from https://adventofcode.com/2022/day/10/input val inputLines = readTestInput("day10") val commands = parseCommands(inputLines) val videoSystem = VideoSystem(commands = commands) videoSystem.playCycles() println("the sum of ${videoSystem.signalStrenths} is ${videoSystem.signalStrenths.sum()}") }
0
Kotlin
0
0
1de6781b4d48852f4a6c44943cc25f9c864a4906
2,520
advent-of-code-2022
MIT License
src/main/kotlin/dev/bogwalk/batch1/Problem17.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch1 /** * Problem 17: Number to Words * * https://projecteuler.net/problem=17 * * Goal #1: Print the given number N as capitalised words (with/without "And"). * * Goal #2: Count the total number of letters used when the first N positive numbers are * converted to words, with "And" used in compliance with British usage. * * Constraints: 0 <= N <= 1e12 * * e.g.: Goal #1 -> N = 243 * output = "Two Hundred And Forty Three" * Goal #2 -> N = 5 -> {"One", "Two", "Three", "Four", "Five"} * output = 19 */ class NumberToWords { private val underTwenty = listOf( null, "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" ) private val tens = listOf( null, null, "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" ) private val powersOfTen = listOf(null, "Thousand", "Million", "Billion", "Trillion") /** * Project Euler specific implementation that sums the amount of letters (excludes whitespace * & punctuations) in the written forms of the first N positive numbers. */ fun countFirstNPositives(n: Long): Int { return (1L..n).sumOf { num -> numberWritten(num).count { it.isLetter() } } } fun numberWritten(number: Long, andIncluded: Boolean = true): String { if (number == 0L) return "Zero" var n = number var words = "" var power = 0 while (n > 0) { val modThousand = (n % 1000).toInt() if (modThousand > 0L) { words = numberUnderThousand(modThousand, andIncluded) + (powersOfTen[power]?.replaceFirstChar { " $it" } ?: "") + if (words.isEmpty()) "" else " $words" } n /= 1000 power++ } return words } private fun numberUnderThousand(n: Int, andIncluded: Boolean): String? { return if (n < 100) { numberUnderHundred(n) } else { val extra = if (andIncluded) " And " else " " "${underTwenty[n / 100]} Hundred" + (numberUnderHundred(n % 100)?.replaceFirstChar { "$extra$it" } ?: "") } } private fun numberUnderHundred(n: Int): String? { return if (n < 20) { underTwenty[n] } else { tens[n / 10] + (underTwenty[n % 10]?.replaceFirstChar { " $it" } ?: "") } } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
2,610
project-euler-kotlin
MIT License
kotlin.kt
darian-catalin-cucer
598,116,321
false
null
import java.util.ArrayList import java.util.LinkedList class MaximumFlow { private var V = 0 private var adj = ArrayList<LinkedList<IntArray>>() private var level = IntArray(0) private fun addEdge(u: Int, v: Int, w: Int) { adj[u].add(intArrayOf(v, w)) adj[v].add(intArrayOf(u, 0)) } private fun bfs(s: Int, t: Int): Boolean { for (i in level.indices) { level[i] = -1 } val queue = LinkedList<Int>() queue.add(s) level[s] = 0 while (queue.isNotEmpty()) { val u = queue.poll() for (p in adj[u]) { val v = p[0] val weight = p[1] if (level[v] < 0 && weight > 0) { queue.add(v) level[v] = level[u] + 1 } } } return level[t] > 0 } private fun dfs(u: Int, t: Int, flow: IntArray): Int { if (u == t) return flow[0] var flowChange = 0 var f: Int for (p in adj[u]) { val v = p[0] val weight = p[1] if (level[v] == level[u] + 1 && weight > 0) { f = dfs(v, t, intArrayOf(Math.min(flow[0] - flowChange, weight))) if (f == 0) { level[v] = -1 } flowChange += f p[1] -= f adj[v][p[0]][1] += f if (flowChange == flow[0]) return flowChange } } return flowChange } fun dinicMaxFlow(s: Int, t: Int): Int { var maxFlow = 0 while (bfs(s, t)) { maxFlow += dfs(s, t, intArrayOf(Int.MAX_VALUE)) } return maxFlow } fun getMaxFlow(graph: ArrayList<IntArray>, s: Int, t: Int): Int { V = graph.size adj = ArrayList() for (i in 0 until V) { adj.add(LinkedList()) } level = IntArray(V) for (i in graph.indices) { addEdge(graph[i][0], graph[i][1], graph[i][2]) } return dinicMaxFlow(s, t) } }
0
Kotlin
0
0
a8cfbcc5ee2d8fc6d03a7f3442a932b76eacb955
1,791
maximum-flow
MIT License
src/Day06.kt
daletools
573,114,602
false
{"Kotlin": 8945}
fun main() { fun part1(input: List<String>): Int { var score = 0 val code = mutableSetOf<Char>() for (index in input[0].indices) { if (code.contains(input[0][index])) { code.clear() code += input[0][index] } else { code += input[0][index] if (code.size == 4) { score = index + 1 break } } } return score } fun part2(input: List<String>): Int { var score = 0 val code = mutableSetOf<Char>() for (index in input[0].indices) { if (code.contains(input[0][index])) { code.clear() code += input[0][index] } else { code += input[0][index] if (code.size == 14) { score = index + 1 break } } } return score } //my solutions, part 2 did not work, learned about .windowed on the jetbrains day 6 recap and came back to fix fun windowedSolve(input: String, size: Int): Int { return input.windowed(size).indexOfFirst { it.toSet().size == size } + size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") println("Part 1 Test:") println(part1(testInput)) println("Part 2 Test:") println(part2(testInput)) val input = readInput("Day06") println("Part 1:") println(part1(input)) println("Part 2:") println(part2(input)) println("Windowed solve") println("Part 1 Test:") println(windowedSolve(testInput[0], 4)) println("Part 2 Test:") println(windowedSolve(testInput[0], 14)) println("Part 1:") println(windowedSolve(input[0], 4)) println("Part 2:") println(windowedSolve(input[0], 14)) }
0
Kotlin
0
0
c955c5d0b5e19746e12fa6a569eb2b6c3bc4b355
1,945
adventOfCode2022
Apache License 2.0
src/Day10.kt
Reivax47
437,028,926
false
{"Kotlin": 3090}
fun main() { fun part1(input: List<String>): Int { var response = 0 val addition = mapOf(")" to 3, "]" to 57, "}" to 1197, ">" to 25137) input.forEach { val retour = test_line(it) if (retour.first) { response += addition[retour.second] ?: 0 } } return response } fun part2(input: List<String>): Long { var compteur:Long = 0 val addition = mapOf(")" to 1, "]" to 2, "}" to 3, ">" to 4) var liste_comp = mutableListOf<Long>() input.forEach { val retour = test_line(it) if (!retour.first) { compteur = 0 for (i in 0 until retour.second.length) { compteur *= 5 compteur += addition[retour.second[i].toString()] ?: 0 } liste_comp.add(compteur) } } liste_comp.sort() return liste_comp[liste_comp.size / 2] } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput) == 26397) check(part2(testInput) == 288957L) val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
891dff770f8c3cf545bad3d0bcc544daa73e70a5
1,295
AOC_2021_Day10
Apache License 2.0
facebook/y2023/qual/c.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package facebook.y2023.qual private fun solve(): Int { readInt() val a = readInts().sorted() if (a.size == 1) return 1 val inf = Int.MAX_VALUE val ans = listOf(a[0] + a.last(), a[0] + a[a.size - 2], a[1] + a.last()).minOf { sum -> val pool = a.groupBy {it}.mapValues { it.value.size }.toMutableMap() fun remove(v: Int) { if (pool[v] == 1) pool.remove(v) else pool[v] = pool[v]!! - 1 } val unpaired = mutableListOf<Int>() while (pool.isNotEmpty()) { val v = pool.iterator().next().key remove(v) val u = sum - v if (u in pool) { remove(u) continue } unpaired.add(v) } if (unpaired.size != 1) return@minOf inf (sum - unpaired[0]).takeIf { it > 0 } ?: inf } return if (ans == inf) -1 else ans } fun main() { System.setIn(java.io.File("input.txt").inputStream()) System.setOut(java.io.PrintStream("output.txt")) repeat(readInt()) { println("Case #${it + 1}: ${solve()}") } } private fun readInt() = readln().toInt() private fun readStrings() = readln().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,075
competitions
The Unlicense
kotlin/1035-uncrossed-lines.kt
neetcode-gh
331,360,188
false
{"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750}
/* * Top down DP with optimized space */ class Solution { fun maxUncrossedLines(nums1: IntArray, nums2: IntArray): Int { var prev = IntArray(nums2.size + 1) for (i in 0 until nums1.size) { val dp = IntArray(nums2.size + 1) for (j in 0 until nums2.size) { if (nums1[i] == nums2[j]) { dp[j + 1] = 1 + prev[j] } else { dp[j + 1] = maxOf( dp[j], prev[j + 1] ) } } prev = dp } return prev[nums2.size] } } /* * Top down DP */ class Solution { fun maxUncrossedLines(nums1: IntArray, nums2: IntArray): Int { val dp = Array(nums1.size + 1) { IntArray(nums2.size + 1) } for (i in 0 until nums1.size) { for (j in 0 until nums2.size) { if (nums1[i] == nums2[j]) { dp[i + 1][j + 1] = 1 + dp[i][j] } else { dp[i + 1][j + 1] = maxOf( dp[i + 1][j], dp[i][j + 1] ) } } } return dp[nums1.size][nums2.size] } } /* * Recursion/dfs + memoization */ class Solution { fun maxUncrossedLines(nums1: IntArray, nums2: IntArray): Int { val memo = Array(nums1.size) { IntArray(nums2.size) {-1} } fun dfs(i: Int, j: Int): Int { if (i == nums1.size || j == nums2.size) return 0 if (memo[i][j] != -1) return memo[i][j] memo[i][j] = 0 if (nums1[i] == nums2[j]) { memo[i][j] = 1 + dfs(i + 1, j + 1) } else { memo[i][j] += maxOf( dfs(i + 1, j), dfs(i, j + 1) ) } return memo[i][j] } return dfs(0, 0) } } /* * Bottom up DP */ class Solution { fun maxUncrossedLines(nums1: IntArray, nums2: IntArray): Int { val dp = Array(nums1.size + 1) { IntArray(nums2.size + 1) } for (i in nums1.lastIndex downTo 0) { for (j in nums2.lastIndex downTo 0) { if (nums1[i] == nums2[j]) { dp[i][j] = 1 + dp[i + 1][j + 1] } else { dp[i][j] = maxOf( dp[i + 1][j], dp[i][j + 1] ) } } } return dp[0][0] } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
2,593
leetcode
MIT License
advent-of-code2016/src/main/kotlin/day03/Advent3-1.kt
REDNBLACK
128,669,137
false
null
package day03 import chunk import parseInput import splitToLines /** --- Day 3: Squares With Three Sides --- --- Part Two --- Now that you've helpfully marked up their design documents, it occurs to you that triangles are specified in groups of three vertically. Each set of three numbers in a column specifies a triangle. Rows are unrelated. For example, given the following specification, numbers with the same hundreds digit would be part of the same triangle: 101 301 501 102 302 502 103 303 503 201 401 601 202 402 602 203 403 603 In your puzzle input, and instead reading by columns, how many of the listed triangles are possible? */ fun main(args: Array<String>) { val test = """101 301 501 |102 302 502 |103 303 503 |201 401 601 |202 402 602 |203 403 603""".trimMargin() val input = parseInput("day3-input.txt") println(findPossibleVertical(test).size == 6) println(findPossibleVertical(input).size) } fun findPossibleVertical(input: String) = parseTrianglesVertical(input).filter { it.isPossible() } private fun parseTrianglesVertical(input: String): List<Triangle> { val lines = input.splitToLines() .map { it.splitToLines(" ").map(String::toInt) } return lines.map { it[0] } .plus(lines.map { it[1] }) .plus(lines.map { it[2] }) .chunk(3) .map { val (x, y, z) = it Triangle(x, y, z) } }
0
Kotlin
0
0
e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7
1,553
courses
MIT License
src/main/kotlin/tr/emreone/adventofcode/days/Day22.kt
EmRe-One
726,902,443
false
{"Kotlin": 95869, "Python": 18319}
package tr.emreone.adventofcode.days import tr.emreone.kotlin_utils.automation.Day import tr.emreone.kotlin_utils.math.Point3D import java.util.* import kotlin.collections.ArrayDeque import kotlin.math.max import kotlin.math.min class Day22 : Day(22, 2023, "Sand Slabs") { data class Brick(val id: Int, var a: Point3D, var b: Point3D) { override fun toString() = "[$id] $a~$b" fun overlapsWith(other: Brick): Boolean { return max(this.a.x, other.a.x) <= min(this.b.x, other.b.x) && max(this.a.y, other.a.y) <= min(this.b.y, other.b.y) } } private val bricks = inputAsList .mapIndexed { index, line -> val (left, right) = line.split("~") val (x1, y1, z1) = left.split(",").map { it.toLong() } val (x2, y2, z2) = right.split(",").map { it.toLong() } Brick(index, Point3D(x1, y1, z1), Point3D(x2, y2, z2)) } .sortedBy { it.a.z } .also { it.forEachIndexed { index, brick -> var maxZ = 1L for (i in 0 until index) { val other = it.elementAt(i) if (brick.overlapsWith(other)) { maxZ = max(maxZ, other.b.z + 1) } } brick.b = Point3D(brick.b.x, brick.b.y, brick.b.z - brick.a.z + maxZ) brick.a = Point3D(brick.a.x, brick.a.y, maxZ) } } .sortedBy { it.a.z } override fun part1(): Int { // https://www.youtube.com/watch?v=imz7uexX394 val supports = this.bricks.associate { it.id to mutableSetOf<Int>() } val supportedBy = this.bricks.associate { it.id to mutableSetOf<Int>() } this.bricks.forEachIndexed { j, upperBrick -> this.bricks.subList(0, j).forEachIndexed { i, lowerBrick -> if (upperBrick.overlapsWith(lowerBrick) && upperBrick.a.z == lowerBrick.b.z + 1) { supports[i]!! += j supportedBy[j]!! += i } } } return supports.values.count { set -> set.all { supportedBy[it]!!.size > 1 } } } override fun part2(): Int { val supports = this.bricks.associate { it.id to mutableSetOf<Int>() } val supportedBy = this.bricks.associate { it.id to mutableSetOf<Int>() } this.bricks.forEachIndexed { j, upperBrick -> this.bricks.subList(0, j).forEachIndexed { i, lowerBrick -> if (upperBrick.overlapsWith(lowerBrick) && upperBrick.a.z == lowerBrick.b.z + 1) { supports[i]!! += j supportedBy[j]!! += i } } } var total = 0 this.bricks.forEachIndexed { i, brick -> val q: Deque<Int> = LinkedList(supports[brick.id]!!.filter { supportedBy[it]!!.size == 1 }) val falling = q.toMutableSet() falling.add(i) while (q.isNotEmpty()) { val j = q.pop() for (k in (supports[j]!! - falling)) { if (supportedBy[k]!!.all { falling.contains(it) }) { q.add(k) falling.add(k) } } } total += falling.size - 1 } return total } }
0
Kotlin
0
0
c75d17635baffea50b6401dc653cc24f5c594a2b
3,416
advent-of-code-2023
Apache License 2.0
Day7/src/IntState.kt
gautemo
225,219,298
false
null
import java.io.File fun main(){ val state = File(Thread.currentThread().contextClassLoader.getResource("input.txt")!!.toURI()).readText() val arr = toArr(state) println(maxThrust(arr, listOf(0,1,2,3,4))) println(maxThrust(arr, listOf(5,6,7,8,9))) } fun maxThrust(start: List<Int>, settings: List<Int>): Int?{ val permutations = permute(settings) return permutations.map { thrust(start, it) }.max() } fun thrust(start: List<Int>, settings: List<Int>): Int{ val e = Amplifier(start, settings.subList(4,5)) val d = Amplifier(start, settings.subList(3,4), e) val c = Amplifier(start, settings.subList(2,3), d) val b = Amplifier(start, settings.subList(1,2), c) val a = Amplifier(start, settings.subList(0,1) + listOf(0), b) e.sendTo = a val amplifiers = listOf(a,b,c,d,e) while(!e.done){ amplifiers.forEach { val output = it.step() output?.let { o -> it.sendTo?.addInput(o) } } } return e.lastOutput } fun toArr(line: String) = line.split(',').map { it.trim().toInt() }.toMutableList() fun <T> permute(input: List<T>): List<List<T>> { if (input.size == 1) return listOf(input) val perms = mutableListOf<List<T>>() val toInsert = input[0] for (perm in permute(input.drop(1))) { for (i in 0..perm.size) { val newPerm = perm.toMutableList() newPerm.add(i, toInsert) perms.add(newPerm) } } return perms }
0
Kotlin
0
0
f8ac96e7b8af13202f9233bb5a736d72261c3a3b
1,513
AdventOfCode2019
MIT License
src/algorithmsinanutshell/spatialtree/KnapSack01.kt
realpacific
234,499,820
false
null
package algorithmsinanutshell.spatialtree import utils.PrintUtils import kotlin.math.max import kotlin.test.assertTrue /** * Knapsack Problem: Given total capacity [totalCapacity] of a bag, * how can you select subset of items of weight [weights] with profit [profits] such that the profit is maximized? * * [Video](https://www.youtube.com/watch?v=8LusJS5-AGo) * * ``` * ! P ! w ! 0 ! 1 ! 2 ! 3 ! 4 ! 5 ! 6 ! 7 ! * ! 1 ! 1 ! ! ! ! ! ! ! ! ! * ! 4 ! 3 ! ! ! ! ! ! ! ! ! <-- while here, everything below are ignored so w1 and w3 are considered * ! 5 ! 4 ! ! ! ! ! ! ! ! ! * ! 6 ! 5 ! ! ! ! ! ! ! ! ! * ``` * */ class KnapSack01(val weights: IntArray, val profits: IntArray, val totalCapacity: Int) { private val matrix: Array<IntArray> = Array(profits.size + 1) { IntArray(totalCapacity + 1) { 0 } } fun getProfitMatrix(): Array<IntArray> { for (row in 1..profits.size) { for (currentCapacity in 0..totalCapacity) { if (weights[row - 1] <= currentCapacity) { // Which item can fit after we choose weights[row-1] val remainingSpace = currentCapacity - weights[row - 1] matrix[row][currentCapacity] = max( matrix[row - 1][currentCapacity], // Previous best profit // I select an item, its profit = values[row - 1] // now I can select any item that can fit in the remaining space (profits[row - 1]) + (matrix[row - 1][remainingSpace]) ) } else { matrix[row][currentCapacity] = matrix[row - 1][currentCapacity] } } } return matrix } fun getSelectedWeight(): MutableList<Int> { val selection = mutableListOf<Int>() // Start from the bottom right corner of the matrix var row = matrix.lastIndex var col = matrix[0].lastIndex for (i in weights.lastIndex downTo 0) { compare(row, col, selection).apply { row = this.first col = this.second } } println(selection) return selection } private fun compare(row: Int, col: Int, selection: MutableList<Int>): Pair<Int, Int> { val currentProfit = matrix[row][col] val profitOneLevelUp = matrix[row - 1][col] // Do nothing if total selected weight exceeds [totalCapacity] if (selection.sum() >= totalCapacity) { return row to col } // Compare current profit with profit directly above // Select current weight if they differ return if (currentProfit != profitOneLevelUp) { // Select the weight val candidateForSelection = weights[row - 1] selection.add(candidateForSelection) // Find remaining space after the weight is selected val remainingSpace = totalCapacity - candidateForSelection // Go one step above and then to remaining space available row - 1 to remainingSpace } else { // Else go one step above and repeat row - 1 to col } } } fun main() { val weights = intArrayOf(1, 3, 4, 5) val profits = intArrayOf(1, 4, 5, 7) val totalCapacity = 7 val algorithm = KnapSack01( weights = weights, profits = profits, totalCapacity = totalCapacity ) algorithm.getProfitMatrix().map { PrintUtils.print(it.toList()) } val selectedWeight = algorithm.getSelectedWeight() assertTrue { selectedWeight.sum() == totalCapacity } assertTrue { selectedWeight.map { weight -> val index = weights.indexOf(weight) profits[index] }.sum() == 9 } }
4
Kotlin
5
93
22eef528ef1bea9b9831178b64ff2f5b1f61a51f
3,947
algorithms
MIT License
2020/src/year2021/day04/code.kt
eburke56
436,742,568
false
{"Kotlin": 61133}
package year2021.day04 import util.readAllLines private data class Node(val value: Int, var marked: Boolean = false) private class Board(values: List<String>) { private val nodes = mutableMapOf<Int, Node>() private val rows = mutableListOf<MutableList<Node>>().apply { repeat(5) { add(mutableListOf<Node>().apply { repeat(5) { add(Node(0)) } }) } } private val cols = mutableListOf<MutableList<Node>>().apply { repeat(5) { add(mutableListOf<Node>().apply { repeat(5) { add(Node(0)) } }) } } init { values.mapIndexed { rowIndex, row -> row.trim().split(Regex("\\s+")).mapIndexed { colIndex, stringValue -> val value = stringValue.toInt() val node = Node(value) nodes[value] = node rows[rowIndex][colIndex] = node cols[colIndex][rowIndex] = node } } } val score: Int get() = nodes.values.sumOf { if (it.marked) 0 else it.value } val isWinner: Boolean get() = rows.any { row -> row.all { it.marked } } || cols.any { col -> col.all { it.marked } } fun mark(value: Int) { nodes[value]?.marked = true } } fun main() { part1() part2() } private fun part1() { val input = readAllLines("input.txt") val boards = createBoard(input) input[0].split(",").map { it.toInt() }.forEach { called -> boards.forEach { it.mark(called) if (it.isWinner) { println(it.score * called) return } } } error("No winner found") } private fun part2() { val input = readAllLines("input.txt") val boards = createBoard(input) input[0].split(",").map { it.toInt() }.forEach { called -> var size = boards.size boards.forEach { it.mark(called) } for (i in 0 until size) { val board = boards[i] if (board.isWinner) { if(size == 1) { println(board.score * called) return } else { boards.remove(board) size -= 1 } } } } error("No last winner found!") } private fun createBoard(input: List<String>): MutableList<Board> { val boards = mutableListOf<Board>() for (i in 2 until input.size step 6) { boards.add(Board(input.subList(i, i + 5))) } return boards }
0
Kotlin
0
0
24ae0848d3ede32c9c4d8a4bf643bf67325a718e
2,819
adventofcode
MIT License
src/main/kotlin/g1401_1500/s1453_maximum_number_of_darts_inside_of_a_circular_dartboard/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1401_1500.s1453_maximum_number_of_darts_inside_of_a_circular_dartboard // #Hard #Array #Math #Geometry #2023_06_13_Time_211_ms_(100.00%)_Space_37.3_MB_(100.00%) class Solution { private class Angle(var a: Double, var enter: Boolean) : Comparable<Angle> { override fun compareTo(other: Angle): Int { if (a > other.a) { return 1 } else if (a < other.a) { return -1 } else if (enter == other.enter) { return 0 } else if (enter) { return -1 } return 1 } } private fun getPointsInside(i: Int, r: Double, n: Int, points: Array<IntArray>, dis: Array<DoubleArray>): Int { val angles: MutableList<Angle> = ArrayList(2 * n) for (j in 0 until n) { if (i != j && dis[i][j] <= 2 * r) { val b = Math.acos(dis[i][j] / (2 * r)) val a = Math.atan2( points[j][1] - points[i][1] * 1.0, points[j][0] * 1.0 - points[i][0] ) val alpha = a - b val beta = a + b angles.add(Angle(alpha, true)) angles.add(Angle(beta, false)) } } angles.sort() var count = 1 var res = 1 for (a in angles) { if (a.enter) { count++ } else { count-- } if (count > res) { res = count } } return res } fun numPoints(points: Array<IntArray>, r: Int): Int { val n = points.size val dis = Array(n) { DoubleArray(n) } for (i in 0 until n - 1) { for (j in i + 1 until n) { dis[j][i] = Math.sqrt( Math.pow(points[i][0] * 1.0 - points[j][0], 2.0) + Math.pow(points[i][1] * 1.0 - points[j][1], 2.0) ) dis[i][j] = dis[j][i] } } var ans = 0 for (i in 0 until n) { ans = Math.max(ans, getPointsInside(i, r.toDouble(), n, points, dis)) } return ans } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,230
LeetCode-in-Kotlin
MIT License
2020/day-01/day01.kts
kevinrobayna
436,414,545
false
{"Ruby": 195446, "Kotlin": 42719, "Shell": 1288}
import java.io.File import java.util.stream.Collectors fun readFile(fileName: String): String = File(fileName).readText(Charsets.UTF_8) fun parseProblem(content: String): List<Int> { content.split("\n").stream().map { it.toInt() }.collect(Collectors.toList()) } fun solve(content: String): Int { val values = parseProblem(content) val pairs: MutableList<Pair<Int, Int>> = mutableListOf() for (outLoop in values.indices) { for (innerLoop in values.indices) { if (!outLoop.equals(innerLoop)) { val first = Math.max(values[outLoop], values[innerLoop]) val second = Math.min(values[outLoop], values[innerLoop]) pairs.add(Pair(first, second)) } } } val pair = pairs .filter { it.first + it.second == 2020 } .distinct() .get(0) return pair.first * pair.second } fun solve2(content: String): Int { val values = parseProblem(content) val tuples: MutableList<Triple<Int, Int, Int>> = mutableListOf() for (outLoop in values) { for (innerLoop in values) { for (innerInnerLoop in values) { val points = listOf(outLoop, innerLoop, innerInnerLoop).sorted() tuples.add(Triple(points[0], points[1], points[2])) } } } val triple = tuples .filter { it.first.plus(it.second).plus(it.third) == 2020 } .distinct() .get(0) return triple.first * triple.second * triple.third } val test = readFile("test.txt") val real = readFile("input.txt") println("Part1 Test ${solve(test)}") println("Part1 ${solve(real)}") println("Part2 Test ${solve2(test)}") println("Part2 ${solve2(real)}")
0
Ruby
0
0
9e48ecdebdb4c479ef00f0fd3b1a44a211fb6577
1,732
adventofcode
MIT License
src/main/kotlin/io/github/clechasseur/adventofcode/y2022/Day14.kt
clechasseur
567,968,171
false
{"Kotlin": 493887}
package io.github.clechasseur.adventofcode.y2022 import io.github.clechasseur.adventofcode.util.Pt import io.github.clechasseur.adventofcode.y2022.data.Day14Data import kotlin.math.sign object Day14 { private val input = Day14Data.input fun part1(): Int = generateSequence(input.toCave(hasFloor = false)) { it.dropOneSand(Pt(500, 0)) }.last().sand.size fun part2(): Int = generateSequence(input.toCave(hasFloor = true)) { it.dropOneSand(Pt(500, 0)) }.last().sand.size private data class Cave(val solid: Set<Pt>, val sand: Set<Pt>, val hasFloor: Boolean) { val bottom: Int = solid.maxOf { it.y } + 2 fun occupied(pt: Pt): Boolean = solid.contains(pt) || sand.contains(pt) || (hasFloor && pt.y >= bottom) fun dropOneSand(from: Pt): Cave? { if (occupied(from)) { return null } var pt = from while (pt.y < bottom) { var nextPt = pt + Pt(0, 1) if (occupied(nextPt)) { nextPt = pt + Pt(-1, 1) if (occupied(nextPt)) { nextPt = pt + Pt(1, 1) if (occupied(nextPt)) { return Cave(solid, sand + pt, hasFloor) } } } pt = nextPt } return null } } private fun String.toCave(hasFloor: Boolean): Cave = Cave(lines().flatMap { line -> line.split(" -> ").map { pt -> val (x, y) = pt.split(",") Pt(x.toInt(), y.toInt()) }.zipWithNext().flatMap { it.asLine() } }.toSet(), emptySet(), hasFloor) private fun Pair<Pt, Pt>.asLine(): Sequence<Pt> { val displacement = Pt((second.x - first.x).sign, (second.y - first.y).sign) return generateSequence(first) { it + displacement }.takeWhile { (it - displacement) != second } } }
0
Kotlin
0
0
7ead7db6491d6fba2479cd604f684f0f8c1e450f
1,970
adventofcode2022
MIT License
src/main/kotlin/day21/main.kt
janneri
572,969,955
false
{"Kotlin": 99028}
package day21 import util.readInput sealed class Monkey(open val name: String) { abstract fun result(): ULong abstract fun resultPart2(humnPath: Set<Monkey>, expectedResult: ULong): ULong companion object { fun parse(str: String) = when { NumberMonkey.matches(str) -> NumberMonkey.of(str) else -> MathOperationMonkey.of(str) } } } data class NumberMonkey(override val name: String, val number: ULong): Monkey(name) { override fun result(): ULong = number override fun resultPart2(humnPath: Set<Monkey>, expectedResult: ULong): ULong = if (name == "humn") expectedResult else number companion object { private val regex = Regex("""([a-z]+): (\d+)""") fun matches(str: String) = regex.containsMatchIn(str) fun of(str: String) = regex.matchEntire(str)!! .destructured .let { (name, number) -> NumberMonkey(name, number.toULong()) } } } data class MathOperationMonkey(override val name: String, val leftName: String, val rightName: String, val operation: String): Monkey(name) { lateinit var leftMonkey: Monkey lateinit var rightMonkey: Monkey override fun result(): ULong = when (operation) { "+" -> leftMonkey.result() + rightMonkey.result() "-" -> leftMonkey.result() - rightMonkey.result() "*" -> leftMonkey.result() * rightMonkey.result() else -> leftMonkey.result() / rightMonkey.result() } /** returns the unknown left value when the right value is known */ private fun calculateLeftValue(expectedResult: ULong, rightValue: ULong): ULong { return when (operation) { "+" -> expectedResult - rightValue // ? + rightValue = expectedResult "-" -> expectedResult + rightValue // ? - rightValue = expectedResult "*" -> expectedResult / rightValue // ? * rightValue = expectedResult else -> expectedResult * rightValue // ? / rightValue = expectedResult } } /** returns the unknown right value when the left value is known */ private fun calculateRightValue(expectedResult: ULong, leftValue: ULong): ULong { return when (operation) { "+" -> expectedResult - leftValue // leftValue + ? = expectedResult "-" -> leftValue - expectedResult // leftValue - ? = expectedResult "*" -> expectedResult / leftValue // leftValue * ? = expectedResult else -> leftValue / expectedResult // leftValue / ? = expectedResult } } override fun resultPart2(humnPath: Set<Monkey>, expectedResult: ULong): ULong { return when (leftMonkey) { // When left the unknown value (and right value is known): in humnPath -> leftMonkey.resultPart2(humnPath, calculateLeftValue(expectedResult, rightMonkey.result())) // When right is the unkown value (and left is fixed): else -> rightMonkey.resultPart2(humnPath, calculateRightValue(expectedResult, leftMonkey.result())) } } companion object { private val regex = Regex("""([a-z]+): ([a-z]+) (.) ([a-z]+)""") fun of(str: String) = regex.matchEntire(str)!! .destructured .let { (name, leftName, operation, rightName) -> MathOperationMonkey(name, leftName, rightName, operation) } } } fun parseMonkeys(inputLines: List<String>): Map<String, Monkey> { val monkeys = inputLines.map { Monkey.parse(it) } val monkeysByName = monkeys.associateBy { it.name } monkeys .filterIsInstance<MathOperationMonkey>() .forEach { it.leftMonkey = monkeysByName[it.leftName]!! it.rightMonkey = monkeysByName[it.rightName]!! } return monkeysByName } fun findHumnPath(rootMonkey: Monkey): Set<Monkey> { fun findPath(monkey: Monkey, path: MutableList<Monkey>): Boolean { path += monkey if (monkey is NumberMonkey) { if (monkey.name == "humn") return true } if (monkey is MathOperationMonkey && (findPath(monkey.leftMonkey, path) || findPath(monkey.rightMonkey, path))) { return true } path.removeLast() return false } val path = mutableListOf<Monkey>() findPath(rootMonkey, path) return path.toSet() } fun part1(inputLines: List<String>): ULong { val monkeysByName = parseMonkeys(inputLines) return monkeysByName["root"]!!.result() } fun part2(inputLines: List<String>): ULong { val monkeysByName = parseMonkeys(inputLines) val humnPathMonkeys = findHumnPath(monkeysByName["root"]!!) val root = monkeysByName["root"]!! as MathOperationMonkey if (root.leftMonkey in humnPathMonkeys) { return root.leftMonkey.resultPart2(humnPathMonkeys, root.rightMonkey.result()) } else { return root.rightMonkey.resultPart2(humnPathMonkeys, root.leftMonkey.result()) } } fun main() { val inputLines = readInput("day21") println(part1(inputLines)) println(part2(inputLines)) }
0
Kotlin
0
0
1de6781b4d48852f4a6c44943cc25f9c864a4906
5,115
advent-of-code-2022
MIT License
src/Day10.kt
maewCP
579,203,172
false
{"Kotlin": 59412}
fun main() { fun printToCrt(crt: String, cycle: Int, x: Int): String { var cycleCount = (cycle % 40) if (cycleCount == 0) cycleCount = 40 val output = if ((cycleCount - x) in listOf(0, 1, 2)) "#" else "." return crt + output } fun _process(input: List<String>): Pair<Int, String> { var cycle = 1 var x = 1 var carry: Int? = null var signalStrength = 0 var cmds = input var crt = "" run breakWhile@{ while (true) { if ((cycle - 20) % 40 == 0 && cycle <= 220) { signalStrength += x * cycle } if ((cycle - 1) % 40 == 0) crt += "\n" crt = printToCrt(crt, cycle, x) if (carry != null) { x += carry!! carry = null } else { if (cmds.isEmpty()) return@breakWhile val line = cmds.take(1).first() cmds = cmds.drop(1) if (line.substring(0, 4) == "addx") { val regex = "(.+) (-?\\d*)".toRegex() val (_, valueStr) = regex.find(line)!!.destructured.toList() carry = valueStr.toInt() } } cycle++ } } return Pair(signalStrength, crt) } fun part1(input: List<String>): Int { return _process(input).first } fun part2(input: List<String>): String { return _process(input).second } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput) == 13140) val input = readInput("Day10") part1(input).println() part2(input).println() }
0
Kotlin
0
0
8924a6d913e2c15876c52acd2e1dc986cd162693
1,850
advent-of-code-2022-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinimumSidewayJumps.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.min /** * 1824. Minimum Sideway Jumps * @see <a href="https://leetcode.com/problems/minimum-sideway-jumps/">Source</a> */ fun interface MinimumSidewayJumps { operator fun invoke(obstacles: IntArray): Int } class MinimumSidewayJumpsDP : MinimumSidewayJumps { override operator fun invoke(obstacles: IntArray): Int { val dp = intArrayOf(1, 0, 1) for (a in obstacles) { if (a > 0) dp[a - 1] = LIMIT for (i in 0..2) if (a != i + 1) { dp[i] = min( dp[i], min( dp[(i + 1) % 3], dp[(i + 2) % 3], ) + 1, ) } } return min(dp[0], min(dp[1], dp[2])) } companion object { private const val LIMIT = 1000000 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,501
kotlab
Apache License 2.0
src/leetcode_problems/medium/PairWithGivenDifference.kt
MhmoudAlim
451,633,139
false
{"Kotlin": 31257, "Java": 586}
package leetcode_problems.medium import java.lang.Exception import kotlin.math.abs /* https://www.geeksforgeeks.org/find-a-pair-with-the-given-difference/ Given an unsorted array and a number n, find if there exists a pair of elements in the array whose difference is n. Examples: -Input: arr[] = {5, 20, 3, 2, 50, 80}, n = 78 =Output: Pair Found: (2, 80) -Input: arr[] = {90, 70, 20, 80, 50}, n = 45 =Output: No Such Pair*/ fun findPair(nums: IntArray, n: Int): IntArray { // //<editor-fold desc = "Solution 1"> // /* // Time Complexity: O(n*n) as two nested for loops are executing both from 1 to n where n is size of input array. // Space Complexity: O(1) as no extra space has been taken // */ // // nums.forEach { i -> // for (j in i + 1 until nums.size) { // if (abs(nums[i] - nums[j]) == n) return intArrayOf(nums[i], nums[j]) // } // } // throw Exception("no pair found") // //</editor-fold> //<editor-fold desc = "Solution 2"> // Time Complexity: O(n*log(n)) val sorted = nums.sorted() var p1 = 0 var p2 = sorted.size - 1 while (p2 >= p1 && p2 < sorted.size) { if (abs(sorted[p1] - sorted[p2]) == n && p1 != p2) { println("p1 = $p1") println("p2 = $p2") println("abs diff = ${abs(sorted[p1] - sorted[p2])}") return intArrayOf(sorted[p1], sorted[p2]) } else { if (sorted[p1] - sorted[p2] > n) { println("p1 = $p1") println("p2 = $p2") println("n = $n") println("diff = ${sorted[p1] - sorted[p2]}") p1++ println("p1++ = ${p1++}") } else { p2-- println("p2-- = ${p2--}") } } } throw Exception("no pair found") //</editor-fold> } fun main() { val result = findPair(nums = intArrayOf(5, 20, 3, 2, 50, 80, 90, 83), n = 78) println(result.contentToString()) }
0
Kotlin
0
0
31f0b84ebb6e3947e971285c8c641173c2a60b68
2,010
Coding-challanges
MIT License
src/Day04.kt
samframpton
572,917,565
false
{"Kotlin": 6980}
fun main() { fun part1(input: List<String>) = getSectionAssignments(input).count { (it.first.first <= it.second.first && it.first.last >= it.second.last) || (it.second.first <= it.first.first && it.second.last >= it.first.last) } fun part2(input: List<String>) = getSectionAssignments(input).count { it.first.any(it.second::contains) } val input = readInput("Day04") println(part1(input)) println(part2(input)) } private fun getSectionAssignments(input: List<String>) = input.map { val assignments = it.split(",") val assignment1 = assignments[0].split("-").map(String::toInt) val assignment2 = assignments[1].split("-").map(String::toInt) assignment1[0]..assignment1[1] to assignment2[0]..assignment2[1] }
0
Kotlin
0
0
e7f5220b6bd6f3c5a54396fa95f199ff3a8a24be
798
advent-of-code-2022
Apache License 2.0
src/main/kotlin/days/Day12.kt
hughjdavey
159,955,618
false
null
package days import com.google.common.collect.EvictingQueue class Day12 : Day(12) { private val initialState = parseInitialState(inputList.first()) private val rules = parseRules(inputList.drop(2)) override fun partOne(): Any { val twentyGenerations = doGenerations(initialState, rules, 20) return totalPlantContainingPots(twentyGenerations) } override fun partTwo(): Any { val fiftyBillionGenerations = doGenerations(initialState, rules, 50000000000) return totalPlantContainingPots(fiftyBillionGenerations) } data class Rule(val rule: String, val result: Char) companion object { fun parseInitialState(input: String) = input.substring(15) fun parseRules(input: List<String>) = input.map { it.trim() }.map { Rule(it.take(5), it.last()) } fun totalPlantContainingPots(state: Pair<String, Int>): Long { // todo could clean this up a bit! val (remainingIterations, repeatingSum) = if (state.first.contains("::")) { 50000000000 - state.first.substring(state.first.indexOf("::") + 2, state.first.lastIndexOf("::")).toLong() to state.first.substring(state.first.lastIndexOf("::") + 2).toLong() } else 0L to 0L return state.first.foldIndexed(0) { index, total, pot -> if (pot == '#') total + (index - state.second) else total } + (remainingIterations * repeatingSum) //9699999999321 correct! } fun doGenerations(initialState: String, rules: List<Rule>, generations: Long): Pair<String, Int> { var state = initialState to 0 var lastSum = 0L val last3Diffs = EvictingQueue.create<Long>(3) (0 until generations).forEach { val sum = totalPlantContainingPots(state) val diff = sum - lastSum lastSum = sum last3Diffs.add(diff) // if diffs have started repeating, return early and add info needed to extrapolate if (last3Diffs.size == 3 && last3Diffs.all { it == diff }) { return "${state.first}::$it::$diff" to state.second } state = doGeneration(state, rules) } return state } fun doGeneration(initialState: Pair<String, Int>, rules: List<Rule>): Pair<String, Int> { val padding = padState(initialState.first) var state = padding.first.replace('#', '.') padding.first.windowed(5, 1).forEachIndexed { index, window -> rules.forEach { rule -> if (rule.rule == window) { state = state.replaceRange(index + 2, index + 3, rule.result.toString()) } } } return state to initialState.second + padding.second } fun padState(state: String): Pair<String, Int> { val start = when { state.startsWith(".....") -> 0 state.startsWith("....") -> 1 state.startsWith("...") -> 2 state.startsWith("..") -> 3 state.startsWith(".") -> 4 else -> 5 } val end = when { state.endsWith(".....") -> 0 state.endsWith("....") -> 1 state.endsWith("...") -> 2 state.endsWith("..") -> 3 state.endsWith(".") -> 4 else -> 5 } return "${".".repeat(start)}$state${".".repeat(end)}" to start } } }
0
Kotlin
0
0
4f163752c67333aa6c42cdc27abe07be094961a7
3,676
aoc-2018
Creative Commons Zero v1.0 Universal
src/day05/Day05.kt
idle-code
572,642,410
false
{"Kotlin": 79612}
package day05 import readInput typealias Crate = Char val commandLineRegex = """move (\d+) from (\d+) to (\d+)""".toRegex() data class CraneCommand( val cratesCount: Int, val sourceStack: ArrayDeque<Crate>, val destinationStack: ArrayDeque<Crate> ) fun main() { fun parseInput(input: List<String>): Pair<Array<ArrayDeque<Crate>>, List<CraneCommand>> { // Find out stack count val stateRepresentation = input.takeWhile { it.isNotEmpty() } val indexLine = stateRepresentation.last() val stackCount = indexLine[indexLine.length - 2].digitToInt() val stacks = Array(stackCount) { ArrayDeque<Crate>() } // Parse state representation for (level in (stateRepresentation.size - 2) downTo 0) { for (stackId in 0 until stackCount) { val crate = stateRepresentation[level][1 + stackId * 4] if (crate != ' ') stacks[stackId].addLast(crate) } } // Parse crane commands val craneCommands = ArrayList<CraneCommand>() for (commandLine in input.drop(stateRepresentation.size + 1)) { val (cratesCount, sourceStackIndex, destinationStackIndex) = commandLineRegex.matchEntire(commandLine)?.groupValues?.drop(1)?.map { it.toInt() } ?: throw IllegalArgumentException("Incorrect command line $commandLine") craneCommands.add( CraneCommand( cratesCount, stacks[sourceStackIndex - 1], stacks[destinationStackIndex - 1] ) ) } return Pair(stacks, craneCommands) } fun listTopCreates(stacks: Array<ArrayDeque<Crate>>): String { val stacksTop = StringBuilder() for (stack in stacks) stacksTop.append(stack.last()) return stacksTop.toString() } fun part1(input: List<String>): String { val (stacks, craneCommands) = parseInput(input) for (command in craneCommands) { for (i in 0 until command.cratesCount) { val movedCrate = command.sourceStack.removeLast() command.destinationStack.addLast(movedCrate) } } // Find top of the stacks return listTopCreates(stacks) } fun part2(input: List<String>): String { val (stacks, craneCommands) = parseInput(input) for (command in craneCommands) { val tempStack = ArrayList<Crate>() for (i in 0 until command.cratesCount) { val movedCrate = command.sourceStack.removeLast() tempStack.add(movedCrate) } command.destinationStack.addAll(tempStack.reversed()) } // Find top of the stacks return listTopCreates(stacks) } val testInput = readInput("sample_data", 5) println(part1(testInput)) check(part1(testInput) == "CMZ") val mainInput = readInput("main_data", 5) println(part1(mainInput)) check(part1(mainInput) == "WSFTMRHPP") println(part2(testInput)) check(part2(testInput) == "MCD") println(part2(mainInput)) check(part2(mainInput) == "GSLCMFBRP") }
0
Kotlin
0
0
1b261c399a0a84c333cf16f1031b4b1f18b651c7
3,260
advent-of-code-2022
Apache License 2.0
src/main/kotlin/com/kodeinc/conway/algorithm/CellMap.kt
evanjpw
124,837,562
false
null
package com.kodeinc.conway.algorithm private fun emptyMapFun(x: Int, y: Int, map: CellMap? = null) = DEAD_CELL internal enum class CellDirection { NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST, NORTHWEST; } data class Coord(val x: Int, val y: Int) class CellMap(val w: Int, val h: Int, oldMap: CellMap? = null, mapFiller: MapFiller = ::emptyMapFun) { constructor(oldMap: CellMap, mapFiller: MapFiller): this(oldMap.w, oldMap.h, oldMap, mapFiller) private val grid = Array(w, { x -> Array(h) { y-> mapFiller(x, y, oldMap) } }) private fun safeX(x: Int) = x in 0..(w - 1) private fun safeY(y: Int) = y in 0..(h - 1) private fun safeCoord(x: Int, y: Int) = safeX(x) && safeY(y) fun cell(x: Int, y: Int) = if (safeCoord(x, y)) { grid[x][y] } else { DEAD_CELL } fun cell(coord: Coord) = cell(coord.x, coord.y) fun setCell(x: Int, y: Int, c: Cell) { if (safeCoord(x, y)) { grid[x][y] = c } } fun setCell(coord: Coord, c: Cell) = setCell(coord.x, coord.y, c) private fun interrogateNeighborLiveness(coord: Coord, direction: CellDirection, map: CellMap): Boolean { return interrogateNeighborLiveness(coord.x, coord.y, direction, map) } private fun interrogateNeighborLiveness(x: Int, y: Int, direction: CellDirection, map: CellMap): Boolean { return when (direction) { CellDirection.NORTH -> map.cell(x, y - 1) CellDirection.NORTHEAST -> map.cell(x + 1, y - 1) CellDirection.EAST -> map.cell(x + 1, y) CellDirection.SOUTHEAST -> map.cell(x + 1, y + 1) CellDirection.SOUTH -> map.cell(x, y + 1) CellDirection.SOUTHWEST -> map.cell(x - 1, y + 1) CellDirection.WEST -> map.cell(x - 1, y) CellDirection.NORTHWEST -> map.cell(x - 1, y - 1) } } fun countCellNeighbors(x: Int, y: Int): Int { return CellDirection.values().count { interrogateNeighborLiveness(x, y, it, this) } } } internal fun evolveMap(map: CellMap, evolver: MapFiller): CellMap { return CellMap(map, evolver) }
0
Kotlin
0
0
bdfbcaf46955da8770188627c9472b78da34cc07
2,133
conway
MIT License
src/main/kotlin/Day03.kt
nmx
572,850,616
false
{"Kotlin": 18806}
fun main(args: Array<String>) { fun findCommonElement(strings: List<String>): Char { val sets = strings.map { it.toSet() } val intersection = sets.reduce { acc, set -> acc.intersect(set) } if (intersection.size != 1) { throw RuntimeException("expected exactly one match, found ${intersection.size}") } return intersection.elementAt(0) } fun findMispackedTypeInRow(row: String): Char? { if (row.isEmpty()) return null val left = row.substring(0, row.length / 2) val right = row.substring(row.length / 2, row.length) return findCommonElement(listOf(left, right)) } fun scoreType(type: Char?): Int { return if (type == null) { 0 } else if (type.isLowerCase()) { type - 'a' + 1 } else { type - 'A' + 27 } } fun findBadge(rows: List<String>): Char { return findCommonElement(rows) } fun part1(input: String) { var sum = 0 input.split("\n").forEach { val type = findMispackedTypeInRow(it) sum += scoreType(type) } println(sum) } fun part2(input: String) { val lines = input.split("\n") var i = 0 var sum = 0 while (i < lines.size && lines[i].isNotEmpty()) { val badge = findBadge(lines.subList(i, i + 3)) sum += scoreType(badge) i += 3 } println(sum) } val input = object {}.javaClass.getResource("Day03.txt").readText() part1(input) part2(input) }
0
Kotlin
0
0
33da2136649d08c32728fa7583ecb82cb1a39049
1,610
aoc2022
MIT License
src/Day02.kt
valerakostin
574,165,845
false
{"Kotlin": 21086}
fun main() { val lost = 0 val draw = 3 val win = 6 val rock = 1 val paper = 2 val scissors = 3 val map = mapOf( "A X" to rock + draw, "A Y" to paper + win, "A Z" to scissors + lost, "B X" to rock + lost, "B Y" to paper + draw, "B Z" to scissors + win, "C X" to rock + win, "C Y" to paper + lost, "C Z" to scissors + draw ) val map2 = mapOf( "A X" to lost + scissors, "A Y" to draw + rock, "A Z" to win + paper, "B X" to lost + rock, "B Y" to draw + paper, "B Z" to win + scissors, "C X" to lost + paper, "C Y" to draw + scissors, "C Z" to win + rock ) fun part1(input: List<String>): Int = input.sumOf { map.getOrDefault(it, 0) } fun part2(input: List<String>): Int = input.sumOf { map2.getOrDefault(it, 0) } val testInput = readInput("Day02_test") check(part1(testInput) == 15) val input = readInput("Day02") println(part1(input)) check(part2(testInput) == 12) println(part2(input)) }
0
Kotlin
0
0
e5f13dae0d2fa1aef14dc71c7ba7c898c1d1a5d1
1,110
AdventOfCode-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/KthSmallestPath.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.extensions.second /** * 1643. Kth The Smallest Instructions * @see <a href="https://leetcode.com/problems/kth-smallest-instructions/">Source</a> */ fun interface KthSmallestPath { operator fun invoke(destination: IntArray, k: Int): String } class KthSmallestPathImpl : KthSmallestPath { override operator fun invoke(destination: IntArray, k: Int): String { if (destination.isEmpty()) return "" val ti = destination.first() val tj = destination.second() val dp = Array(ti + 1) { IntArray(tj + 1) } for (i in ti downTo 0) { for (j in tj downTo 0) { when { i == ti && j == tj -> { dp[i][j] = 1 } i == ti -> { dp[i][j] = dp[i][j + 1] } j == tj -> { dp[i][j] = dp[i + 1][j] } else -> { dp[i][j] = dp[i + 1][j] + dp[i][j + 1] } } } } // in each (i, j), we have dp[i][j] kind of instructions, which equal to dp[i][j+1] + dp[i+1][j] // all dp[i][j+1] kinds of instructions are lexicographically smaller than the left dp[i+1][j] // kinds of instructions. // we can just compare k with dp[i][j+1] to determine how to choose next step. val sb = StringBuilder() helper(dp, 0, 0, k, sb) return sb.toString() } private fun helper(dp: Array<IntArray>, i: Int, j: Int, k: Int, sb: StringBuilder) { var i0 = i var j0 = j if (i0 == dp.size - 1) { // if we came to most down position then we can only go right while (++j0 < dp[0].size) { sb.append("H") } return } if (j0 == dp[0].size - 1) { // if we came to most right position then we can only go down while (++i0 < dp.size) { sb.append("V") } return } if (dp[i0][j0 + 1] >= k) { // if k is smaller than the first dp[i][j+1] solutions, then we should go right sb.append("H") helper(dp, i0, j0 + 1, k, sb) } else { // else we go down, and we should also minus the first dp[i][j+1] solutions from k sb.append("V") helper(dp, i0 + 1, j0, k - dp[i0][j0 + 1], sb) } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,188
kotlab
Apache License 2.0
Retos/Reto #4 - PRIMO, FIBONACCI Y PAR [Media]/kotlin/wakicode.kt
mouredev
581,049,695
false
{"Python": 3866914, "JavaScript": 1514237, "Java": 1272062, "C#": 770734, "Kotlin": 533094, "TypeScript": 457043, "Rust": 356917, "PHP": 281430, "Go": 243918, "Jupyter Notebook": 221090, "Swift": 216751, "C": 210761, "C++": 164758, "Dart": 159755, "Ruby": 70259, "Perl": 52923, "VBScript": 49663, "HTML": 45912, "Raku": 44139, "Scala": 30892, "Shell": 27625, "R": 19771, "Lua": 16625, "COBOL": 15467, "PowerShell": 14611, "Common Lisp": 12715, "F#": 12710, "Pascal": 12673, "Haskell": 11051, "Assembly": 10368, "Elixir": 9033, "Visual Basic .NET": 7350, "Groovy": 7331, "PLpgSQL": 6742, "Clojure": 6227, "TSQL": 5744, "Zig": 5594, "Objective-C": 5413, "Apex": 4662, "ActionScript": 3778, "Batchfile": 3608, "OCaml": 3407, "Ada": 3349, "ABAP": 2631, "Erlang": 2460, "BASIC": 2340, "D": 2243, "Awk": 2203, "CoffeeScript": 2199, "Vim Script": 2158, "Brainfuck": 1550, "Prolog": 1342, "Crystal": 783, "Fortran": 778, "Solidity": 560, "Standard ML": 525, "Scheme": 457, "Vala": 454, "Limbo": 356, "xBase": 346, "Jasmin": 285, "Eiffel": 256, "GDScript": 252, "Witcher Script": 228, "Julia": 224, "MATLAB": 193, "Forth": 177, "Mercury": 175, "Befunge": 173, "Ballerina": 160, "Smalltalk": 130, "Modula-2": 129, "Rebol": 127, "NewLisp": 124, "Haxe": 112, "HolyC": 110, "GLSL": 106, "CWeb": 105, "AL": 102, "Fantom": 97, "Alloy": 93, "Cool": 93, "AppleScript": 85, "Ceylon": 81, "Idris": 80, "Dylan": 70, "Agda": 69, "Pony": 69, "Pawn": 65, "Elm": 61, "Red": 61, "Grace": 59, "Mathematica": 58, "Lasso": 57, "Genie": 42, "LOLCODE": 40, "Nim": 38, "V": 38, "Chapel": 34, "Ioke": 32, "Racket": 28, "LiveScript": 25, "Self": 24, "Hy": 22, "Arc": 21, "Nit": 21, "Boo": 19, "Tcl": 17, "Turing": 17}
import kotlin.math.pow import kotlin.math.sqrt /* * Escribe un programa que, dado un número, compruebe y muestre si es primo, fibonacci y par. * Ejemplos: * - Con el número 2, nos dirá: "2 es primo, fibonacci y es par" * - Con el número 7, nos dirá: "7 es primo, no es fibonacci y es impar" */ fun main(args: Array<String>) { println( isPrimeOrFibOrEven(2)) println( isPrimeOrFibOrEven(7)) } fun isPrimeOrFibOrEven(number: Int): String { val f1 = (1 + sqrt(5.0))/2 val f2 = (1 - sqrt(5.0))/2 val isPrime = number > 1 && (3..sqrt(number.toDouble()).toInt()).map{it}.all { number % it > 0 } val isFibbonacci = (0 until number).any { ((f1.pow(it) - f2.pow(it)) / (f1-f2)).toInt() == it } val isEven = number % 2 == 0 val prime = "$number ${if (isPrime) "es" else "no es"} primo" val fibonnaci = "${if (isFibbonacci) "es" else "no es"} fibonnaci" val even = if (isEven) "es par" else "es impar" return "$prime, $fibonnaci y $even" }
4
Python
2,929
4,661
adcec568ef7944fae3dcbb40c79dbfb8ef1f633c
993
retos-programacion-2023
Apache License 2.0
mps-analyser/src/main/kotlin/nl/dslconsultancy/mps/analyser/usageAnalysis.kt
dslmeinte
131,405,227
false
null
package nl.dslconsultancy.mps.analyser import nl.dslconsultancy.mps.analyser.util.CountingMap import nl.dslconsultancy.mps.analyser.util.asCsvRow import nl.dslconsultancy.mps.analyser.util.combine import nl.dslconsultancy.mps.analyser.util.csvRowOf import nl.dslconsultancy.mps.analyser.xml.* /* * CountingMap is keyed with a fully-qualified name of a concept or a feature. * We don't key on MetaConceptXml or MetaFeatureXml because we're currently not 100% * sure that their .id's are always the same for the same FQname. */ fun usage(mpsProjectOnDisk: MpsProjectOnDisk): CountingMap<String> { val pathsModelFiles = mpsProjectOnDisk.mpsFiles.filter { mpsFileType(it) == MpsFileType.Model } val modelFiles = pathsModelFiles.map { modelXmlFromDisk(it) } // provide 0 counts for all concepts and their features from own, imported languages, not just (non-0 counts for) the used ones: val namesAllImportedLanguages = modelFiles.flatMap { mf -> mf.namesImportedLanguages() }.distinct() val namesOwnImportedLanguages = mpsProjectOnDisk.languages.map { it.name }.intersect(namesAllImportedLanguages) val ownImportedLanguages = namesOwnImportedLanguages.flatMap { n -> mpsProjectOnDisk.languages.filter { l -> l.name == n } } val allStructureOfOwnImportedLanguages = ownImportedLanguages.flatMap { l -> l.structure().concepts().flatMap { concept -> val fqPrefix = "${l.name}.${concept.name}" (concept.features.map { f -> "$fqPrefix#${f.name}" }) + fqPrefix } }.map { it to 0 }.toMap() // FIXME this is not so helpful for languages that are not part of the project! return modelFiles .map { usage(it) } .reduce { l, r -> l.combine(r) } .combine(allStructureOfOwnImportedLanguages) } private fun usage(modelXml: ModelXml): CountingMap<String> { val metaConcepts = modelXml.metaConcepts() val allNodes = modelXml.nodes.flatMap { it.allNodes() } val result = hashMapOf<String, Int>() // count occurrences of concepts: allNodes.map { it.concept } .groupingBy { it } .eachCount() .map { (key, value) -> metaConcepts.byIndex(key).name.withoutStructurePathFragment() to value }.toMap(result) // count occurrences of features (i.e., the role that a node plays): listOf(allNodes.mapNotNull { it.role }) .flatten() .groupingBy { it } .eachCount() .map { (key, value) -> val featureByIndex = metaConcepts.featureByIndex(key) "${featureByIndex.second.name.withoutStructurePathFragment()}#${featureByIndex.first.name}" to value }.toMap(result) return result } private fun String.withoutStructurePathFragment(): String = this.replace(".structure", "") fun CountingMap<String>.asCsvLines(mpsProjectOnDisk: MpsProjectOnDisk): Iterable<String> = listOf(csvRowOf("concept(#feature)", "\"number of usages\"")) + entries .sortedBy { it.key } .map { it.asRow(mpsProjectOnDisk.languages).asCsvRow() } private fun Map.Entry<String, Int>.asRow(languages: List<Language>): Iterable<String> { val parts = key.split('#') val index = parts[0].lastIndexOf('.') val languageName = parts[0].substring(0, index) val elementName = parts[0].substring(index + 1) val elements = languages .filter { l -> l.name == languageName } .flatMap { l -> l.structure().concepts().filter { e -> e.name == elementName } } if (elements.isEmpty()) { return listOf(key, value.toString(), "?") } val thing = if (parts.size == 1) elements.first() else elements.first().features.find { f -> f.name == parts[1]}!! return listOf(key, value.toString(), thing.deprecated.toString()) }
2
JetBrains MPS
2
10
17b3014ebb78cb299844d8b8c284557f30ee211b
3,759
mps-open-source
MIT License
src/Day10.kt
papichulo
572,669,466
false
{"Kotlin": 16864}
import kotlin.math.absoluteValue fun main() { val taps = intArrayOf(20, 60, 100, 140, 180, 220) fun convertToIntList(input: List<String>): List<Int> { return buildList { add(1) // starts with 1 input.forEach { line -> add(0) if (line.startsWith("addx")) { add(line.substringAfter(" ").toInt()) } } } } fun part1(input: List<String>): Int { val valueList = convertToIntList(input).runningReduce(Int::plus) return taps.sumOf { valueList[it - 1] * it } } fun part2(input: List<String>) { convertToIntList(input).runningReduce(Int::plus) .mapIndexed { index, i -> (i-(index%40)).absoluteValue <= 1 } .windowed(40, 40, false) .forEach { row -> row.forEach { pixel -> print(if(pixel) '#' else '.') } println() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput) == 13140) part2(testInput) val input = readInput("Day10") println(part1(input)) part2(input) }
0
Kotlin
0
0
e277ee5bca823ce3693e88df0700c021e9081948
1,273
aoc-2022-in-kotlin
Apache License 2.0
marathons/icpcchallenge/y2020_huaweiGraphMining/practice/b.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package marathons.icpcchallenge.y2020_huaweiGraphMining.practice import java.io.* import kotlin.random.Random private fun solve(edges: List<List<Int>>): BooleanArray { val n = edges.flatten().maxOrNull()!! + 1 val nei = List(n) { mutableListOf<Int>() } for ((u, v) in edges) { nei[u].add(v); nei[v].add(u) } val r = Random(566) @Suppress("unused") fun greedy() { val set = BooleanArray(n) val add = IntArray(n) { r.nextInt(n) } for (u in nei.indices.sortedBy { nei[it].size * n + add[it] }) { set[u] = nei[u].none { set[it] } } } val status = IntArray(n) { 2 } val s = 64 val deg = IntArray(n) { nei[it].size * s + r.nextInt(s) } val byDeg = List(deg.maxOrNull()!! + 1) { mutableSetOf<Int>() } for (u in nei.indices) byDeg[deg[u]].add(u) while (true) { val u = byDeg.firstOrNull { it.isNotEmpty() }?.first() ?: break byDeg[deg[u]].remove(u) status[u] = 1 for (v in nei[u]) { if (status[v] < 2) continue status[v] = 0 byDeg[deg[v]].remove(v) for (w in nei[v]) { if (status[w] < 2) continue byDeg[deg[w]].remove(w) deg[w] -= s byDeg[deg[w]].add(w) } } } return BooleanArray(n) { status[it] == 1 } } fun main() { for (test in 1..4) { val filename = "b$test" val input = BufferedReader(FileReader("$filename.in")) val output = PrintWriter("$filename.out") fun readLn() = input.readLine() fun readStrings() = readLn().split(" ") fun readInts() = readStrings().map { it.toInt() } val (_, m) = readInts() val edges = List(m) { readInts().map { it - 1 } } val ans = solve(edges).map { if (it) 1 else 0 } output.println(ans.sum()) output.println(ans.joinToString(" ")) output.close() } }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,675
competitions
The Unlicense
src/main/kotlin/d10/d10.kt
LaurentJeanpierre1
573,454,829
false
{"Kotlin": 118105}
package d10 import readInput fun part1(input: List<String>): Int { var X = 1 var cycle = 0 var sum = 0 var counted = 0 for (line in input) { if (cycle> counted && ((cycle-20) % 40) == 0) { sum += cycle * X println("Signal $cycle = ${cycle * X}" ) counted = cycle } if (line == "noop") { cycle += 1 } else if (line.startsWith("addx")) { val delta = line.substring(5).toInt() cycle += 2 val rem = (cycle - 20) % 40 if ((rem) in 0 .. 2) { val trueCycle = cycle - rem if (trueCycle> counted) { sum += trueCycle * X println("Signal $trueCycle = ${trueCycle * X}") counted = trueCycle } } X += delta } println("Cycle $cycle - X=$X") if (cycle>221) break } return sum } fun part2(input: List<String>): Int { var X = 1 var cycle = 0 for (line in input) { print(X, cycle) if (line == "noop") { cycle += 1 } else if (line.startsWith("addx")) { val delta = line.substring(5).toInt() cycle += 1 print(X, cycle) cycle += 1 X += delta } cycle = (cycle%40) } return 0 } private fun print(X: Int, cycle: Int) { val trueCycle = (cycle) % 40 if (X in trueCycle - 1..trueCycle + 1) { print("#") } else print(".") if (cycle==39) { println() } } fun main() { //val input = readInput("d10/test") val input = readInput("d10/input1") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5cf6b2142df6082ddd7d94f2dbde037f1fe0508f
1,768
aoc2022
Creative Commons Zero v1.0 Universal
src/main/kotlin/days/Day24.kt
andilau
573,139,461
false
{"Kotlin": 65955}
package days import days.Point.Companion.EAST import days.Point.Companion.NORTH import days.Point.Companion.SOUTH import days.Point.Companion.WEST import java.util.concurrent.ConcurrentHashMap @AdventOfCodePuzzle( name = "<NAME>", url = "https://adventofcode.com/2022/day/2", date = Date(day = 24, year = 2022) ) class Day24(input: List<String>) : Puzzle { private val walls = input.extract('#') private val max = Point(walls.maxOf { it.x }, walls.maxOf { it.y }) private val cycles = (max.x - 1) * (max.y - 1) private val start = openingsIn(0) ?: error("No start found") private val exit = openingsIn(max.y) ?: error("No exit found") private fun openingsIn(y: Int) = (0..max.x).map { x -> Point(x, y) }.firstOrNull { it !in walls } private val blizzardsWest = input.extract('<') private val blizzardsEast = input.extract('>') private val blizzardsNorth = input.extract('^') private val blizzardsSouth = input.extract('v') private val obstacles = ConcurrentHashMap<Int, Set<Point>>() override fun partOne() = solve(listOf(start), exit).lastIndex override fun partTwo() = solve(solve(solve(listOf(start), exit), start), exit).lastIndex private fun solve(path: List<Point>, goal: Point): List<Point> { data class State(val current: Point, val time: Int) val queue = ArrayDeque<List<Point>>().apply { add(path) } val seen = mutableSetOf<State>() while (queue.isNotEmpty()) { val route: List<Point> = queue.removeFirst() if (route.last() == goal) return route val state = State(route.last(), route.size % cycles) if (state in seen) continue seen += state val obstacle = obstacles.getOrPut(route.size % cycles) { computeObstacles(route.size) } route.last().neighboursAndSelf() .filter { it.y in 0..max.y } .filter { it !in obstacle } .forEach { queue += (route + it) } } error("Path not found") } private fun computeObstacles(time: Int): Set<Point> = walls + blizzardsWest.move(time, WEST, max) + blizzardsEast.move(time, EAST, max) + blizzardsNorth.move(time, NORTH, max) + blizzardsSouth.move(time, SOUTH, max) private fun Set<Point>.move(round: Int, vector: Point, max: Point) = map { it + round * vector } .map { Point((it.x - 1).mod(max.x - 1) + 1, (it.y - 1).mod(max.y - 1) + 1) } .toSet() }
0
Kotlin
0
0
da824f8c562d72387940844aff306b22f605db40
2,562
advent-of-code-2022
Creative Commons Zero v1.0 Universal
src/Day22.kt
p357k4
573,068,508
false
{"Kotlin": 59696}
fun main() { fun part1(input: String): Long { val data = input.split("\n\n") val path = data[1] val lines = data[0].lines() val rows = lines.size val columns = lines.maxOf { it.length } val map = lines.map { it.toCharArray() + CharArray(columns - it.length) { ' ' } }.toTypedArray() var row = 0 var column = map[row].indexOf('.') var dirColumn = 1 var dirRow = 0 var steps = 0 var angle = 0 fun go() { var nextColumn = column var nextRow = row while (steps > 0) { nextColumn = (nextColumn + dirColumn).mod(columns) nextRow = (nextRow + dirRow).mod(rows) val next = map[nextRow][nextColumn] if (next == ' ') { continue } if (next == '#') { break } column = nextColumn row = nextRow steps-- } steps = 0 } for (p in path) { var prevDirColumn = dirColumn var prevDirRow = dirRow when (p) { 'R' -> { go() angle = (angle + 1).mod(4) dirColumn = -prevDirRow dirRow = prevDirColumn } 'L' -> { go() angle = (angle - 1).mod(4) dirColumn = prevDirRow dirRow = -prevDirColumn } in '0'..'9' -> { steps = 10 * steps + (p - '0') } } } go() return 1000L*(row + 1) + 4 * (column + 1) + angle } fun part2(input: String): Long { return 0L } // test if implementation meets criteria from the description, like: val testInputExample = readText("Day22_example") check(part1(testInputExample) == 6032L) check(part2(testInputExample) == 0L) val testInput = readText("Day22_test") println(part1(testInput)) println(part2(testInput)) }
0
Kotlin
0
0
b9047b77d37de53be4243478749e9ee3af5b0fac
2,210
aoc-2022-in-kotlin
Apache License 2.0
solutions/aockt/y2023/Y2023D08.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.y2023 import aockt.util.math.lcm import aockt.util.parse import io.github.jadarma.aockt.core.Solution object Y2023D08 : Solution { /** * A node in the desert map. * @property id The ID of this node. * @property leftId The ID of the node reached if navigating leftward. * @property rightId The ID of the node reached if navigating rightward. */ private data class Node(val id: String, val leftId: String, val rightId: String) /** * A ghost's map for navigating the Desert Island and avoid sandstorms. * @property nodes The nodes on the map, indexed by their [Node.id]. * @property instructions The directions given on the map, deciding how to navigate. */ private class DesertGhostMap(private val nodes: Map<String, Node>, private val instructions: String) { /** From the given node, at the given [step], decide which is the next visited node. */ private fun Node.next(step: Int): Node = when (instructions[step % instructions.length]) { 'L' -> nodes.getValue(leftId) 'R' -> nodes.getValue(rightId) else -> error("Impossible state.") } /** * Navigate from a [start]ing node to a [destination], and return the steps required to reach it, or -1 if it * could not be determined. */ private fun navigate(start: Node, destination: (Node) -> Boolean): Int { var node = start var step = 0 while (destination(node).not()) { if (step < 0) return -1 node = node.next(step) step += 1 } return step } /** * Calculates the total steps needed to reach a node safe from sandstorms if traversing as a ghost. * Since we are mere mortals, we make assumptions about the desert map in order to have any hope to * compete with a ghost. If these assumptions don't hold, you're on your own. * Returns the answer, or -1 if we cannot determine the correct path. */ fun navigateAsGhost(): Long { fun navigateAsSuperpositionComponent(start: Node): Int { var node = start val result = navigate(node) { it.id.endsWith('Z') } // Check assumption that the step cycle will keep yielding destination nodes. if (result.times(2).rem(instructions.length) != 0) return -1 for (i in 0..<result) node = node.next(i) return if (node.id.endsWith('Z')) result else -1 } return nodes.values .filter { it.id.endsWith('A') } .map(::navigateAsSuperpositionComponent) .onEach { if (it == -1) return -1 } .lcm() } /** * Returns in how many steps will a human be able to navigate from `AAA` to `ZZZ` by following the directions * on the map, or -1 if such a path cannot be determined. */ fun navigateAsHuman(): Int { val start = nodes["AAA"] ?: return -1 return navigate(start) { it.id == "ZZZ" } } } /** Parse the [input] and return the [DesertGhostMap]. */ private fun parseInput(input: String): DesertGhostMap = parse { val nodeRegex = Regex("""^(\w{3}) = \((\w{3}), (\w{3})\)$""") val instructionRegex = Regex("""^[LR]+$""") val directions = input.substringBefore('\n') require(directions.matches(instructionRegex)) { "Invalid instruction set." } val nodes = input .lineSequence() .drop(2) .map { line -> nodeRegex.matchEntire(line)!!.destructured } .map { (id, left, right) -> Node(id, left, right) } .associateBy { it.id } DesertGhostMap(nodes, directions) } override fun partOne(input: String) = parseInput(input).navigateAsHuman() override fun partTwo(input: String) = parseInput(input).navigateAsGhost() }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
4,061
advent-of-code-kotlin-solutions
The Unlicense
src/day16.kt
miiila
725,271,087
false
{"Kotlin": 77215}
import java.io.File import kotlin.system.exitProcess private const val DAY = 16 fun main() { if (!File("./day${DAY}_input").exists()) { downloadInput(DAY) println("Input downloaded") exitProcess(0) } val transformer = { x: String -> x.toList() } val input = loadInput(DAY, false, transformer) // println(input) println(solvePart1(input)) println(solvePart2(input)) } data class Beam(val x: Int, val y: Int, val heading: Char) // Part 1 private fun solvePart1(grid: List<List<Char>>): Int { return solve(grid, Beam(0, 0, 'E')) } // Part 2 private fun solvePart2(grid: List<List<Char>>): Int { val beams = mutableSetOf<Beam>() for (x in (0..<grid[0].count())) { beams.add(Beam(x, 0, 'S')) beams.add(Beam(x, grid.count() - 1, 'N')) } for (y in (0..<grid.count())) { beams.add(Beam(0, y, 'E')) beams.add(Beam(grid[0].count() - 1, y, 'W')) } return beams.maxOf { solve(grid, it) } } fun solve(grid: List<List<Char>>, start: Beam): Int { val visited = mutableSetOf<Beam>() val queue = mutableListOf(start) while (queue.isNotEmpty()) { val beam = queue.removeFirst() visited.add(beam) val next = getNextDirection(beam, grid[beam.y][beam.x]) for (n in next) { if (n.x >= 0 && n.x < grid[0].count() && n.y >= 0 && n.y < grid.count() && n !in visited) { queue.add(n) } } } return visited.map { Pair(it.x, it.y) }.toSet().count() } fun getNextDirection(beam: Beam, pos: Char): List<Beam> { val newHeading = when (pos) { '|' -> when (beam.heading) { in (listOf('E', 'W')) -> "NS" else -> beam.heading.toString() } '-' -> when (beam.heading) { in (listOf('N', 'S')) -> "EW" else -> beam.heading.toString() } '/' -> when (beam.heading) { 'N' -> "E" 'S' -> "W" 'E' -> "N" 'W' -> "S" else -> error("BOOM") } '\\' -> when (beam.heading) { 'N' -> "W" 'S' -> "E" 'E' -> "S" 'W' -> "N" else -> error("BOOM") } else -> beam.heading.toString() } return newHeading.map { when (it) { 'N' -> Beam(beam.x, beam.y - 1, it) 'S' -> Beam(beam.x, beam.y + 1, it) 'E' -> Beam(beam.x + 1, beam.y, it) 'W' -> Beam(beam.x - 1, beam.y, it) else -> error("BOOM") } } }
0
Kotlin
0
1
1cd45c2ce0822e60982c2c71cb4d8c75e37364a1
2,709
aoc2023
MIT License
src/Day05.kt
lsimeonov
572,929,910
false
{"Kotlin": 66434}
fun main() { fun part1(input: List<String>): String { val stacks = mutableListOf<ArrayDeque<Char>>() var totalIndex = 0 run collectStack@{ input.toList().forEach { totalIndex++ var stackIndex = 0 it.chunked(4).forEach { stackInput -> val d = stacks.getOrElse(stackIndex) { ArrayDeque() } if (stackInput[1].toString().isNotBlank()) { if (stackInput[1].toString().toIntOrNull() != null) { // WE collected the stack now work with it return@collectStack } d.add(stackInput[1]) } if (stacks.indices.contains(stackIndex)) { stacks[stackIndex] = d } else { stacks.add(stackIndex, d) } stackIndex++ } } } val r = Regex("move\\s(\\d+)\\sfrom\\s(\\d+)\\sto\\s(\\d+)") input.toList().subList(totalIndex, input.size).forEach { val result = r.find(it) if (result != null) { val (amount, from, to) = result.destructured var total = amount.toInt() while (total > 0) { stacks[to.toInt() - 1].addFirst(stacks[from.toInt() - 1].removeFirst()) total-- } } } return stacks.fold("".toCharArray()) { acc, s -> acc.plus(s.first()) }.joinToString("") } fun part2(input: List<String>): String { val stacks = mutableListOf<ArrayDeque<Char>>() var totalIndex = 0 run collectStack@{ input.toList().forEach { totalIndex++ var stackIndex = 0 it.chunked(4).forEach { stackInput -> val d = stacks.getOrElse(stackIndex) { ArrayDeque() } if (stackInput[1].toString().isNotBlank()) { if (stackInput[1].toString().toIntOrNull() != null) { // WE collected the stack now work with it return@collectStack } d.add(stackInput[1]) } if (stacks.indices.contains(stackIndex)) { stacks[stackIndex] = d } else { stacks.add(stackIndex, d) } stackIndex++ } } } val r = Regex("move\\s(\\d+)\\sfrom\\s(\\d+)\\sto\\s(\\d+)") input.toList().subList(totalIndex, input.size).forEach { it -> val result = r.find(it) if (result != null) { val (amount, from, to) = result.destructured var total = amount.toInt() val extracted = mutableListOf<Char>() while (total > 0) { extracted.add(stacks[from.toInt() - 1].removeFirst()) total-- } extracted.reversed().forEach { ch -> stacks[to.toInt() - 1].addFirst(ch) } } } return stacks.fold("".toCharArray()) { acc, s -> acc.plus(s.first()) }.joinToString("") } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") check(part2(testInput) == "MCD") val input = readInput("Day05") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
9d41342f355b8ed05c56c3d7faf20f54adaa92f1
3,704
advent-of-code-2022
Apache License 2.0
src/main/kotlin/days/Day3.kt
andilau
726,429,411
false
{"Kotlin": 37060}
package days @AdventOfCodePuzzle( name = "<NAME>", url = "https://adventofcode.com/2023/day/3", date = Date(day = 3, year = 2023) ) class Day3(private val schematic: List<String>) : Puzzle { private val numberRegex = """\d+""".toRegex() override fun partOne(): Int = schematic.flatMapIndexed() { y, line -> numberRegex.findAll(line).map { val isPartNumber: Boolean = schematic .slice((y - 1).coerceAtLeast(0)..(y + 1).coerceAtMost(schematic.lastIndex)) .any { line -> line.slice((it.range.first - 1).coerceAtLeast(0)..(it.range.last + 1).coerceAtMost(line.lastIndex)) .any { it !in "0123456789." } } if (isPartNumber) it.value.toInt() else 0 } }.sum() override fun partTwo(): Int = schematic.flatMapIndexed() { lineNumber, line -> numberRegex.findAll(line).flatMap { matchResult -> ((lineNumber - 1).coerceAtLeast(0)..(lineNumber + 1).coerceAtMost(schematic.lastIndex)) .map { IndexedValue(it, schematic[it]) } .mapNotNull { (y, line) -> ((matchResult.range.first - 1).coerceAtLeast(0)..(matchResult.range.last + 1).coerceAtMost(line.lastIndex)) .firstNotNullOfOrNull { x -> if (line[x] == '*') Pair(x, y) else null } ?.let { it to matchResult.value.toInt() } }.toList() } } .groupBy({ it.first }, { it.second }) .filterValues { it.size == 2 } .values.sumOf { it[0] * it[1] } }
3
Kotlin
0
0
9a1f13a9815ab42d7fd1d9e6048085038d26da90
1,728
advent-of-code-2023
Creative Commons Zero v1.0 Universal
kotlin/src/com/s13g/aoc/aoc2021/Day3.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2021 import com.s13g.aoc.Result import com.s13g.aoc.Solver import com.s13g.aoc.resultFrom /** * --- Day 3: Binary Diagnostic --- * https://adventofcode.com/2021/day/3 */ class Day3 : Solver { override fun solve(lines: List<String>): Result { val ge = lines[0].indices.map { i -> lines.fold(Counter(0, 0)) { cnt, s -> cnt.add(s[i]) } } .fold(GammaEpsi("", "")) { res, cnt -> res.add(cnt) } val partA = ge.g.toInt(2) * ge.e.toInt(2) val partB = processB(lines, 0 /* Most common */) * processB(lines, 1 /* Least common */) return resultFrom(partA, partB) } private fun processB(lines: List<String>, mostLeastIdx: Int): Int { val ratingValues = lines.toCollection(mutableListOf()) for (i in lines[0].indices) { val cnt = ratingValues.fold(Counter(0, 0)) { cnt, s -> cnt.add(s[i]) } for (l in ratingValues.toCollection(mutableListOf())) { if (l[i] != cnt.hiLow()[mostLeastIdx] && ratingValues.size > 1) ratingValues.remove(l) } } return ratingValues[0].toInt(2) } private data class GammaEpsi(val g: String, val e: String) { fun add(cnt: Counter) = cnt.hiLow().let { GammaEpsi(this.g + it[0], this.e + it[1]) } } private data class Counter(val zeros: Int, val ones: Int) { fun add(c: Char) = if (c == '0') Counter(this.zeros + 1, this.ones) else Counter(this.zeros, this.ones + 1) fun hiLow() = if (this.zeros > this.ones) listOf('0', '1') else listOf('1', '0') } }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
1,507
euler
Apache License 2.0
src/week2/PalindromicSubstrings.kt
anesabml
268,056,512
false
null
package week2 import kotlin.math.min import kotlin.system.measureNanoTime class PalindromicSubstrings { /** Center expanding * Iterate over all the palindromic centers and expand * Time complexity : O(n2) * Space complexity : O(1) */ fun countSubstrings(s: String): Int { val length = s.length var ans = 0 for (center in 0 until 2 * length) { var left = center / 2 var right = left + center % 2 while (left >= 0 && right < length && s[left] == s[right]) { ans++ left-- right++ } } return ans } /** Dynamic programming * Time complexity : O(n2) * Space complexity : O(1) */ fun countSubstringsDP(s: String): Int { val length = s.length var ans = 0 val dp = Array(length) { BooleanArray(length) } for (i in s.indices) { for (j in i downTo 0) { dp[i][j] = s[i] == s[j] && (i - j < 3 || dp[i - 1][j + 1]) if (dp[i][j]) { ans++ } } } return ans } /** Manacher's Algorithm * Time complexity : O(n2) * Space complexity : O(1) */ fun countSubstringsManacher(s: String): Int { var chars = CharArray(2 * s.length + 3) chars[0] = '@' chars[1] = '#' chars[chars.size - 1] = '$' var t = 2 s.forEachIndexed { index, c -> chars[t++] = c chars[t++] = '#' } /*val stringBuilder = StringBuilder() stringBuilder.append('@') stringBuilder.append('#') s.forEach { c -> stringBuilder.append(c) stringBuilder.append('#') } stringBuilder.append('$') val str = stringBuilder.toString()*/ var center = 0 var right = 0 val length = chars.size val plen = IntArray(length) for (i in 1 until length - 1) { val mirror = 2 * center - i if (i < right) { plen[i] = min(right - i, plen[mirror]) } while (chars[i - (1 + plen[i])] == chars[i + (1 + plen[i])]) { plen[i]++ } if (i + plen[i] > right) { center = i right = i + plen[i] } } return plen.reduce { acc, i -> acc + (i + 1) / 2 } } } fun main() { val input = "aaaa" val palindromicSubstrings = PalindromicSubstrings() val firstSolutionTime = measureNanoTime { println(palindromicSubstrings.countSubstrings(input)) } val secondSolutionTime = measureNanoTime { println(palindromicSubstrings.countSubstringsDP(input)) } val thirdSolutionTime = measureNanoTime { println(palindromicSubstrings.countSubstringsManacher(input)) } println("First Solution execution time: $firstSolutionTime") println("Second Solution execution time: $secondSolutionTime") println("Third Solution execution time: $thirdSolutionTime") }
0
Kotlin
0
1
a7734672f5fcbdb3321e2993e64227fb49ec73e8
3,102
leetCode
Apache License 2.0
src/day18/Day18.kt
idle-code
572,642,410
false
{"Kotlin": 79612}
package day18 import logEnabled import readInput private const val DAY_NUMBER = 18 data class Position3D(val x: Int, val y: Int, val z: Int) { val neighbours: Sequence<Position3D> get() { return sequenceOf( Position3D(x + 1, y, z), Position3D(x - 1, y, z), Position3D(x, y + 1, z), Position3D(x, y - 1, z), Position3D(x, y, z + 1), Position3D(x, y, z - 1), ) } companion object { fun parse(line: String): Position3D { val (x, y, z) = line.split(',') return Position3D(x.toInt(), y.toInt(), z.toInt()) } } operator fun minus(other: Position3D): Position3D { return Position3D(x - other.x, y - other.y, z - other.z) } operator fun plus(other: Position3D): Position3D { return Position3D(x + other.x, y + other.y, z + other.z) } } class PointCloud { private val voxelSet = mutableSetOf<Position3D>() val positions: Sequence<Position3D> = voxelSet.asSequence() private val visitedSet = mutableSetOf<Position3D>() fun add(position: Position3D) { voxelSet.add(position) } fun remove(position: Position3D) { voxelSet.remove(position) } fun boundingBox(): Pair<Position3D, Position3D> { val minX = voxelSet.minOf { it.x } val minY = voxelSet.minOf { it.y } val minZ = voxelSet.minOf { it.z } val maxX = voxelSet.maxOf { it.x } val maxY = voxelSet.maxOf { it.y } val maxZ = voxelSet.maxOf { it.z } return Pair(Position3D(minX, minY, minZ), Position3D(maxX, maxY, maxZ)) } fun calculateSurfaceArea(): Int { var totalFreeSides = 0 for (voxel in voxelSet) { for (neighbour in voxel.neighbours) { if (neighbour !in voxelSet) ++totalFreeSides } } return totalFreeSides } fun visitConnectedTo(position: Position3D) { val toVisit = ArrayDeque(listOf(position)) while (toVisit.isNotEmpty()) { val visited = toVisit.removeFirst() if (visitedSet.add(visited)) toVisit.addAll(visited.neighbours.filter { n -> n in voxelSet && n !in visitedSet }) } } fun removeUnvisited() { val unvisitedPositions = positions.filter { it !in visitedSet }.toList() voxelSet.removeAll(unvisitedPositions.toSet()) } } private fun Pair<Position3D, Position3D>.calculateSurfaceArea(): Int { val min = this.first val max = this.second + Position3D(1, 1, 1) check(max.x > min.x) check(max.y > min.y) check(max.z > min.z) val xSide = (max.z - min.z) * (max.y - min.y) val ySide = (max.z - min.z) * (max.x - min.x) val zSide = (max.x - min.x) * (max.y - min.y) return 2 * (xSide + ySide + zSide) } fun main() { fun part1(rawInput: List<String>): Int { val pointCloud = PointCloud() val points = rawInput.map { Position3D.parse(it) } for (point in points) pointCloud.add(point) return pointCloud.calculateSurfaceArea() } fun part2(rawInput: List<String>): Int { val positivePointCloud = PointCloud() val points = rawInput.map { Position3D.parse(it) } for (point in points) positivePointCloud.add(point) // Calculate bounding box var (minPosition, maxPosition) = positivePointCloud.boundingBox() val margin = 1 val unitVector = Position3D(margin, margin, margin) minPosition -= unitVector maxPosition += unitVector // Fill negative cloud val negativePointCloud = PointCloud() for (z in minPosition.z..maxPosition.z) { for (y in minPosition.y..maxPosition.y) { for (x in minPosition.x..maxPosition.x) { negativePointCloud.add(Position3D(x, y, z)) } } } // Subtract real cloud from the negative for (point in positivePointCloud.positions) negativePointCloud.remove(point) // Flood fill from the outside and remove negativePointCloud.visitConnectedTo(minPosition) negativePointCloud.removeUnvisited() val negativeArea = negativePointCloud.calculateSurfaceArea() check(Pair(Position3D(-1, -1, -1), Position3D(1, 1, 1)).calculateSurfaceArea() == 9 * 6) val boxArea = Pair(minPosition, maxPosition).calculateSurfaceArea() return negativeArea - boxArea } val sampleInput = readInput("sample_data", DAY_NUMBER) val mainInput = readInput("main_data", DAY_NUMBER) logEnabled = false val part1SampleResult = part1(sampleInput) println(part1SampleResult) check(part1SampleResult == 64) val part1MainResult = part1(mainInput) println(part1MainResult) check(part1MainResult == 4340) val part2SampleResult = part2(sampleInput) println(part2SampleResult) check(part2SampleResult == 58) val part2MainResult = part2(mainInput) println(part2MainResult) check(part2MainResult == 2468) }
0
Kotlin
0
0
1b261c399a0a84c333cf16f1031b4b1f18b651c7
5,204
advent-of-code-2022
Apache License 2.0
src/Day20.kt
Flame239
570,094,570
false
{"Kotlin": 60685}
import kotlin.math.abs import kotlin.math.sign private fun nums(): List<Long> = readInput("Day20").map { it.toLong() } private fun decrypt(nums: List<Long>, mult: Long = 1, times: Int = 1): Long { val n = nums.size val order = nums.mapIndexed { i, v -> V(v * mult, i) } val a = order.toMutableList() repeat(times) { order.forEach { (v, i) -> var diff = (v % (n - 1)).toInt() if (i + diff < 0) diff = n + diff - 1 if (i + diff >= n - 1) diff = diff - n + 1 val ds = diff.sign repeat(abs(diff)) { val j = i + it * ds a.swap(j, j + ds) a[j].ind = j a[j + ds].ind = j + ds } } } val zeroInd = a.indexOfFirst { it.v == 0L } return a[(1000 + zeroInd) % n].v + a[(2000 + zeroInd) % n].v + a[(3000 + zeroInd) % n].v } private fun part1(nums: List<Long>): Long = decrypt(nums) private fun part2(nums: List<Long>): Long = decrypt(nums, 811589153, 10) fun main() { measure { part1(nums()) } measure { part2(nums()) } } private data class V(val v: Long, var ind: Int)
0
Kotlin
0
0
27f3133e4cd24b33767e18777187f09e1ed3c214
1,149
advent-of-code-2022
Apache License 2.0
kotlin/src/com/daily/algothrim/leetcode/easy/MaxAscendingSum.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode.easy import kotlin.math.max /** * 1800.最大升序子数组和 * * 给你一个正整数组成的数组 nums ,返回 nums 中一个 升序 子数组的最大可能元素和。 * * 子数组是数组中的一个连续数字序列。 * * 已知子数组 [numsl, numsl+1, ..., numsr-1, numsr] ,若对所有 i(l <= i < r),numsi < numsi+1 都成立,则称这一子数组为 升序 子数组。注意,大小为 1 的子数组也视作 升序 子数组。 * * 示例 1: * 输入:nums = [10,20,30,5,10,50] * 输出:65 * 解释:[5,10,50] 是元素和最大的升序子数组,最大元素和为 65 。 * * 示例 2: * 输入:nums = [10,20,30,40,50] * 输出:150 * 解释:[10,20,30,40,50] 是元素和最大的升序子数组,最大元素和为 150 。 * * 示例 3: * 输入:nums = [12,17,15,13,10,11,12] * 输出:33 * 解释:[10,11,12] 是元素和最大的升序子数组,最大元素和为 33 。 * * 示例 4: * 输入:nums = [100,10,1] * 输出:100 */ class MaxAscendingSum { companion object { @JvmStatic fun main(args: Array<String>) { println( MaxAscendingSum().maxAscendingSum( intArrayOf( 10, 20, 30, 5, 10, 50 ) ) ) println( MaxAscendingSum().maxAscendingSum( intArrayOf( 10, 20, 30, 40, 50 ) ) ) println( MaxAscendingSum().maxAscendingSum( intArrayOf( 12, 17, 15, 13, 10, 11, 12 ) ) ) println( MaxAscendingSum().maxAscendingSum( intArrayOf( 100, 10, 1 ) ) ) } } fun maxAscendingSum(nums: IntArray): Int { var result = nums[0] var dp = nums[0] for (i in 1 until nums.size) { if (nums[i] <= nums[i - 1]) dp = 0 dp += nums[i] result = max(dp, result) } return result } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
2,285
daily_algorithm
Apache License 2.0
kotlin/src/katas/kotlin/hackerrank/roads_and_libraries/RoadsAndLibraries.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.hackerrank.roads_and_libraries import katas.kotlin.hackerrank.OutputRecorder import katas.kotlin.hackerrank.toReadLineFunction import nonstdlib.printed import datsok.shouldEqual import nonstdlib.sumByLong import org.junit.Test import java.io.BufferedReader import java.io.File import java.io.InputStreamReader import java.util.* import kotlin.collections.HashMap class RoadsAndLibrariesTests { /** * https://www.hackerrank.com/challenges/torque-and-development */ fun main(args: Array<String>) { val reader = BufferedReader(InputStreamReader(System.`in`)) main({ reader.readLine() }) } private fun main(readLine: () -> String, writeLine: (Any?) -> Unit = { println(it) }) { val q = readLine().toInt() (1..1).forEach { val split = readLine().split(' ') val citiesCount = split[0].toInt().printed("citiesCount ") val cityLinksCount = split[1].toInt().printed("cityLinksCount ") val libraryCost = split[2].toInt() val roadCost = split[3].toInt() val cities = (0 until cityLinksCount).mapTo(ArrayList(cityLinksCount)) { readLine().split(' ').map { it.toInt() } } writeLine(roadsAndLibraries(citiesCount, libraryCost, roadCost, cities)) } } private fun roadsAndLibraries(citiesCount: Int, libraryCost: Int, roadCost: Int, cityLinks: List<List<Int>>): Long { val graph = Graph<Int>() (1..citiesCount).forEach { graph.addVertex(it) } cityLinks.forEach { graph.addEdge(it[0], it[1]) } return findMinCost(graph, libraryCost, roadCost) } private fun findMinCost(graph: Graph<Int>, libraryCost: Int, roadCost: Int): Long { val components = graph.components() components.size.printed("componentsSize ") return components.sumByLong { component -> val minSpanningTreeEdgesSize = component.vertices.size - 1 val allRoadsCost = minSpanningTreeEdgesSize * roadCost + libraryCost.toLong() val allLibsCost = component.vertices.size * libraryCost.toLong() minOf(allLibsCost, allRoadsCost) } } private fun <T> Graph<T>.minSpanningTree(): List<Edge<T>> { val result = ArrayList<Edge<T>>() val queuedVertices = HashSet<T>().apply { add(vertices.first()) } val queue = LinkedList<T>().apply { add(vertices.first()) } while (queue.isNotEmpty()) { val vertex = queue.removeFirst() edgesByVertex[vertex]?.forEach { edge -> if (queuedVertices.add(edge.to)) { result.add(edge) queue.add(edge.to) } } } return result } private data class Edge<T>(var from: T, var to: T, var weight: Int? = null) { override fun toString(): String { val weightString = if (weight != null) ", $weight" else "" return "Edge($from->$to$weightString)" } } private data class Graph<T>(val edgesByVertex: MutableMap<T, MutableList<Edge<T>>?> = HashMap()) { val vertices: Set<T> get() = edgesByVertex.keys fun addEdge(from: T, to: T) { edgesByVertex.getOrPut(from, { ArrayList() })!!.add(Edge(from, to)) edgesByVertex.getOrPut(to, { ArrayList() })!!.add(Edge(to, from)) } fun addVertex(vertex: T) { edgesByVertex[vertex] = null } companion object { fun readInts(s: String): Graph<Int> = read(s) { it.toInt() } fun <T> read(s: String, parse: (String) -> T): Graph<T> { val graph = Graph<T>() s.split(",").forEach { token -> val split = token.split("-") if (split.size == 2) { graph.addEdge(from = parse(split[0]), to = parse(split[1])) } else { graph.addVertex(parse(split[0])) } } return graph } } } private fun <T> Graph<T>.components(): List<Graph<T>> { val result = ArrayList<Graph<T>>() val graphByVertex = HashMap<T, Graph<T>>() vertices.forEach { vertex -> var graph = graphByVertex[vertex] if (graph == null) { graph = Graph() result.add(graph) graphByVertex[vertex] = graph } val neighbourEdges = edgesByVertex[vertex] graph.edgesByVertex[vertex] = neighbourEdges neighbourEdges?.forEach { (_, to) -> graphByVertex[to] = graph } } return result } @Test fun `example from problem description`() { val graph = Graph.readInts("1-2,1-3,1-7,2-3,5-6,6-8") findMinCost(graph, libraryCost = 3, roadCost = 2) shouldEqual 16 } @Test fun `sample test case 0`() { findMinCost(Graph.readInts("1-2,2-3,3-1"), libraryCost = 2, roadCost = 1) shouldEqual 4 findMinCost(Graph.readInts("1-3,3-4,2-4,1-2,2-3,5-6"), libraryCost = 2, roadCost = 5) shouldEqual 12 } @Test fun `sample test case 1`() { findMinCost(Graph.readInts("1-2,1-3,4-5,4-6"), libraryCost = 2, roadCost = 3) shouldEqual 12 } @Test fun `sample test case 2`() { findMinCost(Graph.readInts("1-2,1-3,1-4,5"), libraryCost = 6, roadCost = 1) shouldEqual 15 } @Test fun `test case 2`() { val readLine = File("src/katas/kotlin/hackerrank/roads_and_libraries/test-case2.txt").inputStream().toReadLineFunction() val outputRecorder = OutputRecorder() main(readLine, outputRecorder) outputRecorder.text.trim() shouldEqual """ 5649516 5295483 9261576 3960530 7629795 40216260 6701050 40280315 4614540 12407190 """.trimIndent() } @Test fun `test case 3`() { val readLine = File("src/katas/kotlin/hackerrank/roads_and_libraries/test-case3.txt").inputStream().toReadLineFunction() val outputRecorder = OutputRecorder() main(readLine, outputRecorder) outputRecorder.text.trim() shouldEqual """ 7850257285 6785201034 813348013 4211840970 8610471142 7263742960 4331105640 1226092626 7288635830 8276704464 """.trimIndent() } @Test fun `test case 4`() { val readLine = File("src/katas/kotlin/hackerrank/roads_and_libraries/test-case4.txt").inputStream().toReadLineFunction() val outputRecorder = OutputRecorder() main(readLine, outputRecorder) outputRecorder.text.trim() shouldEqual """ 9234981465 5854508506 7754252297 8085193494 9504556779 8011172848 9123393445 7326423794 8259748808 8049633228 """.trimIndent() } }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
7,148
katas
The Unlicense
src/Day06.kt
greeshmaramya
514,310,903
false
{"Kotlin": 8307}
fun main() { fun day06(data: List<String>) { var part1 = 0 var part2 = 0 val h = HashMap<Char, Int>() val ans = data.joinToString(",").split(",,").map { it.split(',') } ans.forEach { group -> if (group.size == 1) { part1 += group.first().length part2 += group.first().length } else { group.forEach { it.forEach { c -> h[c] = h.getOrDefault(c, 0) + 1 } } part1 += h.size part2 += h.filter { it.value == group.size }.size } h.clear() } println(part1) println(part2) } /* ------------- Alternate Solution ------------- */ fun day06AlternateP1(data: List<String>) { var c = 0 val modifiedData = data.joinToString(",").split(",,").map { it.replace(",", "") } modifiedData.forEach { c += it.toSet().size } println(c) } fun day06AlternateP2(data: List<String>) { var c = 0 val ans = data.joinToString(",").split(",,").map { it.split(',') } ans.forEach { if (it.size == 1) { c += it.first().length } else { var s = it[0].toSet() for (j in it) { s = s.intersect(j.toSet()) } c += s.size } } println(c) } val testInput = readInput("Day06Test") val input = readInput("Day06") day06(testInput) day06(input) day06AlternateP1(testInput) day06AlternateP1(input) day06AlternateP2(testInput) day06AlternateP2(input) }
0
Kotlin
0
0
9e1128ee084145f5a70fe3ad4e71b05944260d6e
1,665
aoc2020
Apache License 2.0
2021/src/Day11.kt
Bajena
433,856,664
false
{"Kotlin": 65121, "Ruby": 14942, "Rust": 1698, "Makefile": 454}
import java.util.* // https://adventofcode.com/2021/day/11 fun main() { class Table(cols: Int, rows: Int, numbers: Array<Int>) { val cols = cols val rows = rows var numbers = numbers var fired = mutableSetOf<Int>() var toFire = mutableSetOf<Int>() fun step() : Int { // 1. Increment all by 1 and collect indices of non fired > 9 // 2. While there are non fired, > 9 for each of them do: // 2. a) Set to 0 // 2. b) Mark as fired // 2. c) Bump neighbors by 1 and collect their indices if > 9 and not fired // 3. Mark all as not fired printMe() fired.clear() toFire.clear() var newNumbers = numbers.toMutableList().toTypedArray() numbers.forEachIndexed { index, value -> val newValue = value + 1 newNumbers[index] = newValue if (newValue > 9) { toFire.add(index) } } numbers = newNumbers printMe() while (toFire.isNotEmpty()) { toFire.forEach { index -> numbers[index] = 0 fired.add(index) } printMe() var newToFire = mutableSetOf<Int>() toFire.forEach { index -> getNeighbours(index).forEach { neighbour -> if (!fired.contains(neighbour.first)) { val newValue = neighbour.second + 1 numbers[neighbour.first] = newValue if (newValue > 9) { newToFire.add(neighbour.first) } } } } toFire = newToFire } printMe() return fired.size } // Returns list of pairs of <Index, Value> fun getNeighbours(index : Int) : List<Pair<Int, Int>> { val point = indexToPoint(index) val x = point.first val y = point.second return listOf( Pair(x - 1, y - 1), Pair(x, y - 1), Pair(x + 1, y - 1), Pair(x - 1, y), Pair(x + 1, y), Pair(x - 1, y + 1), Pair(x, y + 1), Pair(x + 1, y + 1), ).filter { it.first >= 0 && it.first < cols && it.second >= 0 && it.second < rows }.map { Pair(pointToIndex(it.first, it.second), get(it.first, it.second)!!) } } fun pointToIndex(x : Int, y : Int) : Int { return y * cols + x } fun indexToPoint(index : Int) : Pair<Int, Int> { return Pair(index % cols, index / cols) } fun get(x : Int, y : Int) : Int? { return numbers.elementAtOrNull(y * cols + x) } fun printMe() { numbers.forEachIndexed { index, v -> if (index % cols == 0) { println("") print("${index / rows }: ") } if (fired.contains(index)) { print(" ^$v^ ") } else print(" $v ") } println() } } fun part1() { val numbers = mutableListOf<Int>() var cols = -1 var rows = 0 for (line in readInput("Day11")) { cols = line.length rows++ numbers.addAll(line.split("").filter { it.isNotEmpty() }.map { it.toInt() }) } val t = Table(cols, rows, numbers.toTypedArray()) var result = 0 for (i in 1..100) result += t.step() println(result) } fun part2() { val numbers = mutableListOf<Int>() var cols = -1 var rows = 0 for (line in readInput("Day11")) { cols = line.length rows++ numbers.addAll(line.split("").filter { it.isNotEmpty() }.map { it.toInt() }) } val t = Table(cols, rows, numbers.toTypedArray()) var stepCount = 0 var step = 0 while (step < numbers.size) { stepCount++ step = t.step() } println("Step count:$stepCount") } part1() part2() }
0
Kotlin
0
0
a5ca56b7ac8d9d48f82dc079c8ea0cf06d17109a
3,704
advent-of-code
Apache License 2.0