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/com/jacobhyphenated/advent2023/day19/Day19.kt | jacobhyphenated | 725,928,124 | false | {"Kotlin": 121644} | package com.jacobhyphenated.advent2023.day19
import com.jacobhyphenated.advent2023.Day
import com.jacobhyphenated.advent2023.product
/**
* Day 19: Aplenty
*
* There is an elaborate system for telling if a part is approved or rejected.
* Each part has 4 categories (x, m, a, s)
* Each workflow has a series of steps that test one of the category values
* and either approve, reject, or send it to another workflow step
*/
class Day19:Day<Pair<List<Part>, Map<String, Workflow>>> {
override fun getInput(): Pair<List<Part>, Map<String, Workflow>> {
return parseInput(readInputFile("19"))
}
/**
* Part 1: Find all the approved parts
* and add each category value together
*/
override fun part1(input: Pair<List<Part>, Map<String, Workflow>>): Int {
val (parts, workflow) = input
// start at the workflow named "in"
val start = workflow.getValue("in")
val acceptList = mutableListOf<Part>()
for (part in parts) {
var currentWorkflow = start
while(true) {
val nextWorkflow = currentWorkflow.execute(part)
if (nextWorkflow == "R") {
break
} else if (nextWorkflow == "A") {
acceptList.add(part)
break
}
else {
currentWorkflow = workflow.getValue(nextWorkflow)
}
}
}
return acceptList.sumOf { it.categories.values.sum() }
}
/**
* Part 2: Ingore the parts
* Each category can have a possible value between 1 and 4000 inclusive.
* How many possible parts exist that could be approved?
*/
override fun part2(input: Pair<List<Part>, Map<String, Workflow>>): Long {
val (_, workflowMap) = input
// Track a range of possible values for each of x, m, a, s
val componentRanges = listOf("x", "m", "a", "s").associateWith { Pair(1L, 4000L) }
val start = workflowMap.getValue("in")
return possibleCombinations(componentRanges, start, workflowMap)
}
/**
* Recursive function that goes through each workflow and narrows down the range of possible approved part values.
* The upper bound of possible combos is 4000 * 4000 * 4000 * 4000
* With each step, we can lower the possible combos for one of x, m, a, s category values.
* For the subsequent steps, use the remaining range of that same category
* such that each componentRange iteration has no overlap of potential category combinations
*/
private fun possibleCombinations(componentRanges: Map<String, Pair<Long,Long>>,
workflow: Workflow,
workflowMap: Map<String, Workflow> ): Long {
// start by copying the map, so we can mutate it safely
val newRanges = componentRanges.toList().toMap().toMutableMap()
var sum = 0L
for (step in workflow.steps) {
// This is the last step in the workflow. The category ranges will not change at this point
if (step.operation == '=') {
if (step.destination == "A") {
sum += newRanges.values.map { (s, e) -> e - s + 1 }.product()
}
else if (step.destination != "R") {
val destination = workflowMap.getValue(step.destination)
sum += possibleCombinations(newRanges, destination, workflowMap)
}
continue
}
// Keep track of the start and end of the range, but also the inverse values
// adjust based on whether the operation is < or >
var (start, end) = newRanges.getValue(step.category)
var elseStart = start
var elseEnd = end
if (step.operation == '<') {
end = step.value.toLong() - 1
elseStart = step.value.toLong()
}else if (step.operation == '>') {
start = step.value.toLong() + 1
elseEnd = step.value.toLong()
}
// Make a new copy of the component range map to send through the recursive function
// update this copy with the ranged that passed the operation test
val sendRanges = newRanges.toList().toMap().toMutableMap()
sendRanges[step.category] = Pair(start, end)
// At 'A', this range combination is approved. Count the possible combinations
if (step.destination == "A") {
// don't forget to add 1 (4000 - 1 + 1 = 4000 combinations)
sum += sendRanges.values.map { (s, e) -> e - s + 1 }.product()
}
else if (step.destination != "R") {
// recurse to find the possible combinations from the next workflow
val destination = workflowMap.getValue(step.destination)
sum += possibleCombinations(sendRanges, destination, workflowMap)
}
// update the ranges for this workflow to be those not sent to the above workflow
newRanges[step.category] = Pair(elseStart, elseEnd)
}
return sum
}
fun parseInput(input: String): Pair<List<Part>, Map<String, Workflow>> {
val (workflowPart, partsPart) = input.split("\n\n")
val parts = partsPart.lines().map { line ->
val map = line.removePrefix("{").removeSuffix("}").split(",").associate {
val (component, value) = it.split("=")
component to value.toInt()
}
Part(map)
}
val workflowMap = mutableMapOf<String, Workflow>()
workflowPart.lines().forEach { line ->
val(workflowName, stepsString) = line.removeSuffix("}").split("{")
val steps = stepsString.split(",").map {
if (it.contains(":")) {
val category = it.substring(0, 1)
val operation = it.toCharArray()[1]
val (value, destination) = it.substring(2).split(":")
WorkflowStep(category, operation, value.toInt(), destination)
} else {
// default step, always navigates to destination
WorkflowStep(it, '=', 0, it)
}
}
workflowMap[workflowName] = Workflow(workflowName, steps)
}
return Pair(parts, workflowMap)
}
}
data class Part(val categories: Map<String, Int>)
data class WorkflowStep(val category: String, val operation: Char, val value: Int, val destination: String) {
fun execute(part: Part): String? {
val match = when(operation) {
'<' -> part.categories.getValue(category) < value
'>' -> part.categories.getValue(category) > value
'=' -> true
else -> throw IllegalStateException("Invalid operation $operation")
}
return if (match) { destination } else { null }
}
}
data class Workflow(val name: String, val steps: List<WorkflowStep>) {
fun execute(part: Part): String {
for (step in steps) {
val destination = step.execute(part)
if (destination != null) {
return destination
}
}
throw IllegalStateException("No valid destination in workflow step $name for part $part")
}
}
fun main(@Suppress("UNUSED_PARAMETER") args: Array<String>) {
Day19().run()
} | 0 | Kotlin | 0 | 0 | 90d8a95bf35cae5a88e8daf2cfc062a104fe08c1 | 6,781 | advent2023 | The Unlicense |
src/twentythree/Day02.kt | Monkey-Matt | 572,710,626 | false | {"Kotlin": 73188} | package twentythree
fun main() {
val day = "02"
// test if implementation meets criteria from the description:
println("Day$day Test Answers:")
val testInput = readInputLines("Day${day}_test")
val part1 = part1(testInput)
part1.println()
check(part1 == 8)
val part2 = part2(testInput)
part2.println()
check(part2 == 2286)
println("---")
println("Solutions:")
val input = readInputLines("Day${day}_input")
part1(input).println()
part2(input).println()
}
private fun part1(input: List<String>): Int {
var sum = 0
input.forEach name@ { inputLine ->
val (titleText, gamesText) = inputLine.split(":")
val gameNumber = titleText.removePrefix("Game ").toInt()
val games = gamesText.split(";")
games.forEach { game ->
val colorDraws = game.split(", ")
colorDraws.forEach { color ->
if (isOutOfBounds(color)) {
// don't count this color
return@name
}
}
}
// inputLine.println()
// gameNumber.println()
sum += gameNumber
}
return sum
}
fun isOutOfBounds(color: String): Boolean {
val maxRed = 12
val maxGreen = 13
val maxBlue = 14
when {
color.contains("blue") -> {
val count = color.removeSuffix("blue").trim()
if (count.toInt() > maxBlue) return true
}
color.contains("green") -> {
val count = color.removeSuffix("green").trim()
if (count.toInt() > maxGreen) return true
}
color.contains("red") -> {
val count = color.removeSuffix("red").trim()
if (count.toInt() > maxRed) return true
}
}
return false
}
private fun part2(input: List<String>): Int {
var sum = 0
input.forEach name@ { inputLine ->
val (_, gamesText) = inputLine.split(":")
val hands = gamesText.split(";")
var gameMaxRed = 0
var gameMaxGreen = 0
var gameMaxBlue = 0
hands.forEach { hand ->
val colorDraws = hand.split(", ")
colorDraws.forEach { colorString ->
val color = Color.fromString(colorString)
when (color) {
is RED -> if (color.value > gameMaxRed) gameMaxRed = color.value
is GREEN -> if (color.value > gameMaxGreen) gameMaxGreen = color.value
is BLUE -> if (color.value > gameMaxBlue) gameMaxBlue = color.value
}
}
}
val power = gameMaxRed * gameMaxBlue * gameMaxGreen
sum += power
}
return sum
}
sealed class Color(value: Int) {
companion object {
fun fromString(color: String): Color {
when {
color.contains("blue") -> {
val count = color.removeSuffix("blue").trim()
return BLUE(count.toInt())
}
color.contains("green") -> {
val count = color.removeSuffix("green").trim()
return GREEN(count.toInt())
}
color.contains("red") -> {
val count = color.removeSuffix("red").trim()
return RED(count.toInt())
}
else -> throw(Exception("Whats the color"))
}
}
}
}
data class RED(val value: Int): Color(value)
data class GREEN(val value: Int): Color(value)
data class BLUE(val value: Int): Color(value)
| 1 | Kotlin | 0 | 0 | 600237b66b8cd3145f103b5fab1978e407b19e4c | 3,574 | advent-of-code-solutions | Apache License 2.0 |
src/main/kotlin/days/Day5.kt | C06A | 435,034,782 | false | {"Kotlin": 20662} | package days
class Day5 : Day(5) {
override fun partOne(): Any {
return readLines(inputList).filter {
it.isVertical() || it.isHorizontal()
}.count()
}
override fun partTwo(): Any {
return readLines(inputList).count()
}
}
fun readLines(inputList: List<String>): List<Line> {
return inputList.fold(mutableListOf()) { lines: List<Line>, str: String ->
val (x1, y1, x2, y2) = str.split(Regex("->"), 2
).map {
it.trim(
).split(","
).map {
it.toInt()
}
}.flatten()
lines + Line(x1, y1, x2, y2)
}
}
fun List<Line>.count(): Int {
return map {
it.toPoints()
}.flatten(
).groupBy {
it
}.filter {
it.value.size > 1
}.count()
}
data class Line(val x1: Int, val y1: Int, val x2: Int, val y2: Int) {
fun isHorizontal(): Boolean {
return x1 == x2
}
fun isVertical(): Boolean {
return y1 == y2
}
fun makeRange(start: Int, end: Int): Iterable<Int> {
return start.compareTo(end).let {
when {
it < 0 -> start..end
it > 0 -> start downTo end
else -> object : Iterable<Int> {
override fun iterator(): Iterator<Int> = object : Iterator<Int> {
override fun hasNext() = true
override fun next() = start
}
}
}
}
}
fun toPoints(): List<Point> {
return makeRange(x1, x2).zip(
makeRange(y1, y2)
).fold(emptyList<Point>()) { list, coords ->
list + Point(coords.first, coords.second)
}
}
}
data class Point(val x: Int, val y: Int)
| 0 | Kotlin | 0 | 0 | afbe60427eddd2b6814815bf7937a67c20515642 | 1,801 | Aoc2021 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/tr/emreone/adventofcode/days/Day11.kt | EmRe-One | 726,902,443 | false | {"Kotlin": 95869, "Python": 18319} | package tr.emreone.adventofcode.days
import tr.emreone.kotlin_utils.automation.Day
import tr.emreone.kotlin_utils.math.Coords
import tr.emreone.kotlin_utils.math.manhattanDistanceTo
class Day11 : Day(11, 2023, "Cosmic Expansion") {
class Galaxy(x: Int, y: Int) {
var coord = Coords(x, y)
fun distanceTo(other: Galaxy): Int {
return coord.manhattanDistanceTo(other.coord)
}
}
class Universe(input: List<List<Char>>) {
val GALAXY_CHAR = '#'
val map = input.mapIndexed { y, lines ->
lines.mapIndexedNotNull { x, c ->
if (c == GALAXY_CHAR) {
Galaxy(x, y)
} else {
null
}
}
}.flatten()
var width = this.map.maxOf { it.coord.first } + 1
var height = this.map.maxOf { it.coord.second } + 1
fun expand(factor: Int = 2) {
val emptyColumns = (0 until width).mapNotNull { x ->
val numberOfGalaxiesInColumn = this.map.count { it.coord.first == x }
if (numberOfGalaxiesInColumn == 0) {
x
} else {
null
}
}
val emptyRows = (0 until height).mapNotNull { y ->
val numberOfGalaxiesInRow = this.map.count { it.coord.second == y }
if (numberOfGalaxiesInRow == 0) {
y
} else {
null
}
}
this.map.forEach { g ->
val diffX = emptyColumns.count { it < g.coord.first }
val diffY = emptyRows.count { it < g.coord.second }
g.coord = Coords(g.coord.first + diffX * (factor - 1), g.coord.second + diffY * (factor - 1))
}
this.width += emptyColumns.size * (factor - 1)
this.height += emptyRows.size * (factor - 1)
}
fun print() {
(0 until height).forEach { y ->
(0 until width).forEach { x ->
this.map.firstOrNull { it.coord.first == x && it.coord.second == y }
?.also {
print('#')
}
?: print('.')
}
println()
}
}
}
override fun part1(): Int {
val universe = Universe(inputAsGrid)
universe.expand()
return universe.map.sumOf { a ->
universe.map.sumOf { b ->
a.distanceTo(b)
}
} / 2
}
override fun part2(): Long {
val universe = Universe(inputAsGrid)
universe.expand(1_000_000)
return universe.map.sumOf { a ->
universe.map.sumOf { b ->
a.distanceTo(b).toLong()
}
} / 2
}
}
| 0 | Kotlin | 0 | 0 | c75d17635baffea50b6401dc653cc24f5c594a2b | 2,899 | advent-of-code-2023 | Apache License 2.0 |
src/main/kotlin/de/jball/aoc2022/day15/Day15.kt | fibsifan | 573,189,295 | false | {"Kotlin": 43681} | package de.jball.aoc2022.day15
import de.jball.aoc2022.Day
import kotlin.math.abs
class Day15(test: Boolean = false) : Day<Long>(test, 26L, 56_000_011L) {
private val parserRegex = "Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)".toRegex()
private val sensors = input.map { parseSensor(it) }
private val beacons = input.map { parseBeacon(it) }.toSet()
private val y = if (test) 10 else 2_000_000
private val xylim = if (test) 20 else 4_000_000
private val largestDistance = sensors.maxOf { (_, _, distance) -> distance }
private val smallestX = sensors.minOf { (x, _, _) -> x }
private val largestX = sensors.maxOf { (x, _, _) -> x }
private fun parseSensor(line: String): Sensor {
val (a, b, c, d) = (1..4).map { parserRegex.find(line)!!.groups[it]!!.value.toInt() }
return Sensor(a, b, manhattanDistance(Position(a, b), Position(c, d)))
}
private fun parseBeacon(line: String): Beacon {
val (a, b) = (3..4).map { parserRegex.find(line)!!.groups[it]!!.value.toInt() }
return Beacon(a, b)
}
private fun manhattanDistance(a: Point, b: Point) = abs(a.x - b.x) + abs(a.y - b.y)
override fun part1(): Long {
val notDistressBeacon = (smallestX - largestDistance..largestX + largestDistance)
.map { x -> Position(x, y) }
.count { sensors.any { (x, y, radius) -> manhattanDistance(Position(x, y), it) <= radius } }
val beaconsOnY = beacons.count { (_, beaconY) -> y == beaconY }
return (notDistressBeacon - beaconsOnY).toLong()
}
override fun part2(): Long {
val (ascendingLines, descendingLines) = sensors.flatMap { it.lines() }.partition { line -> line.slope == 1 }
ascendingLines.forEach { ascendingLine ->
descendingLines.forEach { descendingLine ->
val cross = crossPoint(ascendingLine, descendingLine)
if (inGrid(cross) && sensors.none { manhattanDistance(cross, it) <= it.radius }) {
return cross.x.toLong() * 4_000_000L + cross.y.toLong()
}
}
}
error("No candidate found")
}
private fun inGrid(cross: Position) = cross.x in 0..xylim && cross.y in 0..xylim
private fun crossPoint(ascendingLine: Line, descendingLine: Line): Position {
// x+b == -x+d => x = (d-b) / 2
val x = (descendingLine.ySection - ascendingLine.ySection) / 2
val y = x + ascendingLine.ySection
return Position(x, y)
}
}
sealed class Point(val x: Int, val y: Int) {
operator fun component1() = x
operator fun component2() = y
override fun equals(other: Any?): Boolean {
return other is Point && x == other.x && y == other.y
}
override fun hashCode() = 31*x+y
override fun toString() = "($x,$y)"
}
class Beacon(x: Int, y: Int) : Point(x, y)
class Sensor(x: Int, y: Int, val radius: Int) : Point(x, y) {
operator fun component3() = radius
// lines just right outside the manhattan distance
private val upperAscendingLine = Line(1, y-x+radius+1)
private val lowerAscendingLine = Line(1, y-x-radius-1)
private val upperDescendingLine = Line(-1, y+x+radius+1)
private val lowerDescendingLine = Line(-1, y+x-radius-1)
fun lines() = listOf(upperAscendingLine, lowerAscendingLine, upperDescendingLine, lowerDescendingLine)
}
class Position(x: Int, y: Int): Point(x, y)
data class Line(val slope: Int, val ySection: Int)
fun main() {
Day15().run()
}
| 0 | Kotlin | 0 | 3 | a6d01b73aca9b54add4546664831baf889e064fb | 3,539 | aoc-2022 | Apache License 2.0 |
src/Day07.kt | maciekbartczak | 573,160,363 | false | {"Kotlin": 41932} | import java.lang.IllegalStateException
import java.util.function.Predicate
fun main() {
fun part1(input: List<String>): Int {
val rootDirectory = createDirectoryTree(input)
val result = findDirectoriesWithSizeAtMost(rootDirectory, 100000)
return result.sumOf { it.size }
}
fun part2(input: List<String>): Int {
val rootDirectory = createDirectoryTree(input)
val unusedSpace = 70000000 - rootDirectory.size
val requiredSpace = 30000000 - unusedSpace
val candidates = findDirectoriesWithSizeAtLeast(rootDirectory, requiredSpace)
return candidates.minOf { it.size }
}
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
private class Directory(
var parent: Directory?,
var childDirectories: MutableList<Directory>,
var name: String,
var size: Int
) {
fun findChildDirectory(path: String): Directory {
return childDirectories.find {
it.name == path
} ?: throw IllegalStateException()
}
}
private fun createDirectoryTree(input: List<String>): Directory {
var currentDirectory = Directory(null, mutableListOf(), "/", 0)
val rootDirectory = currentDirectory
input.forEachIndexed { index, it ->
if (it.isCommand()) {
val command = it.substring(2)
if (command.startsWith("cd") && index != 0) {
val path = command.substring(3)
currentDirectory = if (path == "..") {
currentDirectory.parent!!
} else {
currentDirectory.findChildDirectory(path)
}
}
} else {
val entryData = it.split(" ")
if (entryData[0] == "dir") {
currentDirectory.childDirectories.add(
Directory(currentDirectory, mutableListOf(), entryData[1], 0)
)
} else {
currentDirectory.size += entryData[0].toInt()
}
}
}
calculateDirectorySizes(rootDirectory)
prettyPrintStructure(rootDirectory, 0)
return rootDirectory
}
private fun String.isCommand(): Boolean {
return this.startsWith("$")
}
private fun prettyPrintStructure(directory: Directory, i: Int) {
repeat(i) {
print(" ")
}
print("- ${directory.name} ")
print(" size=${directory.size}\n")
directory.childDirectories.forEach {
prettyPrintStructure(it, i + 1)
}
}
private fun calculateDirectorySizes(directory: Directory) {
directory.childDirectories.forEach {
calculateDirectorySizes(it)
directory.size += it.size
}
}
private fun findDirectoriesWithSizeAtMost(directory: Directory, size: Int): List<Directory> {
return findDirectoriesWithSize(
directory,
size
) { it.size <= size }
}
private fun findDirectoriesWithSizeAtLeast(directory: Directory, size: Int): List<Directory> {
return findDirectoriesWithSize(
directory,
size
) { it.size >= size }
}
private fun findDirectoriesWithSize(directory: Directory, size: Int, predicate: Predicate<Directory>): List<Directory> {
val dirs = mutableListOf<Directory>()
if (predicate.test(directory)) {
dirs.add(directory)
}
directory.childDirectories.forEach {
dirs.addAll(findDirectoriesWithSize(it, size, predicate))
}
return dirs
} | 0 | Kotlin | 0 | 0 | 53c83d9eb49d126e91f3768140476a52ba4cd4f8 | 3,555 | advent-of-code-2022 | Apache License 2.0 |
advent-of-code2016/src/main/kotlin/day13/Advent13.kt | REDNBLACK | 128,669,137 | false | null | package day13
import day13.Pos.Pos2D
import java.util.*
/**
--- Day 13: A Maze of Twisty Little Cubicles ---
You arrive at the first floor of this new building to discover a much less welcoming environment than the shiny atrium of the last one. Instead, you are in a maze of twisty little cubicles, all alike.
Every location in this area is addressed by a pair of non-negative integers (x,y). Each such coordinate is either a wall or an open space. You can't move diagonally. The cube maze starts at 0,0 and seems to extend infinitely toward positive x and y; negative values are invalid, as they represent a location outside the building. You are in a small waiting area at 1,1.
While it seems chaotic, a nearby morale-boosting poster explains, the layout is actually quite logical. You can determine whether a given x,y coordinate will be a wall or an open space using a simple system:
Find x*x + 3*x + 2*x*y + y + y*y.
Add the office designer's favorite number (your puzzle input).
Find the binary representation of that sum; count the number of bits that are 1.
If the number of bits that are 1 is even, it's an open space.
If the number of bits that are 1 is odd, it's a wall.
For example, if the office designer's favorite number were 10, drawing walls as # and open spaces as ., the corner of the building containing 0,0 would look like this:
0123456789
0 .#.####.##
1 ..#..#...#
2 #....##...
3 ###.#.###.
4 .##..#..#.
5 ..##....#.
6 #...##.###
Now, suppose you wanted to reach 7,4. The shortest route you could take is marked as O:
0123456789
0 .#.####.##
1 .O#..#...#
2 #OOO.##...
3 ###O#.###.
4 .##OO#OO#.
5 ..##OOO.#.
6 #...##.###
Thus, reaching 7,4 would take a minimum of 11 steps (starting from your current location, 1,1).
What is the fewest number of steps required for you to reach 31,39?
--- Part Two ---
How many locations (distinct x,y coordinates, including your starting location) can you reach in at most 50 steps?
*/
fun main(args: Array<String>) {
println(findShortestPath(10, Pos(7, 4)).first == 11)
println(findShortestPath(1362, Pos(31, 39)))
//138
}
fun findShortestPath(size: Int, endPos: Pos): Pair<Int?, Int?> {
val positions = sequenceOf(Pos(1, 1, 0)).toCollection(LinkedList())
val visited = hashMapOf<Pos2D, Int>()
while (positions.isNotEmpty()) {
val curPos = positions.pop()
visited.put(curPos.to2D(), curPos.z)
positions += curPos.next(size).filter { it.to2D() !in visited || visited[it.to2D()] ?: 0 > it.z }
}
return visited[endPos.to2D()] to visited.count { it.value <= 50 }
}
data class Pos(val x: Int, val y: Int, val z: Int = 0) {
data class Pos2D(val x: Int, val y: Int)
fun to2D() = Pos2D(x, y)
fun isWall(size: Int) = Integer.toBinaryString(x * x + 3 * x + 2 * x * y + y + y * y + size)
.count { it == '1' } % 2 != 0
fun next(size: Int) = listOf(
Pos(x, y + 1, z + 1),
Pos(x, y - 1, z + 1),
Pos(x + 1, y, z + 1),
Pos(x - 1, y, z + 1)
)
.filter { !it.isWall(size) }
}
| 0 | Kotlin | 0 | 0 | e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7 | 3,119 | courses | MIT License |
src/main/kotlin/com/dvdmunckhof/aoc/event2020/Day11.kt | dvdmunckhof | 318,829,531 | false | {"Kotlin": 195848, "PowerShell": 1266} | package com.dvdmunckhof.aoc.event2020
class Day11(input: List<String>) {
private val directionOffsets = (-1..1).flatMap { a -> (-1..1).map { b -> a to b } }.minus(0 to 0)
private val inputSeatGrid = input.map { row ->
row.map {
when (it) {
'L' -> false
'#' -> true
else -> null
}
}
}
fun solvePart1(): Int {
return calculateSeats(inputSeatGrid) { seatGrid: List<List<Boolean?>>, ri: Int, ci: Int, occupied: Boolean ->
val count = directionOffsets.count { (ro, co) -> seatGrid.getOrNull(ri + ro)?.getOrNull(ci + co) ?: false }
if (occupied) {
count < 4
} else {
count == 0
}
}
}
fun solvePart2(): Int {
val rowIndices = inputSeatGrid.indices
val columnIndices = inputSeatGrid[0].indices
return calculateSeats(inputSeatGrid) { seatGrid: List<List<Boolean?>>, rowIndex: Int, columnIndex: Int, occupied: Boolean ->
val count = directionOffsets.count { (rowOffset, columnOffset) ->
var r = rowIndex + rowOffset
var c = columnIndex + columnOffset
while (r in rowIndices && c in columnIndices) {
val seatState = seatGrid[r][c]
if (seatState != null) {
return@count seatState
}
r += rowOffset
c += columnOffset
}
false
}
if (occupied) {
count < 5
} else {
count == 0
}
}
}
private tailrec fun calculateSeats(seatGrid: List<List<Boolean?>>, checkSeat: (seatGrid: List<List<Boolean?>>, ri: Int, si: Int, occupied: Boolean) -> Boolean): Int {
val newGrid = seatGrid.mapIndexed { rowIndex, row ->
row.mapIndexed { columnIndex, occupied ->
if (occupied == null) {
null
} else {
checkSeat(seatGrid, rowIndex, columnIndex, occupied)
}
}
}
return if (seatGrid == newGrid) {
seatGrid.sumOf { row -> row.count { it == true } }
} else {
calculateSeats(newGrid, checkSeat)
}
}
}
| 0 | Kotlin | 0 | 0 | 025090211886c8520faa44b33460015b96578159 | 2,394 | advent-of-code | Apache License 2.0 |
src/day07/Day07.kt | Regiva | 573,089,637 | false | {"Kotlin": 29453} | package day07
import readLines
fun main() {
val id = "07"
val testOutput = 95437
fun readTerminalOutput(fileName: String): List<String> {
return readLines(fileName)
}
fun createFileSystemTree(input: List<String>): FileSystemNode.Directory {
val rootNode = FileSystemNode.Directory(
name = "/",
parent = null,
)
var currentNode = rootNode
input.forEach { inputLine ->
val line = inputLine.split(" ")
if (line.first() == "$") {
when (line[1]) {
"ls" -> return@forEach
"cd" -> {
currentNode = when (val destinationName = line[2]) {
"/" -> rootNode
".." -> currentNode.parent!!
else -> {
val destinationNode = currentNode.children[destinationName]
destinationNode as FileSystemNode.Directory
}
}
}
}
} else {
val destinationName = line[1]
currentNode.children[destinationName] = when (line.first()) {
"dir" -> {
FileSystemNode.Directory(
name = destinationName,
parent = currentNode,
)
}
else -> {
val size = line[0].toInt()
currentNode.updateSize(size)
FileSystemNode.File(
name = destinationName,
size = size,
)
}
}
}
}
return rootNode
}
// Time — O(), Memory — O()
fun part1(input: FileSystemNode.Directory): Int {
val sizeAtMost = 100000
var deleteDirsSize = 0
input.children.forEach { node ->
deleteDirsSize += (node.value as? FileSystemNode.Directory)
?.findDirsTotalSizeBySize(sizeAtMost) ?: 0
}
return deleteDirsSize
}
// Time — O(), Memory — O()
fun part2(input: FileSystemNode.Directory): Int {
val totalSpace = 70000000
val updateSpace = 30000000
val usedSpace = input.size
val neededSpace = updateSpace - (totalSpace - usedSpace)
val dirsToDeleteSizes = mutableListOf(Int.MAX_VALUE)
input.children.forEach { node ->
(node.value as? FileSystemNode.Directory)?.let {
dirsToDeleteSizes.add(it.findDirToDeleteSize(neededSpace))
}
}
return dirsToDeleteSizes.min()
}
val testInput = createFileSystemTree(readTerminalOutput("day$id/Day${id}_test"))
println(part1(testInput))
check(part1(testInput) == testOutput)
val input = createFileSystemTree(readTerminalOutput("day$id/Day$id"))
println(part1(input))
println(part2(input))
}
fun FileSystemNode.Directory.updateSize(size: Int) {
this.size += size
parent?.apply { updateSize(size) }
}
fun FileSystemNode.Directory.findDirsTotalSizeBySize(size: Int): Int {
var deleteDirsSize = 0
if (this.size < size) deleteDirsSize = this.size
children.forEach { node ->
if (node.value is FileSystemNode.Directory) {
deleteDirsSize += (node.value as FileSystemNode.Directory).findDirsTotalSizeBySize(size)
}
}
return deleteDirsSize
}
fun FileSystemNode.Directory.findDirToDeleteSize(neededSpace: Int): Int {
val dirsToDeleteSizes = mutableListOf(Int.MAX_VALUE)
if (this.size > neededSpace) dirsToDeleteSizes.add(this.size)
children.forEach { node ->
if (node.value is FileSystemNode.Directory) {
dirsToDeleteSizes.add(
(node.value as FileSystemNode.Directory).findDirToDeleteSize(neededSpace)
)
}
}
return dirsToDeleteSizes.min()
}
| 0 | Kotlin | 0 | 0 | 2d9de95ee18916327f28a3565e68999c061ba810 | 4,104 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2015/2015-02.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2015
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputLines
fun main() {
val input = readInputLines(2015, "02-input")
val test1 = readInputLines(2015, "02-test1")
println("Part1:")
calculatePaper(test1).println()
calculatePaper(input).println()
println()
println("Part2:")
calculateRibbon(test1).println()
calculateRibbon(input).println()
}
private fun calculatePaper(input: List<String>): Int {
return input.map { line ->
val (x, y, z) = line.split('x').map { it.toInt() }
Triple(x, y, z)
}.sumOf { (x, y, z) ->
val s1 = x * y * 2
val s2 = x * z * 2
val s3 = y * z * 2
s1 + s2 + s3 + (minOf(s1, s2, s3) / 2)
}
}
private fun calculateRibbon(input: List<String>): Int {
return input.map { line ->
val (x, y, z) = line.split('x').map { it.toInt() }
Triple(x, y, z)
}.sumOf { (x, y, z) ->
val bow = x * y * z
val s1 = x + y
val s2 = x + z
val s3 = y + z
bow + minOf(s1, s2, s3) * 2
}
}
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 1,147 | advent-of-code | MIT License |
src/day03/Day03.kt | emartynov | 572,129,354 | false | {"Kotlin": 11347} | package day03
import readInput
private fun Char.toScore() = if (isLowerCase())
this - 'a' + 1
else
this - 'A' + 27
fun main() {
fun part1(input: List<String>): Int {
return input.map { rugzakContent ->
rugzakContent.chunked(size = rugzakContent.length / 2)
}.map { compartmentValues ->
compartmentValues[0].toSet()
.intersect(
compartmentValues[1]
.toSet()
).first()
}.sumOf { sameElement ->
sameElement.toScore()
}
}
fun part2(input: List<String>): Int {
return input.chunked(3)
.map { groupRugzakContent ->
groupRugzakContent
.map { it.toSet() }
.reduce { content1, content2 ->
content1.intersect(content2)
}
}.map { commonFromGroup ->
commonFromGroup.first()
}.sumOf { sameElement ->
sameElement.toScore()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day03/Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("day03/Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 8f3598cf29948fbf55feda585f613591c1ea4b42 | 1,363 | advent-of-code-2022 | Apache License 2.0 |
src/Day09.kt | davedupplaw | 573,042,501 | false | {"Kotlin": 29190} | import kotlin.math.abs
import kotlin.math.sign
fun main() {
data class Position(var x: Int, var y: Int) {
fun moveX(v: Int) {
x += v
}
fun moveY(v: Int) {
y += v
}
fun toPair() = Pair(x, y)
}
fun moveHead(command: String, headPosition: Position) {
when (command) {
"R" -> headPosition.moveX(1)
"L" -> headPosition.moveX(-1)
"U" -> headPosition.moveY(1)
"D" -> headPosition.moveY(-1)
}
}
fun moveKnotBasedOnOtherKnot(headPosition: Position, tailPosition: Position) {
val headTailDiffX = headPosition.x - tailPosition.x
val headTailDiffY = headPosition.y - tailPosition.y
if (abs(headTailDiffX) > 1 || abs(headTailDiffY) > 1) {
if (abs(headTailDiffX) > 1 || (abs(headTailDiffY) > 1 && abs(headTailDiffX) == 1)) {
tailPosition.moveX(1 * headTailDiffX.sign)
}
if (abs(headTailDiffY) > 1 || (abs(headTailDiffX) > 1 && abs(headTailDiffY) == 1)) {
tailPosition.moveY(1 * headTailDiffY.sign)
}
}
}
fun simulateRopeWithNKnots(input: List<String>, n: Int): Int {
val positionsVisited = mutableSetOf<Pair<Int, Int>>()
val knots = List(n) { Position(0, 0) }
input.forEach { line ->
val (command, amountStr) = line.split(" ")
val amount = amountStr.toInt()
repeat(amount) {
moveHead(command, knots[0])
knots.windowed(2) { (leader, follower) ->
moveKnotBasedOnOtherKnot(leader, follower)
}
positionsVisited += knots.last().toPair()
}
}
return positionsVisited.count()
}
fun part1(input: List<String>): Int {
return simulateRopeWithNKnots(input, 2)
}
fun part2(input: List<String>): Int {
return simulateRopeWithNKnots(input, 10)
}
val test = readInput("Day09.test")
val part1test = part1(test)
println("part1 test: $part1test")
check(part1test == 13)
val part2test = part2(test)
println("part2 test: $part2test")
check(part2test == 1)
val test2 = readInput("Day09-2.test")
val part22test = part2(test2)
println("part22 test: $part22test")
check(part22test == 36)
val input = readInput("Day09")
val part1 = part1(input)
println("Part1: $part1")
val part2 = part2(input)
println("Part2: $part2")
}
| 0 | Kotlin | 0 | 0 | 3b3efb1fb45bd7311565bcb284614e2604b75794 | 2,538 | advent-of-code-2022 | Apache License 2.0 |
2023/src/main/kotlin/day6.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parser
import utils.Solution
import utils.cut
import utils.mapItems
fun main() {
Day6.run(skipTest = false)
}
object Day6 : Solution<List<Day6.Race>>() {
override val name = "day6"
override val parser = Parser.lines.mapItems { input ->
input.cut(":").second.split(" ").mapNotNull { it.trim().takeIf(String::isNotBlank)?.toLong() }
}.map { (times, records) ->
require(times.size == records.size)
times.mapIndexed { i, time ->
Race(time, records[i])
}
}
data class Race(
val time: Long,
val record: Long,
) {
operator fun plus(other: Race): Race {
return Race(
time = (this.time.toString() + other.time.toString()).toLong(),
record = (this.record.toString() + other.record.toString()).toLong()
)
}
}
override fun part1(input: List<Race>): Int {
return input.map { race ->
(1 until race.time).count { speed ->
(race.time - speed) * speed > race.record
}
}.reduce { a, b -> a * b }
}
override fun part2(input: List<Race>): Int {
val race = input.reduce { a, b -> a + b }
return (1 until race.time).count { speed ->
(race.time - speed) * speed > race.record
}
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 1,214 | aoc_kotlin | MIT License |
src/main/kotlin/solutions/year2022/Day4.kt | neewrobert | 573,028,531 | false | {"Kotlin": 7605} | package solutions.year2022
import readInputLines
/**
* split te pairs
*
* compare both to see which if one pair is fully contained in the other
*
* count
*/
fun main() {
fun getSectionRange(line: String): List<IntRange> {
return line.split(",").map { pairs ->
val (a, b) = pairs.split("-").map { it.toInt() }
a..b
}
}
fun part1(input: List<String>): Int {
return input.map { getSectionRange(it) }.count { (e1, e2) ->
(e1.first in e2 && e1.last in e2) || (e2.first in e1 && e2.last in e1)
}
}
fun part2(input: List<String>): Int {
return input.map { getSectionRange(it) }.count{
(e1, e2) -> e1.first in e2 || e1.last in e2 || e2.first in e1 || e2.last in e1
}
}
val testInput = readInputLines("2022", "Day4_test")
println(part1(testInput))
check(part1(testInput) != 0)
check(part1(testInput) == 2)
println(part2(testInput))
check(part2(testInput) != 0)
check(part2(testInput) == 4)
val input = readInputLines("2022", "Day4")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 7ecf680845af9d22ef1b9038c05d72724e3914f1 | 1,144 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day09.kt | Flame239 | 570,094,570 | false | {"Kotlin": 60685} | import kotlin.math.abs
import kotlin.math.sign
private fun moves(): List<Pair<String, Int>> {
return readInput("Day09").map { it.split(" ") }.map { Pair(it[0], it[1].toInt()) }
}
private fun part1(moves: List<Pair<String, Int>>): Int = uniqueTailPositions(moves, 2)
private fun part2(moves: List<Pair<String, Int>>): Int = uniqueTailPositions(moves, 10)
private fun uniqueTailPositions(moves: List<Pair<String, Int>>, knotsCount: Int): Int {
val knots = Array(knotsCount) { Coord(0, 0) }
val uniqueTailPos = HashSet<Coord>()
uniqueTailPos.add(knots.last())
moves.forEach { m ->
repeat(m.second) {
when (m.first) {
"R" -> knots[0].x++
"L" -> knots[0].x--
"U" -> knots[0].y++
"D" -> knots[0].y--
}
for (i in 0 until knots.lastIndex) {
knots[i + 1].moveTo(knots[i])
}
uniqueTailPos.add(knots.last().copy())
}
}
return uniqueTailPos.size
}
fun main() {
println(part1(moves()))
println(part2(moves()))
}
data class Coord(var x: Int, var y: Int) {
fun moveTo(other: Coord) {
val diffX = (other.x - x)
val diffY = (other.y - y)
if (abs(diffX) <= 1 && abs(diffY) <= 1) return
y += diffY.sign
x += diffX.sign
}
} | 0 | Kotlin | 0 | 0 | 27f3133e4cd24b33767e18777187f09e1ed3c214 | 1,352 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/leonra/adventofcode/advent2023/day05/Day5.kt | LeonRa | 726,688,446 | false | {"Kotlin": 30456} | package com.leonra.adventofcode.advent2023.day05
import com.leonra.adventofcode.shared.readResource
/** https://adventofcode.com/2023/day/5 */
private object Day5 {
data class Mapping(val source: LongRange, val diff: Long)
fun partOne(): Long {
val mapped = mutableSetOf<Long>()
val ranges = mutableListOf<Mapping>()
readResource("/2023/day05/part1.txt") { line ->
if (line.isBlank()) {
return@readResource
}
val seedMatch = SEEDS.find(line)
val mappingMatch = MAPPINGS.find(line)
if (seedMatch != null) {
requireNotNull(seedMatch.groups[1])
.value
.split(" ")
.map { it.toLong() }
.forEach { mapped.add(it) }
} else if (mappingMatch != null) {
if (ranges.isNotEmpty()) {
val toMap = mapped.toSet()
mapped.clear()
toMap.forEach { input ->
val output = ranges
.firstOrNull { it.source.contains(input) }
?.let { input - it.diff }
?: input
mapped.add(output)
}
}
ranges.clear()
} else {
val values = line.split(" ").map { it.toLong() }
ranges.add(Mapping(source = values[1]until values[1] + values[2], diff = values[1] - values[0]))
}
}
val toMap = mapped.toSet()
mapped.clear()
toMap.forEach { input ->
val output = ranges
.firstOrNull { it.source.contains(input) }
?.let { input - it.diff }
?: input
mapped.add(output)
}
return mapped.min()
}
fun partTwo(): Long {
val seeds = mutableListOf<LongRange>()
var mappingIndex = 0
val mappings = mutableListOf<MutableSet<Mapping>>()
readResource("/2023/day05/part1.txt") { line ->
if (line.isBlank()) {
return@readResource
}
val seedMatch = SEEDS.find(line)
val mappingMatch = MAPPINGS.find(line)
if (seedMatch != null) {
requireNotNull(seedMatch.groups[1])
.value
.split(" ")
.map { it.toLong() }
.chunked(2)
.map { it[0] until it[0] + it[1] }
.forEach { seeds.add(it) }
} else if (mappingMatch != null) {
mappingIndex++
} else {
val values = line.split(" ").map { it.toLong() }
if (mappingIndex > mappings.size) {
mappings.add(mutableSetOf())
}
mappings[mappingIndex - 1]
.add(Mapping(source = values[1]until values[1] + values[2], diff = values[1] - values[0]))
}
}
var min = Long.MAX_VALUE
for (seedGroup in seeds) {
for (seed in seedGroup.iterator()) {
mappingIndex = 0
var input = seed
while (mappingIndex < mappings.size) {
input = mappings[mappingIndex]
.firstOrNull { it.source.contains(input) }
?.let { input - it.diff }
?: input
mappingIndex++
}
if (input < min) {
min = input
}
}
}
return min
}
private val SEEDS = Regex("seeds: (.+)")
private val MAPPINGS = Regex(".+ map:")
}
private fun main() {
println("Part 1 smallest location number: ${Day5.partOne()}")
println("Part 2 smallest location number: ${Day5.partTwo()}")
}
| 0 | Kotlin | 0 | 0 | 46bdb5d54abf834b244ba9657d0d4c81a2d92487 | 3,970 | AdventOfCode | Apache License 2.0 |
src/Day11.kt | jvmusin | 572,685,421 | false | {"Kotlin": 86453} | fun main() {
fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)
fun lcm(a: Long, b: Long): Long = a / gcd(a, b) * b
data class Monkey(
val items: MutableList<Long>,
val operation: (Long) -> Long,
val test: Long,
val ifTrue: Int,
val ifFalse: Int,
)
fun parseOperation(op: String): (Long) -> Long {
val parts = op.split(' ')
fun get(v: String): (Long) -> Long = if (v == "old") { x -> x } else { _ -> v.toLong() }
val v1 = get(parts[0])
val v2 = get(parts[2])
val operation: (Long, Long) -> Long = when (parts[1]) {
"+" -> Long::plus
"*" -> Long::times
else -> error("Unknown op: ${parts[1]}")
}
return { x -> operation(v1(x), v2(x)) }
}
fun parse(input: List<String>): MutableList<Monkey> {
var i = 0
val monkeys = mutableListOf<Monkey>()
while (i < input.size) {
val startingItems = input[++i].split(": ")[1].split(", ").map { it.toLong() }
val operation = input[++i].split("new = ")[1].let(::parseOperation)
val test = input[++i].split(' ').last().toLong()
val ifTrue = input[++i].split(' ').last().toInt()
val ifFalse = input[++i].split(' ').last().toInt()
monkeys += Monkey(startingItems.toMutableList(), operation, test, ifTrue, ifFalse)
i++
i++
}
return monkeys
}
fun part1(input: List<String>): Int {
val monkeys = parse(input)
val inspects = IntArray(monkeys.size)
repeat(20) {
for (monkeyIndex in monkeys.indices) {
val monkey = monkeys[monkeyIndex]
inspects[monkeyIndex] += monkey.items.size
repeat(monkey.items.size) {
var item = monkey.items.removeFirst()
item = monkey.operation(item)
item /= 3
monkeys[if (item % monkey.test == 0L) monkey.ifTrue else monkey.ifFalse].items.add(item)
}
}
}
println(inspects.toList())
return inspects.sortedDescending().take(2).let { (a, b) -> a * b }
}
fun part2(input: List<String>): Long {
val monkeys = parse(input)
var lcm = 1L
for (m in monkeys) {
lcm = lcm(lcm, m.test)
println(lcm)
}
val inspects = IntArray(monkeys.size)
repeat(10_000) {
for (monkeyIndex in monkeys.indices) {
val monkey = monkeys[monkeyIndex]
inspects[monkeyIndex] += monkey.items.size
repeat(monkey.items.size) {
var item = monkey.items.removeFirst()
item = monkey.operation(item) % lcm
monkeys[if (item % monkey.test == 0L) monkey.ifTrue else monkey.ifFalse].items.add(item)
}
}
}
println(inspects.toList())
return inspects.sortedDescending().take(2).let { (a, b) -> a.toLong() * b }
}
@Suppress("DuplicatedCode")
run {
val day = String.format("%02d", 11)
val testInput = readInput("Day${day}_test")
val input = readInput("Day$day")
println("Part 1 test - " + part1(testInput))
println("Part 1 real - " + part1(input))
println("---")
println("Part 2 test - " + part2(testInput))
println("Part 2 real - " + part2(input))
}
}
| 1 | Kotlin | 0 | 0 | 4dd83724103617aa0e77eb145744bc3e8c988959 | 3,534 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/kishor/kotlin/algo/problems/arrayandstrings/DetermineDNAHealth.kt | kishorsutar | 276,212,164 | false | null | package com.kishor.kotlin.algo.problems.arrayandstrings
import java.util.*
fun main(args: Array<String>) {
// val scan = Scanner(System.`in`)
//
// val n = scan.nextLine().trim().toInt()
//
// val genes = scan.nextLine().split(" ").toTypedArray()
//
// val health = scan.nextLine().split(" ").map{ it.trim().toInt() }.toTypedArray()
//
// val s = scan.nextLine().trim().toInt()
//
// val healthList = mutableListOf<Int>()
// for (sItr in 1..s) {
// val firstLastd = scan.nextLine().split(" ")
//
// val first = firstLastd[0].trim().toInt()
//
// val last = firstLastd[1].trim().toInt()
//
// val d = firstLastd[2]
//
// healthList.add(findHealthyDna(first, last, d, genes, health))
// }
//
// healthList.sort()
// println("${healthList[0]} ${healthList[healthList.size-1]}" )
val list = getInputStrCombinationList("caaab")
println(list.toString())
}
fun findHealthyDna(first: Int, last: Int, d: String, genes: Array<String>, health: Array<Int>): Int {
/**
- Get list of all the combinations of input string d
- in the array look from first to last if any of the combination is present
- once we get the index of it, get the respective value from health array
- add to the sum
- add sum to the list
*/
val inputStrCombinationList = getInputStrCombinationList(d) // List<String>
var sum = 0
for (combGene in inputStrCombinationList) {
for (i in first..last+1) {
if (genes[i] == combGene) {
sum += health[i]
println("$combGene and ${genes[i]} sum is $sum")
}
}
}
return sum
}
fun getInputStrCombinationList(d: String): List<String> {
val combList = mutableListOf<String>()
for (i in d.indices) {
for (j in i+1 until d.length) {
combList.add(d.substring(i, j+1))
}
}
println(combList.toString())
return combList
}
| 0 | Kotlin | 0 | 0 | 6672d7738b035202ece6f148fde05867f6d4d94c | 1,958 | DS_Algo_Kotlin | MIT License |
string-similarity/src/commonMain/kotlin/com/aallam/similarity/RatcliffObershelp.kt | aallam | 597,692,521 | false | null | package com.aallam.similarity
/**
* The Ratcliff/Obershelp algorithm computes the similarity of two strings the doubled number of matching characters
* divided by the total number of characters in the two strings. Matching characters are those in the longest common
* subsequence plus, recursively, matching characters in the unmatched region on either side of the longest common
* subsequence.
*/
public class RatcliffObershelp {
/**
* Compute the Ratcliff-Obershelp similarity between strings.
*
* @param first the first string to compare.
* @param second the second string to compare.
*/
public fun similarity(first: String, second: String): Double {
if (first == second) return 1.0
val matches = matchList(first, second)
val sumOfMatches = matches.sumOf { it.length }
return 2.0 * sumOfMatches / (first.length + second.length)
}
/**
* Return 1 - similarity.
*
* @param first the first string to compare.
* @param second the second string to compare.
*/
public fun distance(first: String, second: String): Double {
return 1.0 - similarity(first, second)
}
/**
* Returns a list of matching substrings between the given [first] and [second] strings.
*
* @param first The first string to compare.
* @param second The second string to compare.
*/
private fun matchList(first: String, second: String): List<String> {
val match = frontMaxMatch(first, second)
if (match.isEmpty()) return emptyList()
val frontQueue = matchList(first.substringBefore(match), second.substringBefore(match))
val endQueue = matchList(first.substringAfter(match), second.substringAfter(match))
return listOf(match) + frontQueue + endQueue
}
/**
* Returns the longest substring that occurs at the beginning of both the [first] and [second] strings.
*
* @param first the first string to compare.
* @param second the second string to compare.
*/
private fun frontMaxMatch(first: String, second: String): String {
var longestSubstring = ""
for (i in first.indices) {
for (j in i + 1..first.length) {
val substring = first.substring(i, j)
if (second.contains(substring) && substring.length > longestSubstring.length) {
longestSubstring = substring
}
}
}
return longestSubstring
}
}
| 0 | Kotlin | 0 | 1 | 40cd4eb7543b776c283147e05d12bb840202b6f7 | 2,513 | string-similarity-kotlin | MIT License |
src/Day06.kt | mkfsn | 573,042,358 | false | {"Kotlin": 29625} | import java.util.LinkedList
import java.util.Queue
fun main() {
fun getFirstStartOfPacketMarker(input: List<String>, distinctCharacters: Int): List<Int> {
return input.map outer@{ text ->
val queue: Queue<Char> = LinkedList(text.take(distinctCharacters - 1).toList())
val dict = text
.take(distinctCharacters - 1)
.groupBy { it }.map { e -> e.key to e.value.size }
.toMap()
.toMutableMap()
for ((i, ch) in text.drop(distinctCharacters - 1).withIndex()) {
queue.add(ch)
dict.merge(ch, 1, Int::plus)
if (dict.filter { (_, v) -> v > 0 }.count() == distinctCharacters) {
return@outer i + distinctCharacters
}
dict.merge(queue.remove(), 1, Int::minus)
}
0
}
}
fun part1(input: List<String>): List<Int> = getFirstStartOfPacketMarker(input, 4)
fun part2(input: List<String>): List<Int> = getFirstStartOfPacketMarker(input, 14)
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
check(part1(testInput) == listOf(7, 5, 6, 10, 11))
check(part2(testInput) == listOf(19, 23, 23, 29, 26))
val input = readInput("Day06")
println(part1(input)[0])
println(part2(input)[0])
}
| 0 | Kotlin | 0 | 1 | 8c7bdd66f8550a82030127aa36c2a6a4262592cd | 1,407 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/day14/Day14.kt | cyril265 | 433,772,262 | false | {"Kotlin": 39445, "Java": 4273} | package day14
import readToList
import java.util.UUID
private val input = readToList("day14.txt")
fun main() {
val template = input.first()
.mapIndexed { index, char -> Element(char, index.toString()) }
val rules = input.drop(2)
.map { line ->
val (pair, insertion) = line.split(" -> ")
Rule(pair.first() to pair[1], insertion[0])
}
var templateResult = template
(0 until 10).forEach { step ->
println(step)
templateResult = templateResult.mapIndexed { index, element ->
if (index == templateResult.size - 1) {
null
} else {
rules.map { rule ->
val (first, second) = rule.pair
val nextElement = templateResult[index + 1]
if (element.char == first && nextElement.char == second) {
listOf(element, Element(rule.insertion, UUID.randomUUID().toString()), nextElement)
} else {
listOf(element)
}
}
.flatten()
.distinct()
}
}.filterNotNull()
.flatten()
.distinct()
templateResult.forEachIndexed { index, el -> el.id = index.toString() }
}
println(templateResult.joinToString(separator = ""))
val message = templateResult.groupingBy { it.char }.eachCount()
println(
message.values.maxOf { it } - message.values.minOf { it }
)
}
private data class Rule(val pair: Pair<Char, Char>, val insertion: Char)
private data class Element(val char: Char, var id: String) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Element
if (id != other.id) return false
return true
}
override fun toString(): String {
return char.toString()
}
override fun hashCode(): Int {
return id.hashCode()
}
}
| 0 | Kotlin | 0 | 0 | 1ceda91b8ef57b45ce4ac61541f7bc9d2eb17f7b | 2,075 | aoc2021 | Apache License 2.0 |
src/main/kotlin/day24.kt | Gitvert | 725,292,325 | false | {"Kotlin": 97000} | const val MIN_INTERSECTION = 200000000000000.0
const val MAX_INTERSECTION = 400000000000000.0
fun day24 (lines: List<String>) {
val hailstones = parseHailstones(lines)
val intersections = mutableListOf<Intersection>()
for (i in hailstones.indices) {
for (j in i + 1..hailstones.indices.last) {
val intersection = findIntersection(hailstones[i], hailstones[j])
if (intersection != null) {
if (intersectionInThePast(hailstones[i], intersection) || intersectionInThePast(hailstones[j], intersection)) {
continue
}
intersections.add(intersection)
}
}
}
val validIntersections = intersections.filter { it.x in MIN_INTERSECTION..MAX_INTERSECTION && it.y in MIN_INTERSECTION..MAX_INTERSECTION }
println("Day 24 part 1: ${validIntersections.size}")
println("Day 24 part 2: ")
println()
}
fun intersectionInThePast(hailstone: HailStone, intersection: Intersection): Boolean {
return (intersection.x > hailstone.pos.x && hailstone.vel.x < 0) || (intersection.x < hailstone.pos.x && hailstone.vel.x > 0)
}
fun findIntersection(h1: HailStone, h2: HailStone): Intersection? {
val denominator = h1.vel.x * h2.vel.y - h2.vel.x * h1.vel.y
if (denominator == 0L) {
return null
}
val t = 1.0 * (h2.vel.y * (h2.pos.x - h1.pos.x) + h2.vel.x * (h1.pos.y - h2.pos.y)) / denominator
val intersectionX = h1.vel.x * t + h1.pos.x
val intersectionY = h1.vel.y * t + h1.pos.y
return Intersection(intersectionX, intersectionY)
}
fun parseHailstones(lines: List<String>): MutableList<HailStone> {
val hailstones = mutableListOf<HailStone>()
lines.map{ it.replace(" ", "") }.forEach { line ->
val positions = line.split("@")[0].split(",").map { it.toLong() }
val velocities = line.split("@")[1].split(",").map { it.toLong() }
hailstones.add(HailStone(BigPoint(positions[0], positions[1], positions[2]), BigPoint(velocities[0], velocities[1], velocities[2])))
}
return hailstones
}
data class HailStone(val pos: BigPoint, val vel: BigPoint)
data class BigPoint(val x: Long, val y: Long, val z: Long)
data class Intersection(val x: Double, val y: Double) | 0 | Kotlin | 0 | 0 | f204f09c94528f5cd83ce0149a254c4b0ca3bc91 | 2,311 | advent_of_code_2023 | MIT License |
src/main/kotlin/net/mguenther/adventofcode/day24/Day24.kt | mguenther | 115,937,032 | false | null | package net.mguenther.adventofcode.day24
/**
* @author <NAME> (<EMAIL>)
*/
class ElectromagneticHost {
private fun initialComponents(components: List<Component>) =
components.filter { c -> c.hasZeroPin() }
private fun candidates(components: List<Component>, tail: Component) =
components.filter { component -> tail.isCompatible(component) }
fun solve(components: List<Component>): Int {
val zeroPinComponents = initialComponents(components)
return zeroPinComponents
.flatMap { zeroPinComponent -> solve(components.minus(zeroPinComponent), listOf(zeroPinComponent.assign(0))) }
.groupBy { solution -> solution.size }
.maxBy { c -> c.key }!!
.value
.map { solution -> strengthOf(solution) }
.max() ?: 0
}
fun solve(components: List<Component>, prototype: Bridge): List<Bridge> {
val candidates = candidates(components, prototype.takeLast(1).get(0))
if (candidates.isEmpty()) {
return listOf(prototype)
}
return candidates.flatMap { candidate -> solve(components.minus(candidate), prototype + candidate.assign(connectOn(prototype, candidate))) }
}
fun connectOn(bridge: List<Component>, component: Component): Port {
val tail = bridge.takeLast(1).get(0)
if (tail.free.contains(component.left)) return component.left
else return component.right
}
private fun strengthOf(solution: Bridge): Int = solution.map { c -> c.strength() }.sum()
}
class Component(val left: Port, val right: Port, val free: List<Port> = listOf(left, right)) {
fun assign(port: Port): Component {
return Component(left, right, free.minus(port))
}
fun isCompatible(other: Component): Boolean {
return free.contains(other.left) || free.contains(other.right)
}
fun strength(): Int = left + right
fun hasZeroPin(): Boolean = left == 0 || right == 0
override fun toString(): String {
return "$left/$right"
}
}
typealias Port = Int
typealias Bridge = List<Component>
| 0 | Kotlin | 0 | 0 | c2f80c7edc81a4927b0537ca6b6a156cabb905ba | 2,174 | advent-of-code-2017 | MIT License |
kotlin/src/katas/kotlin/convolve-fft/zero-sum-triplets.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.`convolve-fft`
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertTimeoutPreemptively
import java.time.Duration
import kotlin.random.Random
//
// https://leetcode.com/problems/3sum
// https://en.wikipedia.org/wiki/3SUM
//
// Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0?
// Find all unique triplets in the array which gives the sum of zero.
// Notice that the solution set must not contain duplicate triplets.
// Constraints:
// 0 <= nums.length <= 3000
// -105 <= nums[i] <= 105
//
// Example 1:
// Input: [-1,0,1,2,-1,-4]; Output: [[-1,-1,2],[-1,0,1]]
// index: -4-3-2-1 0 1 2 3 4
// freq: 1,0,0,2,1,1,1,0,0
// index0: 0 1 2 3 4 5 6 7 8 9 10
// index: -8-7-6-5-4-3-2-1 0 1 2 3 4 5 6 7 8
// convolve: 1,0,0,4,2,2,6,4,5,6,3,2,1,0,0,0,0
//
// Example 2:
// Input: []; Output: []
//
// Example 3:
// Input: [0]; Output: []
//
class Tests {
@Test fun `example 1`() {
assertThat(
listOf(-1, 0, 1, 2, -1, -4).findZeroSumTriplets(),
equalTo(setOf(Triplet(-1, -1, 2), Triplet(-1, 0, 1)))
)
}
@Test fun `example 2`() {
assertThat(
listOf<Int>().findZeroSumTriplets(),
equalTo(emptySet())
)
}
@Test fun `example 3`() {
assertThat(
listOf(0).findZeroSumTriplets(),
equalTo(emptySet())
)
}
@Test fun `performance on large input`() {
val random = Random(seed = 42)
val ints = List(size = 3000) { random.nextInt(-105, 106) }
val triplets = assertTimeoutPreemptively(Duration.ofSeconds(1)) {
ints.findZeroSumTriplets()
}
assertThat(triplets.size, equalTo(5618))
}
}
data class Triplet(val value: List<Int>) {
constructor(first: Int, second: Int, third: Int) :
this(listOf(first, second, third).sorted())
init {
require(value.size == 3 && value == value.sorted())
}
}
fun List<Int>.findZeroSumTriplets(): Set<Triplet> {
fun Int.toIndex() = this + 105
fun Int.toValue() = this - 105
val freq = MutableList(size = 105 + 1 + 105) { 0 }
this.forEach { freq[it.toIndex()] += 1 }
val sumFreq = convolve(freq, freq)
.mapIndexed { index, n ->
if (index % 2 == 0 && index / 2 < freq.size) n - freq[index / 2] else n
}.map { it / 2 }
val result = HashSet<Triplet>()
sumFreq.forEachIndexed { index, count ->
if (count > 0) {
val third = -(index - (105 * 2))
val thirdIndex = third.toIndex()
if (freq.indices.contains(thirdIndex) && freq[thirdIndex] > 0) {
freq.indices.forEach { firstIndex ->
val first = firstIndex.toValue()
val second = -third - first
val secondIndex = second.toIndex()
if (firstIndex in (0..thirdIndex - 1) &&
secondIndex in (0..thirdIndex - 1) &&
freq[firstIndex] > 0 && freq[secondIndex] > 0
) {
result.add(Triplet(first, second, third))
}
}
}
}
}
return result
}
fun List<Int>.findZeroSumTriplets_(): Set<Triplet> {
sorted().let {
val result = HashSet<Triplet>()
0.rangeTo(it.lastIndex - 2).forEach { i ->
var left = i + 1
var right = it.lastIndex
while (left < right) {
val sum = it[i] + it[left] + it[right]
when {
sum == 0 -> result.add(Triplet(it[i], it[left++], it[right--]))
sum < 0 -> left++
else -> right--
}
}
}
return result
}
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 3,926 | katas | The Unlicense |
src/main/kotlin/Day17.kt | akowal | 434,506,777 | false | {"Kotlin": 30540} | import kotlin.math.absoluteValue
import kotlin.math.max
import kotlin.math.min
fun main() {
println(Day17.solvePart1())
println(Day17.solvePart2())
}
object Day17 {
private val targetTopLeft: Point
private val targetBottomRight: Point
init {
val input = readInput("day17").single()
val (x1, x2, y1, y2) = """.*x=(.+)\.\.(.+), y=(.+)\.\.(.+)""".toRegex().matchEntire(input)
?.groupValues?.drop(1)?.map(String::toInt) ?: error("xoxoxo")
targetTopLeft = Point(min(x1, x2), max(y1, y2))
targetBottomRight = Point(max(x1, x2), min(y1, y2))
}
fun solvePart1() = findVelocitiesHittingTarget().map { (_, vy) -> vy * (vy - 1) / 2 }.maxOf { it }
fun solvePart2() = findVelocitiesHittingTarget().count()
private fun findVelocitiesHittingTarget() = sequence {
for (vx in 1..targetBottomRight.x) {
for (vy in -targetBottomRight.y.absoluteValue..targetBottomRight.y.absoluteValue) {
if (hitsTarget(vx, vy)) {
yield(vx to vy)
}
}
}
}
private fun hitsTarget(vx0: Int, vy0: Int): Boolean {
var x = 0
var y = 0
var vx = vx0
var vy = vy0
fun hitTarget() = (x in targetTopLeft.x..targetBottomRight.x) && (y in targetBottomRight.y..targetTopLeft.y)
fun overshoot() = x > targetBottomRight.x || y < targetBottomRight.y
while (!hitTarget() && !overshoot()) {
x += vx
y += vy
vx = vx.dec().coerceAtLeast(0)
vy--
}
return hitTarget()
}
}
| 0 | Kotlin | 0 | 0 | 08d4a07db82d2b6bac90affb52c639d0857dacd7 | 1,626 | advent-of-kode-2021 | Creative Commons Zero v1.0 Universal |
src/Day07a.kt | tbilou | 572,829,933 | false | {"Kotlin": 40925} | fun main() {
val day = "Day07"
fun parseInput(input: List<String>): List<Int> {
var path = "/root"
var dirs = mutableListOf<String>("root")
var paths:MutableMap<String, Int> = mutableMapOf()
input
.drop(1)
.forEach { line ->
when {
line.isMoveOutOfCurrentDirectory() -> path = path.substringBeforeLast("/")
line.isFile() -> paths.put(path+"/"+line.substringAfter(" "), line.substringBefore(" ").toInt())
line.isChangeDirectory() -> {
val dirName = line.substringAfter("cd ")
path += "/$dirName"
dirs.add(path)
}
}
}
return dirs
.map { dir -> paths.keys.filter { it.contains(dir) }
// .also { println(it) }
.map {key -> paths.get(key)}
// .also { println(it) }
.sumOf { it!!.toInt() }
}
}
fun part1(input: List<String>): Int {
val sizes = parseInput(input)
return sizes.filter { it < 100000 }.sumOf { it }
}
fun part2(input: List<String>): Int {
val sizes = parseInput(input)
return sizes.filter { it > 30000000 - (70000000 - sizes.max()) }.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("${day}_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("$day")
println(part1(input))
println(part2(input))
}
private fun String.isFile(): Boolean {
return """[0-9]+ .*""".toRegex().matches(this)
}
private fun String.isChangeDirectory():Boolean{
return """\$ cd .+""".toRegex().matches(this)
}
private fun String.isMoveOutOfCurrentDirectory(): Boolean {
return this == "\$ cd .."
} | 0 | Kotlin | 0 | 0 | de480bb94785492a27f020a9e56f9ccf89f648b7 | 1,932 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/briarshore/aoc2022/day07/NoSpaceLeftOnDevicePuzzle.kt | steveswing | 579,243,154 | false | {"Kotlin": 47151} | package com.briarshore.aoc2022.day07
import println
import readInput
fun main() {
fun shared(input: List<String>): Map<String, Int> {
return buildMap {
put("", 0)
var cwd = ""
input.fold(this) { acc, value ->
run {
when {
value.startsWith("$ cd ") -> {
val dir = value.substringAfter("$ cd ")
cwd = when (dir) {
"/" -> ""
".." -> cwd.substringBeforeLast('/', "")
else -> if (cwd.isEmpty()) dir else "$cwd/$dir"
}
}
value == "$ ls" -> {
"listing ${cwd}".println()
}
value.startsWith("dir ") -> {
"$value".println()
}
else -> {
var dir = cwd
val (size, _) = value.split(" ")
while (true) {
put(dir, getOrElse(dir) { 0 } + size.toInt())
if (dir.isEmpty()) break
dir = dir.substringBeforeLast('/', "")
}
}
}
}
acc
}
}
}
fun part1(input: List<String>): Int {
return shared(input).values.sumOf { if (it <= 100_000) it else 0 }
}
fun part2(input: List<String>): Int {
val sizesByName = shared(input)
val total = sizesByName.getValue("")
return sizesByName.values.asSequence().filter { 70_000_000 - (total - it) >= 30_000_000 }.min()
}
val sampleInput = readInput("d7p1-sample")
check(part1(sampleInput) == 95437)
check(part2(sampleInput) == 24933642)
val input = readInput("d7p1-input")
val part1 = part1(input)
check(part1 == 1454188)
"part1 $part1".println()
val part2 = part2(input)
"part2 $part2".println()
check(part2 == 4183246)
}
| 0 | Kotlin | 0 | 0 | a0d19d38dae3e0a24bb163f5f98a6a31caae6c05 | 2,224 | 2022-AoC-Kotlin | Apache License 2.0 |
src/Day04.kt | kmes055 | 577,555,032 | false | {"Kotlin": 35314} | fun main() {
fun String.toRange(): Pair<IntRange, IntRange> =
this.split(',')
.map { it.takeWhile { c -> c.isDigit() }.toInt()..it.takeLastWhile { c -> c.isDigit() }.toInt() }
.let { Pair(it[0], it[1]) }
fun part1(input: List<String>): Int {
return input.map { it.toRange() }
.filter { (r1, r2) ->
(r1.contains(r2.first) && r1.contains(r2.last)) ||
(r2.contains(r1.first) && r2.contains(r1.last))
}
.size
}
fun part2(input: List<String>): Int {
return input.map { it.toRange() }
.filter { (r1, r2) -> (r1.first <= r2.last && r1.last >= r2.first) }
.size
}
val input = readInput("Day04")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 84c2107fd70305353d953e9d8ba86a1a3d12fe49 | 818 | advent-of-code-kotlin | Apache License 2.0 |
src/org/aoc2021/Day9.kt | jsgroth | 439,763,933 | false | {"Kotlin": 86732} | package org.aoc2021
import java.nio.file.Files
import java.nio.file.Path
object Day9 {
data class Point(val x: Int, val y: Int)
private fun solvePart1(lines: List<String>): Int {
val heights = lines.map { line ->
line.map(Char::digitToInt)
}
val lowPoints = findLowPoints(heights)
return lowPoints.sumOf { p ->
1 + heights[p.x][p.y]
}
}
private fun solvePart2(lines: List<String>): Int {
val heights = lines.map { line ->
line.map(Char::digitToInt)
}
val lowPoints = findLowPoints(heights)
val basinMarkers = findBasins(heights, lowPoints)
return basinMarkers.flatten()
.filter { it != 0 }
.groupBy { it }
.map { (_, values) -> values.size }
.sortedDescending()
.take(3)
.reduce { a, b -> a * b }
}
private fun findLowPoints(heights: List<List<Int>>): List<Point> {
val lowPoints = mutableListOf<Point>()
for (i in heights.indices) {
for (j in heights[0].indices) {
if (
(i == 0 || heights[i][j] < heights[i-1][j]) &&
(i == heights.size - 1 || heights[i][j] < heights[i+1][j]) &&
(j == 0 || heights[i][j] < heights[i][j-1]) &&
(j == heights[0].size - 1 || heights[i][j] < heights[i][j+1])
) {
lowPoints.add(Point(i, j))
}
}
}
return lowPoints.toList()
}
private fun findBasins(heights: List<List<Int>>, lowPoints: List<Point>): Array<Array<Int>> {
val basinMarkers = Array(heights.size) { Array(heights[0].size) { 0 } }
lowPoints.forEachIndexed { index, p ->
val marker = index + 1
fill(p, marker, heights, basinMarkers)
}
return basinMarkers
}
private fun fill(p: Point, marker: Int, heights: List<List<Int>>, basinMarkers: Array<Array<Int>>) {
val (x, y) = p
basinMarkers[x][y] = marker
listOf(
-1 to 0,
1 to 0,
0 to -1,
0 to 1,
).forEach { (dx, dy) ->
val i = x + dx
val j = y + dy
if (
i >= 0 && i < heights.size &&
j >= 0 && j < heights[0].size &&
heights[i][j] != 9 && basinMarkers[i][j] == 0
) {
fill(Point(i, j), marker, heights, basinMarkers)
}
}
}
@JvmStatic
fun main(args: Array<String>) {
val lines = Files.readAllLines(Path.of("input9.txt"), Charsets.UTF_8)
val solution1 = solvePart1(lines)
println(solution1)
val solution2 = solvePart2(lines)
println(solution2)
}
} | 0 | Kotlin | 0 | 0 | ba81fadf2a8106fae3e16ed825cc25bbb7a95409 | 2,851 | advent-of-code-2021 | The Unlicense |
src/Day07.kt | diesieben07 | 572,879,498 | false | {"Kotlin": 44432} | private val file = "Day07"
//private val file = "Day07Example"
private sealed class Instruction {
data class CD(val target: String) : Instruction()
object LS : Instruction()
data class FileSizeInfo(val file: String, val size: Long) : Instruction()
data class DirectoryInfo(val name: String) : Instruction()
companion object {
fun parse(line: String): Instruction {
return when {
line.startsWith("$ cd ") -> CD(line.substring(5))
line == "$ ls" -> LS
else -> {
val (size, file) = line.split(' ', limit = 2)
when (size) {
"dir" -> DirectoryInfo(file)
else -> FileSizeInfo(file, size.toLong())
}
}
}
}
}
}
private class Executor {
private val currentDir = ArrayDeque<String>()
val sizesByDir = mutableMapOf<List<String>, Long>()
fun execute(instruction: Instruction) {
when (instruction) {
is Instruction.CD -> {
when (instruction.target) {
".." -> currentDir.removeLast()
else -> currentDir.addLast(instruction.target)
}
}
is Instruction.FileSizeInfo -> {
for (i in currentDir.indices) {
val key = currentDir.subList(0, i + 1).toList()
sizesByDir.compute(key) { _, currentSize -> (currentSize ?: 0L) + instruction.size }
}
}
is Instruction.DirectoryInfo -> {}
is Instruction.LS -> {}
}
}
}
private fun executeInput(): Executor {
return streamInput(file) { input ->
val executor = Executor()
input
.mapNotNull { Instruction.parse(it) }
.forEach { executor.execute(it) }
executor
}
}
private fun part1() {
val executor = executeInput()
val sizeAtMost = 100000
println(
executor.sizesByDir.values.asSequence()
.filter { size -> size <= sizeAtMost }
.sum()
)
}
private fun part2() {
val executor = executeInput()
val diskSpace = 70000000L
val spaceNeeded = 30000000L
val freeSpace = diskSpace - executor.sizesByDir[listOf("/")]!!
val spaceToFree = spaceNeeded - freeSpace
println(
executor.sizesByDir.asSequence()
.filter { e -> e.value >= spaceToFree}
.minBy { it.value }
)
}
fun main() {
part1()
part2()
}
| 0 | Kotlin | 0 | 0 | 0b9993ef2f96166b3d3e8a6653b1cbf9ef8e82e6 | 2,572 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/day06_lanternfish_growth/LanternfishGrowth.kt | barneyb | 425,532,798 | false | {"Kotlin": 238776, "Shell": 3825, "Java": 567} | package day06_lanternfish_growth
import histogram.Histogram
import histogram.buildHistogram
import histogram.count
import histogram.total
import util.saveTextFile
import java.io.PrintWriter
/**
* The first analysis day! Implementing a solution based on the description of
* the "business" problem will get it done, but hardly a good approach. Mapping
* business problems onto a computer domain is the essence of programming, and
* today's the day! In many ways, today is another day one: a very simple
* problem, just "can you do analysis" vs "can you read a text file". Except it
* isn't actually required...
*
* Part two makes it required. There is no possible way to get the second star
* with a naive - though correct - implementation of part one. All "timer 2"
* fish are the same class of fish, and can be treated uniformly. Identifying
* the right types in the business domain is crucial to create good software.
*/
fun main() {
util.solve(371_379, ::partOne)
util.solve(1_674_303_997_472, ::partTwo)
saveTextFile(::csv, "csv")
}
fun partOne(input: String) = simulate(input, 80)
private fun String.toCounts() =
buildHistogram<Int>(9) {
split(',')
.map(String::toInt)
.forEach { count(it, 1) }
}
private fun nextGeneration(curr: Histogram<Int>) =
buildHistogram<Int>(9) {
curr.entries.forEach { (timer, count) ->
if (timer == 0) {
count(6, count) // reset
count(8, count) // birth
} else {
count(timer - 1, count) // decrement
}
}
}
fun simulate(input: String, days: Int) =
simulate(input.toCounts(), days)
fun simulate(initial: Histogram<Int>, days: Int) =
trace(initial, days)
.last()
.total
private fun trace(initial: Histogram<Int>, days: Int) =
(1..days)
.runningFold(initial) { counts, _ ->
nextGeneration(counts)
}
//fun simulate(initial: Histogram<Int>, days: Int): Long {
// var curr = initial
// (1..days).forEach { day ->
// curr = nextGeneration(curr)
// }
// return curr.total
//}
//fun simulate(initial: Histogram<Int>, days: Int): Long {
// var curr = initial
// repeat(days) {
// curr = nextGeneration(curr)
// }
// return curr.total
//}
fun partTwo(input: String) = simulate(input, 256)
private fun csv(input: String, out: PrintWriter) {
out.println("t,value,count")
trace(input.toCounts(), 256)
.forEachIndexed { t, hist ->
hist.forEach { (v, c) ->
out.println("$t,$v,$c")
}
}
}
| 0 | Kotlin | 0 | 0 | a8d52412772750c5e7d2e2e018f3a82354e8b1c3 | 2,645 | aoc-2021 | MIT License |
src/Day08.kt | Sasikuttan2163 | 647,296,570 | false | null | import kotlin.math.abs
fun main() {
val input = readInput("Day08")
var matrix = mutableListOf<MutableList<Int>>()
var part1 = 0
matrix = input.foldIndexed(mutableListOf<MutableList<Int>>()) { index, matrix, line ->
matrix.add(line.map { it -> it.digitToInt() }.toMutableList())
matrix
}
matrix.forEachIndexed { rowIndex, row ->
if (rowIndex == 0 || rowIndex == input.size - 1) {
part1 += row.size
} else {
row.forEachIndexed { index, height ->
if (index == 0 || index == row.size - 1) {
part1++
} else {
val isVisibleHorizontally = row.subList(0, index).max() < height || row.subList(index + 1, row.size).max() < height
val isVisibleVertically = matrix.map { it[index] }
.let { column ->
column.subList(0, rowIndex).max() < height || column.subList(rowIndex + 1, column.size).max() < height
}
if (isVisibleHorizontally || isVisibleVertically) {
part1++
}
}
}
}
}
part1.println()
fun vertical(rowIndex: Int, index: Int, height: Int, isUp: Boolean): Int {
return matrix
.map {
it[index]
}
.withIndex()
.filter {
it.value >= height && if (isUp) it.index < rowIndex else it.index > rowIndex
}
.minOfOrNull {
abs(it.index - rowIndex)
}.let {
if (isUp) {
it ?: rowIndex
} else {
it ?: (matrix.size - rowIndex - 1)
}
}
}
fun horizontal(rowIndex: Int, index: Int, height: Int, isRight: Boolean): Int {
return matrix[rowIndex]
.withIndex()
.filter {
it.value >= height && if (isRight) it.index > index else it.index < index
}
.minOfOrNull {
abs(it.index - index)
}.let {
if (isRight) {
it ?: (matrix[rowIndex].size - index - 1)
} else {
it ?: index
}
}
}
val part2 = matrix
.mapIndexed { rowIndex, row ->
row.mapIndexed { index, height ->
if (rowIndex != 0 && index != 0 && rowIndex != matrix.size - 1 && index != row.size - 1) {
horizontal(rowIndex, index, height, true) * horizontal(rowIndex, index, height, false) * vertical(rowIndex, index, height, true) * vertical(rowIndex, index, height,false)
} else 0
}
}
.flatMap {
it.toList()
}
.max()
part2.println()
} | 0 | Kotlin | 0 | 0 | fb2ade48707c2df7b0ace27250d5ee240b01a4d6 | 2,905 | AoC-2022-Solutions-In-Kotlin | MIT License |
src/Day02.kt | Frendzel | 573,198,577 | false | {"Kotlin": 5336} | /**
* Rock - A, X -> 1 point
* Paper - B, Y -> 2 points
* Scissors - C, Z -> 3 points
*
* Won -> 6
* Draw -> 3
* Lose -> 0
*/
private val gameToPoints: Map<String, Int> =
mapOf(
"A X" to 1 + 3,
"A Y" to 2 + 6,
"A Z" to 3 + 0,
"B X" to 1 + 0,
"B Y" to 2 + 3,
"B Z" to 3 + 6,
"C X" to 1 + 6,
"C Y" to 2 + 0,
"C Z" to 3 + 3
)
/**
* Rock - A
* Paper - B
* Scissors - C
*
* X - need to lose
* Y - need to draw
* Z - need to win
*/
private val resultToGame: Map<String, String> =
mapOf(
"A X" to "A Z",
"A Y" to "A X",
"A Z" to "A Y",
"B X" to "B X",
"B Y" to "B Y",
"B Z" to "B Z",
"C X" to "C Y",
"C Y" to "C Z",
"C Z" to "C X"
)
fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { s: String -> gameToPoints[s]!! }
}
fun part2(input: List<String>): Int {
return input.sumOf { s: String -> gameToPoints[resultToGame[s]]!! }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
val part1 = part1(testInput)
println(part1)
check(part1 == 14297)
val part2 = part2(testInput)
println(part2)
check(part2 == 10498)
}
| 0 | Kotlin | 0 | 0 | a8320504be93dfba1f634413a50e7240d16ba6d9 | 1,491 | advent-of-code-kotlin | Apache License 2.0 |
src/day03/Day03.kt | dkoval | 572,138,985 | false | {"Kotlin": 86889} | package day03
import readInput
private const val DAY_ID = "03"
fun main() {
fun itemPriority(c: Char): Int = if (c.isLowerCase()) c - 'a' + 1 else c - 'A' + 27
fun part1(input: List<String>): Int =
input.sumOf { rucksack ->
val h1 = rucksack.substring(0, rucksack.length / 2).toSet()
val h2 = rucksack.substring(rucksack.length / 2).toSet()
// find common item(s) in 2 compartments of a given rucksack
h1.intersect(h2).sumOf { c -> itemPriority(c) }
}
fun part2(input: List<String>): Int =
input.chunked(3) { group ->
// find common item(s) in a group of 3 rucksacks
val first = group.first().toSet()
group.drop(1)
.fold(first) { acc, rucksack -> acc.intersect(rucksack.toSet()) }
.sumOf { c -> itemPriority(c) }
}.sum()
// test if implementation meets criteria from the description, like:
val testInput = readInput("day${DAY_ID}/Day${DAY_ID}_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("day${DAY_ID}/Day$DAY_ID")
println(part1(input)) // answer = 7785
println(part2(input)) // answer = 2633
}
| 0 | Kotlin | 1 | 0 | 791dd54a4e23f937d5fc16d46d85577d91b1507a | 1,235 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day01.kt | astrofyz | 572,802,282 | false | {"Kotlin": 124466} | fun main() {
fun part1(input: List<String>): Int {
var mutInput: List<String> = input
var maxCalorie = 0
var elfSnacks: List<Int>
var curCalorie: Int
while (mutInput.isNotEmpty()){
elfSnacks = mutInput.takeWhile { !it.isEmpty() }.map { it.toInt() }
curCalorie = elfSnacks.sum()
mutInput = mutInput.dropWhile { !it.isEmpty() }.dropWhile { it.isEmpty() }
maxCalorie = listOf<Int>(maxCalorie, curCalorie).max()
}
return maxCalorie
}
fun part2(input: List<String>): Int {
var mutInput: List<String> = input
var elfSnacks: List<Int>
val curCalorie = mutableListOf<Int>()
while (mutInput.isNotEmpty()) {
elfSnacks = mutInput.takeWhile { !it.isEmpty() }.map { it.toInt() }
curCalorie.add(elfSnacks.sum())
mutInput = mutInput.dropWhile { !it.isEmpty() }.dropWhile { it.isEmpty() }
}
curCalorie.sortDescending()
return curCalorie.slice(0..2).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 | a0bc190b391585ce3bb6fe2ba092fa1f437491a6 | 1,299 | aoc22 | Apache License 2.0 |
src/main/kotlin/ru/amai/study/hackerrank/practice/interviewPreparationKit/warmUpChallenges/clouds/JumpingOnClouds.kt | slobanov | 200,526,003 | false | null | package ru.amai.study.hackerrank.practice.interviewPreparationKit.warmUpChallenges.clouds
import java.util.*
private const val MAX_CLOUDS = 100
private const val MIN_CLOUDS = 2
fun jumpingOnClouds(clouds: Array<Int>): Int {
checkRequirement(clouds)
fun isThunder(cloud: Int) = cloud == 1
val (totalPenalty, _) = clouds.withIndex()
.fold(0 to PenaltyState.EVEN) { (penalty, penaltyState), (indx, cloud) ->
if (isThunder(cloud) && penaltyState.isApplicable(indx)) {
(penalty + 1) to penaltyState.flip()
} else penalty to penaltyState
}
return (clouds.size + totalPenalty) / 2
}
private fun checkRequirement(clouds: Array<Int>) {
require(clouds.all { it in listOf(0, 1) }) {
"clouds must be numbered 0 or 1; got ${clouds.contentToString()}"
}
require(clouds.size in MIN_CLOUDS..MAX_CLOUDS) {
"number of clouds should be <= $MAX_CLOUDS and >= $MIN_CLOUDS; got ${clouds.size}"
}
require(clouds.first() == 0) { "first cloud should be 0; got ${clouds.first()}" }
require(clouds.last() == 0) { "last cloud should be 0; got ${clouds.last()}" }
require(
clouds.toList()
.zipWithNext()
.map { (curr, next) -> curr + next }.all { it != 2 }
) { "there should not be two consecutive 1's in clouds; got ${clouds.contentToString()}" }
}
enum class PenaltyState {
EVEN,
ODD;
fun flip() = when (this) {
EVEN -> ODD
ODD -> EVEN
}
fun isApplicable(indx: Int) = when (this) {
EVEN -> indx % 2 == 0
ODD -> indx % 2 == 1
}
}
fun main() {
val scanner = Scanner(System.`in`)
scanner.nextLine().trim()
val clouds = scanner.nextLine().split(" ").map { it.trim().toInt() }.toTypedArray()
val result = jumpingOnClouds(clouds)
println(result)
}
| 0 | Kotlin | 0 | 0 | 2cfdf851e1a635b811af82d599681b316b5bde7c | 1,853 | kotlin-hackerrank | MIT License |
src/main/kotlin/_2021/Day3.kt | thebrightspark | 227,161,060 | false | {"Kotlin": 548420} | package _2021
import REGEX_LINE_SEPARATOR
import aoc
fun main() {
aoc(2021, 3) {
aocRun { input ->
val bitList = input.split(REGEX_LINE_SEPARATOR).map { it.toBinaryByteArray() }
val numOfOnes = numberOfOnes(bitList)
val listSizeHalf = bitList.size / 2
val mostSigBits = numOfOnes.map { if (it >= listSizeHalf) '1' else '0' }
.joinToString("")
.toBinaryByteArray()
val leastSigBits = ByteArray(mostSigBits.size) { if (mostSigBits[it] == 1.toByte()) 0 else 1 }
return@aocRun mostSigBits.toDecimalInt() * leastSigBits.toDecimalInt()
}
aocRun { input ->
val bitList = input.split(REGEX_LINE_SEPARATOR).map { it.toBinaryByteArray() }
val oxygenRating = oxygenRating(bitList)
val co2Rating = co2Rating(bitList)
return@aocRun oxygenRating.toDecimalInt() * co2Rating.toDecimalInt()
}
}
}
private fun Char.toBinaryByte(): Byte = if (this == '1') 1 else 0
private fun Byte.toBinaryChar(): Char = if (this == 1.toByte()) '1' else '0'
private fun String.toBinaryByteArray(): ByteArray = ByteArray(this.length) { this[it].toBinaryByte() }
private fun ByteArray.toDecimalInt(): Int =
StringBuilder().also { sb -> this.forEach { sb.append(it.toBinaryChar()) } }.toString().toInt(2)
private fun numberOfOnes(bitList: List<ByteArray>): IntArray = IntArray(bitList.first().size) { i ->
bitList.sumOf { it[i].toInt() }
}
private fun bitCriteria(
bitList: List<ByteArray>,
bitFilter: (zeros: Int, ones: Int) -> Byte,
bitPos: Int = 0
): ByteArray {
if (bitPos >= bitList.first().size)
error("Bit pos $bitPos is larger than the number of bits (${bitList.first().size})!")
val numOfOnes = bitList.sumOf { it[bitPos].toInt() }
val numOfZeros = bitList.size - numOfOnes
val bitFilterNum = bitFilter(numOfZeros, numOfOnes)
val filteredBitList = bitList.filter { it[bitPos] == bitFilterNum }
return when (filteredBitList.size) {
0 -> error("Empty bit list!?")
1 -> filteredBitList.single()
else -> bitCriteria(filteredBitList, bitFilter, bitPos + 1)
}
}
private fun oxygenRating(bitList: List<ByteArray>): ByteArray =
bitCriteria(bitList, { zeros, ones -> if (ones >= zeros) 1.toByte() else 0.toByte() })
private fun co2Rating(bitList: List<ByteArray>): ByteArray =
bitCriteria(bitList, { zeros, ones -> if (zeros <= ones) 0.toByte() else 1.toByte() })
| 0 | Kotlin | 0 | 0 | ac62ce8aeaed065f8fbd11e30368bfe5d31b7033 | 2,307 | AdventOfCode | Creative Commons Zero v1.0 Universal |
lib_algorithms_sort_kotlin/src/main/java/net/chris/lib/algorithms/sort/kotlin/KTRadixSorter.kt | chrisfang6 | 105,401,243 | false | {"Java": 68669, "Kotlin": 26275, "C++": 12503, "CMake": 2182, "C": 1403} | package net.chris.lib.algorithms.sort.kotlin
/**
* Radix sort.
*/
abstract class KTRadixSorter : KTSorter() {
override fun subSort(array: IntArray) {
if (array == null) {
return
}
val d = getDigit(array)
var n = 1//代表位数对应的数:1,10,100...
var k = 0//保存每一位排序后的结果用于下一位的排序输入
val bucket = Array(10) { IntArray(array.size) }//排序桶用于保存每次排序后的结果,这一位上排序结果相同的数字放在同一个桶里
val order = IntArray(array.size)//用于保存每个桶里有多少个数字
while (n < d) {
for (num in array)
//将数组array里的每个数字放在相应的桶里
{
val digit = num / n % 10
bucket[digit][order[digit]] = num
order[digit]++
}
for (i in array.indices)
//将前一个循环生成的桶里的数据覆盖到原数组中用于保存这一位的排序结果
{
if (order[i] != 0)
//这个桶里有数据,从上到下遍历这个桶并将数据保存到原数组中
{
for (j in 0..order[i] - 1) {
array[k] = bucket[i][j]
k++
}
}
order[i] = 0//将桶里计数器置0,用于下一次位排序
}
n *= 10
k = 0//将k置0,用于下一轮保存位排序结果
}
}
private fun getDigit(array: IntArray): Int {
var d = 1
for (i in array.indices) {
while (array[i] % Math.pow(10.0, d.toDouble()) != array[i].toDouble()) {
d++
}
}
return Math.pow(10.0, d.toDouble()).toInt()
}
}
| 0 | Java | 0 | 0 | 1f1c2206d5d9f0a3d6c070a7f6112f60c2714ec0 | 1,889 | sort | Apache License 2.0 |
src/main/kotlin/Day02.kt | arosenf | 726,114,493 | false | {"Kotlin": 40487} | import kotlin.math.max
import kotlin.system.exitProcess
fun main(args: Array<String>) {
if (args.isEmpty() or (args.size < 2)) {
println("Games document not specified")
exitProcess(1)
}
val fileName = args.first()
println("Reading $fileName")
val lines = readLines(fileName)
val result =
if (args[1] == "part1") {
Day02().parseGames(lines, 1)
} else {
Day02().parseGames(lines, 2)
}
println("Result: $result")
}
class Day02 {
fun parseGames(games: Sequence<String>, part: Int): Int {
return games
.map { if (part == 1) gameValue1(it) else gameValue2(it) }
.reduce { x, y -> x + y }
.or(0)
}
private fun gameValue1(game: String): Int {
return if (game.substringAfter(':')
.splitToSequence(';')
.map { toRound(it) }
.filter { !isValidRound(it) }
.count() > 0
) 0 else toGameId(game)
}
private fun gameValue2(game: String): Int {
val minRound = game.substringAfter(':')
.splitToSequence(';')
.map { toRound(it) }
.reduce { r1, r2 ->
Round(
max(r1.red, r2.red),
max(r1.green, r2.green),
max(r1.blue, r2.blue)
)
}
return minRound.red * minRound.green * minRound.blue
}
private fun toGameId(game: String): Int {
return game.substringBefore(':').filter { c -> c.isDigit() }.toInt()
}
private fun toRound(round: String): Round {
var red = 0
var green = 0
var blue = 0
round.splitToSequence(',').forEach { s ->
val (digit, color) = s.partition { c -> c.isDigit() }
when (color.trim()) {
"red" -> red = digit.toInt()
"green" -> green = digit.toInt()
"blue" -> blue = digit.toInt()
}
}
return Round(red, green, blue)
}
private fun isValidRound(round: Round): Boolean {
return round.red <= bag["red"]!!
&& round.green <= bag["green"]!!
&& round.blue <= bag["blue"]!!
}
data class Round(val red: Int, val green: Int, val blue: Int)
private val bag = mapOf(
"red" to 12,
"green" to 13,
"blue" to 14
)
}
| 0 | Kotlin | 0 | 0 | d9ce83ee89db7081cf7c14bcad09e1348d9059cb | 2,439 | adventofcode2023 | MIT License |
src/main/kotlin/com/ginsberg/advent2022/Day11.kt | tginsberg | 568,158,721 | false | {"Kotlin": 113322} | /*
* Copyright (c) 2022 by <NAME>
*/
/**
* Advent of Code 2022, Day 11 - Monkey in the Middle
* Problem Description: http://adventofcode.com/2022/day/11
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2022/day11/
*/
package com.ginsberg.advent2022
class Day11(input: List<String>) {
private val monkeys: List<Monkey> = input.chunked(7).map { Monkey.of(it) }
fun solvePart1(): Long {
rounds(20) { it / 3 }
return monkeys.business()
}
fun solvePart2(): Long {
val testProduct: Long = monkeys.map { it.test }.reduce(Long::times)
rounds(10_000) { it % testProduct }
return monkeys.business()
}
private fun List<Monkey>.business(): Long =
sortedByDescending { it.interactions }.let { it[0].interactions * it[1].interactions }
private fun rounds(numRounds: Int, changeToWorryLevel: (Long) -> Long) {
repeat(numRounds) {
monkeys.forEach { it.inspectItems(monkeys, changeToWorryLevel) }
}
}
private class Monkey(
val items: MutableList<Long>,
val operation: (Long) -> Long,
val test: Long,
val trueMonkey: Int,
val falseMonkey: Int
) {
var interactions: Long = 0
fun inspectItems(monkeys: List<Monkey>, changeToWorryLevel: (Long) -> Long) {
items.forEach { item ->
val worry = changeToWorryLevel(operation(item))
val target = if (worry % test == 0L) trueMonkey else falseMonkey
monkeys[target].items.add(worry)
}
interactions += items.size
items.clear()
}
companion object {
fun of(input: List<String>): Monkey {
val items = input[1].substringAfter(": ").split(", ").map { it.toLong() }.toMutableList()
val operationValue = input[2].substringAfterLast(" ")
val operation: (Long) -> Long = when {
operationValue == "old" -> ({ it * it })
'*' in input[2] -> ({ it * operationValue.toLong() })
else -> ({ it + operationValue.toLong() })
}
val test = input[3].substringAfterLast(" ").toLong()
val trueMonkey = input[4].substringAfterLast(" ").toInt()
val falseMonkey = input[5].substringAfterLast(" ").toInt()
return Monkey(
items,
operation,
test,
trueMonkey,
falseMonkey
)
}
}
}
}
| 0 | Kotlin | 2 | 26 | 2cd87bdb95b431e2c358ffaac65b472ab756515e | 2,642 | advent-2022-kotlin | Apache License 2.0 |
day9/src/main/kotlin/aoc2015/day9/Day9.kt | sihamark | 581,653,112 | false | {"Kotlin": 263428, "Shell": 467, "Batchfile": 383} | package aoc2015.day9
import aoc2015.utility.allPermutations
object Day9 {
fun findShortestRoute() = distances().min()!!
fun findLongestRoute() = distances().max()!!
private fun distances(): List<Int> {
val distances = input.map { Parser.parse(it) }
val map = distances
.associate { it.coordinates to it.distance }
.let { it.toRouteMap() }
val allDestinations = distances
.flatMap { it.coordinates.places }
.distinct()
val allRoutes = allDestinations.allPermutations()
.map { it.toRoute() }
return allRoutes.map { map.distance(it) }
}
private object Parser {
private val validCommand = Regex("(\\w+) to (\\w+) = (\\d+)")
fun parse(rawDistance: String): Distance {
val parsedValues = validCommand.find(rawDistance)?.groupValues ?: error("invalid raw command: $rawDistance")
return Distance(
Coordinates(
parsedValues[1],
parsedValues[2]
),
parsedValues[3].toInt()
)
}
}
class Coordinates private constructor(
val places: Set<String>
) {
constructor(from: String, to: String) : this(setOf(from, to))
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Coordinates
if (places != other.places) return false
return true
}
override fun hashCode(): Int {
return places.hashCode()
}
}
data class Route(private val places: List<String>) : Iterable<Coordinates> {
init {
if (places.size < 2) error("must contain at least 2 places")
}
override fun iterator() = object : Iterator<Coordinates> {
private var current = 0
private val last = places.size - 2
override fun hasNext() = current <= last
override fun next() = Coordinates(places[current], places[current + 1]).also {
current++
}
}
}
data class RouteMap(private val distances: Map<Coordinates, Int>) {
fun distance(route: Route) = route.mapNotNull { distances[it] }.sum()
}
data class Distance(
val coordinates: Coordinates,
val distance: Int
)
fun List<String>.toRoute() = Route(this)
fun Map<Coordinates, Int>.toRouteMap() = RouteMap(this)
} | 0 | Kotlin | 0 | 0 | 6d10f4a52b8c7757c40af38d7d814509cf0b9bbb | 2,635 | aoc2015 | Apache License 2.0 |
src/Day05.kt | oleskrede | 574,122,679 | false | {"Kotlin": 24620} | fun main() {
/*
I didn't bother with parsing the stacks as they were specified in the initial input.
So I rotated them clockwise.
E.g. the example input became:
ZN
MCD
P
move 1 from 2 to 1
...
*/
fun parseInput(input: List<String>): Pair<MutableList<MutableList<Char>>, List<List<Int>>> {
val stackEndIndex = input.indexOfFirst { it.isBlank() }
val stacks = input.take(stackEndIndex).map { it.toMutableList() }.toMutableList()
val instructions = input.drop(stackEndIndex + 1)
.map {
it.replace("move ", "")
.replace("from ", "")
.replace("to ", "")
.split(" ").map { value -> value.toInt() }
}
return Pair(stacks, instructions)
}
fun part1(input: List<String>): String {
val (stacks, instructions) = parseInput(input)
instructions.forEach {
val numCrates = it[0]
val from = it[1] - 1
val to = it[2] - 1
for (i in 0 until numCrates) {
val crate = stacks[from].removeLast()
stacks[to].add(crate)
}
}
return stacks.map { it.last() }.joinToString(separator = "")
}
fun part2(input: List<String>): String {
val (stacks, instructions) = parseInput(input)
instructions.forEach {
val numCrates = it[0]
val from = it[1] - 1
val to = it[2] - 1
val movingCrates = stacks[from].takeLast(numCrates)
val remainingCrates = stacks[from].dropLast(numCrates)
stacks[from] = remainingCrates.toMutableList()
stacks[to].addAll(movingCrates)
}
return stacks.map { it.last() }.joinToString(separator = "")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
test(part1(testInput), "CMZ")
test(part2(testInput), "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a3484088e5a4200011335ac10a6c888adc2c1ad6 | 2,123 | advent-of-code-2022 | Apache License 2.0 |
src/Day01/Day01.kt | S-Flavius | 573,063,719 | false | {"Kotlin": 6843} | package day01
import readInput
import kotlin.math.max
fun main() {
fun part1(input: List<String>): Int {
var curMax = -1
var curElf = 0
for (line in input) when {
line.isNotEmpty() -> curElf += line.toInt()
else -> {
curMax = max(curMax, curElf)
curElf = 0
}
}
return curMax
}
fun part2(input: List<String>): Int {
val topThree = arrayOf(-1, -1, -1)
var curElf = 0
for (line in input)
if (line.isNotEmpty()) {
curElf += line.toInt()
} else {
when {
curElf > topThree[2] -> {
topThree[0] = topThree[1]
topThree[1] = topThree[2]
topThree[2] = curElf
}
curElf > topThree[1] -> {
topThree[0] = topThree[1]
topThree[1] = curElf
}
curElf > topThree[0] -> {
topThree[0] = curElf
}
}
curElf = 0
}
when {
curElf > topThree[2] -> {
topThree[0] = topThree[1]
topThree[1] = topThree[2]
topThree[2] = curElf
}
curElf > topThree[1] -> {
topThree[0] = topThree[1]
topThree[1] = curElf
}
curElf > topThree[0] -> {
topThree[0] = curElf
}
}
return topThree.reduce { x, y -> x + y }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day01/Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("day01/Day01")
println("Part 1: " + part1(input))
println("Part 2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | 47ce29125ff6071edbb07ae725ac0b9d672c5356 | 2,002 | AoC-Kotlin-2022 | Apache License 2.0 |
2022/src/test/kotlin/Day14.kt | jp7677 | 318,523,414 | false | {"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338} | import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
private data class Unit(var x: Int, var y: Int)
class Day14 : StringSpec({
"puzzle part 01" {
val rocks = getRocks()
val countOfSand = rocks.produceSand() - rocks.count()
countOfSand shouldBe 808
}
"puzzle part 02" {
val rocks = getRocks()
val minX = rocks.minOf { it.x }
val maxX = rocks.maxOf { it.x }
val distanceX = maxX - minX
val maxY = rocks.maxOf { it.y }
val bottom = ((minX - distanceX * 4)..(maxX + distanceX * 4))
.map { Unit(it, maxY + 2) }
.toSet()
val countOfSand = (rocks + bottom).produceSand() - rocks.count() - bottom.count()
countOfSand shouldBe 26625
}
})
private fun Set<Unit>.produceSand(): Int {
val map = this.toMutableSet()
while (true) {
val sand = Unit(500, 0)
if (sand.cameToRest(map)) return map.size + 1
while (true) {
if (!map.contains(sand.peekDown())) sand.moveDown()
else if (!map.contains(sand.peekLeft())) sand.moveLeft()
else if (!map.contains(sand.peekRight())) sand.moveRight()
if (sand.flowsIntoAbyss(map)) return map.size
if (sand.cameToRest(map)) break
}
map.add(sand)
}
}
private fun Unit.peekDown() = Unit(x, y + 1)
private fun Unit.peekLeft() = Unit(x - 1, y + 1)
private fun Unit.peekRight() = Unit(x + 1, y + 1)
private fun Unit.moveDown() = this.y++
private fun Unit.moveLeft() { this.x--; this.y++ }
private fun Unit.moveRight() { this.x++; this.y++ }
private fun Unit.flowsIntoAbyss(map: Set<Unit>) = map.none { it.y > this.y }
private fun Unit.cameToRest(map: Set<Unit>) = map
.containsAll(listOf(this.peekDown(), this.peekLeft(), this.peekRight()))
private fun getRocks() = getPuzzleInput("day14-input.txt")
.flatMap { line ->
line.split(" -> ").map { s ->
s.split(",").let { Unit(it.first().toInt(), it.last().toInt()) }
}
.fold(listOf<Unit>()) { acc, it ->
if (acc.any()) {
acc + (acc.last().x towards it.x).flatMap { x ->
(acc.last().y towards it.y).map { y -> Unit(x, y) }
}
} else listOf(it)
}
}.toSet()
| 0 | Kotlin | 1 | 2 | 8bc5e92ce961440e011688319e07ca9a4a86d9c9 | 2,353 | adventofcode | MIT License |
Kotlin/DiameterBinaryTree.kt | sukritishah15 | 299,329,204 | false | null | /**
* Algorithm: Diameter of Binary Tree
* Language: Kotlin
* Input:
* Sample Binary Tree
* Output:
* Diameter of Binary Tree
* Time Complexity: O(n) as we are visiting every node once.
* Space Complexity: O(d) where d is the depth of the binary tree
*
* Sample Input:
* 8
* / \
* 3 10
* / \ \
* 1 6 14
* / \ /
* 4 7 13
*
* Sample Output:
* Diameter of Binary Tree: 6
*/
import kotlin.math.max
class BinaryTree(var value: Int) {
var leftChild: BinaryTree? = null
var rightChild: BinaryTree? = null
}
class DiameterBinaryTree {
private fun dfs(root: BinaryTree?): Pair<Int, Int> {
if (root == null) {
return Pair(0, 0)
}
val leftChild = dfs(root.leftChild)
val rightChild = dfs(root.rightChild)
val diameter = max(leftChild.first, max(rightChild.first, leftChild.second + rightChild.second))
return Pair(diameter, max(leftChild.second, rightChild.second) + 1)
}
fun diameterOfBinaryTree(root: BinaryTree?): Int {
return dfs(root).first
}
}
fun main() {
val tree = BinaryTree(8)
tree.leftChild = BinaryTree(3)
tree.rightChild = BinaryTree(10)
tree.leftChild?.leftChild = BinaryTree(1)
tree.leftChild?.rightChild = BinaryTree(6)
tree.leftChild?.rightChild?.leftChild = BinaryTree(4)
tree.leftChild?.rightChild?.rightChild = BinaryTree(7)
tree.rightChild?.rightChild = BinaryTree(14)
tree.rightChild?.rightChild?.leftChild = BinaryTree(13)
val diam = DiameterBinaryTree()
val diameter = diam.diameterOfBinaryTree(tree)
println("Diameter of Binary Tree: $diameter")
}
| 164 | Java | 295 | 955 | 1b6040f7d9af5830882b53916e83d53a9c0d67d1 | 1,716 | DS-Algo-Point | MIT License |
src/Day04.kt | paulbonugli | 574,065,510 | false | {"Kotlin": 13681} | fun main() {
fun determineRange(range: String): IntRange {
val (first, last) = range.split("-").map { it.toInt() }
return IntRange(first, last)
}
fun parseInput(input: List<String>): List<Pair<IntRange, IntRange>> {
return input.map { it.split(",") }.map {
determineRange(it[0]) to determineRange(it[1])
}
}
infix fun IntRange.contains(other: IntRange): Boolean =
contains(other.first) && contains(other.last)
infix fun IntRange.overlaps(other: IntRange): Boolean =
contains(other.first) || contains(other.last) || other.contains(this)
fun part1(input: List<String>): Int {
return parseInput(input).count { pair ->
pair.first.contains(pair.second) || pair.second.contains(pair.first)
}
}
fun part2(input: List<String>): Int {
return parseInput(input).count { pair ->
pair.first overlaps pair.second
}
}
val lines = readInput("Day04")
println("Part 1: " + part1(lines))
println("Part 2: " + part2(lines))
}
| 0 | Kotlin | 0 | 0 | d2d7952c75001632da6fd95b8463a1d8e5c34880 | 1,081 | aoc-2022-kotlin | Apache License 2.0 |
src/Day02.kt | 0xBuro | 572,308,139 | false | {"Kotlin": 4929} | fun main() {
fun encryptedStrategyGuide(input: String): List<List<String>> {
return input.replace(" ", "").split("\n")
.map { it.lines() }
}
fun getShapeWeight(shape: Char): Int {
if(shape == 'X') {
return 1 //rock
}
if(shape == 'Y') {
return 2 //paper
}
if(shape == 'Z') {
return 3 //scissors
}
return 0
}
fun part1(combination: String): Int {
val pairs = encryptedStrategyGuide(combination)
var combinedCases = arrayOf<Int>()
for (i in pairs) {
if (i.contains("BX") || i.contains("CY") || i.contains("AZ")) {
combinedCases += (0 + getShapeWeight(i[0][1])) //lose + shape weight
}
if (i.contains("AX") || i.contains("BY") || i.contains("CZ")) {
combinedCases += (3 + getShapeWeight(i[0][1])) //draw + shape weight
}
if (i.contains("CX") || i.contains("AY") || i.contains("BZ")) {
combinedCases += (6 + getShapeWeight(i[0][1])) //win + shape weight
}
}
return combinedCases.sum()
}
fun getCounterWeight(pair: String): Int {
if(pair == "AY" || pair == "BX" || pair == "CZ") {
return 1 //rock
}
if(pair == "AZ" || pair == "BY" || pair == "CX") {
return 2 //paper
}
if(pair == "AX" || pair == "BZ" || pair == "CY") {
return 3 //scissors
}
return 0
}
fun part2(combination: String): Int {
val pairs = encryptedStrategyGuide(combination)
var combinedCases = arrayOf<Int>()
for (i in pairs) {
if (i.contains("AX") || i.contains("BX") || i.contains("CX")) {
combinedCases += (0 + getCounterWeight(i[0])) //counter shape to lose
}
if (i.contains("AY") || i.contains("BY") || i.contains("CY")) {
combinedCases += (3 + getCounterWeight(i[0])) //counter shape to draw
}
if (i.contains("AZ") || i.contains("BZ") || i.contains("CZ")) {
combinedCases += (6 + getCounterWeight(i[0])) //counter shape to win
}
}
return combinedCases.sum()
}
//val testInput = readInput("esg")
//check(combinationOfCases(testInput) == 15)
//check(indicatedCase(testInput) == 12)
val input = readInput("esg")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | c05c4db78e24fc36f6f112bc1e8cf24ad5fd7698 | 2,545 | Advent-of-Kotlin | Apache License 2.0 |
src/questions/LongestIncreasingSubSeq.kt | realpacific | 234,499,820 | false | null | package questions
import _utils.UseCommentAsDocumentation
import utils.shouldBe
import utils.shouldBeOneOf
/**
* Given an integer array nums, return the longest strictly increasing subsequence.
* A subsequence is a sequence that can be derived from an array by deleting some or no elements
* without changing the order of the remaining elements.
*
* [Explanation](https://youtu.be/mouCn3CFpgg?t=1057)
*
* @see LengthOfLongestIncreasingSubSeq
*/
@UseCommentAsDocumentation
private object LongestIncreasingSubSeq
private fun longestIncreasingSubsequence(nums: IntArray): IntArray {
if (nums.size == 1) return nums
var maxSubsequenceIndex = 0 // record the index
val increasingSeq = IntArray(nums.size) { 1 }
for (i in 1..nums.lastIndex) {
for (j in 0 until i) {
// (Is still increasing?) && (choose the best i.e. larger answer)
if (nums[i] > nums[j] && increasingSeq[i] <= increasingSeq[j]) {
increasingSeq[i] = 1 + increasingSeq[j]
}
}
if (increasingSeq[maxSubsequenceIndex] < increasingSeq[i]) {
maxSubsequenceIndex = i
}
}
// iterate backwards from [maxSubsequenceIndex], and record every element whose [increasingSeq[i]] decreases by 1
var numberOfItemsInLIS = increasingSeq[maxSubsequenceIndex]
val result =
IntArray(increasingSeq[maxSubsequenceIndex]) { -1 } // size is same as the value in [increasingSeq]'s [maxSubsequenceIndex]th index
result[result.lastIndex] = nums[maxSubsequenceIndex]
var resultIndex = result.lastIndex - 1
for (i in maxSubsequenceIndex - 1 downTo 0) {
if (increasingSeq[i] == numberOfItemsInLIS - 1) { // include it in LIS if value decreases by 1
result[resultIndex] = nums[i]
numberOfItemsInLIS--
resultIndex--
}
}
return result
}
fun main() {
longestIncreasingSubsequence(intArrayOf(5, 8, 7, 1, 9)) shouldBeOneOf
listOf(intArrayOf(5, 8, 9), intArrayOf(5, 7, 9))
longestIncreasingSubsequence(intArrayOf(1, 1, 1, 1, 1, 1)) shouldBe intArrayOf(1)
longestIncreasingSubsequence(intArrayOf(1, 2, 3, 4, 5, 6)) shouldBe intArrayOf(1, 2, 3, 4, 5, 6)
longestIncreasingSubsequence(intArrayOf(1, 2, 3, 4, 5, 6, 1)) shouldBe intArrayOf(1, 2, 3, 4, 5, 6)
longestIncreasingSubsequence(intArrayOf(3, 2, 1)) shouldBeOneOf listOf(intArrayOf(1), intArrayOf(2), intArrayOf(3))
longestIncreasingSubsequence(intArrayOf(1, 2, 1)) shouldBe intArrayOf(1, 2)
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 2,522 | algorithms | MIT License |
day17/src/main/kotlin/aoc2015/day17/Day17.kt | sihamark | 581,653,112 | false | {"Kotlin": 263428, "Shell": 467, "Batchfile": 383} | package aoc2015.day17
object Day17 {
private const val TARGET_LITRES = 150
fun findAmountOfTargetCombinations(): Int {
val buckets = input.map { Parser.parse(it) }
val factors = Factors(buckets.size)
return factors.asSequence()
.map { buckets * it }
.filter { it == TARGET_LITRES }
.count()
}
fun findAmountOfTargetCombinationsWithMinimalBuckets(): Int {
val buckets = input.map { Parser.parse(it) }
val factors = Factors(buckets.size)
val minBuckets = factors.asSequence()
.filter { buckets * it == TARGET_LITRES }
.map { it.sizeOfActive }
.min()
return factors.asSequence()
.filter { it.sizeOfActive == minBuckets }
.filter { buckets * it == TARGET_LITRES }
.count()
}
private operator fun List<Bucket>.times(factors: Factors): Int {
if (size != factors.size) error("size of buckets and factors must be equal")
return mapIndexed { index, bucket -> bucket.litre * factors[index] }
.sum()
}
private class Factors(
private val factors: IntArray
) : Iterable<Factors> {
constructor(size: Int) : this(IntArray(size) { 0 })
val size
get() = factors.size
val sizeOfActive
get() = factors.count { it == 1 }
val isLast
get() = factors.all { it == 1 }
operator fun get(index: Int): Int = factors[index]
operator fun inc() = copy().apply { increase() }
fun increase() {
increaseAtIndex(factors.lastIndex)
}
private fun increaseAtIndex(index: Int) {
factors[index]++
if (factors[index] == 2) {
factors[index] = 0
if (index == 0) return
increaseAtIndex(index - 1)
}
}
fun copy() = Factors(factors.copyOf())
override fun iterator() = FactorsIterator()
override fun toString() = factors.joinToString(separator = "")
inner class FactorsIterator : Iterator<Factors> {
private var current = this@Factors
override fun hasNext() = !current.isLast
override fun next(): Factors {
val result = current
current++
return result
}
}
}
private data class Bucket(val litre: Int) {
override fun toString() = litre.toString()
}
private object Parser {
fun parse(rawBucket: String) = Bucket(rawBucket.toInt())
}
} | 0 | Kotlin | 0 | 0 | 6d10f4a52b8c7757c40af38d7d814509cf0b9bbb | 2,676 | aoc2015 | Apache License 2.0 |
src/leetcode/juneChallenge2020/weekfive/WordSearchII.kt | adnaan1703 | 268,060,522 | false | null | package leetcode.juneChallenge2020.weekfive
import utils.print
fun main() {
val board = arrayOf(
charArrayOf('o', 'a', 'a', 'n'),
charArrayOf('e', 't', 'a', 'e'),
charArrayOf('i', 'h', 'k', 'r'),
charArrayOf('i', 'f', 'l', 'v')
)
findWords(board, arrayOf("oath", "pea", "eat", "rain")).print()
}
fun findWords(board: Array<CharArray>, words: Array<String>): List<String> {
val trie = WordSearchTrie()
val wordsFound = HashSet<String>()
val rows = board.size
val cols = board[0].size
val visited = Array(rows) { BooleanArray(cols) }
words.forEach { trie.insert(it) }
for (i in 0 until rows) {
for (j in 0 until cols) {
traverse(board, visited, "", i, j, trie, wordsFound)
}
}
return wordsFound.toList()
}
private fun traverse(
board: Array<CharArray>,
visited: Array<BooleanArray>,
str: String,
i: Int,
j: Int,
trie: WordSearchTrie,
wordsFound: HashSet<String>
) {
if (board.getOrNull(i)?.getOrNull(j) == null || visited[i][j])
return
val word = str + board[i][j]
if (trie.startsWith(word).not())
return
if (trie.search(word)) {
wordsFound.add(word)
}
visited[i][j] = true
traverse(board, visited, word, i + 1, j, trie, wordsFound)
traverse(board, visited, word, i - 1, j, trie, wordsFound)
traverse(board, visited, word, i, j + 1, trie, wordsFound)
traverse(board, visited, word, i, j - 1, trie, wordsFound)
visited[i][j] = false
}
private class WordSearchTrie {
private val _terminatingPosition = 26
private val _terminatingNode = TrieNode()
private val rootNode = TrieNode()
/** Inserts a word into the trie. */
fun insert(word: String) {
var node: TrieNode = rootNode
word.forEach {
val pos = it.getPos()
if (node.nodes[pos] == null) {
node.nodes[pos] = TrieNode()
}
node = node.nodes[pos]!!
}
node.nodes[_terminatingPosition] = _terminatingNode
}
/** Returns if the word is in the trie. */
fun search(word: String): Boolean {
var node: TrieNode? = rootNode
word.forEach {
node = node?.nodes?.getOrNull(it.getPos())
}
return node?.nodes?.get(_terminatingPosition) != null
}
/** Returns if there is any word in the trie that starts with the given prefix. */
fun startsWith(prefix: String): Boolean {
var node: TrieNode? = rootNode
prefix.forEach {
node = node?.nodes?.getOrNull(it.getPos())
}
return node != null
}
private fun Char.getPos(): Int = this - 'a'
private class TrieNode {
val nodes = Array<TrieNode?>(27) { null }
}
}
| 0 | Kotlin | 0 | 0 | e81915db469551342e78e4b3f431859157471229 | 2,803 | KotlinCodes | The Unlicense |
src/Day08.kt | stcastle | 573,145,217 | false | {"Kotlin": 24899} | import kotlin.math.max
/** Holds values for the max tree height in all directions leading up to this spot. */
data class MaxTreeHeight(
var north: Int = -1,
var east: Int = -1,
var south: Int = -1,
var west: Int = -1
)
fun MaxTreeHeight.treeIsVisible(tree: Int) =
tree > north || tree > east || tree > south || tree > west
/** create the list of lists. */
fun createHeights(input: List<String>): MutableList<MutableList<MaxTreeHeight>> {
val heights = mutableListOf<MutableList<MaxTreeHeight>>()
input.forEachIndexed { index, line ->
heights.add(mutableListOf())
line.forEach { heights[index].add(MaxTreeHeight()) }
}
return heights
}
/** update the heights in place. */
fun MutableList<MutableList<MaxTreeHeight>>.fillNorthAndWestHeights(input: List<String>) {
val lastRowIndex = input.size - 1
val lastColumnIndex = input[0].length - 1
input.forEachIndexed { row, line ->
line.forEachIndexed { column, _ ->
// Keep all the outside heights as -1.
if (!(row == 0 || column == 0 || row == lastRowIndex || column == lastColumnIndex)) {
this[row][column].north =
max(this[row - 1][column].north, input[row - 1][column].digitToInt())
this[row][column].west =
max(this[row][column - 1].west, input[row][column - 1].digitToInt())
}
}
}
}
fun MutableList<MutableList<MaxTreeHeight>>.fillSouthAndEastHeights(input: List<String>) {
val lastRowIndex = input.size - 1
val lastColumnIndex = input[0].length - 1
input.withIndex().reversed().forEach { indexedValue ->
val row = indexedValue.index
indexedValue.value.withIndex().reversed().forEach { lineIndexValue ->
val column = lineIndexValue.index
if (!(row == 0 || column == 0 || row == lastRowIndex || column == lastColumnIndex)) {
this[row][column].south =
max(this[row + 1][column].south, input[row + 1][column].digitToInt())
this[row][column].east =
max(this[row][column + 1].east, input[row][column + 1].digitToInt())
}
}
}
}
fun countVisible(input: List<String>, heights: List<List<MaxTreeHeight>>): Int {
var count = 0
heights.forEachIndexed { row, value ->
value.forEachIndexed { column, maxTreeHeight ->
val tree = input[row][column].digitToInt()
if (maxTreeHeight.treeIsVisible(tree)) {
// println("Visible at Row $row and Column $column")
count++
}
}
}
return count
}
fun main() {
fun part1(input: List<String>): Int {
val heights: MutableList<MutableList<MaxTreeHeight>> = createHeights(input)
heights.fillNorthAndWestHeights(input)
heights.fillSouthAndEastHeights(input)
// heights.forEach { println(it) }
return countVisible(input, heights)
}
fun part2(input: List<String>): Int {
val lastRowIndex = input.size - 1
val lastColumnIndex = input[0].length - 1
var maxScenicScore = 0
input.forEachIndexed { row, line ->
line.forEachIndexed { column, c ->
// Only check trees on the inside because the edges have viewing score zero.
// if (!(row == 0 || column == 0 || row == lastRowIndex || column == lastColumnIndex)) {
val tree = c.digitToInt()
// Checks North.
var north = 0
for (currRow in (row - 1) downTo 0) {
north++
if (input[currRow][column].digitToInt() >= tree) break
}
// South.
var south = 0
for (currRow in (row + 1)..lastRowIndex) {
south++
if (input[currRow][column].digitToInt() >= tree) break
}
// East.
var east = 0
for (currCol in (column + 1)..lastColumnIndex) {
east++
if (input[row][currCol].digitToInt() >= tree) break
}
// West.
var west = 0
for (currCol in (column - 1) downTo 0) {
west++
if (input[row][currCol].digitToInt() >= tree) break
}
val scenicScore = north * east * south * west
// println(
// "Row $row and column $column has score $scenicScore: ($north, $east, $south, $west)")
maxScenicScore = max(scenicScore, maxScenicScore)
}
// }
}
return maxScenicScore
}
val day = "08"
val testInput = readInput("Day${day}_test")
println("Part 1 test = ${part1(testInput)}")
val input = readInput("Day${day}")
println("part1 = ${part1(input)}")
println("Part 2 test = ${part2(testInput)}")
println("part2 = ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 746809a72ea9262c6347f7bc8942924f179438d5 | 4,503 | aoc2022 | Apache License 2.0 |
src/main/kotlin/aoc2023/Day12.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2023
import utils.InputUtils
val dots = "\\.+".toRegex()
fun String.replaceAt(index: Int, c: Char): String {
val sb = StringBuilder(this)
sb.setCharAt(index, c)
return sb.toString()
}
fun main() {
val testInput = """???.### 1,1,3
.??..??...?##. 1,1,3
?#?#?#?#?#?#?#? 1,3,1,6
????.#...#... 4,1,1
????.######..#####. 1,6,5
?###???????? 3,2,1""".trimIndent().split("\n")
fun matches(arrangement: String, groups: List<Int>): Boolean {
val actual = arrangement.split(dots).map { it.length }.filter { it != 0 }
return actual == groups
}
fun matches(arrangement: String, pattern: String) {
arrangement.zip(pattern).all { (a, p) ->
a == p || p == '?'
}
}
fun fix(pattern: String, groups: List<Int>): List<String> {
val firstQ = pattern.indexOf('?')
if (firstQ == -1) {
if (matches(pattern, groups))
return listOf(pattern.toString())
else return listOf()
}
return fix(pattern.replaceAt(firstQ, '.'), groups) +
fix(pattern.replaceAt(firstQ, '#'), groups)
}
//fun fix(pattern: String, groups: List<Int>) = fix(StringBuilder(pattern), groups)
fun part1(input: List<String>): Int {
return input.map {
val (pattern, groupString) = it.split(" ")
val groups = listOfNumbers(groupString)
pattern to groups
}
.sumOf {
val size = fix(it.first, it.second).size
size
}
}
fun part2(input: List<String>): Int {
return input.size
}
// test if implementation meets criteria from the description, like:
val testValue = part1(testInput)
println(testValue)
check(testValue == 21)
println(part2(testInput))
val puzzleInput = InputUtils.downloadAndGetLines(2023, 12)
val input = puzzleInput.toList()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5abc9e479bed21ae58c093c8efbe4d343eee7714 | 1,983 | aoc-2022-kotlin | Apache License 2.0 |
archive/src/main/kotlin/com/grappenmaker/aoc/year22/Day11.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year22
import com.grappenmaker.aoc.PuzzleSet
import com.grappenmaker.aoc.product
fun PuzzleSet.day11() = puzzle {
val monkeys = input.split("\n\n").map { m ->
val (items, op, test, t, f) = m.lines().drop(1)
val (operator, operand) = op.split(" ").takeLast(2)
val opLiteral = operand.toLongOrNull()
Monkey(
items.substringAfter(": ").split(", ").map(String::toLong),
{ old ->
val opa = opLiteral ?: old
when (operator) {
"*" -> old * opa
"+" -> old + opa
else -> error("Should not happen")
}
},
test.split(" ").last().toLong(),
t.split(" ").last().toInt(),
f.split(" ").last().toInt()
)
}
fun solve(partTwo: Boolean): String {
val currMonkeys = monkeys.map { it.items.toMutableList() }
val throws = currMonkeys.map { 0 }.toMutableList()
val lcm = monkeys.map { it.test }.product()
repeat(if (!partTwo) 20 else 10000) {
monkeys.forEachIndexed { idx, m ->
val currItems = currMonkeys[idx]
currItems.forEach {
val newLevel = m.operation(it)
val acLevel = if (partTwo) newLevel % lcm else newLevel / 3
when {
acLevel % m.test == 0L -> currMonkeys[m.ifTrue] += acLevel
else -> currMonkeys[m.ifFalse] += acLevel
}
}
throws[idx] += currItems.size
currItems.clear()
}
}
return throws.sortedDescending().take(2).map { it.toLong() }.product().s()
}
partOne = solve(false)
partTwo = solve(true)
}
data class Monkey(
val items: List<Long>,
val operation: (Long) -> Long,
val test: Long,
val ifTrue: Int,
val ifFalse: Int
) | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 1,991 | advent-of-code | The Unlicense |
src/main/kotlin/aoc2018/RegularMap.kt | komu | 113,825,414 | false | {"Kotlin": 395919} | package komu.adventofcode.aoc2018
import komu.adventofcode.utils.Direction
import komu.adventofcode.utils.Direction.*
import komu.adventofcode.utils.Point
import utils.shortestPathBetween
fun regularMap(input: String) =
RoomMap.create(input).solution()
fun regularMap2(input: String) =
RoomMap.create(input).solution2()
private class RoomMap {
private val rooms = mutableMapOf(Point.ORIGIN to Room(Point.ORIGIN))
fun solution(): Int =
rooms.values.maxOf { from -> shortestPathBetween(Point.ORIGIN, from.point) { this[it].neighbors }!!.size }
fun solution2(): Int =
rooms.values.count { from -> shortestPathBetween(Point.ORIGIN, from.point) { this[it].neighbors }!!.size >= 1000 }
operator fun get(p: Point): Room =
rooms[p] ?: error("no room for $p")
fun move(fromRoom: Room, dir: Direction): Room {
val target = fromRoom.point + dir
val targetRoom = rooms.getOrPut(target) { Room(target) }
fromRoom.doors += dir
targetRoom.doors += dir.opposite
return targetRoom
}
fun move(from: Point, dir: Direction): Room =
move(this[from], dir)
class Room(val point: Point) {
val doors = mutableSetOf<Direction>()
val neighbors: List<Point>
get() = doors.map { point + it }
}
companion object {
fun create(input: String): RoomMap {
val parsed = RegexParser(input).parse()
val roomMap = RoomMap()
parsed.traverse(Point.ORIGIN, roomMap)
return roomMap
}
}
}
private sealed class MapRegex {
abstract fun traverse(p: Point, roomMap: RoomMap): Set<Point>
data class Walk(val directions: List<Direction>) : MapRegex() {
override fun traverse(p: Point, roomMap: RoomMap): Set<Point> {
var pt = p
for (d in directions) {
roomMap.move(pt, d)
pt += d
}
return setOf(pt)
}
}
data class Sequence(val exps: List<MapRegex>) : MapRegex() {
override fun traverse(p: Point, roomMap: RoomMap): Set<Point> =
exps.fold(listOf(p)) { ps, r -> ps.flatMap { r.traverse(it, roomMap) } }.toSet()
}
data class Alternation(val exps: List<MapRegex>) : MapRegex() {
override fun traverse(p: Point, roomMap: RoomMap) =
exps.flatMap { it.traverse(p, roomMap) }.toSet()
}
}
private fun directionFor(c: Char) = when (c) {
'N' -> UP
'E' -> RIGHT
'S' -> DOWN
'W' -> LEFT
else -> error("invalid direction '$c'")
}
private class RegexParser(private val s: String) {
private var i = 0
fun parse(): MapRegex {
expect('^')
val exp = parseExp()
expect('$')
check(i == s.length)
return exp
}
private fun parseExp(): MapRegex {
val exps = mutableListOf<MapRegex>()
while (nextChar != '$' && nextChar != ')' && nextChar != '|') {
exps += when (val c = readChar()) {
in "NWSE" -> {
val directions = mutableListOf(directionFor(c))
while (nextChar in "NWSE")
directions += directionFor(readChar())
MapRegex.Walk(directions)
}
'(' ->
parseAlternation()
else ->
error("unexpected character '$c'")
}
}
return exps.singleOrNull() ?: MapRegex.Sequence(exps)
}
private fun parseAlternation(): MapRegex {
val exps = mutableListOf<MapRegex>()
exps += parseExp()
while (nextChar == '|') {
expect('|')
exps += parseExp()
}
expect(')')
return exps.singleOrNull() ?: MapRegex.Alternation(exps)
}
private fun readChar() = s[i++]
private val nextChar: Char
get() = s[i]
private fun expect(c: Char) {
check(readChar() == c)
}
} | 0 | Kotlin | 0 | 0 | 8e135f80d65d15dbbee5d2749cccbe098a1bc5d8 | 4,003 | advent-of-code | MIT License |
src/Day03/Day03.kt | Nathan-Molby | 572,771,729 | false | {"Kotlin": 95872, "Python": 13537, "Java": 3671} | package Day03
import readInput
import java.lang.Error
import java.util.BitSet
fun charToInt(char: Char): Int {
val asciiValue = char.code
return when(asciiValue) {
in 65..90 -> asciiValue - 38
in 97..122 -> asciiValue - 96
else -> 0
}
}
fun findCommonInt(leftInput: List<Int>, rightInput: List<Int>) : Int {
val leftInputBitArray = BitSet(64)
val rightInputBitarray = BitSet(64)
for ((leftValue, rightValue) in leftInput.zip(rightInput)) {
leftInputBitArray.set(leftValue)
rightInputBitarray.set(rightValue)
if (rightInputBitarray[leftValue]) {
return leftValue
} else if (leftInputBitArray[rightValue]) {
return rightValue
}
}
throw Error()
}
fun findCommonInt(inputs: List<List<Int>>): Int {
var bitArrays = mutableListOf(BitSet(64), BitSet(64), BitSet(64))
var index = 0
for (inputList in inputs) {
for (input in inputList) {
bitArrays[index].set(input)
}
index++
}
bitArrays[0].and(bitArrays[1])
bitArrays[0].and(bitArrays[2])
return bitArrays[0].nextSetBit(0)
}
fun main() {
fun part1(input: List<String>): Int {
var total: Int = 0
for(line in input) {
val leftHalf = line.subSequence(0, line.length / 2)
val rightHalf = line.subSequence(line.length / 2, line.length)
total += findCommonInt(leftHalf.map(::charToInt), rightHalf.map(::charToInt))
}
return total
}
fun part2(input: List<String>): Int {
var total: Int = 0
for(lineIndex in 0..input.size - 1 step 3) {
val inputStrings = input.subList(lineIndex, lineIndex + 3)
total += findCommonInt(inputStrings.map{it.map(::charToInt)})
}
return total
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03","Day03_test")
check(part1(testInput) == 157)
val input = readInput("Day03","Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 750bde9b51b425cda232d99d11ce3d6a9dd8f801 | 2,102 | advent-of-code-2022 | Apache License 2.0 |
gcj/y2023/farewell_d/a_small.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package gcj.y2023.farewell_d
private fun solve(): String {
val (nLeft, nRight, c) = readInts()
val (leftIn, rightIn) = List(2) { readInts().map { it - 1 } }
val n = nLeft + nRight
return List(c) {
val (cu, cvIn) = readInts().map { it - 1 }
val cv = nLeft + cvIn
val nei = List(n) { mutableListOf<Int>() }
fun addEdge(u: Int, v: Int) { nei[u].add(v); nei[v].add(u) }
addEdge(cu, cv)
for (i in leftIn.indices) addEdge(i, leftIn[i])
for (i in rightIn.indices) addEdge(nLeft + i, nLeft + rightIn[i])
// val all = LongArray(n)
// val down = LongArray(n)
var ans = 0L
val size = IntArray(n) { 1 }
fun dfs(v: Int, p: Int) {
for (u in nei[v]) if (u != p) {
dfs(u, v)
size[v] += size[u]
ans += size[u].toLong() * (n - size[u])
// down[v] += down[u] + size[u]
}
}
dfs(0, -1)
ans * 2.0 / (n * (n - 1L))
}.joinToString(" ")
}
fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,128 | competitions | The Unlicense |
src/Day03.kt | makohn | 571,699,522 | false | {"Kotlin": 35992} | fun main() {
fun part1(input: List<String>): Int {
val items = mutableListOf<Char>()
for (r in input) {
outer@for (c in 0 until r.length/2) {
for (c2 in r.length/2 until r.length) {
if (r[c] == r[c2]) {
items.add(r[c])
break@outer
}
}
}
}
return items.sumOf { if (it.isUpperCase()) it - 'A' + 27 else it - 'a' + 1 }
}
fun part2(input: List<String>): Int {
val scores = mutableListOf<Int>()
for (r in input.indices step 3) {
val s1 = input[r].toList().toSet()
val s2 = input[r+1].toList().toSet()
val s3 = input[r+2].toList().toSet()
val res = s1.intersect(s2).intersect(s3)
scores.add(res.map { if (it.isUpperCase()) it - 'A' + 27 else it - 'a' + 1 }[0])
}
return scores.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 2734d9ea429b0099b32c8a4ce3343599b522b321 | 1,245 | aoc-2022 | Apache License 2.0 |
src/Day04.kt | kprow | 573,685,824 | false | {"Kotlin": 23005} | fun main() {
class SectionAssignment {
val start: Int
val end: Int
val sequence: IntArray
constructor(assignment: String) {
val startEnd = assignment.split("-")
this.start = startEnd[0].toInt()
this.end = startEnd[1].toInt()
this.sequence = IntRange(start, end).step(1).toList().toIntArray()
}
fun contains(section: SectionAssignment): Boolean {
if (start <= section.start && end >= section.end) {
return true
}
return false
}
fun hasOverlap(section: SectionAssignment): Boolean {
var bothSequences = sequence + section.sequence
if (bothSequences.distinct().count() < sequence.count() + section.sequence.count()) {
return true
}
return false
}
}
fun part1(input: List<String>): Int {
var fullyContainedCount = 0
for (pair in input) {
val assignmentStrings = pair.split(",")
val first = SectionAssignment(assignmentStrings[0])
val second = SectionAssignment(assignmentStrings[1])
if (first.contains(second) || second.contains(first)) {
fullyContainedCount += 1
}
}
return fullyContainedCount
}
fun part2(input: List<String>): Int {
var overlapCount = 0
for (pair in input) {
val assignmentStrings = pair.split(",")
val first = SectionAssignment(assignmentStrings[0])
val second = SectionAssignment(assignmentStrings[1])
if (first.hasOverlap(second)) {
overlapCount += 1
}
}
return overlapCount
}
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
val input = readInput("Day04")
println(part1(input))
check(part2(testInput) == 4)
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 9a1f48d2a49aeac71fa948656ae8c0a32862334c | 1,974 | AdventOfCode2022 | Apache License 2.0 |
src/Day03.kt | rtperson | 434,792,067 | false | {"Kotlin": 6811} | fun main() {
fun countBitN(input: List<String>, n: Int): Int {
var ones = 0
var zeroes = 0
for (y in input.indices) {
when (input[y][n]) {
'0' -> zeroes++
'1' -> ones++
}
}
if (zeroes > ones) return 0 else return 1
}
fun gammaToEpsilon(gamma: String) : String {
var epsilon = ""
for (x in gamma.indices) {
when (gamma[x]) {
'0' -> epsilon += "1"
'1' -> epsilon += "0"
}
}
return epsilon
}
fun filterOnPosition(input: List<String>, pos: Int, num: Char): List<String> {
return input.filter{ it[pos] == num }
}
fun part1(input: List<String>): Int {
var gamma = ""
for (x in input[0].indices) {
val newbit = countBitN(input, x)
gamma += newbit
}
val epsilon = gammaToEpsilon(gamma)
println("gamma: $gamma, epsilon: $epsilon")
return gamma.toInt(2) * epsilon.toInt(2)
}
fun part2(input: List<String>): Int {
var o2 = input
var x = 0
while (o2.size > 1) {
when(countBitN(o2, x)) {
1 -> o2 = filterOnPosition(o2, x++, '1')
0 -> o2 = filterOnPosition(o2, x++, '0')
}
}
var co2 = input
x = 0
while (co2.size > 1) {
when(countBitN(co2, x)) {
1 -> co2 = filterOnPosition(co2, x++, '0')
0 -> co2 = filterOnPosition(co2, x++, '1')
}
}
return o2[0].toInt(2) * co2[0].toInt(2)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(countBitN(testInput, 0) == 1)
println(filterOnPosition(testInput, 0, '1'))
check(part1(testInput) == 198)
check(part2(testInput) == 230)
// println(part2(testInput) )
// check(part2(testInput) == 198)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | ae827a46c8aba336a7d46762f4e1a94bc1b9d850 | 2,098 | Advent_of_Code_Kotlin | Apache License 2.0 |
src/main/kotlin/com/hjk/advent22/Day05.kt | h-j-k | 572,485,447 | false | {"Kotlin": 26661, "Racket": 3822} | package com.hjk.advent22
object Day05 {
fun part1(input: List<String>): String = process(input) { it.reversed() }
fun part2(input: List<String>): String = process(input) { it }
private fun process(input: List<String>, mapper: (String) -> String): String {
val (stacks, instructions) = input.indexOf("").let { input.take(it) to input.drop(it + 1) }
return instructions.mapNotNull(Move::parse).fold(convertStacks(stacks)) { acc, move ->
val from = acc[move.from - 1]
val to = acc[move.to - 1]
acc[move.from - 1] = from.dropLast(move.n)
acc[move.to - 1] = to + mapper(from.takeLast(move.n))
acc
}.joinToString(separator = "") { it[it.lastIndex].toString() }
}
private fun convertStacks(stacks: List<String>): MutableList<String> =
(1..stacks.last().count { it.isDigit() })
.map { (it - 1) * 4 + 1 }
.map { i ->
List(stacks.size - 1) { j ->
stacks[stacks.lastIndex - 1 - j].getOrNull(i) ?: ' '
}.filter { it.isLetter() }.joinToString(separator = "")
}.toMutableList()
private data class Move(val n: Int, val from: Int, val to: Int) {
companion object {
private val pattern = "move (\\d+) from (\\d+) to (\\d+)".toRegex()
fun parse(instruction: String): Move? =
pattern.matchEntire(instruction)?.destructured
?.let { (n, from, to) -> Move(n = n.toInt(), from = from.toInt(), to = to.toInt()) }
}
}
}
| 0 | Kotlin | 0 | 0 | 20d94964181b15faf56ff743b8646d02142c9961 | 1,586 | advent22 | Apache License 2.0 |
src/Day04.kt | ZiomaleQ | 573,349,910 | false | {"Kotlin": 49609} | fun main() {
fun part1(input: List<String>): Int {
var summary = 0
for (line in input) {
val (first, second) = line.split(',').let { Pair(it[0], it[1]) }
val firstRange = first.split('-').let { it[0].toInt()..it[1].toInt() }
val secondRange = second.split('-').let { it[0].toInt()..it[1].toInt() }
val isInFirst = firstRange.fold(true) { sum, curr -> curr in secondRange && sum }
val isInSecond = secondRange.fold(true) { sum, curr -> curr in firstRange && sum }
if (isInFirst || isInSecond) {
summary++
}
}
return summary
}
fun part2(input: List<String>): Int {
var summary = 0
for (line in input) {
val (first, second) = line.split(',').let { Pair(it[0], it[1]) }
val firstRange = first.split('-').let { it[0].toInt()..it[1].toInt() }
val secondRange = second.split('-').let { it[0].toInt()..it[1].toInt() }
val isThere = firstRange.any { secondRange.contains(it) }
if (isThere) {
summary++
}
}
return summary
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | b8811a6a9c03e80224e4655013879ac8a90e69b5 | 1,465 | aoc-2022 | Apache License 2.0 |
day11/part2.kts | bmatcuk | 726,103,418 | false | {"Kotlin": 214659} | // --- Part Two ---
// The galaxies are much older (and thus much farther apart) than the
// researcher initially estimated.
//
// Now, instead of the expansion you did before, make each empty row or column
// one million times larger. That is, each empty row should be replaced with
// 1000000 empty rows, and each empty column should be replaced with 1000000
// empty columns.
//
// (In the example above, if each empty row or column were merely 10 times
// larger, the sum of the shortest paths between every pair of galaxies would
// be 1030. If each empty row or column were merely 100 times larger, the sum
// of the shortest paths between every pair of galaxies would be 8410. However,
// your universe will need to expand far beyond these values.)
//
// Starting with the same initial image, expand the universe according to these
// new rules, then find the length of the shortest path between every pair of
// galaxies. What is the sum of these lengths?
import java.io.*
import kotlin.math.absoluteValue
// Instead of actually expanding the photo, just calculate a map of indexes for
// each row and column, as if the photo had been expanded.
val photo = File("input.txt").readLines()
val emptyRows = photo.foldIndexed(mutableListOf<Int>(0)) { idx, acc, row ->
acc.also {
if (!row.contains('#')) {
it.add(idx)
}
}
}
emptyRows.add(photo.size)
val emptyCols = (0..<photo[0].length).fold(mutableListOf<Int>(0)) { acc, idx ->
acc.also {
if (!photo.any { it[idx] == '#' }) {
it.add(idx)
}
}
}
emptyCols.add(photo[0].length)
// build list of galaxies
val rowIdxs = emptyRows.zipWithNext().withIndex().flatMap { (adj, pair) -> (pair.first + adj * 999999L)..<(pair.second + adj * 999999L) }
val colIdxs = emptyCols.zipWithNext().withIndex().flatMap { (adj, pair) -> (pair.first + adj * 999999L)..<(pair.second + adj * 999999L) }
val galaxies = photo.zip(rowIdxs).flatMap { (row, y) ->
row.toList().zip(colIdxs).filter { (pixel, _) -> pixel == '#' }.map { (_, x) -> x to y }
}
// calculate shortest paths
val result = galaxies.withIndex().sumOf { (i, a) ->
galaxies.subList(i + 1, galaxies.size).sumOf { b -> (b.first - a.first).absoluteValue + (b.second - a.second).absoluteValue }
}
println(result)
| 0 | Kotlin | 0 | 0 | a01c9000fb4da1a0cd2ea1a225be28ab11849ee7 | 2,246 | adventofcode2023 | MIT License |
src/Day04.kt | sbaumeister | 572,855,566 | false | {"Kotlin": 38905} | fun main() {
fun part1(input: List<String>): Int {
var count = 0
input.forEach { line ->
val (range1, range2) = line.split(",").map { assignment ->
assignment.split("-").map { it.toInt() }.let { (it.first()..it.last()) }
}
if ((range1.first <= range2.first && range1.last >= range2.last)
|| (range2.first <= range1.first && range2.last >= range1.last)
) {
count++
}
}
return count
}
fun part2(input: List<String>): Int {
var count = 0
input.forEach { line ->
val (range1, range2) = line.split(",").map { assignment ->
assignment.split("-").map { it.toInt() }.let { (it.first()..it.last()) }
}
if (range1.intersect(range2).isNotEmpty()) {
count++
}
}
return count
}
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e3afbe3f4c2dc9ece1da7cf176ae0f8dce872a84 | 1,135 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | muellerml | 573,601,715 | false | {"Kotlin": 14872} | fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { line ->
val split = line.count() / 2
val first = line.take(split)
val last = line.takeLast(split)
val character = first.first { last.contains(it) }
val value = character.getValue()
value
}
}
fun part2(input: List<String>): Int {
return input.windowed(3, step = 3).sumOf { list ->
val first = list[0]
first.first { list[1].contains(it) && list[2].contains(it) }.getValue()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day03_test")
val result = part1(testInput)
check(result == 157)
val input = readInput("day03")
println("Part1: " + part1(input))
val result2 = part2(testInput)
check(result2 == 70)
println("Part2: " + part2(input))
}
fun Char.getValue() = if (this.isUpperCase()) this.minus('A') + 27 else this.minus('a') + 1
| 0 | Kotlin | 0 | 0 | 028ae0751d041491009ed361962962a64f18e7ab | 1,044 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/aoc2021/Day01.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2021
import readInput
import java.util.*
/**
* @return a sequence of the result of the [compareTo] invocation on each element and its predecessor
*/
private fun <T : Comparable<T>> Sequence<T>.compareWithPrevious(): Sequence<Int> {
val input = this
return sequence {
yield(0)
var previous = input.first()
input.drop(1).forEach {
yield(it.compareTo(previous))
previous = it
}
}
}
/**
* Represents a sliding window of measurement data.
*
* @property measurements all the measurements in this window. New measurements can be added using the [add] method
*/
private data class MeasurementWindow(private val measurements: MutableList<Int> = mutableListOf()) :
Comparable<MeasurementWindow> {
override fun compareTo(other: MeasurementWindow) = measurements.sum().compareTo(other.measurements.sum())
fun add(measurement: Int) = measurements.add(measurement)
}
private fun part1(input: List<Int>) = input.asSequence().compareWithPrevious().count { it > 0 }
private fun part2(input: List<Int>): Int {
val windows = 3
val windowQueue: Queue<MeasurementWindow> = ArrayDeque(windows)
val windowSequence = sequence {
input.forEach { measurement ->
// add measurement to all active windows
windowQueue.forEach { it.add(measurement) }
// special case to handle the first few measurements, where we don't have enough windows yet
if (windowQueue.size == windows) {
// remove & emit the first (full) window
windowQueue.poll()?.run {
yield(this)
}
}
// add new empty window at the end
windowQueue.add(MeasurementWindow())
}
}
return windowSequence.compareWithPrevious().count { it > 0 }
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test").map { it.toInt() }
check(part1(testInput) == 7)
check(part2(testInput) == 5)
val input = readInput("Day01").map { it.toInt() }
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 2,188 | adventOfCode | Apache License 2.0 |
solutions/aockt/y2021/Y2021D17.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2021
import io.github.jadarma.aockt.core.Solution
import kotlin.math.absoluteValue
import kotlin.math.sign
object Y2021D17 : Solution {
/** Represents a discrete point in 2D space. */
private data class Point(val x: Int, val y: Int)
/** Generates the sequence of all the triangular numbers that fit in an [Int] */
private fun triangularNumbers(): Sequence<Int> = (0 until 46341).asSequence().map { n -> n * (n + 1) / 2 }
/** Simulates launching a projectile from the origin of (0,0) with a [launchVelocity] vector. */
private fun simulateTrajectory(launchVelocity: Point): Sequence<Point> = sequence {
var (dx, dy) = launchVelocity
var point = Point(0, 0).also { yield(it) }
while (true) {
point = Point(point.x + dx, point.y + dy).also { yield(it) }
dx += -1 * dx.sign
dy -= 1
}
}
/**
* Calculates all the possible launch velocities such that, if shot from the origin, a projectile would pass through
* the [target]. For every possibility, returns the initial velocity and the path the projectile would take.
*/
private fun generateTrajectories(target: Pair<Point, Point>): Sequence<Pair<Point, List<Point>>> = sequence {
val minimumXMagnitude = triangularNumbers().indexOfFirst { it >= target.first.x }
val maximumYMagnitude = target.second.y.absoluteValue - 1
val xRange = minimumXMagnitude..target.second.x
val yRange = target.second.y..maximumYMagnitude
val sanityIterationLimit = xRange.last + yRange.last
fun Point.isInBounds() = x in target.first.x..target.second.x && y in target.second.y..target.first.y
for (x in xRange) {
for (y in yRange) {
val velocity = Point(x, y)
val path = simulateTrajectory(velocity)
.take(sanityIterationLimit)
.takeWhile { point -> point.x <= target.second.x && point.y >= target.second.y }
.toList()
if (path.last().isInBounds()) yield(velocity to path)
}
}
}
/** Parse the input and return the target area for the probe to visit. */
private fun parseInput(input: String): Pair<Point, Point> = runCatching {
val regex = Regex("""^target area: x=(-?\d+)\.\.(-?\d+), y=(-?\d+)\.\.(-?\d+)$""")
val (xl, xh, yl, yh) = regex.matchEntire(input)!!.groupValues.drop(1).map { it.toInt() }
require(xl < xh && yl < yh)
require(xl >= 0) { "We only assume positive values of X. Transform your cartesian and try again." }
require(yh <= 0) { "We only assume negative values of Y. Is your trench above sea level?" }
return Point(xl, yh) to Point(xh, yl)
}.getOrElse { throw IllegalArgumentException("Invalid input", it) }
override fun partOne(input: String) =
parseInput(input).let {
val maxYValue = it.second.y.absoluteValue - 1
triangularNumbers().drop(maxYValue).first()
}
override fun partTwo(input: String) =
parseInput(input)
.let(this::generateTrajectories)
.count()
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 3,186 | advent-of-code-kotlin-solutions | The Unlicense |
src/day02/Day02.kt | sanyarajan | 572,663,282 | false | {"Kotlin": 24016} | package day02
import readInput
enum class RPSOptions {
ROCK, PAPER, SCISSORS;
companion object {
fun beatenBy(rpsOptions: RPSOptions): RPSOptions {
return when (rpsOptions) {
ROCK -> PAPER
PAPER -> SCISSORS
SCISSORS -> ROCK
}
}
}
}
enum class CodeOptions {
A, B, C, X, Y, Z;
companion object {
fun valueToRPS(option: CodeOptions): RPSOptions {
return when (option) {
A -> RPSOptions.ROCK
X -> RPSOptions.ROCK
B -> RPSOptions.PAPER
Y -> RPSOptions.PAPER
C -> RPSOptions.SCISSORS
Z -> RPSOptions.SCISSORS
}
}
}
}
enum class DesiredOutcome {
WIN, LOSE, DRAW;
companion object {
fun getDesiredOutcome(s: String): DesiredOutcome {
return when (s) {
"Z" -> WIN
"X" -> LOSE
"Y" -> DRAW
else -> throw IllegalArgumentException("Invalid option")
}
}
}
}
class RPSValues {
companion object {
private var rock = 1
private var paper = 2
private var scissors = 3
fun getValue(playerOption: RPSOptions): Int {
return when (playerOption) {
RPSOptions.ROCK -> rock
RPSOptions.PAPER -> paper
RPSOptions.SCISSORS -> scissors
}
}
}
}
fun main() {
val inputLineRegex = """([ABC]) ([XYZ])""".toRegex()
fun part1(input: List<String>): Int {
var score = 0
input.forEach { line ->
val (opponent, player) = inputLineRegex.matchEntire(line)!!.destructured
val opponentOption = CodeOptions.valueToRPS(CodeOptions.valueOf(opponent))
val playerOption = CodeOptions.valueToRPS(CodeOptions.valueOf(player))
score += when {
opponentOption == playerOption -> {
3 + RPSValues.getValue(playerOption)
}
(opponentOption == RPSOptions.ROCK && playerOption == RPSOptions.SCISSORS) || (opponentOption == RPSOptions.PAPER && playerOption == RPSOptions.ROCK) || (opponentOption == RPSOptions.SCISSORS && playerOption == RPSOptions.PAPER) -> {
RPSValues.getValue(playerOption)
}
else -> {
6 + RPSValues.getValue(playerOption)
}
}
}
return score
}
fun part2(input: List<String>): Int {
var score = 0
input.forEach { line ->
val (opponent, outcome) = inputLineRegex.matchEntire(line)!!.destructured
val opponentOption = CodeOptions.valueToRPS(CodeOptions.valueOf(opponent))
//convert outcome to DesiredOutcome
val desiredOutcome = DesiredOutcome.getDesiredOutcome(outcome)
score += when (desiredOutcome) {
DesiredOutcome.DRAW -> {
3 + RPSValues.getValue(opponentOption)
}
DesiredOutcome.WIN -> {
6 + RPSValues.getValue(RPSOptions.beatenBy(opponentOption))
}
DesiredOutcome.LOSE -> {
RPSValues.getValue(RPSOptions.beatenBy(RPSOptions.beatenBy(opponentOption)))
}
}
}
return score
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day02/Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("day02/day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e23413357b13b68ed80f903d659961843f2a1973 | 3,752 | Kotlin-AOC-2022 | Apache License 2.0 |
src/main/kotlin/Day01V2Simplified.kt | rgawrys | 572,698,359 | false | {"Kotlin": 20855} | import utils.readRawInput
fun main() {
fun part1(input: String): Int = maxCaloriesOfElves(input)
fun part2(input: String): Int = sumCaloriesOfTopElves(input, 3)
// test if implementation meets criteria from the description, like:
val testInput = readRawInput("Day01_test")
part1(testInput).let {
check(it == 24000) { "Part 1: Incorrect result. Is `$it`, but should be `24000`" }
}
part2(testInput).let {
check(it == 45000) { "Part 2: Incorrect result. Is `$it`, but should be `45000`" }
}
val input = readRawInput("Day01")
println(part1(input))
println(part2(input))
}
private fun sumCaloriesOfTopElves(input: String, top: Int): Int =
input
.toCaloriesByElves()
.sortedByDescending { it }
.take(top)
.sum()
private fun maxCaloriesOfElves(input: String): Int =
input
.toSnacksByElves()
.maxOf(List<Int>::sum)
private fun String.toCaloriesByElves(): List<Int> =
this
.split("\n\n")
.map { it.lines().sumOf(String::toInt) }
private fun String.toSnacksByElves(): List<List<Int>> =
this
.split("\n\n")
.map { it.lines().map(String::toInt) }
| 0 | Kotlin | 0 | 0 | 5102fab140d7194bc73701a6090702f2d46da5b4 | 1,199 | advent-of-code-2022 | Apache License 2.0 |
src/Day11.kt | Kvest | 573,621,595 | false | {"Kotlin": 87988} | import java.util.*
fun main() {
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158L)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Long {
val monkeys = input.toMonkeys()
val worryLevelAdjuster = WorryLevelAdjuster { worryLevel ->
worryLevel / 3
}
return solve(monkeys, roundsCount = 20, worryLevelAdjuster)
}
private fun part2(input: List<String>): Long {
val monkeys = input.toMonkeys()
//Use divider in order to avoid overflow of the worryLevel's variable
val divider = monkeys.fold(1L) { acc, monkey -> acc * monkey.test.testValue }
val worryLevelAdjuster = WorryLevelAdjuster { worryLevel ->
worryLevel % divider
}
return solve(monkeys, roundsCount = 10_000, worryLevelAdjuster)
}
private fun solve(
monkeys: List<Monkey>,
roundsCount: Int,
worryLevelAdjuster: WorryLevelAdjuster
): Long {
val counts = LongArray(monkeys.size) { 0 }
val redirectListener = RedirectListener { monkeyNumber, worryLevel ->
monkeys[monkeyNumber].items.addLast(worryLevel)
}
repeat(roundsCount) {
monkeys.forEachIndexed { index, monkey ->
//monkey will inspect "monkey.items.size" in this round
counts[index] += monkey.items.size.toLong()
monkey.round(worryLevelAdjuster, redirectListener)
}
}
counts.sortDescending()
return counts[0] * counts[1]
}
private fun List<String>.toMonkeys(): List<Monkey> = this.chunked(7).map(List<String>::toMonkey)
private fun List<String>.toMonkey(): Monkey {
val initialItems = this[1]
.substringAfter("Starting items: ")
.split(", ")
.map { it.toLong() }
val operation = Operation.fromString(this[2])
val testValue = this[3].substringAfter("Test: divisible by ").toLong()
val trueDestination = this[4].substringAfter("If true: throw to monkey ").toInt()
val falseDestination = this[5].substringAfter("If false: throw to monkey ").toInt()
val test = Test(
testValue = testValue,
trueDestination = trueDestination,
falseDestination = falseDestination
)
return Monkey(initialItems, operation, test)
}
private fun interface RedirectListener {
fun redirect(monkeyNumber: Int, worryLevel: Long)
}
private fun interface WorryLevelAdjuster {
fun adjust(worryLevel: Long): Long
}
private class Monkey(
initialItems: List<Long>,
val operation: Operation,
val test: Test
) {
val items = LinkedList(initialItems)
fun round(worryLevelAdjuster: WorryLevelAdjuster, redirectListener: RedirectListener) {
while (items.isNotEmpty()) {
var worryLevel = items.pollFirst()
worryLevel = operation.perform(worryLevel)
worryLevel = worryLevelAdjuster.adjust(worryLevel)
val monkeyNumber = test.test(worryLevel)
redirectListener.redirect(monkeyNumber, worryLevel)
}
}
}
sealed interface Operation {
fun perform(worryLevel: Long): Long
companion object {
fun fromString(operation: String): Operation {
return when {
operation.contains("Operation: new = old * old") -> SqrOperation
operation.contains("Operation: new = old +") -> AdditionOperation(
incValue = operation.substringAfter("Operation: new = old + ").toLong()
)
operation.contains("Operation: new = old *") -> MultiplicationOperation(
factor = operation.substringAfter("Operation: new = old * ").toLong()
)
else -> error("Unknown operation $operation")
}
}
}
class AdditionOperation(private val incValue: Long) : Operation {
override fun perform(worryLevel: Long): Long = worryLevel + incValue
}
class MultiplicationOperation(private val factor: Long) : Operation {
override fun perform(worryLevel: Long): Long = worryLevel * factor
}
object SqrOperation : Operation {
override fun perform(worryLevel: Long): Long = worryLevel * worryLevel
}
}
private class Test(
val testValue: Long,
val trueDestination: Int,
val falseDestination: Int,
) {
fun test(worryLevel: Long): Int = if (worryLevel % testValue == 0L) trueDestination else falseDestination
} | 0 | Kotlin | 0 | 0 | 6409e65c452edd9dd20145766d1e0ea6f07b569a | 4,478 | AOC2022 | Apache License 2.0 |
y2017/src/main/kotlin/adventofcode/y2017/Day16.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2017
import adventofcode.io.AdventSolution
import adventofcode.util.collections.takeWhileDistinct
object Day16 : AdventSolution(2017, 16, "Permutation Promenade") {
override fun solvePartOne(input: String): String = dance(parseInput(input), "abcdefghijklmnop")
//There's actually a small upper bound for the loop size! Landau's Function
override fun solvePartTwo(input: String): String {
val danceMoves: List<Action> = parseInput(input)
val orderings = generateSequence("abcdefghijklmnop") { dance(danceMoves, it) }
.takeWhileDistinct()
.toList()
val remainder = (1_000_000_000 % orderings.size)
return orderings[remainder]
}
private fun parseInput(input: String): List<Action> = input.split(",")
.map { move ->
when (move[0]) {
's' -> Action.Spin(move.substring(1).toInt())
'x' -> move.substring(1).split('/').let { Action.Exchange(it[0].toInt(), it[1].toInt()) }
'p' -> Action.Promenade(move[1], move[3])
else -> throw IllegalArgumentException("$move is not a dance move")
}
}
private fun dance(moves: List<Action>, initialPositions: String) =
moves.fold(initialPositions) { acc, action -> action.execute(acc) }
}
private sealed class Action {
abstract fun execute(programs: String): String
class Spin(private val n: Int) : Action() {
override fun execute(programs: String) = programs.takeLast(n) + programs.dropLast(n)
}
class Exchange(private val i1: Int, private val i2: Int) : Action() {
override fun execute(programs: String): String {
val exchanged = programs.toCharArray()
exchanged[i1] = programs[i2]
exchanged[i2] = programs[i1]
return String(exchanged)
}
}
class Promenade(private val p1: Char, private val p2: Char) : Action() {
override fun execute(programs: String): String {
val promenaded = programs.toCharArray()
val i1 = programs.indexOf(p1)
val i2 = programs.indexOf(p2)
promenaded[i1] = programs[i2]
promenaded[i2] = programs[i1]
return String(promenaded)
}
}
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 2,024 | advent-of-code | MIT License |
src/main/kotlin/aoc2022/Day11.kt | w8mr | 572,700,604 | false | {"Kotlin": 140954} | package aoc2022
import aoc.*
import aoc.parser.*
class Day11 {
sealed class Argument {
data class Number(val value: Long) : Argument()
object Old : Argument()
}
data class Monkey(
val index: Int,
var items: List<Long>,
val operator: Pair<(Long, Long) -> Long, Argument>,
val divisibleBy : Int,
val ifTrue : Int,
val ifFalse: Int,
var inspected: Int = 0)
// Monkey 0:
// Starting items: 79, 98
// Operation: new = old * 19
// Test: divisible by 23
// If true: throw to monkey 2
// If false: throw to monkey 3
val index = "Monkey " followedBy number() followedBy ":\n"
val itemNumbers = number() map { it.toLong() } sepBy ", "
val items = " Starting items: " followedBy itemNumbers followedBy "\n"
val plus = "+ " asValue { n: Long, m: Long -> n + m }
val times = "* " asValue { n: Long, m: Long -> n * m }
val numberArgument = number() map { Argument.Number(it.toLong()) }
val oldArgument = literal("old") asValue Argument.Old
val operation = seq(" Operation: new = old " followedBy (plus or times), numberArgument or oldArgument) followedBy "\n"
val divisibleBy = " Test: divisible by " followedBy number() followedBy "\n"
val ifTrue = " If true: throw to monkey " followedBy number() followedBy "\n"
val ifFalse = " If false: throw to monkey " followedBy number() followedBy "\n"
val monkey = seq(index, items, operation, divisibleBy, ifTrue, ifFalse, ::Monkey)
val monkeys = monkey sepBy "\n"
fun solve(input: String, n: Int, d: Int): Long {
val parsed = monkeys.parse(input)
val ring = parsed.map(Monkey::divisibleBy).product()
(1..n).forEach {
parsed.forEach {
it.items.forEach { item ->
val right: Long = when (val r = it.operator.second) {
is Argument.Number -> r.value
is Argument.Old -> item
}
val new = (it.operator.first(item, right) / d) % ring
if (new % it.divisibleBy == 0L) {
parsed[it.ifTrue].items += new
} else {
parsed[it.ifFalse].items += new
}
}
it.inspected += it.items.size
it.items = listOf()
}
}
val inspectedMost = parsed.map(Monkey::inspected).sortedDescending().take(2)
return inspectedMost[0].toLong() * inspectedMost[1]
}
fun part1(input: String): Long {
return solve(input, 20, 3)
}
fun part2(input: String): Long {
return solve(input, 10000, 1)
}
}
| 0 | Kotlin | 0 | 0 | e9bd07770ccf8949f718a02db8d09daf5804273d | 2,779 | aoc-kotlin | Apache License 2.0 |
src/Day04.kt | jamesrobert | 573,249,440 | false | {"Kotlin": 13069} | typealias Section = Pair<Int, Int>
fun main() {
fun parseSectionRange(item: String): Section =
item.split('-')
.map { it.toInt() }
.let { (first, second) -> Pair(first, second) }
fun calculateOverlap(input: List<String>, compare: (Section, Section) -> Int?): Int =
input.map {
it.split(',')
.let { (first, second) ->
val left = parseSectionRange(first)
val right = parseSectionRange(second)
compare(left, right) ?: compare(right, left) ?: 0
}
}.sumOf { it }
fun part1(input: List<String>): Int {
fun compare(left: Section, right: Section) =
if (left.first <= right.first && left.second >= right.second) 1 else null
return calculateOverlap(input, ::compare)
}
fun part2(input: List<String>): Int {
fun compare(left: Section, right: Section): Int? =
if ((right.first in left.first..left.second) ||
(right.second in left.first..left.second)
) 1 else null
return calculateOverlap(input, ::compare)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | d0b49770fc313ae42d802489ec757717033a8fda | 1,435 | advent-of-code-2022 | Apache License 2.0 |
2021/src/main/kotlin/com/github/afranken/aoc/Day202104.kt | afranken | 434,026,010 | false | {"Kotlin": 28937} | package com.github.afranken.aoc
object Day202104 {
fun part1(inputs: Array<String>): Int {
val draws = inputs[0].split(',')
val boards = inputs
.drop(1)
.filter { it.isNotEmpty() }
.chunked(5)
.map {
Board.of(it.map {
it.split(" ", " ")
.filter { it.isNotBlank() } // Leading whitespace
.map { it.toInt() }
})
}
for (draw in draws) {
boards.forEach { it.markField(Integer.valueOf(draw)) }
val bingoBoard = boards.firstOrNull { it.isBingo() }
if (bingoBoard != null) {
return bingoBoard.getUnmarked().sum() * Integer.valueOf(draw)
}
}
return -1
}
fun part2(inputs: Array<String>): Int {
val draws = inputs[0].split(',')
var boards = inputs
.drop(1)
.filter { it.isNotEmpty() }
.chunked(5)
.map {
Board.of(it.map {
it.split(" ", " ")
.filter { it.isNotBlank() } // Leading whitespace
.map { it.toInt() }
})
}
for ((count, draw) in draws.withIndex()) {
boards.forEach { it.markField(Integer.valueOf(draw)) }
boards.filter { it.isBingo() }
.forEach {
// there are 100 draws. If this is not the last board, it's still the last one to win.
if (boards.size == 1 || count == 100) {
return it.getUnmarked().sum() * Integer.valueOf(draw)
}
boards = boards - it
}
}
return -1
}
data class Field(val value: Int, var marked: Boolean = false)
data class Board(val fields: List<MutableList<Field>>) {
private val widthIndices = fields[0].indices
private val heightIndices = fields.indices
companion object {
fun of(lines: List<List<Int>>): Board {
return Board(lines.map { it.map { Field(it) }.toMutableList() })
}
}
fun markField(value: Int) {
fields.forEach { it.filter { it.value == value }.forEach { it.marked = true } }
}
fun getUnmarked(): List<Int> {
return fields.flatten().filter { !it.marked }.map { it.value }
}
fun isBingo(): Boolean {
return checkColumnMarked() || checkRowMarked()
}
private fun checkRowMarked(): Boolean {
return fields.any { it.all { it.marked } }
}
private fun checkColumnMarked(): Boolean {
for (column in widthIndices) {
var columnMarked = true
for (row in heightIndices) {
if (!fields[row][column].marked) {
columnMarked = false
continue
}
}
if (columnMarked) return true
}
return false
}
}
}
| 0 | Kotlin | 0 | 0 | 0140f68e60fa7b37eb7060ade689bb6634ba722b | 3,171 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/SumOfFlooredPairs.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.MOD
import kotlin.math.min
/**
* 1862. Sum of Floored Pairs
* @see <a href="https://leetcode.com/problems/sum-of-floored-pairs/">Source</a>
*/
fun interface SumOfFlooredPairs {
operator fun invoke(nums: IntArray): Int
}
class SumOfFlooredPairsBF : SumOfFlooredPairs {
override operator fun invoke(nums: IntArray): Int {
val counts = IntArray(MAX + 1)
for (num in nums) {
++counts[num]
}
for (i in 1..MAX) {
counts[i] += counts[i - 1]
}
var total: Long = 0
for (i in 1..MAX) {
if (counts[i] > counts[i - 1]) {
var sum: Long = 0
var j = 1
while (i * j <= MAX) {
val lower = i * j - 1
val upper = i * (j + 1) - 1
sum += (counts[min(upper, MAX)] - counts[lower]) * j.toLong()
++j
}
total = (total + sum % MOD * (counts[i] - counts[i - 1])) % MOD
}
}
return total.toInt()
}
companion object {
private const val MAX = 1e5.toInt()
}
}
class SumOfFlooredPairsBF2 : SumOfFlooredPairs {
override operator fun invoke(nums: IntArray): Int {
val max: Int = nums.max()
val preSum = IntArray(max + 1)
for (num in nums) preSum[num]++
for (i in 1..max) preSum[i] += preSum[i - 1]
var ans = 0
for (i in 1..max) {
if (preSum[i] > preSum[i - 1]) {
val count = preSum[i] - preSum[i - 1]
var j = 1
while (i * j <= max) {
ans = (ans + count * j * (preSum[min(max, i * (j + 1) - 1)] - preSum[i * j - 1])) % MOD
j++
}
}
}
return ans
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,500 | kotlab | Apache License 2.0 |
src/Day05.kt | roxanapirlea | 572,665,040 | false | {"Kotlin": 27613} | private data class Procedure(val count: Int, val from: Int, val to: Int)
fun main() {
fun String.getStackedCrates(): List<ArrayDeque<Char>> {
val linesOfCrates = substringBefore("${System.lineSeparator()}${System.lineSeparator()}")
.split(System.lineSeparator())
.map {
it.chunked(4).map { crate -> crate[1] }
}
val maxSize = linesOfCrates.last().size
val stacks = List<ArrayDeque<Char>>(maxSize) { ArrayDeque(listOf()) }
linesOfCrates.forEach { line ->
line.forEachIndexed { i, crate ->
if (crate != ' ') stacks[i].addFirst(crate)
}
}
return stacks
}
fun String.getProcedure(): List<Procedure> {
return substringAfter("${System.lineSeparator()}${System.lineSeparator()}")
.split(System.lineSeparator())
.map {
val count = it.substringAfter("move ")
.substringBefore(" from")
.toInt()
val from = it.substringAfter("from ")
.substringBefore(" to")
.toInt()
val to = it.substringAfter("to ")
.toInt()
Procedure(count, from, to)
}
}
fun part1(input: String): String {
val stacks = input.getStackedCrates()
input.getProcedure().forEach { procedure ->
repeat(procedure.count) {
val toMove = stacks[procedure.from - 1].removeLast()
stacks[procedure.to - 1].addLast(toMove)
}
}
return stacks.map { it.last() }.joinToString("")
}
fun part2(input: String): String {
val stacks = input.getStackedCrates()
input.getProcedure().forEach { procedure ->
val toMove = ArrayDeque<Char>()
repeat(procedure.count) {
toMove.add(stacks[procedure.from - 1].removeLast())
}
while (toMove.isNotEmpty()) {
val crate = toMove.removeLast()
stacks[procedure.to - 1].addLast(crate)
}
}
return stacks.map { it.last() }.joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = readText("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readText("Day05")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 6c4ae6a70678ca361404edabd1e7d1ed11accf32 | 2,504 | aoc-2022 | Apache License 2.0 |
Algorithms/Search/Minimum Loss/Solution.kt | ahmed-mahmoud-abo-elnaga | 449,443,709 | false | {"Kotlin": 14218} | /*
Problem: https://www.hackerrank.com/challenges/minimum-loss
Kotlin Language Version
Tool Version : Android Studio
Initial Thoughts: We can sort the array to reduce the number of comparisons since
we know that the absolute difference is always smallest between
adjacent elements in a sorted array. Then because we have the
stipulation that we must buy the house before we can sell it
we should verify that the buy price we are using is a price
that occurred in a year prior to the sell price year. We can
accomplish this by using a map that will be at most size n and
will store distinct key,value pairs where the key is the price
and the value is the year.
Time Complexity: O(n log(n)) //We must sort the input array
Space Complexity: O(n) //We use a map to store the price,year pairs*/
object Main {
/*
* Complete the 'minimumLoss' function below.
*
* The function is expected to return an INTEGER.
* The function accepts LONG_INTEGER_ARRAY price as parameter.
*/
fun minimumLoss(price: Array<Long>): Int {
// create hashmap to save item index
val indices: HashMap<Long, Int> = HashMap()
price.forEachIndexed { index, item ->
indices.put(item, index)
}
// sort Array Quick sort
price.sort()
var minLoss = Long.MAX_VALUE
for (i in 0..price.size - 2) {
// lose between two item
val loss = price[i + 1] - price[i]
if (loss < minLoss && (indices.getValue(price[i]) > indices.getValue(price[i + 1])))
minLoss = loss
}
return minLoss.toInt()
}
fun main(args: Array<String>) {
val n = readLine()!!.trim().toInt()
val price = readLine()!!.trimEnd().split(" ").map { it.toLong() }.toTypedArray()
val result = minimumLoss(price)
println(result)
}
}
| 0 | Kotlin | 1 | 1 | a65ee26d47b470b1cb2c1681e9d49fe48b7cb7fc | 2,048 | HackerRank | MIT License |
src/main/kotlin/aoc23/Day13.kt | tom-power | 573,330,992 | false | {"Kotlin": 254717, "Shell": 1026} | package aoc23
import aoc23.Day13Domain.PointOfIncidence
import aoc23.Day13Parser.toPointsOfIncidence
import common.Collections.partitionedBy
import common.Strings.transpose
import common.Year23
object Day13 : Year23 {
fun List<String>.part1(): Int =
toPointsOfIncidence(targetNumberOfDifferences = 0)
.summaryOfNotes()
fun List<String>.part2(): Int =
toPointsOfIncidence(targetNumberOfDifferences = 1)
.summaryOfNotes()
}
object Day13Domain {
data class PointOfIncidence(
private val notes: List<List<String>>,
private val targetNumberOfDifferences: Int
) {
fun summaryOfNotes(): Int =
notes.sumOf { note ->
note.linesAboveReflection()?.let { it * 100 }
?: note.transpose().linesAboveReflection()!!
}
private fun List<String>.linesAboveReflection(): Int? = this.let(::Note).linesAboveLineOfReflection()
private inner class Note(
private val lines: List<String>
) {
fun linesAboveLineOfReflection(): Int? =
lines
.mapIndexedNotNull { index, _ ->
index.takeIf {
index > 0
&& lines.differencesToEdgeFrom(index - 1 to index) == targetNumberOfDifferences
}
}
.firstOrNull()
private fun List<String>.differencesToEdgeFrom(indexes: Pair<Int, Int>): Int {
val firstLine = this.getOrNull(indexes.first)
val secondLine = this.getOrNull(indexes.second)
return when {
firstLine == null || secondLine == null -> 0
else ->
firstLine.numberOfDifferences(secondLine) +
differencesToEdgeFrom(indexes.first - 1 to indexes.second + 1)
}
}
private fun String.numberOfDifferences(other: String): Int =
this.zip(other).count { (a, b) -> a != b }
}
}
}
object Day13Parser {
fun List<String>.toPointsOfIncidence(targetNumberOfDifferences: Int): PointOfIncidence =
PointOfIncidence(
notes = this.partitionedBy(""),
targetNumberOfDifferences = targetNumberOfDifferences
)
}
| 0 | Kotlin | 0 | 0 | baccc7ff572540fc7d5551eaa59d6a1466a08f56 | 2,394 | aoc | Apache License 2.0 |
src/main/kotlin/y2023/day08/Day08.kt | TimWestmark | 571,510,211 | false | {"Kotlin": 97942, "Shell": 1067} | package y2023.day08
import NumberStuff
fun main() {
AoCGenerics.printAndMeasureResults(
part1 = { part1() },
part2 = { part2() }
)
}
data class Input(
val instruction: String,
val maps: Map<String, Pair<String,String>>
)
fun input(): Input {
val lines = AoCGenerics.getInputLines("/y2023/day08/input.txt")
val instruction = lines[0]
val mapLines = lines.subList(2, lines.size)
val maps = mapLines.associate {
val source = it.split("=")[0].trim()
val destL = it.split("=")[1].trim().split(",")[0].trim().split("(")[1].trim()
val destR = it.split("=")[1].trim().split(",")[1].trim().split(")")[0].trim()
source to Pair(destL, destR)
}
return Input(instruction, maps)
}
fun part1(): Int {
val input = input()
val instruction = input.instruction
val maps = input.maps
var currentLocation = "AAA"
var steps = 0
while (currentLocation != "ZZZ") {
val nextInstruction = instruction[steps % instruction.length]
currentLocation = when {
nextInstruction == 'L' -> maps[currentLocation]!!.first
else -> maps[currentLocation]!!.second
}
steps++
}
return steps
}
fun part2(): Long {
val input = input()
val currentPositions = input.maps.keys.filter { it.endsWith("A") }.toMutableList()
val steps = currentPositions.map { pos -> getSteps(pos, input) }
return NumberStuff.findLCMOfListOfNumbers(steps)
}
fun getSteps(start: String, input: Input ): Long {
val instruction = input.instruction
val maps = input.maps
var currentLocation = start
var steps = 0L
while (!currentLocation.endsWith("Z")) {
val nextInstruction = instruction[(steps % instruction.length).toInt()]
currentLocation = when {
nextInstruction == 'L' -> maps[currentLocation]!!.first
else -> maps[currentLocation]!!.second
}
steps++
}
return steps
}
| 0 | Kotlin | 0 | 0 | 23b3edf887e31bef5eed3f00c1826261b9a4bd30 | 1,998 | AdventOfCode | MIT License |
src/main/kotlin/utils/graphs/Graph.kt | Arch-vile | 433,381,878 | false | {"Kotlin": 57129} | package utils.graphs
import utils.SortedLookup
// Not immutable by any means
data class Node<T>(val value: T) {
val edges: MutableSet<Edge<T>> = mutableSetOf()
fun link(distance: Long, target: Node<T>) {
edges.add(Edge(distance, target))
}
fun link(distance: Long, targets: List<Node<T>>) {
targets.forEach { link(distance, it) }
}
fun biLink(distance: Long, targets: List<Node<T>>) {
targets.forEach { biLink(distance, it) }
}
fun biLink(distance: Long, other: Node<T>) {
link(distance, other)
other.link(distance, this)
}
override fun toString(): String {
return "Node(value=$value, edges=$edges)"
}
override fun equals(other: Any?): Boolean {
return this === other
}
override fun hashCode(): Int {
return super.hashCode()
}
}
data class Edge<T>(var distance: Long, var target: Node<T>) {
override fun toString(): String {
return "Edge(distance=$distance, target=Node(${target.value}))"
}
}
fun <T> shortestPath(start: Node<T>, target: Node<T>): Long? {
val unvisitedNodes = SortedLookup<Node<T>, Long>()
allNodes(start)
.forEach {
unvisitedNodes.add(it, Long.MAX_VALUE)
}
unvisitedNodes.add(start, 0)
var current = start
while (true) {
val edges = current.edges.filter { unvisitedNodes.containsKey(it.target) }
edges.forEach { edge ->
val newDistance = unvisitedNodes.get(current)!! + edge.distance
if (newDistance < unvisitedNodes.get(edge.target)!!)
unvisitedNodes.add(edge.target, newDistance)
}
val removed = unvisitedNodes.drop(current)
if (removed.first === target) {
return removed.second
}
else {
current = unvisitedNodes.sortedSequence()
.filter { unvisitedNodes.containsKey(it.first) }
.first().first
}
}
}
fun <T> route(
start: Node<T>,
target: Node<T>,
tentativeDistances: MutableMap<Node<T>, Long>
): List<Node<T>> {
return backtrack(target, start, tentativeDistances)
}
fun <T> backtrack(
current: Node<T>,
target: Node<T>,
tentativeDistances: MutableMap<Node<T>, Long>
): List<Node<T>> {
if (current == target) {
return listOf()
}
val next = current.edges.minByOrNull { tentativeDistances[it.target]!! }!!.target
return listOf(next).plus(route(next, target, tentativeDistances))
}
fun <T> allNodes(start: Node<T>): Set<Node<T>> {
val unvisited = mutableSetOf(start)
val visited = mutableSetOf<Node<T>>()
while (unvisited.isNotEmpty()) {
val current = unvisited.first()
unvisited.remove(current)
current.edges
.filter { !visited.contains(it.target) }
.forEach { unvisited.add(it.target) }
visited.add(current)
}
return visited
}
| 0 | Kotlin | 0 | 0 | 4cdafaa524a863e28067beb668a3f3e06edcef96 | 2,951 | adventOfCode2021 | Apache License 2.0 |
src/Day05.kt | robotfooder | 573,164,789 | false | {"Kotlin": 25811} | data class Instruction(val qty: Int, val from: Int, val to: Int)
fun main() {
fun initStack(columns: Int): List<ArrayDeque<String>> = buildList {
for (x in 0 until columns) {
add(ArrayDeque())
}
}
fun parseToStack(input: List<String>): List<ArrayDeque<String>> {
var columns: Int
return input
.filter { it.contains("[") }
.map { it.chunked(4) }
.also { columns = it.first().size }
.map { strings ->
strings.map { it.trim() }
.map { it.replace("[", "") }
.map { it.replace("]", "") }
}
.fold(initStack(columns)) { acc, row ->
row.forEachIndexed { index, s ->
if (s.isNotEmpty()) {
val stack = acc[index]
stack.add(s)
}
}
acc
}
}
fun parseInstructions(input: List<String>): List<Instruction> {
return input
.filter { it.startsWith("move") }
.map { it.toInstruction() }
}
fun part1(input: List<String>): String {
val stacks = parseToStack(input)
val instructions = parseInstructions(input)
instructions.forEach { instruction ->
val fromStack = stacks[instruction.from - 1]
val toStack = stacks[instruction.to - 1]
fromStack
.take(instruction.qty)
.onEach {
toStack.addFirst(it)
fromStack.remove(it)
}
}
return stacks.joinToString(separator = "") {
it.first()
}
}
fun part2(input: List<String>): String {
val stacks = parseToStack(input)
val instructions = parseInstructions(input)
instructions.forEach { instruction ->
val fromStack = stacks[instruction.from - 1]
val toStack = stacks[instruction.to - 1]
val take = fromStack.take(instruction.qty)
toStack.addAll(0, take)
take.forEach { fromStack.remove(it) }
}
return stacks.joinToString(separator = "") {
if (it.isNotEmpty()) it.first() else ""
}
}
fun runTest(expected: String, day: String, testFunction: (List<String>) -> String) {
val actual = testFunction(readTestInput(day))
check(expected == actual)
{
"Failing for day $day, ${testFunction}. " +
"Expected $expected but got $actual"
}
}
val day = "05"
// test if implementation meets criteria from the description, like:
runTest("CMZ", day, ::part1)
runTest("MCD", day, ::part2)
val input = readInput(day)
println(part1(input))
println(part2(input))
}
fun String.toInstruction(): Instruction {
val inputRegex = "move (\\d+) from (\\d+) to (\\d+)".toRegex()
val (qty, from, to) = inputRegex
.matchEntire(this)
?.destructured
?: throw IllegalArgumentException("Incorrect input line $this")
return Instruction(qty.toInt(), from.toInt(), to.toInt())
}
| 0 | Kotlin | 0 | 0 | 9876a52ef9288353d64685f294a899a58b2de9b5 | 3,209 | aoc2022 | Apache License 2.0 |
src/main/kotlin/aoc22/Day19.kt | tom-power | 573,330,992 | false | {"Kotlin": 254717, "Shell": 1026} | package aoc22
import common.Collections.product
import aoc22.Day19Domain.Blueprint
import aoc22.Day19Domain.Material.*
import aoc22.Day19Domain.RobotBlueprint
import aoc22.Day19Domain.State
import aoc22.Day19Parser.toBluePrints
import aoc22.Day19Runner.GeodeFactory
import aoc22.Day19Solution.part1Day19
import aoc22.Day19Solution.part2Day19
import common.Maps.minusInt
import common.Maps.plusInt
import common.Year22
import java.util.*
import kotlin.math.ceil
object Day19: Year22 {
fun List<String>.part1(): Int = part1Day19()
fun List<String>.part2(): Int = part2Day19()
}
object Day19Solution {
fun List<String>.part1Day19(): Int =
toBluePrints()
.map { it.id * GeodeFactory(it, 24).maxGeodes() }
.sum()
fun List<String>.part2Day19(): Int =
toBluePrints()
.take(3)
.map { GeodeFactory(it, 32).maxGeodes() }
.product()
}
object Day19Runner {
data class GeodeFactory(
val blueprint: Blueprint,
val maxTime: Int,
) {
fun maxGeodes(): Int {
var maxGeodes = 0
val queue: PriorityQueue<State> = PriorityQueue(State.geodeComparator).apply { add(State.initial()) }
while (queue.isNotEmpty()) {
val state = queue.poll()
if (canBeatMax(state, maxGeodes)) {
queue.addAll(nextStatesFor(state))
}
maxGeodes = maxOf(state.materialCount(Geode), maxGeodes)
}
return maxGeodes
}
private fun canBeatMax(state: State, maxGeodes: Int) = state.maxGeodesPossible(maxTime) > maxGeodes
private fun nextStatesFor(state: State): List<State> =
robotsToBuild(state)
.filter { (_, timeNeeded) -> state.time + timeNeeded <= maxTime }
.filter { (robotToBuild, _) -> robotToBuild.material == Geode || needMaterialFrom(robotToBuild, state) }
.map { (robotToBuild, timeNeeded) ->
State(
time = state.time + timeNeeded,
materialCountMap = state.materialCountMap plusInt state.materialCollectedMap(timeNeeded) minusInt robotToBuild.costMap,
robotCountMap = state.robotCountMap plusInt robotToBuild.buildMap,
)
}
private val maxRobotCostMap = blueprint.maxRobotCostMap()
private fun needMaterialFrom(robotBlueprint: RobotBlueprint, state: State) =
with(robotBlueprint) {
maxRobotCostMap[material]!! > state.robotCount(material)
}
private data class RobotPlan(val robotToBuild: RobotBlueprint, val timeNeeded: Int)
private fun robotsToBuild(state: State): List<RobotPlan> =
blueprint.robots
.map { robotToBuild ->
RobotPlan(
robotToBuild = robotToBuild,
timeNeeded = robotToBuild.timeNeeded(state)
)
}
}
}
object Day19Domain {
data class State(
val time: Int,
val materialCountMap: Map<Material, Int>,
val robotCountMap: Map<Material, Int>
) {
fun materialCount(material: Material) = materialCountMap.getOrDefault(material, 0)
fun robotCount(material: Material) = robotCountMap.getOrDefault(material, 0)
fun materialCollectedMap(timeNeeded: Int): Map<Material, Int> =
robotCountMap.mapValues { it.value * timeNeeded }
fun maxGeodesPossible(maxTime: Int): Int {
val timeLeft = maxTime - time
val mostPossible = (0 until timeLeft).sumOf { it + robotCount(Geode) }
return materialCount(Geode) + mostPossible
}
companion object {
fun initial(): State =
State(
time = 1,
materialCountMap = mapOf(Ore to 1, Clay to 0, Obsidian to 0, Geode to 0),
robotCountMap = mapOf(Ore to 1, Clay to 0, Obsidian to 0, Geode to 0)
)
val geodeComparator = Comparator<State> { o1, o2 ->
o2.materialCount(Geode).compareTo(o1.materialCount(Geode))
}
}
}
data class Blueprint(
val id: Int,
val robots: List<RobotBlueprint>,
) {
fun maxRobotCostMap(): Map<Material, Int> =
Material.values()
.associateWith { material ->
this.robots.maxOf { robot -> robot.cost(material) }
}
}
data class RobotBlueprint(
val material: Material,
val costMap: Map<Material, Int>,
) {
fun timeNeeded(state: State): Int =
this.costMap
.maxOf { (material, _) -> this.timeToGet(material, state) } + 1
private fun timeToGet(material: Material, state: State): Int =
if (cost(material) <= state.materialCount(material)) 0 else timeToGetFuture(material, state)
private fun timeToGetFuture(material: Material, state: State): Int {
val materialNeeded = cost(material) - state.materialCount(material)
return ceil(materialNeeded / state.robotCount(material).toFloat()).toInt()
}
val buildMap: Map<Material, Int> get() = mapOf(this.material to 1)
fun cost(material: Material): Int = costMap.getOrDefault(material, 0)
}
enum class Material { Ore, Clay, Obsidian, Geode }
}
object Day19Parser {
fun List<String>.toBluePrints(): List<Blueprint> =
map {
it.toRobotNumbers().let { numbers ->
Blueprint(
id = numbers[0][0],
robots = listOf(
RobotBlueprint(
material = Ore,
costMap = mapOf(Ore to numbers[1][0]),
),
RobotBlueprint(
material = Clay,
costMap = mapOf(Ore to numbers[2][0]),
),
RobotBlueprint(
material = Obsidian,
costMap = mapOf(
Ore to numbers[3][0],
Clay to numbers[3][1]
),
),
RobotBlueprint(
material = Geode,
costMap = mapOf(
Ore to numbers[4][0],
Obsidian to numbers[4][1]
),
),
)
)
}
}
private fun String.toRobotNumbers(): List<List<Int>> =
split(":", ".")
.map { idAndRobots ->
idAndRobots.split("ore")
.map { it.filter { it.isDigit() } }
.filter { it.isNotEmpty() }
.map { it.toInt() }
}
}
| 0 | Kotlin | 0 | 0 | baccc7ff572540fc7d5551eaa59d6a1466a08f56 | 7,111 | aoc | Apache License 2.0 |
src/Day09.kt | Kvest | 573,621,595 | false | {"Kotlin": 87988} | import kotlin.math.abs
import kotlin.math.sign
fun main() {
val testInput1 = readInput("Day09_test1")
val testInput2 = readInput("Day09_test2")
check(part1(testInput1) == 13)
check(part2(testInput1) == 1)
check(part2(testInput2) == 36)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int = solve(input, ropeSize = 2)
private fun part2(input: List<String>): Int = solve(input, ropeSize = 10)
private fun solve(input: List<String>, ropeSize: Int): Int {
val rope = List(ropeSize) { MutableXY(0, 0) }
val adjacentKnots = rope.windowed(2, 1)
val head = rope.first()
val tail = rope.last()
val visitedCells = mutableSetOf<XY>()
var dx = 0
var dy = 0
input.forEach { action ->
val cnt = action.substringAfter(" ").toInt()
when {
action.startsWith("L") -> {
dx = -1
dy = 0
}
action.startsWith("R") -> {
dx = 1
dy = 0
}
action.startsWith("U") -> {
dx = 0
dy = 1
}
action.startsWith("D") -> {
dx = 0
dy = -1
}
}
repeat(cnt) {
head.x += dx
head.y += dy
adjacentKnots.forEach { (first, second) ->
adjustKnotes(first, second)
}
visitedCells.add(tail.toXY())
}
}
return visitedCells.size
}
private fun adjustKnotes(first: MutableXY, second: MutableXY) {
if (abs(first.x - second.x) >= 2 || abs(first.y - second.y) >= 2) {
second.x = second.x + 1 * (first.x - second.x).sign
second.y = second.y + 1 * (first.y - second.y).sign
}
} | 0 | Kotlin | 0 | 0 | 6409e65c452edd9dd20145766d1e0ea6f07b569a | 1,831 | AOC2022 | Apache License 2.0 |
2021/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2021/day10/Day10.kt | sanderploegsma | 224,286,922 | false | {"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171} | package nl.sanderp.aoc.aoc2021.day10
import nl.sanderp.aoc.common.measureDuration
import nl.sanderp.aoc.common.prettyPrint
import nl.sanderp.aoc.common.readResource
import java.util.*
fun main() {
val input = readResource("Day10.txt").lines().map { parse(it) }
val (answer1, duration1) = measureDuration<Long> { partOne(input) }
println("Part one: $answer1 (took ${duration1.prettyPrint()})")
val (answer2, duration2) = measureDuration<Long> { partTwo(input) }
println("Part two: $answer2 (took ${duration2.prettyPrint()})")
}
private val brackets = mapOf(
')' to '(',
']' to '[',
'}' to '{',
'>' to '<',
)
private val corruptLineScores = mapOf(
')' to 3L,
']' to 57L,
'}' to 1197L,
'>' to 25137L,
)
private val incompleteLineScores = mapOf(
')' to 1,
']' to 2,
'}' to 3,
'>' to 4,
)
sealed class Line(val score: Long)
class CorruptLine(val char: Char) : Line(corruptLineScores[char]!!) {
override fun toString(): String {
return "Incorrect token '$char' (score: $score)"
}
}
class IncompleteLine(val missing: List<Char>): Line(missing.fold(0) { s, c -> 5 * s + incompleteLineScores[c]!!}) {
override fun toString(): String {
return "Incomplete line, missing '${missing.joinToString("")}' (score: $score)"
}
}
private fun parse(line: String): Line {
val open = Stack<Char>()
for (c in line) {
if (brackets.containsValue(c)) {
open.push(c)
} else if (open.empty() || open.peek() != brackets[c]) {
return CorruptLine(c)
} else {
open.pop()
}
}
val missing = buildList {
while (open.isNotEmpty()) {
val opening = open.pop()
add(brackets.filterValues { it == opening }.keys.first())
}
}
return IncompleteLine(missing)
}
private fun partOne(input: List<Line>) = input.filterIsInstance(CorruptLine::class.java).sumOf { it.score }
private fun partTwo(input: List<Line>): Long {
val scores = input.filterIsInstance(IncompleteLine::class.java).map { it.score }
return scores.sorted()[scores.size / 2]
} | 0 | C# | 0 | 6 | 8e96dff21c23f08dcf665c68e9f3e60db821c1e5 | 2,148 | advent-of-code | MIT License |
src/main/kotlin/16_solution.kt | barta3 | 112,792,199 | false | null | fun solve(input: List<String>, times: Int = 1): String {
val sequence = mutableListOf<List<Char>>()
var curr = (0 until 16).map { 'a' + it }
repeat(times) {
if (curr in sequence) {
return sequence[times % sequence.size].joinToString(separator = "")
} else {
sequence.add(curr)
curr = dance(curr, input)
}
}
return curr.joinToString(separator = "")
}
fun dance(curr: List<Char>, input: List<String>): List<Char> {
var next = curr.toMutableList()
for (move in input) {
when (move[0]) {
's' -> {
val pos = move.drop(1).toInt()
next = (next.drop(next.size - pos) + next.take(next.size - pos)).toMutableList()
}
'x' -> {
val (a, b) = move.drop(1).split("/").map { it.trim().toInt() }
next[a] = next[b].also { next[b] = next[a] }
}
'p' -> {
val (a, b) = move.drop(1).split("/").map { next.indexOf(it[0]) }
next[a] = next[b].also { next[b] = next[a] }
}
}
}
return next
}
fun main(args: Array<String>) {
val input = Permutation::class.java
.getResource("16_input.txt")
.readText()
.split(",")
//println("Part One = ${solve(input)}")
println("Part Two = ${solve(input, 1_000_000_000)}")
}
| 0 | Kotlin | 0 | 0 | 51ba74dc7b922ac11f202cece8802d23011f34f1 | 1,412 | AdventOfCode2017 | MIT License |
src/main/kotlin/day16.kt | bfrengley | 318,716,410 | false | null | package aoc2020.day16
import aoc2020.util.loadTextResource
fun main(args: Array<String>) {
val lines = loadTextResource("/day16.txt").lines()
val fields = lines.takeWhile { it.isNotBlank() }.toList()
val ticket = lines.drop(fields.size + 2).first().split(',').map { it.toInt() }
val nearTickets = lines.drop(fields.size + 5).map { ticketStr ->
ticketStr.split(',').map { it.toInt() }
}
val ticketProps = TicketProps(fields)
val (validTickets, invalidTickets) =
nearTickets.partition { ticketProps.findInvalidField(it) == null }
println("Part 1: ${
invalidTickets.mapNotNull { ticketProps.findInvalidField(it) }.sum()
}")
part2(ticketProps, ticket, validTickets)
}
fun part2(props: TicketProps, myTicket: List<Int>, nearTickets: List<List<Int>>) {
val assignments = nearTickets.map { props.assignments(it) }
val candidates = assignments.reduce { assgns, ticket ->
assgns.zip(ticket).map { (a1, a2) -> a1.intersect(a2) }
}
val mutableCandidates = candidates.toMutableList()
val propsByCount = props.props.sortedBy { prop -> candidates.count { prop in it } }
for (prop in propsByCount) {
reduceCandidates(prop, mutableCandidates)
}
assert(mutableCandidates.all { it.size == 1 })
val departureProduct = myTicket
.zip(mutableCandidates.map { it.first() })
.fold(1L) { acc, (value, cand) ->
when (cand.name.startsWith("departure")) {
true -> acc * value.toLong()
false -> acc
}
}
println("Part 3: $departureProduct")
}
fun reduceCandidates(prop: TicketProps.Prop, candidates: MutableList<Set<TicketProps.Prop>>) {
val candIdx = candidates.indexOfFirst { prop in it }
candidates[candIdx] = setOf(prop)
}
class TicketProps(fields: List<String>) {
data class Prop(val name: String, val ranges: List<IntRange>) {
fun contains(value: Int) = ranges.any { value in it }
override fun equals(other: Any?) = other is Prop && name == other.name
override fun hashCode() = name.hashCode()
}
val props: List<Prop> = fields.map { propStr ->
val (name, rangeStrs) = propStr.split(":")
val ranges = rangeStrs.split("or").map { range ->
val (start, end) = range.trim().split('-')
(start.toInt()..end.toInt())
}
Prop(name, ranges)
}
fun findInvalidField(fieldVals: List<Int>) = fieldVals.find { value ->
props.all { !it.contains(value) }
}
fun assignments(fieldVals: List<Int>) = fieldVals.map { value ->
props.filter { it.contains(value) }.toSet()
}
}
| 0 | Kotlin | 0 | 0 | 088628f585dc3315e51e6a671a7e662d4cb81af6 | 2,681 | aoc2020 | ISC License |
src/main/kotlin/algorithms/SigmaTable.kt | Furetur | 439,579,145 | false | {"Kotlin": 21223, "ANTLR": 246} | package algorithms
import model.Grammar
import model.Lang
import model.NonTerm
private typealias SigmaInput = Pair<NonTerm, NonTerm>
class SigmaTable(private val grammar: Grammar, private val firstTable: FirstTable, private val k: Int) {
private var sigmas = mutableMapOf<SigmaInput, Set<Lang>>()
private val allSigmaInputs = cartesianProduct(grammar.allNonTerms, grammar.allNonTerms)
private val notSaturatedSigmaInputs = allSigmaInputs.toMutableSet()
init {
start()
}
fun xsigma(a: NonTerm, b: NonTerm): Set<Lang> = sigmas[Pair(a, b)] ?: error("Sigma'($a, $b) is not calculated")
fun sigma(nonTerm: NonTerm): Set<Lang> = xsigma(grammar.main, nonTerm)
private fun start() {
baseCase()
var i = 0
while (notSaturatedSigmaInputs.isNotEmpty()) {
// println("Sigmas i = $i. Not saturated: ${notSaturatedSigmaInputs.size}")
// println(sigmas.mapValues { it.value.map { it.debugString() } })
val nextSigmas = sigmas.mapValues { it.value.toSet() }.toMutableMap()
for ((a, b) in notSaturatedSigmaInputs.toSet()) {
val nextSigmasAB = calcNewSigmas(a, b)
if (nextSigmasAB == nextSigmas[Pair(a, b)]) {
notSaturatedSigmaInputs.remove(Pair(a, b))
}
nextSigmas[Pair(a, b)] = nextSigmasAB
}
sigmas = nextSigmas
i += 1
}
}
private fun calcNewSigmas(a: NonTerm, b: NonTerm): Set<Lang> {
val newSigmas = sigmas[Pair(a, b)]!!.toMutableSet()
for (rule in grammar.rules[a] ?: emptySet()) {
for ((xIndex, x) in rule.value.withIndex()) {
if (x !is NonTerm) continue
val leftLangs = sigmas[Pair(x, b)]!!
val rightFirst = firstTable.firstOf(rule.value.subList(xIndex + 1, rule.value.size))
for (leftLang in leftLangs) {
newSigmas.add(kProduct(leftLang, rightFirst, k))
}
}
}
return newSigmas
}
// i = 0
private fun baseCase() {
for ((a, b) in allSigmaInputs) {
val thisSigma = mutableSetOf<Lang>()
for (rule in grammar.rules[a] ?: emptySet()) {
val allRightContexts = rule.value.findAll(b).map { i -> rule.value.subList(i + 1, rule.value.size) }
for (rightContext in allRightContexts) {
thisSigma.add(firstTable.firstOf(rightContext))
}
}
sigmas[Pair(a, b)] = thisSigma
}
}
}
| 0 | Kotlin | 0 | 1 | 002cc53bcca6f9b591c4090d354f03fe3ffd3ed6 | 2,610 | LLkChecker | MIT License |
src/day11/Day11.kt | zypus | 573,178,215 | false | {"Kotlin": 33417, "Shell": 3190} | package day11
import AoCTask
import java.math.BigInteger
// https://adventofcode.com/2022/day/11
sealed class Operation {
abstract operator fun invoke(value: BigInteger): BigInteger
data class Add(val amount: BigInteger): Operation() {
override fun invoke(value: BigInteger): BigInteger = value + amount
}
data class Multiply(val amount: BigInteger): Operation() {
override fun invoke(value: BigInteger): BigInteger = value * amount
}
object AddSelf: Operation() {
override fun invoke(value: BigInteger): BigInteger = value + value
}
object Squared: Operation() {
override fun invoke(value: BigInteger): BigInteger = value * value
}
}
data class Test(val divisor: BigInteger, val ifTrue: Int, val ifFalse: Int) {
operator fun invoke(value: BigInteger): Int {
return if (value.mod(divisor) == BigInteger.ZERO) {
ifTrue
} else {
ifFalse
}
}
}
data class Monkey(val items: MutableList<BigInteger>, val op: Operation, val test: Test, var inspections: BigInteger = BigInteger.ZERO) {
companion object {
fun fromLines(lines: List<String>): Monkey {
val (itemLine, operationLine, testLine, ifTrueLine, ifFalseLine) = lines.drop(1).map(String::trim)
val items = itemLine.replace("Starting items: ", "").split(", ").map { it.toBigInteger() }
val (opType, amount) = operationLine.replace("Operation: new = old ", "").split(" ")
val op = when(opType) {
"+" -> if (amount == "old") Operation.AddSelf else Operation.Add(amount.toBigInteger())
"*" -> if (amount == "old") Operation.Squared else Operation.Multiply(amount.toBigInteger())
else -> throw Exception("Unknown op type: '$opType'")
}
val divisor = testLine.replace("Test: divisible by ", "").toBigInteger()
val ifTrue = ifTrueLine.split(" ").last().toInt()
val ifFalse = ifFalseLine.split(" ").last().toInt()
return Monkey(
items = items.toMutableList(),
op = op,
test = Test(divisor, ifTrue, ifFalse)
)
}
}
}
private fun parseMonkeys(input: List<String>): List<Monkey> {
var monkeyIndex = 0
val monkeyLines = input.groupBy {
if (it.isBlank()) {
monkeyIndex += 1
}
monkeyIndex
}.map { group ->
group.value.filter { it.isNotBlank() }
}
val monkeys = monkeyLines.map { lines ->
Monkey.fromLines(lines)
}
return monkeys
}
private fun simulateRounds(monkeys: List<Monkey>, rounds: Int, transformWorry: (BigInteger) -> BigInteger = {it}) {
(1..rounds).forEach { round ->
if ((round + 1) % 100 == 0) {
println("Simulating round ${round + 1}")
}
monkeys.forEach { monkey ->
val (items, op, test) = monkey
monkey.inspections += items.size.toBigInteger()
items.forEach { item ->
val worryLevel = transformWorry(op(item))
val targetMonkeyIndex = test(worryLevel)
monkeys[targetMonkeyIndex].items.add(worryLevel)
}
items.clear()
}
}
}
fun part1(input: List<String>): BigInteger {
val monkeys = parseMonkeys(input)
val three = 3.toBigInteger()
simulateRounds(monkeys, 20) {
it / three
}
val (topMonkey1, topMonkey2) = monkeys.map { it.inspections }.sortedDescending().take(2)
return topMonkey1 * topMonkey2
}
fun part2(input: List<String>): BigInteger {
val monkeys = parseMonkeys(input)
val mod = monkeys.map { it.test.divisor }.reduce { acc, bigInteger -> acc * bigInteger }
simulateRounds(monkeys, 10000) {
it.mod(mod)
}
val (topMonkey1, topMonkey2) = monkeys.map { it.inspections }.sortedDescending().take(2)
return topMonkey1 * topMonkey2
}
fun main() = AoCTask("day11").run {
// test if implementation meets criteria from the description, like:
check(part1(testInput) == 10605.toBigInteger())
check(part2(testInput) == 2713310158.toBigInteger())
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f37ed8e9ff028e736e4c205aef5ddace4dc73bfc | 4,244 | aoc-2022 | Apache License 2.0 |
src/2023/Day07.kt | nagyjani | 572,361,168 | false | {"Kotlin": 369497} | package `2023`
import java.io.File
import java.util.*
fun main() {
Day07().solve()
}
class Day07 {
val input1 = """
32T3K 765
T55J5 684
KK677 28
KTJJT 220
QQQJA 483
""".trimIndent()
fun String.rank1(): Long {
val m = mutableMapOf<Char, Int>()
forEach { m[it] = m.getOrDefault(it, 0) + 1 }
if (m.values.max() == 5) {
return 7
}
if (m.values.max() == 4) {
return 6
}
if (m.values.max() == 3) {
if (m.values.min() == 2) {
return 5
}
return 4
}
if (m.values.max() == 2) {
if (m.keys.size == 3) {
return 3
}
return 2
}
return 1
}
fun String.rank2(r : Long): Long {
val cards = "AKQJT98765432"
return fold(r){acc, it -> 15L * acc + (14 - cards.indexOf(it))}
}
fun String.rank2j(r : Long): Long {
val cards = "AKQT98765432J"
return fold(r){acc, it -> 15L * acc + (14 - cards.indexOf(it))}
}
fun String.rankj(): Long {
return rank2j(joker().rank1())
}
fun String.rank(): Long {
return rank2(rank1())
}
fun String.joker() : String {
val m = mutableMapOf<Char, Int>()
forEach { m[it] = m.getOrDefault(it, 0) + 1 }
if ('J' !in m.keys) {
return this
}
val n = m['J']!!
val m1 = m.toMutableMap()
m1.remove('J')
if (m1.size == 0) {
return "AAAAA"
}
val mx = m1.values.max()
val cs = m1.filter{it.value == mx}.keys
val r0 = cs.map {
this.map{
c ->
if (c == 'J') {
it
} else {
c }}.joinToString("") }
r0.sortedBy { it.rank() }
return r0[0]
}
val input2 = """
""".trimIndent()
class Hand(val cards: String, val bid: Long)
fun solve() {
val f = File("src/2023/inputs/day07.in")
val s = Scanner(f)
// val s = Scanner(input1)
// val s = Scanner(input2)
var sum = 0L
var sum1 = 0L
var lineix = 0
val lines = mutableListOf<String>()
val bids = mutableMapOf<String, Long>()
val hands = mutableListOf<Hand>()
while (s.hasNextLine()) {
lineix++
val line = s.nextLine().trim()
if (line.isEmpty()) {
continue
}
lines.add(line)
}
lines.forEach {
val l = it.split(" ")
bids[l[0]] = l[1].toLong()
hands.add(Hand(l[0], l[1].toLong()))}
val sortedHands = bids.keys.sortedBy { it.rank() }
for (i in sortedHands.indices) {
val h = sortedHands[i]
sum += (i+1) * bids[h]!!
}
val sortedHands2 = bids.keys.sortedBy { it.rankj() }
for (i in sortedHands2.indices) {
val h = sortedHands2[i]
sum1 += (i+1) * bids[h]!!
}
print("$sum $sum1\n")
}
} | 0 | Kotlin | 0 | 0 | f0c61c787e4f0b83b69ed0cde3117aed3ae918a5 | 3,174 | advent-of-code | Apache License 2.0 |
src/Day02.kt | polbins | 573,082,325 | false | {"Kotlin": 9981} | fun main() {
// Rock/Paper/Scissor = 1,2,3
// Lose/Draw/Win = 0,3,6
fun part1(input: List<String>): Int {
var result = 0
for (s in input) {
val left = s[0].toScore()
val right = s[2].toScore()
val outcome = when (right - left) {
1, -2 -> 6 // greater or -overlap (rock - scissor)
-1, 2 -> 0 // lesser or +overlap (scissor - rock)
else -> 3
}
result += right + outcome
}
return result
}
fun part2(input: List<String>): Int {
var result = 0
for (s in input) {
val left = s[0].toScore()
val outcome = s[2].toScore()
result += when (outcome) {
// lesser or +overlap
1 -> when (left) {
1 -> 3
else -> left - 1
}.plus(0)
// match
2 -> left.plus(3)
// greater or -overlap
else -> when (left) {
3 -> 1
else -> left + 1
}.plus(6)
}
}
return result
}
// test if implementation meets criteria from the description, like:
val testInput1 = readInput("Day02_test")
check(part1(testInput1) == 15)
val input1 = readInput("Day02")
println(part1(input1))
val testInput2 = readInput("Day02_test")
check(part2(testInput2) == 12)
val input2 = readInput("Day02")
println(part2(input2))
}
private fun Char.toScore() = when (this) {
'A', 'X' -> 1
'B', 'Y' -> 2
'C', 'Z' -> 3
else -> throw IllegalArgumentException("Unknown Char '$this'!")
}
| 0 | Kotlin | 0 | 0 | fb9438d78fed7509a4a2cf6c9ea9e2eb9d059f14 | 1,478 | AoC-2022 | Apache License 2.0 |
src/Day10.kt | vlsolodilov | 573,277,339 | false | {"Kotlin": 19518} | fun main() {
fun getProgram(line: String): ProgramLine =
if (line == "noop") {
ProgramLine(1, 0)
} else {
ProgramLine(2, line.split(" ")[1].toInt())
}
fun getSignalStrengthList(input: List<String>): List<Int> {
val signalStrengthList = ArrayList<Int>()
signalStrengthList.add(1)
var buffer = 0
input.map(::getProgram).forEach { programLine ->
val lastSignalStrength = signalStrengthList.last() + buffer
repeat(programLine.cycle) {
signalStrengthList.add(lastSignalStrength)
}
buffer = programLine.value
}
return signalStrengthList
}
fun part1(input: List<String>): Int {
val signalStrengthList = getSignalStrengthList(input)
return listOf(20, 60, 100, 140, 180, 220).sumOf { signalStrengthList[it] * it }
}
fun part2(input: List<String>) {
val signalStrengthList = getSignalStrengthList(input)
for (i in 1..240) {
if (i % 40 in (signalStrengthList[i])..(signalStrengthList[i] + 2 )) {
print('#')
} else {
print('.')
}
if (i != 0 && i % 40 == 0) println()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
part2(testInput)
val input = readInput("Day10")
println(part1(input))
part2(input)
}
data class ProgramLine(val cycle: Int, val value: Int)
| 0 | Kotlin | 0 | 0 | b75427b90b64b21fcb72c16452c3683486b48d76 | 1,588 | aoc22 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaximumBuildingHeight.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.max
import kotlin.math.min
/**
* 1840. Maximum Building Height
* @see <a href="https://leetcode.com/problems/maximum-building-height/">Source</a>
*/
fun interface MaximumBuildingHeight {
fun maxBuilding(n: Int, restrictions: Array<IntArray>): Int
}
class MaximumBuildingHeightImpl : MaximumBuildingHeight {
override fun maxBuilding(n: Int, restrictions: Array<IntArray>): Int {
// sorting restrictions according to index.
restrictions.sortWith { a, b -> a[0] - b[0] }
val len: Int = restrictions.size + 2
val arr = Array(len) { IntArray(2) }
arr[0][0] = 1
arr[0][1] = 0
arr[len - 1][0] = n
arr[len - 1][1] = n - 1
for (i in 1 until len - 1) {
arr[i] = restrictions[i - 1]
}
// looping from left to right
for (i in 0 until len - 1) {
arr[i + 1][1] = min(arr[i + 1][1], arr[i][1] + (arr[i + 1][0] - arr[i][0]))
}
// looping from right to left
for (i in len - 1 downTo 1) {
arr[i - 1][1] = min(arr[i - 1][1], arr[i][1] + (arr[i][0] - arr[i - 1][0]))
}
var max = 0
for (i in 0 until len - 1) {
var j = arr[i][0]
val h1 = arr[i][1]
val k = arr[i + 1][0]
val h2 = arr[i + 1][1]
// calculating difference between heights of both buildings.
val diff = max(h1, h2) - min(h1, h2)
j += diff
// calculating maximum height possible between both buildings.
max = max(max, max(h1, h2) + (k - j) / 2)
}
return max
}
}
class MaximumBuildingHeight2Passes : MaximumBuildingHeight {
override fun maxBuilding(n: Int, restrictions: Array<IntArray>): Int {
val newRes = Array<IntArray>(restrictions.size + 2) { intArrayOf() }
System.arraycopy(restrictions, 0, newRes, 0, restrictions.size)
// extra restriction for building 1
newRes[newRes.size - 1] = intArrayOf(1, 0)
// extra restriction for the last building
newRes[newRes.size - 2] = intArrayOf(n, n - 1)
newRes.sortWith { a, b -> a[0] - b[0] }
// Adjust restrictions from the left
for (i in 0 until newRes.size - 1) {
val r1 = newRes[i][1]
val r2 = newRes[i + 1][1]
val h = r1 + (newRes[i + 1][0] - newRes[i][0])
newRes[i + 1][1] = min(h, r2)
}
// Adjust restrictions from the right
for (i in newRes.size - 2 downTo 0) {
val r1 = newRes[i][1]
val r2 = newRes[i + 1][1]
val h = r2 + (newRes[i + 1][0] - newRes[i][0])
newRes[i][1] = min(h, r1)
}
var res = 0
for (i in 0 until newRes.size - 1) {
val r1 = newRes[i][1]
val r2 = newRes[i + 1][1]
var h = r1 + (newRes[i + 1][0] - newRes[i][0])
if (h > r2) h = r2 + (h - r2) / 2
res = max(res, h)
}
return res
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,684 | kotlab | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem179/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem179
/**
* LeetCode page: [179. Largest Number](https://leetcode.com/problems/largest-number/);
*/
class Solution {
/* Complexity:
* Time O(NLogN) and Space O(N) where N is the size of nums;
*/
fun largestNumber(nums: IntArray): String {
val sortedBuckets = getSortedDigitBuckets(nums)
return getLargestNumber(sortedBuckets)
}
private fun getSortedDigitBuckets(nums: IntArray): List<List<String>> {
val sortedBucket = List(10) { mutableListOf<String>() }
for (num in nums) {
val strForm = num.toString()
sortedBucket[strForm[0] - '0'].add(strForm)
}
val comparator = getDesiredComparator()
for (bucket in sortedBucket) {
bucket.sortWith(comparator)
}
return sortedBucket
}
private fun getDesiredComparator(): Comparator<String> {
val comparator = Comparator<String> { strNum1, strNum2 ->
val strNum1Num2 = strNum1 + strNum2
val strNum2Num1 = strNum2 + strNum1
for (index in 0 until (strNum1.length + strNum2.length)) {
if (strNum1Num2[index] != strNum2Num1[index]) {
return@Comparator strNum2Num1[index] - strNum1Num2[index]
}
}
return@Comparator 0
}
return comparator
}
private fun getLargestNumber(sortedDigitBuckets: List<List<String>>): String {
if (containsZerosOnly(sortedDigitBuckets)) return "0"
val largestNumber = StringBuilder()
for (digit in sortedDigitBuckets.indices.reversed()) {
for (strNum in sortedDigitBuckets[digit]) {
largestNumber.append(strNum)
}
}
return largestNumber.toString()
}
private fun containsZerosOnly(sortedDigitBuckets: List<List<String>>): Boolean {
for (digit in 1..9) {
if (sortedDigitBuckets[digit].isNotEmpty()) return false
}
return true
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,043 | hj-leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/dev/siller/aoc2023/Day04.kt | chearius | 725,594,554 | false | {"Kotlin": 50795, "Shell": 299} | package dev.siller.aoc2023
import java.util.LinkedList
import kotlin.math.pow
data object Day04 : AocDayTask<UInt, UInt>(
day = 4,
exampleInput =
"""
|Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53
|Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19
|Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1
|Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83
|Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36
|Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11
""".trimMargin(),
expectedExampleOutputPart1 = 13u,
expectedExampleOutputPart2 = 30u
) {
private val WHITESPACES = "\\s+".toRegex()
private data class ScratchCard(
val id: UInt,
val winningNumbers: Set<UInt>,
val ownNumbers: Set<UInt>
) {
private val matchingNumbers = winningNumbers.intersect(ownNumbers)
val matchingNumbersCount = matchingNumbers.size.toUInt()
val wonScratchCardCopiesIds = (id + 1u)..(id + matchingNumbersCount)
}
override fun runPart1(input: List<String>): UInt =
input.map(::parseScratchCard)
.sumOf { scratchCard -> (2.0).pow((scratchCard.matchingNumbersCount - 1u).toInt()).toUInt() }
override fun runPart2(input: List<String>): UInt =
input.map(::parseScratchCard)
.associateBy { scratchCard -> scratchCard.id }
.let { scratchCards ->
val queue = LinkedList(scratchCards.values)
val scratchCardInstances = scratchCards.keys.associateWith { _ -> 1u }.toMutableMap()
while (queue.isNotEmpty()) {
queue.poll().wonScratchCardCopiesIds.mapNotNull { id ->
scratchCards[id]
}.forEach { wonScratchCardCopy ->
scratchCardInstances[wonScratchCardCopy.id] =
scratchCardInstances.getOrDefault(wonScratchCardCopy.id, 0u) + 1u
queue.add(wonScratchCardCopy)
}
}
scratchCardInstances.values.sum()
}
private fun parseScratchCard(line: String): ScratchCard {
val (cardPart, winningNumbersPart, ownNumbersPart) =
line
.split("\\s?[:|]\\s".toRegex(), limit = 3)
.map { part ->
part.trim().replace(WHITESPACES, " ")
}
return ScratchCard(
id = cardPart.filter { c -> c in '0'..'9' }.toUInt(),
winningNumbers = winningNumbersPart.split(' ').map(String::toUInt).toSet(),
ownNumbers = ownNumbersPart.split(' ').map(String::toUInt).toSet()
)
}
}
| 0 | Kotlin | 0 | 0 | fab1dd509607eab3c66576e3459df0c4f0f2fd94 | 2,710 | advent-of-code-2023 | MIT License |
src/Day05.kt | RandomUserIK | 572,624,698 | false | {"Kotlin": 21278} | import java.util.*
private const val STACK_DISTANCE = 4
data class Directive(
val numberOfCrates: Int,
val from: Int,
val to: Int,
)
fun List<String>.toStacks(): List<Stack<Char>> {
val numberOfStacks = last().split(" ").size
val result = List(numberOfStacks) { Stack<Char>() }
takeWhile { it.contains("[") }.reversed().forEach { crates ->
crates.forEachIndexed { idx, symbol ->
if (symbol.isUpperCase())
result[idx / STACK_DISTANCE].push(symbol)
}
}
return result
}
fun List<String>.toDirectives(): List<Directive> =
map {
Directive(
numberOfCrates = it.substringAfter("move ").substringBefore(" from").toInt(),
from = it.substringAfter("from ").substringBefore(" to").toInt() - 1,
to = it.substringAfter("to ").toInt() - 1
)
}
fun main() {
fun getStacksAndDirectives(input: List<String>): Pair<List<Stack<Char>>, List<Directive>> =
Pair(
input.takeWhile { it.isNotEmpty() }.toStacks(),
input.takeLastWhile { it.isNotEmpty() }.toDirectives()
)
fun part1(crateStacks: List<Stack<Char>>, directives: List<Directive>) {
directives.forEach { directive ->
repeat(directive.numberOfCrates) { crateStacks[directive.to].push(crateStacks[directive.from].pop()) }
}
println(crateStacks.map { it.peek() }.joinToString(""))
}
fun part2(crateStacks: List<Stack<Char>>, directives: List<Directive>) {
directives.forEach { directive ->
val toBeMoved = crateStacks[directive.from].takeLast(directive.numberOfCrates)
crateStacks[directive.to].addAll(toBeMoved)
repeat(directive.numberOfCrates) { crateStacks[directive.from].pop() }
}
println(crateStacks.map { it.peek() }.joinToString(""))
}
val input = readInput("inputs/day05_input")
val (crateStacks, directives) = getStacksAndDirectives(input)
part1(crateStacks, directives)
part2(crateStacks, directives)
} | 0 | Kotlin | 0 | 0 | f22f10da922832d78dd444b5c9cc08fadc566b4b | 1,831 | advent-of-code-2022 | Apache License 2.0 |
lib/src/main/kotlin/aoeiuv020/DynamicProgramming.kt | AoEiuV020 | 85,785,447 | false | {"Java": 22453, "Kotlin": 2576} | package aoeiuv020
import java.util.*
typealias StringBuilder = java.lang.StringBuilder
/**
* 最长公共子序列,
* 输出所有子序列,
* Created by AoEiuV020 on 2017/05/14.
*/
object DynamicProgramming {
enum class Last {
XY, X, Y, E
}
fun longestCommonSubsequence(x: String, y: String): List<String> = longestCommonSubsequence(x.toCharArray(), y.toCharArray())
private fun longestCommonSubsequence(x: CharArray, y: CharArray): List<String> {
val c = Array(x.size, {
Array(y.size, {
Pair(0, Last.XY)
})
})
var i = x.size - 1
var j = y.size - 1
_lcs(c, x, y, i, j)
return collect(c, x, y, i, j).map(StringBuilder::toString).distinct().sorted()
}
private fun collect(c: Array<Array<Pair<Int, Last>>>, x: CharArray, y: CharArray, i: Int, j: Int): MutableList<StringBuilder> = if (i < 0 || j < 0) mutableListOf<StringBuilder>(StringBuilder())
else when (c[i][j].second) {
Last.X -> collect(c, x, y, i - 1, j)
Last.Y -> collect(c, x, y, i, j - 1)
Last.E -> (collect(c, x, y, i - 1, j) + collect(c, x, y, i, j - 1)).toMutableList()
Last.XY -> {
collect(c, x, y, i - 1, j - 1).map {
it.append(x[i])
}.toMutableList()
}
}
private fun _lcs(c: Array<Array<Pair<Int, Last>>>, x: CharArray, y: CharArray, i: Int, j: Int): Int = when {
i == -1 || j == -1 -> 0
x[i] == y[j] -> {
val xy = _lcs(c, x, y, i - 1, j - 1) + 1
c[i][j] = Pair(xy, Last.XY)
c[i][j].first
}
else -> {
val x1 = _lcs(c, x, y, i - 1, j)
val y1 = _lcs(c, x, y, i, j - 1)
c[i][j] = if (x1 > y1) {
Pair(x1, Last.X)
} else if (x1 < y1) {
Pair(y1, Last.Y)
} else {
Pair(x1, Last.E)
}
c[i][j].first
}
}
}
| 0 | Java | 0 | 0 | 6161b9630e936c071d654f8c2364f3d5acf8a3a1 | 1,997 | DataStructuresTraining | MIT License |
src/main/kotlin/leetcode/Problem1878.kt | fredyw | 28,460,187 | false | {"Java": 1280840, "Rust": 363472, "Kotlin": 148898, "Shell": 604} | package leetcode
import java.util.TreeSet
/**
* https://leetcode.com/problems/get-biggest-three-rhombus-sums-in-a-grid/
*/
class Problem1878 {
fun getBiggestThree(grid: Array<IntArray>): IntArray {
val rightDiagonalSums = mutableMapOf<RowCol, Int>()
val maxRow = grid.size
val maxCol = if (maxRow > 0) grid[0].size else 0
for (row in 0 until maxRow) {
rightDiagonalSums(grid, rightDiagonalSums, row, 0)
}
for (col in 0 until maxCol) {
rightDiagonalSums(grid, rightDiagonalSums, 0, col)
}
val leftDiagonalSums = mutableMapOf<RowCol, Int>()
for (row in 0 until maxRow) {
leftDiagonalSums(grid, leftDiagonalSums, row, maxCol - 1)
}
for (col in maxCol - 1 downTo 0) {
leftDiagonalSums(grid, leftDiagonalSums, 0, col)
}
val set = TreeSet<Int>()
for (row in 0 until maxRow) {
for (col in 0 until maxCol) {
set += rhombusSum(grid, leftDiagonalSums, rightDiagonalSums, row, col)
}
}
var list = mutableListOf<Int>()
var i = 0
while (set.isNotEmpty() && i < 3) {
list.add(set.pollLast())
i++
}
return list.toIntArray()
}
private data class RowCol(val row: Int, val col: Int)
private fun rightDiagonalSums(grid: Array<IntArray>,
rightDiagonalSums: MutableMap<RowCol, Int>,
row: Int, col: Int) {
val maxRow = grid.size
val maxCol = if (maxRow > 0) grid[0].size else 0
var r = row
var c = col
while (r < maxRow && c < maxCol) {
rightDiagonalSums[RowCol(r, c)] = if (rightDiagonalSums[RowCol(r - 1, c - 1)] == null) {
grid[r][c]
} else {
rightDiagonalSums[RowCol(r - 1, c - 1)]!! + grid[r][c]
}
r++
c++
}
}
private fun leftDiagonalSums(grid: Array<IntArray>,
leftDiagonalSums: MutableMap<RowCol, Int>,
row: Int, col: Int) {
val maxRow = grid.size
var r = row
var c = col
while (r < maxRow && c >= 0) {
leftDiagonalSums[RowCol(r, c)] = if (leftDiagonalSums[RowCol(r - 1, c + 1)] == null) {
grid[r][c]
} else {
leftDiagonalSums[RowCol(r - 1, c + 1)]!! + grid[r][c]
}
r++
c--
}
}
private fun rhombusSum(grid: Array<IntArray>,
leftDiagonalSums: MutableMap<RowCol, Int>,
rightDiagonalSums: MutableMap<RowCol, Int>,
row: Int, col: Int): MutableSet<Int> {
val set = mutableSetOf(grid[row][col])
val maxRow = grid.size
val maxCol = if (maxRow > 0) grid[0].size else 0
var r = row
val c = col
var length = 1
while (r + (length * 2) < maxRow && c - length >= 0 && c + length < maxCol) {
val topLeft = leftDiagonalSums[RowCol(r + length, c - length)]!! -
leftDiagonalSums[RowCol(r, c)]!! + grid[r][c]
val topRight = rightDiagonalSums[RowCol(r + length, c + length)]!! -
rightDiagonalSums[RowCol(r, c)]!! + grid[r][c]
val bottomLeft = rightDiagonalSums[RowCol(r + length * 2, c)]!! -
rightDiagonalSums[RowCol(r + length, c - length)]!! +
grid[r + length][c - length]
val bottomRight = leftDiagonalSums[RowCol(r + length * 2, c)]!! -
leftDiagonalSums[RowCol(r + length, c + length)]!! +
grid[r + length][c + length]
val sum = topLeft + topRight + bottomLeft + bottomRight -
(grid[r][c] + grid[r + length][c - length] +
grid[r + length][c + length] + grid[r + length * 2][c])
set += sum
length++
}
return set
}
}
| 0 | Java | 1 | 4 | a59d77c4fd00674426a5f4f7b9b009d9b8321d6d | 4,112 | leetcode | MIT License |
src/test/kotlin/chapter3/solutions/ex28/listing.kt | DavidGomesh | 680,857,367 | false | {"Kotlin": 204685} | package chapter3.solutions.ex28
import chapter3.Branch
import chapter3.Leaf
import chapter3.Tree
import io.kotest.matchers.shouldBe
import io.kotest.core.spec.style.WordSpec
// tag::init[]
fun <A, B> fold(ta: Tree<A>, l: (A) -> B, b: (B, B) -> B): B =
when (ta) {
is Leaf -> l(ta.value)
is Branch -> b(fold(ta.left, l, b), fold(ta.right, l, b))
}
fun <A> sizeF(ta: Tree<A>): Int =
fold(ta, { 1 }, { b1, b2 -> 1 + b1 + b2 })
fun maximumF(ta: Tree<Int>): Int =
fold(ta, { a -> a }, { b1, b2 -> maxOf(b1, b2) })
fun <A> depthF(ta: Tree<A>): Int =
fold(ta, { 0 }, { b1, b2 -> 1 + maxOf(b1, b2) })
fun <A, B> mapF(ta: Tree<A>, f: (A) -> B): Tree<B> =
fold(ta, { a: A -> Leaf(f(a)) },
{ b1: Tree<B>, b2: Tree<B> -> Branch(b1, b2) })
// end::init[]
class Solution28 : WordSpec({
"tree fold" should {
val tree = Branch(
Branch(Leaf(1), Leaf(2)),
Branch(
Leaf(3),
Branch(
Branch(Leaf(4), Leaf(5)),
Branch(
Leaf(21),
Branch(Leaf(7), Leaf(8))
)
)
)
)
"generalise size" {
sizeF(tree) shouldBe 15
}
"generalise maximum" {
maximumF(tree) shouldBe 21
}
"generalise depth" {
depthF(tree) shouldBe 5
}
"generalise map" {
mapF(tree) { it * 10 } shouldBe
Branch(
Branch(Leaf(10), Leaf(20)),
Branch(
Leaf(30),
Branch(
Branch(Leaf(40), Leaf(50)),
Branch(
Leaf(210),
Branch(Leaf(70), Leaf(80))
)
)
)
)
}
}
})
| 0 | Kotlin | 0 | 0 | 41fd131cd5049cbafce8efff044bc00d8acddebd | 1,986 | fp-kotlin | MIT License |
2021/src/main/kotlin/de/skyrising/aoc2021/day9/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2021.day9
import de.skyrising.aoc.*
import it.unimi.dsi.fastutil.ints.IntArrayList
val test = TestInput("""
2199943210
3987894921
9856789892
8767896789
9899965678
""")
@PuzzleName("Smoke Basin")
fun PuzzleInput.part1(): Any {
val (points, width, height) = parseInput(this)
var risk = 0
forEachLowPoint(points, width, height) { _, _, value ->
//println("$x,$y $value")
risk += value + 1
}
return risk
}
fun PuzzleInput.part2(): Any {
val (points, width, height) = parseInput(this)
val basins = IntArrayList()
forEachLowPoint(points, width, height) { x, y, _ ->
val basin = mutableSetOf<Pair<Int, Int>>()
searchBasin(points, width, height, basin, x, y)
basins.add(basin.size)
//println("$x,$y $v ${basin.size} $basin")
}
basins.sort()
return basins.getInt(basins.lastIndex) * basins.getInt(basins.lastIndex - 1) * basins.getInt(basins.lastIndex - 2)
}
private fun parseInput(input: PuzzleInput): Triple<Array<IntArray>, Int, Int> {
val points = Array<IntArray>(input.lines.size) { line -> input.lines[line].chars().map { n -> n - '0'.code }.toArray() }
val width = points[0].size
val height = points.size
return Triple(points, width, height)
}
inline fun forEachLowPoint(map: Array<IntArray>, width: Int, height: Int, fn: (Int, Int, Int) -> Unit) {
for (y in 0 until height) {
for (x in 0 until width) {
val v = map[y][x]
if (x > 0 && map[y][x - 1] <= v) continue
if (x < width - 1 && map[y][x + 1] <= v) continue
if (y > 0 && map[y - 1][x] <= v) continue
if (y < height - 1 && map[y + 1][x] <= v) continue
fn(x, y, v)
}
}
}
fun searchBasin(map: Array<IntArray>, width: Int, height: Int, basin: MutableSet<Pair<Int, Int>>, x: Int, y: Int) {
val value = map[y][x]
if (value == 9 || !basin.add(x to y)) return
if (x > 0 && map[y][x - 1] >= value) searchBasin(map, width, height, basin, x - 1, y)
if (x < width - 1 && map[y][x + 1] >= value) searchBasin(map, width, height, basin, x + 1, y)
if (y > 0 && map[y - 1][x] >= value) searchBasin(map, width, height, basin, x, y - 1)
if (y < height - 1 && map[y + 1][x] >= value) searchBasin(map, width, height, basin, x, y + 1)
} | 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 2,347 | aoc | MIT License |
2018/kotlin/day18p1/src/main.kt | sgravrock | 47,810,570 | false | {"Rust": 1263100, "Swift": 1167766, "Ruby": 641843, "C++": 529504, "Kotlin": 466600, "Haskell": 339813, "Racket": 264679, "HTML": 200276, "OpenEdge ABL": 165979, "C": 89974, "Objective-C": 50086, "JavaScript": 40960, "Shell": 33315, "Python": 29781, "Elm": 22980, "Perl": 10662, "BASIC": 9264, "Io": 8122, "Awk": 5701, "Raku": 5532, "Rez": 4380, "Makefile": 1241, "Objective-C++": 1229, "Tcl": 488} | import java.util.*
fun main(args: Array<String>) {
val start = Date()
val classLoader = World::class.java.classLoader
val input = classLoader.getResource("input.txt").readText()
val result = scoreAfter10(World.parse(input))
println(result)
println("in ${Date().time - start.time} ms")
}
enum class Acre { Open, Wooded, LumberYard }
fun scoreAfter10(world: World): Int {
val endState = (1..10).fold(world, { prev, ignored -> prev.next() })
val wooded = endState.cells().count { it == Acre.Wooded }
val lumberYards = endState.cells().count { it == Acre.LumberYard }
return wooded * lumberYards
}
data class Coord(val x: Int, val y: Int)
data class World(val data: List<List<Acre>>) {
fun next(): World {
val result = data.mapIndexed { y, row ->
row.mapIndexed { x, acre ->
when (acre) {
Acre.Open -> {
if (numNeighbors(x, y, Acre.Wooded) >= 3) {
Acre.Wooded
} else {
Acre.Open
}
}
Acre.Wooded -> {
if (numNeighbors(x, y, Acre.LumberYard) >= 3) {
Acre.LumberYard
} else {
Acre.Wooded
}
}
Acre.LumberYard -> {
if (
numNeighbors(x, y, Acre.LumberYard) >= 1 &&
numNeighbors(x, y, Acre.Wooded) >= 1
) {
Acre.LumberYard
} else {
Acre.Open
}
}
}
}
}
return World(result)
}
fun cells(): Sequence<Acre> {
return data.asSequence().flatMap { it.asSequence() }
}
private fun numNeighbors(x: Int, y: Int, type: Acre): Int {
val candidates = listOf(
Coord(x - 1, y - 1),
Coord(x, y - 1),
Coord(x + 1, y - 1),
Coord(x - 1, y),
Coord(x + 1, y),
Coord(x - 1, y + 1),
Coord(x, y + 1),
Coord(x + 1, y + 1)
)
return candidates.count { c -> at(c) == type }
}
private fun at(c: Coord): Acre? {
val row = data.getOrNull(c.y)
?: return null
return row.getOrNull(c.x)
}
override fun toString(): String {
return data
.map { row ->
row.map {
when (it) {
Acre.Open -> '.'
Acre.Wooded -> '|'
Acre.LumberYard -> '#'
}
}.joinToString("")
}.joinToString("\n")
}
companion object {
fun parse(input: String): World {
val result = input.lines()
.map { line ->
line.toCharArray()
.map { c ->
when (c) {
'.' -> Acre.Open
'|' -> Acre.Wooded
'#' -> Acre.LumberYard
else -> throw Error("Unrecognized character: $c")
}
}
}
return World(result)
}
}
} | 0 | Rust | 0 | 0 | ea44adeb128cf1e3b29a2f0c8a12f37bb6d19bf3 | 3,524 | adventofcode | MIT License |
src/day12/Day12.kt | PoisonedYouth | 571,927,632 | false | {"Kotlin": 27144} | package day12
import readInput
import java.util.*
private class Point(
val x: Int,
val y: Int,
val code: Char,
val height: Int,
) : Comparable<Point> {
var dist: Int = -1
override fun compareTo(other: Point): Int {
return this.dist.compareTo(other.dist)
}
}
fun main() {
fun setupGrid(input: List<String>): List<List<Point>> {
val grid = input.mapIndexed { yIndex, s ->
s.mapIndexed { xIndex, c ->
Point(
x = xIndex,
y = yIndex,
code = c,
height = when (c) {
'S' -> 0
'E' -> 26
else -> c - 'a'
}
)
}
}
return grid
}
fun processGrid(grid: List<List<Point>>, target: Char): Int {
fun getPointOrNull(x: Int, y: Int): Point? {
return when {
x < 0 || x > grid[0].lastIndex || y < 0 || y > grid.lastIndex -> null
else -> grid[y][x]
}
}
fun Point.neighbors(): List<Point> {
val neighbourList = mutableListOf<Point?>()
neighbourList.add(getPointOrNull(x, y + 1))
neighbourList.add(getPointOrNull(x, y - 1))
neighbourList.add(getPointOrNull(x + 1, y))
neighbourList.add(getPointOrNull(x - 1, y))
return neighbourList.filterNotNull()
}
val destinationPoint = grid.flatten().single { it.code == 'E' }
val processedPoints = mutableSetOf<Point>()
val priorityQueue = PriorityQueue<Point>().apply { add(destinationPoint) }
while (priorityQueue.isNotEmpty()) {
val point = priorityQueue.poll()
point.neighbors().filter { it.height + 1 >= point.height }.forEach { neighbour ->
if (neighbour.code == target) {
return point.dist
}
if (neighbour !in processedPoints) {
neighbour.dist = point.dist + 1
processedPoints.add(neighbour)
priorityQueue.add(neighbour)
}
}
}
error("target '$target' not found in grid!")
}
fun part1(input: List<String>): Int {
val grid = setupGrid(input)
return processGrid(grid, 'S')
}
fun part2(input: List<String>): Int {
val grid = setupGrid(input)
return processGrid(grid, 'a')
}
val input = readInput("day12/Day12")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 1 | 0 | dbcb627e693339170ba344847b610f32429f93d1 | 2,639 | advent-of-code-kotlin-2022 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.