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/day22.kt | gautemo | 572,204,209 | false | {"Kotlin": 78294} | import shared.Point
import shared.getText
fun main() {
val input = getText("day22.txt")
println(day22A(input))
println(day22B(input))
}
fun day22A(input: String): Int {
val board = Board(input)
board.followInstructions()
return board.password()
}
fun day22B(input: String): Int {
val board = Board(input, true)
board.followInstructions()
return board.password()
}
private class Board(input: String, val cubeMode: Boolean = false) {
var instructions = input.lines().last()
private val map = mutableMapOf <Point, Char>()
var on = Point(input.lines()[0].indexOfFirst { it == '.' }, 0)
val facing = Facing()
init {
for(y in 0 until input.lines().size-2) {
for(x in 0 until input.lines()[y].length) {
map[Point(x, y)] = input.lines()[y][x]
}
}
}
fun followInstructions() {
while (instructions.isNotEmpty()) {
val command = instructions.takeWhile { it != 'R' && it != 'L' }.ifEmpty { instructions.take(1) }
instructions = instructions.removePrefix(command)
when(command) {
"R" -> facing.turnR()
"L" -> facing.turnL()
else -> {
repeat(command.toInt()) {
val topY = map.filter { it.key.x == on.x && it.value != ' ' }.minOf { it.key.y }
val bottomY = map.filter { it.key.x == on.x && it.value != ' ' }.maxOf { it.key.y }
val lefX = map.filter { it.key.y == on.y && it.value != ' ' }.minOf { it.key.x }
val rightX = map.filter { it.key.y == on.y && it.value != ' ' }.maxOf { it.key.x }
when(facing.dir) {
'R' -> next(1, 0, Point(lefX, on.y))
'D' -> next(0, 1, Point(on.x, topY))
'L' -> next(-1, 0, Point(rightX, on.y))
else -> next(0, -1, Point(on.x, bottomY))
}
}
}
}
}
}
private fun setOn(point: Point, newDir: Char? = null) {
if(map[point] == '.') {
on = point
newDir?.let { facing.dir = it }
}
}
private fun next(xDir: Int, yDir: Int, warpTo: Point) {
val next = Point(on.x+xDir, on.y+yDir)
if(map[next] == null || map[next] == ' ') {
if(cubeMode) cubeTurn(next) else setOn(warpTo)
} else {
setOn(next)
}
}
fun password() = 1000 * (on.y+1) + 4 * (on.x+1) + facing.value
private fun cubeTurn(to: Point) {
when {
to.x == 150 -> {
setOn(Point(99, 149 - to.y), 'L')
}
to.x == 49 && (0..49).contains(to.y) -> {
setOn(Point(0, 149-to.y), 'R')
}
to.y == -1 && (50..99).contains(to.x) -> {
setOn(Point(0, 100 + to.x), 'R')
}
to.y == -1 && (100..149).contains(to.x) -> {
setOn(Point(to.x - 100, 199), 'U')
}
to.x == 49 && (50..99).contains(to.y) -> {
setOn(Point(to.y-50, 100), 'D')
}
to.x == 100 && (50..99).contains(to.y) -> {
setOn(Point(50 + to.y, 49), 'U')
}
to.y == 50 && (100..149).contains(to.x) -> {
setOn(Point(99, to.x - 50), 'L')
}
to.y == 99 && (0..49).contains(to.x) -> {
setOn(Point(50, to.x + 50), 'R')
}
to.x == -1 && (100..149).contains(to.y) -> {
setOn(Point(50, 149 - to.y), 'R')
}
to.x == 100 && (100..149).contains(to.y) -> {
setOn(Point(149, 49 - (to.y - 100)), 'L')
}
to.y == 150 && (50..99).contains(to.x) -> {
setOn(Point(49, to.x + 100), 'L')
}
to.x == -1 && (150..199).contains(to.y) -> {
setOn(Point(to.y - 100, 0), 'D')
}
to.x == 50 && (150..199).contains(to.y) -> {
setOn(Point(to.y - 100, 149), 'U')
}
to.y == 200 -> {
setOn(Point(to.x + 100, 0), 'D')
}
}
}
}
private class Facing {
var dir = 'R'
val value: Int
get(){
return when(dir) {
'R' -> 0
'D' -> 1
'L' -> 2
else -> 3
}
}
fun turnR() {
dir = when(dir) {
'R' -> 'D'
'D' -> 'L'
'L' -> 'U'
else -> 'R'
}
}
fun turnL() {
dir = when(dir) {
'R' -> 'U'
'D' -> 'R'
'L' -> 'D'
else -> 'L'
}
}
} | 0 | Kotlin | 0 | 0 | bce9feec3923a1bac1843a6e34598c7b81679726 | 4,876 | AdventOfCode2022 | MIT License |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions34.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.special
import kotlin.math.min
fun test34() {
printlnResult(arrayOf("offer", "is", "coming"), "abcdefghijklmnopqrstuvwxyz".reversed())
}
/**
* Questions 34: Judge if a group of words is sorted by a new alphabet
*/
private infix fun Array<String>.isSorted(alphabet: String): Boolean {
require(isNotEmpty()) { "The array can't be empty" }
require(alphabet.length == 26) { "The alphabet is illegal" }
if (size == 1)
return true
val alphabetMap = IntArray(26)
alphabet.forEachIndexed { i, c ->
alphabetMap[c.code - 97] = i
}
var index = 1
while (index < size) {
val word = this[index]
val preWord = this[index - 1]
if (!isBefore(preWord, word, alphabetMap)) {
return false
}
index++
}
return true
}
private fun isBefore(a: String, b: String, alphabetMap: IntArray): Boolean {
var index = 0
val shortLength = min(a.length, b.length)
while (index < shortLength) {
val ca = a[index]
val cb = b[index]
when {
alphabetMap[ca.code - 97] < alphabetMap[cb.code - 97] -> return true
alphabetMap[ca.code - 97] > alphabetMap[cb.code - 97] -> return false
else -> index++
}
}
return a.length <= b.length
}
private fun printlnResult(words: Array<String>, alphabet: String) =
println("Is statement ${words.toList()} arranged by alphabet $alphabet: ${words isSorted alphabet}") | 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 1,501 | Algorithm | Apache License 2.0 |
year2023/day05/part2/src/main/kotlin/com/curtislb/adventofcode/year2023/day05/part2/Year2023Day05Part2.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | /*
--- Part Two ---
Everyone will starve if you only plant such a small number of seeds. Re-reading the almanac, it
looks like the seeds: line actually describes ranges of seed numbers.
The values on the initial seeds: line come in pairs. Within each pair, the first value is the start
of the range and the second value is the length of the range. So, in the first line of the example
above:
```
seeds: 79 14 55 13
```
This line describes two ranges of seed numbers to be planted in the garden. The first range starts
with seed number 79 and contains 14 values: 79, 80, ..., 91, 92. The second range starts with seed
number 55 and contains 13 values: 55, 56, ..., 66, 67.
Now, rather than considering four seed numbers, you need to consider a total of 27 seed numbers.
In the above example, the lowest location number can be obtained from seed number 82, which
corresponds to soil 84, fertilizer 84, water 84, light 77, temperature 45, humidity 46, and location
46. So, the lowest location number is 46.
Consider all of the initial seed numbers listed in the ranges on the first line of the almanac. What
is the lowest location number that corresponds to any of the initial seed numbers?
*/
package com.curtislb.adventofcode.year2023.day05.part2
import com.curtislb.adventofcode.year2023.day05.almanac.Almanac
import java.nio.file.Path
import java.nio.file.Paths
/**
* Returns the solution to the puzzle for 2023, day 5, part 2.
*
* @param inputPath The path to the input file for this puzzle.
* @param sourceCategory The category of the initial values to be converted.
* @param destCategory The target category to which the values should be converted.
*/
fun solve(
inputPath: Path = Paths.get("..", "input", "input.txt"),
sourceCategory: String = "seed",
destCategory: String = "location"
): Long {
val (values, almanac) = Almanac.parseFile(inputPath.toFile())
val ranges = values.windowed(size = 2, step = 2) { it[0]..<(it[0] + it[1]) }.toSet()
val destRanges = almanac.convertRanges(ranges, sourceCategory, destCategory)
return destRanges.minOf { it.first }
}
fun main() {
println(solve())
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 2,145 | AdventOfCode | MIT License |
src/main/kotlin/year2022/Day24.kt | forketyfork | 572,832,465 | false | {"Kotlin": 142196} | package year2022
import utils.Direction
import utils.Direction.*
import utils.Point2D
import utils.lcm
class Day24(contents: String) {
data class Blizzard(val position: Point2D, val direction: Direction)
data class State(val step: Int, val position: Point2D)
private val lines = contents.lines()
private val width = lines.first().length
private val height = lines.size
private val entrance = Point2D(1, 0)
private val exit = Point2D(width - 2, height - 1)
private val blizzardPeriod = (width - 2).lcm(height - 2)
private val blizzardsByStep = mapOf(
0 to lines.flatMapIndexed { row, line ->
line.withIndex().filter { it.value in Direction.ARROWS }.map { (col, char) ->
Point2D(col, row) to listOf(Blizzard(Point2D(col, row), Direction.byArrow(char)))
}
}.toMap()
).toMutableMap()
fun part1() = solve(State(0, entrance), exit)
fun part2() = listOf(entrance, exit, entrance, exit)
.windowed(2)
.fold(0) { step, (from, to) -> solve(State(step, from), to) }
private fun solve(initialState: State, destination: Point2D): Int = with(ArrayDeque(setOf(initialState))) {
val seenStates = mutableMapOf<Point2D, MutableSet<Int>>()
while (!isEmpty()) {
val state = removeFirst()
if (state.position == destination) {
return state.step - 1
}
if (seenStates.getOrPut(state.position) { mutableSetOf() }.add(state.step % blizzardPeriod)) {
val nextBlizzards = blizzardsByStep.computeIfAbsent(state.step % blizzardPeriod) {
blizzardsByStep[state.step % blizzardPeriod - 1]!!.values.flatMap { blizzards ->
blizzards.map { blizzard ->
val nextPosition = blizzard.position.move(blizzard.direction).let {
if (it.x == width - 1) {
it.copy(x = 1)
} else if (it.x == 0) {
it.copy(x = width - 2)
} else if (it != exit && it.y == height - 1 || it == exit) {
it.copy(y = 1)
} else if (it != entrance && it.y == 0 || it == entrance) {
it.copy(y = height - 2)
} else {
it
}
}
nextPosition to blizzard.copy(position = nextPosition)
}
}.groupBy({ it.first }, { it.second }).toMap()
}
sequenceOf(DOWN, LEFT, UP, RIGHT)
.map { dir -> state.position.move(dir) }
.filter {
it == entrance || it == exit || it.x in (1..width - 2) && it.y in (1..height - 2)
}
.plus(state.position)
.filter { !nextBlizzards.keys.contains(it) }
.forEach { nextPosition -> addLast(State(state.step + 1, nextPosition)) }
}
}
error("Solution not found")
}
}
| 0 | Kotlin | 0 | 0 | 5c5e6304b1758e04a119716b8de50a7525668112 | 3,278 | aoc-2022 | Apache License 2.0 |
2019/task_10/src/main/kotlin/task_10/App.kt | romanthekat | 52,710,492 | false | {"Go": 90415, "Kotlin": 74230, "Python": 57300, "Nim": 22698, "Ruby": 7404, "Rust": 1516, "Crystal": 967} | package task_10
import java.io.File
import java.lang.Integer.max
import java.lang.Integer.min
class App {
fun solveFirst(input: List<String>): Int {
val map = Map(input)
var (_, asteroids) = map.getBestLocation()
return asteroids.size
}
fun solveSecond(input: List<String>): Int {
return -1
}
}
class Map(input: List<String>) {
var map = mutableListOf<List<Int>>()
var asteroids = mutableListOf<Point>()
init {
for ((y, line) in input.withIndex()) {
val row = mutableListOf<Int>()
for ((x, value) in line.withIndex()) {
val fieldValue = value.getFieldValue()
if (fieldValue.isAsteroid()) {
asteroids.add(Point(x, y))
}
row.add(fieldValue)
}
map.add(row)
}
}
fun getBestLocation(): Pair<Point, List<Point>> {
var bestPosition = Point(0, 0)
var bestVisibleAsteroids = listOf<Point>()
//TODO use channels
for (asteroid in asteroids) {
val visibleAsteroids = getVisibleAsteroids(asteroid, asteroids)
if (visibleAsteroids.size > bestVisibleAsteroids.size) {
bestPosition = asteroid
bestVisibleAsteroids = visibleAsteroids
}
}
return Pair(bestPosition, bestVisibleAsteroids)
}
private fun getVisibleAsteroids(asteroid: Point, asteroids: MutableList<Point>): List<Point> {
val visibleAsteroids = mutableListOf<Point>()
for (asteroidToCheck in asteroids) {
if (asteroid == asteroidToCheck) {
continue
}
if (hiddenByAsteroids(asteroids, asteroid, asteroidToCheck)) {
continue
}
visibleAsteroids.add(asteroidToCheck)
}
return visibleAsteroids
}
private fun hiddenByAsteroids(asteroids: MutableList<Point>, fromPoint: Point, toPoint: Point): Boolean {
for (asteroid in asteroids) {
if (fromPoint != asteroid && toPoint != asteroid
&& isOnSegment(asteroid, fromPoint, toPoint)) {
return true
}
}
return false
}
fun isOnSegment(point: Point, lineStart: Point, lineEnd: Point): Boolean {
val isOnLine = ((lineStart.y - lineEnd.y) * point.x
+ (lineEnd.x - lineStart.x) * point.y
+ (lineStart.x * lineEnd.y - lineEnd.x * lineStart.y) == 0)
if (!isOnLine) {
return false
}
return point.x > min(lineStart.x, lineEnd.x) && point.x < max(lineStart.x, lineEnd.x)
&& point.y > min(lineStart.y, lineEnd.y) && point.y < max(lineStart.y, lineEnd.y)
}
fun Char.getFieldValue(): Int {
return when (this) {
'.' -> 0
'#' -> 1
else -> throw RuntimeException("unknown value of '$this'")
}
}
fun Int.isAsteroid(): Boolean {
return this == 1
}
data class Point(val x: Int, val y: Int)
}
fun main() {
val app = App()
val input = File("input.txt").readLines()
println(app.solveFirst(input))
println(app.solveSecond(input))
} | 4 | Go | 0 | 0 | f410f71c3ff3e1323f29898c1ab39ad6858589bb | 3,273 | advent_of_code | MIT License |
src/jvmMain/kotlin/day15/initial/Day15.kt | liusbl | 726,218,737 | false | {"Kotlin": 109684} | package day15.initial
import util.add
import util.removeAt
import util.set
import java.io.File
fun main() {
// solvePart1() // Solution: 507769, time: 9:18
solvePart2() // Solution: 269747, time: 23:12
}
fun solvePart2() {
val input = File("src/jvmMain/kotlin/day15/input/input.txt")
// val input = File("src/jvmMain/kotlin/day15/input/input_part2_test.txt")
val line = input.readLines()[0]
val lensList = line.split(",").map(::Lens)
val boxList = BoxList()
lensList.forEachIndexed { index, lens ->
boxList.update(lens)
println("Finished iteration: $index, boxList: \n${boxList}")
println()
}
println("Final")
println(boxList)
println()
val result = boxList.value.mapIndexed { index, box ->
val boxNumber = index + 1
box.lensList.mapIndexed { slotIndex, lens ->
val slotNumber = slotIndex + 1
boxNumber * slotNumber * (lens.focalLength as FocalLength.Available).value
}.sum()
}.sum()
println(result)
}
class BoxList {
val value = Array(256) { Box(emptyList()) }
fun update(lens: Lens) {
when (lens.focalLength) {
is FocalLength.Available -> {
val box = value[lens.boxIndex!!]
val boxLensWithIndex = box.lensList.withIndex().find { (_, boxLens) -> boxLens.name == lens.name }
val newLensList = if (boxLensWithIndex == null) {
// Add lens
box.lensList.add(lens)
} else {
// Replace lens
val (boxLens, boxLensIndex) = boxLensWithIndex.value to boxLensWithIndex.index
box.lensList.set(boxLensIndex, lens)
}
value[lens.boxIndex] = Box(newLensList)
}
FocalLength.None -> {
// val box = value[lens.boxIndex!!]
val boxWithIndex = value.withIndex()
.find { (_, box) -> box.lensList.find { boxLens -> boxLens.name == lens.name } != null }
if (boxWithIndex == null) {
// Do nothing
// box.lensList
} else {
// Remove lens
val boxIndex = boxWithIndex.index
val box = value[boxIndex]
val lensIndex = box.lensList.withIndex().find { (_, boxLens) -> boxLens.name == lens.name }!!
val newLensList = box.lensList.removeAt(lensIndex.index)
value[boxIndex] = Box(newLensList)
}
}
}
}
override fun toString(): String =
value.withIndex()
.filterNot { !it.value.lensList.isNotEmpty() }
.joinToString("\n") { indexedBox ->
val box = indexedBox.value
box.lensList.joinToString(",") { lens -> "${lens.name}=${(lens.focalLength as FocalLength.Available).value}" }
}
// override fun toString(): String {
// return value.withIndex()
// .fold("") { acc, indexedValue ->
// if (indexedValue.value.lensList.isEmpty()) {
// acc
// } else {
// val box = indexedValue.value
// box.lensList.joinToString(", ") { lens ->
// when(lens.focalLength) {
// is FocalLength.Available -> "${lens.name}=${lens.focalLength.value}"
// FocalLength.None -> error("Should not have empty lens. lens: $lens, lensList: ${box.lensList}")
// }
// } + "; Box #${indexedValue.index}" + "\n"
// }
// }
//// .joinToString("\n") { (index, box) -> box.lensList.joinToString(", ") + "; Box #$index" }
// }
}
data class Box(
val lensList: List<Lens>
)
fun Lens(text: String): Lens {
val focalLength = FocalLength(text)
val (name, boxIndex) = when (focalLength) {
is FocalLength.Available -> {
val name = text.split("=")[0]
name to name.fold(0) { acc, next -> ((acc + next.code) * 17) % 256 }
}
FocalLength.None -> {
text.dropLast(1) to null
}
}
return Lens(
name = name,
focalLength = focalLength,
boxIndex = boxIndex
)
}
data class Lens(
val name: String,
val focalLength: FocalLength,
val boxIndex: Int?
)
fun FocalLength(text: String): FocalLength =
if (text.contains("=")) {
FocalLength.Available(text.split("=")[1].toInt())
} else {
FocalLength.None
}
sealed interface FocalLength {
data class Available(val value: Int) : FocalLength
object None : FocalLength
}
fun solvePart1() {
// val input = File("src/jvmMain/kotlin/day15/input/input_part2_test.txt")
val input = File("src/jvmMain/kotlin/day15/input/input.txt")
val lines = input.readLines()[0]
val res = lines.split(",").map { value ->
value.fold(0) { acc, next ->
((acc + next.code) * 17) % 256
}
}
println(res.sum())
} | 0 | Kotlin | 0 | 0 | 1a89bcc77ddf9bc503cf2f25fbf9da59494a61e1 | 5,166 | advent-of-code | MIT License |
src/2022/Day01.kt | bartee | 575,357,037 | false | {"Kotlin": 26727} | fun main() {
fun groupCaloryListPerElf(input: List<String>): HashMap<Int, Int> {
// Every line is an amount of calories carried by an elf
// Every blank line indicates a new elf.
var res = 0
var iterator = 0
var resultset = HashMap<Int, Int>()
var counter = 0
input.map {
if (it.isNullOrEmpty()) {
res = 0
iterator++
} else {
res = res + it.toInt()
}
resultset.set(iterator, res)
counter++
}
return resultset
}
fun part1(input: List<String>): Int {
var resultset = groupCaloryListPerElf(input).values
return resultset.max()
}
fun part2(input: List<String>): Int {
var resultset = groupCaloryListPerElf(input).values
return resultset.sortedDescending().subList(0,3).sum()
}
// test if implementation meets criteria from the description, like:
val test_input = readInput("resources/day01_example")
check(part1(test_input) == 24000)
check(part2(test_input) == 45000)
// Calculate the results from the input:
val input = readInput("resources/day01_dataset")
println("Max calories: " + part1(input))
println("Max calories top 3 elves: " +part2(input))
}
| 0 | Kotlin | 0 | 0 | c7141d10deffe35675a8ca43297460a4cc16abba | 1,322 | adventofcode2022 | Apache License 2.0 |
src/day07/Day07.kt | IThinkIGottaGo | 572,833,474 | false | {"Kotlin": 72162} | package day07
import readInput
import java.util.*
fun main() {
fun part1(input: List<String>): Int {
val structure = parseInput(input)
structure.accept(PrintlnContentVisitor())
println("——————————————————————————————————————")
val sizeVisitor = TotalSizeVisitor()
structure.accept(sizeVisitor)
return sizeVisitor.validDirSizes.sum()
}
fun part2(input: List<String>): Int {
val structure = parseInput(input)
val needToFreeSize = 30000000 - (70000000 - structure.size)
val sizeVisitor = FreeSizeVisitor()
structure.accept(sizeVisitor)
var minValidFreeSize = 0
while (sizeVisitor.dirSizes.isNotEmpty()) {
val s = sizeVisitor.dirSizes.poll()
if (s >= needToFreeSize) minValidFreeSize = s
else break
}
return minValidFreeSize
}
val testInput = readInput("day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("day07")
println(part1(input)) // 1723892
println(part2(input)) // 8474158
}
fun parseInput(input: List<String>): Visitable {
var structure: Visitable? = null
lateinit var current: Directory
var name: String
var size: Int
var index = 0
while (index < input.size) {
val line = input[index]
when {
line.startsWith("$ cd") -> {
if (line.contains("..")) {
current = current.parent!!
} else {
name = line.substringAfterLast(" ")
structure?.apply {
current = current.contents.first { it.name == name } as Directory
} ?: run {
current = Directory(name)
structure = current
}
}
++index
}
line.startsWith("$ ls") -> {
var detailsLine = input[++index]
do {
name = detailsLine.substringAfter(" ")
if (detailsLine.startsWith("dir")) {
current.add(Directory(name, current))
} else {
size = detailsLine.substringBefore(" ").toInt()
current.add(File(name, size, current))
}
} while (++index < input.size && !input[index].also { detailsLine = it }.startsWith("$"))
}
else -> error("unknown command!")
}
}
return structure!!
}
interface Visitable {
val name: String
val size: Int
var parent: Directory?
fun accept(visitor: Visitor)
}
interface Visitor {
fun visit(file: File)
fun visit(dir: Directory)
}
data class Directory(
override val name: String,
override var parent: Directory? = null,
) : Visitable {
val contents: MutableList<Visitable> = LinkedList()
override val size: Int by lazy {
contents.sumOf { it.size }
}
override fun accept(visitor: Visitor) {
visitor.visit(this)
}
fun add(visitable: Visitable) {
contents.add(visitable)
}
}
data class File(
override val name: String,
override val size: Int,
override var parent: Directory?,
) : Visitable {
override fun accept(visitor: Visitor) {
visitor.visit(this)
}
}
class PrintlnContentVisitor : Visitor {
var depth = 0
override fun visit(file: File) {
repeat(depth - 2) { print(" ") }
println("└─file (${file.name}, ${file.size})")
}
override fun visit(dir: Directory) {
repeat(depth) { print(" ") }
println("|dir ${dir.name}")
depth += 2
dir.contents.forEach {
it.accept(this)
if (it is Directory) depth -= 2
}
}
}
class TotalSizeVisitor : Visitor {
private val limit = 100000
val validDirSizes = mutableListOf<Int>()
override fun visit(file: File) {
// nothing here
}
override fun visit(dir: Directory) {
dir.contents.forEach {
it.accept(this)
}
val s = dir.size
if (s <= limit) {
validDirSizes.add(s)
}
}
}
class FreeSizeVisitor : Visitor {
val dirSizes = PriorityQueue<Int>(Comparator.reverseOrder())
override fun visit(file: File) {
// nothing here
}
override fun visit(dir: Directory) {
dir.contents.forEach {
it.accept(this)
}
val s = dir.size
dirSizes.offer(s)
}
} | 0 | Kotlin | 0 | 0 | 967812138a7ee110a63e1950cae9a799166a6ba8 | 4,703 | advent-of-code-2022 | Apache License 2.0 |
day18/kotlin/corneil/src/main/kotlin/solution.kt | jensnerche | 317,661,818 | true | {"HTML": 2739009, "Java": 348790, "Kotlin": 271602, "TypeScript": 262310, "Python": 198318, "Groovy": 125347, "Jupyter Notebook": 116902, "C++": 101742, "Dart": 47762, "Haskell": 43633, "CSS": 35030, "Ruby": 27091, "JavaScript": 13242, "Scala": 11409, "Dockerfile": 10370, "PHP": 4152, "C": 3201, "Go": 2838, "Shell": 2651, "Rust": 2082, "Clojure": 567, "Tcl": 46} | package com.github.corneil.aoc2019.day18
import com.github.corneil.aoc2019.common.permutations
import java.io.File
import java.util.*
fun BitSet.copy(extra: BitSet? = null): BitSet {
val result = BitSet(this.size())
result.or(this)
if (extra != null) {
result.or(extra)
}
return result
}
data class Coord(val x: Int, val y: Int) : Comparable<Coord> {
fun left() = copy(x = x - 1)
fun right() = copy(x = x + 1)
fun top() = copy(y = y - 1)
fun bottom() = copy(y = y + 1)
fun surrounds() = listOf(left(), right(), top(), bottom())
override fun compareTo(other: Coord): Int {
var result = x.compareTo(other.x)
if (result == 0) {
result = y.compareTo(other.y)
}
return result
}
override fun toString(): String {
return "Coord($x,$y)"
}
}
data class Cell(val c: Char, val pos: Coord) : Comparable<Cell> {
override fun compareTo(other: Cell): Int {
var result = c.compareTo(other.c)
if (result == 0) {
result = pos.compareTo(other.pos)
}
return result
}
fun isDoor() = c.isLetter() && c.isUpperCase()
fun isKey() = c.isLetter() && c.isLowerCase()
fun isEntrance() = c == '@' || c.isDigit()
fun isWall() = c == '#'
fun toBit(): Int {
return when {
isKey() -> c - 'a'
isDoor() -> c - 'A'
else -> error("Didn't expected to support toBit for $c")
}
}
fun toBitSet(): BitSet {
val result = BitSet()
if (isKey() || isDoor()) {
result.set(toBit())
}
return result
}
fun isFloor(): Boolean {
return c == '.'
}
override fun toString(): String {
return "Cell($c:${pos.x},${pos.y})"
}
}
data class Route(val node: Cell, val distance: Int, val doors: BitSet = BitSet(26)) {
override fun toString(): String {
return "Route(node=$node, distance=$distance, doors=$doors)"
}
fun makeCopy(node: Cell, distance: Int, doors: BitSet? = null): Route {
return Route(node, distance, doors ?: this.doors.copy())
}
}
data class Step(val node: Cell, val distance: Int, val visits: BitSet = BitSet(26)) {
override fun toString(): String {
return "Step(${node.c}, $distance, $visits)"
}
}
data class MultiStep(val nodes: Set<Cell>, val distance: Int, val visits: BitSet = BitSet(26)) {
override fun toString(): String {
return "MultiStep(${nodes.map { it.c }.joinToString(",")}, $distance, $visits)"
}
}
data class Visit(val distance: Int, val doors: BitSet) {
override fun toString(): String {
return "Visit($distance, $doors)"
}
}
data class Grid(val cells: MutableMap<Coord, Cell>) {
fun printToString(): String {
val output = StringBuilder()
val maxX = cells.keys.maxBy { it.x }?.x ?: error("Expected cells")
val maxY = cells.keys.maxBy { it.y }?.y ?: error("Expected cells")
for (y in 0..maxY) {
for (x in 0..maxX) {
output.append(cells[Coord(x, y)]?.c ?: ' ')
}
output.append('\n')
}
return output.toString()
}
}
class World(val grid: Grid) {
private val keys: Set<Cell> = grid.cells.values.filter { it.isKey() }.toSet()
private val doors: Set<Cell> = grid.cells.values.filter { it.isDoor() }.toSet()
private val entrances: Set<Cell> = grid.cells.values.filter { it.isEntrance() }.toSet()
val route = mutableMapOf<Cell, MutableMap<Cell, Visit>>()
init {
createRoute()
}
private fun createRoute() {
val nodes = keys() + entrances()
nodes.forEach { node ->
val queue = ArrayDeque(listOf(Route(node, 0)))
val visited = mutableSetOf(node.pos)
while (queue.isNotEmpty()) {
val current = queue.pop()
current.node.pos.surrounds().mapNotNull {
grid.cells[it]
}.filterNot {
it.isWall()
}.filterNot {
visited.contains(it.pos)
}.forEach { next ->
visited.add(next.pos)
when {
next.isDoor() -> {
val doors = current.doors.copy(next.toBitSet())
queue.add(current.makeCopy(next, current.distance + 1, doors))
}
next.isKey() -> {
val routeMap = route[node] ?: mutableMapOf()
if (routeMap.isEmpty()) {
route[node] = routeMap
}
routeMap[next] = Visit(current.distance + 1, current.doors)
queue.add(current.makeCopy(next, current.distance + 1))
}
next.isEntrance() || next.isFloor() -> {
queue.add(current.makeCopy(next, current.distance + 1))
}
else -> error("Unexpected $next")
}
}
}
}
}
fun keys(): Set<Cell> = keys
fun doors(): Set<Cell> = doors
fun entrances(): Set<Cell> = entrances
fun entrance(): Cell = entrances.first()
}
fun findPath(progress: Boolean, world: World, start: Cell): Int {
val visited = mutableMapOf<Pair<Cell, BitSet>, Int>()
val allVisits = BitSet(world.keys().size)
var visits = 0
world.keys().forEach { allVisits.or(it.toBitSet()) }
println("All Visits:$allVisits")
val combinations = permutations(world.keys().size)
println("Combinations:$combinations")
println("Start:$start")
if (progress) {
println("Routes:")
world.route.forEach { route ->
println("Route:${route.key}")
route.value.forEach { entry ->
print("\t")
println(entry)
}
}
}
val comparator = compareByDescending<Step> { it.visits.cardinality() }.thenBy { it.distance }
val queue = PriorityQueue<Step>(world.keys().size * world.doors().size, comparator)
queue.add(Step(start, 0))
var best = Int.MAX_VALUE
while (queue.isNotEmpty()) {
val step = queue.poll()
if (step.distance >= best) {
continue
}
if (progress) println("Checking $step")
world.route[step.node].orEmpty().asSequence().filterNot { entry ->
// only those we haven't visited yet
val key = entry.key
if (key.isKey()) {
step.visits[key.toBit()]
} else {
false
}.also {
if (progress) println("FilterNot#1:$it = $step -> $entry")
}
}.filter { entry ->
// if door for which we have a key
if (entry.key.isKey()) {
val doors = entry.value.doors.copy()
doors.andNot(step.visits)
if (progress) println("Checking Door ${entry.value.doors} for ${step.visits}")
doors.cardinality() == 0
} else {
true
}.also { if (progress) println("Doors#2:$it = $step -> $entry") }
}.map { entry ->
// Create a new Step
val visits = step.visits.copy(entry.key.toBitSet())
Step(entry.key, entry.value.distance + step.distance, visits)
.also { if (progress) println("Next Step#3:$entry -> $it") }
}.filter { bestStep ->
// Allow where total distance is better than best
val result = bestStep.distance < best
result.also { if (progress) println("Better#4:$it = $step -> $bestStep") }
}.filter { bestStep ->
// where visited is better
val key = Pair(bestStep.node, bestStep.visits)
val result = bestStep.distance < visited[key] ?: Int.MAX_VALUE
result.also { if (progress) println("Filter#5:$it = $step -> $bestStep") }
}.forEach {
visits += 1
val key = Pair(it.node, it.visits)
if (progress) println("Step=$step, Node=$it, Key=$key")
visited[key] = it.distance // record best visit
if (it.visits == allVisits) {
best = minOf(best, it.distance)
if (progress) println("Best=$it, Queue:$queue")
queue.removeIf { step -> step.distance >= best }
} else {
queue.offer(it)
}
if (progress) println("Queue:$queue")
}
}
println("Visits=$visits")
return best
}
data class MultiRoute(val from: Cell, val route: Cell, val visit: Visit)
fun findPathMultipleEntrances(progress: Boolean, world: World, start: Set<Cell>): Int {
val visited = mutableMapOf<Pair<Set<Cell>, BitSet>, Int>()
val allVisits = BitSet(world.keys().size)
var visits = 0
world.keys().forEach { allVisits.or(it.toBitSet()) }
println("All Visits:$allVisits")
val combinations = permutations(world.keys().size)
println("Combinations:$combinations")
println("Start:$start")
if (progress) {
println("Routes:")
world.route.forEach { route ->
println("Route:${route.key}")
route.value.forEach { entry ->
print("\t")
println(entry)
}
}
}
val comparator = compareByDescending<MultiStep> { it.visits.cardinality() }.thenBy { it.distance }
val queue = PriorityQueue<MultiStep>(world.keys().size * world.doors().size, comparator)
queue.add(MultiStep(start, 0))
var best = Int.MAX_VALUE
while (queue.isNotEmpty()) {
val step = queue.poll()
if (step.distance >= best) {
continue
}
if (progress) {
println("Checking $step")
}
step.nodes.flatMap { node ->
world.route[node].orEmpty().map { MultiRoute(node, it.key, it.value) }
}.asSequence().filterNot { entry ->
// only those we haven't visited yet
val key = entry.route
val result = if (key.isKey()) step.visits[key.toBit()] else false
result.also { if (progress) println("FilterNot#1:$it = $step -> $entry") }
}.filter { entry ->
// if door for which we have a key
if (entry.route.isKey()) {
val doors = entry.visit.doors.copy()
doors.andNot(step.visits)
if (progress) println("Checking Door ${entry.visit.doors} for ${step.visits}")
doors.cardinality() == 0
} else {
true
}.also { if (progress) println("Doors#2:$it = $step -> $entry") }
}.map { route ->
// Create a new Step
val visits = step.visits.copy(route.route.toBitSet())
MultiStep(step.nodes - route.from + route.route, route.visit.distance + step.distance, visits).also {
if (progress) println("Next Step#3:$route -> $it")
}
}.filter { bestStep ->
// Allow where total distance is better than best
val result = bestStep.distance < best
result.also { if (progress) println("Better#4:$it = $step -> $bestStep") }
}.filter { bestStep ->
// where visited is better
val key = Pair(bestStep.nodes, bestStep.visits)
val result = bestStep.distance < visited[key] ?: Int.MAX_VALUE
result.also { if (progress) println("Filter#5:$it = $step -> $bestStep") }
}.forEach {
visits += 1
val key = Pair(it.nodes, it.visits)
if (progress) println("Step=$step, Node=$it, Key=$key")
visited[key] = it.distance // record best visit
if (it.visits == allVisits) {
best = minOf(best, it.distance)
if (progress) {
println("Best=$it")
println("Queue:$queue")
}
queue.removeIf { step -> step.distance >= best }
} else {
queue.offer(it)
}
if (progress) {
println("Queue:$queue")
}
}
}
println("Visits=$visits")
return best
}
fun findKeys(progress: Boolean, grid: Grid): Int {
val world = World(grid)
println("Grid:${grid.cells.size}")
var start = world.entrance()
println("Entrance:${world.entrance()}")
val combinations = permutations(world.keys().size)
println("Combinations:$combinations")
val keys = world.keys()
println("Keys:${keys.size}:${keys.map { it.c }.joinToString(", ")}")
val doors = world.doors()
println("Doors:${doors.size}:${doors.map { it.c }.joinToString(", ")}")
println("------------------------------------")
val result = findPath(progress, world, start)
println("=====================")
println("Steps=${result}")
return result
}
fun findKeysMultipleEntrances(progress: Boolean, grid: Grid): Int {
val world = World(grid)
println("Grid:${grid.cells.size}")
var start = world.entrances()
println("Entrances:$start")
val combinations = permutations(world.keys().size)
println("Combinations:$combinations")
val keys = world.keys()
println("Keys:${keys.size}:${keys.map { it.c }.joinToString(", ")}")
val doors = world.doors()
println("Doors:${doors.size}:${doors.map { it.c }.joinToString(", ")}")
println("------------------------------------")
val result = findPathMultipleEntrances(progress, world, start)
println("=====================")
println("Steps=${result}")
return result
}
fun readGrid(input: String): Grid {
var loc = Coord(0, 0)
var cells = mutableMapOf<Coord, Cell>()
input.forEach { c ->
if (c == '\n') {
loc = loc.copy(y = loc.y + 1, x = 0)
} else {
cells[loc] = Cell(c, loc)
loc = loc.copy(x = loc.x + 1)
}
}
return Grid(cells)
}
fun modifyBots(grid: Grid): Grid {
val cells = grid.cells.toMap().toMutableMap()
val entrances = grid.cells.values.filter { it.isEntrance() }.toSet()
require(entrances.size == 1)
val entrance = entrances.first()
cells[entrance.pos] = entrance.copy(c = '#')
entrance.pos.surrounds().forEach {
cells[it] = Cell('#', it)
}
val replacements = mutableListOf<Cell>()
replacements.add(entrance.copy(c = '1', pos = Coord(entrance.pos.x - 1, entrance.pos.y - 1)))
replacements.add(entrance.copy(c = '2', pos = Coord(entrance.pos.x + 1, entrance.pos.y - 1)))
replacements.add(entrance.copy(c = '3', pos = Coord(entrance.pos.x - 1, entrance.pos.y + 1)))
replacements.add(entrance.copy(c = '4', pos = Coord(entrance.pos.x + 1, entrance.pos.y + 1)))
replacements.forEach {
cells[it.pos] = it
}
return Grid(cells)
}
fun main(args: Array<String>) {
val progress = args.toSet().contains("-p")
val input = File("input.txt").readText()
val grid = readGrid(input)
println(grid.printToString())
val distance = findKeys(progress, grid)
println("Distance = $distance")
require(distance == 5068) // ensure refactoring is still working
val grid2 = modifyBots(grid)
println(grid2.printToString())
val distance2 = findKeysMultipleEntrances(progress, grid2)
println("Distance Multiple = $distance2")
require(distance2 == 1966)
}
| 0 | HTML | 0 | 0 | a84c00ddbeb7f9114291125e93871d54699da887 | 15,679 | aoc-2019 | MIT License |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[14]最长公共前缀.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | import java.util.*
//编写一个函数来查找字符串数组中的最长公共前缀。
//
// 如果不存在公共前缀,返回空字符串 ""。
//
//
//
// 示例 1:
//
//
//输入:strs = ["flower","flow","flight"]
//输出:"fl"
//
//
// 示例 2:
//
//
//输入:strs = ["dog","racecar","car"]
//输出:""
//解释:输入不存在公共前缀。
//
//
//
// 提示:
//
//
// 0 <= strs.length <= 200
// 0 <= strs[i].length <= 200
// strs[i] 仅由小写英文字母组成
//
// Related Topics 字符串
// 👍 1616 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun longestCommonPrefix(strs: Array<String>): String {
//最长公共前缀,先排序保证 第一个元素和最后一个元素的第一个字符相等,不相等随后直接返回
//时间复杂度 O(n)
Arrays.sort(strs)
//记录相同的 前缀 index
var index = 0
var first = strs[0]
var last = strs[strs.size-1]
while (index < first.length){
if(first[index] == last[index]){
index++
}else{
break
}
}
return if(index == 0) "" else first.substring(0,index)
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 1,353 | MyLeetCode | Apache License 2.0 |
src/puzzles/day01/Day01.kt | sferjanec | 573,682,195 | false | {"Kotlin": 1962} | package puzzles.day01
import puzzles.readInput
import java.io.File
import java.util.*
fun main() {
fun parseInput(input: String): List<List<Int>> = input.split("\r\n\r\n").map { elf: String ->
elf.lines().map { it.toInt() }
}
// fun List<List<Int>>.topElves(n: Int): Int {
// return map { it.sum() }6
// .sortedDescending()
// .take( n )
// .sum()
// }
//Java version
fun List<List<Int>>.topElves(n: Int): Int {
val best = PriorityQueue<Int>()
for (calories: Int in map { it.sum() }) {
best.add(calories)
if (best.size > n) {
best.poll()
}
}
return best.sum()
}
fun part1(input: String): Int {
val data:List<List<Int>> = parseInput(input)
return data.topElves(1)
}
fun part2(input: String): Int {
val data:List<List<Int>> = parseInput(input)
return data.topElves(3)
}
// test if implementation meets criteria from the description, like:
val testInput = File("src/puzzles/day01/Day01_test.txt").readText()
check(part1(testInput) == 24000 )
val input: String = File("src/puzzles/day01/Day01_test.txt").readText()
println(part1(input))
//println(part2(input))
}
| 0 | Kotlin | 0 | 0 | c4e928719f36d236534a92b059a66b61eef19717 | 1,297 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/util/Coord.kt | aormsby | 425,644,961 | false | {"Kotlin": 68415} | package util
import kotlin.math.abs
import kotlin.math.pow
import kotlin.math.sqrt
data class Coord(
var x: Int,
var y: Int
) {
operator fun plus(c: Coord) = Coord(x = x + c.x, y = y + c.y)
operator fun minus(c: Coord) = Coord(x = x - c.x, y = y - c.y)
/**
* Get adjacent neighbor [Coord] list
*/
fun neighbors(xLimit: Int = -1, yLimit: Int = -1): List<Coord> {
var n = listOf(
Coord(x, y + 1),
Coord(x, y - 1),
Coord(x + 1, y),
Coord(x - 1, y)
)
if (xLimit > -1)
n = n.filter { it.x in 0..xLimit }
if (yLimit > -1)
n = n.filter { it.y in 0..yLimit }
return n
}
/**
* Get adjacent and diagonal neighbor [Coord] list
*/
fun allNeighbors(xLimit: Int = -1, yLimit: Int = -1): List<Coord> {
var n = listOf(
Coord(x - 1, y - 1),
Coord(x - 1, y + 1),
Coord(x + 1, y - 1),
Coord(x + 1, y + 1)
)
if (xLimit > -1)
n = n.filter { it.x in 0..xLimit }
if (yLimit > -1)
n = n.filter { it.y in 0..yLimit }
return neighbors(xLimit, yLimit) + n
}
fun allNeighborsWithSelf(xLimit: Int = -1, yLimit: Int = -1): List<Coord> {
return allNeighbors(xLimit, yLimit) + listOf(Coord(x, y))
}
fun distanceTo(c: Coord): Float = sqrt(
((x - c.x).toFloat()).pow(2) + ((y - c.y).toFloat()).pow(2)
)
fun diffWith(c: Coord): Coord = Coord(c.x - x, c.y - y)
fun opposite(): Coord = Coord(x * -1, y * -1)
override fun toString(): String = "($x, $y)"
}
data class Coord3d(
var x: Int,
var y: Int,
var z: Int
) {
fun distanceTo(c: Coord3d): Float = sqrt(
((x - c.x).toFloat()).pow(2) + ((y - c.y).toFloat()).pow(2) + ((z - c.z).toFloat()).pow(2)
)
fun opposite(): Coord3d = Coord3d(x * -1, y * -1, z * -1)
fun diffWith(c: Coord3d): Coord3d = Coord3d(c.x - x, c.y - y, c.z - z)
operator fun plus(c: Coord3d) = Coord3d(x = x + c.x, y = y + c.y, z = z + c.z)
operator fun minus(c: Coord3d) = Coord3d(x = x - c.x, y = y - c.y, z = z - c.z)
fun manhattanDistanceTo(c: Coord3d): Int =
with(diffWith(c)) {
abs(this.x) + abs(this.y) + abs(this.z)
}
override fun toString(): String = "($x, $y, $z)"
} | 0 | Kotlin | 1 | 1 | 193d7b47085c3e84a1f24b11177206e82110bfad | 2,382 | advent-of-code-2021 | MIT License |
src/Day01.kt | hufman | 573,586,479 | false | {"Kotlin": 29792} | fun main() {
fun parse(input: List<String>): List<List<Int>> {
var elf = ArrayList<Int>()
val elves = ArrayList<List<Int>>().apply { add(elf) }
input.map { it.toIntOrNull() }.forEach {
if (it != null) {
elf.add(it)
} else {
elf = ArrayList()
elves.add(elf)
}
}
return elves
}
fun part1(input: List<String>): Int {
return parse(input).map { it.sum() }.max()
}
fun part2(input: List<String>): Int {
return parse(input).map { it.sum() }.sortedByDescending { it }.take(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1bc08085295bdc410a4a1611ff486773fda7fcce | 886 | aoc2022-kt | Apache License 2.0 |
src/main/kotlin/day10/Day10.kt | qnox | 575,581,183 | false | {"Kotlin": 66677} | package day10
import readInput
fun main() {
fun toSequence(input: List<String>) = sequence {
var register = 1
input.forEach { line ->
if (line.startsWith("noop")) {
yield(register)
} else if (line.startsWith("addx ")) {
val value = line.substring(5).toInt()
yield(register)
yield(register)
register += value
} else {
error("Unknown input $line")
}
}
}
fun part1(input: List<String>): Long {
val sequence = toSequence(input)
return sequence
.mapIndexed { index, i -> (index + 1).toLong() * i }
.filterIndexed { index, _ -> index == 19 || (index - 19) % 40 == 0 }
.sum()
}
fun part2(input: List<String>): String {
val sequence = toSequence(input).iterator()
return (0..5).joinToString(separator = "\n") { row ->
(0..39).joinToString(separator = "") { column ->
val middle = sequence.next()
if (column in middle - 1..middle + 1) {
"#"
} else {
"."
}
}
}
}
val testInput = readInput("day10", "test")
val input = readInput("day10", "input")
check(part1(testInput) == 13140L)
println(part1(input))
println(part2(testInput))
println()
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 727ca335d32000c3de2b750d23248a1364ba03e4 | 1,484 | aoc2022 | Apache License 2.0 |
src/Day19/Day19.kt | Nathan-Molby | 572,771,729 | false | {"Kotlin": 95872, "Python": 13537, "Java": 3671} | package Day19
import readInput
import java.util.Objects
import java.util.PriorityQueue
import kotlin.math.*
data class CombinedCost(val oreCost: Int, val clayCost: Int, val obsidianCost: Int)
data class Blueprint(val oreRobotCost: Int, val clayRobotCost: Int, val obsidianRobotCost: CombinedCost, val geodeRobotCost: CombinedCost) {
var maxGeodesOpened = 0
var statesSeen = hashMapOf<State, Int>()
}
data class State(var minute: Int,
var blueprint: Blueprint,
var oreRobotCount: Int,
var clayRobotCount: Int,
var obsidianRobotCount: Int,
var geodeRobotCount: Int,
var oreCount: Int,
var clayCount: Int,
var obsidianCount: Int,
var geodeCount: Int): Comparable<State> {
override fun compareTo(other: State) = other.minute.compareTo(minute)
override fun hashCode(): Int {
return Objects.hash(minute, oreRobotCount, clayRobotCount, obsidianRobotCount, geodeRobotCount, oreCount, clayCount, obsidianCount, geodeCount)
}
}
class RobotOptimizer(val maxTime: Int) {
var blueprints = mutableListOf<Blueprint>()
var areActionsPossible = hashMapOf<Action, Boolean>(
Action.NOTHING to true,
Action.CREATE_ORE_ROBOT to false,
Action.CREATE_CLAY_ROBOT to false,
Action.CREATE_OBSIDIAN_ROBOT to false,
Action.CREATE_GEODE_ROBOT to false
)
enum class Action {
CREATE_ORE_ROBOT, CREATE_CLAY_ROBOT, CREATE_OBSIDIAN_ROBOT, CREATE_GEODE_ROBOT, NOTHING
}
fun readInput(input: List<String>) {
for (row in input) {
val robotStrings = row.split(".").map { it.split(" ") }
val oreRobotCost = robotStrings[0][6].toInt()
val clayRobotCost = robotStrings[1][5].toInt()
val obsidianOreCost = robotStrings[2][5].toInt()
val obsidianClayCost = robotStrings[2][8].toInt()
val geodeOreCost = robotStrings[3][5].toInt()
val geodeClayCost = robotStrings[3][8].toInt()
blueprints.add(Blueprint(oreRobotCost, clayRobotCost, CombinedCost(obsidianOreCost, obsidianClayCost, 0), CombinedCost(geodeOreCost, 0, geodeClayCost)))
}
}
fun findMaxGeodes() {
// blueprints.parallelStream().forEach { blueprint ->
for (blueprint in blueprints) {
findMaxGeodes(blueprint)
println("blueprint done: " + blueprint.maxGeodesOpened.toString())
}
}
fun findMaxGeodes(blueprint: Blueprint) {
val initialState = State(1, blueprint, 1, 0, 0, 0, 0, 0, 0, 0)
val result = findMaxGeodesNotRecursive(initialState)
blueprint.maxGeodesOpened = result
}
fun findMaxGeodesNotRecursive(initialState: State): Int {
var queue = PriorityQueue<State>()
queue.add(initialState)
while (queue.isNotEmpty()) {
val state = queue.remove()
if (state.blueprint.statesSeen.contains(state)) {
continue
}
val timeRemaining = maxTime - state.minute
val maxPossibleGeodes = state.geodeCount + state.geodeRobotCount * (timeRemaining + 1) + (timeRemaining.toDouble() / 2) * (1 + timeRemaining)
if(state.blueprint.maxGeodesOpened > maxPossibleGeodes) {
continue
}
if (state.minute > maxTime) {
state.blueprint.maxGeodesOpened = max(state.blueprint.maxGeodesOpened, state.geodeCount)
continue
}
areActionsPossible[Action.CREATE_GEODE_ROBOT] = false
areActionsPossible[Action.CREATE_CLAY_ROBOT] = false
areActionsPossible[Action.CREATE_ORE_ROBOT] = false
areActionsPossible[Action.CREATE_OBSIDIAN_ROBOT] = false
val maxOreRequiredPerMinute = max(max(state.blueprint.geodeRobotCost.oreCost, state.blueprint.obsidianRobotCost.oreCost), state.blueprint.clayRobotCost)
val maxClayRequiredPerMinute = state.blueprint.obsidianRobotCost.clayCost
val maxObsidianRequiredPerMinute = state.blueprint.geodeRobotCost.obsidianCost
if (state.oreCount >= state.blueprint.oreRobotCost
&& timeRemaining > state.blueprint.geodeRobotCost.oreCost
&& state.oreRobotCount < maxOreRequiredPerMinute) {
areActionsPossible[Action.CREATE_ORE_ROBOT] = true
}
if (state.oreCount >= state.blueprint.clayRobotCost
&& state.clayRobotCount < maxClayRequiredPerMinute) {
areActionsPossible[Action.CREATE_CLAY_ROBOT] = true
}
if (state.oreCount >= state.blueprint.obsidianRobotCost.oreCost
&& state.clayCount >= state.blueprint.obsidianRobotCost.clayCost
&& state.obsidianRobotCount < maxObsidianRequiredPerMinute) {
areActionsPossible[Action.CREATE_OBSIDIAN_ROBOT] = true
}
if (state.oreCount >= state.blueprint.geodeRobotCost.oreCost && state.obsidianCount >= state.blueprint.geodeRobotCost.obsidianCost) {
areActionsPossible[Action.CREATE_GEODE_ROBOT] = true
}
for (action_possible in areActionsPossible) {
if( !action_possible.value ) { continue }
val action = action_possible.key
var newState = state.copy(minute = state.minute + 1,
oreCount = state.oreCount + state.oreRobotCount,
clayCount = state.clayCount + state.clayRobotCount,
obsidianCount = state.obsidianCount + state.obsidianRobotCount,
geodeCount = state.geodeCount + state.geodeRobotCount
)
when (action) {
Action.NOTHING -> {}
Action.CREATE_ORE_ROBOT -> {
newState.oreCount -= state.blueprint.oreRobotCost
newState.oreRobotCount++
}
Action.CREATE_CLAY_ROBOT -> {
newState.oreCount -= state.blueprint.clayRobotCost
newState.clayRobotCount++
}
Action.CREATE_OBSIDIAN_ROBOT -> {
newState.oreCount -= state.blueprint.obsidianRobotCost.oreCost
newState.clayCount -= state.blueprint.obsidianRobotCost.clayCost
newState.obsidianRobotCount++
}
Action.CREATE_GEODE_ROBOT -> {
newState.oreCount -= state.blueprint.geodeRobotCost.oreCost
newState.obsidianCount -= state.blueprint.geodeRobotCost.obsidianCost
newState.geodeRobotCount++
}
}
queue.add(newState)
}
state.blueprint.statesSeen[state] = 1
}
return initialState.blueprint.maxGeodesOpened
}
fun findMaxGeodesRecursive(state: State): Int {
if (state.minute > maxTime) {
return state.geodeCount
}
if (state.blueprint.statesSeen.contains(state)) {
return state.blueprint.statesSeen[state]!!
}
areActionsPossible[Action.CREATE_GEODE_ROBOT] = false
areActionsPossible[Action.CREATE_CLAY_ROBOT] = false
areActionsPossible[Action.CREATE_ORE_ROBOT] = false
areActionsPossible[Action.CREATE_OBSIDIAN_ROBOT] = false
val timeRemaining = maxTime - state.minute
val maxOreRequiredPerMinute = max(max(state.blueprint.geodeRobotCost.oreCost, state.blueprint.obsidianRobotCost.oreCost), state.blueprint.clayRobotCost)
val maxClayRequiredPerMinute = state.blueprint.obsidianRobotCost.clayCost
val maxObsidianRequiredPerMinute = state.blueprint.geodeRobotCost.obsidianCost
if (state.oreCount >= state.blueprint.oreRobotCost
&& timeRemaining > state.blueprint.geodeRobotCost.oreCost
&& state.oreRobotCount < maxOreRequiredPerMinute) {
areActionsPossible[Action.CREATE_ORE_ROBOT] = true
}
if (state.oreCount >= state.blueprint.clayRobotCost
&& state.clayRobotCount < maxClayRequiredPerMinute) {
areActionsPossible[Action.CREATE_CLAY_ROBOT] = true
}
if (state.oreCount >= state.blueprint.obsidianRobotCost.oreCost
&& state.clayCount >= state.blueprint.obsidianRobotCost.clayCost
&& state.obsidianRobotCount < maxObsidianRequiredPerMinute) {
areActionsPossible[Action.CREATE_OBSIDIAN_ROBOT] = true
}
if (state.oreCount >= state.blueprint.geodeRobotCost.oreCost && state.obsidianCount >= state.blueprint.geodeRobotCost.obsidianCost) {
areActionsPossible[Action.CREATE_GEODE_ROBOT] = true
}
var maxGeodesFromThisState = 0
for (action_possible in areActionsPossible) {
if( !action_possible.value ) { continue }
val action = action_possible.key
// possibleActions.parallelStream().forEach { action ->
var newState = state.copy(minute = state.minute + 1,
oreCount = state.oreCount + state.oreRobotCount,
clayCount = state.clayCount + state.clayRobotCount,
obsidianCount = state.obsidianCount + state.obsidianRobotCount,
geodeCount = state.geodeCount + state.geodeRobotCount
)
when (action) {
Action.NOTHING -> {}
Action.CREATE_ORE_ROBOT -> {
newState.oreCount -= state.blueprint.oreRobotCost
newState.oreRobotCount++
}
Action.CREATE_CLAY_ROBOT -> {
newState.oreCount -= state.blueprint.clayRobotCost
newState.clayRobotCount++
}
Action.CREATE_OBSIDIAN_ROBOT -> {
newState.oreCount -= state.blueprint.obsidianRobotCost.oreCost
newState.clayCount -= state.blueprint.obsidianRobotCost.clayCost
newState.obsidianRobotCount++
}
Action.CREATE_GEODE_ROBOT -> {
newState.oreCount -= state.blueprint.geodeRobotCost.oreCost
newState.obsidianCount -= state.blueprint.geodeRobotCost.obsidianCost
newState.geodeRobotCount++
}
}
maxGeodesFromThisState = max(maxGeodesFromThisState, findMaxGeodesRecursive(newState))
}
state.blueprint.statesSeen[state] = maxGeodesFromThisState
state.blueprint.maxGeodesOpened = max(maxGeodesFromThisState, state.blueprint.maxGeodesOpened)
return maxGeodesFromThisState
}
fun part1(): Int {
return blueprints.withIndex()
.sumOf { (it.index + 1) * it.value.maxGeodesOpened }
}
fun part2(): Int {
return blueprints[0].maxGeodesOpened * blueprints[1].maxGeodesOpened * blueprints[2].maxGeodesOpened
}
}
fun main() {
fun part1(input: List<String>): Int {
val robotOptimizer = RobotOptimizer(24)
robotOptimizer.readInput(input)
robotOptimizer.findMaxGeodes()
return robotOptimizer.part1()
}
fun part2(input: List<String>): Int {
val robotOptimizer = RobotOptimizer(32)
robotOptimizer.readInput(input)
robotOptimizer.findMaxGeodes()
return robotOptimizer.part2()
}
val testInput = readInput("Day19","Day19_test")
// println(part1(testInput))
// check(part1(testInput) == 64)
// println(part2(testInput))
// check(part2(testInput) == 58)
val input = readInput("Day19","Day19")
// println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 750bde9b51b425cda232d99d11ce3d6a9dd8f801 | 11,887 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/cc/stevenyin/algorithms/_02_sorts/_05_MergeSort_BottomUp.kt | StevenYinKop | 269,945,740 | false | {"Kotlin": 107894, "Java": 9565} | package cc.stevenyin.algorithms._02_sorts
import cc.stevenyin.algorithms.RandomType
import cc.stevenyin.algorithms.testSortAlgorithm
import kotlin.math.min
class _05_MergeSort_BottomUp: SortAlgorithm {
override val name: String
get() = "MergeSort_BottomUp"
// 2,3,1,5,3,6,9,8
//
override fun <T : Comparable<T>> sort(array: Array<T>) {
var size = 1
// 对size大小的元素进行归并
while (size < array.size) {
// 对[i, i + size - 1]和[i + size, i + 2 * size - 1]的元素进行归并
var index = 0
while (index < array.size) {
if (index + size < array.size) {
val middle = index + size - 1
val right = min(array.size - 1, index + 2 * size - 1)
merge(array, left = index, middle, right)
}
index += size * 2
}
size *= 2
}
}
fun <T : Comparable<T>> merge(array: Array<T>, left: Int, middle: Int, right: Int) {
val aux = array.copyOfRange(left, right + 1)
var p = left
var p1 = 0
var p2 = middle - left + 1
while (p1 <= middle - left && p2 <= right - left) {
if (aux[p1] < aux[p2]) {
array[p] = aux[p1]
p1++
} else {
array[p] = aux[p2]
p2++
}
p++
}
while (p1 <= middle - left) {
array[p] = aux[p1]
p1++
p++
}
while (p2 <= right - left) {
array[p] = aux[p2]
p2++
p++
}
}
}
fun main() {
testSortAlgorithm(10, RandomType.CHAOS, _04_MergeSort(), _05_MergeSort_BottomUp())
}
| 0 | Kotlin | 0 | 1 | 748812d291e5c2df64c8620c96189403b19e12dd | 1,784 | kotlin-demo-code | MIT License |
day21/Kotlin/day21.kt | Ad0lphus | 353,610,043 | false | {"C++": 195638, "Python": 139359, "Kotlin": 80248} | import java.io.*
import java.util.concurrent.atomic.AtomicInteger
fun print_day_21() {
val yellow = "\u001B[33m"
val reset = "\u001b[0m"
val green = "\u001B[32m"
println(yellow + "-".repeat(25) + "Advent of Code - Day 21" + "-".repeat(25) + reset)
println(green)
val process = Runtime.getRuntime().exec("figlet Dirac Dice -c -f small")
val reader = BufferedReader(InputStreamReader(process.inputStream))
reader.forEachLine { println(it) }
println(reset)
println(yellow + "-".repeat(33) + "Output" + "-".repeat(33) + reset + "\n")
}
fun main() {
print_day_21()
Day21().part1()
Day21().part2()
println("\n" + "\u001B[33m" + "=".repeat(72) + "\u001b[0m" + "\n")
}
class Day21 {
fun part1() {
val startPos = File("../Input/day21.txt").readLines().map { it.last().digitToInt() }
val scores = intArrayOf(0, 0)
val space = startPos.toIntArray()
val dice = AtomicInteger()
var diceRolls = 0
fun nextRoll(): Int {
if (dice.get() >= 100) dice.set(0)
diceRolls++
return dice.incrementAndGet()
}
while (true) {
repeat(2) {
val roll = nextRoll() + nextRoll() + nextRoll()
space[it] = (space[it] + roll) % 10
scores[it] += if (space[it] != 0) space[it] else 10
if (scores[it] >= 1000) {
println("Puzzle 1: " + scores[(it + 1) % 2] * diceRolls)
return
}
}
}
}
fun part2() {
data class Universe(val p1: Int, val p2: Int, val s1: Int, val s2: Int)
val startPos = File("../Input/day21.txt").readLines().map { it.last().digitToInt() }
val dp = mutableMapOf<Universe, Pair<Long, Long>>()
fun solve(u: Universe): Pair<Long, Long> {
dp[u]?.let {
return it
}
if (u.s1 >= 21) return 1L to 0L
if (u.s2 >= 21) return 0L to 1L
var ans = 0L to 0L
for (d1 in 1..3) for (d2 in 1..3) for (d3 in 1..3) {
val newP1 = (u.p1 + d1 + d2 + d3 - 1) % 10 + 1
val newS1 = u.s1 + newP1
val (x, y) = solve(Universe(u.p2, newP1, u.s2, newS1))
ans = ans.first + y to ans.second + x
}
return ans.also { dp[u] = it }
}
println(
"Puzzle 2: " +
solve(Universe(startPos[0], startPos[1], 0, 0)).let {
maxOf(it.first, it.second)
}
)
}
}
| 0 | C++ | 0 | 0 | 02f219ea278d85c7799d739294c664aa5a47719a | 2,642 | AOC2021 | Apache License 2.0 |
src/Day03.kt | filipradon | 573,512,032 | false | {"Kotlin": 6146} | fun main() {
fun String.intoHalves(): List<String> {
return listOf(substring(0..length/2), substring(length/2))
}
fun List<String>.findCommonCharacter(): Char {
return this.map { it.toSet() }
.reduce { left, right -> left intersect right }
.first()
}
fun Char.toPriority(): Int =
if(isUpperCase()) {
this - 'A' + 27
} else {
this - 'a' + 1
}
fun part1(input: List<String>): Int {
return input
.map { it.intoHalves() }
.map { it.findCommonCharacter() }
.sumOf { it.toPriority() }
}
fun part2(input: List<String>): Int {
return input
.chunked(3)
.map { it.findCommonCharacter() }
.sumOf { it.toPriority() }
}
val input = readInputAsList("input-day3")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | dbac44fe421e29ab2ce0703e5827e4645b38548e | 927 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day07.kt | kipwoker | 572,884,607 | false | null | import java.math.BigInteger
enum class NodeType { File, Dir }
class Node(val parent: Node?, val children: MutableMap<String, Node>, val alias: String, val size: BigInteger?, val type: NodeType) {
var totalSize = BigInteger.ZERO
fun getRoot(): Node {
var currentNode = this
while (currentNode.parent != null) {
currentNode = currentNode.parent!!
}
return currentNode
}
fun calculateTotalSize(): BigInteger {
if (type == NodeType.File) {
totalSize = size!!
return totalSize
}
totalSize = children.values.sumOf { it.calculateTotalSize() }
return totalSize
}
fun sumBy(threshold: BigInteger): BigInteger {
var result = BigInteger.ZERO
if (type == NodeType.Dir && totalSize <= threshold) {
result += totalSize
}
return result + children.values.sumOf { it.sumBy(threshold) }
}
fun printNode() {
printNode(0)
}
fun printNode(indentLevel: Int) {
val indent = (0..indentLevel).map { ' ' }.joinToString("")
val typeMsg = if (type == NodeType.Dir) "dir" else "file, size=$size"
println("$indent- $alias ($typeMsg)")
children.values.forEach { it.printNode(indentLevel + 2) }
}
fun getDirSizes(): List<BigInteger> {
val result = mutableListOf(totalSize)
result.addAll(children.values.flatMap { it.getDirSizes() })
return result
}
}
fun main() {
fun ensureDirExists(node: Node, alias: String) {
if (node.children[alias] == null) {
node.children[alias] = Node(node, mutableMapOf(), alias, null, NodeType.Dir)
}
}
fun ensureFileExists(node: Node, alias: String, size: BigInteger) {
if (node.children[alias] == null) {
node.children[alias] = Node(node, mutableMapOf(), alias, size, NodeType.File)
}
}
fun parse(input: List<String>): Node {
val root = Node(null, mutableMapOf(), "/", null, NodeType.Dir)
var pointer = root
var lineIdx = 0
val totalSize = input.size
while (lineIdx < totalSize) {
val line = input[lineIdx]
println("Command: $line")
if (line == "$ cd /") {
pointer = pointer.getRoot()
++lineIdx
} else if (line == "$ cd ..") {
pointer = pointer.parent!!
++lineIdx
} else if (line.startsWith("$ cd")) {
val dirAlias = line.split(' ')[2]
ensureDirExists(pointer, dirAlias)
pointer = pointer.children[dirAlias]!!
++lineIdx
} else if (line == "$ ls") {
var listIdx = lineIdx + 1
while (listIdx < totalSize && !input[listIdx].startsWith("$")) {
val node = input[listIdx]
if (node.startsWith("dir")) {
val dirAlias = node.split(' ')[1]
ensureDirExists(pointer, dirAlias)
} else {
val parts = node.split(' ')
val size = parts[0].toBigInteger()
val fileAlias = parts[1]
ensureFileExists(pointer, fileAlias, size)
}
++listIdx
}
lineIdx = listIdx
} else {
println("Unexpected line: $line")
return root
}
println("Root")
root.printNode()
println()
}
return root
}
fun part1(input: List<String>): BigInteger {
val root = parse(input)
root.calculateTotalSize()
return root.sumBy(BigInteger.valueOf(100000))
}
fun part2(input: List<String>): BigInteger {
val root = parse(input)
root.calculateTotalSize()
val threshold = root.totalSize - BigInteger.valueOf(40000000)
return root.getDirSizes().filter { it >= threshold }.min()
}
val testInput = readInput("Day07_test")
assert(part1(testInput), BigInteger.valueOf(95437L))
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d8aeea88d1ab3dc4a07b2ff5b071df0715202af2 | 4,293 | aoc2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinimumAverageDifference.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.abs
/**
* 2256. Minimum Average Difference
* @see <a href="https://leetcode.com/problems/minimum-average-difference/">Source</a>
*/
fun interface MinimumAverageDifference {
operator fun invoke(nums: IntArray): Int
}
/**
* Approach 1: Brute Force
*/
class MinimumAverageDifferenceBruteForce : MinimumAverageDifference {
override operator fun invoke(nums: IntArray): Int {
val n: Int = nums.size
var ans = -1
var minAvgDiff = Int.MAX_VALUE
for (index in 0 until n) {
// Calculate average of left part of array, index 0 to i.
var leftPartAverage: Long = 0
for (i in 0..index) {
leftPartAverage += nums[i]
}
leftPartAverage /= (index + 1).toLong()
// Calculate average of right part of array, index i+1 to n-1.
var rightPartAverage: Long = 0
for (j in index + 1 until n) {
rightPartAverage += nums[j]
}
// If right part have 0 elements, then we don't divide by 0.
if (index != n - 1) {
rightPartAverage /= (n - index - 1).toLong()
}
val currDifference = abs(leftPartAverage - rightPartAverage).toInt()
// If current difference of averages is smaller,
// then current index can be our answer.
if (currDifference < minAvgDiff) {
minAvgDiff = currDifference
ans = index
}
}
return ans
}
}
/**
* Approach 2: Prefix Sum
*/
class MinimumAverageDifferencePrefixSum : MinimumAverageDifference {
override operator fun invoke(nums: IntArray): Int {
val n: Int = nums.size
var ans = -1
var minAvgDiff = Int.MAX_VALUE
// Generate prefix and suffix sum arrays.
// Generate prefix and suffix sum arrays.
val prefixSum = LongArray(n + 1)
val suffixSum = LongArray(n + 1)
for (index in 0 until n) {
prefixSum[index + 1] = prefixSum[index] + nums[index]
}
for (index in n - 1 downTo 0) {
suffixSum[index] = suffixSum[index + 1] + nums[index]
}
for (i in 0 until n) {
// Calculate average of left part of array, index 0 to i.
var leftPartAverage = prefixSum[i + 1]
leftPartAverage /= (i + 1).toLong()
// Calculate average of right part of array, index i+1 to n-1.
var rightPartAverage = suffixSum[i + 1]
// If right part have 0 elements, then we don't divide by 0.
if (i != n - 1) {
rightPartAverage /= (n - i - 1).toLong()
}
val currDifference = abs(leftPartAverage - rightPartAverage).toInt()
// If current difference of averages is smaller,
// then current index can be our answer.
if (currDifference < minAvgDiff) {
minAvgDiff = currDifference
ans = i
}
}
return ans
}
}
/**
* Approach 3: Prefix Sum Optimized
*/
class MinimumAverageDifferencePrefixSumOpt : MinimumAverageDifference {
override operator fun invoke(nums: IntArray): Int {
val n: Int = nums.size
var ans = -1
var minAvgDiff = Int.MAX_VALUE
var currPrefixSum: Long = 0
// Get total sum of array.
// Get total sum of array.
var totalSum: Long = 0
for (index in 0 until n) {
totalSum += nums[index]
}
for (index in 0 until n) {
currPrefixSum += nums[index]
// Calculate average of left part of array, index 0 to i.
var leftPartAverage = currPrefixSum
leftPartAverage /= (index + 1).toLong()
// Calculate average of right part of array, index i+1 to n-1.
var rightPartAverage = totalSum - currPrefixSum
// If right part have 0 elements, then we don't divide by 0.
if (index != n - 1) {
rightPartAverage /= (n - index - 1).toLong()
}
val currDifference = abs(leftPartAverage - rightPartAverage).toInt()
// If current difference of averages is smaller,
// then current index can be our answer.
if (currDifference < minAvgDiff) {
minAvgDiff = currDifference
ans = index
}
}
return ans
}
}
class MinimumAverageDifferenceKt : MinimumAverageDifference {
override operator fun invoke(nums: IntArray): Int {
var sum = 0L
nums.forEach { sum += it.toLong() }
var leftSum = 0L
var min = Long.MAX_VALUE
var minInd = 0
for (i in 0..nums.lastIndex) {
val leftCount = (i + 1).toLong()
leftSum += nums[i].toLong()
val front = leftSum / leftCount
val rightCount = nums.size.toLong() - leftCount
val rightSum = sum - leftSum
val back = if (rightCount == 0L) 0L else rightSum / rightCount
val diff = abs(front - back)
if (diff < min) {
min = diff
minInd = i
}
}
return minInd
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 5,931 | kotlab | Apache License 2.0 |
kotlin/src/main/kotlin/dev/egonr/leetcode/13_RomanToInt.kt | egon-r | 575,970,173 | false | null | package dev.egonr.leetcode
/* Easy
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer.
Example 1:
Input: s = "III"
Output: 3
Explanation: III = 3.
Example 2:
Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 3:
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
Constraints:
1 <= s.length <= 15
s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
It is guaranteed that s is a valid roman numeral in the range [1, 3999].
*/
class RomanToInt {
private val romanMap = hashMapOf<Char, Int>(
Pair('I', 1),
Pair('V', 5),
Pair('X', 10),
Pair('L', 50),
Pair('C', 100),
Pair('D', 500),
Pair('M', 1000)
)
fun test() {
println(romanToInt("LVIII"))
println(romanToInt("MCMXCIV"))
}
fun romanToInt(s: String): Int {
var result = 0
var skip = false
s.forEachIndexed { index, c ->
if(skip) {
skip = false
return@forEachIndexed
}
var nextChar = s.getOrNull(index+1)
if(nextChar != null) {
if(c == 'I' && (nextChar == 'V' || nextChar == 'X')) {
result += (romanCharToInt(nextChar) - romanCharToInt(c))
skip = true
}
else if(c == 'X' && (nextChar == 'L' || nextChar == 'C')) {
result += (romanCharToInt(nextChar) - romanCharToInt(c))
skip = true
}
else if(c == 'C' && (nextChar == 'D' || nextChar == 'M')) {
result += (romanCharToInt(nextChar) - romanCharToInt(c))
skip = true
} else {
result += romanCharToInt(c)
}
} else {
result += romanCharToInt(c)
}
}
return result
}
private fun romanCharToInt(c: Char): Int {
return romanMap[c] ?: throw RuntimeException("Unexpected roman numeral '$c'")
}
} | 0 | Kotlin | 0 | 0 | b9c59e54ca2d1399d34d1ee844e03c16a580cbcb | 3,067 | leetcode | The Unlicense |
day04/src/main/kotlin/Day04.kt | bzabor | 160,240,195 | false | null |
class Day04(private val input: List<String>) {
val guardMap = mutableMapOf<String, Guard>()
val sorted = input.toTypedArray().sorted()
fun part1(): Int {
processInput()
val maxGuard = guardMostAsleep()
var maxIdx = 0
var minuteMax = 0
for ((idx, minute) in maxGuard!!.asleep.withIndex()) {
println("$idx - $minute")
if (minute > minuteMax) {
minuteMax = minute
maxIdx = idx
}
}
return maxGuard.id.toInt() * maxIdx
}
fun part2(): Int {
processInput()
var maxGuard: Guard? = null
var maxGuardMaxMinutesIdx = 0
var maxMinutes = 0
for (guard in guardMap.values) {
for ((idx, minutes) in guard.asleep.withIndex()) {
if (minutes > maxMinutes) {
maxMinutes = minutes
maxGuardMaxMinutesIdx = idx
maxGuard = guard
}
}
}
return maxGuard.id.toInt() * maxGuardMaxMinutesIdx
}
private fun processInput() {
val guardRegex = Regex("""#\d+""")
val minuteRegex = Regex(""":\d\d""")
var guard: Guard? = null
var sleeps = 0
for (line in sorted) {
var match = guardRegex.find(line)
if(match != null) {
val guardId = match.value.drop(1)
guard = guardMap.getOrPut(guardId) {Guard(guardId)}
} else {
match = minuteRegex.find(line)
if (match != null) {
if (line.contains("asleep")) {
sleeps = match.value.drop(1).toInt()
} else {
val wakes = match.value.drop(1).toInt()
for (idx in sleeps until wakes) {
guard!!.asleep[idx]++
}
println(guard!!.asleep)
}
}
}
}
}
private fun guardMostAsleep(): Guard? {
var maxGuard: Guard? = null
for (guard in guardMap.values) {
if (maxGuard == null || guard.asleep.sum() > maxGuard.asleep.sum()) {
maxGuard = guard
}
}
return maxGuard
}
data class Guard(val id: String) {
var asleep = Array(60) {0}
}
}
| 0 | Kotlin | 0 | 0 | 14382957d43a250886e264a01dd199c5b3e60edb | 2,439 | AdventOfCode2018 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/SubarraySumEqualsK.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <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
fun interface SubarraySumStrategy {
operator fun invoke(nums: IntArray, k: Int): Int
}
class SubarraySumBruteForce : SubarraySumStrategy {
override operator fun invoke(nums: IntArray, k: Int): Int {
var count = 0
for (start in nums.indices) {
for (end in start + 1..nums.size) {
var sum = 0
for (i in start until end) sum += nums[i]
if (sum == k) count++
}
}
return count
}
}
class SubarraySumUsingCumulativeSum : SubarraySumStrategy {
override operator fun invoke(nums: IntArray, k: Int): Int {
var count = 0
val sum = IntArray(nums.size + 1)
sum[0] = 0
for (i in 1..nums.size) sum[i] = sum[i - 1] + nums[i - 1]
for (start in nums.indices) {
for (end in start + 1..nums.size) {
if (sum[end] - sum[start] == k) count++
}
}
return count
}
}
class SubarraySumWithoutSpace : SubarraySumStrategy {
override operator fun invoke(nums: IntArray, k: Int): Int {
var count = 0
for (start in nums.indices) {
var sum = 0
for (end in start until nums.size) {
sum += nums[end]
if (sum == k) count++
}
}
return count
}
}
class SubarraySumUsingHashmap : SubarraySumStrategy {
override operator fun invoke(nums: IntArray, k: Int): Int {
var count = 0
var sum = 0
val map: HashMap<Int, Int> = HashMap()
map[0] = 1
for (element in nums) {
sum += element
if (map.containsKey(sum - k)) count += map[sum - k]!!
map[sum] = map.getOrDefault(sum, 0) + 1
}
return count
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,423 | kotlab | Apache License 2.0 |
src/main/kotlin/days/Day25.kt | andilau | 433,504,283 | false | {"Kotlin": 137815} | package days
@AdventOfCodePuzzle(
name = "<NAME>",
url = "https://adventofcode.com/2021/day/25",
date = Date(day = 25, year = 2021)
)
class Day25(val input: List<String>) : Puzzle {
private val seafloor = parseSeafloor()
private val max = Point(input.first().lastIndex, input.lastIndex)
override fun partOne() =
generateSequence(seafloor) { it.next() }
.withIndex()
.zipWithNext()
.first { it.first.value == it.second.value }
.first.index + 1 // 1-based
override fun partTwo() {}
private fun Map<Point, SeaCucumber>.next(): Map<Point, SeaCucumber> =
toMutableMap().move(SeaCucumber.EAST) { east() }
.move(SeaCucumber.SOUTH) { south() }
private fun Point.east() = copy(x = (x + 1) % (max.x + 1))
private fun Point.south() = copy(y = (y + 1) % (max.y + 1))
private inline fun MutableMap<Point, SeaCucumber>.move(type: SeaCucumber, transition: Point.() -> Point) =
this.apply {
filterValues { it == type }
.keys
.associateWith(transition)
.filterValues { new -> new !in this }
.forEach { (old, new) ->
this.remove(old)
this[new] = type
}
}
internal fun stepAndList(times: Int = 1): List<String> =
(1..times)
.fold(seafloor) { map, _ -> map.next() }
.asList()
internal fun asString() = seafloor.asList().joinToString("\n")
private fun Map<Point, SeaCucumber>.asList() = buildList {
for (y in 0..max.y)
add((0..max.x).mapNotNull { x ->
this@asList[Point(x, y)]?.type ?: SeaCucumber.NONE
}.joinToString(""))
}
private fun parseSeafloor() = buildMap {
input.forEachIndexed { y, row ->
row.forEachIndexed { x, char ->
if (char in SeaCucumber.values().map(SeaCucumber::type))
put(Point(x, y), SeaCucumber.from(char))
}
}
}
enum class SeaCucumber(val type: Char) {
EAST('>'), SOUTH('v');
companion object {
const val NONE = '.'
fun from(type: Char) = when (type) {
'>' -> EAST
'v' -> SOUTH
else -> error("Unknown sea cucumber of type: $type")
}
}
}
} | 0 | Kotlin | 0 | 0 | b3f06a73e7d9d207ee3051879b83e92b049a0304 | 2,422 | advent-of-code-2021 | Creative Commons Zero v1.0 Universal |
day21/src/Day21.kt | rnicoll | 438,043,402 | false | {"Kotlin": 90620, "Rust": 1313} | import java.lang.StringBuilder
object Day21 {
const val TARGET_SCORE_PART_1 = 1000
const val TARGET_SCORE_PART_2 = 21
}
fun main() {
val positions = mapOf(Pair(Player.ONE, 6), Pair(Player.TWO, 8))
println(part1(Day21.TARGET_SCORE_PART_1, positions))
println(part2(Day21.TARGET_SCORE_PART_2, positions))
}
private fun part1(target: Int, positions: Map<Player, Int>): Outcome {
val score1 = PlayerScore(Player.ONE, positions[Player.ONE]!!)
val score2 = PlayerScore(Player.TWO, positions[Player.TWO]!!)
val die = DeterministicDie()
while (true) {
if (score1.move(die.roll() + die.roll() + die.roll()) >= target) {
return Outcome(score1, score2, die)
} else if (score2.move(die.roll() + die.roll() + die.roll()) >= target) {
return Outcome(score2, score2, die)
}
}
}
private fun part2(target: Int, positions: Map<Player, Int>): Map<Player, Long> {
val rolls: Map<Int, Int> = generateAllRolls(1..3)
println(rolls)
return rollPart2(
PlayerScore(Player.ONE, positions[Player.ONE]!!),
PlayerScore(Player.TWO, positions[Player.TWO]!!),
target, rolls)
}
private fun rollPart2(currentPlayer: PlayerScore,
lastPlayer: PlayerScore,
target: Int,
rolls: Map<Int, Int>): Map<Player, Long> {
val outcomes = mutableMapOf<Player, Long>()
for ((roll, count) in rolls.entries) {
val splitPlayer = currentPlayer.split(roll)
val universe: Map<Player, Long> = if (splitPlayer.score >= target) {
mapOf(Pair(splitPlayer.player, 1), Pair(lastPlayer.player, 0))
} else {
rollPart2(lastPlayer, splitPlayer, target, rolls)
}
universe.forEach { (player, winUniverses) ->
outcomes.merge(player, winUniverses * count) { a, b ->
a + b
}
}
}
return outcomes
}
private fun generateAllRolls(range: IntRange): Map<Int, Int> {
val result = mutableMapOf<Int, Int>()
for (dieA in range) {
for (dieB in range) {
for (dieC in range) {
result.compute(dieA + dieB + dieC) { _, v ->
(v ?: 0) + 1
}
}
}
}
return result
}
data class Outcome(val winner: PlayerScore, val loser: PlayerScore, val die: Dice) {
override fun toString(): String {
val builder = StringBuilder()
builder.append("Loser score: ${loser.score}\n")
.append("Winner score: ${winner.score}\n")
.append("Die rolls: ${die.rollCount}\n")
.append(loser.score * die.rollCount)
return builder.toString()
}
} | 0 | Kotlin | 0 | 0 | 8c3aa2a97cb7b71d76542f5aa7f81eedd4015661 | 2,723 | adventofcode2021 | MIT License |
year2023/src/cz/veleto/aoc/year2023/Day12.kt | haluzpav | 573,073,312 | false | {"Kotlin": 164348} | package cz.veleto.aoc.year2023
import cz.veleto.aoc.core.AocDay
class Day12(config: Config) : AocDay(config) {
override fun part1(): String = solve(folds = 1)
override fun part2(): String = solve(folds = 5)
private fun solve(folds: Int): String = input
.map { line -> line.parse(folds) }
.map { (row, counts) -> countArrangements(row, counts) }
.sum()
.toString()
private fun String.parse(folds: Int): Pair<String, List<Int>> {
val (foldedRow, foldedCounts) = split(' ')
val row = List(folds) { foldedRow }.joinToString("?")
val counts = foldedCounts.split(',').map { it.toInt() }
val unfoldedCounts = List(folds) { counts }.flatten()
return row to unfoldedCounts
}
private fun countArrangements(row: String, counts: List<Int>): Int {
if (config.log) println("row $row, counts $counts")
val unknowns = row.withIndex().filter { it.value == '?' }.map { it.index }
val damaged = row.withIndex().filter { it.value == '#' }.map { it.index }
counts[0]
generateSequence { }
.runningFold(List(counts.size) { 0 } as List<Int>?) { previousPositions, _ ->
// create single arr
generateSequence { }
.runningFoldIndexed(row as String?) { index, row, _ ->
null
}
.takeWhile { it != null }
null
}
.takeWhile { it != null }
.count()
return 0
}
}
| 0 | Kotlin | 0 | 1 | 32003edb726f7736f881edc263a85a404be6a5f0 | 1,573 | advent-of-pavel | Apache License 2.0 |
year2020/day07/baggage/src/main/kotlin/com/curtislb/adventofcode/year2020/day07/baggage/BagRules.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | package com.curtislb.adventofcode.year2020.day07.baggage
/**
* A set of rules indicating the number and type of bags (see [BagCount]) that must be contained in
* other bags.
*
* @param rulesString A string representing all bag rules. Each line may end with a `.` and must
* be a rule of the form `"$container bags contain $bagCount1, ..., $bagCountN"` or
* `"$container bags contain no other bags"`.
*/
class BagRules(rulesString: String) {
/**
* A map from each bag type to the bag counts it must contain.
*/
private val bagContents: Map<String, List<BagCount>>
/**
* A map from each bag type to the bag types that must contain it.
*/
private val bagContainers: Map<String, List<String>>
init {
val bagContentsMap = mutableMapOf<String, List<BagCount>>()
val bagContainersMap = mutableMapOf<String, MutableList<String>>()
for (ruleString in rulesString.trim().lines()) {
// Parse the relevant tokens from each rule string
val tokens = ruleString
.trimEnd('.')
.replace(REMOVAL_REGEX, "")
.split("contain")
.map { it.trim() }
require(tokens.size == 2) { "Malformed rule string: $ruleString" }
// Convert tokens into the containing bag type and contained bag counts
val (container, contentsString) = tokens
val contents = if (contentsString.isBlank()) {
emptyList()
} else {
contentsString.split(',').map { BagCount.from(it) }
}
// Add the container and contents to the relevant maps
bagContentsMap[container] = contents
for (bagCount in contents) {
bagContainersMap.getOrPut(bagCount.bagType) { mutableListOf() }.add(container)
}
}
bagContents = bagContentsMap
bagContainers = bagContainersMap
}
/**
* Returns the total number of bags contained by (and including) the given [bagCount].
*/
fun countTotalBags(bagCount: BagCount): Int {
return bagCount.count * (1 + (bagContents[bagCount.bagType]?.sumOf(::countTotalBags) ?: 0))
}
/**
* Returns all unique bag types that recursively contain the given [bagType].
*/
fun findBagsContaining(bagType: String): Set<String> {
val containers = mutableSetOf<String>()
var bags = setOf(bagType)
do {
bags = bags.flatMap { bagContainers[it] ?: emptyList() }.toSet()
containers.addAll(bags)
} while (bags.isNotEmpty())
return containers
}
override fun toString(): String {
return bagContents.map { (bagType, contents) ->
val contentString = if (contents.isEmpty()) "no other bags" else contents.joinToString()
"$bagType bags contain $contentString."
}.joinToString(separator = "\n")
}
companion object {
/**
* A regex for matching and removing unnecessary portions of each rule string.
*/
private val REMOVAL_REGEX = Regex("""( *bags? *)|(no other)""")
}
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 3,167 | AdventOfCode | MIT License |
src/adventofcode/blueschu/y2017/day10/solution.kt | blueschu | 112,979,855 | false | null | package adventofcode.blueschu.y2017.day10
import java.io.File
import kotlin.test.assertEquals
val input: String by lazy {
File("resources/y2017/day10.txt")
.bufferedReader()
.use { it.readText() }
.trim()
}
fun main(args: Array<String>) {
assertEquals(12, part1("3,4,1,5", Knot(circleSize = 5)))
println("Part 1: ${part1(input)}")
assertEquals("a2582a3a0e66e6e86e3812dcb672a272", knotHash(""))
assertEquals("33efeb34ea91902bb2f59c9920caa6cd", knotHash("AoC 2017"))
assertEquals("3efbe78a8d82f29979031a4aa0b16a9d", knotHash("1,2,3"))
assertEquals("63960835bcdc130f0b66d7ff4f6a5a8e", knotHash("1,2,4"))
println("Part 2: ${knotHash(input)}")
}
fun part1(lengthString: String, knot: Knot = Knot()): Int {
val lengths = lengthString
.split(',')
.map(String::toInt)
lengths.forEach {
knot.twistLength(it)
}
return knot.hash
}
class Knot(private val circleSize: Int = 256) {
// array of [0,1,2,3,4...circleSize - 1]
private val _circleMarks = Array<Int>(circleSize, { it })
// circle marks rotated to their true position
val circleMarks get() = _circleMarks.copyOf().apply { rotate(position) }
// product of first and second mark when the circle has been rotated to its true position
val hash: Int
get() = _circleMarks[circleSize - position] * _circleMarks[circleSize - position + 1]
private var skipSize = 0
private var position = 0
fun twistLength(lengthFromPos: Int) {
_circleMarks.reverseRange(0, lengthFromPos - 1)
advancePos(lengthFromPos)
}
// keep "position" always at the first index of the array
private fun advancePos(length: Int) {
_circleMarks.rotate(-(length + skipSize))
position = (position + length + skipSize) % circleSize
skipSize++
}
}
fun <T> Array<T>.reverseRange(start: Int, end: Int) {
var left = start
var right = end
while (left < right) {
val temp = this[left]
this[left] = this[right]
this[right] = temp
left++
right--
}
}
fun <T> Array<T>.rotate(shift: Int) {
val wrappedShift = shift % size
if (wrappedShift == 0) return
if (wrappedShift > 0) {
val offset = size - wrappedShift
reverseRange(offset, size - 1)
reverseRange(0, offset - 1)
reverse()
} else { // shift < 0
reverseRange(0, -wrappedShift - 1)
reverseRange(-wrappedShift, size - 1)
reverse()
}
}
// part 2
fun knotHash(stringToBeHashed: String): String {
fun Knot.twistLength(l: Byte) = twistLength(l.toInt())
val hashInput = byteArrayOf(*stringToBeHashed.toByteArray(), 17, 31, 73, 47, 23)
val knot = Knot()
repeat(times = 64) {
hashInput.forEach { knot.twistLength(it) }
}
val sparseHash = knot.circleMarks
val denseHash = (0 until 16).map {
sparseHash
.copyOfRange(it * 16, it * 16 + 16)
.reduce { acc, next -> acc xor next }
}
return denseHash.fold("") { hash, next: Int ->
val hex = next.toString(radix = 0x10) // hexadecimal string
hash + if (hex.length == 1) "0" + hex else hex // pad with leading 0
}
}
| 0 | Kotlin | 0 | 0 | 9f2031b91cce4fe290d86d557ebef5a6efe109ed | 3,235 | Advent-Of-Code | MIT License |
src/main/kotlin/eu/michalchomo/adventofcode/year2023/Day05.kt | MichalChomo | 572,214,942 | false | {"Kotlin": 56758} | package eu.michalchomo.adventofcode.year2023
import eu.michalchomo.adventofcode.Day
import eu.michalchomo.adventofcode.intersect
import eu.michalchomo.adventofcode.main
import eu.michalchomo.adventofcode.removeIntersectWith
import eu.michalchomo.adventofcode.split
object Day05 : Day {
override val number: Int = 5
override fun part1(input: List<String>): String = input.split { line -> line.isEmpty() || !line[0].isDigit() }
.fold(mutableListOf<MutableList<Long>>().apply {
val seeds = input[0].split(": ", " ")
seeds.slice(1..<seeds.size).map { it.toLong() }.forEach { seed ->
this.add(mutableListOf(seed))
}
}) { destinationLists, category ->
val sourceRangesToDestinationStarts = category.toSourceRangesToDestinationStarts()
destinationLists.forEach { destinations ->
val last = destinations.last()
val sourceRange = sourceRangesToDestinationStarts.keys.find { last in it }
if (sourceRange != null) {
val destinationStart = sourceRangesToDestinationStarts[sourceRange]!!
destinations.add(destinationStart + last - sourceRange.first)
} else {
destinations.add(last)
}
}
destinationLists
}.minOf { it.lastOrNull() ?: Long.MAX_VALUE }.toString()
override fun part2(input: List<String>): String = input.split { line -> line.isEmpty() || !line[0].isDigit() }
.fold(mutableListOf<MutableList<List<LongRange>>>().apply {
val seeds = input[0].split(": ", " ")
seeds.slice(1..<seeds.size).chunked(2).map { range ->
val rangeStart = range[0].toLong()
val rangeLength = range[1].toLong()
this.add(mutableListOf(listOf(rangeStart..<(rangeStart + rangeLength))))
}
}) { destinationRangeLists, category ->
val sourceRangesToDestinationStarts = category.toSourceRangesToDestinationStarts()
destinationRangeLists.forEach { destinationRanges ->
val currentSources = destinationRanges.last()
destinationRanges.add(
currentSources.fold(currentSources to mutableListOf<List<LongRange>>()) { acc, currentRange ->
var newNotMapped = acc.first
sourceRangesToDestinationStarts.keys.forEach { sourceRange ->
newNotMapped.mapNotNull { it.intersect(sourceRange) }.forEach { intersect ->
if (intersect.first < intersect.last) {
newNotMapped = newNotMapped.map { it.removeIntersectWith(intersect) }.flatten()
val destinationStart = sourceRangesToDestinationStarts[sourceRange]!!
val offset = destinationStart - sourceRange.first
acc.second.add(listOf((intersect.first + offset)..(intersect.last + offset)))
}
}
}
newNotMapped to acc.second
}.let { it.first + it.second.flatten() }
)
}
destinationRangeLists
}.minOf { it.last().minOf { it.first } }.toString()
private fun List<String>.toSourceRangesToDestinationStarts() = this.associate { line ->
val split = line.split(' ')
val destinationStart = split[0].toLong()
val sourceStart = split[1].toLong()
val rangeLength = split[2].toLong()
val sourceRange = sourceStart..<(sourceStart + rangeLength)
sourceRange to destinationStart
}
}
fun main() {
main(Day05)
}
| 0 | Kotlin | 0 | 0 | a95d478aee72034321fdf37930722c23b246dd6b | 3,834 | advent-of-code | Apache License 2.0 |
src/Day10.kt | CrazyBene | 573,111,401 | false | {"Kotlin": 50149} | fun main() {
open class Instruction(val cycles: Int)
class NoOp : Instruction(1)
class AddX(val amount: Int) : Instruction(2)
fun List<String>.toInstructions(): List<Instruction> {
return this.map {
val i = it.split(" ")
when (i[0]) {
"noop" -> NoOp()
"addx" -> AddX(i[1].toInt())
else -> error("Instruction $it is unknown.")
}
}
}
fun part1(input: List<String>): Int {
val instructions = input.toInstructions()
var currentCycle = 1
var registerX = 1
val cycleValues = mutableListOf<Int>()
instructions.forEach {
for (i in 0 until it.cycles) {
if ((currentCycle - 20) % 40 == 0)
cycleValues += registerX * currentCycle
currentCycle++
}
if (it is AddX)
registerX += it.amount
}
return cycleValues.sum()
}
fun part2(input: List<String>): String {
val instructions = input.toInstructions()
var currentCycle = 1
var registerX = 1
var crtOutput = ""
instructions.forEach {
for (i in 0 until it.cycles) {
val crtPosition = (currentCycle - 1) % 40
crtOutput += if (crtPosition in registerX - 1..registerX + 1) "#" else "."
if (currentCycle % 40 == 0)
crtOutput += "\n"
currentCycle++
}
if (it is AddX)
registerX += it.amount
}
return crtOutput
}
val testInput = readInput("Day10Test")
check(part1(testInput) == 13140)
val input = readInput("Day10")
println("Question 1 - Answer: ${part1(input)}")
println("Question 2 - Answer: \n${part2(input)}")
} | 0 | Kotlin | 0 | 0 | dfcc5ba09ca3e33b3ec75fe7d6bc3b9d5d0d7d26 | 1,868 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2017/Day22.kt | tginsberg | 112,672,087 | false | null | /*
* Copyright (c) 2017 by <NAME>
*/
package com.ginsberg.advent2017
/**
* AoC 2017, Day 22
*
* Problem Description: http://adventofcode.com/2017/day/22
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2017/day22/
*/
class Day22(input: List<String>) {
private val grid = parseInput(input)
private var current = Point(input.size / 2, input.first().length / 2)
private val directions = listOf(Point(0, -1), Point(1, 0), Point(0, 1), Point(-1, 0))
private var pointing = 0
fun solvePart1(iterations: Int = 10_000): Int {
var infectionsCaused = 0
repeat(iterations) {
if (grid.getOrDefault(current, NodeState.Clean) == NodeState.Clean) {
infectionsCaused += 1
grid[current] = NodeState.Infected
pointing = left()
} else {
// Infected
grid[current] = NodeState.Clean
pointing = right()
}
current += directions[pointing]
}
return infectionsCaused
}
fun solvePart2(iterations: Int = 10_000_000): Int {
var infectionsCaused = 0
repeat(iterations) {
when (grid.getOrDefault(current, NodeState.Clean)) {
NodeState.Clean -> {
pointing = left()
grid[current] = NodeState.Weakened
}
NodeState.Weakened -> {
infectionsCaused += 1
grid[current] = NodeState.Infected
}
NodeState.Infected -> {
pointing = right()
grid[current] = NodeState.Flagged
}
NodeState.Flagged -> {
pointing = reverse()
grid[current] = NodeState.Clean
}
}
current += directions[pointing]
}
return infectionsCaused
}
private fun left(): Int =
if (pointing == 0) 3 else pointing - 1
private fun right(): Int =
pointing.inc() % 4
private fun reverse(): Int =
(pointing + 2) % 4
private fun parseInput(input: List<String>): MutableMap<Point, NodeState> {
val destination = mutableMapOf<Point, NodeState>()
input.forEachIndexed { y, row ->
row.forEachIndexed { x, char ->
destination[Point(x, y)] = if (char == '.') NodeState.Clean else NodeState.Infected
}
}
return destination
}
data class Point(private val x: Int, private val y: Int) {
operator fun plus(that: Point): Point =
Point(x + that.x, y + that.y)
}
enum class NodeState {
Clean,
Infected,
Weakened,
Flagged
}
}
| 0 | Kotlin | 0 | 15 | a57219e75ff9412292319b71827b35023f709036 | 2,821 | advent-2017-kotlin | MIT License |
ceria/15/src/main/kotlin/Solution.kt | VisionistInc | 433,099,870 | false | {"Kotlin": 91599, "Go": 87605, "Ruby": 65600, "Python": 21104} | import java.io.File;
// Thanks to https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Algorithm and comments in
// the slack that it uses this algorithm
fun main(args : Array<String>) {
val input = File(args.first()).readLines()
.map { line -> line.map { it -> it.digitToInt() }.toMutableList() }.toMutableList()
println("Solution 1: ${solution1(input)}")
println("Solution 2: ${solution2(input)}")
}
fun solution1(input: List<List<Int>>) :Int {
return doDijkstra(input)
}
private fun solution2(input: MutableList<MutableList<Int>>) :Int {
// go down
val largeMap = input
var modifiedInput = input
repeat(4) {
val nextInc = increment(modifiedInput)
largeMap.addAll(nextInc)
modifiedInput = nextInc
}
// now go accross
modifiedInput = largeMap
repeat(4) {
val nextInc = increment(modifiedInput)
for (x in 0..modifiedInput.size - 1) {
largeMap[x].addAll(nextInc[x])
}
modifiedInput = nextInc
}
return doDijkstra(largeMap)
}
private fun doDijkstra(input: List<List<Int>>) :Int {
// make the graph from the input
val vertices = mutableSetOf<Pair<Int, Int>>()
val edges = mutableListOf<Triple<Pair<Int, Int>, Pair<Int, Int>, Int>>()
for (y in 0..input.size - 1) {
for (x in 0..input[0].size - 1) {
val vertex = Pair(x, y)
vertices.add(vertex)
if (x < input[0].size - 1) {
edges.add(Triple(vertex, Pair(x + 1, y), input[y][x + 1]))
}
if (x > 0) {
edges.add(Triple(vertex, Pair(x - 1, y), input[y][x - 1]))
}
if (y < input.size - 1) {
edges.add(Triple(vertex, Pair(x, y + 1), input[y + 1][x]))
}
if (y > 0) {
edges.add(Triple(vertex, Pair(x, y - 1), input[y - 1][x]))
}
}
}
val neighbors = mutableMapOf<Pair<Int, Int>, MutableMap<Pair<Int, Int>, Int>>()
for ((from, to, risk) in edges) {
val neighboursFrom = neighbors[from] ?: mutableMapOf()
neighboursFrom[to] = risk
neighbors[from] = neighboursFrom
}
val start = Pair<Int, Int>(0, 0)
val moves = mutableSetOf(start)
// store the selected postion pair and it's associated risk
val positionsToRisks = vertices.fold(mutableMapOf<Pair<Int, Int>, Int>()) { acc, vertex ->
acc[vertex] = Int.MAX_VALUE // I don't know how big to make this
acc
}
positionsToRisks.put(start, 0)
// the algorithm is done when we are out of moves...
while (moves.isNotEmpty()) {
val currentPos = moves.minByOrNull{ positionsToRisks.getOrDefault(it, 0) }
// can no longer move to this position, so remove it from moves -- this is key
moves.remove(currentPos)
// assess the risk of each neighbor, and if it's less, add the neighbor to the moves
for (neighbor in neighbors.getOrDefault(currentPos, emptyMap<Pair<Int, Int>, Int>()).keys ) {
val newRisk = positionsToRisks.getOrDefault(currentPos, 0) + neighbors.getOrDefault(currentPos, emptyMap<Pair<Int, Int>, Int>()).getOrDefault(neighbor, 0)
if (newRisk < positionsToRisks.getOrDefault(neighbor, 0)) {
positionsToRisks[neighbor] = minOf(positionsToRisks.getOrDefault(neighbor, 0), newRisk)
moves.add(neighbor)
}
}
}
// the end position should have the cumulative path
return positionsToRisks.getOrDefault(Pair<Int, Int>(input[0].size - 1, input.size - 1), 0)
}
private fun increment(input: MutableList<MutableList<Int>>): MutableList<MutableList<Int>> {
val result = MutableList(input.size) { MutableList(input[0].size) { 0 } }
for (y in 0..input.size - 1) {
for (x in 0..input[0].size - 1) {
if (input[y][x] == 9) {
result[y][x] = 1
} else {
result[y][x] = input[y][x] + 1
}
}
}
return result
} | 0 | Kotlin | 4 | 1 | e22a1d45c38417868f05e0501bacd1cad717a016 | 4,059 | advent-of-code-2021 | MIT License |
src/Day01.kt | VadimB95 | 574,449,732 | false | {"Kotlin": 19743} | fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int {
var topElfCalories = 0
var elfCalories = 0
input.forEach {
if (it == "") {
if (elfCalories > topElfCalories) {
topElfCalories = elfCalories
}
elfCalories = 0
} else {
elfCalories += it.toInt()
}
}
return topElfCalories
}
private fun part2(input: List<String>): Int {
val elvesCalories = mutableListOf<Int>()
var elfCalories = 0
input.forEach {
if (it == "") {
elvesCalories.add(elfCalories)
elfCalories = 0
} else {
elfCalories += it.toInt()
}
}
return elvesCalories.sortedDescending().take(3).sum()
}
| 0 | Kotlin | 0 | 0 | 3634d1d95acd62b8688b20a74d0b19d516336629 | 995 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/NumberOfEnclaves.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.LinkedList
import java.util.Queue
/**
* 1020. Number of Enclaves
* @see <a href="https://leetcode.com/problems/number-of-enclaves/">Source</a>
*/
fun interface NumberOfEnclaves {
operator fun invoke(grid: Array<IntArray>): Int
}
class NumberOfEnclavesDFS : NumberOfEnclaves {
override operator fun invoke(grid: Array<IntArray>): Int {
var result = 0
for (i in grid.indices) {
for (j in 0 until grid[i].size) {
if (i == 0 || j == 0 || i == grid.size - 1 || j == grid[i].size - 1) {
dfs(grid, i, j)
}
}
}
for (i in grid.indices) {
for (j in 0 until grid[i].size) {
if (grid[i][j] == 1) result++
}
}
return result
}
private fun dfs(a: Array<IntArray>, i: Int, j: Int) {
if (i >= 0 && i <= a.size - 1 && j >= 0 && j <= a[i].size - 1 && a[i][j] == 1) {
a[i][j] = 0
dfs(a, i + 1, j)
dfs(a, i - 1, j)
dfs(a, i, j + 1)
dfs(a, i, j - 1)
}
}
}
class NumberOfEnclavesBFS : NumberOfEnclaves {
private val directions = arrayOf(intArrayOf(-1, 0), intArrayOf(1, 0), intArrayOf(0, -1), intArrayOf(0, 1))
override operator fun invoke(grid: Array<IntArray>): Int {
if (grid.isEmpty()) return 0
if (grid.first().isEmpty()) return 0
val rows = grid.size
val cols = grid[0].size
val visited = Array(rows) { BooleanArray(cols) }
val q = getStartPositions(grid, visited, rows, cols)
while (q.isNotEmpty()) {
val cell = q.poll()
for (i in directions.indices) {
val row = cell[0] + directions[i][0]
val col = cell[1] + directions[i][1]
if (isValid(grid, visited, row, col, rows, cols)) {
visited[row][col] = true
q.offer(intArrayOf(row, col))
}
}
}
var unvisitedCount = 0
for (i in 1 until rows - 1) {
for (j in 1 until cols - 1) {
if (grid[i][j] == 1 && !visited[i][j]) unvisitedCount++
}
}
return unvisitedCount
}
private fun getStartPositions(
grid: Array<IntArray>,
visited: Array<BooleanArray>,
rows: Int,
cols: Int,
): Queue<IntArray> {
val bottom = rows - 1
val right = cols - 1
val q: Queue<IntArray> = LinkedList()
calculateTopRight(q = q, bottom = bottom, right = right, grid = grid, visited = visited)
calculateBottomLeft(q = q, bottom = bottom, right = right, grid = grid, visited = visited)
return q
}
@Suppress("UNUSED_CHANGED_VALUE")
private fun calculateTopRight(
q: Queue<IntArray>,
top: Int = 0,
bottom: Int,
left: Int = 0,
right: Int,
grid: Array<IntArray>,
visited: Array<BooleanArray>,
) {
var t = top
var r = right
// UP
if (t <= bottom && left <= r) {
for (col in left..r) {
if (grid[t][col] == 1) {
visited[t][col] = true
q.offer(intArrayOf(t, col))
}
}
t++
}
// RIGHT
if (top <= bottom && left <= r) {
for (row in top..bottom) {
if (grid[row][r] == 1) {
visited[row][r] = true
q.offer(intArrayOf(row, r))
}
}
r--
}
}
@Suppress("UNUSED_CHANGED_VALUE")
private fun calculateBottomLeft(
q: Queue<IntArray>,
top: Int = 0,
bottom: Int,
left: Int = 0,
right: Int,
grid: Array<IntArray>,
visited: Array<BooleanArray>,
) {
var b = bottom
// DOWN
if (top <= b && left <= right) {
for (col in right downTo left) {
if (grid[b][col] == 1) {
visited[b][col] = true
q.offer(intArrayOf(b, col))
}
}
b--
}
// LEFT
if (top <= bottom && left <= right) {
for (row in bottom downTo top) {
if (grid[row][left] == 1) {
visited[row][left] = true
q.offer(intArrayOf(row, left))
}
}
}
}
private fun isValid(
grid: Array<IntArray>,
visited: Array<BooleanArray>,
row: Int,
col: Int,
rows: Int,
cols: Int,
): Boolean {
if (!validCoords(row, col, rows, cols)) return false
return if (visited[row][col]) {
false
} else {
grid[row][col] == 1
}
}
private fun validCoords(row: Int, col: Int, rows: Int, cols: Int): Boolean {
return row in 0 until rows && col >= 0 && col < cols
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 5,682 | kotlab | Apache License 2.0 |
src/Day02.kt | pimtegelaar | 572,939,409 | false | {"Kotlin": 24985} | const val WIN = 6
const val LOSE = 0
const val DRAW = 3
const val ROCK = 1
const val PAPER = 2
const val SCISSORS = 3
fun main() {
fun part1(input: List<String>) = input.sumOf {
when (it) {
"A X" -> DRAW + ROCK
"A Y" -> WIN + PAPER
"A Z" -> LOSE + SCISSORS
"B X" -> LOSE + ROCK
"B Y" -> DRAW + PAPER
"B Z" -> WIN + SCISSORS
"C X" -> WIN + ROCK
"C Y" -> LOSE + PAPER
"C Z" -> DRAW + SCISSORS
else -> throw UnsupportedOperationException("Unknown case $it")
}
}
fun part2(input: List<String>) = input.sumOf {
when (it) {
"A X" -> LOSE + SCISSORS
"A Y" -> DRAW + ROCK
"A Z" -> WIN + PAPER
"B X" -> LOSE + ROCK
"B Y" -> DRAW + PAPER
"B Z" -> WIN + SCISSORS
"C X" -> LOSE + PAPER
"C Y" -> DRAW + SCISSORS
"C Z" -> WIN + ROCK
else -> throw UnsupportedOperationException("Unknown case $it")
}
}
val testInput = readInput("Day02_test")
val input = readInput("Day02")
val part1 = part1(testInput)
check(part1 == 15) { part1 }
println(part1(input))
val part2 = part2(testInput)
check(part2 == 12) { part2 }
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 16ac3580cafa74140530667413900640b80dcf35 | 1,346 | aoc-2022 | Apache License 2.0 |
src/net/sheltem/aoc/y2022/Day08.kt | jtheegarten | 572,901,679 | false | {"Kotlin": 178521} | package net.sheltem.aoc.y2022
class Day08 : Day<Int>(21, 8) {
override suspend fun part1(input: List<String>): Int = input.trees().countVisible()
override suspend fun part2(input: List<String>): Int = input.trees().toScenicScores().max()
}
suspend fun main() {
Day08().run()
}
private fun Array<Array<Int>>.countVisible(): Int = countEdges() + countInsides()
private fun List<String>.trees(): Array<Array<Int>> = map { it.toTreeLine() }.toTypedArray()
private fun String.toTreeLine() = this.toCharArray().map { it.digitToInt() }.toTypedArray()
private fun Array<Array<Int>>.countEdges() = (size + this[0].size - 2) * 2
private fun Array<Array<Int>>.countInsides(): Int {
var visibles = 0
for (i in 1 until (this.size - 1)) {
for (j in 1 until (this[i].size - 1)) {
if (isVisible(i, j, this)) visibles++
}
}
return visibles
}
private fun scenicScore(i: Int, j: Int, array: Array<Array<Int>>) =
array[i][j].let { currentTree ->
array[i].take(j).reversed().viewDistance(currentTree)
.times(array[i].takeLast(array[i].size - (j + 1)).viewDistance(currentTree))
.times(array.take(i).map { it[j] }.reversed().viewDistance(currentTree))
.times(array.takeLast(array.size - (i + 1)).map { it[j] }.viewDistance(currentTree))
}
private fun List<Int>.viewDistance(maxHeight: Int) = indexOfFirst { it >= maxHeight }.let { if (it == -1) size else it + 1 }
private fun isVisible(i: Int, j: Int, array: Array<Array<Int>>): Boolean =
array[i][j].let { currentTree ->
array[i].take(j).all { it < currentTree }
|| array[i].takeLast(array[i].size - (j + 1)).all { it < currentTree }
|| array.take(i).map { it[j] }.all { it < currentTree }
|| array.takeLast(array.size - (i + 1)).map { it[j] }.all { it < currentTree }
}
private fun Array<Array<Int>>.toScenicScores(): List<Int> {
val scenicScores = mutableListOf<Int>()
for (i in indices) {
for (j in this[i].indices) {
scenicScores.add(scenicScore(i, j, this))
}
}
return scenicScores
}
| 0 | Kotlin | 0 | 0 | ac280f156c284c23565fba5810483dd1cd8a931f | 2,147 | aoc | Apache License 2.0 |
src/Day01.kt | arturkowalczyk300 | 573,084,149 | false | {"Kotlin": 31119} | fun main() {
fun part1(input: List<String>): Int {
var maxCalories = 0
var currentCalories = 0
input.forEach {
if (it != "")
currentCalories += it.toIntOrNull() ?: 0
else {
if (currentCalories > maxCalories)
maxCalories = currentCalories
currentCalories = 0
}
}
return maxCalories
}
fun part2(input: List<String>): Int {
val sumOfCalories = mutableListOf<Int>()
var currentCalories = 0
input.forEach {
if (it != "")
currentCalories += it.toIntOrNull() ?: 0
else {
sumOfCalories.add(currentCalories)
currentCalories = 0
}
}
sumOfCalories.sortDescending()
return ((sumOfCalories.getOrNull(0) ?: 0)
+ (sumOfCalories.getOrNull(1) ?: 0)
+ (sumOfCalories.getOrNull(2) ?: 0))
}
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 69a51e6f0437f5bc2cdf909919c26276317b396d | 1,090 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/treesandgraphs/MostStonesRemovedWithSameRowOrColumn.kt | e-freiman | 471,473,372 | false | {"Kotlin": 78010} | package treesandgraphs
private var xIndex = mapOf<Int, List<Int>>()
private var yIndex = mapOf<Int, List<Int>>()
private var visited = booleanArrayOf()
private fun dfs(stones: Array<IntArray>, index: Int): Int {
visited[index] = true
var sum = 0
for (i in xIndex[stones[index][0]]!!) {
if (!visited[i]) {
sum += dfs(stones, i) + 1
}
}
for (i in yIndex[stones[index][1]]!!) {
if (!visited[i]) {
sum += dfs(stones, i) + 1
}
}
return sum
}
fun removeStones(stones: Array<IntArray>): Int {
xIndex = stones.indices.groupBy({stones[it][0]},{it})
yIndex = stones.indices.groupBy({stones[it][1]},{it})
visited = BooleanArray(stones.size) { false }
var stonesToRemove = 0
for (i in stones.indices) {
if (!visited[i]) {
stonesToRemove += dfs(stones, i)
}
}
return stonesToRemove
}
fun main() {
println(removeStones(arrayOf(intArrayOf(0, 0), intArrayOf(0, 1), intArrayOf(1, 0),
intArrayOf(1, 2), intArrayOf(2, 1), intArrayOf(2, 2))))
}
| 0 | Kotlin | 0 | 0 | fab7f275fbbafeeb79c520622995216f6c7d8642 | 1,081 | LeetcodeGoogleInterview | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/NumMusicPlaylists.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 dev.shtanko.algorithms.MOD
import java.util.Arrays
import kotlin.math.min
/**
* 920. Number of Music Playlists
* @see <a href="https://leetcode.com/problems/number-of-music-playlists">Source</a>
*/
fun interface NumMusicPlaylists {
operator fun invoke(n: Int, goal: Int, k: Int): Int
}
/**
* Approach 1: Bottom-up Dynamic Programming
*/
class NumMusicPlaylistsBottomUp : NumMusicPlaylists {
override operator fun invoke(n: Int, goal: Int, k: Int): Int {
// Initialize the DP table
val dp = Array(goal + 1) { LongArray(n + 1) }
dp[0][0] = 1
for (i in 1..goal) {
for (j in 1..min(i, n)) {
// The i-th song is a new song
dp[i][j] = dp[i - 1][j - 1] * (n - j + 1) % MOD
// The i-th song is a song we have played before
if (j > k) {
dp[i][j] = (dp[i][j] + dp[i - 1][j] * (j - k)) % MOD
}
}
}
return dp[goal][n].toInt()
}
}
/**
* Approach 2: Top-down Dynamic Programming (Memoization)
*/
class NumMusicPlaylistsTopDown : NumMusicPlaylists {
private lateinit var dp: Array<LongArray>
override operator fun invoke(n: Int, goal: Int, k: Int): Int {
dp = Array(goal + 1) { LongArray(n + 1) }
for (row in dp) {
Arrays.fill(row, -1L)
}
return numberOfPlaylists(goal, n, k, n).toInt()
}
private fun numberOfPlaylists(i: Int, j: Int, k: Int, n: Int): Long {
// Base cases
if (i == 0 && j == 0) {
return 1
}
if (i == 0 || j == 0) {
return 0
}
if (dp[i][j] != -1L) {
return dp[i][j]
}
// DP transition: add a new song or replay an old one
dp[i][j] = numberOfPlaylists(i - 1, j - 1, k, n) * (n - j + 1) % MOD
if (j > k) {
dp[i][j] = (dp[i][j] + numberOfPlaylists(i - 1, j, k, n) * (j - k) % MOD) % MOD
}
return dp[i][j]
}
}
/**
* Approach 3: Combinatorics
*/
class NumMusicPlaylistsCombinatorics : NumMusicPlaylists {
// Pre-calculated factorials and inverse factorials
private lateinit var factorial: LongArray
private lateinit var invFactorial: LongArray
override operator fun invoke(n: Int, goal: Int, k: Int): Int {
// Pre-calculate factorials and inverse factorials
precalculateFactorials(n)
// Initialize variables for calculation
var sign = 1
var answer: Long = 0
// Loop from 'n' down to 'k'
for (i in n downTo k) {
// Calculate temporary result for this iteration
var temp = power(i - k.toLong(), goal - k)
temp = temp * invFactorial[n - i] % MOD
temp = temp * invFactorial[i - k] % MOD
// Add or subtract temporary result to/from answer
answer = (answer + sign * temp + MOD) % MOD
// Flip sign for next iteration
sign *= -1
}
// Final result is n! * answer, all under modulo
return (factorial[n] * answer % MOD).toInt()
}
// Method to pre-calculate factorials and inverse factorials up to 'n'
private fun precalculateFactorials(n: Int) {
factorial = LongArray(n + 1)
invFactorial = LongArray(n + 1)
factorial[0] = 1
invFactorial[0] = 1
// Calculate factorials and inverse factorials for each number up to 'n'
for (i in 1..n) {
factorial[i] = factorial[i - 1] * i % MOD
// Inverse factorial calculated using Fermat's Little Theorem
invFactorial[i] = power(factorial[i], MOD - 2)
}
}
// Method to calculate power of a number under modulo using binary exponentiation
private fun power(base: Long, exponent: Int): Long {
var result = 1L
// Loop until exponent is not zero
var exp = exponent
var b = base
while (exp > 0) {
// If exponent is odd, multiply result with base
if (exp and 1 == 1) {
result = result * b % MOD
}
// Divide the exponent by 2 and square the base
exp = exp shr 1
b = b * b % MOD
}
return result
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 4,935 | kotlab | Apache License 2.0 |
src/main/kotlin/days/Day9.kt | MisterJack49 | 729,926,959 | false | {"Kotlin": 31964} | package days
class Day9 : Day(9) {
override fun partOne(): Any {
return inputList
.map { line -> line.split(" ").map { it.toInt() } }
.map { it.extrapolate() }
.sumOf { it.last() }
}
override fun partTwo(): Any {
return inputList
.map { line -> line.split(" ").map { it.toInt() } }
.map { it.reversed().extrapolate() }
.sumOf { it.last() }
}
private fun List<Int>.differential(): List<Int> =
zipWithNext().map { it.second - it.first }
private fun List<Int>.chainDifferential(): List<List<Int>> =
generateSequence(this) { it.differential() }
.takeWhile {list -> list.any { it != 0 } }
.let { it.plusElement(it.last().differential()) }
.toList()
private fun List<Int>.extrapolate(diff: Int) =
plus(last() + diff)
private fun List<Int>.extrapolate() =
chainDifferential()
.reversed()
.foldIndexed(emptyList<Int>()) { index, previous, current ->
if (index == 0) current.plus(0) else current.extrapolate(previous.last())
}
}
| 0 | Kotlin | 0 | 0 | 807a6b2d3ec487232c58c7e5904138fc4f45f808 | 1,182 | AoC-2023 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/leetcode/kotlin/tree/1305. All Elements in Two Binary Search Trees.kt | sandeep549 | 262,513,267 | false | {"Kotlin": 530613} | package leetcode.kotlin.tree
import java.util.*
import kotlin.collections.ArrayList
// Taken from
// https://leetcode.com/problems/all-elements-in-two-binary-search-trees/discuss/464368/Short-O(n)-Python
// In Java also, time performance is almost O(n) when input is almost sorted, which is true in this case.
// Seems java also adopted Timsort for some special cases
private fun getAllElements(root1: TreeNode?, root2: TreeNode?): List<Int> {
var ans = mutableListOf<Int>()
fun dfs(root: TreeNode?) {
root?.let {
dfs(it.left)
ans.add(it.`val`)
dfs(it.right)
}
}
dfs(root1)
dfs(root2)
ans.sort() // Timsort, almost O(n) performance
return ans
}
private fun getAllElements2(root1: TreeNode?, root2: TreeNode?): List<Int> {
var list1 = ArrayList<Int>()
var list2 = ArrayList<Int>()
fun collect(node: TreeNode?, list: ArrayList<Int>) {
if (node != null) {
collect(node.left, list)
list.add(node.`val`)
collect(node.right, list)
}
}
collect(root1, list1)
collect(root2, list2)
var i = 0
var j = 0
var mergedList = ArrayList<Int>()
while (i < list1.size && j < list2.size) {
if (list1.get(i) <= list2.get(j)) {
mergedList.add(list1.get(i++))
} else {
mergedList.add(list2.get(j++))
}
}
while (i < list1.size) mergedList.add(list1.get(i++))
while (j < list2.size) mergedList.add(list2.get(j++))
return mergedList
}
private fun getAllElements3(root1: TreeNode?, root2: TreeNode?): List<Int> {
fun collectIterative(root: TreeNode?): ArrayList<Int> {
var list = ArrayList<Int>()
var stack = Stack<TreeNode>()
var curr = root
while (curr != null || !stack.isEmpty()) {
while (curr != null) {
stack.push(curr)
curr = curr.left
}
curr = stack.pop()
list.add(curr.`val`)
curr = curr.right
}
return list
}
var list1 = collectIterative(root1)
var list2 = collectIterative(root2)
var i = 0
var j = 0
var mergedList = ArrayList<Int>()
while (i < list1.size && j < list2.size) {
if (list1.get(i) <= list2.get(j)) {
mergedList.add(list1.get(i++))
} else {
mergedList.add(list2.get(j++))
}
}
while (i < list1.size) mergedList.add(list1.get(i++))
while (j < list2.size) mergedList.add(list2.get(j++))
return mergedList
}
/**
* Traverse iteratively both tree same time inroder, take smallest elment and add it to the list.
* O(n)
* O(n)
*/
private fun getAllElements4(root1: TreeNode?, root2: TreeNode?): List<Int> {
val stack1: ArrayDeque<TreeNode> = ArrayDeque()
val stack2: ArrayDeque<TreeNode> = ArrayDeque()
val output: MutableList<Int> = ArrayList()
var root1 = root1
var root2 = root2
while (root1 != null || root2 != null || !stack1.isEmpty() || !stack2.isEmpty()) {
while (root1 != null) {
stack1.push(root1)
root1 = root1.left
}
while (root2 != null) {
stack2.push(root2)
root2 = root2.left
}
// Add the smallest value into output,
// pop it from the stack,
// and then do one step right
if (stack2.isEmpty() || !stack1.isEmpty() && stack1.first.`val` <= stack2.first.`val`) {
root1 = stack1.pop()
output.add(root1.`val`)
root1 = root1.right
} else {
root2 = stack2.pop()
output.add(root2.`val`)
root2 = root2.right
}
}
return output
}
| 1 | Kotlin | 0 | 0 | cf357cdaaab2609de64a0e8ee9d9b5168c69ac12 | 3,740 | leetcode-kotlin | Apache License 2.0 |
src/Day16.kt | flex3r | 572,653,526 | false | {"Kotlin": 63192} | import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
suspend fun main() {
val testInput = readInput("Day16_test")
check(part1(testInput) == 1651)
check(part2(testInput) == 1707)
val input = readInput("Day16")
measureAndPrintResult {
part1(input)
}
measureAndPrintResult {
part2(input)
}
}
private fun part1(input: List<String>): Int {
val (pathDistances, flowRates, tunnels) = parseTunnels(input)
return solve("AA", tunnels, 0, 0, 0, pathDistances, flowRates, 30)
}
private suspend fun part2(input: List<String>): Int = coroutineScope {
val (pathDistances, flowRates, tunnels) = parseTunnels(input)
(1..tunnels.size / 2).maxOf { i ->
combinations(tunnels, i).toList().map { tunnelsCombination ->
async {
val opposite = tunnels - tunnelsCombination.toSet()
val ownScore = solve("AA", tunnelsCombination, 0, 0, 0, pathDistances, flowRates, 26)
val elephantScore = solve("AA", opposite, 0, 0, 0, pathDistances, flowRates, 26)
ownScore + elephantScore
}
}.awaitAll().max()
}
}
private fun solve(
tunnel: String,
remainingTunnels: List<String>,
time: Int,
flow: Int,
pressure: Int,
pathDistances: Map<String, Map<String, Int>>,
flowRates: Map<String, Int>,
limit: Int,
): Int {
// initial pressure for current time and flow
var maxPressure = pressure + (limit - time) * flow
remainingTunnels.forEach { newTunnel ->
val travelAndOpenTime = pathDistances.getValue(tunnel).getValue(newTunnel) + 1
if (time + travelAndOpenTime >= limit) return@forEach
val newTime = time + travelAndOpenTime
val newPressure = pressure + travelAndOpenTime * flow
val newFlow = flow + flowRates.getValue(newTunnel)
val newRemainingTunnels = remainingTunnels - newTunnel
val newScore = solve(newTunnel, newRemainingTunnels, newTime, newFlow, newPressure, pathDistances, flowRates, limit)
if (newScore > maxPressure) {
maxPressure = newScore
}
}
return maxPressure
}
private fun parseTunnels(input: List<String>): Triple<Map<String, Map<String, Int>>, Map<String, Int>, List<String>> {
val flowRates = mutableMapOf<String, Int>()
val paths = mutableMapOf<String, List<String>>()
val tunnels = input.map {
val (data, tunnels) = it.split(";")
val name = data.substringAfter("Valve ").substringBefore(" has")
val rate = data.substringAfter("rate=").toInt()
val otherValves = tunnels.substringAfter("valves ", missingDelimiterValue = "")
.ifEmpty { tunnels.substringAfter("valve ") }
.split(", ")
flowRates[name] = rate
paths[name] = otherValves
name
}
val shortestPathDistances = tunnels.associateWith { t1 ->
tunnels.associateWith { t2 -> bfs(t1) { paths.getValue(it) }.first { it.value == t2 }.index }
}
// reduces tunnels from 59 to 15!!
val tunnelsWithNonZeroRate = tunnels.filter { flowRates.getValue(it) > 0 }
return Triple(shortestPathDistances, flowRates, tunnelsWithNonZeroRate)
} | 0 | Kotlin | 0 | 0 | 8604ce3c0c3b56e2e49df641d5bf1e498f445ff9 | 3,250 | aoc-22 | Apache License 2.0 |
src/main/kotlin/day8/Day8.kt | Arch-vile | 317,641,541 | false | null | package day8
import readFile
enum class InstructionType {
NOP, ACC, JMP
}
data class Instruction(
val type: InstructionType,
val value: Int,
var isExecuted: Boolean = false) {
fun execute(memory: Memory): Int {
isExecuted = true
when (type) {
InstructionType.ACC -> memory.accumulator += value
InstructionType.JMP -> Unit
InstructionType.NOP -> Unit
}
return when (type) {
InstructionType.ACC -> 1
InstructionType.JMP -> value
InstructionType.NOP -> 1
}
}
}
data class Memory(var accumulator: Int = 0)
data class ReturnValue(val value: Int, val code: Int)
data class Computer(
val instructions: List<Instruction>,
var memory: Memory = Memory(),
var pointer: Int = 0) {
fun run(): ReturnValue {
val nextInstruction = instructions[pointer]
if (nextInstruction.isExecuted) {
return ReturnValue(memory.accumulator, -1)
}
pointer += nextInstruction.execute(memory)
if (pointer == instructions.size) {
return ReturnValue(memory.accumulator, 0)
}
return run()
}
}
fun main(args: Array<String>) {
val instructions = instructionsFromFile()
// Part 1
val computer = Computer(clone(instructions))
val output = computer.run()
println(output)
// Part 2
part2(instructions)
}
fun part2(instructionsO: List<Instruction>) {
var nextInstructionToChange = 0
var instructions = clone(instructionsO)
while (true) {
val computer = Computer(instructions)
var result = computer.run()
if (result.code == 0) {
println(result.value)
break
}
instructions = changeInstruction(nextInstructionToChange, clone(instructionsO))
nextInstructionToChange++
}
}
fun changeInstruction(instructionIndex: Int, instructions: List<Instruction>): List<Instruction> {
var instruction = instructions[instructionIndex]
if (instruction.type == InstructionType.NOP) {
instruction = instruction.copy(type = InstructionType.JMP)
} else if (instruction.type == InstructionType.JMP) {
instruction = instruction.copy(type = InstructionType.NOP)
}
var mutableList = instructions.toMutableList()
mutableList[instructionIndex] = instruction
return mutableList
}
private fun instructionsFromFile() = readFile("./src/main/resources/day8Input.txt")
.map { parse(it) }
fun parse(row: String): Instruction {
val regexp = """([a-z]{3}) ((?:\+|-)\d+)""".toRegex()
val values = regexp.find(row)?.groupValues!!
return Instruction(InstructionType.valueOf(values[1].toUpperCase()),
values[2].toInt()
)
}
fun clone(instructions: List<Instruction>): List<Instruction> {
return instructions.map { it.copy() }
}
| 0 | Kotlin | 0 | 0 | 12070ef9156b25f725820fc327c2e768af1167c0 | 2,676 | adventOfCode2020 | Apache License 2.0 |
src/test/kotlin/nl/dirkgroot/adventofcode/year2022/Day18Test.kt | dirkgroot | 317,968,017 | false | {"Kotlin": 187862} | package nl.dirkgroot.adventofcode.year2022
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import nl.dirkgroot.adventofcode.util.input
import nl.dirkgroot.adventofcode.util.invokedWith
import java.util.ArrayDeque
private fun solution1(input: String) = parseCubes(input).allSurfaceSides().size
private fun solution2(input: String) = parseCubes(input).surfaceSidesTouchedBySteam().size
private fun parseCubes(input: String) = input.lineSequence()
.map { it.split(",").let { (x, y, z) -> Cube(x.toInt(), y.toInt(), z.toInt()) } }
.toSet()
private fun Set<Cube>.surfaceSidesTouchedBySteam(): List<Side> {
val steam = mutableSetOf<Cube>()
val queue = ArrayDeque<Cube>()
val xRange = minOf { it.x1 } - 1 until maxOf { it.x2 } + 1
val yRange = minOf { it.y1 } - 1 until maxOf { it.y2 } + 1
val zRange = minOf { it.z1 } - 1 until maxOf { it.z2 } + 1
queue.add(Cube(xRange.first, yRange.first, zRange.first))
while (queue.isNotEmpty()) {
val candidate = queue.removeFirst()
if (!contains(candidate) && !steam.contains(candidate)) {
steam.add(candidate)
queue.addAll(candidate.neighbors().filter { it.x1 in xRange && it.y1 in yRange && it.z1 in zRange })
}
}
return steam.allSurfaceSides().filter {
it.x1 - 1 in xRange && it.x2 in xRange && it.y1 - 1 in yRange && it.y2 in yRange && it.z1 - 1 in zRange && it.z2 in zRange
}
}
private fun Set<Cube>.allSurfaceSides() = allSides().groupBy { it }
.filter { (_, sides) -> sides.size == 1 }.map { (side, _) -> side }
private fun Set<Cube>.allSides() = asSequence().flatMap { it.sides() }
private data class Side(val x1: Int, val y1: Int, val z1: Int, val x2: Int, val y2: Int, val z2: Int)
private data class Cube(val x1: Int, val y1: Int, val z1: Int) {
val x2 = x1 + 1
val y2 = y1 + 1
val z2 = z1 + 1
fun sides() = sequenceOf(
Side(x1, y1, z1, x1, y2, z2), Side(x1, y1, z1, x2, y1, z2), Side(x1, y1, z1, x2, y2, z1),
Side(x1, y1, z2, x2, y2, z2), Side(x1, y2, z1, x2, y2, z2), Side(x2, y1, z1, x2, y2, z2),
)
fun neighbors() = sequenceOf(
Cube(x1 - 1, y1, z1), Cube(x1 + 1, y1, z1),
Cube(x1, y1 - 1, z1), Cube(x1, y1 + 1, z1),
Cube(x1, y1, z1 - 1), Cube(x1, y1, z1 + 1),
)
}
//===============================================================================================\\
private const val YEAR = 2022
private const val DAY = 18
class Day18Test : StringSpec({
"example part 1" { ::solution1 invokedWith exampleInput shouldBe 64 }
"part 1 solution" { ::solution1 invokedWith input(YEAR, DAY) shouldBe 4500 }
"example part 2" { ::solution2 invokedWith exampleInput shouldBe 58 }
"part 2 solution" { ::solution2 invokedWith input(YEAR, DAY) shouldBe 2558 }
})
private val exampleInput =
"""
2,2,2
1,2,2
3,2,2
2,1,2
2,3,2
2,2,1
2,2,3
2,2,4
2,2,6
1,2,5
3,2,5
2,1,5
2,3,5
""".trimIndent()
| 1 | Kotlin | 1 | 1 | ffdffedc8659aa3deea3216d6a9a1fd4e02ec128 | 3,074 | adventofcode-kotlin | MIT License |
kotest-property/src/commonMain/kotlin/io/kotest/property/arbitrary/ints.kt | swanandvk | 284,610,632 | true | {"Kotlin": 2715433, "HTML": 423, "Java": 145} | package io.kotest.property.arbitrary
import io.kotest.property.Arb
import io.kotest.property.Shrinker
import kotlin.math.abs
import kotlin.random.nextInt
fun Arb.Companion.int(min: Int, max: Int) = int(min..max)
/**
* Returns an [Arb] where each value is a randomly chosen [Int] in the given range.
* The edgecases are: [[Int.MIN_VALUE], [Int.MAX_VALUE], 0, 1, -1] with any not in the range
* filtered out.
*/
fun Arb.Companion.int(range: IntRange = Int.MIN_VALUE..Int.MAX_VALUE): Arb<Int> {
val edgecases = listOf(0, 1, -1, Int.MAX_VALUE, Int.MIN_VALUE).filter { it in range }
return arbitrary(edgecases, IntShrinker(range)) { it.random.nextInt(range) }
}
/**
* Returns an [Arb] where each value is a randomly chosen natural integer.
* The edge cases are: [[Int.MAX_VALUE], 1]
*/
fun Arb.Companion.nats(max: Int = Int.MAX_VALUE) = int(1..max).filter { it > 0 }
/**
* Returns an [Arb] where each value is a randomly chosen negative integer.
* The edge cases are: [[Int.MIN_VALUE], -1]
*/
fun Arb.Companion.negativeInts(min: Int = Int.MIN_VALUE) = int(min..0).filter { it < 0 }
/**
* Returns an [Arb] where each value is a randomly chosen positive integer.
* The edge cases are: [[Int.MAX_VALUE], 1]
*/
fun Arb.Companion.positiveInts(max: Int = Int.MAX_VALUE) = int(1..max).filter { it > 0 }
class IntShrinker(val range: IntRange) : Shrinker<Int> {
override fun shrink(value: Int): List<Int> =
when (value) {
0 -> emptyList()
1, -1 -> listOf(0).filter { it in range }
else -> {
val a = listOf(0, 1, -1, abs(value), value / 3, value / 2, value * 2 / 3)
val b = (1..5).map { value - it }.reversed().filter { it > 0 }
(a + b).distinct()
.filterNot { it == value }
.filter { it in range }
}
}
}
fun <A, B> Shrinker<A>.bimap(f: (B) -> A, g: (A) -> B): Shrinker<B> = object : Shrinker<B> {
override fun shrink(value: B): List<B> = this@bimap.shrink(f(value)).map(g)
}
| 5 | Kotlin | 0 | 1 | 6d7dcaa2c96db13c7e81ba76b9f8dd95b7113871 | 2,008 | kotest | Apache License 2.0 |
day09/kotlin/RJPlog/day2309_1_2.kt | mr-kaffee | 720,687,812 | false | {"Rust": 223627, "Kotlin": 46100, "Python": 39390, "Shell": 3369, "Haskell": 3122, "Dockerfile": 2236, "Gnuplot": 1678, "C++": 980, "HTML": 592, "CMake": 314} | import java.io.File
import kotlin.math.*
fun day09(in1: Int): Long {
var result = 0L
var lines = File("day2309_puzzle_input.txt").readLines()
lines.forEach {
var line = it.split(" ").map { it.toLong() }.toList()
var interpolationValues = mutableListOf<Long>()
var diffList = mutableListOf<Long>()
if (in1 == 1) {
diffList = line.windowed(2).map { it[1] - it[0] }.toMutableList()
interpolationValues.add(line.last())
interpolationValues.add(diffList.last())
} else {
diffList = line.windowed(2).map { it[0] - it[1] }.toMutableList()
interpolationValues.add(line.first())
interpolationValues.add(diffList.first())
}
while (diffList.distinct().size > 1 || diffList[0] != 0L) {
if (in1 == 1) {
diffList = diffList.windowed(2).map { it[1] - it[0] }.toMutableList()
interpolationValues.add(diffList.last())
} else {
diffList = diffList.windowed(2).map { it[0] - it[1] }.toMutableList()
interpolationValues.add(diffList.first())
}
}
result += interpolationValues.sum()
}
return result
}
fun main() {
var t1 = System.currentTimeMillis()
var solution1 = day09(1)
var solution2 = day09(2)
// print solution for part 1
println("*******************************")
println("--- Day 9: Mirage Maintenance ---")
println("*******************************")
println("Solution for part1")
println(" $solution1 ")
println()
// print solution for part 2
println("*******************************")
println("Solution for part2")
println(" $solution2 ")
println()
t1 = System.currentTimeMillis() - t1
println("puzzle solved in ${t1} ms")
}
| 0 | Rust | 2 | 0 | 5cbd13d6bdcb2c8439879818a33867a99d58b02f | 1,610 | aoc-2023 | MIT License |
src/main/kotlin/adventofcode2023/day18/day18.kt | dzkoirn | 725,682,258 | false | {"Kotlin": 133478} | package adventofcode2023.day18
import adventofcode2023.Point
import adventofcode2023.col
import adventofcode2023.line
import adventofcode2023.readInput
import java.awt.geom.Point2D
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import kotlin.time.measureTime
data class Line(
val start: Point,
val end: Point
)
fun makeLine(prevPoint: Point, direction: String, steps: Int): Line {
val newPoint = when (direction) {
"U" -> prevPoint.copy(first = prevPoint.line - steps)
"R" -> prevPoint.copy(second = prevPoint.col + steps)
"D" -> prevPoint.copy(first = prevPoint.line + steps)
"L" -> prevPoint.copy(second = prevPoint.col - steps)
else -> throw IllegalArgumentException("Could not handle $direction")
}
return Line(prevPoint, newPoint)
}
fun parseInputToGraph(input: List<String>): List<Line> {
val split = input.map { line -> line.split(' ') }
val firstLine = split.first().let { (dir, steps, _) -> makeLine(Point(0, 0), dir, steps.toInt()) }
return split.subList(1, split.size).fold(mutableListOf(firstLine)) { acc, (dir, steps, _) ->
val newLine = makeLine(acc.last.end, dir, steps.toInt())
acc.apply {
add(newLine)
}
}
}
fun visualizeGraph(polygon: List<Line>): String {
val startLine = polygon.minBy { it.start.line }.start.line
val endLine = polygon.maxBy { it.end.line }.end.line
val startCol = polygon.minBy { it.start.col }.start.col
val endCol = polygon.maxBy { it.end.col }.end.col
return buildString {
for (i in startLine..endLine) {
for (j in startCol..endCol) {
val isBorder = isPointABorder(i, j, polygon)
if (isBorder) {
append('#')
} else {
append('.')
}
}
append(System.lineSeparator())
}
}
}
fun isPointABorder(pLine: Int, pCol: Int, polygon: List<Line>): Boolean {
return polygon.any { line ->
pLine in (min(line.start.line, line.end.line)..max(line.start.line, line.end.line)) &&
pCol in (min(line.start.col, line.end.col)..max(line.start.col, line.end.col))
}
}
fun isPointInsidePolygon(pLine: Int, pCol: Int, polygon: List<Line>): Boolean {
var inside = false
for (line in polygon) {
if ((line.start.col > pCol) != (line.end.col > pCol) &&
pLine < (line.end.line - line.start.line) * (pCol - line.start.col) / (line.end.col - line.start.col) + line.start.line
) {
inside = !inside
}
}
return inside
}
fun countPointsInsidePolygon(polygon: List<Line>): Int {
val startLine = polygon.minBy { it.start.line }.start.line
val endLine = polygon.maxBy { it.end.line }.end.line
val startCol = polygon.minBy { it.start.col }.start.col
val endCol = polygon.maxBy { it.end.col }.end.col
var count = 0
for (i in startLine..endLine) {
for (j in startCol..endCol) {
val isBorder = isPointABorder(i, j, polygon)
if (isBorder) {
print('*')
count++
continue
}
val isInside = isPointInsidePolygon(i, j, polygon)
if (isInside) {
print('#')
count++
} else {
print('.')
}
}
println()
}
return count
}
fun puzzle1(input: List<String>): Int {
val graph = parseInputToGraph(input)
return countPointsInsidePolygon(graph)
}
fun parseHex(hex: String): Pair<String, Int> {
return hex.substring(hex.indexOf('#') + 1).let {
Pair(
when (val c = it.last()) {
'0' -> "R"
'1' -> "D"
'2' -> "L"
'3' -> "U"
else -> throw IllegalArgumentException("Illegal arrgument $c")
},
it.substring(0, 5).toInt(radix = 16)
)
}
}
fun parseInputToGraph2(input: List<String>): List<Line> {
val split = input.map { line -> line.split(' ') }
val firstLine = split.first().let { (_, _, hexNumber) ->
val (dir, steps) = parseHex(hexNumber.substring(hexNumber.indexOf('(') + 1, hexNumber.indexOf(')') ))
makeLine(Point(0, 0), dir, steps) }
return split.subList(1, split.size).fold(mutableListOf(firstLine)) { acc, (_, _, hexNumber) ->
val (dir, steps) = parseHex(hexNumber.substring(hexNumber.indexOf('(') + 1, hexNumber.indexOf(')')))
val newLine = makeLine(acc.last.end, dir, steps)
acc.apply {
add(newLine)
}
}
}
/**
* Works like a charm!
* Thanks https://www.reddit.com/r/adventofcode/comments/18l2nk2/2023_day_18_easiest_way_to_solve_both_parts/ and
* https://github.com/wilkotom/Aoc2023/blob/main/day18/src/main.rs
*/
fun shoelaceFormula(lines: List<Line>): Long {
val perimeter = lines.fold(0L) { p, l -> p + max(abs(l.end.line - l.start.line), abs(l.end.col - l.start.col))}
val points = listOf(lines.first.start) + lines.map { it.end }
val area = abs(points.windowed(size = 2).fold(0L) { area, (p1, p2) ->
area + (p1.line.toLong() * p2.col.toLong() - p2.line.toLong() * p1.col.toLong())
} / 2)
return area + (perimeter / 2) + 1
}
fun puzzle2(input: List<String>): Long {
val graph = parseInputToGraph2(input)
return shoelaceFormula(graph)
}
fun main() {
println("Day 18")
val input = readInput("day18")
val time1 = measureTime {
println("Puzzle 1 ${puzzle1(input)}")
}
println("Puzzle 1 took $time1")
val time2 = measureTime {
println("Puzzle 2 ${puzzle2(input)}")
}
println("Puzzle 2 took $time2")
}
| 0 | Kotlin | 0 | 0 | 8f248fcdcd84176ab0875969822b3f2b02d8dea6 | 5,760 | adventofcode2023 | MIT License |
src/main/kotlin/com/mantono/lingress/Regression.kt | mantono | 100,183,137 | false | null | package com.mantono.lingress
data class RegressionLine(val m: Double, val b: Double)
{
fun y(x: Double): Double = m*x+b
fun x(y: Double): Double = (y-b)/m
operator fun get(x: Double): Double = y(x)
override fun toString(): String = "y = $m * x + $b"
}
data class Point(val x: Double, val y: Double)
{
constructor(independent: Number, dependent: Number): this(independent.toDouble(), dependent.toDouble())
}
fun residual(line: RegressionLine, point: Point): Double
{
val predictedY = line[point.x]
val actualY = point.y
return actualY - predictedY
}
fun sumOfSquaredErrors(line: RegressionLine, data: Collection<Point>): Double
{
return data.asSequence()
.map {squaredError(line, it)}
.sum()
}
fun squaredError(line: RegressionLine, p: Point): Double = Math.pow(residual(line, p), 2.0)
fun rootMeanSquareError(line: RegressionLine, data: Collection<Point>): Double
{
if(data.isEmpty())
return Double.NaN
if(data.size == 1)
return 0.0
val squaredErr = sumOfSquaredErrors(line, data) / (data.size - 1)
return Math.sqrt(squaredErr)
}
fun totalVariationInY(data: Collection<Point>): Double
{
val avg = data.asSequence()
.map { it.y }
.average()
return data
.asSequence()
.map { it.y - avg }
.map { Math.pow(it, 2.0) }
.sum()
}
inline fun squared(n: Double): Double = Math.pow(n, 2.0)
fun regressionLineFrom(c: Collection<Point>): RegressionLine
{
val xMean = c.asSequence()
.map { it.x }
.average()
val yMean = c.asSequence()
.map { it.y }
.average()
val xyMean = c.asSequence()
.map { it.x * it.y }
.average()
val xSquaredMean = c.asSequence()
.map {squared(it.x)}
.average()
val m: Double = (xMean * yMean - (xyMean)) / (Math.pow(xMean, 2.0) - xSquaredMean)
val b: Double = yMean - (m * xMean)
return RegressionLine(m, b)
} | 0 | Kotlin | 0 | 0 | 0c7cb0ff9b8feb946aea0d57538da8bd0423aada | 1,810 | linear-regression | MIT License |
src/main/kotlin/y2022/Day04.kt | jforatier | 432,712,749 | false | {"Kotlin": 44692} | package y2022
class Day04(private val data: List<String>) {
data class Section(val start: Int, val end: Int)
data class Assignment(val firstElf: Section, val secondElf: Section) {
fun fullyContain(): Boolean {
val firstElfRange = firstElf.start.rangeTo(firstElf.end)
val secondElfRange = secondElf.start.rangeTo(secondElf.end)
return firstElfRange.all { secondElfRange.contains(it) } || secondElfRange.all { firstElfRange.contains(it) }
}
fun neverContain(): Boolean {
val firstElfRange = firstElf.start.rangeTo(firstElf.end)
val secondElfRange = secondElf.start.rangeTo(secondElf.end)
return firstElfRange.any { secondElfRange.contains(it) } && secondElfRange.any { firstElfRange.contains(it) }
}
}
fun part1(): Int {
return data.map {
Assignment(
Section(it.split(",")[0].split("-")[0].toInt(), it.split(",")[0].split("-")[1].toInt()),
Section(it.split(",")[1].split("-")[0].toInt(), it.split(",")[1].split("-")[1].toInt())
)
}.count {
it.fullyContain()
}
}
fun part2(): Int {
return data.map {
Assignment(
Section(it.split(",")[0].split("-")[0].toInt(), it.split(",")[0].split("-")[1].toInt()),
Section(it.split(",")[1].split("-")[0].toInt(), it.split(",")[1].split("-")[1].toInt())
)
}.count {
it.neverContain()
}
}
}
| 0 | Kotlin | 0 | 0 | 2a8c0b4ccb38c40034c6aefae2b0f7d4c486ffae | 1,544 | advent-of-code-kotlin | MIT License |
math/SmallestIntegerDivisibleByK/kotlin/Solution.kt | YaroslavHavrylovych | 78,222,218 | false | {"Java": 284373, "Kotlin": 35978, "Shell": 2994} | import java.util.LinkedList
/**
* Given a positive integer K, you need to find the length of the smallest
* positive integer N such that N is divisible by K,
* and N only contains the digit 1.
* Return the length of N. If there is no such N, return -1.
* Note: N may not fit in a 64-bit signed integer.
* <br>
* https://leetcode.com/problems/smallest-integer-divisible-by-k/
*/
fun smallestRepunitDivByK(K: Int): Int {
if (K % 2 == 0 || K % 5 == 0) return -1
var l = 1L
var n = 1
while (l < K) {
n++
l = l * 10 + 1
}
l %= K
while (l != 0L) {
l = (((l % K) * (10 % K)) % K + 1) % K
if (n == Int.MAX_VALUE) return -1
n++
}
return n
}
fun main() {
print("Smallest Integer Divisible by K: ")
var a = true
a = a && smallestRepunitDivByK(1) == 1
a = a && smallestRepunitDivByK(3) == 3
a = a && smallestRepunitDivByK(7) == 6
a = a && smallestRepunitDivByK(12371) == 1012
println(if(a) "SUCCESS" else "FAIL")
}
| 0 | Java | 0 | 2 | cb8e6f7e30563e7ced7c3a253cb8e8bbe2bf19dd | 1,021 | codility | MIT License |
src/net/sheltem/aoc/y2015/Day07.kt | jtheegarten | 572,901,679 | false | {"Kotlin": 178521} | package net.sheltem.aoc.y2015
suspend fun main() {
Day07().run()
}
class Day07 : Day<Int>(72, 72) {
override suspend fun part1(input: List<String>): Int = solve(input)
override suspend fun part2(input: List<String>): Int = solve(input, 956)
private fun solve(input:List<String>, overrideB: Int? = null): Int {
var workList = if (overrideB!= null) input.map { if (it.endsWith(" -> b")) "$overrideB -> b" else it } else input
while (true) {
val valueMap = workList.mapNotNull {line ->
val (what, where) = line.split(" -> ")
what.toUShortOrNull()?.let { where to it }
}.toMap()
if (valueMap.containsKey("a")) break
workList = workList.map {
var realValues = it
for (value in valueMap) {
if (realValues.startsWith("${value.key} ") || realValues.contains(" ${value.key} ") || realValues.endsWith(" ${value.key}"))
realValues = realValues.replace(value.key, value.value.toString())
}
realValues
}
workList = workList.map {line ->
line.split(" -> ").let { (what, where) ->
when {
line.startsWith("NOT") -> {
what.removePrefix("NOT ").toUShortOrNull()?.inv()?.let { "$it -> $where" }?: line
}
line.contains("OR") -> what.split(" OR ").map { it.toUShortOrNull() }.let { (one, two) ->
if (one != null && two != null) "${one or two} -> $where" else line
}
line.contains("AND") -> what.split(" AND ").map { it.toUShortOrNull() }.let { (one, two) ->
if (one != null && two != null) "${one and two} -> $where" else line
}
line.contains("LSHIFT") -> what.split(" LSHIFT ").map { it.toUShortOrNull() }.let { (one, two) ->
if (one != null && two != null) "${one shl two} -> $where" else line
}
line.contains("RSHIFT") -> what.split(" RSHIFT ").map { it.toUShortOrNull() }.let { (one, two) ->
if (one != null && two != null) "${one shr two} -> $where" else line
}
else -> line
}
}
}
workList = workList.mapNotNull { line ->
if (line.split(" -> ").all { it.toUShortOrNull() != null }) null else line
}
}
return workList.single { it.endsWith(" a") }.split(" ")[0].toInt()
}
}
private infix fun UShort.shl(steps: UShort) = this.toLong().shl(steps.toInt()).toUShort()
private infix fun UShort.shr(steps: UShort) = this.toLong().shr(steps.toInt()).toUShort()
| 0 | Kotlin | 0 | 0 | ac280f156c284c23565fba5810483dd1cd8a931f | 2,938 | aoc | Apache License 2.0 |
src/com/mrxyx/algorithm/TreeNodeAlg.kt | Mrxyx | 366,778,189 | false | null | package com.mrxyx.algorithm
import com.mrxyx.algorithm.model.TreeNode
import java.util.*
/**
* 二叉树
*/
class TreeNodeAlg {
/**
* 反转二叉树
* https://leetcode-cn.com/problems/invert-binary-tree/
*/
fun invertTree(root: TreeNode?): TreeNode? {
//base case
if (root == null) return null
/**前序遍历**/
//当前节点 翻转左右子节点
val tmp = root.left
root.left = root.right
root.right = tmp
//左右节点依次翻转子节点
invertTree(root.left)
invertTree(root.right)
return root
}
/**
* 填充二叉树节点的右侧指针(完美二叉树)
* https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/
*/
fun connect(root: TreeNode?): TreeNode? {
//base case
if (root == null) return null
connectTwoNode(root.left, root.right)
return root
}
private fun connectTwoNode(left: TreeNode?, right: TreeNode?) {
if (left == null || right == null) return
/**前序遍历**/
//连结左右节点
left.next = right
//连接相同父节点的左右节点
connectTwoNode(left.left, left.right)
connectTwoNode(right.left, right.right)
//连接不同父节点的两子节点 左节点的右节点 与 右节点的左节点
connectTwoNode(left.right, right.left)
}
/**
* 将二叉树展开为链表
* https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/
* step1: 左右节点拉直
* step2: 左节点作为根节点的右节点 原来的右节点拼接在左节点的右节点
*/
fun flatten(root: TreeNode?) {
if (root == null) return
//拉直左右节点
flatten(root.left)
flatten(root.right)
val left = root.left
val right = root.right
//将左子树作为右子树
root.left = null
root.right = left
var p: TreeNode = root
while (p.right != null)
p = p.right
p.right = right
}
/**
* 最大二叉树
* https://leetcode-cn.com/problems/maximum-binary-tree/
*/
fun constructMaxBinaryTree(nums: IntArray): TreeNode? {
return build(nums, 0, nums.size - 1)
}
private fun build(nums: IntArray, lo: Int, hi: Int): TreeNode? {
if (nums.isEmpty()) return null
var index = 0
var maxVal = Int.MIN_VALUE
//得到最大值index
for (i in lo..hi) {
if (nums[i] > maxVal) {
maxVal = nums[i]
index = i
}
}
val root = TreeNode(maxVal)
root.left = build(nums, lo, index - 1)
root.right = build(nums, index + 1, hi)
return root
}
/**
* 通过前序遍历和中序遍历构造二叉树
* https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
*/
fun buildTreeByPreIn(preorder: IntArray, inorder: IntArray): TreeNode? {
return buildByPI(preorder, 0, preorder.size - 1, inorder, 0, inorder.size - 1)
}
private fun buildByPI(preorder: IntArray, preStart: Int, preEnd: Int, inorder: IntArray, inStart: Int, inEnd: Int): TreeNode? {
if (preStart > preEnd) return null
val rootVal = preorder[preStart]
val root = TreeNode(rootVal)
var mid = 0
for (i in inStart..inEnd) {
if (inorder[i] == rootVal) {
mid = i
break
}
}
val leftSize = mid - inStart
root.left = buildByPI(preorder, preStart + 1, preStart + leftSize, inorder, inStart, mid - 1)
root.right = buildByPI(preorder, preStart + leftSize + 1, preEnd, inorder, mid + 1, inEnd)
return root
}
/**
* 通过后序和中序遍历结果构造二叉树
* https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
*/
fun buildTreeByInPost(inorder: IntArray, postorder: IntArray): TreeNode? {
return buildByIP(inorder, 0, inorder.size - 1, postorder, 0, postorder.size - 1)
}
private fun buildByIP(inorder: IntArray, inStart: Int, inEnd: Int, postorder: IntArray, postStart: Int, postEnd: Int): TreeNode? {
if (inStart > inEnd) return null
val rootVal = postorder[postEnd]
var mid = 0
for (i in inStart..inEnd) {
if (inorder[i] == rootVal) {
mid = i
break
}
}
val root = TreeNode(rootVal)
val leftSize = mid - inStart
root.left = buildByIP(inorder, inStart, mid - 1, postorder, postStart, postStart + leftSize - 1)
root.right = buildByIP(inorder, mid + 1, inEnd, postorder, postStart + leftSize, postEnd - 1)
return root
}
/**
* 寻找重复子树
* https://leetcode-cn.com/problems/find-duplicate-subtrees/
* step1 以我为根子树什么样
* step2 以其他节点为根子树什么样
*/
//记录子树 及其出现的次数
private val memo = HashMap<String, Int>()
//记录重复子树根节点
private val res = LinkedList<TreeNode>()
fun findDuplicateSubtrees(root: TreeNode?): List<TreeNode> {
traverse(root)
return res
}
private fun traverse(root: TreeNode?): String {
if (root == null) return "#"
val left = traverse(root.left)
val right = traverse(root.right)
//后序遍历
val subTree = left + "," + right + "," + root.`val`
val freq = memo.getOrDefault(subTree, 0)
if (freq == 1) res.add(root)
memo[subTree] = freq + 1
return subTree
}
/**
* 二叉树的序列化 前序遍历
* https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/
*/
fun serializeV1(root: TreeNode?): String {
val sb = StringBuilder()
serializeHelperV1(root, sb)
return sb.toString()
}
private var sep = ","
private var n = "null"
private fun serializeHelperV1(root: TreeNode?, sb: StringBuilder) {
if (root == null) {
sb.append(n).append(sep)
return
}
/****** 前序遍历位置 ******/
sb.append(root.`val`).append(sep)
/***********************/
serializeHelperV1(root.left, sb)
serializeHelperV1(root.right, sb)
}
/**
* 二叉树的反序列化 前序遍历
* 将字符串反序列化为二叉树结构
*/
fun deserializeV1(data: String): TreeNode? {
// 将字符串转化成列表
val nodes = LinkedList<String>()
for (s in data.split(sep).toTypedArray()) {
nodes.addLast(s)
}
return deserializeV1(nodes)
}
private fun deserializeV1(nodes: LinkedList<String>): TreeNode? {
if (nodes.isEmpty()) return null
/****** 前序遍历位置 */
// 列表最左侧就是根节点
val first = nodes.removeFirst()
if (first == n) return null
val root = TreeNode(first.toInt())
root.left = deserializeV1(nodes)
root.right = deserializeV1(nodes)
return root
}
/**
* 二叉树的序列化 后序遍历
* https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/
*/
private var sb = StringBuilder()
fun serializeV2(root: TreeNode?): String {
serializeHelperV2(root)
return sb.toString()
}
private fun serializeHelperV2(root: TreeNode?) {
if (root == null) {
sb.append(n).append(sep)
return
}
serializeHelperV2(root.left)
serializeHelperV2(root.right)
/****** 后序遍历位置 ******/
sb.append(root.`val`).append(sep)
/***********************/
}
/**
* 二叉树的反序列化 后序遍历
* 将字符串反序列化为二叉树结构
*/
fun deserializeV2(data: String): TreeNode? {
val nodes = LinkedList<String>()
for (s in data.split(sep)) {
if (s.isEmpty()) continue
nodes.addLast(s)
}
return deserializeV2(nodes)
}
private fun deserializeV2(nodes: LinkedList<String>): TreeNode? {
if (nodes.isEmpty()) return null
// 从后往前取出元素
val last = nodes.removeLast()
if (n == last) {
return null
}
val root = TreeNode(last.toInt())
// 限构造右子树,后构造左子树
root.right = deserializeV2(nodes)
root.left = deserializeV2(nodes)
return root
}
/**
* 二叉树的序列化 层级遍历
* https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/
*/
fun serializeV3(root: TreeNode?): String {
if (root == null) return ""
val sb = StringBuilder()
val q = LinkedList<TreeNode>()
q.offer(root)
while (!q.isEmpty()) {
val cur = q.poll()
if (cur == null) {
sb.append(n).append(sep)
continue
}
sb.append(cur.`val`).append(sep)
q.offer(cur.left)
q.offer(cur.right)
}
return sb.toString()
}
/**
* 二叉树的反序列化 层级遍历
* 将字符串反序列化为二叉树结构
*/
fun deserializeV3(data: String): TreeNode? {
if (data.isEmpty()) return null
val nodes = data.split(sep)
val root = TreeNode(nodes[0].toInt())
val q = LinkedList<TreeNode>()
q.offer(root)
var i = 1
while (i < nodes.size) {
// 队列中存的都是父节点
val parent = q.poll()
// 父节点对应的左侧子节点的值
val left = nodes[i++]
if (left.isEmpty()) continue
if (left != n) {
parent.left = TreeNode(left.toInt())
q.offer(parent.left)
} else {
parent.left = null
}
// 父节点对应的右侧子节点的值
val right = nodes[i++]
if (right.isEmpty()) continue
if (right != n) {
parent.right = TreeNode(right.toInt())
q.offer(parent.right)
} else {
parent.right = null
}
}
return root
}
/**
* 二叉树的最近公共祖先
* https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/
*/
fun lowestCommonAncestor(root: TreeNode?, p: TreeNode, q: TreeNode): TreeNode? {
// base case
if (root == null) return null
if (root === p || root === q) return root
val left = lowestCommonAncestor(root.left, p, q)
val right = lowestCommonAncestor(root.right, p, q)
// 情况 1
if (left != null && right != null) {
return root
}
// 情况 2
return if (left == null && right == null) {
null
} else left ?: right
// 情况 3
}
} | 0 | Kotlin | 0 | 0 | b81b357440e3458bd065017d17d6f69320b025bf | 11,249 | algorithm-test | The Unlicense |
src/main/kotlin/aoc2021/Day09.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2021
import aoc2022.product
import utils.ArrayAsSurface
import utils.Coordinates
import utils.InputUtils
class Surface(val input: List<String>): ArrayAsSurface(input) {
fun basinAt(start: Coordinates): Sequence<Coordinates> {
val queue = ArrayDeque<Coordinates>()
queue.add(start)
val seen = mutableSetOf<Coordinates>()
while (!queue.isEmpty()) {
val pos = queue.removeFirst()
queue.addAll(pos.adjacent().filter { c -> c !in seen && inBounds(c) && at(c) != '9' })
seen.add(pos)
}
return seen.asSequence()
}
}
fun main() {
val testInput = """2199943210
3987894921
9856789892
8767896789
9899965678""".split("\n")
fun Surface.lowPoints() = allPoints().filter { p ->
val c = at(p)
p.adjacent().filter(this::inBounds).all { at(it) > c }
}
fun part1(input: List<String>): Int {
val surface = Surface(input)
return surface.lowPoints().sumOf { surface.at(it).digitToInt() + 1 }
}
fun part2(input: List<String>): Int {
val surface = Surface(input)
return surface.lowPoints().map {
surface.basinAt(it).count()
}.sortedDescending().take(3).product()
}
// test if implementation meets criteria from the description, like:
val testValue = part1(testInput)
println(testValue)
check(testValue == 15)
val puzzleInput = InputUtils.downloadAndGetLines(2021, 9)
val input = puzzleInput.toList()
println(part1(input))
println("=== Part 2 ===")
println(part2(testInput))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5abc9e479bed21ae58c093c8efbe4d343eee7714 | 1,630 | aoc-2022-kotlin | Apache License 2.0 |
src/main/aoc2018/Day7.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2018
import java.util.*
class Day7(input: List<String>) {
// Letter is key, list of requirements is value
private val steps = parseInput(input)
private fun parseInput(input: List<String>): Map<String, MutableList<String>> {
val ret = mutableMapOf<String, MutableList<String>>()
// To parse: Step C must be finished before step A can begin.
input.forEach { instruction ->
val req = instruction.substringAfter("Step ").substringBefore(" ")
val step = instruction.substringBefore(" can begin.").substringAfterLast(" ")
ret.putIfAbsent(req, mutableListOf())
ret.putIfAbsent(step, mutableListOf())
ret[step]!!.add(req)
}
return ret
}
private fun getOrder(steps: Map<String, MutableList<String>>): String {
val remaining = steps.toMutableMap()
val order = Stack<String>()
while (remaining.isNotEmpty()) {
val available = remaining.filterValues { it.isEmpty() }.keys.toList().sorted()
val next = available.first()
order.push(next)
remaining.remove(next)
remaining.values.forEach { it.remove(next) }
}
return order.joinToString("")
}
private data class Worker(val id: Int, var workingOn: String?, var done: Int?, val delay: Int) {
val durations = ('A'..'Z').associate { Pair("$it", delay + 1 + (it - 'A')) }
fun isWorking() = workingOn != null
fun isIdle() = workingOn == null
fun startWork(which: String, currentTime: Int): Int {
workingOn = which
done = currentTime + durations.getValue(which)
return done!!
}
fun stopWorking() {
workingOn = null
done = null
}
}
private fun getAssemblyDuration(steps: Map<String, MutableList<String>>, numWorkers: Int, delay: Int): Int {
val remaining = steps.toMutableMap()
val order = Stack<String>()
val workers = Array(numWorkers) { Worker(it, null, null, delay) }
var currentTime = 0
val workLog = mutableListOf<Pair<String, Int>>() // part, time when done
while (remaining.isNotEmpty() || workers.any { it.isWorking() }) {
val available = remaining.filterValues { it.isEmpty() }.keys.toList().sorted()
if (available.isNotEmpty() && workers.any { it.isIdle() }) {
// start working
val next = available.first()
val done = workers.first { it.isIdle() }.startWork(next, currentTime)
workLog.add(Pair(next, done))
remaining.remove(next)
}
val finishedWork = workLog.filter { it.second == currentTime }
finishedWork.forEach { finished ->
// Some work finishes this second
workers.find { it.workingOn == finished.first }!!.stopWorking()
order.push(finished.first)
remaining.values.forEach { it.remove(finished.first) }
workLog.remove(finished)
}
if ((available.isEmpty() || workers.all { it.isWorking() }) && finishedWork.isEmpty()) {
// No work to start or finish this second, advance time
currentTime = workLog.minByOrNull { it.second }!!.second
}
}
return currentTime
}
fun solvePart1(): String {
return getOrder(steps)
}
fun solvePart2(numWorkers: Int, delay: Int): Int {
return getAssemblyDuration(steps, numWorkers, delay)
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 3,623 | aoc | MIT License |
aoc-2023/src/main/kotlin/aoc/aoc22.kts | triathematician | 576,590,518 | false | {"Kotlin": 615974} | import aoc.AocParser.Companion.parselines
import aoc.*
import aoc.util.Loc3
import aoc.util.getDayInput
val testInput = """
1,0,1~1,2,1
0,0,2~2,0,2
0,2,3~2,2,3
0,0,4~0,2,4
2,0,5~2,2,5
0,1,6~2,1,6
1,1,8~1,1,9
""".parselines
class Brick(val p1: Loc3, val p2: Loc3) {
val locs = when {
p1.x == p2.x && p1.y == p2.y -> (p1.z..p2.z).map { Loc3(p1.x, p1.y, it) }
p1.x == p2.x && p1.z == p2.z -> (p1.y..p2.y).map { Loc3(p1.x, it, p1.z) }
p1.y == p2.y && p1.z == p2.z -> (p1.x..p2.x).map { Loc3(it, p1.y, p1.z) }
else -> error("Invalid brick")
}.toSet()
fun fall() = Brick(p1.copy(z = p1.z-1), p2.copy(z = p2.z-1))
}
/** Return true if the bottom if this brick is touching the top of the other brick. */
fun Brick.onTopOf(other: Brick) = locs.any { Loc3(it.x, it.y, it.z-1) in other.locs }
class BrickConfig(val bricks: List<Brick>) {
/** Which bricks are on the ground. */
val grounded = bricks.filter { it.p1.z == 1 || it.p2.z == 1 }.toSet()
/** Generate graph of which bricks are touching the top of other bricks. A given key is "on top of" each of its values. */
val graphOnTop: Map<Brick, Set<Brick>>
/** Generate graph of which bricks are supporting other bricks. A given key is "supporting" each of its values. */
val graphSupporting: Map<Brick, Set<Brick>>
init {
val graph = mutableSetOf<Pair<Brick, Brick>>()
bricks.indices.forEach { a ->
bricks.indices.forEach { b ->
if (a != b && bricks[a].onTopOf(bricks[b])) {
graph.add(bricks[a] to bricks[b])
}
}
}
graphOnTop = graph.groupBy { it.first }.mapValues { it.value.map { it.second }.toSet() }
graphSupporting = graph.groupBy { it.second }.mapValues { it.value.map { it.first }.toSet() }
}
/** Which bricks are stacked on other bricks connected to the ground. */
val stacked: Set<Brick> = run {
var layer = grounded.toSet()
val remainingBricks = bricks.toMutableSet()
val result = mutableSetOf<Brick>()
while (layer.isNotEmpty()) {
result.addAll(layer)
remainingBricks.removeAll(layer)
layer = remainingBricks.filter { brick -> layer.any { brick.onTopOf(it) } }.toSet()
}
result
}
/** Which bricks are free and could fall. */
val free = bricks - stacked
/** Return a new [BrickConfig] with all free bricks fallen. */
fun fall() = BrickConfig(bricks.map { if (it in free) it.fall() else it })
fun disintegrable() = bricks.count {
val supp = graphSupporting[it] ?: emptyList()
supp.all { graphOnTop[it]!!.size > 1 }
}
fun howManyWouldFall() = bricks.sumOf { solelySupportedBy(it).size - 1 }
/** How many bricks are solely supported by [brick], all the way up the chain, including the brick itself. */
fun solelySupportedBy(brick: Brick): Set<Brick> {
val supportingGroup = mutableSetOf(brick)
var toCheck = mutableSetOf(brick)
while (toCheck.isNotEmpty()) {
val supps = toCheck.flatMap { graphSupporting[it] ?: emptyList() }.toSet()
val wouldFall = supps.filter { it !in supportingGroup && graphOnTop[it]!!.all { it in supportingGroup } }
supportingGroup.addAll(wouldFall)
toCheck = wouldFall.toMutableSet()
}
return supportingGroup
}
}
fun String.parse() = split("~").map { it.split(",").map { it.toInt() } }.let {
Brick(Loc3(it[0][0], it[0][1], it[0][2]), Loc3(it[1][0], it[1][1], it[1][2]))
}
// part 1
fun List<String>.part1(): Int {
var bricks = BrickConfig(map { it.parse() })
while (bricks.free.isNotEmpty()) {
bricks = bricks.fall()
}
return bricks.disintegrable()
}
// part 2
fun List<String>.part2(): Int {
var bricks = BrickConfig(map { it.parse() })
while (bricks.free.isNotEmpty()) {
bricks = bricks.fall()
}
return bricks.howManyWouldFall()
}
// calculate answers
val day = 22
val input = getDayInput(day, 2023)
val testResult = testInput.part1().also { it.print }
val testResult2 = testInput.part2().also { it.print }
val answer1 = input.part1().also { it.print }
val answer2 = input.part2().also { it.print }
// print results
AocRunner(day,
test = { "$testResult, $testResult2" },
part1 = { answer1 },
part2 = { answer2 }
).run()
| 0 | Kotlin | 0 | 0 | 7b1b1542c4bdcd4329289c06763ce50db7a75a2d | 4,413 | advent-of-code | Apache License 2.0 |
src/Day03.kt | matusekma | 572,617,724 | false | {"Kotlin": 119912, "JavaScript": 2024} | class Day03 {
fun part1(input: List<String>): Int {
var sum = 0
for(rucksack in input) {
var firstComp = rucksack.substring(0, rucksack.length / 2).toCharArray().toMutableSet()
var secondComp = rucksack.substring(rucksack.length / 2).toCharArray().toMutableSet()
firstComp.retainAll(secondComp.toSet())
sum += firstComp.sumOf { itemToValue(it) }
}
return sum
}
private fun itemToValue(it: Char) = if (it.isUpperCase()) it.code - 38 else it.code - 96
fun part2(input: List<String>): Int {
var sum = 0
for(i in 0 .. input.size - 3 step 3){
var elfes = input.subList(i, i + 3)
var common = elfes[0].toList().intersect(elfes[1].toList().toSet()).intersect(elfes[2].toList().toSet())
sum += common.sumOf { itemToValue(it) }
}
return sum
}
}
fun main() {
val day03 = Day03()
val input = readInput("input03_1")
println(day03.part1(input))
println(day03.part2(input))
} | 0 | Kotlin | 0 | 0 | 744392a4d262112fe2d7819ffb6d5bde70b6d16a | 1,048 | advent-of-code | Apache License 2.0 |
src/Day03.kt | mborromeo | 571,999,097 | false | {"Kotlin": 10600} | fun main() {
fun priority(el: Char): Int {
return when (el) {
in 'a'..'z' -> el - 'a' + 1
in 'A'..'Z' -> el - 'A' + 27
else -> 0
}
}
fun part1(input: List<String>): Int {
return input.sumOf { rucksack ->
priority((rucksack.take(rucksack.length / 2).toSet() intersect rucksack.drop(rucksack.length / 2).toSet()).single())
}
}
fun part2(input: List<String>): Int {
val groups = input.chunked(3)
return groups.sumOf { rucksacks ->
priority(rucksacks.map { it.toSet() }.reduce { commonItems, content -> commonItems intersect content }.single())
}
}
val inputData = readInput("Day03_input")
println("Part 1: " + part1(inputData))
println("Part 2: " + part2(inputData))
} | 0 | Kotlin | 0 | 0 | d01860ecaff005aaf8e1e4ba3777a325a84c557c | 820 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/com/adventofcode/year2021/day3/part2/App.kt | demidko | 433,889,383 | false | {"Kotlin": 7692, "Dockerfile": 264} | package com.adventofcode.year2021.day3.part2
import com.adventofcode.year2021.day
import java.math.BigInteger
fun List<String>.mostCommonBit(column: Int): Char {
return when (count { it[column] == '1' } >= count { it[column] == '0' }) {
true -> '1'
else -> '0'
}
}
fun List<String>.leastCommonBit(column: Int): Char {
return when (count { it[column] == '0' } <= count { it[column] == '1' }) {
true -> '0'
else -> '1'
}
}
tailrec fun List<String>.filterBy(detectBitCriteria: List<String>.(Int) -> Char, column: Int = 0): BigInteger {
val bitCriteria = detectBitCriteria(column)
val foundedNumbers = filter { it[column] == bitCriteria }
return when (foundedNumbers.size > 1) {
true -> foundedNumbers.filterBy(detectBitCriteria, column + 1)
else -> BigInteger(foundedNumbers.first(), 2)
}
}
fun main() {
val allBinaryNumbers = day(3)
val oxygenGeneratorRating = allBinaryNumbers.filterBy(List<String>::mostCommonBit)
val co2ScrubberRating = allBinaryNumbers.filterBy(List<String>::leastCommonBit)
println(oxygenGeneratorRating * co2ScrubberRating)
}
| 0 | Kotlin | 0 | 0 | 2f42bede3ed0c4b17cb2575f6b61a1917a465bda | 1,101 | adventofcode | MIT License |
src/commonMain/kotlin/advent2020/day23/Day23Puzzle.kt | jakubgwozdz | 312,526,719 | false | null | package advent2020.day23
fun part1(input: String): String {
val circle = Circle(input.trim())
circle.makeNMoves(times = 100)
return part1formatAnswer(circle)
}
fun part1formatAnswer(circle: Circle) = buildString {
var n = circle.cups[1].next
while (n.id != 1) {
append(n.id)
n = n.next
}
}
fun part2(input: String): String {
val circle = Circle(input.trim(), noOfCups = 1000000)
circle.makeNMoves(times = 10000000)
return part2formatAnswer(circle)
}
fun part2formatAnswer(circle: Circle): String {
val one = circle.cups[1]
val first = one.next.id
val second = one.next.next.id
val result = (first.toLong() * second.toLong()).toString()
println(" $first * $second = $result ")
return result
}
class Cup(val id: Int) {
lateinit var next: Cup
}
class Circle(input: String, val noOfCups: Int = input.length) {
val cups = Array(noOfCups + 1) { Cup(it) }.toList() // ignore idx 0, keep for readability
var current: Cup
init {
repeat(input.length - 1) {
val c = "${input[it]}".toInt()
val n = "${input[it + 1]}".toInt()
cups[c].next = cups[n]
}
val lastFromInput = "${input.last()}".toInt()
val firstFromInput = "${input.first()}".toInt()
cups[lastFromInput].next = cups[firstFromInput]
if (noOfCups > input.length) {
cups[lastFromInput].next = cups[input.length + 1]
(input.length + 1 until noOfCups).forEach {
cups[it].next = cups[it + 1]
}
cups[noOfCups].next = cups[firstFromInput]
}
current = cups[firstFromInput]
}
fun makeMove() {
val c0 = current
val c1 = c0.next
val c2 = c1.next
val c3 = c2.next
val c4 = c3.next
var destId = c0.id - 1
if (destId == 0) destId = noOfCups
while (destId == c1.id || destId == c2.id || destId == c3.id) {
destId--
if (destId == 0) destId = noOfCups
}
val d0 = cups[destId]
val d1 = d0.next
d0.next = c1
c3.next = d1
c0.next = c4
current = c4
}
fun makeNMoves(times: Int) = repeat(times) { makeMove() }
}
// UNUSED
//
//fun Circle.format() = buildString(10000) {
// var c = current
// append("[")
// repeat(noOfCups.coerceAtMost(52)) {
// append(c.id)
// if (it < noOfCups - 1) append(" ")
// c = c.next
// }
// if (noOfCups > 52) append("...")
// append("]")
//}
//
| 0 | Kotlin | 0 | 2 | e233824109515fc4a667ad03e32de630d936838e | 2,574 | advent-of-code-2020 | MIT License |
year2022/src/main/kotlin/net/olegg/aoc/year2022/day3/Day3.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2022.day3
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.year2022.DayOf2022
/**
* See [Year 2022, Day 3](https://adventofcode.com/2022/day/3)
*/
object Day3 : DayOf2022(3) {
private val ALPHABET = buildSet {
addAll('a'..'z')
addAll('A'..'Z')
}
override fun first(): Any? {
return lines
.map { line ->
line.take(line.length / 2) to line.drop(line.length / 2)
}
.map { (first, second) ->
first.toSet().intersect(second.toSet())
}
.sumOf {
when (val char = it.first()) {
in 'a'..'z' -> char - 'a' + 1
in 'A'..'Z' -> char - 'A' + 27
else -> 0
}
}
}
override fun second(): Any? {
return lines
.chunked(3)
.map { threeLines ->
threeLines.fold(ALPHABET) { acc, value ->
acc.intersect(value.toSet())
}
}
.sumOf {
when (val char = it.first()) {
in 'a'..'z' -> char - 'a' + 1
in 'A'..'Z' -> char - 'A' + 27
else -> 0
}
}
}
}
fun main() = SomeDay.mainify(Day3)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,122 | adventofcode | MIT License |
src/aoc2022/Day05.kt | NoMoor | 571,730,615 | false | {"Kotlin": 101800} | package aoc2022
import utils.*
internal class Day05(val lines: List<String>) {
init { lines.forEach { println(it) } }
fun part1(): String {
val (startingStacks, moves) = lines.splitBy { it == "" }
val stacks = startingStacks.reversed()[0].last().digitToInt() * mutableListOf<Char>()
startingStacks
.dropLast(1)
.forEach { it.chunked(4).forEachIndexed { i, str ->
if (str[1].isLetter()) stacks[i].add(0, str[1])
}
}
moves.forEach { m ->
val (num, s, d) = m.split(" ").filter { it[0].isDigit() }.map { it.toInt() }
stacks[d - 1].addAll(stacks[s - 1].removeLast(num).reversed())
}
return stacks.joinToString(separator = "") { if (it.isNotEmpty()) it.last().toString() else "" }
}
fun part2(): String {
val (startingStacks, moves) = lines.splitBy { it == "" }
val stacks = startingStacks.reversed()[0].last().digitToInt() * mutableListOf<Char>()
startingStacks.reversed().drop(1)
.forEach {
it.chunked(4).forEachIndexed { i, str ->
if (str[1].isLetter()) stacks[i].add(str[1])
}
}
moves.forEach { m ->
val (num, s, d) = m.allInts()
stacks[d - 1].addAll(stacks[s - 1].removeLast(num))
}
return stacks.joinToString(separator = "") { if (it.isNotEmpty()) it.last().toString() else "" }
}
companion object {
fun runDay() {
val day = "05".toInt()
val todayTest = Day05(readInput(day, 2022, true))
execute(todayTest::part1, "Day[Test] $day: pt 1", "CMZ")
val today = Day05(readInput(day, 2022))
execute(today::part1, "Day $day: pt 1", "FWNSHLDNZ")
execute(todayTest::part2, "Day[Test] $day: pt 2", "MCD")
execute(today::part2, "Day $day: pt 2", "RNRGDNFQG") // Wrong guess: FWNSHLDNZ
}
}
}
fun main() {
Day05.runDay()
} | 0 | Kotlin | 1 | 2 | d561db73c98d2d82e7e4bc6ef35b599f98b3e333 | 1,836 | aoc2022 | Apache License 2.0 |
src/me/anno/maths/EquationSolver.kt | AntonioNoack | 456,513,348 | false | {"Kotlin": 9845766, "C": 236481, "GLSL": 9454, "Java": 6754, "Lua": 4404} | package me.anno.maths
import me.anno.maths.Maths.TAUf
import me.anno.maths.Maths.pow
import kotlin.math.abs
import kotlin.math.acos
import kotlin.math.cos
import kotlin.math.sqrt
object EquationSolver {
private const val TOO_LARGE_RATIO = 1e9 // idk...
fun solveQuadratic(dst: FloatArray, a: Float, b: Float, c: Float): Int {
// a = 0 -> linear equation
if (a == 0f || abs(b) + abs(c) > TOO_LARGE_RATIO * abs(a)) {
// a, b = 0 -> no solution
if (b == 0f || abs(c) > TOO_LARGE_RATIO * abs(b)) {
return if (c == 0f) -1 else 0 // 0 = 0
}
dst[0] = -c / b
return 1
}
var dscr = b * b - 4 * a * c
return when {
dscr > 0f -> {
dscr = sqrt(dscr)
dst[0] = (-b + dscr) / (2 * a)
dst[1] = (-b - dscr) / (2 * a)
2
}
dscr == 0f -> {
dst[0] = -b / (2 * a)
1
}
else -> 0
}
}
fun solveCubicNormed(dst: FloatArray, a0: Float, b: Float, c: Float): Int {
var a = a0
val a2 = a * a
var q = (a2 - 3 * b) / 9
val r = (a * (2 * a2 - 9 * b) + 27 * c) / 54
val r2 = r * r
val q3 = q * q * q
return if (r2 < q3) {
var t = r / sqrt(q3)
if (t < -1) t = -1f
if (t > 1) t = 1f
t = acos(t)
a /= 3f
q = -2 * sqrt(q)
dst[0] = q * cos(t / 3f) - a
dst[1] = q * cos((t + TAUf) / 3f) - a
dst[2] = q * cos((t - TAUf) / 3f) - a
3
} else {
var a3 = -pow(abs(r) + sqrt(r2 - q3), 1f / 3f)
if (r < 0) a3 = -a3
val b3 = if (a3 == 0f) 0f else q / a3
a /= 3f
dst[0] = a3 + b3 - a
dst[1] = -0.5f * (a3 + b3) - a
dst[2] = +0.5f * sqrt(3f) * (a3 - b3)
if (abs(dst[2]) < 1e-14) 2 else 1
}
}
fun solveCubic(dst: FloatArray, a: Float, b: Float, c: Float, d: Float): Int {
if (a != 0f) {
val bn = b / a
val cn = c / a
val dn: Float = d / a
// Check, that <a> isn't "almost zero"
if (abs(bn) < TOO_LARGE_RATIO && abs(cn) < TOO_LARGE_RATIO && abs(dn) < TOO_LARGE_RATIO)
return solveCubicNormed(dst, bn, cn, dn)
}
return solveQuadratic(dst, b, c, d)
}
} | 0 | Kotlin | 3 | 17 | 3d0d08566309a84e1e68585593b76844633132c4 | 2,500 | RemsEngine | Apache License 2.0 |
src/Day01.kt | afranken | 572,923,112 | false | {"Kotlin": 15538} | fun main() {
fun countCalories(input: List<String>): List<Int> {
val caloryList: MutableList<Int> = mutableListOf()
var caloryCounter = 0
for (it in input) {
if (it.isBlank()) {
caloryList.add(caloryCounter)
caloryCounter = 0
} else {
caloryCounter += it.toInt()
}
}
caloryList.add(caloryCounter)
return caloryList
}
fun part1(input: List<String>): Int {
val maxCalories = countCalories(input).max()
println("Max calories found: $maxCalories")
return maxCalories
}
fun part2(input: List<String>): Int {
val maxCalories = countCalories(input).sortedDescending().take(3).sum()
println("Max calories found: $maxCalories")
return maxCalories
}
// 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")
check(part1(input) == 72602)
check(part2(input) == 207410)
}
| 0 | Kotlin | 0 | 0 | f047d34dc2a22286134dc4705b5a7c2558bad9e7 | 1,143 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day05.kt | TinusHeystek | 574,474,118 | false | {"Kotlin": 53071} | class Day05 : Day(5) {
class Instruction(val move: Int, val from: Int, val to: Int)
// --- Part 1 ---
private fun parseCrates(input: String, shouldReverseOrder: Boolean): String {
val crateGroups = mutableMapOf<Int, MutableList<Char>>()
val instructions = mutableListOf<Instruction>()
for (line in input.lines()) {
if (line.contains("[")) {
// build crates
for (index in 1 until line.toCharArray().size step 4) {
val crate = line[index]
if (crate == ' ')
continue
val crateIndex: Int = index.floorDiv(4)
if (crateGroups.containsKey(crateIndex)) {
crateGroups[crateIndex]?.add(crate)
} else {
crateGroups[crateIndex] = mutableListOf(crate)
}
}
} else if (line.startsWith("move")) {
//move 1 from 2 to 1
val move = line.substring(line.indexOf("move") + 5, line.indexOf("from") - 1)
val from = line.substring(line.indexOf("from") + 5, line.indexOf("to") - 1)
val to = line.substring(line.indexOf("to") + 3, line.length)
instructions.add(Instruction(move.toInt(), from.toInt() -1, to.toInt() -1))
}
}
for (instruction in instructions) {
var moveCrates = crateGroups[instruction.from]?.take(instruction.move)
if (moveCrates != null) {
// Part 2
if (shouldReverseOrder)
moveCrates = moveCrates.asReversed()
for (moveCrate in moveCrates) {
crateGroups[instruction.to]?.add(0, moveCrate)
crateGroups[instruction.from]?.remove(moveCrate)
}
}
}
val outputChars = crateGroups.toSortedMap()
.map { it.value.first() }
return String(outputChars.toCharArray())
}
override fun part1ToString(input: String): String {
return parseCrates(input, false)
}
// --- Part 2 ---
override fun part2ToString(input: String): String {
return parseCrates(input, true)
}
}
fun main() {
val day = Day05()
day.printToStringResults("CMZ", "MCD")
}
| 0 | Kotlin | 0 | 0 | 80b9ea6b25869a8267432c3a6f794fcaed2cf28b | 2,380 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/aoc2020/day14/BitMask.kt | arnab | 75,525,311 | false | null | package aoc2020.day14
object BitMask {
private val DEFAULT_MASK = Mask.from("X".repeat(36))
private val memoryLocationPattern = Regex("""mem\[(\d+)]""")
data class Mask(
val bits: List<Int?>
) {
companion object {
fun from(mask: String) = mask.split("")
.filterNot { it.isBlank() }
.map { s ->
if (s == "X") null
else s.toInt()
}.let { bits -> Mask(bits) }
}
}
fun process(
instructions: List<String>,
mask: Mask = DEFAULT_MASK,
memory: MutableMap<Int, Long> = mutableMapOf()
): Map<Int, Long> {
if (instructions.isEmpty()) return memory
val (code, data) = instructions.first().split(" = ")
val remainingInstructions = instructions.drop(1)
return when {
code == "mask" -> process(remainingInstructions, Mask.from(data), memory)
code.startsWith("mem") -> {
val memoryLocation = memoryLocationPattern.matchEntire(code)!!.destructured.component1().toInt()
memory[memoryLocation] = data.toLong().withMask(mask)
process(remainingInstructions, mask, memory)
}
else -> throw IllegalArgumentException("Unknown code: $code!")
}
}
fun part1(instructions: List<String>) = process(instructions).values.sum()
}
private fun Long.withMask(mask: BitMask.Mask): Long {
val bitsStr = this.toString(2).padStart(36, '0')
val bits = BitMask.Mask.from(bitsStr).bits
val maskedBits = mask.bits.zip(bits).map { it.first ?: it.second }
return maskedBits.joinToString("").toLong(2)
}
| 0 | Kotlin | 0 | 0 | 1d9f6bc569f361e37ccb461bd564efa3e1fccdbd | 1,701 | adventofcode | MIT License |
src/day16/Day16.kt | Puju2496 | 576,611,911 | false | {"Kotlin": 46156} | package day16
import println
import readInput
import java.util.*
fun main() {
// test if implementation meets criteria from the description, like:
val input = readInput("src/day16", "Day16")
println("Part1")
part1(input)
println("Part2")
part2(input)
}
private fun part1(inputs: List<String>) {
val valveList: MutableList<Valve> = mutableListOf()
inputs.forEach {
val value = it.split(" ", "=", ";")
val list = if (it.contains("valves")) it.substringAfter("valves ").split(", ").map { Edge(it) }.toMutableList() else it.substringAfter("valve ").split(", ").map { Edge(it) }.toMutableList()
valveList.add(Valve(value[1], value[5].toInt(), list))
}
println("valves - $valveList")
var minute = 1
var index = 0
val openedValves: MutableList<String> = mutableListOf()
while (minute <= 30) {
if (valveList[index].rate != 0 && !openedValves.contains(valveList[index].name)) {
openedValves.add(valveList[index].name)
}
valveList.forEach { valve ->
valve.edges.find { it.name == valveList[index].name}?.opened = true
var allOpened = false
valve.edges.forEach {
allOpened = allOpened && it.opened
}
valve.isAllEdgesOpened = allOpened
}
var isOpened = false
var toOpen = Edge("")
println("valves check - ${valveList[index]}")
run go@ {
valveList[index].edges.forEach { edge ->
println("before - ${edge}, ${valveList.filter { it.name == edge.name}[0]}")
isOpened = valveList.filter { it.name == edge.name}[0].isAllEdgesOpened
if (!isOpened) {
println("inside if")
toOpen = edge
return@go
}
}
}
println("toOpen - $isOpened - $toOpen")
if (!isOpened) {
index = valveList.indexOf(valveList.first { it.name == toOpen.name})
}
minute++
}
println("opened - $openedValves")
}
private fun part2(inputs: List<String>) {
}
data class Valve(val name: String, val rate: Int, val edges: MutableList<Edge>, var isAllEdgesOpened: Boolean = false)
data class Edge(val name: String, var opened: Boolean = false) | 0 | Kotlin | 0 | 0 | e04f89c67f6170441651a1fe2bd1f2448a2cf64e | 2,332 | advent-of-code-2022 | Apache License 2.0 |
src/day14/Day14.kt | seastco | 574,758,881 | false | {"Kotlin": 72220} | package day14
import readLines
import kotlin.math.max
import kotlin.math.min
private class Grid(var grid: Array<Array<String>>, val minX: Int, val maxX: Int, val minY: Int, val maxY: Int) {
companion object {
fun of(input: List<String>, part2: Boolean): Grid {
// Parse 498,4 -> 498,6 -> 496,6 into [ [(498,4), (498,6)], [(498,6), (496,6)] ]
// The windowed approach gives us clear A -> B, B -> C ranges for drawing rock paths
val rockPaths = input.map { line ->
line.split("->").map { pair ->
pair.trim()
val x = pair.substringBefore(",").trim().toInt()
val y = pair.substringAfter(",").trim().toInt()
Pair(x, y)
}
}.map {
it.windowed(2, 1)
}
var minX = Integer.MAX_VALUE
var maxX = Integer.MIN_VALUE
var minY = 0
var maxY = Integer.MIN_VALUE
var grid: Array<Array<String>>?
// Find min/max x/y boundaries so we can appropriately size the grid
rockPaths.forEach { path ->
path.forEach { windowedPair ->
windowedPair.forEach { pair ->
minX = min(minX, pair.first)
maxX = max(maxX, pair.first)
maxY = max(maxY, pair.second)
}
}
}
grid = Array(maxY + 1) { Array(maxX - minX + 1) { "." } }
// Part2 has an "infinite" X-axis (I hardcoded 1000 which is sufficient) and an additional column
if (part2) {
grid = Array(maxY + 2) { Array(maxX - minX + 1000) { "." } } // 1000 is our "infinite" X axis
}
rockPaths.forEach { path ->
path.forEach { windowedPair ->
for (col in rangeBetween(windowedPair.first().first, windowedPair.last().first)) {
for (row in rangeBetween(windowedPair.first().second, windowedPair.last().second)) {
// Size & fill in the grid (size dependent on which part we're solving for)
val i = row - (if (part2) 0 else minY)
val j = col - (if (part2) 0 else minX)
grid[i][j] = "#"
}
}
}
}
return Grid(grid, minX, maxX, minY, maxY)
}
private fun rangeBetween(a: Int, b: Int) = min(a, b)..max(a, b)
}
}
// Part1 requires us to terminate once the sand falls out of the grid boundaries, hence terminateOutOfBonds=true
// Part2 requires us to go until sand reaches the starting point, so we do not want to terminate when exceeding a boundary
private fun dropSand(grid: Array<Array<String>>, x: Int, y: Int, terminateOutOfBounds: Boolean): Pair<Boolean, Int> {
if (y >= grid.size || y < 0 || x >= grid[0].size || x < 0) {
// Off grid, do not continue
return Pair(!terminateOutOfBounds, 0)
}
if (grid[y][x] != ".") {
// We hit a rock or sand, do not continue
return Pair(true, 0)
}
// Drop sand down, left, and then right. Order matters!
// For P1, terminate the recursive stack if we exceed a boundary.
val down = dropSand(grid, x, y + 1, terminateOutOfBounds)
if (!down.first) {
return Pair(false, down.second)
}
val left = dropSand(grid, x - 1, y + 1, terminateOutOfBounds)
if (!left.first) {
return Pair(false, down.second + left.second)
}
val right = dropSand(grid, x + 1, y + 1, terminateOutOfBounds)
if (!right.first) {
return Pair(false, down.second + left.second + right.second)
}
grid[y][x] = "o"
return Pair(true, down.second + left.second + right.second + 1)
}
private fun part1(input: List<String>): Int {
val grid = Grid.of(input, false)
val result = dropSand(grid.grid, 500 - grid.minX, 1, true)
return result.second
}
private fun part2(input: List<String>): Int {
val grid = Grid.of(input, true)
val result = dropSand(grid.grid, 500, 0, false)
return result.second
}
fun main() {
println(part1(readLines("day14/test")))
println(part1(readLines("day14/input")))
println(part2(readLines("day14/test")))
println(part2(readLines("day14/input")))
} | 0 | Kotlin | 0 | 0 | 2d8f796089cd53afc6b575d4b4279e70d99875f5 | 4,440 | aoc2022 | Apache License 2.0 |
src/Day24.kt | joy32812 | 573,132,774 | false | {"Kotlin": 62766} | import java.util.LinkedList
private data class Position(val x: Int, val y: Int, val time: Int)
private fun Position.toId() = "$x,$y,$time"
private fun String.toPosition() = split(",").map { it.toInt() }.let { Position(it[0], it[1], it[2]) }
fun main() {
// up, down, left, right
val dx = listOf(-1, 1, 0, 0)
val dy = listOf(0, 0, -1, 1)
fun Char.getDeltaId() = when (this) {
'^' -> 0
'v' -> 1
'<' -> 2
'>' -> 3
else -> throw IllegalArgumentException("Invalid direction: $this")
}
fun initBlockSet(grid: List<String>): Set<String> {
val m = grid.size
val n = grid[0].length
val blockSet = mutableSetOf<String>()
fun generateBlockSet(x: Int, y: Int, dId: Int) {
var nx = x
var ny = y
for (i in 0 until 1000) {
blockSet += "$nx,$ny,$i"
nx = (nx + dx[dId] + m) % m
ny = (ny + dy[dId] + n) % n
while (grid[nx][ny] == '#') {
nx = (nx + dx[dId] + m) % m
ny = (ny + dy[dId] + n) % n
}
}
}
for (i in 0 until m) {
for (j in 0 until n) {
if (grid[i][j] in "^v<>") {
generateBlockSet(i, j, grid[i][j].getDeltaId())
}
}
}
return blockSet
}
fun travel(from: Position, to: Position, blockSet: Set<String>, grid: List<String>): Int {
var Q = mutableSetOf(from.toId())
while (Q.isNotEmpty()) {
val newQ = mutableSetOf<String>()
for (p in Q) {
val (x, y, time) = p.toPosition()
if ("$x,$y,${time + 1}" !in blockSet) {
newQ += "$x,$y,${time + 1}"
}
for (k in dx.indices) {
val nx = x + dx[k]
val ny = y + dy[k]
val nTime = time + 1
if (nx !in grid.indices || ny !in grid[0].indices) continue
if (grid[nx][ny] == '#') continue
if (nx == to.x && ny == to.y) {
return nTime
}
val nP = Position(nx, ny, nTime)
if (nP.toId() in blockSet) continue
newQ += nP.toId()
}
}
Q = newQ
}
return -1
}
fun part1(grid: List<String>): Int {
val blockSet = initBlockSet(grid)
return travel(Position(0, 1, 0), Position(grid.size - 1, grid[0].length - 2, 0), blockSet, grid)
}
fun part2(grid: List<String>): Int {
val blockSet = initBlockSet(grid)
val t1 = travel(Position(0, 1, 0), Position(grid.size - 1, grid[0].length - 2, 0), blockSet, grid)
val t2 = travel(Position(grid.size - 1, grid[0].length - 2, t1), Position(0, 1, 0), blockSet, grid)
val t3 = travel(Position(0, 1, t2), Position(grid.size - 1, grid[0].length - 2, 0), blockSet, grid)
return t3
}
// println(part1(readInput("data/Day24_test")))
// println(part1(readInput("data/Day24")))
println(part2(readInput("data/Day24_test")))
println(part2(readInput("data/Day24")))
}
| 0 | Kotlin | 0 | 0 | 5e87958ebb415083801b4d03ceb6465f7ae56002 | 3,307 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/_0047_PermutationsII.kt | ryandyoon | 664,493,186 | false | null | // https://leetcode.com/problems/permutations-ii
fun permuteUnique(nums: IntArray): List<List<Int>> {
nums.sort()
return mutableListOf<List<Int>>().also {
buildPermutations(nums, 0, it)
}
}
private fun buildPermutations(nums: IntArray, startIndex: Int, permutations: MutableList<List<Int>>) {
if (startIndex == nums.lastIndex) {
permutations.add(nums.toList())
return
}
val swapped = mutableSetOf<Int>()
var index = startIndex
while (index <= nums.lastIndex) {
swapped.add(nums[index])
nums.swap(startIndex, index)
buildPermutations(nums = nums, startIndex = startIndex + 1, permutations = permutations)
nums.swap(startIndex, index)
index++
while (nums.getOrNull(index) == nums[startIndex] || swapped.contains(nums.getOrNull(index))) index++
}
}
private fun IntArray.swap(i: Int, j: Int) {
if (i == j) return
val temp = this[i]
this[i] = this[j]
this[j] = temp
}
| 0 | Kotlin | 0 | 0 | 7f75078ddeb22983b2521d8ac80f5973f58fd123 | 989 | leetcode-kotlin | MIT License |
kotlin/src/_0005.kt | yunshuipiao | 179,794,004 | false | null | import org.testng.annotations.Test
fun longestPalindrome(s: String): String {
return longCommonSubString(s)
}
fun dp(s: String): String {
if (s.isBlank()) {
return s
}
var result = ""
val map = Array(s.length) { Array(s.length) { 0 } }
for (i in 0 until map.size) {
for (j in 0 until map[0].size) {
if (s[j] == s[i]) {
if (i - j <= 1) {
map[j][i] = 1
} else if (map[j + 1][i - 1] == 1) {
map[j][i] = 1
}
}
if (map[j][i] == 1 && i - j + 1 >= result.length) {
result = s.substring(j, i + 1)
}
}
}
return result
}
fun longCommonSubString(s: String): String {
if (s.isBlank()) {
return s
}
var result = ""
val rs = s.reversed()
val map = Array(s.length) { Array(s.length) { 0 } }
for (i in 0 until s.length) {
for (j in 0 until rs.length) {
if (s[i] == rs[j]) {
if (i - 1 < 0 || j - 1 < 0) {
map[i][j] = 1
} else {
map[i][j] = map[i - 1][j - 1] + 1
}
} else {
map[i][j] = 0
}
if (map[i][j] > result.length) {
val temp = s.substring(i - map[i][j] + 1, i + 1)
if (isPalindrome(temp)) {
result = temp
}
}
}
}
return result
}
fun isPalindrome(s: String): Boolean {
var l = 0
var r = s.length - 1
while (l <= r) {
if (s[l] != s[r]) {
return false
}
l += 1
r -= 1
}
return true
}
fun bestMethod(s: String): String {
if (s.isBlank()) {
return s
}
var result = ""
for (i in 0 until s.length) {
val len1 = getPalindromeLen(s, i, i)
if (len1 >= result.length) {
result = s.substring(i - len1 / 2, i + len1 / 2 + 1)
}
val len2 = getPalindromeLen(s, i, i + 1)
if (len2 >= result.length) {
result = s.substring(i - len2 / 2 + 1, i + len2 / 2 + 1)
}
}
return result
}
/**
* 判断回文串
*/
fun getPalindromeLen(s: String, i: Int, j: Int): Int {
var l = i
var r = j
while (l >= 0 && r < s.length) {
if (s[l] == s[r]) {
l -= 1
r += 1
} else {
break
}
}
return r - l - 1
}
@Test
fun _0005() {
// var str = "aacdefdcaa"
var str = "abcdcb"
val result = dp(str)
println(result)
}
| 29 | Kotlin | 0 | 2 | 6b188a8eb36e9930884c5fa310517be0db7f8922 | 2,629 | rice-noodles | Apache License 2.0 |
src/main/kotlin/ca/kiaira/advent2023/day11/Day11.kt | kiairatech | 728,913,965 | false | {"Kotlin": 78110} | package ca.kiaira.advent2023.day11
import ca.kiaira.advent2023.Puzzle
import kotlin.math.abs
/**
* Solution object for Day 11 puzzle of Advent of Code 2023.
*
* @author <NAME> <<EMAIL>>
* @since December 11th, 2023
*/
object Day11 : Puzzle<List<List<Char>>>(11) {
/**
* Parses the raw input data into a List of Lists containing individual characters.
*
* @param input The input data as a sequence of lines.
* @return A List of Lists representing the puzzle input.
*/
override fun parse(input: Sequence<String>): List<List<Char>> {
return input.map { it.toCharArray().toList() }.toList()
}
/**
* Solves Part 1 of the Day 11 puzzle.
*
* @param input The parsed puzzle data.
* @return The solution to Part 1 as any type.
*/
override fun solvePart1(input: List<List<Char>>): Any {
return solve(input, 2)
}
/**
* Solves Part 2 of the Day 11 puzzle.
*
* @param input The parsed puzzle data.
* @return The solution to Part 2 as any type.
*/
override fun solvePart2(input: List<List<Char>>): Any {
return solve(input, 1000000)
}
/**
* The core logic for solving both parts of the puzzle.
*
* @param universe The puzzle input represented as a List of Lists containing characters.
* @param size The size parameter used in the solution logic.
* @return The solution as a Long.
*/
private fun solve(universe: List<List<Char>>, size: Long): Long {
// Identify initial galaxy positions
val galaxies = mutableListOf<Pair<Int, Int>>()
for (row in universe.indices) {
for (col in universe[0].indices) {
if (universe[row][col] == '#') {
galaxies.add(row to col)
}
}
}
// Expand the universe based on size parameter
val expandedGalaxies = expandUniverse(galaxies, universe, size)
// Calculate the shortest paths between all expanded galaxies
return calculateShortestPaths(expandedGalaxies)
}
/**
* Expands the universe based on the given parameters and calculates new galaxy positions.
*
* @param galaxies The list of initial galaxy positions.
* @param universe The puzzle input represented as a List of Lists containing characters.
* @param size The size parameter used for expanding the universe.
* @return A List of expanded galaxy positions.
*/
private fun expandUniverse(
galaxies: MutableList<Pair<Int, Int>>,
universe: List<List<Char>>,
size: Long
): List<Pair<Long, Long>> {
// Identify empty rows and columns
val emptyRows = universe.indices.filter { row -> universe[row].all { it == '.' } }
val emptyCols = universe[0].indices.filter { col -> universe.all { it[col] == '.' } }
// Apply expansion logic for each galaxy
return galaxies.map { (row, col) ->
var newRow = row.toLong()
var newCol = col.toLong()
for (er in emptyRows) {
if (row > er) newRow += size - 1
}
for (ec in emptyCols) {
if (col > ec) newCol += size - 1
}
newRow to newCol
}
}
/**
* Calculates the shortest paths between all pairs of galaxies in the expanded universe.
*
* @param galaxies The list of expanded galaxy positions.
* @return The sum of all shortest paths as a Long.
*/
private fun calculateShortestPaths(galaxies: List<Pair<Long, Long>>): Long {
// Calculate all pairwise distances
return galaxies.flatMap { galaxy1 ->
galaxies.map { galaxy2 ->
abs(galaxy1.first - galaxy2.first) + abs(galaxy1.second - galaxy2.second)
}
}.sum() / 2L // Each pair is counted twice, so divide by 2
}
}
| 0 | Kotlin | 0 | 1 | 27ec8fe5ddef65934ae5577bbc86353d3a52bf89 | 3,482 | kAdvent-2023 | Apache License 2.0 |
src/Day22.kt | AlaricLightin | 572,897,551 | false | {"Kotlin": 87366} | import java.io.PrintWriter
import java.lang.StringBuilder
// This solution works only on my input fold type
fun main() {
fun part1(input: List<String>): Int {
val map: Array<Array<Cell>> = readMap(input)
val instructions = input.last()
val board = Board(map, true)
return board.execute(instructions)
}
fun part2(input: List<String>): Int {
val map: Array<Array<Cell>> = readMap(input)
val instructions = input.last()
val board = Board(map, false)
return board.execute(instructions)
}
val testInput = readInput("Day22_test")
check(part1(testInput) == 6032)
//check(part2(testInput) == 301L)
check(part2(readInput("Day22_test2")) == 4039)
val input = readInput("Day22")
println(part1(input))
println(part2(input))
}
private enum class Cell { EMPTY, OPEN, WALL }
private data class Position(val row: Int, val column: Int, val direction: Int)
private fun readMap(input: List<String>): Array<Array<Cell>> {
val maxWidth = input.maxOf { it.length }
return Array(input.size - 2) {
Array(maxWidth) { idx ->
if (idx <= input[it].lastIndex)
when (input[it][idx]) {
' ' -> Cell.EMPTY
'.' -> Cell.OPEN
'#' -> Cell.WALL
else -> throw IllegalArgumentException()
}
else Cell.EMPTY
}
}
}
private class Board(
val map: Array<Array<Cell>>,
val isPart1: Boolean
) {
private val edgeSize = map.size / 4
private val movesArray: Array<Pair<Int, Int>> = arrayOf(
Pair(0, 1), Pair(1, 0), Pair(0, -1), Pair(-1, 0)
)
val getNextPositionFunction: (Position, Pair<Int, Int>) -> Position? = if (isPart1)
this::getNextPosition
else
this::getNextPosition2
private val savedMap: Array<StringBuilder> = Array(map.size) {
val result = StringBuilder()
for (cell in map[it]) {
val c: Char = when (cell) {
Cell.EMPTY -> ' '
Cell.OPEN -> '.'
Cell.WALL -> '#'
}
result.append(c)
}
result
}
fun execute(instructions: String): Int {
var position = getStartPosition()
var stepCount = 0
var iteration = 0
for (c in instructions) {
if (c == 'R' || c == 'L') {
if (stepCount > 0) {
position = getNextMove(position, stepCount)
stepCount = 0
}
position = rotate(position, c)
iteration++
//if (iteration % 100 == 0)
// savePathToFile(iteration)
} else
stepCount = stepCount * 10 + c.digitToInt()
}
if (stepCount > 0) {
position = getNextMove(position, stepCount)
}
return 1000 * (position.row + 1) + 4 * (position.column + 1) + position.direction
}
private fun rotate(position: Position, c: Char): Position {
var direction = position.direction
if (c == 'R')
direction++
else
direction--
if (direction == 4)
direction = 0
else if (direction == -1)
direction = 3
return Position(position.row, position.column, direction)
}
private fun getStartPosition(): Position {
map[0].forEachIndexed { index, cell ->
if (cell == Cell.OPEN) return Position(0, index, 0)
}
throw IllegalArgumentException()
}
private fun getNextMove(
position: Position,
count: Int
): Position {
var current = position
repeat(count) {
val move = movesArray[current.direction]
val next: Position? = getNextPositionFunction(current, move)
if (next != null)
current = next
else
return current
}
return current
}
fun getNextPosition(position: Position, move: Pair<Int, Int>): Position? {
var newRow = position.row
var newColumn = position.column
while (true) {
newRow += move.first
newColumn += move.second
if (newRow < 0)
newRow = map.lastIndex
else if (newRow == map.size)
newRow = 0
if (newColumn < 0)
newColumn = map[newRow].lastIndex
else if (newColumn == map[newRow].size)
newColumn = 0
when (map[newRow][newColumn]) {
Cell.EMPTY -> {}
Cell.WALL -> return null
Cell.OPEN -> return Position(newRow, newColumn, position.direction)
}
}
}
fun getNextPosition2(position: Position, move: Pair<Int, Int>): Position? {
val newPosition0 = Position(
position.row + move.first,
position.column + move.second,
position.direction
)
val newPosition = moveThroughEdge(newPosition0)
return if (map[newPosition.row][newPosition.column] == Cell.OPEN) {
addToSavedMap(newPosition)
newPosition
} else
null
}
private fun moveThroughEdge(position: Position): Position {
return when {
// 1 -> 6
position.row < 0 && position.column in edgeSize until 2 * edgeSize ->
Position(2 * edgeSize + position.column, 0, 0)
// 2 -> 6
position.row < 0 && position.column >= 2 * edgeSize ->
Position(4 * edgeSize - 1, position.column - 2 * edgeSize, 3)
// 2 -> 5
position.row in 0 until edgeSize && position.column == 3 * edgeSize ->
Position(3 * edgeSize - 1 - position.row, 2 * edgeSize - 1, 2)
// 2 -> 3
position.row == edgeSize && position.column >= 2 * edgeSize &&
position.direction == 1 ->
Position(position.column - edgeSize, 2 * edgeSize - 1, 2)
// 3 -> 2
position.row in edgeSize until 2 * edgeSize && position.column == 2 * edgeSize &&
position.direction == 0 ->
Position(edgeSize - 1, edgeSize + position.row, 3)
// 5 -> 2
position.row in 2 * edgeSize until 3 * edgeSize && position.column == 2 * edgeSize &&
position.direction == 0 ->
Position(3 * edgeSize - 1 - position.row, 3 * edgeSize - 1, 2)
// 5 -> 6
position.row == 3 * edgeSize && position.column in edgeSize until 2 * edgeSize &&
position.direction == 1 ->
Position(2 * edgeSize + position.column, edgeSize - 1, 2)
// 6 -> 5
position.row >= 3 * edgeSize && position.column == edgeSize &&
position.direction == 0 ->
Position(3 * edgeSize - 1, position.row - 2 * edgeSize, 3)
// 6 -> 2
position.row == 4 * edgeSize ->
Position(0, position.column + 2 * edgeSize, 1)
// 6 -> 1
position.row >= 3 * edgeSize && position.column < 0 ->
Position(0, position.row - 2 * edgeSize, 1)
// 4 -> 1
position.row in 2 * edgeSize until 3 * edgeSize && position.column < 0 ->
Position(3 * edgeSize - 1 - position.row, edgeSize, 0)
// 4 -> 3
position.row == 2 * edgeSize - 1 && position.column < edgeSize
&& position.direction == 3 ->
Position(position.column + edgeSize, edgeSize, 0)
// 3 -> 4
position.row in edgeSize until 2 * edgeSize && position.column == edgeSize - 1 &&
position.direction == 2 ->
Position(2 * edgeSize, position.row - edgeSize, 1)
// 1 -> 4
position.row < edgeSize && position.column == edgeSize - 1 &&
position.direction == 2 ->
Position(3 * edgeSize - 1 - position.row, 0, 0)
else -> position
}
}
private fun addToSavedMap(position: Position) {
val c: Char = when (position.direction) {
0 -> '>'
1 -> 'v'
2 -> '<'
3 -> 'A'
else -> '%'
}
savedMap[position.row][position.column] = c
}
private fun savePathToFile(iteration: Int) {
if (isPart1)
return
PrintWriter("logs/$iteration.txt").use {
savedMap.forEach { sb ->
it.appendLine(sb.toString())
}
}
}
}
| 0 | Kotlin | 0 | 0 | ee991f6932b038ce5e96739855df7807c6e06258 | 8,754 | AdventOfCode2022 | Apache License 2.0 |
src/Day01.kt | AlexeyVD | 575,495,640 | false | {"Kotlin": 11056} | fun main() {
fun part1(input: List<String>): Int {
return getMaxSum(input, 1)
}
fun part2(input: List<String>): Int {
return getMaxSum(input, 3)
}
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
fun getMaxSum(input: List<String>, entries: Int): Int {
if (input.isEmpty()) return 0
val result = ArrayList<Int>()
var current = 0
input.forEach {
if (it.isBlank()) {
result.add(current)
current = 0
} else {
current += it.toInt()
}
}
if (current != 0)
result.add(current)
result.sort()
return when {
result.isEmpty() -> 0
else -> result.takeLast(minOf(result.size, entries)).sum()
}
}
| 0 | Kotlin | 0 | 0 | ec217d9771baaef76fa75c4ce7cbb67c728014c0 | 898 | advent-kotlin | Apache License 2.0 |
src/Day14.kt | sushovan86 | 573,586,806 | false | {"Kotlin": 47064} | import kotlin.math.abs
import kotlin.math.sign
class RegolithReservoir private constructor(private val rocksCoordinates: Set<Coordinate>) {
private val initialSandCoordinate = Coordinate(500, 0)
private val restingSandCoordinates = mutableSetOf<Coordinate>()
private val depth: Int = rocksCoordinates.maxOf { it.y }
private fun Coordinate.nextSandCoordinate() = sequence {
yield(copy(y = y + 1))
yield(copy(x = x - 1, y = y + 1))
yield(copy(x = x + 1, y = y + 1))
}.firstOrNull { it !in rocksCoordinates && it !in restingSandCoordinates }
fun getUnitsOfSandInRest(): Int {
restingSandCoordinates.clear()
var currentSandCoordinate = initialSandCoordinate
while (currentSandCoordinate.y < depth) {
val nextSandCoordinate = currentSandCoordinate.nextSandCoordinate()
if (nextSandCoordinate != null) {
currentSandCoordinate = nextSandCoordinate
} else {
restingSandCoordinates += currentSandCoordinate
currentSandCoordinate = initialSandCoordinate
}
}
return restingSandCoordinates.size
}
fun getUnitsOfSandToBlockSource(): Int {
restingSandCoordinates.clear()
val floor = depth + 2
var currentSandCoordinate = initialSandCoordinate
while (initialSandCoordinate !in restingSandCoordinates) {
val nextSandCoordinate = currentSandCoordinate.nextSandCoordinate()
if (nextSandCoordinate == null || nextSandCoordinate.y == floor) {
restingSandCoordinates += currentSandCoordinate
currentSandCoordinate = initialSandCoordinate
} else {
currentSandCoordinate = nextSandCoordinate
}
}
return restingSandCoordinates.size
}
data class Coordinate(val x: Int = 0, val y: Int = 0) {
infix fun lineTo(other: Coordinate): List<Coordinate> {
val dx = other.x - x
val dy = other.y - y
val coordinateList = mutableListOf(this)
// Add In between coordinates
(1 until maxOf(abs(dx), abs(dy))).map {
coordinateList += Coordinate(x + it * dx.sign, y + it * dy.sign)
}
coordinateList += other
return coordinateList
}
}
companion object {
fun load(inputList: List<String>): RegolithReservoir {
val rocksCoordinates = inputList.flatMap { line ->
line.split("->")
.map {
val (first, second) = it.split(",")
Coordinate(first.trim().toInt(), second.trim().toInt())
}
.zipWithNext()
.flatMap { (start, end) -> start lineTo end }
}.toSet()
return RegolithReservoir(rocksCoordinates)
}
}
}
fun main() {
val testInput = readInput("Day14_test")
val testRegolithReservoir = RegolithReservoir.load(testInput)
check(testRegolithReservoir.getUnitsOfSandInRest() == 24)
check((testRegolithReservoir.getUnitsOfSandToBlockSource() == 93))
val actualInput = readInput("Day14")
val regolithReservoir = RegolithReservoir.load(actualInput)
println(regolithReservoir.getUnitsOfSandInRest())
println(regolithReservoir.getUnitsOfSandToBlockSource())
} | 0 | Kotlin | 0 | 0 | d5f85b6a48e3505d06b4ae1027e734e66b324964 | 3,437 | aoc-2022 | Apache License 2.0 |
Kotlin/src/ThreeSumClosest.kt | TonnyL | 106,459,115 | false | null | /**
* Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target.
* Return the sum of the three integers.
* You may assume that each input would have exactly one solution.
*
* For example, given array S = {-1 2 1 -4}, and target = 1.
*
* The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
*
* Accepted.
*/
class ThreeSumClosest {
fun threeSumClosest(nums: IntArray, target: Int): Int {
nums.sort()
var result = nums[0] + nums[1] + nums[2]
for (i in 0 until nums.size - 2) {
var l = i + 1
var r = nums.size - 1
while (l < r) {
val tmp = nums[i] + nums[l] + nums[r]
if (tmp == target) {
return tmp
}
if (Math.abs(tmp - target) < Math.abs(result - target)) {
result = tmp
}
if (tmp < target) {
l++
} else if (tmp > target) {
r--
}
}
}
return result
}
}
| 1 | Swift | 22 | 189 | 39f85cdedaaf5b85f7ce842ecef975301fc974cf | 1,132 | Windary | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindUnsortedSubArray.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.Stack
import kotlin.math.max
import kotlin.math.min
/**
* Shortest Unsorted Continuous Subarray
* @see <a href="https://leetcode.com/problems/shortest-unsorted-continuous-subarray/">Source</a>
*/
fun interface FindUnsortedSubArray {
operator fun invoke(nums: IntArray): Int
}
/**
* Approach 1: Brute Force
* Time complexity : O(n^3)
* Space complexity : O(1)
*/
class FindUnsortedSubArrayBruteForce : FindUnsortedSubArray {
override operator fun invoke(nums: IntArray): Int {
var res: Int = nums.size
for (i in nums.indices) {
for (j in i..nums.size) {
var min = Int.MAX_VALUE
var max = Int.MIN_VALUE
var prev = Int.MIN_VALUE
for (k in i until j) {
min = min(min, nums[k])
max = max(max, nums[k])
}
val first = i > 0 && nums[i - 1] > min
val second = j < nums.size && nums[j] < max
if (first || second) continue
var k = 0
while (k < i && prev <= nums[k]) {
prev = nums[k]
k++
}
if (k != i) continue
k = j
while (k < nums.size && prev <= nums[k]) {
prev = nums[k]
k++
}
if (k == nums.size) {
res = min(res, j - i)
}
}
}
return res
}
}
/**
* Approach 2: Better Brute Force
* Time complexity : O(n^2)
* Space complexity : O(1)
*/
class FindUnsortedSubArrayBetterBruteForce : FindUnsortedSubArray {
override operator fun invoke(nums: IntArray): Int {
var l: Int = nums.size
var r = 0
for (i in 0 until nums.size - 1) {
for (j in i + 1 until nums.size) {
if (nums[j] < nums[i]) {
r = max(r, j)
l = min(l, i)
}
}
}
return if (r - l <= 0) 0 else r - l + 1
}
}
/**
* Approach 3: Using Sorting
* Time complexity : O(n\log n)
* Space complexity : O(n)
*/
class FindUnsortedSubArraySort : FindUnsortedSubArray {
override operator fun invoke(nums: IntArray): Int {
val snums = nums.clone().sorted()
var start = snums.size
var end = 0
for (i in snums.indices) {
if (snums[i] != nums[i]) {
start = min(start, i)
end = max(end, i)
}
}
return if (end - start > 0) end - start + 1 else 0
}
}
/**
* Approach 4: Using Stack
* Time complexity : O(n)
* Space complexity : O(n)
*/
class FindUnsortedSubArrayStack : FindUnsortedSubArray {
override operator fun invoke(nums: IntArray): Int {
val stack: Stack<Int> = Stack<Int>()
var l: Int = nums.size
var r = 0
for (i in nums.indices) {
while (stack.isNotEmpty() && nums[stack.peek()] > nums[i]) l = min(l, stack.pop())
stack.push(i)
}
stack.clear()
for (i in nums.size - 1 downTo 0) {
while (stack.isNotEmpty() && nums[stack.peek()] < nums[i]) r = max(r, stack.pop())
stack.push(i)
}
return if (r - l > 0) r - l + 1 else 0
}
}
/**
* Approach 5: Without Using Extra Space
* Time complexity : O(n)
* Space complexity : O(1)
*/
class FindUnsortedSubArrayConstSpace : FindUnsortedSubArray {
override operator fun invoke(nums: IntArray): Int {
var min = Int.MAX_VALUE
var max = Int.MIN_VALUE
var flag = false
for (i in 1 until nums.size) {
if (nums[i] < nums[i - 1]) flag = true
if (flag) min = min(min, nums[i])
}
flag = false
for (i in nums.size - 2 downTo 0) {
if (nums[i] > nums[i + 1]) flag = true
if (flag) max = max(max, nums[i])
}
var l = 0
while (l < nums.size) {
if (min < nums[l]) break
l++
}
var r: Int = nums.size - 1
while (r >= 0) {
if (max > nums[r]) break
r--
}
return if (r - l < 0) 0 else r - l + 1
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 4,922 | kotlab | Apache License 2.0 |
src/main/kotlin/Day02.kt | robert-iits | 573,124,643 | false | {"Kotlin": 21047} | import org.junit.jupiter.api.Assertions.assertEquals
// ROCK PAPER SCISSOR
// A, B, C
// X, Y, Z
// 0 1 2
// win draw loss
// PAPER (1) -> ROCK (0)
// ROCK (0) -> SCISSOR (2)
// SCISSOR (2) -> PAPER (1)
fun main() {
fun normalize(char: Char): Int {
return if (char.code >= 'X'.code) {
char.code - 'X'.code
} else {
char.code - 'A'.code
}
}
fun previous(n: Int) = (n + 2) % 3
fun next(n: Int) = (n + 1) % 3
fun score(game: Game): Int =
game.self + 1 + 3 * (if (game.self == next(game.opponent)) 2 else if (game.self == game.opponent) 1 else 0)
fun correctRound(round: String): Game {
return when (round.last()) {
'X' -> Game(normalize(round.first()), previous(normalize(round.first())))
'Y' -> Game(normalize(round.first()), normalize(round.first()))
'Z' -> Game(normalize(round.first()), next(normalize(round.first())))
else -> throw IllegalAccessException()
}
}
fun part1(input: List<String>): Int {
return input.map { Game(normalize(it.first()), normalize(it.last())) }.sumOf { score(it) }
}
fun part2(input: List<String>): Int {
return input.map { correctRound(it) }.sumOf { score(it) }
}
// test if implementation meets criteria from the description, like:
val testInput = listOf("A Y", "B X", "C Z")
assertEquals(15, part1(testInput))
assertEquals(12, part2(testInput))
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
class Game(val opponent: Int, val self: Int) | 0 | Kotlin | 0 | 0 | 223017895e483a762d8aa2cdde6d597ab9256b2d | 1,620 | aoc2022 | Apache License 2.0 |
src/Day06.kt | andydenk | 573,909,669 | false | {"Kotlin": 24096} | fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
check(part1(testInput[0]) == 7)
check(part1(testInput[1]) == 5)
check(part1(testInput[2]) == 6)
check(part1(testInput[3]) == 10)
check(part1(testInput[4]) == 11)
check(part2(testInput[0]) == 19)
check(part2(testInput[1]) == 23)
check(part2(testInput[2]) == 23)
check(part2(testInput[3]) == 29)
check(part2(testInput[4]) == 26)
val input = readInput("Day06").first()
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
private fun part1(input: String): Int = detectSignal(input, 4)
private fun part2(input: String): Int = detectSignal(input, 14)
private fun detectSignal(input: String, uniqueCharacters: Int): Int {
return input
.windowedSequence(uniqueCharacters)
.indexOfFirst { it.toSet().size == uniqueCharacters } + uniqueCharacters
}
| 0 | Kotlin | 0 | 0 | 1b547d59b1dc55d515fe8ca8e88df05ea4c4ded1 | 966 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | DiamondMiner88 | 573,073,199 | false | {"Kotlin": 26457, "Rust": 4093, "Shell": 188} | fun main() {
d3part1()
d3part2()
}
fun d3part1() {
val input = readInput("input/day03.txt")
.split("\n")
.filter { it.isNotBlank() }
.map { it.take(it.length / 2) to it.takeLast(it.length / 2) }
var total = 0
for (rucksack in input) {
val (comp1, comp2) = rucksack
val common = comp1.toList().intersect(comp2.toList())
for (char in common) {
if (char >= 'a') total += char.code - 96
else if (char >= 'A') total += char.code - 38
}
}
println(total)
}
fun d3part2() {
val input = readInput("input/day03.txt")
.split("\n")
.filter { it.isNotBlank() }
.chunked(3)
var total = 0
for (group in input) {
val (ruck1, ruck2, ruck3) = group
val common = ruck1.toList().intersect(ruck2.toList().intersect(ruck3.toList()))
for (char in common) {
if (char >= 'a') total += char.code - 96
else if (char >= 'A') total += char.code - 38
}
}
println(total)
}
| 0 | Kotlin | 0 | 0 | 55bb96af323cab3860ab6988f7d57d04f034c12c | 1,060 | advent-of-code-2022 | Apache License 2.0 |
src/test/kotlin/com/igorwojda/string/issubstring/Solution.kt | igorwojda | 159,511,104 | false | {"Kotlin": 254856} | package com.igorwojda.string.issubstring
// Time complexity: O(n*m)
// Space complexity: O(1)
//
// Optimal solution using double pointer.
private object Solution1 {
private fun isSubstring(str: String, subStr: String): Boolean {
if (subStr.isEmpty()) return true
if (str.length < subStr.length) return false
var pointer1 = 0
var pointer2 = 0
while (pointer1 <= str.lastIndex) {
if (str[pointer1] == subStr[pointer2]) {
pointer1++
pointer2++
if (pointer2 == subStr.length) {
return true
}
} else {
pointer1 = pointer1 - pointer2 + 1
pointer2 = 0
}
}
return false
}
}
// Time complexity: O(n*m)
// Space complexity: ??, but more than O(1)
// Number of iterations (n) is bounded by the length of the first string
// and String.drop requires copying the entire remaining string (on it's own it has O(m) complexity)
// First of 5 chars, needs 5 iterations at most and 15 character copied (5+4+3+2+1=15). Second is copied less often.
//
// Recursive solution
private object Solution2 {
private fun isSubstring(str: String, subStr: String): Boolean {
fun isExactMatch(str: String, subStr: String): Boolean {
if (subStr.length > str.length) {
return false
}
return when {
str.isEmpty() && subStr.isEmpty() -> true
str.isNotEmpty() && subStr.isEmpty() -> true
else -> str[0] == subStr[0] && isExactMatch(str.drop(1), subStr.drop(1))
}
}
if (subStr.length > str.length) {
return false
}
if (str.isEmpty() || subStr.isEmpty()) {
return true
}
return isExactMatch(str, subStr) || isSubstring(str.drop(1), subStr)
}
}
private object Solution3 {
private fun isSubstring(str: String, subStr: String): Boolean {
if (subStr.isEmpty()) return true
return str
.windowed(subStr.length)
.any { it == subStr }
}
}
// Time complexity: O(n*m)
// Space complexity: O(1)
// This recursive solution is faster than solution with String.drop because it uses double pointer
//
// Recursive solution
private fun isSubstring(str: String, subStr: String): Boolean {
if (subStr.isEmpty()) {
return true
}
fun helper(first: String, second: String, firstPointer1: Int = 0, secondPointer2: Int = 0): Boolean {
if (firstPointer1 > first.lastIndex) {
return false
}
return if (first[firstPointer1] == second[secondPointer2]) {
val localPointer1 = firstPointer1 + 1
val localPointer2 = secondPointer2 + 1
when {
localPointer1 <= first.lastIndex && localPointer2 <= second.lastIndex -> {
helper(first, second, localPointer1, localPointer2)
}
localPointer2 <= second.lastIndex && localPointer1 > first.lastIndex -> false
else -> true
}
} else {
val p1 = firstPointer1 - secondPointer2 + 1
if (p1 > first.lastIndex) {
return false
} else {
helper(first, second, p1, 0)
}
}
}
return helper(str, subStr)
}
| 9 | Kotlin | 225 | 895 | b09b738846e9f30ad2e9716e4e1401e2724aeaec | 3,435 | kotlin-coding-challenges | MIT License |
src/Day10.kt | casslabath | 573,177,204 | false | {"Kotlin": 27085} | fun main() {
fun part1(input: List<String>): Int {
var cycleStop = 20
var cycle = 0
var x = 1
val signalStrengths = mutableListOf<Int>()
input.map{
val splitStr = it.split(" ")
val op = splitStr[0]
if(op == "addx") {
val num = splitStr[1].toInt()
for(i in 0..1) {
cycle++
// if the cycle is at 20,60,100,140,180 or 220 get signal strength
if(cycle == cycleStop) {
signalStrengths.add(x * cycle)
cycleStop += 40
}
// if this is the second cycle for the addx, add num to x
if(i == 1) {
x += num
}
}
} else {
cycle++
// if the cycle is at 20,60,100,140,180 or 220 get signal strength
if(cycle == cycleStop) {
signalStrengths.add(x * cycle)
cycleStop += 40
}
}
}
return signalStrengths.sum()
}
fun part2(input: List<String>) {
val pixels = MutableList(240){'.'}
var xPos = mutableListOf(0,1,2)
var cycle = 0
input.map{
val splitStr = it.split(" ")
val op = splitStr[0]
if(op == "addx") {
val num = splitStr[1].toInt()
for(i in 0..1) {
// draw pixel if cycle location is in the register
if(xPos.contains((cycle).mod(40))) {
pixels[cycle] = '#'
}
cycle++
// On the second cycle of the addx set the register at the num
if(i == 1) {
val x = xPos[1] + num
xPos = mutableListOf(x-1,x,x+1)
}
}
} else {
// draw pixel if cycle location is in the register
if(xPos.contains((cycle).mod(40))) {
pixels[cycle] = '#'
}
cycle++
}
}
pixels.chunked(40) {
it.forEach{num -> print("$num ") }
println()
}
}
val input = readInput("Day10")
println(part1(input))
part2(input)
}
| 0 | Kotlin | 0 | 0 | 5f7305e45f41a6893b6e12c8d92db7607723425e | 2,449 | KotlinAdvent2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/GetSumAbsoluteDifferences.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
/**
* 1685. Sum of Absolute Differences in a Sorted Array
* @see <a href="https://leetcode.com/problems/sum-of-absolute-differences-in-a-sorted-array/">Source</a>
*/
fun interface GetSumAbsoluteDifferences {
operator fun invoke(nums: IntArray): IntArray
}
class GetSumAbsoluteDifferencesPrefixSum : GetSumAbsoluteDifferences {
override fun invoke(nums: IntArray): IntArray {
val n: Int = nums.size
val prefix = IntArray(n)
prefix[0] = nums[0]
for (i in 1 until n) {
prefix[i] = prefix[i - 1] + nums[i]
}
val ans = IntArray(n)
for (i in 0 until n) {
val leftSum = prefix[i] - nums[i]
val rightSum = prefix[n - 1] - prefix[i]
val rightCount = n - 1 - i
val leftTotal = i * nums[i] - leftSum
val rightTotal = rightSum - rightCount * nums[i]
ans[i] = leftTotal + rightTotal
}
return ans
}
}
class GetSumAbsoluteDifferencesPrefixSum2 : GetSumAbsoluteDifferences {
override fun invoke(nums: IntArray): IntArray {
val n: Int = nums.size
var totalSum = 0
for (num in nums) {
totalSum += num
}
var leftSum = 0
val ans = IntArray(n)
for (i in 0 until n) {
val rightSum = totalSum - leftSum - nums[i]
val rightCount = n - 1 - i
val leftTotal = i * nums[i] - leftSum
val rightTotal = rightSum - rightCount * nums[i]
ans[i] = leftTotal + rightTotal
leftSum += nums[i]
}
return ans
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,255 | kotlab | Apache License 2.0 |
src/main/kotlin/org/sjoblomj/adventofcode/day7/visualisation/Visualiser.kt | sjoblomj | 161,537,410 | false | null | package org.sjoblomj.adventofcode.day7.visualisation
import org.sjoblomj.adventofcode.Score
import org.sjoblomj.adventofcode.day7.Node
import org.sjoblomj.adventofcode.writeFile
import java.io.File
data class Coord(val col: Int, val row: Int)
fun visualise(nodes: List<Node>, resultingOrder: String) {
val preReqs = nodes.convertToPreReq()
val grid = orderNodesInGrid(preReqs)
// grid has mapped every node id to an x and y coordinate.
// It is, however, a dense graph that is not visually very pleasing.
// When drawing lines between the nodes, it will be difficult to
// make out the graph since the nodes are so close together,
// and many lines will go through other nodes.
//
// Although each node id has a unique x and y coordinate, we wish
// to update the y-coordinates so that the graph will look better.
// Using a genetic algorithm, we can stochastically compute this.
// The x coordinate for each node will be fixed, but the algorithm
// will seek to find better y coordinates.
val (solution, initialPopulation, bestIndividualInEachIteration) = runGeneticAlgorithm(preReqs, grid)
createVisualisationFileOnHarddrive(nodes, resultingOrder, grid, solution, initialPopulation,
bestIndividualInEachIteration)
}
/**
* Given a list of nodes, this function will return the node ids mapped to x and y positions for that node.
* The positions are chosen so that every node p that is a prerequisite for node q, the x-position of p will
* always be before that of q. In other words, the nodes are placed in the order that they must be completed in.
*
* The positions can be seen as a grid of x and y coordinates, although it should be noted that the majority
* of the positions in the grid will be empty. In the result, each id will deterministically have the same
* x-position assigned to it each time the function is executed, but the y-position is subject to change.
* A stochastic genetic algorithm is used to calculate y-positions, and the result is thus subject to randomness.
*/
internal fun orderNodesInGrid(nodes: List<PreReq>): Map<String, Coord> {
val grid = HashMap<String, Coord>()
var column = 0
while (!nodes.all { grid.containsKey(it.id) }) {
val nodesToBeAdded = nodes
.filter { !grid.containsKey(it.id) }
.filter { mapContainsEveryPrerequisite(it, grid) }
for (node in nodesToBeAdded) {
var row = 0
while (grid.containsValue(Coord(column, row))) {
row++
}
grid[node.id] = Coord(column, row)
}
column++
}
return grid
}
private fun mapContainsEveryPrerequisite(node: PreReq, grid: Map<String, Coord>) =
getAllPrerequisites(node).all { grid.containsKey(it.id) }
private fun getAllPrerequisites(node: PreReq) = getAllPrerequisitesIncludingSelf(node).minus(node)
private fun getAllPrerequisitesIncludingSelf(node: PreReq): List<PreReq> {
return node.prerequisites
.flatMap { getAllPrerequisitesIncludingSelf(it) }
.toMutableList()
.plus(node)
}
fun createVisualisationFileOnHarddrive(nodes: List<Node>, resultingOrder: String, originalGrid: Map<String, Coord>,
solution: Map<String, Coord>, initialPopulation: List<Map<String, Coord>>,
bestIndividualInEachIteration: List<Pair<Map<String, Coord>, Score>>) {
val content = Day7GeneticVisualiser::class.java.getResource("/visualisations/day7.html").readText()
fun replaceLine(content: String, searchString: String, newValue: String): String {
val stringIndex = content.indexOf(searchString)
val indexOfPreviousNewline = content.substring(0, stringIndex).lastIndexOf("\n") + 1
val indexOfNextNewline = content.indexOf("\n", stringIndex)
return content.substring(0, indexOfPreviousNewline) + newValue + content.substring(indexOfNextNewline)
}
val linkData = nodes.flatMap { nodeRep -> nodeRep.dependers.map { dep -> "{from: \"${nodeRep.id}\", to: \"${dep.id}\"}" } }.toString()
val nodeData = solution.map { "{id: \"${it.key}\", x: ${it.value.col + 1}, y: ${it.value.row + 1}}" }.toString()
val originalNodeOrdering = originalGrid.map { "{id: \"${it.key}\", x: ${it.value.col + 1}, y: ${it.value.row + 1}}" }.toString()
val initialPopulationData = initialPopulation.map { individual -> individual.map { "{id: \"${it.key}\", x: ${it.value.col + 1}, y: ${it.value.row + 1}}" }.toString() }
val bestIndividual = bestIndividualInEachIteration.map { (individual, score) ->
"{score: $score, individual: " + individual.map { "{id: \"${it.key}\", x: ${it.value.col + 1}, y: ${it.value.row + 1}}" }.toString() + "}"}
var updatedContent = content
updatedContent = replaceLine(updatedContent, "##VISUALIZER_RESULTING_ORDER##", " var resultingOrder = \"$resultingOrder\";")
updatedContent = replaceLine(updatedContent, "##VISUALIZER_LINK_DATA##", " var linkData = $linkData;")
updatedContent = replaceLine(updatedContent, "##VISUALIZER_SOLUTION##", " var solution = $nodeData;")
updatedContent = replaceLine(updatedContent, "##VISUALIZER_ORIGINAL_NODE_ORDERING##", " var originalNodeOrdering = $originalNodeOrdering;")
updatedContent = replaceLine(updatedContent, "##VISUALIZER_ORIGINAL_POPULATION##", " var initialPopulation = $initialPopulationData;")
updatedContent = replaceLine(updatedContent, "##VISUALIZER_BEST_INDIVIDUAL_IN_EACH_ITERATION##", " var bestIndividualInEachIteration = $bestIndividual;")
val dir = "./build/visualisations/"
val filename = "day7.html"
if (!File(dir).exists()) {
assert(File(dir).mkdir())
}
writeFile(dir + filename, updatedContent)
}
data class PreReq(val id: String, val prerequisites: List<PreReq>)
internal fun Collection<Node>.convertToPreReq(): List<PreReq> {
fun createPreReq(node: Node): PreReq = PreReq(node.id, node.prerequisites.map { createPreReq(it) } )
return this.map { createPreReq(it) }
}
| 0 | Kotlin | 0 | 0 | 80db7e7029dace244a05f7e6327accb212d369cc | 5,909 | adventofcode2018 | MIT License |
src/Day05.kt | arhor | 572,349,244 | false | {"Kotlin": 36845} | import java.util.*
fun main() {
val input = readInput {}
println("Part 1: " + solvePuzzle(input, insertReversed = true))
println("Part 2: " + solvePuzzle(input, insertReversed = false))
}
private val cratePattern = Regex("(\\[([A-Z])])| {3}")
private val instrPattern = Regex("^move ([0-9]+) from ([0-9]+) to ([0-9]+)$")
private fun solvePuzzle(input: List<String>, insertReversed: Boolean): String {
val table = TreeMap<Int, LinkedList<String>>()
for (line in input) {
cratePattern.findAll(line).map { it.groupValues[2] }.forEachIndexed { i, crate ->
if (crate.isNotEmpty()) {
table.computeIfAbsent(i + 1) { LinkedList() }.push(crate)
}
}
instrPattern.find(line)?.destructured?.toList()?.map { it.toInt() }?.let { (number, from, to) ->
val source = table[from]!!
val target = table[to]!!
if (insertReversed) {
repeat(number) {
target.add(source.removeLast())
}
} else {
val insertPos = target.lastIndex
repeat(number) {
target.add(insertPos + 1, source.removeLast())
}
}
}
}
return table.values.joinToString(separator = "") { it.last }
}
| 0 | Kotlin | 0 | 0 | 047d4bdac687fd6719796eb69eab2dd8ebb5ba2f | 1,325 | aoc-2022-in-kotlin | Apache License 2.0 |
TwoSumEqualToTarget.kt | sysion | 353,734,921 | false | null | /**
* https://leetcode.com/problems/two-sum/
*
* Two Sum Less Than K
*
* Given an array of integers nums and an integer target, return indices of the
* two numbers such that they add up to target.
*
* You may assume that each input would have exactly one solution, and you may
* not use the same element twice.
*
* You can return the answer in any order.
*
* Example 1:
* Input: nums = [2,7,11,15], target = 9
* Output: [0,1]
* Output: Because nums[0] + nums[1] == 9, we return [0, 1].
*
* Example 2:
* Input: nums = [3,2,4], target = 6
* Output: [1,2]
*
* Example 3:
* Input: nums = [3,3], target = 6
* Output: [0,1]
*
* Constraints:
*
* 2 <= nums.length <= 10^3
* -10^9 <= nums[i] <= 10^9
* -10^9 <= target <= 10^9
* Only one valid answer exists.
*/
import java.util.Arrays
fun main(){
//val inputArray: IntArray = intArrayOf(2,7,11,15)
//val targetSum = 9
//val inputArray: IntArray = intArrayOf(3,2,4)
//val targetSum = 6
val inputArray: IntArray = intArrayOf(3,3)
val targetSum = 6
SumTwoNumbersEqualToTarget(inputArray, targetSum)
}
fun SumTwoNumbersEqualToTarget(intArray: IntArray, target: Int): IntArray {
var result: IntArray = IntArray(2)
val sumCheck: HashMap<Int, Int> = hashMapOf<Int, Int>()
var sumPair = 0
for (cnt in intArray.indices){
sumPair = target - intArray[cnt]
if (sumCheck.containsKey(sumPair)) {
result[0] = sumCheck[sumPair]!!
result[1] = cnt
}
sumCheck[intArray[cnt]] = cnt
}
println(Arrays.toString(result))
return result
} | 0 | Kotlin | 0 | 0 | 6f9afda7f70264456c93a69184f37156abc49c5f | 1,494 | DataStructureAlgorithmKt | Apache License 2.0 |
src/Day04.kt | joy32812 | 573,132,774 | false | {"Kotlin": 62766} | fun main() {
fun String.toRange() = this.split("-").map { it.toInt() }.let { it[0]..it[1] }
fun part1(input: List<String>): Int {
return input.count { line ->
val r1 = line.split(",").first().toRange()
val r2 = line.split(",").last().toRange()
r1.all { it in r2 } || r2.all { it in r1 }
}
}
fun part2(input: List<String>): Int {
return input.count { line ->
val r1 = line.split(",").first().toRange()
val r2 = line.split(",").last().toRange()
r1.any { it in r2 }
}
}
println(part1(readInput("data/Day04_test")))
println(part1(readInput("data/Day04")))
println(part2(readInput("data/Day04_test")))
println(part2(readInput("data/Day04")))
}
| 0 | Kotlin | 0 | 0 | 5e87958ebb415083801b4d03ceb6465f7ae56002 | 793 | aoc-2022-in-kotlin | Apache License 2.0 |
src/questions/SpiralMatrix.kt | realpacific | 234,499,820 | false | null | package questions
import _utils.UseCommentAsDocumentation
import utils.assertIterableSame
/**
* Given an `m x n` matrix, return all elements of the `matrix` in spiral order.
*
* [Source](https://leetcode.com/problems/spiral-matrix) – [Solution](https://leetcode.com/problems/spiral-matrix/discuss/20571/1-liner-in-Python-%2B-Ruby)
*/
@UseCommentAsDocumentation
private fun spiralOrder(matrix: Array<IntArray>): List<Int> {
val result = ArrayList<Int>(matrix[0].size * matrix.size)
_spiralOrder(matrix.toMutableList(), result)
return result
}
private fun _spiralOrder(matrix: MutableList<IntArray>, result: MutableList<Int>) {
if (matrix.isEmpty()) {
return
}
val firstRow = matrix[0]
val remaining = matrix.slice(1..matrix.lastIndex) // remove the first row
firstRow.forEach {
result.add(it) // add the removed row
}
_spiralOrder(invert(transpose(remaining)), result) // transpose and then invert (rotate anti-clockwise)
}
private fun transpose(matrix: List<IntArray>): MutableList<IntArray> {
if (matrix.isEmpty()) return mutableListOf()
val transposedMatrix = MutableList(matrix[0].size) {
IntArray(matrix.size) { -1 }
}
for (row in 0..matrix.lastIndex) {
for (col in 0..matrix[0].lastIndex) {
transposedMatrix[col][row] = matrix[row][col]
}
}
return transposedMatrix
}
private fun invert(matrix: MutableList<IntArray>): MutableList<IntArray> {
if (matrix.isEmpty()) return mutableListOf()
for (row in 0..matrix.lastIndex / 2) { // Gotcha: loop till half way
val temp = matrix[row]
matrix[row] = matrix[matrix.lastIndex - row]
matrix[matrix.lastIndex - row] = temp
}
return matrix
}
fun main() {
assertIterableSame(
listOf(1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7),
spiralOrder(
arrayOf(
intArrayOf(1, 2, 3, 4),
intArrayOf(5, 6, 7, 8),
intArrayOf(9, 10, 11, 12)
)
)
)
assertIterableSame(
listOf(1, 2, 3, 6, 9, 8, 7, 4, 5),
spiralOrder(arrayOf(intArrayOf(1, 2, 3), intArrayOf(4, 5, 6), intArrayOf(7, 8, 9))),
)
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 2,254 | algorithms | MIT License |
src/Day01.kt | devheitt | 573,207,407 | false | {"Kotlin": 11944} | fun main() {
fun part1(input: List<String>): Int {
var maxAccumulated = 0
var accumulated = 0
for (calories in input) {
if (calories.isEmpty()) {
accumulated = 0
continue
}
val value = calories.toInt()
accumulated += value
if (accumulated > maxAccumulated)
maxAccumulated = accumulated
}
return maxAccumulated
}
fun part2(input: List<String>): Int {
var accumulated = 0
var listOfTotals = mutableListOf<Int>()
for (calories in input) {
if (calories.isEmpty()) {
listOfTotals.add(accumulated)
accumulated = 0
continue
}
val value = calories.toInt()
accumulated += value
}
listOfTotals.add(accumulated)
return listOfTotals.sortedDescending().subList(0,3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a9026a0253716d36294709a547eaddffc6387261 | 1,258 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/aoc2022/Day09.kt | Playacem | 573,606,418 | false | {"Kotlin": 44779} | package aoc2022
import utils.readInput
import kotlin.math.abs
private data class Pos(val x: Int, val y: Int)
private data class Day09Command(val direction: String, val times: Int)
private operator fun Pos.plus(pair: Pair<Int, Int>): Pos {
val (plusX, plusY) = pair
return this.copy(x = this.x + plusX, y = this.y + plusY)
}
private fun isTouching(head: Pos, tail: Pos): Boolean {
val xDiff = abs(head.x - tail.x)
val yDiff = abs(head.y - tail.y)
return xDiff <= 1 && yDiff <= 1
}
private fun hasSameXLevel(head: Pos, tail: Pos): Boolean {
return head.x - tail.x == 0
}
private fun hasSameYLevel(head: Pos, tail: Pos): Boolean {
return head.y - tail.y == 0
}
private fun newTailPos(head: Pos, tail: Pos): Pos {
if (isTouching(head, tail)) {
return tail
}
if (hasSameXLevel(head, tail)) {
return when (head.y - tail.y) {
2 -> tail.copy(y = tail.y + 1)
-2 -> tail.copy(y = tail.y - 1)
else -> error("more than two difference y-wise! $head, $tail")
}
}
if (hasSameYLevel(head, tail)) {
return when (head.x - tail.x) {
2 -> tail.copy(x = tail.x + 1)
-2 -> tail.copy(x = tail.x - 1)
else -> error("more than two difference x-wise! $head, $tail")
}
}
val diffPos = Pos(head.x - tail.x, head.y - tail.y)
return when {
diffPos.x > 0 && diffPos.y > 0 -> tail + (1 to 1)
diffPos.x < 0 && diffPos.y > 0 -> tail + (-1 to 1)
diffPos.x > 0 && diffPos.y < 0 -> tail + (1 to -1)
diffPos.x < 0 && diffPos.y < 0 -> tail + (-1 to -1)
else -> error("weird difference $diffPos - $head, $tail")
}
}
private fun newHeadPos(head: Pos, dir: String): Pos {
return when (dir) {
"U" -> head + (0 to 1)
"D" -> head + (0 to -1)
"L" -> head + (-1 to 0)
"R" -> head + (1 to 0)
else -> error("Unknown direction $dir")
}
}
private fun parseInstruction(instruction: String): Day09Command {
val (dir, times) = instruction.split(' ', limit = 2)
return Day09Command(dir, times.toInt(radix = 10))
}
private class Snake {
var head: Pos = Pos(0, 0)
var tail: Pos = Pos(0, 0)
private val visitedPositions: MutableSet<Pos> = mutableSetOf(tail)
fun consume(instruction: Day09Command) {
repeat(instruction.times) {
head = newHeadPos(head, instruction.direction)
tail = newTailPos(head, tail)
visitedPositions += tail
}
}
fun consume(instructions: List<Day09Command>) {
instructions.forEach {
consume(it)
}
}
fun visited(): Int {
return visitedPositions.size
}
}
private class SnakeWithList(size: Int) {
private var knots: List<Pos> = List(size) { Pos(0, 0) }
private val visitedPositions: MutableSet<Pos> = mutableSetOf(knots.last())
fun consume(instruction: Day09Command) {
repeat(instruction.times) {
val head = knots.first()
val rest = knots.drop(1)
val newHead = newHeadPos(head, instruction.direction)
var left = newHead
val newRest = rest.map { pos ->
newTailPos(left, pos).also { newTail -> left = newTail }
}
knots = listOf(newHead, *newRest.toTypedArray())
visitedPositions += knots.last()
}
}
fun consume(instructions: List<Day09Command>) {
instructions.forEach {
consume(it)
}
}
fun visited(): Int {
return visitedPositions.size
}
}
fun main() {
val (year, day) = 2022 to "Day09"
fun part1(input: List<String>): Int {
return Snake().also { it.consume(input.map(::parseInstruction)) }.visited()
}
fun part1Alt(input: List<String>): Int {
return SnakeWithList(2).also { it.consume(input.map(::parseInstruction)) }.visited()
}
fun part2(input: List<String>): Int {
return SnakeWithList(10).also { it.consume(input.map(::parseInstruction)) }.visited()
}
val testInput = readInput(year, "${day}_test")
val input = readInput(year, day)
// test if implementation meets criteria from the description, like:
check(part1(testInput) == 13)
println(part1(input))
check(part1Alt(testInput) == 13)
println("====")
check(part2(testInput) == 1)
println("checking alternative test input")
check(part2(readInput(year, "${day}_test_part2")) == 36)
println("Done with test input")
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 4ec3831b3d4f576e905076ff80aca035307ed522 | 4,570 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/g1401_1500/s1449_form_largest_integer_with_digits_that_add_up_to_target/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1401_1500.s1449_form_largest_integer_with_digits_that_add_up_to_target
// #Hard #Array #Dynamic_Programming #2023_06_07_Time_201_ms_(100.00%)_Space_38.8_MB_(100.00%)
@Suppress("NAME_SHADOWING")
class Solution {
fun largestNumber(cost: IntArray, target: Int): String {
var target = target
val dp = Array(10) { IntArray(5001) }
dp[0].fill(-1)
for (i in 1..cost.size) {
for (j in 1..target) {
if (cost[i - 1] > j) {
dp[i][j] = dp[i - 1][j]
} else {
var temp = if (dp[i - 1][j - cost[i - 1]] == -1) -1 else 1 + dp[i - 1][j - cost[i - 1]]
val t = if (dp[i][j - cost[i - 1]] == -1) -1 else 1 + dp[i][j - cost[i - 1]]
temp = if (t != -1 && temp == -1) {
t
} else {
Math.max(t, temp)
}
if (dp[i - 1][j] == -1) {
dp[i][j] = temp
} else if (temp == -1) {
dp[i][j] = dp[i - 1][j]
} else {
dp[i][j] = Math.max(temp, dp[i - 1][j])
}
}
}
}
if (dp[9][target] == -1) {
return "0"
}
var i = 9
val result = StringBuilder()
while (target > 0) {
if (target - cost[i - 1] >= 0 && dp[i][target - cost[i - 1]] + 1 == dp[i][target] ||
(
target - cost[i - 1] >= 0 &&
dp[i - 1][target - cost[i - 1]] + 1 == dp[i][target]
)
) {
result.append(i)
target -= cost[i - 1]
} else {
i--
}
}
return result.toString()
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,881 | LeetCode-in-Kotlin | MIT License |
src/Day01.kt | vjgarciag96 | 572,719,091 | false | {"Kotlin": 44399} | import java.util.*
fun main() {
fun part1(input: List<String>): Int {
var maxCalories = -1
var currentCalories = 0
input.forEach { line ->
if (line.isEmpty()) {
if (currentCalories > maxCalories) {
maxCalories = currentCalories
}
currentCalories = 0
} else {
currentCalories += line.toInt()
}
}
if (currentCalories > maxCalories) {
maxCalories = currentCalories
}
return maxCalories
}
fun part2(input: List<String>): Int {
val maxHeap = PriorityQueue<Int>(Collections.reverseOrder())
var currentCalories = 0
input.forEach { line ->
if (line.isEmpty()) {
if (currentCalories > 0) {
maxHeap.add(currentCalories)
}
currentCalories = 0
} else {
currentCalories += line.toInt()
}
}
if (currentCalories > 0) {
maxHeap.add(currentCalories)
}
return (1..3).sumOf { maxHeap.poll() ?: 0 }
}
val testInput = readInput("Day01_test")
check(part1(testInput) == 24_000)
check(part2(testInput) == 45_000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ee53877877b21166b8f7dc63c15cc929c8c20430 | 1,390 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/jacobhyphenated/advent2022/day24/Day24.kt | jacobhyphenated | 573,603,184 | false | {"Kotlin": 144303} | package com.jacobhyphenated.advent2022.day24
import com.jacobhyphenated.advent2022.Day
import java.util.PriorityQueue
import kotlin.math.absoluteValue
/**
* Day 24: <NAME>
*
* The puzzle input represents an area with open spaces and blizzards.
* Each blizzard moves in a defined direction. When the blizzard reaches
* the edge of the map, a new one starts on the opposite edge (same direction).
* Multiple blizzards can occupy the same space.
* Blizzards move one space per minute.
*
* Solutions are somewhat slow
* Part 1 ~ 8 seconds
* Part 2 ~ 26 seconds
*
* This is an improvement on my original DFS approach that took about 1 minute for part 1
*/
class Day24: Day<List<Blizzard>> {
override fun getInput(): List<Blizzard> {
return parseInput(readInputFile("day24"))
}
/**
* Starting in the top left corner, get to the bottom left corner.
* Find the fastest possible time to do this while never occupying the
* same location as a blizzard.
*/
override fun part1(input: List<Blizzard>): Int {
val maxCol = input.maxOf { it.currentLocation.second }
val maxRow = input.maxOf { it.currentLocation.first }
return bfs(input, Pair(0,1), Pair(maxRow, maxCol), 0, maxRow, maxCol)
}
/**
* Get from the start to the end. Then go back to the start to grab snacks.
* Then go back to the end again.
*
* What is the best possible time to complete the journey in?
*/
override fun part2(input: List<Blizzard>): Int {
val blizzards = input.map { it.copy() }
val maxCol = blizzards.maxOf { it.currentLocation.second }
val maxRow = blizzards.maxOf { it.currentLocation.first }
val timeAtEnd = bfs(input, Pair(0,1), Pair(maxRow, maxCol), 0, maxRow, maxCol)
val timeToReturn = bfs(blizzards, Pair(maxRow+1, maxCol), Pair(1,1), timeAtEnd, maxRow, maxCol)
return bfs(blizzards, Pair(0,1), Pair(maxRow, maxCol), timeToReturn, maxRow, maxCol)
}
/**
* Solve using Breadth First Search.
* A previous attempt using DFS was about 7 times slower.
*
* Find all viable paths, but optimize by focusing on states closest to the end location first.
*
* @param blizzards A list of all blizzards on the map
* @param start the start location
* @param end the end location - or rather, the location adjacent to the end location,
* which is just outside the boundary rectangle
* @param startMinute the time the bfs starts from the start location
* @param maxRow the row boundary of the search rectangle: [1,maxRow]
* @param maxCol the column boundary of the search rectangle: [1, maxCol]
*/
private fun bfs(blizzards: List<Blizzard>,
start: Pair<Int, Int>,
end: Pair<Int,Int>,
startMinute: Int,
maxRow: Int,
maxCol: Int): Int {
var bestSolution = 1000
val visited = mutableSetOf<State>()
// use a priority queue ordered by the minimum distance to the end location
val queue = PriorityQueue<State> { a, b -> a.distance(end) - b.distance(end) }
queue.add(State(start, startMinute))
while(queue.isNotEmpty()) {
val state = queue.remove()
// We've already explored this state, defined by location and time
if (state in visited) {
continue
}
visited.add(state)
// If we're at the end location, update the best solution time
val (location, time) = state
if (location == end) {
if (time + 1 < bestSolution) {
bestSolution = time + 1
}
continue
}
// Imagine we can move from here to the end location without any blizzards
// If we can't possibly beat our known best time, then we can stop searching this branch
val (row, col) = location
val (endRow, endCol) = end
if ((endRow - row).absoluteValue + (endCol - col).absoluteValue + 1 + time > bestSolution) {
continue
}
// Blizzard locations can be calculated based on the initial blizzard location and elapsed time
val blizzardLocations = blizzards.map { it.locationAtTime(maxCol, maxRow, time + 1) }.toSet()
// Explore the adjacent spaces within the boundary rectangle that will not have a blizzard in the next minute
listOf(Pair(row - 1, col), Pair(row, col - 1), Pair(row, col + 1), Pair(row + 1, col))
.filter { (r,c) -> r >= 1 && r <= maxRow && c >= 1 && c <= maxCol }
.filter { it !in blizzardLocations }
.forEach { nextLocation ->
queue.add(State(nextLocation, time + 1))
}
// Also explore just staying in place and not moving this minute
if (location !in blizzardLocations) {
queue.add(State(location, time + 1))
}
}
return bestSolution
}
fun parseInput(input: String): List<Blizzard> {
return input.lines().flatMapIndexed { row, line -> line.mapIndexedNotNull { col, c ->
when(c) {
'>' -> Blizzard(Pair(row, col), Direction.RIGHT)
'<' -> Blizzard(Pair(row, col), Direction.LEFT)
'^' -> Blizzard(Pair(row, col), Direction.UP)
'v' -> Blizzard(Pair(row, col), Direction.DOWN)
else -> null
}
} }
}
}
data class Blizzard(val currentLocation: Pair<Int,Int>, private val direction: Direction) {
// We can tell where a blizzard will be at a given time using math
fun locationAtTime(maxCol: Int, maxRow: Int, time: Int): Pair<Int,Int> {
val (row,col) = currentLocation
return when(direction) {
Direction.UP -> Pair((row - 1 - time).mod(maxRow) + 1, col)
Direction.DOWN -> Pair((row - 1 + time).mod(maxRow) + 1, col)
Direction.LEFT -> Pair(row, (col - 1 - time).mod(maxCol) + 1)
Direction.RIGHT -> Pair(row, (col - 1 + time).mod(maxCol) + 1)
}
}
}
enum class Direction {
DOWN, RIGHT, LEFT, UP
}
data class State(val location: Pair<Int,Int>, val time: Int) {
fun distance(other: Pair<Int,Int>): Int {
return (other.first - location.first).absoluteValue + (other.second - location.second).absoluteValue
}
} | 0 | Kotlin | 0 | 0 | 9f4527ee2655fedf159d91c3d7ff1fac7e9830f7 | 6,539 | advent2022 | The Unlicense |
src/main/kotlin/com/colinodell/advent2023/Day18.kt | colinodell | 726,073,391 | false | {"Kotlin": 114923} | package com.colinodell.advent2023
class Day18(input: List<String>) {
private val regex = Regex("""([UDLR]) (\d+) \(#(\w+)\)""")
private val originalDigPlan = input.map {
val (dir, dist) = regex.matchEntire(it)!!.destructured
getDirection(dir[0]).vector() * dist.toLong()
}
private val correctedDigPlan = input.map {
val (_, _, color) = regex.matchEntire(it)!!.destructured
getDirection(color.last()).vector() * color.dropLast(1).toLong(16)
}
private fun getBoundarySize(plan: List<Vector2L>) = plan.sumOf { it.size() }
private fun getVertices(plan: List<Vector2L>) = plan.scan(Vector2L(0, 0)) { pos, trench -> pos + trench }
// Calculated via the shoelace formula
private fun innerArea(vertices: List<Vector2L>) = vertices.zipWithNext().sumOf { (a, b) -> a.x * b.y - b.x * a.y } / 2
// Calculated via Pick's theorem
private fun solve(plan: List<Vector2L>) = innerArea(getVertices(plan)) + getBoundarySize(plan) / 2 + 1
fun solvePart1() = solve(originalDigPlan)
fun solvePart2() = solve(correctedDigPlan)
private fun getDirection(d: Char) = when (d) {
'U', '3' -> Direction.NORTH
'D', '1' -> Direction.SOUTH
'L', '2' -> Direction.WEST
'R', '0' -> Direction.EAST
else -> throw IllegalArgumentException("Invalid direction: $d")
}
}
| 0 | Kotlin | 0 | 0 | 97e36330a24b30ef750b16f3887d30c92f3a0e83 | 1,371 | advent-2023 | MIT License |
src/main/kotlin/kt/kotlinalgs/app/dynprog/Coins.ws.kts | sjaindl | 384,471,324 | false | null | package kt.kotlinalgs.app.dynprog
Solution().test()
/*
11:
10,1
5,5,1
5,1,1,1,1,1,1
1,1,1,1,1,1,1,1,1,1,1
10: 1 or 0
5: 0,1 or 2
1: 0,1,2,3,4,5,6
ways(1x10) + ways(0x10)
ways(1x10) = ways(1x1) = 1
ways(1x1) = 1
ways(0x10) = ways(2x5) + ways(1x5) + ways(0x5)
ways(2x5) = ways(1x1)
ways(1x5) = ways(6x5)
ways(0x5) = ways(11x1)
*/
class Solution {
fun test() {
println(Coins().waysToCollectCoins(0))
println(Coins().waysToCollectCoins(1))
println(Coins().waysToCollectCoins(11))
println(Coins().waysToCollectCoins(15))
// 10+5, 10+1+1+1+1+1, 5+5+5, 5+5+1+1+1+1+1, 5+1+1+.., 1+1+1+..
println(Coins().waysToCollectCoins(25))
}
}
/*
11, [25, 10, 5, 1]
= 4 ways:
0*25 + 1*10 + 1*1
0*25 + 0*10 + 2*5 + 1*1
0*25 + 0*10 + 1*5 + 6*1
0*25 + 0*10 + 0*5 + 11*1
memo: O(C*D)
dp:
D = 10, 5, 1
C = 10
dp
0 1 5 10 D
0 0 1 1 1
1 0 1
2 0 1
3 0 1
4 0 1
5 0 1
6 0 1
7 0 1
8 0 1
9 0 1
10 0 1
C
*/
class Coins {
fun waysToCollectCoins(cents: Int, denominators: List<Int> = listOf(25, 10, 5, 1)): Int {
val included: MutableList<MutableMap<Int, Int>> = mutableListOf()
included.add(mutableMapOf())
val memo = Array(denominators.size) { IntArray(cents + 1) { -1 } }
val res = waysToCollectCoinsRec(cents, 0, included, memo, denominators)
//println(included)
return res
}
private fun waysToCollectCoinsRec(
cents: Int, // 11
denomIndex: Int, // 0
included: MutableList<MutableMap<Int, Int>>,
memo: Array<IntArray>,
denominators: List<Int> = listOf(25, 10, 5, 1)
): Int {
val denom = denominators[denomIndex]
if (denomIndex == denominators.size - 1 && cents % denom == 0) {
included.add(mutableMapOf())
return 1
}
if (cents < 0 || denomIndex >= denominators.size) {
//println("invalid")
return 0
}
if (memo[denomIndex][cents] != -1) return memo[denomIndex][cents]
var ways = 0 // 0
val maxOfDenomToInclude = cents / denom + 1
for (times in 0 until maxOfDenomToInclude) { // 0 until 11 / 10 = 0
val remaining = cents - denominators[denomIndex] * times
//println("cents: $cents, $times x ${denominators[denomIndex]}, rem.: $remaining")
if (times >= 0) {
val map = included[included.lastIndex]
map[denominators[denomIndex]] = times
included[included.lastIndex] = map
}
ways += waysToCollectCoinsRec(remaining, denomIndex + 1, included, memo, denominators)
}
//println("$cents - $ways")
memo[denomIndex][cents] = ways
return ways
}
}
| 0 | Java | 0 | 0 | e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0 | 2,827 | KotlinAlgs | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/GarbageCollection.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
/**
* 2391. Minimum Amount of Time to Collect Garbage
* @see <a href="https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage">Source</a>
*/
fun interface GarbageCollection {
operator fun invoke(garbage: Array<String>, travel: IntArray): Int
}
sealed interface GarbageCollectionStrategy {
data object HashMap : GarbageCollection, GarbageCollectionStrategy {
override fun invoke(garbage: Array<String>, travel: IntArray): Int {
// Array to store the prefix sum in travel.
val prefixSum = IntArray(travel.size + 1)
prefixSum[1] = travel[0]
for (i in 1 until travel.size) {
prefixSum[i + 1] = prefixSum[i] + travel[i]
}
// Map to store garbage type to the last house index.
val garbageLastPos: MutableMap<Char, Int> = HashMap()
// Map to store the total count of each type of garbage in all houses.
val garbageCount: MutableMap<Char, Int> = HashMap()
for (i in garbage.indices) {
for (c in garbage[i].toCharArray()) {
garbageLastPos[c] = i
garbageCount[c] = garbageCount.getOrDefault(c, 0) + 1
}
}
val garbageTypes = "MPG"
var ans = 0
for (c in garbageTypes.toCharArray()) {
// Add only if there is at least one unit of this garbage.
if (garbageCount.containsKey(c)) {
ans += prefixSum[garbageLastPos.getOrDefault(c, 0)] + garbageCount.getOrDefault(c, 0)
}
}
return ans
}
}
data object HashMapInPlace : GarbageCollection, GarbageCollectionStrategy {
override fun invoke(garbage: Array<String>, travel: IntArray): Int {
// Store the prefix sum in travel itself.
for (i in 1 until travel.size) {
travel[i] = travel[i - 1] + travel[i]
}
// Map to store garbage type to the last house index.
val garbageLastPos: MutableMap<Char, Int> = HashMap()
var ans = 0
for (i in garbage.indices) {
for (c in garbage[i].toCharArray()) {
garbageLastPos[c] = i
}
ans += garbage[i].length
}
val garbageTypes = "MPG"
for (c in garbageTypes.toCharArray()) {
// No travel time is required if the last house is at index 0.
ans += if (garbageLastPos.getOrDefault(c, 0) == 0) {
0
} else {
travel[garbageLastPos.getOrDefault(c, 0) - 1]
}
}
return ans
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,430 | kotlab | Apache License 2.0 |
src/main/kotlin/day2.kt | Gitvert | 725,292,325 | false | {"Kotlin": 97000} | const val RED_MAX = 12
const val GREEN_MAX = 13
const val BLUE_MAX = 14
fun day2 (lines: List<String>) {
var sum = 0
var powerSum = 0
lines.forEach {
sum += getIdToSum(it)
powerSum += getPowerOfSetToSum(it)
}
println("Day 2 part 1: $sum")
println("Day 2 part 2: $powerSum")
println()
}
fun getIdToSum(line: String): Int {
val game = line.split(":")[1]
val rounds = game.split(";")
var possible = true
rounds.forEach { round ->
val cubes = round.split(",")
cubes.forEach { cube ->
val number = Integer.parseInt(cube.filter { it.isDigit() })
if (cube.contains("blue") && number > BLUE_MAX) {
possible = false
} else if (cube.contains("green") && number > GREEN_MAX) {
possible = false
} else if (cube.contains("red") && number > RED_MAX) {
possible = false
}
}
}
if (possible) {
return Integer.parseInt(line.split(":")[0].filter { it.isDigit() })
}
return 0
}
fun getPowerOfSetToSum(line: String): Int {
val game = line.split(":")[1]
val rounds = game.split(";")
var minRed = Integer.MIN_VALUE
var minGreen = Integer.MIN_VALUE
var minBlue = Integer.MIN_VALUE
rounds.forEach { round ->
val cubes = round.split(",")
cubes.forEach { cube ->
val number = Integer.parseInt(cube.filter { it.isDigit() })
if (cube.contains("blue") && number > minBlue) {
minBlue = number
} else if (cube.contains("green") && number > minGreen) {
minGreen = number
} else if (cube.contains("red") && number > minRed) {
minRed = number
}
}
}
return minRed * minGreen * minBlue
} | 0 | Kotlin | 0 | 0 | f204f09c94528f5cd83ce0149a254c4b0ca3bc91 | 1,899 | advent_of_code_2023 | MIT License |
src/Day07.kt | realpacific | 573,561,400 | false | {"Kotlin": 59236} | fun main() {
open class Directory(open val name: String) {
val children = mutableListOf<Directory>()
var parentDir: Directory? = null
override fun toString(): String {
return "Directory(name=${name}, parentDir=${parentDir})"
}
}
class File(override val name: String, val size: Int) : Directory(name) {
override fun toString(): String {
return "File(name=${name}, size=${size})"
}
}
class FileTree {
// maintains parent-child relation
// used during "cd .."
var directory: Directory = Directory("/")
fun execCommand(cmd: String) {
val words = cmd.split(" ")
if (words[1] == "ls") return // ignore this, only its output is useful
if (words[1] == "cd") {
handleChangeDirectory(words[2])
} else {
// for the output of "ls" command
val isFile = words[0].toIntOrNull() != null // file output starts with size
if (isFile) {
directory.children.add(File(words[1], words[0].toInt()))
} else if (words[0] == "dir") { // is directory
directory.children.add(Directory(words[1]))
}
}
}
private fun handleChangeDirectory(dir: String) {
when (dir) {
".." -> directory = directory.parentDir!! // set parent directory as current dir
"/" -> directory // do nothing
else -> {
val newDir = directory.children.find { it.name == dir }!!
newDir.parentDir = directory // set current directory as its parent
directory = newDir // navigate inside
}
}
}
fun calcSize(rootDir: Directory): Int {
var size = 0
if (rootDir is File) {
size += rootDir.size
} else {
rootDir.children.forEach { size += calcSize(it) }
}
return size
}
fun findDirSizeLowerThan(rootDir: Directory, limit: Int): List<Int> {
fun calcSize(rootDir: Directory, collector: MutableList<Int>): Int {
var size = 0
if (rootDir is File) {
size += rootDir.size
} else {
rootDir.children.forEach {
size += calcSize(it, collector)
}
}
if (size < limit && rootDir !is File) {
collector.add(size)
}
return size
}
val collector = mutableListOf<Int>()
calcSize(rootDir, collector)
return collector
}
fun findSizesOfDirectories(rootDir: Directory): Map<String, Int> {
fun calcSize(rootDir: Directory, collector: MutableMap<String, Int>): Int {
var size = 0
if (rootDir is File) {
size += rootDir.size
} else {
rootDir.children.forEach {
size += calcSize(it, collector)
}
}
if (rootDir !is File) {
collector[rootDir.name] = size
}
return size
}
val collector = mutableMapOf<String, Int>()
calcSize(rootDir, collector)
return collector
}
}
fun part1(input: List<String>): Int {
val fileTree = FileTree()
val rootDir = fileTree.directory
input.forEach(fileTree::execCommand)
val collector = fileTree.findDirSizeLowerThan(rootDir, 100000)
return collector.sum()
}
fun part2(input: List<String>): Int {
val fileTree = FileTree()
val rootDir = fileTree.directory
input.forEach(fileTree::execCommand)
val totalSpace = 70000000
val totalSpaceRequiredForUpdate = 30000000
val sizeOfRootDir = fileTree.calcSize(rootDir)
val freeSpace = totalSpace - sizeOfRootDir
val spaceRequired = totalSpaceRequiredForUpdate - freeSpace
val dirSizes = fileTree.findSizesOfDirectories(rootDir)
return dirSizes.values.sorted().find { it >= spaceRequired }!!
}
run {
val input = readInput("Day07_test")
assert(part1(input) == 95437)
assert(part2(input) == 24933642)
}
run {
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
}
| 0 | Kotlin | 0 | 0 | f365d78d381ac3d864cc402c6eb9c0017ce76b8d | 4,660 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/de/mbdevelopment/adventofcode/year2021/solvers/day19/Day19Puzzle1.kt | Any1s | 433,954,562 | false | {"Kotlin": 96683} | package de.mbdevelopment.adventofcode.year2021.solvers.day19
import de.mbdevelopment.adventofcode.year2021.solvers.PuzzleSolver
class Day19Puzzle1 : PuzzleSolver {
override fun solve(inputLines: Sequence<String>) = numberOfBeacons(inputLines).toString()
private fun numberOfBeacons(scannerData: Sequence<String>): Int {
val scanners = parseScanners(scannerData)
val flippedScanners = scanners.map { flipAllAxis(it) }
val flippedAndRotatedScanners = flippedScanners.map { scanner ->
scanner +
scanner.map { rotateAroundX(it, 1) }.toSet() +
scanner.map { rotateAroundX(it, 2) }.toSet() +
scanner.map { rotateAroundX(it, 3) }.toSet() +
scanner.map { rotateAroundY(it, 1) }.toSet() +
scanner.map { rotateAroundY(it, 2) }.toSet() +
scanner.map { rotateAroundY(it, 3) }.toSet() +
scanner.map { rotateAroundZ(it, 1) }.toSet() +
scanner.map { rotateAroundZ(it, 2) }.toSet() +
scanner.map { rotateAroundZ(it, 3) }.toSet()
}
// TODO Some other day. I don't have time for this
return 0
}
private fun parseScanners(scannerData: Sequence<String>): List<Set<Point>> {
val scanners = mutableListOf<Set<Point>>()
var currentScanner = mutableSetOf<Point>()
scannerData
.drop(1)
.filter { it.isNotBlank() }
.forEach { dataLine ->
if (dataLine.startsWith("--- scanner")) {
scanners += currentScanner
currentScanner = mutableSetOf()
} else {
val coordinates = dataLine.split(',').map { it.toInt() }
currentScanner += Point(coordinates[0], coordinates[1], coordinates[2])
}
}.also { scanners += currentScanner }
return scanners
}
private fun flipAllAxis(points: Set<Point>) =
setOf(points, flipX(points))
.flatMap { setOf(it, flipY(it)) }
.flatMap { setOf(it, flipZ(it)) }
.toSet()
private fun flipX(points: Set<Point>) = points.map { it * Point(-1, 1, 1) }.toSet()
private fun flipY(points: Set<Point>) = points.map { it * Point(1, -1, 1) }.toSet()
private fun flipZ(points: Set<Point>) = points.map { it * Point(1, 1, -1) }.toSet()
private fun rotateAroundX(points: Set<Point>, times90Degrees: Int) = points.map {
// x = x
// y = y * cos(angle) - z * sin(angle)
// z = y * sin(angle) + z * cos(angle)
// Hardcoded, no time for math
when (times90Degrees) {
1 -> Point(it.x, it.z, it.y)
2 -> Point(it.x, -1 * it.y, -1 * it.z)
3 -> Point(it.x, -1 * it.z, -1 * it.y)
else -> throw IllegalArgumentException("times90Degrees must be in {1, 2, 3}")
}
}.toSet()
private fun rotateAroundY(points: Set<Point>, times90Degrees: Int) = points.map {
// x = z * sin(angle) + x * cos(angle)
// y = y
// z = y * cos(angle) - x * sin(angle)
// Hardcoded, no time for math
when (times90Degrees) {
1 -> Point(it.z, it.y, -1 * it.x)
2 -> Point(-1 * it.x, it.y, -1 * it.y)
3 -> Point(-1 * it.z, it.y, it.x)
else -> throw IllegalArgumentException("times90Degrees must be in {1, 2, 3}")
}
}.toSet()
private fun rotateAroundZ(points: Set<Point>, times90Degrees: Int) = points.map {
// x = x * cos(angle) - y * sin(angle)
// y = x * sin(angle) + y * cos(angle)
// z = z
// Hardcoded, no time for math
when (times90Degrees) {
1 -> Point(-1 * it.y, it.x, it.z)
2 -> Point(-1 * it.x, -1 * it.y, it.z)
3 -> Point(it.y, -1 * it.x, it.z)
else -> throw IllegalArgumentException("times90Degrees must be in {1, 2, 3}")
}
}.toSet()
}
data class Point(val x: Int, val y: Int, val z: Int) {
operator fun times(other: Point) = Point(x * other.x, y * other.y, z * other.z)
operator fun plus(other: Point) = Point(x + other.x, y + other.y, z + other.z)
}
| 0 | Kotlin | 0 | 0 | 21d3a0e69d39a643ca1fe22771099144e580f30e | 4,261 | AdventOfCode2021 | Apache License 2.0 |
src/main/kotlin/days/Solution20.kt | Verulean | 725,878,707 | false | {"Kotlin": 62395} | package days
import adventOfCode.InputHandler
import adventOfCode.Solution
typealias FlipFlopState = MutableMap<String, Boolean>
typealias ConjunctionState = MutableMap<String, MutableMap<String, Boolean>>
typealias ModuleGraph = Map<String, Set<String>>
object Solution20 : Solution<Triple<ModuleGraph, FlipFlopState, ConjunctionState>>(AOC_YEAR, 20) {
override fun getInput(handler: InputHandler): Triple<ModuleGraph, FlipFlopState, ConjunctionState> {
val graph = mutableMapOf<String, Set<String>>()
val flipFlops = mutableMapOf<String, Boolean>()
val conjunctions = mutableMapOf<String, MutableMap<String, Boolean>>()
handler.getInput("\n")
.map { it.split(" -> ") }
.map { it.first() to it.last().split(", ").toSet() }
.forEach { (source, dests) ->
val sourceName = when (source[0]) {
'%' -> {
flipFlops[source.drop(1)] = false
source.drop(1)
}
'&' -> {
conjunctions[source.drop(1)] = mutableMapOf()
source.drop(1)
}
else -> source
}
graph[sourceName] = dests
}
graph.entries.forEach { (source, dests) ->
dests.forEach { conjunctions[it]?.set(source, false) }
}
return Triple(graph, flipFlops, conjunctions)
}
private fun ModuleGraph.invert(): ModuleGraph {
val inverseGraph = mutableMapOf<String, MutableSet<String>>()
this.entries.forEach { (source, dests) ->
dests.forEach { dest ->
if (dest in inverseGraph) inverseGraph.getValue(dest).add(source)
else inverseGraph[dest] = mutableSetOf(source)
}
}
return inverseGraph
}
override fun solve(input: Triple<ModuleGraph, FlipFlopState, ConjunctionState>): Pair<Int, Long> {
val (graph, flipFlops, conjunctions) = input
// Part 1
val pulses = mutableMapOf(false to 0, true to 0)
val queue = ArrayDeque<Triple<String, String, Boolean>>()
repeat(1000) {
queue.add(Triple("button", "broadcaster", false))
while (queue.isNotEmpty()) {
val (sender, receiver, state) = queue.removeFirst()
pulses.merge(state, 1, Int::plus)
var newState = state
if (receiver in flipFlops) {
if (state) continue
newState = !flipFlops.getValue(receiver)
flipFlops[receiver] = newState
} else conjunctions[receiver]?.let { states ->
states[sender] = state
newState = !states.values.all { it }
}
graph[receiver]?.forEach { queue.add(Triple(receiver, it, newState)) }
}
}
// Part 2
val inverseGraph = graph.invert()
val binaryEncoders = inverseGraph.getValue(inverseGraph.getValue("rx").first())
.flatMap(inverseGraph::getValue)
.toSet()
val ans2 = graph.getValue("broadcaster").map { counterStart ->
var curr = counterStart
val bits = mutableListOf<Boolean>()
while (curr !in binaryEncoders) {
val receivers = graph.getValue(curr)
val conj = receivers.intersect(binaryEncoders)
val flip = receivers - binaryEncoders
bits.add(conj.isNotEmpty())
curr = flip.firstOrNull() ?: conj.first()
}
bits.reversed().fold(0L) { acc, b -> acc.shl(1) + if (b) 1 else 0 }
}.reduce(Long::times)
return pulses.values.reduce(Int::times) to ans2
}
}
| 0 | Kotlin | 0 | 1 | 99d95ec6810f5a8574afd4df64eee8d6bfe7c78b | 3,843 | Advent-of-Code-2023 | MIT License |
src/main/kotlin/g2501_2600/s2561_rearranging_fruits/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2501_2600.s2561_rearranging_fruits
// #Hard #Array #Hash_Table #Greedy #2023_07_07_Time_746_ms_(100.00%)_Space_60.5_MB_(100.00%)
class Solution {
fun minCost(basket1: IntArray, basket2: IntArray): Long {
val n = basket1.size
val map1: MutableMap<Int, Int> = HashMap()
val map2: MutableMap<Int, Int> = HashMap()
var minVal = Int.MAX_VALUE // Use on indirect swap
// Counting the basket's number to each HashMap
for (i in 0 until n) {
map1[basket1[i]] = map1.getOrDefault(basket1[i], 0) + 1
map2[basket2[i]] = map2.getOrDefault(basket2[i], 0) + 1
minVal = minVal.coerceAtMost(basket1[i])
minVal = minVal.coerceAtMost(basket2[i])
}
// build swap list, if any number is too more, add numbers to prepare swap list
val swapList1: MutableList<Int> = ArrayList()
for (key in map1.keys) {
val c1 = map1[key]!!
val c2 = map2.getOrDefault(key, 0)
if ((c1 + c2) % 2 == 1) return -1
if (c1 > c2) {
var addCnt = (c1 - c2) / 2
while (addCnt-- > 0) {
swapList1.add(key)
}
}
}
val swapList2: MutableList<Int> = ArrayList()
for (key in map2.keys) {
val c1 = map1.getOrDefault(key, 0)
val c2 = map2[key]!!
if ((c1 + c2) % 2 == 1) return -1
if (c2 > c1) {
var addCnt = (c2 - c1) / 2
while (addCnt-- > 0) {
swapList2.add(key)
}
}
}
// Sorting
swapList1.sort()
swapList2.sortWith { a: Int, b: Int -> b - a }
// visite swap list
var res: Long = 0
for (i in swapList1.indices) {
// Two choices to swap, direct swap or indirect swap
res += (2 * minVal).coerceAtMost(swapList1[i].coerceAtMost(swapList2[i])).toLong()
}
return res
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,035 | LeetCode-in-Kotlin | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.