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/Day9.kt | noamfreeman | 572,834,940 | false | {"Kotlin": 30332} | import kotlin.math.abs
private val exampleInput = """
R 4
U 4
L 3
D 1
R 4
D 1
L 5
R 2
""".trimIndent()
private val largeExample = """
R 5
U 8
L 8
D 3
R 17
D 10
L 25
U 20
""".trimIndent()
fun main() {
println("day8")
println()
println("part1")
assertEquals(part1(exampleInput), 13)
println(part1(readInputFile("day9_input.txt")))
println()
println("part2")
assertEquals(part2(exampleInput), 1)
assertEquals(part2(largeExample), 36)
println(part2(readInputFile("day9_input.txt")))
}
private fun part1(input: String): Int {
val moves = parseInput(input)
return countPositionsOfTail(2, moves)
}
private fun part2(input: String): Int {
val moves = parseInput(input)
return countPositionsOfTail(10, moves)
}
private fun countPositionsOfTail(ropeLength: Int, moves: List<Direction>): Int {
val startPosition = Rope(List(ropeLength) { Coord2.ZERO })
val positions = moves.fold(listOf(startPosition)) { positions, move ->
positions + positions.last().move(move)
}
return positions.map {
it.nodes.last()
}.toSet().size
}
private fun parseInput(input: String): List<Direction> {
return input.lines().flatMap { line ->
val (dir, count) = line.split(" ")
val direction = Direction.fromString(dir)
val amount = count.toInt()
List(amount) { direction }
}
}
data class Rope(val nodes: List<Coord2>) {
fun move(direction: Direction): Rope {
val newNodes =nodes.fold(listOf<Coord2>()) { rope, node ->
if (rope.isEmpty()) rope + (node + direction)
else rope + moveTailToHead(node, rope.last())
}
return Rope(newNodes)
}
}
private fun moveTailToHead(tail: Coord2, head: Coord2): Coord2 {
val xDiff = head.x - tail.x
val yDiff = head.y - tail.y
val isDiagonal = abs(xDiff) > 0 && abs(yDiff) > 1 || abs(yDiff) > 0 && abs(xDiff) > 1
if (isDiagonal) {
return tail + Coord2(sign(xDiff), sign(yDiff))
}
return tail + Coord2(singleDimensionPull(xDiff), singleDimensionPull(yDiff))
}
private fun singleDimensionPull(int: Int): Int {
if (int == 1) return 0
if (int == -1) return 0
return sign(int)
}
private fun Direction.Companion.fromString(dir: String) = when (dir) {
"R" -> Direction.RIGHT
"L" -> Direction.LEFT
"U" -> Direction.UP
"D" -> Direction.DOWN
else -> error("unknown direction $dir")
} | 0 | Kotlin | 0 | 0 | 1751869e237afa3b8466b213dd095f051ac49bef | 2,502 | advent_of_code_2022 | MIT License |
src/Day12.kt | rweekers | 573,305,041 | false | {"Kotlin": 38747} | fun main() {
fun part1(input: List<String>): Int {
val grid = determineGrid(input)
val start: Point = input.determinePointFor("S")
val end: Point = input.determinePointFor("E")
return grid.shortestPathBFS(
begin = start,
end = end,
goalReached = { it == end },
moveAllowed = { from, to -> to - from <= 1 }
)
}
fun part2(input: List<String>): Int {
val grid = determineGrid(input)
val endPoint = input.determinePointFor("E")
val startPoints = buildList {
add(input.determinePointFor("S"))
addAll(input.determinePointsFor("a"))
}
return startPoints
.mapNotNull { startPoint ->
try {
grid.shortestPathBFS(
begin = startPoint,
end = endPoint,
goalReached = { it == endPoint },
moveAllowed = { from, to -> to - from <= 1 }
)
} catch (e: IllegalStateException) {
null
}
}
.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
private fun determineGrid(input: List<String>): Grid<Int> {
val gridPoints = input.flatMapIndexed { indexY, row ->
row.mapIndexed { indexX, c ->
val current = Point(indexX, indexY)
current to when (c) {
'S' -> 0
'E' -> 25
else -> c.code - 'a'.code
}
}
}.toMap()
return Grid(gridPoints)
}
| 0 | Kotlin | 0 | 1 | 276eae0afbc4fd9da596466e06866ae8a66c1807 | 1,863 | adventofcode-2022 | Apache License 2.0 |
hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_12928_divisors.kt | boris920308 | 618,428,844 | false | {"Kotlin": 137657, "Swift": 35553, "Java": 1947, "Rich Text Format": 407} | package main.kotlin.programmers.lv01
import kotlin.math.ceil
import kotlin.math.sqrt
/**
*
* https://school.programmers.co.kr/learn/courses/30/lessons/12928
*
* 문제 설명
* 정수 n을 입력받아 n의 약수를 모두 더한 값을 리턴하는 함수, solution을 완성해주세요.
*
* 제한 사항
* n은 0 이상 3000이하인 정수입니다.
* 입출력 예
* n return
* 12 28
* 5 6
* 입출력 예 설명
* 입출력 예 #1
* 12의 약수는 1, 2, 3, 4, 6, 12입니다. 이를 모두 더하면 28입니다.
*
* 입출력 예 #2
* 5의 약수는 1, 5입니다. 이를 모두 더하면 6입니다.
*/
private fun findDivisors(number: Int): List<Int> {
val divisors = mutableListOf<Int>()
if (number == 1) {
divisors.add(1)
}
val sqrt = ceil(sqrt(number.toDouble())).toInt()
println("get number = $number , sqrt = $sqrt")
for (i in 1 until sqrt) {
if (number % i == 0) {
divisors.add(i)
divisors.add(number / i)
}
}
if(sqrt * sqrt == number) {
divisors.add(sqrt)
}
return divisors
}
private fun solution(n: Int): Int {
if (n == 1) return 1
var answer = 0
val sqrt = ceil(sqrt(n.toDouble())).toInt()
for (i in 1 until sqrt) {
if (n % i == 0) {
answer += i
answer += (n / i)
}
}
if(sqrt * sqrt == n) {
answer += sqrt
}
return answer
}
fun main() {
println("findDivisors(0) = ${findDivisors(0).sorted()}")
println("input = 0, result = ${solution(0)}")
println(" * * * * * ")
println("findDivisors(1) = ${findDivisors(1).sorted()}")
println("input = 1, result = ${solution(1)}")
println(" * * * * * ")
println("findDivisors(2) = ${findDivisors(2).sorted()}")
println("input = 2, result = ${solution(2)}")
println(" * * * * * ")
println("findDivisors(16) = ${findDivisors(16).sorted()}")
println("input = 16, result = ${solution(16)}")
println(" * * * * * ")
} | 1 | Kotlin | 1 | 2 | 88814681f7ded76e8aa0fa7b85fe472769e760b4 | 2,023 | HoOne | Apache License 2.0 |
src/main/kotlin/_2019/Day12.kt | thebrightspark | 227,161,060 | false | {"Kotlin": 548420} | package _2019
import aocRun
import java.util.regex.Pattern
import kotlin.math.abs
private val pattern = Pattern.compile("<x=(?<x>-?\\d+), y=(?<y>-?\\d+), z=(?<z>-?\\d+)>")
fun main() {
aocRun(puzzleInput) { input ->
val moons = parseMoons(input)
repeat(1000) {
moveMoons(moons)
// if ((it + 1) % 10 == 0)
// println("I: ${(it + 1)}\n${moonsToString(moons)}")
}
return@aocRun calcTotalEnergy(moons)
}
aocRun(puzzleInput) { input ->
val moons = parseMoons(input)
val initialState = moons.map { Moon(it.pos.copy(), it.vel.copy()) }
var steps = 0
val loopLength = MutableTriple(0, 0, 0)
do {
moveMoons(moons)
steps++
if (loopLength.x == 0 && moonAxisMatches(initialState, moons) { it.x }) {
loopLength.x = steps
println("Found X loop length: $steps")
}
if (loopLength.y == 0 && moonAxisMatches(initialState, moons) { it.y }) {
loopLength.y = steps
println("Found Y loop length: $steps")
}
if (loopLength.z == 0 && moonAxisMatches(initialState, moons) { it.z }) {
loopLength.z = steps
println("Found Z loop length: $steps")
}
if (loopLength.x != 0 && loopLength.y != 0 && loopLength.z != 0)
break
} while (initialState != moons)
val lcm = lcm(loopLength.x, loopLength.y, loopLength.z)
return@aocRun "$loopLength -> $lcm"
}
}
private fun moonsToString(moons: List<Moon>) = moons.joinToString("\n")
private fun parseMoons(input: String): List<Moon> = input.split("\n").map { posString ->
val matcher = pattern.matcher(posString)
if (!matcher.matches())
throw RuntimeException("Invalid position input: $posString")
return@map Moon(MutableTriple(matcher.group("x").toInt(), matcher.group("y").toInt(), matcher.group("z").toInt()))
}
private fun moveMoons(moons: List<Moon>) {
val oldMoons = moons.toList()
moons.forEachIndexed new@{ i, moon ->
oldMoons.forEachIndexed old@{ oldI, oldMoon ->
if (i == oldI) return@old
moon.applyGravity(oldMoon)
}
}
moons.forEach { it.move() }
}
private fun calcTotalEnergy(moons: List<Moon>): Int = moons.sumBy {
val potential = it.pos.run { abs(x) + abs(y) + abs(z) }
val kinetic = it.vel.run { abs(x) + abs(y) + abs(z) }
val total = potential * kinetic
// println("$it\nPot: $potential\tKin: $kinetic\tTotal: $total")
return@sumBy total
}
private fun moonAxisMatches(
initialState: List<Moon>,
currentState: List<Moon>,
axisSelector: (MutableTriple) -> Int
): Boolean {
currentState.forEachIndexed { index, moon ->
val initialMoon = initialState[index]
if (axisSelector(moon.pos) != axisSelector(initialMoon.pos) || axisSelector(moon.vel) != axisSelector(
initialMoon.vel
)
)
return false
}
return true
}
private fun lcm(vararg ints: Int): Long = lcmInternal(num = ints.maxOrNull()!!.toLong(), ints = ints.map { it.toLong() })
private tailrec fun lcmInternal(num: Long, increment: Long = num, ints: List<Long>): Long =
if (ints.all { num % it == 0.toLong() }) num else lcmInternal(num + increment, increment, ints)
private data class MutableTriple(var x: Int, var y: Int, var z: Int)
private data class Moon(val pos: MutableTriple, val vel: MutableTriple = MutableTriple(0, 0, 0)) {
fun applyGravity(other: Moon) {
vel.x += other.pos.x.compareTo(pos.x)
vel.y += other.pos.y.compareTo(pos.y)
vel.z += other.pos.z.compareTo(pos.z)
}
fun move() {
pos.x += vel.x
pos.y += vel.y
pos.z += vel.z
}
}
private val testInput1 = """
<x=-1, y=0, z=2>
<x=2, y=-10, z=-7>
<x=4, y=-8, z=8>
<x=3, y=5, z=-1>
""".trimIndent()
private val testInput2 = """
<x=-8, y=-10, z=0>
<x=5, y=5, z=10>
<x=2, y=-7, z=3>
<x=9, y=-8, z=-3>
""".trimIndent()
private val puzzleInput = """
<x=4, y=12, z=13>
<x=-9, y=14, z=-3>
<x=-7, y=-1, z=2>
<x=-11, y=17, z=-1>
""".trimMargin() | 0 | Kotlin | 0 | 0 | ac62ce8aeaed065f8fbd11e30368bfe5d31b7033 | 4,211 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/main/kotlin/day3.kt | kevinrobayna | 436,414,545 | false | {"Ruby": 195446, "Kotlin": 42719, "Shell": 1288} | import java.util.stream.Collectors
// https://adventofcode.com/2020/day/3
class Day3(
private val forest: List<List<String>>,
private val down: Int,
private val right: Int,
) {
companion object {
const val TREE = "#"
}
fun solve(): Long {
var position = Pair(0, 0)
var treeCount: Long = 0
for (levels in forest.indices) {
if (isTree(position.first, position.second)) {
treeCount++
}
position = next(position.first, position.second)
if (position.first > forest.size) {
return treeCount
}
}
return treeCount
}
fun next(x: Int, y: Int): Pair<Int, Int> {
return Pair(x.plus(down), y.plus(right) % forest[0].size)
}
fun isTree(x: Int, y: Int): Boolean {
return forest[x][y] == TREE
}
}
class Part2Day3(
private val forest: List<List<String>>,
private val routes: List<Pair<Int, Int>>,
) {
fun solve(): Long {
var solution: Long = 1
val solutions = routes.stream().map {
val s = Day3(forest, it.first, it.second).solve()
println("solution with route $it = $s")
s
}.collect(Collectors.toList())
for (x: Long in solutions) {
solution = solution.times(x)
}
return solution
}
}
fun main() {
val problem: List<List<String>> = buildMapFromString(Day3::class.java.getResource("day3.txt").readText())
println("solution = ${Day3(problem, 1, 3).solve()}")
val routes = listOf(
Pair(1, 1),
Pair(1, 3),
Pair(1, 5),
Pair(1, 7),
Pair(2, 1),
)
println("solution_Part = ${Part2Day3(problem, routes).solve()}")
}
fun buildMapFromString(text: String): List<List<String>> = text
.split('\n')
.stream()
.map { line ->
line.trim()
.split("")
.stream()
.filter { it != "" }
.collect(Collectors.toList())
}
.collect(Collectors.toList()) | 0 | Ruby | 0 | 0 | 9e48ecdebdb4c479ef00f0fd3b1a44a211fb6577 | 2,064 | adventofcode_2020 | MIT License |
src/Day10.kt | EdoFanuel | 575,561,680 | false | {"Kotlin": 80963} | import java.util.*
fun main() {
fun readState(input: List<String>): TreeMap<Int, Int> {
var cycle = 0
var signal = 1
val state = TreeMap<Int, Int>()
for (line in input) {
when {
line == "noop" -> cycle++
line.startsWith("addx") -> {
cycle++
val increment = line.split(" ")[1].toInt()
signal += increment
cycle++
}
}
state[cycle] = signal
}
return state
}
fun part1(state: TreeMap<Int, Int>): Int {
return listOf(20, 60, 100, 140, 180, 220).sumOf { it * (state.lowerEntry(it)?.value ?: 0) }
}
fun part2(state: TreeMap<Int, Int>): String {
val sb = StringBuilder()
for (i in 0 until state.keys.max()) {
if (i % 40 == 0) sb.append('\n')
val pointer = state.lowerEntry(i + 1)?.value ?: 1
sb.append(if (i % 40 in pointer - 1..pointer + 1) '#' else '.')
}
return sb.toString()
}
val test = readInput("Day10_test")
val testState = readState(test)
println(part1(testState))
println(part2(testState))
val input = readInput("Day10")
val state = readState(input)
println(part1(state))
println(part2(state))
}
| 0 | Kotlin | 0 | 0 | 46a776181e5c9ade0b5e88aa3c918f29b1659b4c | 1,349 | Advent-Of-Code-2022 | Apache License 2.0 |
src/day07/Day07.kt | devEyosiyas | 576,863,541 | false | null | package day07
import println
import readInput
fun main() {
fun String.isDigit() = all { it in '0'..'9' }
fun processFileSystem(input: List<String>): Map<String, Long> {
val sizes = mutableMapOf<String, Long>()
var path = mutableListOf<String>()
input.forEach {
val split = it.split(" ")
if (split[0] == "$" && split[1] == "cd") {
if (split[2] == "..") path = path.dropLast(1).toMutableList()
else path.add(split[2])
} else if (split[0].isDigit()) {
path.map { p ->
var dir = path.subList(0, path.indexOf(p) + 1).joinToString("/")
if (dir.startsWith("//")) dir.drop(1).also { d -> dir = d }
if (sizes[dir] == null) sizes[dir] = 0
sizes[dir] = sizes[dir]!! + split[0].toLong()
}
}
}
return sizes
}
fun partOne(input: List<String>, limit: Long): Long {
return processFileSystem(input).map { it.value }.filter { it <= limit }.sum()
}
fun partTwo(input: List<String>, updateSize: Long): Long {
val requiredSpace = updateSize - (70_000_000 - processFileSystem(input)["/"]!!)
return processFileSystem(input).toList().sortedBy { it.second }.first { it.second >= requiredSpace }.second
}
val testInput = readInput("day07", true)
val input = readInput("day07")
// part one
partOne(testInput, 100_000).println()
partOne(input, 100_000).println()
// part two
partTwo(testInput, 30_000_000).println()
partTwo(input, 30_000_000).println()
} | 0 | Kotlin | 0 | 0 | 91d94b50153bdab1a4d972f57108d6c0ea712b0e | 1,651 | advent_of_code_2022 | Apache License 2.0 |
src/day2/Day02.kt | mmilenkov | 573,101,780 | false | {"Kotlin": 9427} | package day2
import readText
sealed class Shape(val score: Int) {
object Rock: Shape(1)
object Paper: Shape(2)
object Scissors: Shape(3)
companion object {
fun toShape(input: String): Shape {
return if (isPaper(input)) {
Paper
} else if (isRock(input)) {
Rock
} else {
Scissors
}
}
private fun isRock(input: String) = "A" == input || "X" == input
private fun isPaper(input: String) = "B" == input || "Y" == input
}
}
fun main() {
fun part1() {
fun isWin(player:Shape, opponent: Shape): Boolean {
if (player == Shape.Rock && opponent == Shape.Scissors) {
return true
} else if (player == Shape.Paper && opponent == Shape.Rock) {
return true
} else if (player == Shape.Scissors && opponent == Shape.Paper) {
return true
}
return false
}
fun calculateRoundScore(opponent: String, player: String): Int {
val playerShape = Shape.toShape(player)
val opponentShape = Shape.toShape(opponent)
var score = playerShape.score
score += if (playerShape == opponentShape) {
3
} else if (isWin(playerShape, opponentShape)) {
6
} else {
0
}
return score
}
fun calculate(round: String) = round.split("\n")
.map { split ->
split.split(" ")
}.sumOf { game ->
calculateRoundScore(game[0], game[1])
}
println(calculate(readText("day2")))
}
fun part2() {
fun toWinningShape(input: Shape): Shape {
return when (input) {
Shape.Paper -> {
Shape.Scissors
}
Shape.Rock -> {
Shape.Paper
}
else -> {
Shape.Rock
}
}
}
fun toLoseShape(input: Shape): Shape {
return when (input) {
Shape.Rock -> {
Shape.Scissors
}
Shape.Scissors -> {
Shape.Paper
}
else -> {
Shape.Rock
}
}
}
fun calculateRoundScore(opponent: String, round: String): Int {
val opponentShape = Shape.toShape(opponent)
val score = when (round) {
"Y" -> {
3 + opponentShape.score
}
"Z" -> {
6 + toWinningShape(opponentShape).score
}
else -> {
toLoseShape(opponentShape).score
}
}
return score
}
fun calculate(round: String) = round.split("\n")
.map { split ->
split.split(" ")
}.sumOf { game ->
calculateRoundScore(game[0], game[1])
}
println(calculate(readText("day2")))
}
part1()
part2()
} | 0 | Kotlin | 0 | 0 | 991df03f2dcffc9fa4596f6dbbc4953c95fcd17c | 3,275 | AdventOfCode2022 | Apache License 2.0 |
app/src/main/java/com/employees/domain/BusinessLogic.kt | nicolegeorgieva | 621,254,848 | false | null | package com.employees.domain
import com.employees.domain.data.Employee
import com.employees.domain.data.TaskResult
import java.time.LocalDate
import java.time.temporal.ChronoUnit
/**
* Finds the pair of employees who have worked together on common projects
* for the longest period of time.
*
* @param employees A list of [Employee] objects.
* @return A [TaskResult] object containing the employee IDs, common project IDs, and days worked,
* or null if no matching pair is found.
*/
fun longestWorkingTogetherEmployees(employees: List<Employee>): TaskResult? {
val projectGroups = employees.groupBy { it.projectId }
val pairProjects = mutableMapOf<Pair<Int, Int>, MutableList<Pair<Int, Long>>>()
for ((_, group) in projectGroups) {
calculatePairProjects(group, pairProjects)
}
val longestWorkingPair =
pairProjects.maxByOrNull { it.value.sumBy { project -> project.second.toInt() } }
return if (longestWorkingPair != null) {
val (emp1Id, emp2Id) = longestWorkingPair.key
val projectsAndDays = longestWorkingPair.value
val commonProjects = projectsAndDays.map { it.first }
val daysWorked = projectsAndDays.map { it.second }
TaskResult(emp1Id, emp2Id, commonProjects.toList(), daysWorked.toList())
} else {
null
}
}
/**
* Processes a list of employees working on a project and updates the pairProjects map with
* the project ID and overlapping days for each pair of employees.
*
* @param group A list of [Employee] objects working on the same project.
* @param pairProjects A mutable map containing pairs of employee IDs as keys and a list of
* project ID - overlapping days pairs as values.
*/
fun calculatePairProjects(
group: List<Employee>,
pairProjects: MutableMap<Pair<Int, Int>, MutableList<Pair<Int, Long>>>
) {
for (i in group.indices) {
for (j in i + 1 until group.size) {
val emp1 = group[i]
val emp2 = group[j]
val overlappingDuration =
calculateOverlappingDuration(emp1.dateFrom, emp1.dateTo, emp2.dateFrom, emp2.dateTo)
if (overlappingDuration > 0) {
val pair = emp1.empId to emp2.empId
val projectId = emp1.projectId
pairProjects.getOrPut(pair) { mutableListOf() }
.add(Pair(projectId, overlappingDuration))
}
}
}
}
/**
* Calculates the overlapping days between two date ranges.
*
* @param date1From The start date of the first date range.
* @param date1To The end date of the first date range.
* @param date2From The start date of the second date range.
* @param date2To The end date of the second date range.
* @return The number of overlapping days between the two date ranges, or 0 if there is no overlap.
*/
fun calculateOverlappingDuration(
date1From: LocalDate,
date1To: LocalDate,
date2From: LocalDate,
date2To: LocalDate
): Long {
val start = maxOf(date1From, date2From)
val end = minOf(date1To, date2To)
return if (start.isBefore(end) || start.isEqual(end)) ChronoUnit.DAYS.between(
start,
end
) + 1 else 0
} | 0 | Kotlin | 0 | 0 | 227c7ef3c7b56b70cd37f666c22a3ac47cb086bb | 3,209 | nicole-georgieva-employees | MIT License |
src/main/kotlin/com/groundsfam/advent/y2023/d12/Day12.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2023.d12
import com.groundsfam.advent.DATAPATH
import com.groundsfam.advent.timed
import kotlin.io.path.div
import kotlin.io.path.useLines
// e.g. SpringRecord(".??..??...?##.", listOf(1, 1, 3))
data class SpringRecord(val row: String, val brokenCounts: List<Int>)
fun SpringRecord.unfold() = SpringRecord(
(0 until 5).joinToString("?") { row },
(0 until 5).flatMap { brokenCounts }
)
fun springArrangements(row: String, brokenGroupLengths: List<Int>): Long {
// cache[i][j], if set, equals the number of arrangements of springs
// for the substring row[i..] and the sublist brokenCounts[j..]
val cache = Array(row.length) {
LongArray(brokenGroupLengths.size + 1) { -1L }
}
// from inclusive, to exclusive
fun brokenGroupPossible(from: Int, to: Int): Boolean = when {
to > row.length -> {
// not enough springs remaining
false
}
to == row.length -> {
// all in range must not be marked as working
(from until to).all { row[it] != '.' }
}
else -> {
// all in range must not be marked as working,
// and the following spring must not be marked as broken
(from until to).all { row[it] != '.' } && row[to] != '#'
}
}
fun compute(i: Int, j: Int): Long {
if (i == row.length) {
return if (j == brokenGroupLengths.size) 1 else 0
}
if (cache[i][j] != -1L) {
return cache[i][j]
}
fun computeWorking(): Long =
compute(i + 1, j)
fun computeBroken(): Long {
if (j == brokenGroupLengths.size) {
return 0
}
// index of the end of the group, exclusive
val endGroupIdx = i + brokenGroupLengths[j]
if (!brokenGroupPossible(i, endGroupIdx)) {
return 0
}
if (endGroupIdx == row.length) {
// reached end of row -- this is a successful arrangement precisely when
// there are no more groups to build
return if (j == brokenGroupLengths.size - 1) 1 else 0
}
// set i to position after end of this group, including the working spring
// that ends this group, and increment j
return compute(endGroupIdx + 1, j + 1)
}
return when (val c = row[i]) {
'.' -> computeWorking()
'#' -> computeBroken()
'?' -> computeWorking() + computeBroken()
else -> throw RuntimeException("Illegal character in spring record: $c")
}
.also { cache[i][j] = it }
}
return compute(0, 0)
}
fun main() = timed {
val springRecords: List<SpringRecord> = (DATAPATH / "2023/day12.txt").useLines { lines ->
lines.mapTo(mutableListOf()) { line ->
val (row, countsStr) = line.split(" ", limit = 2)
val counts = countsStr.split(",").map(String::toInt)
SpringRecord(row, counts)
}
}
springRecords
.sumOf { (row, counts) ->
springArrangements(row, counts)
}
.also { println("Part one: $it") }
springRecords
.map(SpringRecord::unfold)
.sumOf { (row, counts) ->
springArrangements(row, counts)
}
.also { println("Part two: $it") }
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 3,432 | advent-of-code | MIT License |
src/day-8.kt | drademacher | 160,820,401 | false | null | import java.io.File
fun main(args: Array<String>) {
println("part 1: " + partOne())
println("part 2: " + partTwo())
}
private data class Node(val children: List<Node>, val metadata: List<Int>)
private fun partOne(): Int {
val rawFile = File("res/day-8.txt").readText()
val numbers = rawFile
.filter { it != '\n' }
.split(" ")
.filter { it != "" }
.map { it.toInt() }
val (root, _) = parseToTree(numbers, 0)
return sumOfMetadata(root)
}
private fun partTwo(): Int {
val rawFile = File("res/day-8.txt").readText()
val numbers = rawFile
.filter { it != '\n' }
.split(" ")
.filter { it != "" }
.map { it.toInt() }
val (root, _) = parseToTree(numbers, 0)
return puzzleSum(root)
}
private fun parseToTree(numbers: List<Int>, offset: Int): Pair<Node, Int> {
val numberOfChildren = numbers[offset + 0]
val numberOfMetaData = numbers[offset + 1]
val children = mutableListOf<Node>()
var currentOffset = offset + 2
for (i in 1..numberOfChildren) {
val pair = parseToTree(numbers, currentOffset)
children.add(pair.first)
currentOffset = pair.second
}
val metadata = numbers.slice(currentOffset until currentOffset + numberOfMetaData)
currentOffset += numberOfMetaData
return Pair(Node(children, metadata), currentOffset)
}
private fun sumOfMetadata(node: Node): Int {
return node.metadata.sum() + node.children.map { sumOfMetadata(it) }.sum()
}
private fun puzzleSum(node: Node): Int {
if (node.children.isEmpty()) {
return node.metadata.sum()
}
return node.metadata
.filter { node.children.size >= it }
.map { node.children[it - 1] }
.map { puzzleSum(it) }
.sum()
} | 0 | Kotlin | 0 | 0 | a7f04450406a08a5d9320271148e0ae226f34ac3 | 1,840 | advent-of-code-2018 | MIT License |
src/main/kotlin/dev/paulshields/aoc/day10/AdapterArray.kt | Pkshields | 318,658,287 | false | null | package dev.paulshields.aoc.day10
import dev.paulshields.aoc.common.readFileAsStringList
fun main() {
println(" ** Day 10: Adapter Array ** \n")
val joltageAdapters = readFileAsStringList("/day10/JoltageAdapters.txt")
.mapNotNull { it.toIntOrNull() }
.let { compileListOfJoltageAdaptors(it) }
val differencesInJoltage = countNumberOfDifferencesBetweenJoltageInAdapterChain(joltageAdapters)
val countOf1JoltDifferences = differencesInJoltage[1] ?: 0
val countOf3JoltDifferences = differencesInJoltage[3] ?: 0
val part1Answer = countOf1JoltDifferences * countOf3JoltDifferences
println("$countOf1JoltDifferences have a 1 jolt difference between adapters, " +
"$countOf3JoltDifferences have a 3 jolt difference between adapters, " +
"thus the answer is ${part1Answer}!")
val differentAdapterArrangementsCount = countNumberOfPotentialAdapterChains(joltageAdapters.sorted())
println("The number of different valid adapter arrangements is $differentAdapterArrangementsCount!")
}
fun compileListOfJoltageAdaptors(adaptersInBag: List<Int>) = adaptersInBag
.toMutableList()
.also {
it.add(0, 0)
it.add(max(it) + 3)
}
.toList()
private fun max(list: Iterable<Int>) = list.maxOrNull() ?: 0
fun countNumberOfDifferencesBetweenJoltageInAdapterChain(joltageAdapters: List<Int>): Map<Int, Int> {
val sortedAdaptors = joltageAdapters.sorted()
return sortedAdaptors
.drop(1)
.mapIndexed { index, item -> item - sortedAdaptors[index] }
.groupingBy { it }
.eachCount()
}
fun countNumberOfPotentialAdapterChains(joltageAdapters: List<Int>) =
countNumberOfPotentialAdapterChainsAtPosition(
joltageAdapters,
joltageAdapters.first(),
mutableMapOf(joltageAdapters.last() to 1))
private fun countNumberOfPotentialAdapterChainsAtPosition(
joltageAdapters: List<Int>,
nextElementInChain: Int = 0,
cache: MutableMap<Int, Long>): Long =
cache[nextElementInChain] ?: run {
(nextElementInChain+1 .. nextElementInChain+3)
.filter { joltageAdapters.contains(it) }
.map {
countNumberOfPotentialAdapterChainsAtPosition(joltageAdapters, it, cache)
.also { result -> cache[it] = result }
}
.sum()
} | 0 | Kotlin | 0 | 0 | a7bd42ee17fed44766cfdeb04d41459becd95803 | 2,360 | AdventOfCode2020 | MIT License |
src/day09/Day09_functional.kt | seastco | 574,758,881 | false | {"Kotlin": 72220} | package day09
import readLines
import kotlin.math.absoluteValue
import kotlin.math.sign
/**
* Credit goes to tginsberg (https://github.com/tginsberg/advent-2022-kotlin)
* I'm experimenting with his solutions to better learn functional programming in Kotlin.
* Files without the _functional suffix are my original solutions.
*/
private data class Point(val x: Int = 0, val y: Int = 0) {
fun move(direction: Char): Point =
when (direction) {
'U' -> copy(y = y + 1)
'D' -> copy(y = y - 1)
'L' -> copy(x = x - 1)
'R' -> copy(x = x + 1)
else -> throw IllegalArgumentException("Unknown Direction: $direction")
}
fun touches(other: Point): Boolean =
(x - other.x).absoluteValue <= 1 && (y - other.y).absoluteValue <= 1
fun moveTowards(other: Point): Point =
Point(
(other.x - x).sign + x,
(other.y - y).sign + y
)
}
private fun followPath(path: String, knots: Int): Int {
val rope = Array(knots) { Point() } // initialize rope array with n=knots Points
val tailVisits = mutableSetOf(Point())
path.forEach { direction ->
rope[0] = rope[0].move(direction)
rope.indices.windowed(2, 1) { (head, tail) -> // use windowed to go through [0,1],[1,0]...[8,9]
if (!rope[head].touches(rope[tail])) {
rope[tail] = rope[tail].moveTowards(rope[head])
}
}
tailVisits += rope.last()
}
return tailVisits.size
}
private fun part1(input: List<String>): Int {
val path: String = parseInput(input)
return followPath(path, 2)
}
private fun part2(input: List<String>): Int {
val path: String = parseInput(input)
return followPath(path, 10)
}
private fun parseInput(input: List<String>): String =
input.joinToString("") { row -> // for each row, translate "U 4" to "UUUU"
val direction = row.substringBefore(" ")
val numberOfMoves = row.substringAfter(' ').toInt()
direction.repeat(numberOfMoves) // U.repeat(4) --> UUUU
}
fun main() {
println(part1(readLines("day09/test1")))
println(part2(readLines("day09/test2")))
} | 0 | Kotlin | 0 | 0 | 2d8f796089cd53afc6b575d4b4279e70d99875f5 | 2,190 | aoc2022 | Apache License 2.0 |
src/main/kotlin/me/camdenorrb/timorforest/tree/DecisionTree3.kt | camdenorrb | 202,772,314 | false | null | package me.camdenorrb.timorforest.tree
/*
import kotlin.math.pow
val trainingData0 = listOf(
listOf("Green", 3, "Apple"),
listOf("Yellow", 3, "Apple"),
listOf("Red", 1, "Grape"),
listOf("Red", 1, "Grape"),
listOf("Yellow", 3, "Lemon")
)
val trainingData1 = listOf(
listOf("Black", 2, "Cat"),
listOf("Brown", 3, "Duck"),
listOf("White", 4, "Dog")
)
fun main() {
val tree = buildTree(trainingData1)
//println(tree.data(listOf("dwedewwe", 3)))
printTree(tree)
}
fun buildTree(rows: List<List<Any>>): Tree {
val (gain, question) = findBestSplit(rows)
if (gain == 0.0) {
return Leaf(classCounts(rows))
}
val (trueRows, falseRows) = rows.partition { question!!.match(it) }
val trueBranch = buildTree(trueRows)
val falseBranch = buildTree(falseRows)
return Node(question!!, trueBranch, falseBranch)
}
fun findBestSplit(rows: List<List<Any>>): Pair<Double, Question?> {
var bestGain = 0.0
var bestQuestion: Question? = null
val currentUncertainty = gini(rows)
val nFeatures = rows[0].size - 1
for (column in 0 until nFeatures) {
val values = rows.fold(mutableListOf<Any>()) { list, next ->
list.add(next[column])
list
}
for (value in values) {
val question = Question(column, value)
val (trueRows, falseRows) = rows.partition { question.match(it) }
if (trueRows.isEmpty() || falseRows.isEmpty()) {
continue
}
val gain = infoGain(trueRows, falseRows, currentUncertainty)
if (gain >= bestGain) {
bestGain = gain
bestQuestion = question
}
}
}
return bestGain to bestQuestion
}
fun infoGain(trueRows: List<List<Any>>, falseRows: List<List<Any>>, currentUncertainty: Double): Double {
val p = trueRows.size.toDouble() / (trueRows.size.toDouble() + falseRows.size.toDouble())
return currentUncertainty - (p * gini(trueRows)) - (1 - p) * gini(falseRows)
}
fun gini(rows: List<List<Any>>): Double {
val counts = classCounts(rows)
var impurity = 1.0
for (value in counts.values) {
val probOfLabel = value.toDouble() / rows.size.toDouble()
impurity -= probOfLabel.pow(2.0)
}
return impurity
}
fun classCounts(rows: List<List<Any>>): Map<String, Int> {
val counts = mutableMapOf<String, Int>()
for (row in rows) {
counts.compute(row[row.size - 1] as String) { s: String, i: Int? ->
(i ?: 0) + 1
}
}
return counts
}
fun printTree(tree: Tree, spacing: String = " ")
{
when(tree)
{
is Leaf ->
{
println("${spacing}Predict: ${tree.predictions}")
}
is Node ->
{
println("${spacing}${tree.question}")
println("${spacing}-> True:")
printTree(tree.trueBranch, "$spacing ")
println("${spacing}-> False:")
printTree(tree.falseBranch, "$spacing ")
}
}
}
fun printLeaf(counts: Map<String, Int>): Map<String, String>
{
var total = 0.0
for (value in counts.values) {
total += value
}
val probs = mutableMapOf<String, String>()
for ((k, v) in counts) {
probs[k] = "${v / total * 100}%"
}
return probs
}
class Leaf(val predictions: Map<String, Int>) : Tree {
override fun data(rows: List<Any>): Map<String, Int> {
return predictions
}
}
class Node(val question: Question, val trueBranch: Tree, val falseBranch: Tree) : Tree {
override fun data(rows: List<Any>): Map<String, Int> {
return if (question.match(rows)) {
trueBranch.data(rows)
} else {
falseBranch.data(rows)
}
}
}
data class Question(val column: Int, val value: Any) {
fun match(rows: List<Any>): Boolean {
val value = rows[column]
if (value is Number) {
return value.toInt() >= this.value as Int
}
return value == this.value
}
}
interface Tree {
fun data(rows: List<Any>): Map<String, Int>
}*/ | 0 | Kotlin | 0 | 0 | b746f0ca27b587fbff4dcc08d97051f463cac53e | 4,184 | TimorForest | MIT License |
src/Day03.kt | andyludeveloper | 573,249,939 | false | {"Kotlin": 7818} | fun main() {
val ansChar = listOf(('a'..'z').toList(), ('A'..'Z').toList()).flatten()
fun part1(input: List<String>): Int {
return input.sumOf {
it.chunked(it.length / 2)
.let { compartment ->
compartment[0].filter { c: Char -> compartment[1].contains(c) }
.map { ans: Char -> ansChar.indexOf(ans) + 1 }
.take(1).single()
}
}
}
fun part2(input: List<String>): Int {
return input.chunked(3).sumOf {
it.let { compartment ->
compartment[0].filter { c: Char -> compartment[1].contains(c) && compartment[2].contains(c) }
.map { ans: Char -> ansChar.indexOf(ans) + 1 }
.take(1).single()
}
}
}
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
// val split0 = line1.subSequence(0, (line1.length) / 2)
// val split1 = line1.subSequence(line1.length / 2, line1.length)
// for (char: Char in chunked[0]) {
// if (chunked[1].contains(char)) {
// println(char)
// println(ansChar.indexOf(char) + 1)
// }
// }
// line1.chunked(line1.length / 2)
} | 0 | Kotlin | 0 | 1 | 684cf9ff315f15bf29914ca25b44cca87ceeeedf | 1,384 | Kotlin-in-Advent-of-Code-2022 | Apache License 2.0 |
src/d13.main.kts | cjfuller | 317,725,797 | false | null | import java.io.File
data class Bus(val number: Long, val offset: Long) {
fun arrivesAtCorrectOffset(t: Long): Boolean =
(t + offset) % number == 0L
}
fun parseInput(): Pair<Long, List<Bus>> {
val lines = File("./data/d13.txt").readLines()
val departureTime = lines[0].toLong()
val busses = lines[1]
.split(",")
.withIndex()
.map { (i, v) ->
Bus(
number = if (v == "x") {
-1L
} else {
v.toLong()
},
offset = i.toLong()
)
}
.filter { (v, _) -> v != -1L }
return Pair(departureTime, busses)
}
fun delayForBus(departureTime: Long, bus: Long): Long =
bus - (departureTime % bus)
val (departureTime, bussesWithOffset) = parseInput()
val busses = bussesWithOffset.map { it.number }
val bestBus = busses.minByOrNull { delayForBus(departureTime, it) }!!
println("Part 1:")
println("Best bus: $bestBus")
println("Result: ${bestBus * delayForBus(departureTime, bestBus)}")
println("Part 2:")
val orderedBusses = bussesWithOffset.sortedBy { it.number }.reversed()
fun findTForPair(lhs: Bus, rhs: Bus): Long {
var t: Long = (lhs.number - lhs.offset)
while (!rhs.arrivesAtCorrectOffset(t)) {
t += lhs.number
}
return t
}
val result = orderedBusses.reduce { b0, b1 ->
val t = findTForPair(b0, b1)
val combinedNum = b0.number * b1.number
println(t)
Bus(number = combinedNum, offset = combinedNum - (t % combinedNum))
}
println(result)
| 0 | Kotlin | 0 | 0 | c3812868da97838653048e63b4d9cb076af58a3b | 1,568 | adventofcode2020 | MIT License |
src/exercises/Day04.kt | Njko | 572,917,534 | false | {"Kotlin": 53729} | // ktlint-disable filename
package exercises
import readInput
fun main() {
fun isRangeIncludedInOther(
elf1: IntRange,
elf2: IntRange
): Boolean {
if (elf2.first < elf1.first) {
if (elf2.last >= elf1.last) {
return true
}
} else {
if (elf2.first == elf1.first) {
return true
}
if (elf2.last <= elf1.last) {
return true
}
}
return false
}
fun isRangeIncludedInOtherV2(
elf1: IntRange,
elf2: IntRange
): Boolean {
return elf1.intersect(elf2).containsAll(elf2.toList()) ||
elf2.intersect(elf1).containsAll(elf1.toList())
}
fun part1(input: List<String>): Int {
var numberOfValidPairs = 0
input.forEach { line ->
val bounds = line
.split(",")
.map {
it.split("-")
.let { (lowerBound, upperBound) ->
lowerBound.toInt()..upperBound.toInt()
}
}
val elf1 = bounds[0]
val elf2 = bounds[1]
if (isRangeIncludedInOtherV2(elf1, elf2)) {
numberOfValidPairs++
}
}
return numberOfValidPairs
}
fun part2(input: List<String>): Int {
var numberOfValidPairs = 0
input.forEach { line ->
val bounds = line
.split(",")
.map {
it.split("-")
.let { (lowerBound, upperBound) ->
lowerBound.toInt()..upperBound.toInt()
}
}
val elf1 = bounds[0]
val elf2 = bounds[1]
if (elf1.intersect(elf2).isNotEmpty()) {
numberOfValidPairs++
}
}
return numberOfValidPairs
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
println("Test results:")
println(part1(testInput))
check(part1(testInput) == 2)
check(isRangeIncludedInOtherV2(elf1 = 6..6, elf2 = 5..9))
println(part2(testInput))
check(part2(testInput) == 4)
val input = readInput("Day04")
println("Final results:")
println(part1(input))
check(part1(input) == 305)
println(part2(input))
check(part2(input) == 811)
}
| 0 | Kotlin | 0 | 2 | 68d0c8d0bcfb81c183786dfd7e02e6745024e396 | 2,501 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/headlessideas/adventofcode/december8/Counter.kt | Nandi | 113,094,752 | false | null | package com.headlessideas.adventofcode.december8
import com.headlessideas.adventofcode.utils.readFile
import kotlin.math.max
fun registerCounter(instructions: List<Instruction>) {
val register = mutableMapOf<String, Int>()
var maxValue = 0
instructions.forEach {
it.run(register)
maxValue = checkMax(register, maxValue)
}
println(register.maxBy { it.value }?.value ?: "Register empty")
println(maxValue)
}
fun checkMax(register: MutableMap<String, Int>, maxValue: Int): Int {
return max(register.maxBy { it.value }?.value ?: 0, maxValue)
}
fun main(args: Array<String>) {
val r = readFile("8.dec.txt").map {
val parts = it.split(" ")
Instruction(parts[0],
type(parts[1]),
parts[2].toInt(),
Logic.create(parts[4], parts[5], parts[6]))
}
registerCounter(r)
}
class Instruction(private val register: String, private val type: Type, private val amount: Int, private val logic: Logic) {
fun run(registers: MutableMap<String, Int>) {
var current = registers.getOrDefault(register, 0)
if (logic.test(registers)) {
current += when (type) {
Type.INC -> amount
Type.DEC -> -amount
}
}
registers[register] = current
}
}
class Logic(private val left: String, private val condition: Condition, private val right: Int) {
fun test(registers: Map<String, Int>): Boolean {
val amount = registers[left] ?: 0
return when (condition) {
Condition.BANG_EQUAL -> amount != right
Condition.EQUAL_EQUAL -> amount == right
Condition.GREATER -> amount > right
Condition.GREATER_EQUAL -> amount >= right
Condition.LESS -> amount < right
Condition.LESS_EQUAL -> amount <= right
}
}
companion object {
fun create(left: String, condition: String, right: String): Logic {
val c = when (condition) {
"!=" -> Condition.BANG_EQUAL
"==" -> Condition.EQUAL_EQUAL
">" -> Condition.GREATER
">=" -> Condition.GREATER_EQUAL
"<" -> Condition.LESS
"<=" -> Condition.LESS_EQUAL
else -> Condition.EQUAL_EQUAL
}
return Logic(left, c, right.toInt())
}
}
}
enum class Condition {
BANG_EQUAL, EQUAL_EQUAL, GREATER, GREATER_EQUAL, LESS, LESS_EQUAL
}
enum class Type {
INC, DEC
}
fun type(t: String): Type {
return when (t) {
"inc" -> Type.INC
"dec" -> Type.DEC
else -> Type.INC
}
} | 0 | Kotlin | 0 | 0 | 2d8f72b785cf53ff374e9322a84c001e525b9ee6 | 2,678 | adventofcode-2017 | MIT License |
src/day08/solution.kt | bohdandan | 729,357,703 | false | {"Kotlin": 80367} | package day08
import println
import readInput
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
fun main() {
class Puzzle {
var commands: String
var network: MutableMap<String, Pair<String, String>>
constructor(input: List<String>) {
commands = input[0]
network = emptyMap<String, Pair<String, String>>().toMutableMap()
(2..<input.size).forEach{it ->
val regex = Regex("""(\w+) = \((\w*), (\w*)\)""")
val matchResult = regex.find(input[it])!!
network[matchResult.groupValues[1]] = Pair(matchResult.groupValues[2], matchResult.groupValues[3])
}
}
fun goThroughNetwork(start: String, isEndNode: (String) -> Boolean): Long {
var numberOfSteps = 0L
var nextNode = start
do {
var commandIndex = (numberOfSteps % commands.length).toInt()
var entry = network[nextNode]!!
nextNode = if (commands[commandIndex] == 'L') entry.first else entry.second
numberOfSteps++
} while (!isEndNode(nextNode))
return numberOfSteps
}
fun countMaxSteps(): Long {
return goThroughNetwork("AAA") { str -> str == "ZZZ" }
}
fun lcm(number1: Long, number2: Long): Long {
if (number1 == 0L || number2 == 0L) {
return 0
}
val absNumber1 = abs(number1.toDouble()).toLong()
val absNumber2 = abs(number2.toDouble()).toLong()
val absHigherNumber = max(absNumber1.toDouble(), absNumber2.toDouble()).toLong()
val absLowerNumber = min(absNumber1.toDouble(), absNumber2.toDouble()).toLong()
var lcm = absHigherNumber
while (lcm % absLowerNumber != 0L) {
lcm += absHigherNumber
}
return lcm
}
fun countMaxStepsForParallelPath(): Long {
var loopSizes = network.keys.filter { it.endsWith('A') }
.map { goThroughNetwork(it) { str -> str.endsWith("Z")} }
.toList()
loopSizes.println()
var lcm = 1L;
loopSizes.forEach{loopSize ->
lcm = lcm(lcm, loopSize)
}
return lcm;
}
}
var testPuzzle = Puzzle(readInput("day08/test1"))
check(testPuzzle.countMaxSteps() == 2L)
var testPuzzle2 = Puzzle(readInput("day08/test2"))
check(testPuzzle2.countMaxSteps() == 6L)
var puzzle = Puzzle(readInput("day08/input"))
puzzle.countMaxSteps().println()
var testPuzzle3 = Puzzle(readInput("day08/test3"))
check(testPuzzle3.countMaxStepsForParallelPath() == 6L)
// 14,321,394,058,031
puzzle.countMaxStepsForParallelPath().println()
} | 0 | Kotlin | 0 | 0 | 92735c19035b87af79aba57ce5fae5d96dde3788 | 2,854 | advent-of-code-2023 | Apache License 2.0 |
src/Day19.kt | max-zhilin | 573,066,300 | false | {"Kotlin": 114003} | import java.util.*
data class Blueprint(val ore4Ore: Int, val ore4Clay: Int, val ore4Obsidian: Int, val clay4Obsidian: Int, val ore4Geode: Int, val obsidian4Geode: Int) {
companion object {
fun parse(s: String): Blueprint {
// Blueprint 1: Each ore robot costs 4 ore. Each clay robot costs 2 ore. Each obsidian robot costs 3 ore and 14 clay. Each geode robot costs 2 ore and 7 obsidian.
val regex = """Blueprint \d+: Each ore robot costs (\d+) ore\. Each clay robot costs (\d+) ore\. Each obsidian robot costs (\d+) ore and (\d+) clay\. Each geode robot costs (\d+) ore and (\d+) obsidian\."""
.toRegex()
return regex.matchEntire(s)//?.groupValues
//?.map { it.toInt() }
?.destructured
?.let { (ore4Ore, ore4Clay, ore4Obsidian, clay4Obsidian, ore4Geode, obsidian4Geode) ->
Blueprint(ore4Ore.toInt(), ore4Clay.toInt(), ore4Obsidian.toInt(), clay4Obsidian.toInt(), ore4Geode.toInt(), obsidian4Geode.toInt())
}
?: error("Bad input '$s'") }
}
}
fun main() {
fun part1(input: List<String>): Int {
var sum = 0
input.forEachIndexed { index, line ->
val blueprint = Blueprint.parse(line)
fun calc(time: Int, oreRobots: Int, clayRobots: Int, obsidianRobots: Int, geodeRobots: Int,
ore: Int, clay: Int, obsidian: Int): Int {
var geode = 0
with(blueprint) {
if (time in 1..2)
return geodeRobots * time + if (obsidian >= obsidian4Geode && ore >= ore4Geode) time - 1 else 0
if (obsidian >= obsidian4Geode && ore >= ore4Geode)
geode = maxOf(geode, calc(time - 1, oreRobots, clayRobots, obsidianRobots, geodeRobots + 1,
ore + oreRobots - ore4Geode, clay + clayRobots, obsidian + obsidianRobots - obsidian4Geode))
else if (clay >= clay4Obsidian && ore >= ore4Obsidian)
geode = maxOf(geode, calc(time - 1, oreRobots, clayRobots, obsidianRobots + 1, geodeRobots,
ore + oreRobots - ore4Obsidian, clay + clayRobots - clay4Obsidian, obsidian + obsidianRobots))
else if (ore >= ore4Clay)
geode = maxOf(geode, calc(time - 1, oreRobots, clayRobots + 1, obsidianRobots, geodeRobots,
ore + oreRobots - ore4Clay, clay + clayRobots, obsidian + obsidianRobots))
if (ore >= ore4Ore)
geode = maxOf(geode, calc(time - 1, oreRobots + 1, clayRobots, obsidianRobots, geodeRobots,
ore + oreRobots - ore4Ore, clay + clayRobots, obsidian + obsidianRobots))
geode = maxOf(geode, calc(time - 1, oreRobots, clayRobots, obsidianRobots, geodeRobots,
ore + oreRobots, clay + clayRobots, obsidian + obsidianRobots))
}
return geodeRobots + geode
}
var maxNumberOfGeodes = calc(time = 24, 1, 0, 0, 0, 0, 0, 0)
// var maxNumberOfGeodes = calc(time = 17, 1, 3, 0, 0, 1, 6, 0)
sum += maxNumberOfGeodes * (index + 1).also { println("$maxNumberOfGeodes") }
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 1
// input.forEachIndexed { index, line ->
input.take(3).forEach { line ->
val blueprint = Blueprint.parse(line)
val (maxOreRobots, maxClayRobots, maxObsidianRobots) = with(blueprint) {
listOf(maxOf(ore4Ore, ore4Clay, ore4Obsidian, ore4Geode),
clay4Obsidian ,// 2 + 1,
obsidian4Geode // 2 + 1
)
}
data class Params(val oreRobots: Int, val clayRobots: Int, val obsidianRobots: Int, val geodeRobots: Int, val ore: Int, val clay: Int, val obsidian: Int, val geode: Int)
val preset = mutableSetOf<Params>()
fun precalc(time: Int, oreRobots: Int, clayRobots: Int, obsidianRobots: Int, geodeRobots: Int, ore: Int, clay: Int, obsidian: Int, geode: Int) {
with(blueprint) {
if (time == 0) {
preset.add(Params(oreRobots, clayRobots, obsidianRobots, geodeRobots, ore, clay, obsidian, geode))
return
}
if (obsidian >= obsidian4Geode && ore >= ore4Geode)
precalc(time - 1, oreRobots, clayRobots, obsidianRobots, geodeRobots + 1,
ore + oreRobots - ore4Geode, clay + clayRobots, obsidian + obsidianRobots - obsidian4Geode, geode + geodeRobots)
if (obsidianRobots < maxObsidianRobots && clay >= clay4Obsidian && ore >= ore4Obsidian)
precalc(time - 1, oreRobots, clayRobots, obsidianRobots + 1, geodeRobots,
ore + oreRobots - ore4Obsidian, clay + clayRobots - clay4Obsidian, obsidian + obsidianRobots, geode + geodeRobots)
if (clayRobots < maxClayRobots && ore >= ore4Clay)
precalc(time - 1, oreRobots, clayRobots + 1, obsidianRobots, geodeRobots,
ore + oreRobots - ore4Clay, clay + clayRobots, obsidian + obsidianRobots, geode + geodeRobots)
if (oreRobots < maxOreRobots && ore >= ore4Ore)
precalc(time - 1, oreRobots + 1, clayRobots, obsidianRobots, geodeRobots,
ore + oreRobots - ore4Ore, clay + clayRobots, obsidian + obsidianRobots, geode + geodeRobots)
precalc(time - 1, oreRobots, clayRobots, obsidianRobots, geodeRobots,
ore + oreRobots, clay + clayRobots, obsidian + obsidianRobots, geode + geodeRobots)
}
}
var maxOre = 0; var maxClay = 0; var maxObsidian = 0
fun calc(time: Int, oreRobots: Int, clayRobots: Int, obsidianRobots: Int, geodeRobots: Int,
ore: Int, clay: Int, obsidian: Int): Int {
var geodes = 0
// maxOre = maxOf(maxOre, ore); maxClay = maxOf(maxClay, clay); maxObsidian = maxOf(maxObsidian, obsidian)
with(blueprint) {
if (time in 1..2)
return geodeRobots * time + if (obsidian >= obsidian4Geode && ore >= ore4Geode) time - 1 else 0
if (time == 3)
return geodeRobots * time + if (obsidian >= obsidian4Geode && ore >= ore4Geode)
if (obsidian - obsidian4Geode + obsidianRobots >= obsidian4Geode && ore - ore4Geode + oreRobots >= ore4Geode) 3 else 2
else if (obsidian + obsidianRobots >= obsidian4Geode && ore + oreRobots >= ore4Geode) 1 else 0
if (obsidian >= obsidian4Geode && ore >= ore4Geode)
geodes = maxOf(geodes, calc(time - 1, oreRobots, clayRobots, obsidianRobots, geodeRobots + 1,
ore + oreRobots - ore4Geode, clay + clayRobots, obsidian + obsidianRobots - obsidian4Geode))
// else
if (
obsidianRobots < maxObsidianRobots &&
clay >= clay4Obsidian && ore >= ore4Obsidian)
geodes = maxOf(geodes, calc(time - 1, oreRobots, clayRobots, obsidianRobots + 1, geodeRobots,
ore + oreRobots - ore4Obsidian, clay + clayRobots - clay4Obsidian, obsidian + obsidianRobots))
if (
// time > 8 &&
clayRobots < maxClayRobots &&
ore >= ore4Clay)
geodes = maxOf(geodes, calc(time - 1, oreRobots, clayRobots + 1, obsidianRobots, geodeRobots,
ore + oreRobots - ore4Clay, clay + clayRobots, obsidian + obsidianRobots))
if (
// time > 8 &&
oreRobots < maxOreRobots &&
ore >= ore4Ore)
geodes = maxOf(geodes, calc(time - 1, oreRobots + 1, clayRobots, obsidianRobots, geodeRobots,
ore + oreRobots - ore4Ore, clay + clayRobots, obsidian + obsidianRobots))
if (
// time > 5 &&
// ore < maxOreRobots * 4 && clay < maxClayRobots * 4 && //obsidian < maxObsidianRobots * 4 &&
true)
geodes = maxOf(geodes, calc(time - 1, oreRobots, clayRobots, obsidianRobots, geodeRobots,
ore + oreRobots, clay + clayRobots, obsidian + obsidianRobots))
}
return geodeRobots + geodes
}
val precalcTime = 22
precalc(precalcTime, 1, 0, 0, 0, 0, 0, 0, 0)
println("set size ${preset.size}")
var count = 0
// sum += (index + 1) * preset.maxOf { params ->
sum *= preset.maxOf { params ->
with(params) {
count++
if (count % 10000 == 0) print("*")
geode + calc(time = 32 - precalcTime, oreRobots, clayRobots, obsidianRobots, geodeRobots, ore, clay, obsidian)
}
}.also { println(); println(it) }
// println("max $maxOre $maxClay $maxObsidian")
}
return sum
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day19_test")
val testInput2 = readInput("Day19_test2")
// println(part1(testInput))
// check(part1(testInput2) == 33)
// check(part1(testInput) == 33)
// println(part2(testInput))
// println(part2(testInput2))
// check(part2(testInput) == 58)
@Suppress("UNUSED_VARIABLE")
val input = readInput("Day19")
// println(part1(input)) // = 1346
println(part2(input)) // = 7644
}
| 0 | Kotlin | 0 | 0 | d9dd7a33b404dc0d43576dfddbc9d066036f7326 | 10,123 | AoC-2022 | Apache License 2.0 |
src/Day5.kt | HenryCadogan | 574,509,648 | false | {"Kotlin": 12228} | fun main() {
val input = readInput("Day05")
fun part1(input: List<String>): String {
val structure = getStructure(input)
val actions = getActions(input)
return structure.performActions(actions).getTopElements()
}
fun part2(input: List<String>): String {
val structure = getStructure(input)
val actions = getActions(input)
return structure.performActions(actions, true).getTopElements()
}
println(part1(input))
println(part2(input))
}
typealias Structure = MutableList<MutableList<Char>>
private fun Structure.performActions(actions: List<Action>, reversed: Boolean = false): Structure {
actions.forEach{action ->
val itemsToMove = this[action.origin-1].takeLast(action.quantity).toMutableList()
this[action.origin-1] = this[action.origin-1].dropLast(action.quantity).toMutableList()
if(reversed){
itemsToMove.reverse()
}
this[action.destination-1].addAll(itemsToMove)
}
return this
}
private fun Structure.getTopElements(): String = this.map { it.last() }.joinToString("")
private fun getStructure(input: List<String>): Structure {
val structureText = input.takeWhile { it.isNotBlank() }
val numberOfLists: Int = structureText.last().filter { it.isDigit() }.max().digitToInt()
val structure = MutableList(numberOfLists) { mutableListOf<Char>() }
structureText.dropLast(1).forEachIndexed { rowIndex, string ->
string.mapIndexedNotNull { columnIndex, char ->
if (char.isLetter()) {
val structureIndex = (columnIndex / 4)
structure[structureIndex].add(0, char)
}
}
}
return structure
}
private fun getActions(input: List<String>): List<Action> {
val actionText = input.dropWhile { it.isNotBlank() }.drop(1)
return actionText.map { text ->
val numbers = text.split(" ").mapNotNull { it.toIntOrNull() }
Action(
quantity = numbers[0],
origin = numbers[1],
destination = numbers[2],
)
}
}
data class Action(
val quantity: Int,
val origin: Int,
val destination: Int,
){
override fun toString(): String = "Move $quantity from $origin to $destination"
} | 0 | Kotlin | 0 | 0 | 0a0999007cf16c11355fcf32fc8bc1c66828bbd8 | 2,278 | AOC2022 | Apache License 2.0 |
src/main/kotlin/com/colinodell/advent2022/Day19.kt | colinodell | 572,710,708 | false | {"Kotlin": 105421} | package com.colinodell.advent2022
class Day19(input: List<String>) {
private val blueprints = input.map {
val tokens = it.split(" ")
mapOf(
MaterialType.ORE to Materials(tokens[6].toInt(), 0, 0, 0),
MaterialType.CLAY to Materials(tokens[12].toInt(), 0, 0, 0),
MaterialType.OBSIDIAN to Materials(tokens[18].toInt(), tokens[21].toInt(), 0, 0),
MaterialType.GEODE to Materials(tokens[27].toInt(), 0, tokens[30].toInt(), 0),
)
}
fun solvePart1() = blueprints.mapIndexed { i, b -> calculateMaxGeodesWithBlueprint(b, 24) * (i + 1) }.sum()
fun solvePart2() = blueprints.take(3).productOf { calculateMaxGeodesWithBlueprint(it, 32) }
enum class MaterialType {
ORE,
CLAY,
OBSIDIAN,
GEODE
}
/**
* Basically a map of material type to count
*/
data class Materials(var ore: Int = 0, var clay: Int = 0, var obsidian: Int = 0, var geode: Int = 0) {
operator fun get(material: MaterialType) = when (material) {
MaterialType.ORE -> ore
MaterialType.CLAY -> clay
MaterialType.OBSIDIAN -> obsidian
MaterialType.GEODE -> geode
}
operator fun set(material: MaterialType, value: Int) = when (material) {
MaterialType.ORE -> ore = value
MaterialType.CLAY -> clay = value
MaterialType.OBSIDIAN -> obsidian = value
MaterialType.GEODE -> geode = value
}
}
/**
* Encapsulates the state of our recursive search
*/
data class State(val materials: Materials, val robots: Materials, val time: Int = 0)
private fun calculateMaxGeodesWithBlueprint(blueprint: Map<MaterialType, Materials>, maxTime: Int): Int {
val initialState = State(
// No materials to start
Materials(),
// One ore robot to start
Materials(ore = 1)
)
// Limit the number of robots to the amount necessary to gather enough materials to build one more robot each turn
val robotLimit = Materials(
blueprint.values.maxOf { it[MaterialType.ORE] },
blueprint.values.maxOf { it[MaterialType.CLAY] },
blueprint.values.maxOf { it[MaterialType.OBSIDIAN] },
// But don't limit geode robots
Int.MAX_VALUE,
)
return solveRecursive(blueprint, initialState, maxTime, robotLimit, 0)
}
private fun solveRecursive(blueprint: Map<MaterialType, Materials>, state: State, maxTime: Int, robotLimit: Materials, maxGeodes: Int): Int {
var maxGeodes = maxGeodes
// Create a new branch for each robot we can create
var robotRecipesToTry = blueprint.filterKeys { type -> state.robots[type] < robotLimit[type] }
for ((robotType, recipe) in robotRecipesToTry) {
// How long must we wait until we can create this new robot?
val buildTime = 1 + MaterialType.values().maxOf { type ->
when {
// We already have enough of this material to build the robot immediately, or we don't need this material at all (recipe[type] == 0)
recipe[type] <= state.materials[type] -> 0
// We don't have any robots that can collect this material yet
state.robots[type] == 0 -> maxTime + 1
// We have the necessary robots but not enough materials yet
else -> (recipe[type] - state.materials[type] + state.robots[type] - 1) / state.robots[type]
}
}
// If we can't build this robot before we run out of time, skip it
val timeUntilBuilt = state.time + buildTime
if (timeUntilBuilt >= maxTime) {
continue
}
// How many materials and robots would we have once this robot is built?
val newMaterials = Materials()
val newRobots = Materials()
MaterialType.values().forEach { type ->
newMaterials[type] = state.materials[type] + state.robots[type] * buildTime - recipe[type]
newRobots[type] = state.robots[type] + (if (type == robotType) 1 else 0)
}
// Can we beat the current maximum if we only build geode robots from this point forwards?
val remainingTime = maxTime - timeUntilBuilt
val geodesWeCouldCollect = (((remainingTime - 1) * remainingTime) / 2) + newMaterials[MaterialType.GEODE] + (remainingTime * newRobots[MaterialType.GEODE])
if (geodesWeCouldCollect < maxGeodes) {
continue
}
// We'll need to build some other robots
maxGeodes = solveRecursive(blueprint, State(newMaterials, newRobots, timeUntilBuilt), maxTime, robotLimit, maxGeodes)
}
return maxOf(maxGeodes, state.materials[MaterialType.GEODE] + state.robots[MaterialType.GEODE] * (maxTime - state.time))
}
}
| 0 | Kotlin | 0 | 1 | 32da24a888ddb8e8da122fa3e3a08fc2d4829180 | 5,031 | advent-2022 | MIT License |
y2018/src/main/kotlin/adventofcode/y2018/Day11.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2018
import adventofcode.io.AdventSolution
object Day11 : AdventSolution(2018, 11, "Chronal Charge") {
override fun solvePartOne(input: String): String {
val g = CumulativeGrid(300) { x, y -> power(x + 1, y + 1, input.toInt()) }
var maxP = 0
var answer = ""
for (x in 1..300 - 3) {
for (y in 1..300 - 3) {
val p = g.cumulative(x - 1, y - 1, 3)
if (p > maxP) {
maxP = p
answer = "${x + 1},${y + 1}"
}
}
}
return answer
}
override fun solvePartTwo(input: String): String {
val g = CumulativeGrid(300) { x, y -> power(x + 1, y + 1, input.toInt()) }
var maxP = 0
var answer = ""
for (sq in 1..300) {
for (x in 1..300 - sq) {
for (y in 1..300 - sq) {
val p = g.cumulative(x - 1, y - 1, sq)
if (p > maxP) {
maxP = p
answer = "${x + 1},${y + 1},$sq"
}
}
}
}
return answer
}
private fun power(x: Int, y: Int, serial: Int): Int {
val id = x + 10
val p = id * (id * y + serial)
return p / 100 % 10 - 5
}
private class CumulativeGrid(size: Int, value: (x: Int, y: Int) -> Int) {
private val g = List(size + 1) { IntArray(size + 1) }
init {
for (y in 1..size)
for (x in 1..size)
g[y][x] = value(x, y) + g[y - 1][x] + g[y][x - 1] - g[y - 1][x - 1]
}
fun cumulative(x: Int, y: Int, sq: Int): Int =
g[y + sq][x + sq] - g[y + sq][x] - g[y][x + sq] + g[y][x]
}
} | 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,806 | advent-of-code | MIT License |
src/year2022/day02/Solution.kt | LewsTherinTelescope | 573,240,975 | false | {"Kotlin": 33565} | package year2022.day02
import utils.runIt
fun main() = runIt(
testInput = """
A Y
B X
C Z
""".trimIndent(),
::part1,
testAnswerPart1 = 15,
::part2,
testAnswerPart2 = 12,
)
fun part1(input: String) = splitInput(input).fold(0) { acc, (them, you) ->
acc + playRound(them, xyzToAbc[you]!!)
}
fun part2(input: String) = splitInput(input).fold(0) { acc, (them, action) ->
acc + cheatRound(them, action)
}
fun splitInput(input: String) = input.split("\n").map { it.split(" ") }
val xyzToAbc = mapOf(
"X" to "A",
"Y" to "B",
"Z" to "C",
)
val shapeScores = mapOf(
"A" to 1,
"B" to 2,
"C" to 3,
)
val beatingShapes = mapOf(
"A" to "B",
"B" to "C",
"C" to "A",
)
val losingShapes = beatingShapes.map { (k, v) -> v to k }.toMap()
fun playRound(them: String, you: String): Int = shapeScores[you]!! + when (you) {
them -> 3
beatingShapes[them] -> 6
else -> 0
}
fun cheatRound(them: String, action: String): Int = playRound(
them,
you = when (action) {
"X" -> losingShapes[them]!!
"Y" -> them
"Z" -> beatingShapes[them]!!
else -> throw IllegalArgumentException("Invalid action: $action")
},
)
| 0 | Kotlin | 0 | 0 | ee18157a24765cb129f9fe3f2644994f61bb1365 | 1,127 | advent-of-code-kotlin | Do What The F*ck You Want To Public License |
src/main/kotlin/dev/kosmx/aoc23/poker/WellItsNot.kt | KosmX | 726,056,762 | false | {"Kotlin": 32011} | package dev.kosmx.aoc23.poker
import java.io.File
import java.math.BigInteger
fun main() {
val games = File("poker.txt").readLines().map {
var (cards, score) = it.split(" ")
//cards = cards.replace("J", "X") Uncomment it to solve Part1
Hand(cards) to score.toInt()
}.sortedByDescending { it.first }
println(games.filter { game -> game.first.cards.any { it == WILDCARD } }.joinToString("\n"))
var score = BigInteger.ZERO
for (i in games.indices) {
score += BigInteger.valueOf(games[i].second.toLong()) * BigInteger.valueOf(i.toLong()+1)
}
println("Part1: Total score is $score")
}
data class Card(val letter: Char) : Comparable<Card> {
private companion object {
val ordering = arrayOf('A', 'K', 'Q', 'X', 'T', '9', '8', '7', '6', '5', '4', '3', '2', 'J')
}
override fun compareTo(other: Card): Int {
return ordering.indexOf(this.letter).compareTo(ordering.indexOf(other.letter))
}
}
val WILDCARD = Card('J')
class Hand(input: String): Comparable<Hand> {
val cards: Array<Card>
init {
cards = input.map { Card(it) }.toTypedArray()
assert(cards.size == 5)
}
override fun compareTo(other: Hand): Int {
if (type == other.type) {
for (i in 0..<5) {
val c = cards[i].compareTo(other.cards[i])
if (c != 0) return c
}
}
return other.type.compareTo(type) // compare but inverted
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Hand
return cards.contentEquals(other.cards)
}
override fun hashCode(): Int {
return cards.contentHashCode()
}
override fun toString(): String {
return "Hand(cards=${cards.joinToString(separator = "") { it.letter.toString() }}, type=$type)"
}
val type: Int
get() {
val groups = cards.asSequence().groupingBy { it }.eachCount()
val wildcard = groups[Card('J')] ?: 0
return when {
//Only one type or two types including wildcard type. Any number of wildcard can exist in this case
// edge-case here: all joker
groups.size == 1 || groups.filter { it.key != WILDCARD }.any { it.value + wildcard == 5 } -> 6
// Max 3 wildcards here
//There is at least one group with size of four including wildcards.
//Max 3 wildcards, if there is more, that would make a five
// If there are 3 wildcards, this will happen anyway
groups.filter { it.key != WILDCARD }.any { it.value + wildcard == 4 } -> 5
// Max 2 wildcards and at least 3 groups
// 2 groups are easy: If the sizes are 1 and 4, it is a four, it can't be. Only 2 and 3 or 3 and 2 are possible...
// Wildcard case:
// 1 single element can't be again
// only possibility: 2, 2 and 1 wildcard which is matched
//groups.size == 2 || groups.size == 3 && wildcard != 0 -> 4 // there are only two types or three types with wildcards
groups.filter { it.key != WILDCARD }.size == 2 -> 4
// There is any three with wildcards
groups.any { it.value + wildcard == 3 } -> 3
// Max 1 wildcard
// if there would be more wildcards than 1, it would be a three
// 3 groups are impossible
// the wildcard will pair with a single card creating 1 extra group
else -> (groups.count { it.value >= 2 } + wildcard).coerceAtMost(2) // 2 1 or 0 // if we have at least 2 wildcards, it'll be a three in a kind, only one wildcard can exist
// which will increase the amount of groups but only to two
}
}
} | 0 | Kotlin | 0 | 0 | ad01ab8e9b8782d15928a7475bbbc5f69b2416c2 | 3,969 | advent-of-code23 | MIT License |
facebook/y2021/qual/a2.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package facebook.y2021.qual
private fun solve(from: Char = 'A', toInclusive: Char = 'Z'): Int {
val s = readLn()
val letters = toInclusive - from + 1
val inf = letters + 1
val e = List(letters) { IntArray(letters) { inf } }
repeat(readInt()) {
val (u, v) = readLn().map { it - from }
e[u][v] = 1
}
for (k in e.indices) {
e[k][k] = 0
for (i in e.indices) {
for (j in e.indices) {
e[i][j] = minOf(e[i][j], e[i][k] + e[k][j])
}
}
}
fun cost(k: Int): Int? {
return s.sumOf { c -> e[c - from][k].also { if (it == inf) return null } }
}
return e.indices.mapNotNull { cost(it) }.minOrNull() ?: -1
}
fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 779 | competitions | The Unlicense |
src/main/kotlin/Day03.kt | todynskyi | 573,152,718 | false | {"Kotlin": 47697} | fun main() {
fun List<String>.findCommonChar(): Char = map { it.toSet() }
.reduce { left, right -> left.intersect(right) }
.first()
fun Char.priority(): Int = when (this) {
in 'a'..'z' -> (this - 'a') + 1
in 'A'..'Z' -> (this - 'A') + 27
else -> 0
}
fun part1(input: List<String>): Int = input
.map {
listOf(
it.substring(0..it.length / 2),
it.substring(it.length / 2)
)
}
.map { it.findCommonChar() }.sumOf { it.priority() }
fun part2(input: List<String>): Int = input.chunked(3)
.map { it.findCommonChar() }
.sumOf { it.priority() }
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
println(part2(testInput))
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5f9d9037544e0ac4d5f900f57458cc4155488f2a | 967 | KotlinAdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/aoc/utils/graphs/Graph.kt | Arch-vile | 572,557,390 | false | {"Kotlin": 132454} | package aoc.utils.graphs
import aoc.utils.SortedLookup
import day16.Valve
// Not immutable by any means
data class Node<T>(var 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>): List<Node<T>> {
val distances = shortestDistances(start, target)
// Only consider nodes that were visited while searching for shortest distances
val allNodes = allNodes(start).filter { distances.containsKey(it) }
val path = mutableListOf(target)
var current = target
while (current != start) {
// Nodes that connect to current
val connected = allNodes.filter { it.edges.firstOrNull { it.target == current } != null }
// Out of those the closest to start is where we go
val closestToStart = connected.minByOrNull { distances[it]!! }!!
current = closestToStart
path.add(current)
}
return path.reversed()
}
fun <T> shortestDistance(start: Node<T>, target: Node<T>): Long? {
val distances = shortestDistances(start, target)
return distances[target]
}
/**
* Shortest distances from start to all other nodes. If target is given, will
* stop when shortest distance to target is found.
*/
fun <T> shortestDistances(start: Node<T>, target: Node<T>?): Map<Node<T>, Long> {
val unvisitedNodes = SortedLookup<Node<T>, Long>()
// Shortest distance to all nodes from start
val completedNodes = mutableMapOf<Node<T>, Long>()
val allNodes = allNodes(start)
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)
completedNodes[removed.first] = removed.second
if (unvisitedNodes.size() == 0) {
return completedNodes
}
if (removed.first === target) {
return completedNodes
} else {
current = unvisitedNodes.sortedByValue().filter { unvisitedNodes.containsKey(it.first) }.first().first
}
}
}
fun <T> shortestPath2(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.sortedByValue().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
}
fun allRoutes(
nodeCount: Int,
visited: Set<String>,
routeSoFar: List<Node<Valve>>
): List<List<Node<Valve>>> {
val current = routeSoFar.last()
// We have visited all nodes, no where to expand
if (visited.size == nodeCount) {
return listOf( routeSoFar);
}
// Can we get to new place from this node?
val neighboursToVisit = current.edges.filter { !visited.contains(it.target.value.name) }
if (neighboursToVisit.isNotEmpty()) {
return neighboursToVisit.flatMap { allRoutes(nodeCount, visited.plus(it.target.value.name), routeSoFar.plus(it.target)) }
}
// Unvisited nodes remain, but cannot directly access any from current, kind of dead end that is
// Let's backtrack until we find a node that connects to an unvisited node
val reverseBackTo = routeSoFar.reversed().first {
val connectsTo = it.edges.map { it.target.value.name }
val unvisited = connectsTo.firstOrNull { !visited.contains(it) }
unvisited != null
}
// FIXME: It could be that the one we should start from is not the first one we found backtracking?
val pathToReverse = shortestPath(current,reverseBackTo)
return allRoutes(nodeCount, visited, routeSoFar + pathToReverse )
}
| 0 | Kotlin | 0 | 0 | e737bf3112e97b2221403fef6f77e994f331b7e9 | 6,315 | adventOfCode2022 | Apache License 2.0 |
src/shreckye/coursera/algorithms/GraphShortestPathAlgorithms.kt | ShreckYe | 205,871,625 | false | {"Kotlin": 72136} | package shreckye.coursera.algorithms
import kotlin.math.min
/* A number representing positive infinity in all these algorithms
When running algorithms, assuming all path distances in the graph are strictly smaller than this value */
const val POSITIVE_INFINITY_INT = Int.MAX_VALUE / 2
data class VertexDistance(val vertex: Int, val distance: Int)
fun dijkstraShortestPathDistances(
verticesEdges: VerticesSimplifiedEdges,
numVertices: Int,
fromVertex: Int,
initialDistance: Int = POSITIVE_INFINITY_INT
): IntArray {
val shortestDistances = IntArray(numVertices) { initialDistance }
val vertexShortestDistanceHeap = CustomPriorityQueue(numVertices, compareBy(VertexDistance::distance))
val vertexDistanceHeapHolders = arrayOfNulls<CustomPriorityQueue.Holder<VertexDistance>>(numVertices)
shortestDistances[fromVertex] = 0
vertexDistanceHeapHolders[fromVertex] = vertexShortestDistanceHeap.offerAndGetHolder(VertexDistance(fromVertex, 0))
repeat(numVertices) {
val (vertex, distance) = vertexShortestDistanceHeap.poll()
vertexDistanceHeapHolders[vertex] = null
for (edge in verticesEdges[vertex]) {
val head = edge.otherVertex
val headDistance = distance + edge.weight
if (shortestDistances[head] == initialDistance) {
shortestDistances[head] = headDistance
vertexDistanceHeapHolders[head] =
vertexShortestDistanceHeap.offerAndGetHolder(VertexDistance(head, headDistance))
} else if (headDistance < shortestDistances[head]) {
shortestDistances[head] = headDistance
vertexDistanceHeapHolders[head] = vertexShortestDistanceHeap.replaceByHolder(
vertexDistanceHeapHolders[head]!!,
VertexDistance(head, headDistance)
)
}
}
}
assert(vertexShortestDistanceHeap.isEmpty()) { "size = ${vertexShortestDistanceHeap.size}" }
return shortestDistances
}
fun bellmanFordShortestPathDistances(
inverseGraphVerticesEdges: VerticesSimplifiedEdges, numVertices: Int, fromVertex: Int
): IntArray? {
var lastShortestDistances = IntArray(numVertices) { POSITIVE_INFINITY_INT }
lastShortestDistances[fromVertex] = 0
var currentShortestDistances = IntArray(numVertices)
for (i in 1 until numVertices) {
var isUpdated = false
for (v in 0 until numVertices) {
val lastShortestDistance = lastShortestDistances[v]
val newShortestDistance = inverseGraphVerticesEdges[v].map { (otherVertex, weight) ->
lastShortestDistances[otherVertex] + weight
}.min()
if (newShortestDistance !== null && newShortestDistance < lastShortestDistance) {
currentShortestDistances[v] = newShortestDistance
isUpdated = true
} else
currentShortestDistances[v] = lastShortestDistance
}
if (!isUpdated)
return lastShortestDistances
val temp = lastShortestDistances
lastShortestDistances = currentShortestDistances
currentShortestDistances = temp
}
// There is a negative cycle
return null
}
fun floydWarshallAllPairsShortestPathDistances(
inverseGraphVerticesEdges: VerticesSimplifiedEdges, numVertices: Int
): Array<IntArray>? {
val shortestDistances = Array(numVertices) { IntArray(numVertices) { POSITIVE_INFINITY_INT } }
for (i in 0 until numVertices)
shortestDistances[i][i] = 0
for ((vertex, vertexEdges) in inverseGraphVerticesEdges.withIndex())
for ((otherVertex, weight) in vertexEdges)
shortestDistances[otherVertex][vertex] = weight
for (k in 0 until numVertices) {
for (i in 0 until numVertices)
for (j in 0 until numVertices)
shortestDistances[i][j] =
min(shortestDistances[i][j], shortestDistances[i][k] + shortestDistances[k][j])
if ((0 until numVertices).any { shortestDistances[it][it] < 0 })
return null
}
return shortestDistances
}
fun johnsonAllPairsShortestPathDistances(
verticesEdges: VerticesSimplifiedEdges, inverseGraphVerticesEdges: VerticesSimplifiedEdges, numVertices: Int
): Array<IntArray>? {
// Use the Bellman-Ford algorithm to reweight edges
val reweightingVertex = numVertices
val reweightingVertexInverseEdge = WeightedSimplifiedEdge(reweightingVertex, 0)
val reweightingInverseGraphVerticesEdges =
(inverseGraphVerticesEdges.map { it + reweightingVertexInverseEdge } + listOf(emptyList())).toTypedArray()
val reweightingShortestDistances =
bellmanFordShortestPathDistances(reweightingInverseGraphVerticesEdges, numVertices + 1, reweightingVertex)
if (reweightingShortestDistances === null) return null
val reweightedVerticesEdges = verticesEdges.mapIndexed { vertex, edges ->
edges.map { (otherVertex, weight) ->
WeightedSimplifiedEdge(
otherVertex,
(weight + reweightingShortestDistances[vertex] - reweightingShortestDistances[otherVertex])
.also { assert(it >= 0) }
)
}
}.toTypedArray()
// Run Dijkstra's algorithm from all vertices
return (0 until numVertices)
.map { tail ->
dijkstraShortestPathDistances(reweightedVerticesEdges, numVertices, tail).mapIndexed { head, distance ->
distance - reweightingShortestDistances[tail] + reweightingShortestDistances[head]
}.toIntArray()
}.toTypedArray()
} | 0 | Kotlin | 1 | 2 | 1746af789d016a26f3442f9bf47dc5ab10f49611 | 5,650 | coursera-stanford-algorithms-solutions-kotlin | MIT License |
src/main/kotlin/com/nibado/projects/advent/y2016/Day04.kt | nielsutrecht | 47,550,570 | false | null | package com.nibado.projects.advent.y2016
import com.nibado.projects.advent.Day
import com.nibado.projects.advent.resourceRegex
object Day04 : Day {
val comp : Comparator<Pair<Char, Int>> = compareByDescending<Pair<Char, Int>>{ it.second }.thenBy { it.first }
private val regex = Regex("([a-z-]+)-([0-9]+)\\[([a-z]+)]")
val input = resourceRegex(2016, 4, regex).map { Room(it[1], it[2].toInt(), it[3].toCharArray().toHashSet()) }
override fun part1() = input.filter { it.real() }.sumBy { it.sector }.toString()
override fun part2() = input.find { it.name() == "northpole object storage" }!!.sector.toString()
}
data class Room(val name: String, val sector: Int, val checksum: Set<Char>) {
fun counts() = name.toCharArray()
.filter { it != '-' }
.groupBy { it }
.map { Pair(it.key, it.value.size) }
.sortedWith(Day04.comp)
fun real() =
counts().subList(0, 5).map { it.first }.count { !checksum.contains(it) } == 0
fun name() = name.toCharArray().map { if(it == '-') ' ' else 'a' + (it - 'a' + sector % 26) % 26 }.joinToString("")
}
| 1 | Kotlin | 0 | 15 | b4221cdd75e07b2860abf6cdc27c165b979aa1c7 | 1,126 | adventofcode | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinimumTime.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.min
/**
* 2167. Minimum Time to Remove All Cars Containing Illegal Goods
* @see <a href="https://leetcode.com/problems/minimum-time-to-remove-all-cars-containing-illegal-goods">
* Source</a>
*/
fun interface MinimumTime {
operator fun invoke(s: String): Int
}
class MinimumTimeOnePass : MinimumTime {
override operator fun invoke(s: String): Int {
val n: Int = s.length
var left = 0
var res = n
for (i in 0 until n) {
left = min(left + (s[i] - '0') * 2, i + 1)
res = min(res, left + n - 1 - i)
}
return res
}
}
class MinimumTimePrefixSuffix : MinimumTime {
override operator fun invoke(s: String): Int {
if (s.isEmpty()) {
return 0
}
return calculateRes(s, calculateLeft(s), calculateRight(s))
}
private fun calculateRes(s: String, left: IntArray, right: IntArray, res: Int = Int.MAX_VALUE): Int {
var r = res
for (i in s.indices) {
if (i == 0) {
if (right[i] < r) {
r = right[i]
}
} else if (i == s.length - 1) {
if (left[i] < r) {
r = left[i]
}
} else {
if (left[i] + right[i + 1] < r) {
r = left[i] + right[i + 1]
}
}
}
return r
}
private fun calculateRight(s: String): IntArray {
val right = IntArray(s.length)
for (i in s.length - 1 downTo 0) {
if (s[i] == '1') {
right[i] = if (i == s.length - 1) 1 else min(right[i + 1] + 2, s.length - i)
} else {
right[i] = if (i == s.length - 1) 0 else right[i + 1]
}
}
return right
}
private fun calculateLeft(s: String): IntArray {
val left = IntArray(s.length)
for (i in s.indices) {
if (s[i] == '1') {
left[i] = if (i == 0) 1 else min(left[i - 1] + 2, i + 1)
} else {
left[i] = if (i == 0) 0 else left[i - 1]
}
}
return left
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,839 | kotlab | Apache License 2.0 |
src/main/kotlin/graph/variation/RemoveAddOneVertex.kt | yx-z | 106,589,674 | false | null | package graph.variation
import graph.core.Vertex
import graph.core.WeightedEdge
import graph.core.WeightedGraph
import graph.core.warshall
import util.*
// given a directed and weighted graph G = (V, E), with weights being either
// > 0, 0, or < 0
// 1. now given a specific vertex v in V, construct another directed and weighted
// graph G' = (V', E') from G : V' = V \ { v }, that is removing v in V
// and you have to make sure all other pairs of shortest path distance u -> w in
// G' is the same of that in G
// do this in O(V^2) time
fun <V> WeightedGraph<V, Int>.removeVertex(v: Vertex<V>,
checkIdentity: Boolean = true)
: Tuple2<WeightedGraph<V, Int>, List<WeightedEdge<V, Int>>> {
val newVertices = vertices.filterNot { if (checkIdentity) v === it else v == it }
val newEdges = weightedEdges.toMutableList()
getEdgesTo(v, checkIdentity).forEach { (u, _, _, w1) ->
getEdgesFrom(v, checkIdentity).forEach { (_, w, _, w2) ->
// for each u -> v -> w
// perform an add or replace
val ori = newEdges.firstOrNull { (s, e, _, _) -> s === u && e === w }
if (ori == null) {
newEdges.add(WeightedEdge(u, w, true, weight = w1!! + w2!!))
} else {
ori.weight = min(w1!! + w2!!, ori.weight!!)
}
}
}
val removedEdges = getEdgesOf(v, checkIdentity)
newEdges.removeAll(removedEdges)
return WeightedGraph(newVertices, newEdges) tu removedEdges
}
// 2. now suppose you have computed all pairs shortest paths for G' (in which
// we have removed v from V), and are given such table dist[u, w]: u, w in V'
// report two tables toV[1..V] and fromV[1..V} : toV[u] is the shortest distance
// from u to v in G and fromV[1..V] is the shortest distance from v to w in G
// also do this in O(V^2) time
fun <V> WeightedGraph<V, Int>.addVertex(v: Vertex<V>,
dist: Map<Vertex<V>, Map<Vertex<V>, Int>>,
checkIdentity: Boolean = true)
: Tuple2<Map<Vertex<V>, Int>, Map<Vertex<V>, Int>> {
val toV = HashMap<Vertex<V>, Int>()
val fromV = HashMap<Vertex<V>, Int>()
vertices.forEach {
toV[it] = INF
fromV[it] = INF
}
toV[v] = 0
fromV[v] = 0
vertices
.filterNot { if (checkIdentity) it === v else it == v }
.forEach { u ->
getEdgesTo(v, checkIdentity).forEach { (r, _, _, w) ->
// u -> r -> v
toV[u] = min(toV[u]!!, dist[u, r]!! + w!!)
}
getEdgesFrom(v, checkIdentity).forEach { (_, r, _, w) ->
// v -> r -> u
fromV[u] = min(fromV[u]!!, dist[r, u]!! + w!!)
}
}
return toV tu fromV
}
// 3. now combining ideas from 1 and 2, find a O(V^3) algorithm that computes
// all pairs shortest paths in a given directed, weighted graph G
// it should look similar to warshall's algorithm
fun <V> WeightedGraph<V, Int>.apsp(checkIdentity: Boolean = true)
: Map<Vertex<V>, Map<Vertex<V>, Int>> {
val v = vertices.toList()
val removedEdges = Array<ArrayList<WeightedEdge<V, Int>>>(v.size) { ArrayList() }
var g = this
// removing vertices as part 1
for (i in v.size - 1 downTo 0) {
val (tmpG, tmpE) = g.removeVertex(v[i])
g = tmpG
removedEdges[i].addAll(tmpE)
}
val dist = HashMap<Vertex<V>, HashMap<Vertex<V>, Int>>()
vertices.forEach { u ->
dist[u] = HashMap()
vertices.forEach { v -> dist[u, v] = INF }
dist[u, u] = 0
}
// adding vertices as part 2
for (i in 0 until v.size) {
val newVertices = g.vertices.toMutableList()
newVertices.add(v[i])
val newEdges = g.weightedEdges.toMutableList()
newEdges.addAll(removedEdges[i])
g = WeightedGraph(newVertices, newEdges)
val (toI, fromI) = g.addVertex(v[i], dist, checkIdentity)
g.vertices.forEach { u ->
dist[u, v[i]] = toI[u]!!
dist[v[i], u] = fromI[u]!!
}
}
return dist
}
fun main(args: Array<String>) {
val vertices = (0..4).map { Vertex(it) }
val edges = setOf(
WeightedEdge(vertices[0], vertices[1], true, 10),
WeightedEdge(vertices[0], vertices[2], true, 3),
WeightedEdge(vertices[1], vertices[4], true, 12),
WeightedEdge(vertices[2], vertices[3], true, 12),
WeightedEdge(vertices[2], vertices[4], true, 4),
WeightedEdge(vertices[3], vertices[4], true, 2),
WeightedEdge(vertices[4], vertices[2], true, 3))
val graph = WeightedGraph(vertices, edges)
val (newGraph, _) = graph.removeVertex(vertices[3])
val gDist = graph.warshall()
val nDist = newGraph.warshall()
println(gDist)
// 1.
// println(nDist)
// 2.
// println(graph.addVertex(vertices[3], nDist))
// 3.
println(graph.apsp())
} | 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 4,517 | AlgoKt | MIT License |
src/Day05.kt | jgodort | 573,181,128 | false | null | fun main() {
val inputData = readInput("Day5_input")
val (crates, moves) = inputData.split("\n\n")
val cratesStacks = crates.lines().dropLast(1).reversed().map { it.convertToCrate() }
val workingCrates = List(9) { ArrayDeque<Char>() }
cratesStacks.forEach { row ->
for ((index, letter) in row.withIndex()) {
if (letter == null) continue
workingCrates[index].addLast(letter)
}
}
val workingCratesStep1 = workingCrates.map { ArrayDeque(it) }
val workingCratesStep2 = workingCrates.map { ArrayDeque(it) }
val movements = processInputMovements(moves)
movements.forEach { movement -> movement.perform1(workingCratesStep1) }
movements.forEach { movement -> movement.perform2(workingCratesStep2) }
val result1 = workingCratesStep1.joinToString("") { "${it.last()}" }
val result2 = workingCratesStep2.joinToString("") { "${it.last()}" }
println(result1)
println(result2)
}
private fun processInputMovements(movements: String): List<Movement> = movements
.lines()
.map { instructions ->
val actions = instructions.split(" ")
Movement(
quantity = actions[1].toInt(),
from = actions[3].toInt(),
to = actions[5].toInt()
)
}
fun String.convertToCrate(): List<Char?> =
this.chunked(4) {
if (it[1].isLetter()) it[1] else null
}
data class Movement(
val quantity: Int,
val from: Int,
val to: Int
) {
fun perform1(stack: List<ArrayDeque<Char>>) {
val fromStack = stack[from - 1]
val toStack = stack[to - 1]
repeat(quantity) {
val inCraneClaw = fromStack.removeLast()
toStack.addLast(inCraneClaw)
}
}
fun perform2(stack: List<ArrayDeque<Char>>) {
val fromStack = stack[from - 1]
val toStack = stack[to - 1]
val inCraneClaw = fromStack.takeLast(quantity)
repeat(quantity) { fromStack.removeLast() }
for (crate in inCraneClaw) {
toStack.addLast(crate)
}
}
}
| 0 | Kotlin | 0 | 0 | 355f476765948c79bfc61367c1afe446fe9f6083 | 2,081 | aoc2022Kotlin | Apache License 2.0 |
Advent-of-Code-2023/src/Day08.kt | Radnar9 | 726,180,837 | false | {"Kotlin": 93593} | private const val AOC_DAY = "Day08"
private const val PART1_TEST_FILE = "${AOC_DAY}_test_part1"
private const val PART2_TEST_FILE = "${AOC_DAY}_test_part2"
private const val INPUT_FILE = AOC_DAY
private data class Direction(val left: String, val right: String)
/**
* Counts the number of steps until finding a position ending with "ZZZ".
*/
private fun part1(input: List<String>): Int {
var instructions = input.first()
val map = input.drop(2).associate {
val line = it.split(" = ")
val dir = line[1].removePrefix("(").removeSuffix(")").split(", ")
line[0] to Direction(dir[0], dir[1])
}
var currentDir = "AAA"
var steps = 0
while (currentDir != "ZZZ") {
currentDir = if (instructions[0] == 'R') map[currentDir]!!.right else map[currentDir]!!.left
instructions = instructions.substring(1) + instructions[0]
steps++
}
return steps
}
private const val STARTING_CHAR = 'A'
private const val ENDING_CHAR = 'Z'
/**
* After finding that the numbers of steps until finding a position ending with 'Z' are always the same for each initial
* position, I just need to find each cycle length and calculate the Least Common Multiple of all of them.
*/
private fun part2(input: List<String>): Long {
var instructions = input.first()
val startingNodes = mutableListOf<String>()
val map = input.drop(2).associate {
val line = it.split(" = ")
if (line[0].last() == STARTING_CHAR) startingNodes.add(line[0])
val dir = line[1].removePrefix("(").removeSuffix(")").split(", ")
line[0] to Direction(dir[0], dir[1])
}
val cycles = mutableListOf<Long>()
for (i in startingNodes.indices) {
var steps = 0L
while (startingNodes[i].last() != ENDING_CHAR) {
val node = startingNodes[i]
startingNodes[i] = if (instructions[0] == 'R') map[node]!!.right else map[node]!!.left
instructions = instructions.substring(1) + instructions[0]
steps++
}
cycles.add(steps)
}
return lcm(cycles)
}
fun main() {
val part1TestInput = readInputToList(PART1_TEST_FILE)
val part1ExpectedRes = 6
println("---| TEST INPUT |---")
println("* PART 1: ${part1(part1TestInput)}\t== $part1ExpectedRes")
val part2TestInput = readInputToList(PART2_TEST_FILE)
val part2ExpectedRes = 6
println("* PART 2: ${part2(part2TestInput)}\t== $part2ExpectedRes\n")
val input = readInputToList(INPUT_FILE)
val improving = true
println("---| FINAL INPUT |---")
println("* PART 1: ${part1(input)}${if (improving) "\t== 11567" else ""}")
println("* PART 2: ${part2(input)}${if (improving) "\t== 9858474970153" else ""}")
}
| 0 | Kotlin | 0 | 0 | e6b1caa25bcab4cb5eded12c35231c7c795c5506 | 2,743 | Advent-of-Code-2023 | Apache License 2.0 |
src/Day04.kt | timmiller17 | 577,546,596 | false | {"Kotlin": 44667} | fun main() {
fun part1(input: List<String>): Int {
val pairs = input.map { it.split(',') }
var count = 0
for (pair in pairs) {
val low1 = pair[0].substring(0, pair[0].indexOf('-')).toInt()
val high1 = pair[0].substring(pair[0].indexOf('-') + 1).toInt()
val low2 = pair[1].substring(0, pair[1].indexOf('-')).toInt()
val high2 = pair[1].substring(pair[1].indexOf('-') + 1).toInt()
val range1 = low1..high1
val range2 = low2..high2
if ((range1.contains(low2) && range1.contains(high2)) ||
(range2.contains(low1) && range2.contains(high1))) {
count++
}
}
return count
}
fun part2(input: List<String>): Int {
val pairs = input.map { it.split(',') }
var count = 0
for (pair in pairs) {
val low1 = pair[0].substring(0, pair[0].indexOf('-')).toInt()
val high1 = pair[0].substring(pair[0].indexOf('-') + 1).toInt()
val low2 = pair[1].substring(0, pair[1].indexOf('-')).toInt()
val high2 = pair[1].substring(pair[1].indexOf('-') + 1).toInt()
val range1 = low1..high1
val range2 = low2..high2
if ((range1.contains(low2) || range1.contains(high2)) ||
(range2.contains(low1) || range2.contains(high1))) {
count++
}
}
return count
}
// 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")
part1(input).println()
part2(input).println()
} | 0 | Kotlin | 0 | 0 | b6d6b647c7bb0e6d9e5697c28d20e15bfa14406c | 1,753 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day11/Solution.kt | TestaDiRapa | 573,066,811 | false | {"Kotlin": 50405} | package day11
import java.io.File
import java.lang.Exception
data class Monkey(
val id: Int,
val items: List<Long>,
val operation: (Long) -> Long,
val nextMonkey: (Long) -> Int,
val monkeyActivity: Int = 0
) {
fun doATurn(monkeys: List<Monkey>, reduceLevel: Int = 1, verbose: Boolean = false): List<Monkey> {
if (items.isEmpty()) return monkeys
val updatedMonkeys = items.fold(monkeys) { acc, item ->
if (verbose) println("Monkey $id inspects an item with a worry level of $item.")
val newLevel = operation(item)
if (verbose) println("\tWorry level is now $newLevel.")
val dividedLevel = newLevel/reduceLevel.toLong()
if (verbose) println("\tMonkey gets bored with item. Worry level is divided by 3 to $dividedLevel.")
val receiverMonkeyId = nextMonkey(dividedLevel)
if (verbose) println("\tItem with worry level $dividedLevel is thrown to monkey $receiverMonkeyId.")
val receiverMonkey = acc.first { it.id == receiverMonkeyId }
acc.filter { it.id != receiverMonkeyId } + receiverMonkey.copy(
items = receiverMonkey.items + dividedLevel
)
}
return updatedMonkeys.filter { it.id != id } +
this.copy(items = emptyList(), monkeyActivity = monkeyActivity + items.size)
}
}
fun parseNextMonkey(input: String): (Long) -> Int {
val divisor = Regex("Test: divisible by ([0-9]+)").find(input)!!.groupValues[1].toInt()
val ifTrue = Regex("If true: throw to monkey ([0-9]+)").find(input)!!.groupValues[1].toInt()
val ifFalse = Regex("If false: throw to monkey ([0-9]+)").find(input)!!.groupValues[1].toInt()
return { it -> if (it%divisor.toLong() == 0.toLong()) ifTrue else ifFalse}
}
fun parseOperation(rawOperation: String): (Long) -> Long {
Regex("new = ([0-9a-z]+) ([*+-]) ([0-9a-z]+)")
.find(rawOperation)!!
.groupValues
.let { groups ->
val first = groups[1]
val op = groups[2]
val second = groups[3]
return if(first == "old" && second == "old") {
when(op) {
"+" -> { it -> it + it }
"*" -> { it -> it * it }
else -> throw Exception("Operation not supported")
}
} else {
when(op) {
"+" -> { it -> it + second.toLong() }
"*" -> { it -> it * second.toLong() }
else -> throw Exception("Operation not supported")
}
}
}
}
fun parseInputFile() =
File("src/main/kotlin/day11/input.txt")
.readText()
.split(Regex("\r\n\r\n"))
.fold(emptyList<Monkey>()) { acc, rawMonkey ->
val monkeyId = Regex("Monkey ([0-9]+)").find(rawMonkey)!!.groupValues[1].toInt()
val items = Regex("[0-9]+").findAll(
Regex("Starting items: ([0-9]+,? ?)+").find(rawMonkey)!!.value
).toList().map { it.value.toLong() }
val operation = parseOperation(
Regex("Operation: new = [a-z0-9]+ [*+-] [a-z0-9]+").find(rawMonkey)!!.value
)
val nextMonkey = parseNextMonkey(rawMonkey)
acc + Monkey(
monkeyId,
items,
operation,
nextMonkey
)
}
fun findMonkeyBusinessAfterNthRound(round: Int, worryLevel: Int): Int {
val monkeys = parseInputFile()
val ids = (monkeys.indices)
val finalMonkeys = (0 until round).fold(monkeys) { m, _ ->
ids.fold(m) { acc, id ->
val monkey = acc.first { it.id == id }
monkey.doATurn(acc, worryLevel)
}
}
val monkeyActivity = finalMonkeys.map { it.monkeyActivity }.sortedDescending()
return monkeyActivity[0] * monkeyActivity[1]
}
fun main() {
println("The level of monkey business after 20 rounds is ${findMonkeyBusinessAfterNthRound(20, 3)}")
} | 0 | Kotlin | 0 | 0 | b5b7ebff71cf55fcc26192628738862b6918c879 | 4,045 | advent-of-code-2022 | MIT License |
src/com/kingsleyadio/adventofcode/y2022/day09/Solution.kt | kingsleyadio | 435,430,807 | false | {"Kotlin": 134666, "JavaScript": 5423} | package com.kingsleyadio.adventofcode.y2022.day09
import com.kingsleyadio.adventofcode.util.readInput
import kotlin.math.abs
import kotlin.math.sign
fun main() {
solution(2)
solution(10)
}
fun solution(knotCount: Int) {
val grid = Array(1000) { BooleanArray(1000) }
val knots = List(knotCount) { intArrayOf(500, 500) }
val h = knots.first()
val t = knots.last()
grid[t[0]][t[1]] = true
readInput(2022, 9).forEachLine { line ->
val (direction, count) = line.split(" ")
repeat(count.toInt()) {
when (direction) {
"R" -> h[1]++
"U" -> h[0]--
"L" -> h[1]--
"D" -> h[0]++
}
for (knot in 0 until knots.lastIndex) {
val lead = knots[knot]
val follower = knots[knot + 1]
val dy = lead[0] - follower[0]
val dx = lead[1] - follower[1]
if (abs(dy) <= 1 && abs(dx) <= 1) continue
// Lead has drifted. Need to move follower
follower[0] += dy.sign // -ve dy => move up and +ve dy => move down
follower[1] += dx.sign // -ve dx => move left and +ve dx => move right
}
grid[t[0]][t[1]] = true
}
}
val visits = grid.sumOf { it.count { visited -> visited } }
println(visits)
}
| 0 | Kotlin | 0 | 1 | 9abda490a7b4e3d9e6113a0d99d4695fcfb36422 | 1,383 | adventofcode | Apache License 2.0 |
src/Day04.kt | akleemans | 574,937,934 | false | {"Kotlin": 5797} | fun main() {
fun part1(input: List<String>): Int {
var score = 0
for (line in input) {
val (a, b) = line.split(",")
val (a1, a2) = a.split("-").map { s -> s.toInt() }
val (b1, b2) = b.split("-").map { s -> s.toInt() }
if ((a1 >= b1 && a2 <= b2) || (a1 <= b1 && a2 >= b2)) {
score += 1
}
}
return score
}
fun part2(input: List<String>): Int {
var score = 0
for (line in input) {
val (a, b) = line.split(",")
val (a1, a2) = a.split("-").map { s -> s.toInt() }
val (b1, b2) = b.split("-").map { s -> s.toInt() }
if (b1 in a1..a2 || a1 in b1..b2) {
score += 1
}
}
return score
}
val testInput = readInput("Day04_test_input")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04_input")
println("Part 1: " + part1(input))
println("Part 2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | fa4281772d89a6d1cda071db4b6fb92fff5b42f5 | 1,048 | aoc-2022-kotlin | Apache License 2.0 |
src/Day03.kt | fercarcedo | 573,142,185 | false | {"Kotlin": 60181} | private const val FIRST_LOWERCASE_PRIORITY = 1
private const val FIRST_UPPERCASE_PRIORITY = 27
fun List<String>.calculateCommonItemsPriorities() = map { it.toSet() }
.intersect()
.map { it.priority }
fun <T> List<Set<T>>.intersect() = fold(this[0]) { acc, next ->
acc intersect next
}
val Char.priority: Int
get() = if (isUpperCase()) {
this - 'A' + FIRST_UPPERCASE_PRIORITY
} else {
this - 'a' + FIRST_LOWERCASE_PRIORITY
}
fun main() {
fun play(groups: List<List<String>>) = groups.map {
it.calculateCommonItemsPriorities()
}.sumOf { it.sum() }
fun part1(input: List<String>) = play(input.map { it.chunked(it.length / 2) })
fun part2(input: List<String>) = play(input.chunked(3))
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input)) // 7878
println(part2(input)) // 2760
}
| 0 | Kotlin | 0 | 0 | e34bc66389cd8f261ef4f1e2b7f7b664fa13f778 | 972 | Advent-of-Code-2022-Kotlin | Apache License 2.0 |
src/day24/solution.kt | bohdandan | 729,357,703 | false | {"Kotlin": 80367} | package day24
import assert
import println
import readInput
import kotlin.math.*
data class Velocity(val x: Long, val y: Long, val z: Long)
data class Hailstone(val x: Long, val y: Long, val z: Long, val velocity: Velocity) {
}
class NeverTellMeTheOdds(input: List<String>) {
private val hailstones = input.map { row ->
val (point1, point2) = row.split("@")
val (x1, y1, z1) = point1.split(",").map{it.trim().toLong()}
val (x2, y2, z2) = point2.split(",").map{it.trim().toLong()}
Hailstone(x1,y1,z1, Velocity(x2, y2, z2))
}
private fun toABC(hailstone: Hailstone): Triple<Double, Double, Double> {
val a = ((hailstone.y + hailstone.velocity.y) - hailstone.y).toDouble() / ((hailstone.x + hailstone.velocity.x) - hailstone.x)
val c = hailstone.y - hailstone.x.toDouble() * ((hailstone.y + hailstone.velocity.y) - hailstone.y) / ((hailstone.x + hailstone.velocity.x) - hailstone.x)
return Triple(a, -1.0, c)
}
private fun collisionPoint(hailstone1: Hailstone, hailstone2: Hailstone): Pair<Double, Double> {
val (a1, b1, c1) = toABC(hailstone1)
val (a2, b2, c2) = toABC(hailstone2)
val x = (b1 * c2 - b2 * c1) / (a1 * b2 - a2 * b1)
val y = (a2 * c1 - a1 * c2) / (a1 * b2 - a2 * b1)
val t = min((x - hailstone1.x) / hailstone1.velocity.x, (x - hailstone2.x) / hailstone2.velocity.x)
if (t < 0) return Pair(0.0, 0.0)
return Pair(x, y)
}
fun countIntersections(area: LongRange = 7L..27L): Int {
val collisions = hailstones.mapIndexed { index, h1 ->
val collisions = mutableListOf<Pair<Double, Double>>()
for (h2 in hailstones.listIterator(index + 1)) {
collisions += collisionPoint(h1, h2)
}
collisions
}.flatten()
return collisions.count {
it.first > area.first && it.first < area.last &&
it.second > area.first && it.second < area.last
}
}
// Paste results in SageMath 😝
// https://sagecell.sagemath.org/
fun getEquation(): String {
var equationCounter = 1
return buildString {
appendLine("var('x y z vx vy vz t1 t2 t3 ans')")
hailstones.take(3).forEachIndexed { index, h ->
appendLine("eq${equationCounter++} = x + (vx * t${index + 1}) == ${h.x} + (${h.velocity.x} * t${index + 1})")
appendLine("eq${equationCounter++} = y + (vy * t${index + 1}) == ${h.y} + (${h.velocity.y} * t${index + 1})")
appendLine("eq${equationCounter++} = z + (vz * t${index + 1}) == ${h.z} + (${h.velocity.z} * t${index + 1})")
}
appendLine("eq10 = ans == x + y + z")
appendLine("print(solve([eq1,eq2,eq3,eq4,eq5,eq6,eq7,eq8,eq9,eq10],x,y,z,vx,vy,vz,t1,t2,t3,ans))")
}
}
}
fun main() {
NeverTellMeTheOdds(readInput("day24/test1"))
.countIntersections()
.assert(2)
"Part 1:".println()
NeverTellMeTheOdds(readInput("day24/input"))
.countIntersections(200000000000000..400000000000000)
.assert(27732)
.println()
"Part 2:".println()
"-".repeat(100).println()
NeverTellMeTheOdds(readInput("day24/input"))
.getEquation()
.println()
"-".repeat(100).println()
// 641619849766168
} | 0 | Kotlin | 0 | 0 | 92735c19035b87af79aba57ce5fae5d96dde3788 | 3,363 | advent-of-code-2023 | Apache License 2.0 |
kotlin/src/2022/Day13_2022.kt | regob | 575,917,627 | false | {"Kotlin": 50757, "Python": 46520, "Shell": 430} | private typealias Item = Any
private fun parse(s: String): Item {
val path = mutableListOf<MutableList<Item>>()
var acc = mutableListOf<Char>()
fun closeAcc() {
if (acc.isNotEmpty())
path.last().add(acc.joinToString("").toInt())
acc = mutableListOf()
}
for (c in s) {
when (c) {
in '0'..'9' -> {
acc.add(c)
}
'[' -> {
path.add(mutableListOf())
}
']' -> {
closeAcc()
if (path.size == 1) return path.last()
val l = path.removeLast()
path.last().add(l)
}
',' -> closeAcc()
' ' -> closeAcc()
else -> throw IllegalStateException("Got char: $c")
}
}
throw IllegalStateException("List not closed.")
}
private fun Item.compare(y: Item): Int {
if (this is Int && y is Int) return this.compareTo(y)
if (this is Int) return listOf(this).compare(y)
if (y is Int) return this.compare(listOf(y))
val (l1, l2) = this as List<Item> to y as List<Item>
for ((a, b) in l1.zip(l2)) {
val comp = a.compare(b)
if (comp != 0) return comp
}
return l1.size.compareTo(l2.size)
}
fun main() {
val input = readInput(13).trim().split("\n\n")
.map {it.trim().split("\n")}
// part1
val total = input
.map {
parse(it[0]) to parse(it[1])
}
.withIndex()
.map {e ->
if (e.value.first.compare(e.value.second) < 0) e.index + 1 else 0
}.sum()
println(total)
// part2
val barriers = listOf(parse("[[2]]"), parse("[[6]]"))
val sorted = (input.flatten().map(::parse) + barriers)
.sortedWith { p0, p1 -> p0.compare(p1)}
val (i1, i2) = barriers.map {sorted.indexOf(it)}
println((i1 + 1) * (i2 + 1))
} | 0 | Kotlin | 0 | 0 | cf49abe24c1242e23e96719cc71ed471e77b3154 | 1,911 | adventofcode | Apache License 2.0 |
src/year2023/23/Day23.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2023.`23`
import readInput
private const val CURRENT_DAY = "23"
private data class Point(
val x: Int,
val y: Int,
) {
override fun toString(): String {
return "[$x,$y]"
}
}
private fun Point.neighbours(
currentValue: String,
): Set<Point> {
return when (currentValue) {
">" -> setOf(
Point(x = x + 1, y = y),
)
"v" -> setOf(
Point(x = x, y = y + 1),
)
"." -> setOf(
Point(x = x, y = y + 1),
Point(x = x, y = y - 1),
Point(x = x + 1, y = y),
Point(x = x - 1, y = y),
)
else -> error("Illegal neighbours value: $currentValue")
}
}
private fun solve(input: List<String>, isPart1: Boolean): Int {
val start = Point(1, 0)
val end = Point(input.first().lastIndex - 1, input.lastIndex)
val visited = Array(input.size) { BooleanArray(input.first().length) }
return findMax(
isPart1 = isPart1,
input = input,
end = end,
point = start,
visited = visited,
current = 0,
)
}
private fun findMax(
isPart1: Boolean,
input: List<String>,
end: Point,
point: Point,
visited: Array<BooleanArray>,
current: Int,
): Int {
// Skip if outside of the box
if (point.y !in input.indices || point.x !in input.first().indices) {
return -1
}
// Skip if Visited
if (visited[point.y][point.x]) {
return -1
}
// Skip If Wall
if (input[point.y][point.x] == '#') {
return -1
}
// Return answer
if (point == end) {
return current
}
// Set this point to visited to avoid going back
visited[point.y][point.x] = true
val currentSymbol = input[point.y][point.x].toString().takeIf { isPart1 } ?: "."
val max = point.neighbours(
currentValue = currentSymbol,
).maxOf { neighbour ->
findMax(
isPart1 = isPart1,
input = input,
end = end,
point = neighbour,
visited = visited,
current = current + 1,
)
}
// Clear this point, to give ability to other recurstions to visit it.
visited[point.y][point.x] = false
return max
}
fun main() {
fun part1(input: List<String>): Int {
return solve(input, true)
}
fun part2(input: List<String>): Int {
return solve(input, false)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day${CURRENT_DAY}_test")
val part1Test = part1(testInput)
println(part1Test)
check(part1Test == 94)
val part2Test = part2(testInput)
println(part2Test)
check(part2Test == 154)
val input = readInput("Day$CURRENT_DAY")
// Part 1
val part1 = part1(input)
println(part1)
check(part1 == 2170)
// Part 2
val part2 = part2(input)
println(part2)
check(part2 == 6502)
} | 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 2,983 | KotlinAdventOfCode | Apache License 2.0 |
src/Day07.kt | LauwiMeara | 572,498,129 | false | {"Kotlin": 109923} | const val MAX_SIZE_PART_1 = 100000
const val MAX_USED_SPACE = 70000000 - 30000000
fun main() {
fun getListPerDirectory(input: List<String>): Map<String, List<String>> {
val listPerDirectory = mutableMapOf<String, MutableList<String>>()
var currentDirectory = ""
for (line in input) {
val command = line.split(" ")
when (command[0]) {
"$" -> {
if (command[1] == "cd") {
// Change currentDirectory
if (command[2] == "..") {
currentDirectory = currentDirectory.substringBeforeLast("/")
} else {
currentDirectory += "/" + command[2]
}
// Check if listPerDirectory already contains the new currentDirectory.
// If not, add it and create an empty list to avoid null exceptions later on.
if (!listPerDirectory.containsKey(currentDirectory)) {
listPerDirectory[currentDirectory] = mutableListOf()
}
}
}
"dir" -> {
// Add child directory to the list of the files within the currentDirectory.
listPerDirectory[currentDirectory]!!.add(currentDirectory + "/" + command[1])
}
else -> {
// Add file size to the list of the files within the currentDirectory.
listPerDirectory[currentDirectory]!!.add(command[0])
}
}
}
return listPerDirectory
}
fun calculateDirectorySize(listPerDirectory: Map<String, List<String>>, directory: String): Long {
return listPerDirectory[directory]!!.sumOf { it.toLongOrNull() ?: calculateDirectorySize(listPerDirectory, it) }
}
fun getSizePerDirectory(listPerDirectory: Map<String, List<String>>): Map<String, Long> {
val sizePerDirectory = mutableMapOf<String, Long>()
for (directory in listPerDirectory.keys) {
sizePerDirectory[directory] = calculateDirectorySize(listPerDirectory, directory)
}
return sizePerDirectory
}
fun part1(input: List<String>): Long {
val listPerDirectory = getListPerDirectory(input)
val sizePerDirectory = getSizePerDirectory(listPerDirectory)
return sizePerDirectory.values.filter{it <= MAX_SIZE_PART_1}.sum()
}
fun part2(input: List<String>): Long {
val listPerDirectory = getListPerDirectory(input)
val sizePerDirectory = getSizePerDirectory(listPerDirectory)
val sizeToDelete = sizePerDirectory.values.first() - MAX_USED_SPACE
return sizePerDirectory.values.sorted().first { it >= sizeToDelete }
}
val input = readInputAsStrings("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 34b4d4fa7e562551cb892c272fe7ad406a28fb69 | 2,968 | AoC2022 | Apache License 2.0 |
src/day12/b/day12b.kt | pghj | 577,868,985 | false | {"Kotlin": 94937} | package day12.b
import readInputLines
import shouldBe
import util.IntGrid
import util.IntVector
import vec2
import java.lang.Integer.min
fun main() {
val map = day12.a.readInput()
val dist = IntGrid(map.width, map.height)
dist.compute { Integer.MAX_VALUE }
val (_, end) = findStartAndEnd(map)
val modified = HashSet<IntVector>()
// here we begin searching from the end
dist[end] = 0
modified.add(end)
var least = Integer.MAX_VALUE
while(modified.isNotEmpty()) {
val l = ArrayList(modified)
modified.clear()
for (p1 in l) {
var d = vec2(1, 0)
val d1 = dist[p1]
val h1 = map[p1]
for (i in 1..4) {
val p2 = p1 + d
if (map.contains(p2)) {
val h2 = map[p2]
val d2 = dist[p2]
if (h2 >= h1-1 && d2-1 > d1) {
dist[p2] = d1+1
if (map[p2] == 0) least = min(least, d1+1)
modified.add(p2)
}
}
d = d.rotate(0, 1)
}
}
}
shouldBe(488, least)
}
fun findStartAndEnd(map: IntGrid): Pair<IntVector, IntVector> {
var start : IntVector? = null
var end : IntVector? = null
map.forEachIndexed { p, v ->
if (v == -14) {
map[p] = 0
start = p
} else if (v == -28) {
map[p] = 25
end = p
}
}
return Pair(start!!, end!!)
}
fun readInput(): IntGrid {
val r = ArrayList<IntArray>()
val lines = readInputLines(12)
for (l in lines) {
if (l.isBlank()) continue
r.add(l.chars().map { c -> c - 'a'.code}.toArray())
}
return IntGrid(r)
}
| 0 | Kotlin | 0 | 0 | 4b6911ee7dfc7c731610a0514d664143525b0954 | 1,791 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/g2901_3000/s2973_find_number_of_coins_to_place_in_tree_nodes/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2901_3000.s2973_find_number_of_coins_to_place_in_tree_nodes
// #Hard #Dynamic_Programming #Sorting #Depth_First_Search #Tree #Heap_Priority_Queue
// #2024_01_19_Time_1134_ms_(90.91%)_Space_73.7_MB_(90.91%)
import java.util.PriorityQueue
import kotlin.math.max
class Solution {
private lateinit var result: LongArray
fun placedCoins(edges: Array<IntArray>, cost: IntArray): LongArray {
val n = cost.size
val g: MutableList<MutableList<Int>> = ArrayList()
for (i in 0 until n) {
g.add(ArrayList())
}
for (e in edges) {
g[e[0]].add(e[1])
g[e[1]].add(e[0])
}
result = LongArray(n)
dp(g, cost, 0, -1)
return result
}
private class PQX {
var min: PriorityQueue<Int>? = null
var max: PriorityQueue<Int>? = null
}
private fun dp(g: List<MutableList<Int>>, cost: IntArray, i: Int, p: Int): PQX {
if (i >= g.size) {
val pqx = PQX()
pqx.max = PriorityQueue { a: Int, b: Int -> b - a }
pqx.min = PriorityQueue(Comparator.comparingInt { a: Int? -> a!! })
return pqx
}
val next: List<Int> = g[i]
var pq = PriorityQueue { a: Int, b: Int -> b - a }
var pq2 = PriorityQueue(Comparator.comparingInt { a: Int? -> a!! })
if (cost[i] > 0) {
pq.add(cost[i])
} else {
pq2.add(cost[i])
}
for (ne in next) {
if (ne != p) {
val r = dp(g, cost, ne, i)
while (r.min!!.isNotEmpty()) {
val a = r.min!!.poll()
pq2.add(a)
}
while (r.max!!.isNotEmpty()) {
val a = r.max!!.poll()
pq.add(a)
}
}
}
if (pq.size + pq2.size < 3) {
result[i] = 1
} else {
val a = if (pq.isNotEmpty()) pq.poll() else 0
val b = if (pq.isNotEmpty()) pq.poll() else 0
val c = if (pq.isNotEmpty()) pq.poll() else 0
val aa = if (pq2.isNotEmpty()) pq2.poll() else 0
val bb = if (pq2.isNotEmpty()) pq2.poll() else 0
result[i] = max(0, (a.toLong() * b * c))
result[i] = max(result[i], max(0, (a.toLong() * aa * bb)))
.toLong()
pq = PriorityQueue { x: Int, y: Int -> y - x }
pq.add(a)
pq.add(b)
pq.add(c)
pq2 = PriorityQueue(Comparator.comparingInt { x: Int? -> x!! })
pq2.add(aa)
pq2.add(bb)
}
val pqx = PQX()
pqx.min = pq2
pqx.max = pq
return pqx
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,741 | LeetCode-in-Kotlin | MIT License |
2023/src/main/kotlin/Day05.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | object Day05 {
data class Almanac(val seeds: List<Long>, val steps: List<List<Transformer>>)
data class Transformer(val range: LongRange, val transform: Long)
fun part1(input: String): Long {
val almanac = parseAlmanac(input)
return almanac.seeds.minOf { seed ->
almanac.steps.fold(seed) { value, transfomers ->
val transformer = transfomers.find { value in it.range }
return@fold if (transformer != null) value + transformer.transform else value
}
}
}
fun part2(input: String): Long {
val almanac = parseAlmanac(input)
val initialRanges = almanac.seeds.chunked(2).map { (start, len) -> start..<start + len }
// For each step, convert all set of ranges into new set of ranges
return almanac.steps
.map { transformers -> transformers.sortedBy { it.range.first } }
.fold(initialRanges) { ranges, transformers ->
ranges.flatMap { range ->
val newRanges = mutableListOf<LongRange>()
var curr = range.first
var stepIndex = 0
// Step through all transformers, creating new ranges when matching
while (curr <= range.last && stepIndex < transformers.size) {
val transformer = transformers[stepIndex]
if (curr in transformer.range) {
// Map this range onto a new range
val end = minOf(range.last, transformer.range.last)
val length = end - curr
val newStart = curr + transformer.transform
newRanges.add(newStart..newStart + length)
curr = end + 1
stepIndex++
} else if (range.last < transformer.range.first) {
// We end before the next possible transformer range
break
} else if (curr < transformer.range.first) {
// We're not in transformer range, but could step up to be within it
newRanges.add(curr..<transformer.range.first)
curr = transformer.range.first
} else {
// We can't match with this transformer, but might with the next
stepIndex++
}
}
// Leftover range converted 1:1 with no transform
if (curr <= range.last) {
newRanges.add(curr..range.last)
}
return@flatMap newRanges
}
}
.minOf { it.first }
}
private fun parseAlmanac(input: String): Almanac {
val lines = input.splitNewlines()
val seeds = lines[0].drop(7).splitWhitespace().toLongList()
val steps = mutableListOf<List<Transformer>>()
var transformers = mutableListOf<Transformer>()
lines.drop(2).forEach { line ->
if (line.isEmpty()) {
steps.add(transformers)
transformers = mutableListOf()
} else if (line[0].isDigit()) {
val (destinationRangeStart, sourceRangeStart, rangeLength) = line.splitWhitespace().toLongList()
transformers.add(
Transformer(
range = sourceRangeStart..<sourceRangeStart + rangeLength,
transform = destinationRangeStart - sourceRangeStart
)
)
}
}
steps.add(transformers)
return Almanac(seeds, steps)
}
} | 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 3,226 | advent-of-code | MIT License |
day10/src/main/kotlin/Main.kt | rstockbridge | 159,586,951 | false | null | import java.io.File
fun main() {
val points = parseInput(readInputFile())
val board = Board(points)
println("Part I: the solution is\n")
val numberOfSeconds = solveProblem(board)
println("Part II: the solution is $numberOfSeconds.")
}
fun readInputFile(): List<String> {
return File(ClassLoader.getSystemResource("input.txt").file).readLines()
}
fun parseInput(input: List<String>): List<Point> {
return input.map { line ->
val inputRegex = "position=<\\s*+(-?\\d+),\\s*+(-?\\d+)> velocity=<\\s*+(-?\\d+),\\s*+(-?\\d+)>".toRegex()
val (positionX, positionY, velocityX, velocityY) = inputRegex.matchEntire(line)!!.destructured
Point(Coordinate(positionX.toInt(), positionY.toInt()), Coordinate(velocityX.toInt(), velocityY.toInt()))
}
}
fun solveProblem(board: Board): Int {
var currentBoard = board
var nextBoard = board.next()
var i = 0
while (currentBoard.getArea() > nextBoard.getArea()) {
currentBoard = nextBoard
nextBoard = nextBoard.next()
i++
}
currentBoard.print()
return i
}
class Board(private val points: List<Point>) {
fun next(): Board {
return Board(points.map { it.next() })
}
fun print() {
for (y in getMinY()..getMaxY()) {
for (x in getMinX()..getMaxX()) {
if (hasPoint(x, y)) {
print("#")
} else {
print(".")
}
}
println()
}
println()
}
private fun hasPoint(x: Int, y: Int): Boolean {
for (point in points) {
if (point.position == Coordinate(x, y)) {
return true
}
}
return false
}
private fun getMinX(): Int {
return points
.map { it -> it.position.x }
.min()!!
}
private fun getMaxX(): Int {
return points
.map { it -> it.position.x }
.max()!!
}
private fun getMinY(): Int {
return points
.map { it -> it.position.y }
.min()!!
}
private fun getMaxY(): Int {
return points
.map { it -> it.position.y }
.max()!!
}
fun getArea(): Long {
return (getMaxX().toLong() - getMinX().toLong()) * (getMaxY().toLong() - getMinY().toLong())
}
}
data class Point(val position: Coordinate, val velocity: Coordinate) {
fun next(): Point {
val newPosition = Coordinate(position.x + velocity.x, position.y + velocity.y)
return Point(newPosition, velocity)
}
}
data class Coordinate(val x: Int, val y: Int)
| 0 | Kotlin | 0 | 0 | c404f1c47c9dee266b2330ecae98471e19056549 | 2,713 | AdventOfCode2018 | MIT License |
src/main/kotlin/day3/main.kt | janneri | 572,969,955 | false | {"Kotlin": 99028} | package day3
import util.readTestInput
data class Rucksack(val part1Chars: CharArray, val part2Chars: CharArray) {
fun getDuplicateChar(): Char {
return part1Chars.find { part2Chars.contains(it) }!!
}
companion object {
fun parse(str: String): Rucksack {
val partLength = str.length / 2
return Rucksack(str.take(partLength).toCharArray(), str.substring(partLength).toCharArray())
}
}
}
fun getPrioOfChar(char: Char): Int {
return if (char.isUpperCase()) char.code - 38 else char.code - 96
}
fun part1(inputLines: List<String>): Int {
return inputLines
.map { Rucksack.parse(it) }
.map { getPrioOfChar(it.getDuplicateChar()) }
.sum()
}
/** The group has always 3 items. Returns a char found in all three groups. */
fun findCommonChar(group: List<String>): Char {
val charArrays = group.map { it.toCharArray() }
return charArrays[0].find { group[1].contains(it) && group[2].contains(it) }!!
// charArrays[0].find { char -> group.drop(1).all { it.contains(char) } }!!
// The commented versio would be more generic, but I think the not generic version is more readable
}
fun part2(inputLines: List<String>): Int {
return inputLines.chunked(3)
.map { findCommonChar(it) }
.map { getPrioOfChar(it) }
.sum()
}
fun main() {
val inputLines = readTestInput("day3")
println(part1(inputLines))
println(part2(inputLines))
} | 0 | Kotlin | 0 | 0 | 1de6781b4d48852f4a6c44943cc25f9c864a4906 | 1,473 | advent-of-code-2022 | MIT License |
src/year2023/day18/Day.kt | tiagoabrito | 573,609,974 | false | {"Kotlin": 73752} | package year2023.day18
import year2023.solveIt
fun main() {
val day = "18"
val expectedTest1 = 62L
val expectedTest2 = 952408144115L
data class Coordinate(val x: Long, val y: Long) {
fun add(other: Coordinate): Coordinate = Coordinate(x + other.x, y + other.y)
}
fun move(len: Long, direction: Char) = when (direction) {
'U', '3' -> Coordinate(0, len * -1)
'D', '1' -> Coordinate(0, len)
'L', '2' -> Coordinate(len * -1, 0)
'R', '0' -> Coordinate(len, 0)
else -> throw Exception()
}
fun shoeLace(v: List<Coordinate>) = v.zipWithNext { a, b -> a.x * b.y - a.y * b.x }.sum() / 2L
fun part1(input: List<String>): Long {
var perimeter = 0L
val v = input.scan(Coordinate(0, 0)) { acc, s ->
val (dir, sz) = s.split(" ")
val m = sz.toLong()
perimeter += m
val move = move(m, dir[0])
acc.add(move)
}
return shoeLace(v) + perimeter / 2 + 1
}
fun part2(input: List<String>): Long {
var perimeter = 0L
val v = input.scan(Coordinate(0, 0)) { acc, s ->
val color = s.split(" ")[2]
val m = color.substring(2, 7).toLong(radix = 16)
perimeter += m
val move = move(m, color[7])
acc.add(move)
}
return shoeLace(v) + perimeter / 2 + 1
}
solveIt(day, ::part1, expectedTest1, ::part2, expectedTest2, "test")
}
| 0 | Kotlin | 0 | 0 | 1f9becde3cbf5dcb345659a23cf9ff52718bbaf9 | 1,489 | adventOfCode | Apache License 2.0 |
src/main/kotlin/y2022/day09/Day09.kt | TimWestmark | 571,510,211 | false | {"Kotlin": 97942, "Shell": 1067} | package y2022.day09
import java.lang.IllegalStateException
import kotlin.math.abs
fun main() {
AoCGenerics.printAndMeasureResults(
part1 = { part1() },
part2 = { part2() }
)
}
enum class Direction {
LEFT,
RIGHT,
UP,
DOWN
}
data class Move(
val direction: Direction,
val steps: Int
)
fun input(): List<Move> {
return AoCGenerics.getInputLines("/y2022/day09/input.txt").map { line ->
Move(
direction = when (line.split(" ")[0]) {
"U" -> Direction.UP
"D" -> Direction.DOWN
"L" -> Direction.LEFT
"R" -> Direction.RIGHT
else -> throw IllegalStateException("Invalid Move")
},
steps = line.split(" ")[1].toInt()
)
}
}
data class Field(
var visitedByTail: Boolean = false,
val x: Int,
val y: Int
)
fun initField(size:Int): List<List<Field>> {
return IntRange(0, size).map { y ->
IntRange(0, size)
.map { x ->
Field(false, x, y)
}
}
}
fun moveHead(head: Field, direction: Direction, field: List<List<Field>>): Field {
return when (direction) {
Direction.LEFT -> field[head.y][head.x - 1]
Direction.RIGHT -> field[head.y][head.x + 1]
Direction.UP -> field[head.y - 1][head.x]
Direction.DOWN -> field[head.y + 1][head.x]
}
}
fun moveTail(head:Field, tail: Field, field:List<List<Field>>): Field {
return when {
// Move the tail horizontally
tail.y == head.y && abs(tail.x - head.x) > 1 -> field[tail.y][(tail.x + head.x) / 2]
// Move the tail vertically
tail.x == head.x && abs(tail.y - head.y) > 1 -> field[(tail.y + head.y) / 2][tail.x]
// move diagonally
abs(tail.y - head.y) > 1 && abs(tail.x - head.x) > 1 -> field[(tail.y + head.y) / 2][(tail.x + head.x) / 2]
abs(tail.y - head.y) > 1 -> field[(tail.y + head.y) / 2][head.x]
abs(tail.x - head.x) > 1 -> field[head.y][(tail.x + head.x) / 2]
// Do not move
else -> return tail
}
}
fun part1(): Int {
val commands = input()
val fieldSize = 1000
val field = initField(fieldSize)
val start = field[fieldSize/2][fieldSize/2]
start.visitedByTail = true
var head = start
var tail = start
commands.forEach { command ->
repeat(command.steps) {
// Move the Head
head = moveHead(head, command.direction, field)
// Move the Tail
tail = moveTail(head, tail, field)
tail.visitedByTail = true
}
}
return field.flatten().count { it.visitedByTail }
}
fun part2(): Int {
val commands = input()
val fieldSize = 1000
val field = initField(fieldSize)
val start = field[fieldSize/2][fieldSize/2]
start.visitedByTail = true
var head = start
val tails: MutableList<Field> = MutableList(9) { start}
commands.forEach { command ->
repeat(command.steps) {
// Move the Head
head = moveHead(head, command.direction, field)
var previousHead = head
// Move the Tails
tails.forEachIndexed { index, tail ->
tails[index] = moveTail(previousHead, tail, field)
previousHead = tails[index]
}
tails.last().visitedByTail = true
}
}
return field.flatten().count { it.visitedByTail }
}
| 0 | Kotlin | 0 | 0 | 23b3edf887e31bef5eed3f00c1826261b9a4bd30 | 3,490 | AdventOfCode | MIT License |
src/kotlin2022/Day05.kt | egnbjork | 571,981,366 | false | {"Kotlin": 18156} | package kotlin2022
import readInput
fun main() {
val gameInput = readInput("Day05_test")
val part1 = executePart1(normalizeCrates(gameInput), normalizeActions(gameInput))
val part2 = executePart2(normalizeCrates(gameInput), normalizeActions(gameInput))
printSolution(part1)
printSolution(part2)
}
fun normalizeCrates(input: List<String>): MutableList<MutableList<Char>> {
val crateStackList = mutableListOf<MutableList<Char>>()
for(line in input) {
if(line.contains("[0-9]".toRegex())) {
break
}
val normalizedLine = line.replace(" ", "[-] ")
for ((index, crate) in normalizedLine.split(" ").withIndex()) {
val normalizedCrate = crate.replace("[", "").replace("]", "")
if(normalizedCrate == "-" || normalizedCrate.isEmpty()) {
if (crateStackList.size <= index && normalizedCrate.isNotEmpty()) {
val crateStack = mutableListOf<Char>()
crateStackList.add(crateStack)
}
continue
}
if(crateStackList.size <= index || crateStackList.isEmpty()) {
val crateStack = mutableListOf<Char>()
crateStack.add(normalizedCrate.toCharArray()[0])
crateStackList.add(crateStack)
} else {
crateStackList[index].add(normalizedCrate.toCharArray()[0])
}
}
}
return crateStackList
}
fun normalizeActions(input: List<String>): List<Triple<Int, Int, Int>> {
val actions = mutableListOf<Triple<Int, Int, Int>>()
for(line in input) {
if (line.startsWith("move")) {
val action = line.split(" ")
actions.add(Triple(action[1].toInt(), action[3].toInt() - 1, action[5].toInt() - 1))
}
}
return actions
}
fun executePart1(crates: List<MutableList<Char>>, actions: List<Triple<Int, Int, Int>>): List<MutableList<Char>> {
for(action in actions) {
repeat(action.first) {
val crateToMove = crates[action.second].removeFirst()
crates[action.third].add(0, crateToMove)
}
}
return crates
}
fun executePart2(crates: MutableList<MutableList<Char>>, actions: List<Triple<Int, Int, Int>>): List<MutableList<Char>> {
for(action in actions) {
val crateToMove = crates[action.second].take(action.first)
crates[action.third].addAll(0, crateToMove)
crates[action.second] = crates[action.second].drop(action.first).toMutableList()
}
return crates
}
fun printSolution(crates: List<MutableList<Char>>) {
var solution = ""
for (crate in crates) {
solution += crate.first()
}
print("$solution \n")
} | 0 | Kotlin | 0 | 0 | 1294afde171a64b1a2dfad2d30ff495d52f227f5 | 2,745 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/Day2.kt | ueneid | 575,213,613 | false | null | class Day2(inputs: List<String>) {
private val matches = parse(inputs)
private fun parse(inputs: List<String>): List<Pair<String, String>> {
return inputs.map { it.split(" ").toPair() }
}
enum class Choice(s: String, val point: Int) {
A("Rock", 1) {
override fun judgeAgainst(c: Choice?): Result {
return when (c) {
A -> Result.DRAW
C -> Result.WIN
else -> Result.LOSE
}
}
override fun getChoiceByResult(s: Result): Choice {
return when (s) {
Result.WIN -> B
Result.DRAW -> A
Result.LOSE -> C
}
}
},
B("Paper", 2) {
override fun judgeAgainst(c: Choice?): Result {
return when (c) {
B -> Result.DRAW
A -> Result.WIN
else -> Result.LOSE
}
}
override fun getChoiceByResult(s: Result): Choice {
return when (s) {
Result.WIN -> C
Result.DRAW -> B
Result.LOSE -> A
}
}
},
C("Scissors", 3) {
override fun judgeAgainst(c: Choice?): Result {
return when (c) {
C -> Result.DRAW
B -> Result.WIN
else -> Result.LOSE
}
}
override fun getChoiceByResult(s: Result): Choice {
return when (s) {
Result.WIN -> A
Result.DRAW -> C
Result.LOSE -> B
}
}
};
abstract fun judgeAgainst(c: Choice?): Result
abstract fun getChoiceByResult(s: Result): Choice
}
enum class Result(val point: Int) {
WIN(6), LOSE(0), DRAW(3);
}
fun solve1(): Int {
val choiceMap = mapOf<String, Choice>(
"X" to Choice.A, "Y" to Choice.B, "Z" to Choice.C
)
var score = 0
for ((a, b) in matches) {
val firstChoice = Choice.valueOf(a)
val secondChoice = choiceMap[b]
val ret = firstChoice.judgeAgainst(secondChoice)
score += ret.point + (secondChoice?.point ?: 0)
}
return score
}
fun solve2(): Int {
var score = 0
val retMap = mapOf<String, Result>(
"X" to Result.LOSE, "Y" to Result.DRAW, "Z" to Result.WIN
)
for ((a, b) in matches) {
val firstChoice = Choice.valueOf(a)
val ret = retMap.getOrDefault(b, Result.LOSE)
score += ret.point + firstChoice.getChoiceByResult(ret).point
}
return score
}
}
fun main() {
val inputs = Resource.resourceAsListOfString("day2/input.txt")
val obj = Day2(inputs)
println(obj.solve1())
println(obj.solve2())
}
| 0 | Kotlin | 0 | 0 | 743c0a7adadf2d4cae13a0e873a7df16ddd1577c | 3,044 | adventcode2022 | MIT License |
src/main/kotlin/net/wrony/aoc2023/a11/11.kt | kopernic-pl | 727,133,267 | false | {"Kotlin": 52043} | package net.wrony.aoc2023.a11
import kotlin.io.path.Path
import kotlin.io.path.readLines
import kotlin.math.absoluteValue
fun discreteDistance(p: Pair<Position, Position>): Long {
return discreteDistance(p.first, p.second)
}
fun discreteDistance(first: Position, second: Position): Long {
return discreteDistance(first.first.toLong(), first.second.toLong(), second.first.toLong(), second.second.toLong())
}
fun discreteDistance(x1: Long, y1: Long, x2: Long, y2: Long): Long {
return (y2 - y1).absoluteValue + (x2 - x1).absoluteValue
}
fun calcSumOfAllDistances(stars: List<Position>): Long {
return stars.flatMapIndexed { idx, star ->
stars.drop(idx + 1).map { otherStar ->
star to otherStar
}
}
.sumOf { starsPair -> discreteDistance(starsPair) }
.also { println("sumOf distances: $it") }
}
typealias Position = Pair<Int, Int>
fun main() {
Path("src/main/resources/11.txt").readLines().let { rows ->
val emptyRows = rows.foldIndexed(mutableSetOf<Int>()) { idx, acc, row ->
if (row.all { c -> c == '.' }) {
acc.add(idx)
}
acc
}.sorted()
val emptyCols = (0..<rows[0].length - 1).fold(mutableSetOf<Int>()) { acc, col ->
if (rows.all { row -> row[col] == '.' }) {
acc.add(col)
}
acc
}.sorted()
println("emptyRows: $emptyRows, emptyCols: $emptyCols")
val originalStars = sequence {
rows.indices.forEach { r ->
(0..<rows[r].length).forEach { c ->
if (rows[r][c] == '#') yield(Position(r, c))
}
}
}
val expansionMultiplier = 1000000
val expandedStars = originalStars.map {
(row, col) ->
(emptyRows.count { it < row } * (expansionMultiplier-1) + row) to (emptyCols.count { it < col } * (expansionMultiplier-1) + col)
}
calcSumOfAllDistances(expandedStars.toList())
}
} | 0 | Kotlin | 0 | 0 | 1719de979ac3e8862264ac105eb038a51aa0ddfb | 2,186 | aoc-2023-kotlin | MIT License |
2023/src/main/kotlin/Day15.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | object Day15 {
fun part1(input: String) = input.splitCommas().sumOf(::hash)
fun part2(input: String): Int {
val operations = parse(input)
val boxes = Array(256) { mutableListOf<Lens>() }
operations.forEach { op ->
val box = boxes[hash(op.label)]
when (op) {
is Operation.Put -> {
val newLens = Lens(op.label, op.focalLength)
val existingLens = box.indexOfFirst { it.label == op.label }
if (existingLens == -1) {
box.add(newLens)
} else {
box[existingLens] = newLens
}
}
is Operation.Remove -> box.removeIf { it.label == op.label }
}
}
return boxes.withIndex().sumOf { (box, lenses) ->
lenses.withIndex().sumOf { (slot, lens) ->
(box + 1) * (slot + 1) * lens.focalLength
}
}
}
private fun hash(input: String) = input.fold(0) { acc, c -> (acc + c.code) * 17 % 256 }
private sealed class Operation {
abstract val label: String
data class Put(override val label: String, val focalLength: Int) : Operation()
data class Remove(override val label: String) : Operation()
}
private data class Lens(val label: String, val focalLength: Int)
private fun parse(input: String): List<Operation> {
val regex = Regex("(\\w+)([=-])(\\d+)?")
return input.splitCommas().map {
val match = regex.matchEntire(it)!!
when (match.groupValues[2]) {
"-" -> Operation.Remove(match.groupValues[1])
else -> Operation.Put(match.groupValues[1], match.groupValues[3].toInt())
}
}
}
} | 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 1,597 | advent-of-code | MIT License |
kotlin/2022/qualification-round/chain-reactions/src/main/kotlin/Solution.kt | ShreckYe | 345,946,821 | false | null | fun main() {
val t = readLine()!!.toInt()
repeat(t, ::testCase)
}
fun testCase(ti: Int) {
val nn = readLine()!!.toInt()
val ffs = readLine()!!.splitToSequence(' ').map { it.toInt() }.toList()
val pps = readLine()!!.splitToSequence(' ').map { it.toInt() }.toList()
val outs = pps.map { if (it != 0) it - 1 else null }
val inss = List(nn) { mutableListOf<Int>() }
for (i in 0 until nn) {
val out = outs[i]
if (out !== null)
inss[out].add(i)
}
val sinks = (0 until nn).filter { outs[it] === null }
val y = sinks.sumOf {
dfsMaxSumMaxFun(inss, ffs, it).sumMaxFun
}
println("Case #${ti + 1}: $y")
}
data class SelectedIn(val inV: Int?, val maxFun: Int, val sumMaxFun: Long)
// We are searching a reversed forest instead of a DAG.
fun dfsMaxSumMaxFun(inss: List<List<Int>>, fs: List<Int>, v: Int): SelectedIn {
val f = fs[v]
val ins = inss[v]
return if (ins.isEmpty()) {
val fLong = f.toLong()
SelectedIn(null, f, fLong)
} else {
val inSIns = ins.map { dfsMaxSumMaxFun(inss, fs, it) }
val min = inSIns.withIndex().minByOrNull { it.value.maxFun }!!
val minValue = min.value
if (f <= minValue.maxFun)
SelectedIn(ins[min.index], minValue.maxFun, inSIns.sumOf { it.sumMaxFun })
else
SelectedIn(ins[min.index], f, inSIns.sumOf { it.sumMaxFun } + f - minValue.maxFun)
}
}
| 0 | Kotlin | 1 | 1 | 743540a46ec157a6f2ddb4de806a69e5126f10ad | 1,456 | google-code-jam | MIT License |
src/main/kotlin/aoc2021/Day08.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2021
import utils.InputUtils
fun main() {
val testInput = """be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe
edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc
fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef | cg cg fdcagb cbg
fbegcd cbd adcefb dageb afcb bc aefdc ecdab fgdeca fcdbega | efabcd cedba gadfec cb
aecbfdg fbg gf bafeg dbefa fcge gcbea fcaegb dgceab fcbdga | gecf egdcabf bgf bfgea
fgeab ca afcebg bdacfeg cfaedg gcfdb baec bfadeg bafgc acf | gebdcfa ecba ca fadegcb
dbcfg fgd bdegcaf fgec aegbdf ecdfab fbedc dacgb gdcebf gf | cefg dcbef fcge gbcadfe
bdfegc cbegaf gecbf dfcage bdacg ed bedf ced adcbefg gebcd | ed bcgafe cdgba cbgef
egadfb cdbfeg cegd fecab cgb gbdefca cg fgcdab egfdb bfceg | gbdfcae bgc cg cgb
gcafb gcf dcaebfg ecagb gf abcdeg gaef cafbge fdbac fegbdc | fgae cfgab fg bagce""".split("\n")
fun parse(input: List<String>) = input.map { line ->
val (inputList, output) = line
.split("|")
.map { it.trim().split(' ') }
inputList to output
}
fun part1(input: List<String>): Int {
val unique = listOf(2,3,4,7)
return parse(input).sumOf { (_, output) -> output.count { it.length in unique }}
}
fun deduceNumbers(input: List<String>): Map<String, Int> {
val asSets = input.map { it.toCharArray().toSet() }
val byLength = asSets.groupBy { it.size }
val knownNumbers = mutableMapOf(
1 to byLength[2]!!.first(),
4 to byLength[4]!!.first(),
7 to byLength[3]!!.first(),
8 to byLength[7]!!.first(),
)
val four = knownNumbers[4]!!
val fiveLong = byLength[5]!!
val digitA = (knownNumbers[7]!! - knownNumbers[1]).first()
val digitD = fiveLong.reduce { a,b -> a.intersect(b) }.intersect(four).first()
val digitG = fiveLong.reduce { a,b -> a.intersect(b) }.intersect(knownNumbers[8]!!.minus(four).minus(digitA)).first()
val sixLong = byLength[6]!!
val zero = sixLong.first { digitD !in it }
knownNumbers[0] = zero
val sixOrNine = sixLong.minusElement(zero)
knownNumbers[6] = sixOrNine.first {
it.intersect(four).size == 3
}
knownNumbers[9] = sixOrNine.minusElement(knownNumbers[6]!!).first()
val digitC = (knownNumbers[8]!! - knownNumbers[6]!!).first()
val digitE = (knownNumbers[8]!! - knownNumbers[9]!!).first()
knownNumbers[2] = fiveLong.first { digitE in it }
knownNumbers[5] = fiveLong.first { digitC !in it }
knownNumbers[3] = fiveLong.minusElement(knownNumbers[5]!!).minusElement(knownNumbers[2]!!).first()
return knownNumbers.entries.associateBy({ it.value.sorted().joinToString("") }, { it.key })
}
fun part2(input: List<String>): Int {
return parse(input).map { (key, out) ->
val decoder = deduceNumbers(key)
out.map { decoder[it.toCharArray().sorted().joinToString("")] ?: '?' }
}.sumOf { it.joinToString("").toInt() }
}
// test if implementation meets criteria from the description, like:
val testValue = part1(testInput)
println(testValue)
check(testValue == 26)
val puzzleInput = InputUtils.downloadAndGetLines(2021, 8)
val input = puzzleInput.toList()
println(part1(input))
println("=== Part 2 ===")
println(part2(testInput))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5abc9e479bed21ae58c093c8efbe4d343eee7714 | 3,495 | aoc-2022-kotlin | Apache License 2.0 |
src/Day05.kt | roxspring | 573,123,316 | false | {"Kotlin": 9291} | fun main() {
class State {
val instructionRegex = "move (\\d+) from (\\d+) to (\\d+)".toRegex()
val stacks: MutableList<MutableList<Char>> = mutableListOf()
fun push(stackIndex: Int, content: Char): State {
if (content == ' ') {
return this
}
for (i in stacks.size..stackIndex) {
stacks.add(mutableListOf())
}
stacks[stackIndex] += content
return this
}
fun moveOneByOne(instruction: String): State =
instructionRegex.matchEntire(instruction)!!.destructured.let { (count, from, to) ->
moveOneByOne(count.toInt(), from.toInt() - 1, to.toInt() - 1)
}
fun moveOneByOne(count: Int, fromIndex: Int, toIndex: Int): State {
for (n in 0 until count) {
val content = stacks[fromIndex].removeLast()
stacks[toIndex].add(content)
}
return this
}
fun moveByBlock(instruction: String): State =
instructionRegex.matchEntire(instruction)!!.destructured.let { (count, from, to) ->
moveByBlock(count.toInt(), from.toInt() - 1, to.toInt() - 1)
}
fun moveByBlock(count: Int, fromIndex: Int, toIndex: Int): State {
val fromStack = stacks[fromIndex]
val toStack = stacks[toIndex]
toStack.addAll(fromStack.subList(fromStack.size - count, fromStack.size))
for (i in 0 until count) {
fromStack.removeLast()
}
return this
}
fun tops(): String = stacks.map { it.last() }.joinToString("")
override fun toString(): String = stacks.maxOfOrNull { it.size }!!.downTo(0).joinToString("\n") { depth ->
stacks.joinToString(" ") { stack ->
stack.getOrNull(depth)?.let { "[$it]" } ?: " "
}
} + "\n" + (0 until stacks.size).joinToString(" ") { " ${it + 1} " }
}
fun List<String>.toState(): State = reversed().drop(1).fold(State()) { state, line ->
(1..line.length step 4).fold(state) { state2, i ->
state2.push(i / 4, line[i])
}
}
fun part1(lines: List<String>): String = lines.chunkedByBlank().toList().let {
val initialState = it[0].toState()
val instructions = it[1]
instructions.fold(initialState) { state, instruction ->
state.moveOneByOne(instruction)
}
}.tops()
fun part2(lines: List<String>): String = lines.chunkedByBlank().toList().let {
val initialState = it[0].toState()
val instructions = it[1]
instructions.fold(initialState) { state, instruction ->
state.moveByBlock(instruction)
}
}.tops()
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
val input = readInput("Day05")
println(part1(input))
check(part2(testInput) == "MCD")
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 535beea93bf84e650d8640f1c635a430b38c169b | 3,098 | advent-of-code-2022 | Apache License 2.0 |
src/leetcode_study_badge/dynamic_programming/Day6.kt | faniabdullah | 382,893,751 | false | null | package leetcode_study_badge.dynamic_programming
class Day6 {
fun maxProduct(nums: IntArray): Int {
if (nums.isEmpty()) return 0
var min = nums[0]
var max = nums[0]
var res = nums[0]
for (i in 1 until nums.size) {
val tmp = max
val n = nums[i]
max = maxOf(max * n, maxOf(min * n, n))
min = minOf(tmp * n, minOf(min * n, n))
res = maxOf(res, max)
}
return res
}
fun getMaxLen(nums: IntArray): Int {
val len: Int = nums.size
var max = 0
val fneg = IntArray(len + 1) // the length of longest negative product sub-array
val fpos = IntArray(len + 1) // the length of longest positive product sub-array
for (i in 1..len) {
if (nums[i - 1] > 0) {
// when positive subarray meets a positive number, the length will be increased by one at all case
// the negative subarray will be increased only if it is not empty.
fpos[i] = fpos[i - 1] + 1
fneg[i] = if (fneg[i - 1] > 0) fneg[i - 1] + 1 else 0
} else if (nums[i - 1] < 0) {
// the positive subarray will be increased only if the previous product is negative
// the negative subarray will be increased only if the previous product is positive
fpos[i] = if (fneg[i - 1] > 0) fneg[i - 1] + 1 else 0
fneg[i] = fpos[i - 1] + 1
}
max = maxOf(fpos[i], max)
}
return max
}
fun maxProfit(prices: IntArray): Int {
var profitOne = 0
var profitTwo = 0
for (i in 1 until prices.size) {
val temp = profitOne
profitOne = maxOf(profitOne + prices[i] - prices[i - 1], profitTwo)
profitTwo = maxOf(temp, profitTwo)
}
return maxOf(profitOne, profitTwo)
}
}
fun main() {
println(Day6().getMaxLen(intArrayOf(2, 8, 2, 3, 5, 4, -2, 10, 0, 1, 2, -3, 4, 5, 6, 7, 8, -9, 10)))
} | 0 | Kotlin | 0 | 6 | ecf14fe132824e944818fda1123f1c7796c30532 | 2,060 | dsa-kotlin | MIT License |
kotlin/src/katas/kotlin/leetcode/course_schedule/CourseSchedule.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.leetcode.course_schedule
import datsok.shouldEqual
import org.junit.Test
/**
* https://leetcode.com/problems/course-schedule/
*/
class CourseScheduleTests {
@Test fun `determine if it's possible to finish all courses`() {
canFinish(n = 0, deps = emptyList()) shouldEqual true
canFinish(n = 1, deps = emptyList()) shouldEqual true
canFinish(n = 2, deps = emptyList()) shouldEqual true
canFinish(n = 2, deps = listOf(Pair(0, 1))) shouldEqual true
canFinish(n = 2, deps = listOf(Pair(0, 1), Pair(1, 0))) shouldEqual false
canFinish(n = 7,
deps = listOf(Pair(0, 1), Pair(1, 3), Pair(3, 2), Pair(3, 4), Pair(5, 6))) shouldEqual true
canFinish(n = 7,
deps = listOf(Pair(0, 1), Pair(1, 3), Pair(3, 2), Pair(2, 0), Pair(3, 4), Pair(5, 6))) shouldEqual false
}
}
private fun canFinish(n: Int, deps: List<Pair<Int, Int>>): Boolean {
val graph = Graph(deps)
val processed = HashSet<Int>()
(0 until n).forEach { course ->
if (!processed.contains(course)) {
val visited = HashSet<Int>()
if (graph.hasNoCycles(course, visited)) processed.addAll(visited)
else return false
}
}
return true
}
private class Graph(private val deps: List<Pair<Int, Int>>) {
fun hasNoCycles(value: Int, visited: HashSet<Int>): Boolean {
if (visited.contains(value)) return false
visited.add(value)
return neighboursOf(value).all { neighbour ->
hasNoCycles(neighbour, visited)
}
}
private fun neighboursOf(course: Int): List<Int> {
return deps.filter { it.first == course }.map { it.second }
}
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 1,714 | katas | The Unlicense |
src/Day09.kt | YunxiangHuang | 572,333,905 | false | {"Kotlin": 20157} | fun main() {
fun calDistance(head: Pair<Int, Int>, tail: Pair<Int, Int>): Int {
return kotlin.math.abs(head.first - tail.first) +
kotlin.math.abs(head.second - tail.second)
}
fun needMove(head: Pair<Int, Int>, tail: Pair<Int, Int>): Boolean {
if (head.first != tail.first && head.second != tail.second) {
return calDistance(head, tail) > 2
}
return calDistance(head, tail) > 1
}
fun follow(head: Pair<Int, Int>, tail: Pair<Int, Int>): Pair<Int, Int> {
if (!needMove(head, tail)) {
return tail
}
// in same row
if (head.first == tail.first && head.second != tail.second) {
if (head.second > tail.second) {
return Pair(tail.first, tail.second + 1)
}
return Pair(tail.first, tail.second - 1)
}
// in same col
if (head.first != tail.first && head.second == tail.second) {
if (head.first > tail.first) {
return Pair(tail.first + 1, tail.second)
}
return Pair(tail.first - 1, tail.second)
}
var df = -1
var ds = -1
if (head.first > tail.first) {
df = 1
}
if (head.second > tail.second) {
ds = 1
}
return Pair(tail.first + df, tail.second + ds)
}
val size = 10
val nodes = ArrayList<Pair<Int, Int>>(size)
val flags = HashMap<Pair<Int, Int>, Boolean>()
for (i in 0 until size) {
nodes.add(Pair(0, 0))
}
for (cmd in readInput("Day09")) {
val l = cmd.split(" ")
val direct = l[0]
val steps = l[1].toInt()
for (step in 0 until steps) {
var head = nodes[0]
when (direct) {
"L" -> {
head = Pair(head.first - 1, head.second)
}
"R" -> {
head = Pair(head.first + 1, head.second)
}
"U" -> {
head = Pair(head.first, head.second + 1)
}
"D" -> {
head = Pair(head.first, head.second - 1)
}
}
nodes[0] = head
flags[nodes[size - 1]] = true
for (i in 1 until size) {
nodes[i] = follow(nodes[i - 1], nodes[i])
}
flags[nodes[size - 1]] = true
}
}
println("Part I: ${flags.size}")
} | 0 | Kotlin | 0 | 0 | f62cc39dd4881f4fcf3d7493f23d4d65a7eb6d66 | 2,516 | AoC_2022 | Apache License 2.0 |
kotlin-advent-of-code/src/main/kotlin/advent/twenty_sixteen/Day01NoTimeForATaxicab.kt | AKiwiCoder | 162,471,091 | false | {"Java": 531288, "Scala": 463157, "C#": 15266, "Python": 14164, "Kotlin": 11280, "Shell": 1566, "C++": 1206, "Makefile": 157} | package advent.twenty_sixteen
import advent.common.DailyProblem
import kotlin.math.abs
data class Position(val x: Int, val y: Int)
enum class Facing {
North {
override fun left(): Facing = West
override fun right(): Facing = East
override fun move(pos: Position, steps: Int): Position = Position(pos.x, pos.y + steps)
},
South {
override fun left(): Facing = East
override fun right(): Facing = West
override fun move(pos: Position, steps: Int): Position = Position(pos.x, pos.y - steps)
},
East {
override fun left(): Facing = North
override fun right(): Facing = South
override fun move(pos: Position, steps: Int): Position = Position(pos.x + steps, pos.y)
},
West {
override fun left(): Facing = South
override fun right(): Facing = North
override fun move(pos: Position, steps: Int): Position = Position(pos.x - steps, pos.y)
};
abstract fun left(): Facing
abstract fun right(): Facing
abstract fun move(pos: Position, steps: Int): Position;
}
data class Location(val facing: Facing, val position: Position)
class Day01NoTimeForATaxicab : DailyProblem<Int, Int> {
override var part1Answer: Int = -1
override var part2Answer: Int = -1
private fun move(location: Location, stepsSoFar: List<Position>, command: String): Pair<Location, List<Position>> {
val steps = Integer.parseInt(command.substring(1))
val newFacing = when (command[0]) {
'L' -> location.facing.left()
'R' -> location.facing.right()
else -> location.facing
}
var newSteps = stepsSoFar
var newPosition = location.position
for (i in 0 until steps) {
newPosition = newFacing.move(newPosition, 1)
newSteps += newPosition
}
return Pair(Location(newFacing, newPosition), newSteps)
}
constructor (filename: String) {
val input = Day01NoTimeForATaxicab::class.java.getResource(filename).readText().split(",")
val (endLoc, steps) = input.fold(Pair(Location(Facing.North, Position(0, 0)), listOf<Position>())) { acc, cmd ->
move(acc.first, acc.second, cmd.trim())
}
part1Answer = manhattenDistance(Position(0,0), endLoc.position)
part2Answer = manhattenDistance(Position(0,0), search(steps[0], 0, steps.drop(1)))
}
private fun manhattenDistance(lhs : Position, rhs : Position) : Int {
return abs(lhs.x - rhs.x) + abs(lhs.y - rhs.y)
}
private tailrec fun search(position: Position, index: Int, rest: List<Position>): Position {
return when {
rest.contains(position) -> position
rest.isEmpty() -> Position(0,0)
else -> search(rest[0], index + 1, rest.drop(1))
}
}
} | 0 | Java | 0 | 1 | 07d0f496d9efd620a21c906dd55f097326ab8b5f | 2,851 | advent-of-code | MIT License |
kotlin/src/com/s13g/aoc/aoc2021/Day13.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2021
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
/**
* --- Day 13: Transparent Origami ---
* https://adventofcode.com/2021/day/13
*/
class Day13 : Solver {
override fun solve(lines: List<String>): Result {
val positions = lines.filter { it.contains(',') }
.map { it.split(',') }
.map { XY(it[0].toInt(), it[1].toInt()) }
.toMutableSet()
val folds = lines.filter { it.startsWith("fold") }
.map { it.split('=') }
.map { Fold(it[0].substring(11), it[1].toInt()) }
var width = positions.map { it.x }.max()!!
var height = positions.map { it.y }.max()!!
var partA = 0
for ((i, fold) in folds.withIndex()) {
for (pos in positions.toSet()) {
if ((fold.axis == "y" && pos.y > fold.v) || (fold.axis == "x" && pos.x > fold.v)) {
positions.remove(pos)
if (fold.axis == "y") positions.add(XY(pos.x, fold.v - (pos.y - fold.v)))
if (fold.axis == "x") positions.add(XY(fold.v - (pos.x - fold.v), pos.y))
}
}
if (i == 0) partA = positions.size
width = positions.map { it.x }.max()!!
height = positions.map { it.y }.max()!!
}
val partB = printGrid(positions, width, height)
return Result("$partA", "\n$partB")
}
private data class XY(val x: Int, val y: Int)
private data class Fold(val axis: String, val v: Int)
private fun printGrid(pos: Set<XY>, width: Int, height: Int): String {
var result = ""
for (y in 0..height) {
for (x in 0..width) {
result += if (pos.contains(XY(x, y))) '#' else '.'
}
result += '\n'
}
return result
}
}
| 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 1,656 | euler | Apache License 2.0 |
advent-of-code/src/main/kotlin/com/akikanellis/adventofcode/year2022/Day02.kt | akikanellis | 600,872,090 | false | {"Kotlin": 142932, "Just": 977} | package com.akikanellis.adventofcode.year2022
import com.akikanellis.adventofcode.year2022.Day02.RoundResult.DRAW
import com.akikanellis.adventofcode.year2022.Day02.RoundResult.LOSE
import com.akikanellis.adventofcode.year2022.Day02.RoundResult.WIN
object Day02 {
fun totalScoreForHands(input: String) = firstColumnToSecondColumn(input)
.map { Pair(Hand.of(it.first), Hand.of(it.second)) }
.sumOf { (firstHand, secondHand) ->
secondHand.score + secondHand.roundResultAgainst(firstHand).score
}
fun totalScoreForFirstHandAndRoundResult(input: String) = firstColumnToSecondColumn(input)
.map { Pair(Hand.of(it.first), RoundResult.of(it.second)) }
.sumOf { (firstHand, roundResult) ->
roundResult.score + roundResult.handNeededForRoundResult(firstHand).score
}
private fun firstColumnToSecondColumn(input: String) = input
.lines()
.filter { it.isNotEmpty() }
.map { it.split(" ") }
.map { Pair(it[0], it[1]) }
private enum class Hand(
val score: Int,
val firstRepresentation: String,
val secondRepresentation: String
) {
ROCK(1, "A", "X") {
override fun losesAgainst() = PAPER
},
PAPER(2, "B", "Y") {
override fun losesAgainst() = SCISSORS
},
SCISSORS(3, "C", "Z") {
override fun losesAgainst() = ROCK
};
companion object {
fun of(representation: String) = Hand.values()
.firstOrNull { it.firstRepresentation == representation }
?: Hand.values().first { it.secondRepresentation == representation }
}
abstract fun losesAgainst(): Hand
private fun losesAgainst(opponentsHand: Hand) = losesAgainst() == opponentsHand
fun drawsAgainst() = this
private fun drawsAgainst(opponentsHand: Hand) = drawsAgainst() == opponentsHand
fun winsAgainst() = Hand.values().single { it.losesAgainst(this) }
fun roundResultAgainst(opponentsHand: Hand) =
when {
losesAgainst(opponentsHand) -> LOSE
drawsAgainst(opponentsHand) -> DRAW
else -> WIN
}
}
private enum class RoundResult(val score: Int, val representation: String) {
LOSE(0, "X") {
override fun handNeededForRoundResult(opponentsHand: Hand) = opponentsHand.winsAgainst()
},
DRAW(3, "Y") {
override fun handNeededForRoundResult(opponentsHand: Hand) =
opponentsHand.drawsAgainst()
},
WIN(6, "Z") {
override fun handNeededForRoundResult(opponentsHand: Hand) =
opponentsHand.losesAgainst()
};
companion object {
fun of(representation: String) = values().first { it.representation == representation }
}
abstract fun handNeededForRoundResult(opponentsHand: Hand): Hand
}
}
| 8 | Kotlin | 0 | 0 | 036cbcb79d4dac96df2e478938de862a20549dce | 2,991 | advent-of-code | MIT License |
src/Day14.kt | thorny-thorny | 573,065,588 | false | {"Kotlin": 57129} | sealed class Line(val topY: Int) {
data class HorizontalInfinite(val y: Int): Line(y)
data class Horizontal(val y: Int, val xMin: Int, val xMax: Int): Line(y)
data class Vertical(val x: Int, val yMin: Int, val yMax: Int): Line(yMin)
fun hasX(value: Int) = when (this) {
is HorizontalInfinite -> true
is Horizontal -> value in xMin..xMax
is Vertical -> value == x
}
fun hasY(value: Int) = when (this) {
is HorizontalInfinite -> value == y
is Horizontal -> value == y
is Vertical -> value in yMin..yMax
}
}
class SandSimulator(lines: List<Line>) {
private val spawn = 500 to 0
private val lines = lines.sortedBy(Line::topY)
private val piles = mutableMapOf<Pair<Line, Int>, Int>()
var sandPiled = 0
private set
private fun getPileTop(line: Line, x: Int) = when (val pile = piles[line to x]) {
null -> line.topY
else -> pile
}
private fun addPileTop(line: Line, x: Int) {
val pair = line to x
piles[pair] = (piles[pair] ?: line.topY) - 1
}
fun dropSandUntilPiles() {
while (dropSand()) {
}
}
private fun dropSand(): Boolean {
var (x, y) = spawn
while (true) {
val centerLine = lines.firstOrNull { it.hasX(x) && it.topY > y } ?: return false
val centerPile = getPileTop(centerLine, x)
if (centerPile == y) {
return false
}
val leftLine =
lines.firstOrNull { it.hasX(x - 1) && (it.hasY(centerPile) || it.topY >= centerPile) } ?: return false
val leftPile = getPileTop(leftLine, x - 1)
val rightLine =
lines.firstOrNull { it.hasX(x + 1) && (it.hasY(centerPile) || it.topY >= centerPile) } ?: return false
val rightPile = getPileTop(rightLine, x + 1)
val canGoLeft = leftPile > centerPile
val canGoRight = rightPile > centerPile
if (!canGoLeft && !canGoRight) {
addPileTop(centerLine, x)
sandPiled += 1
return true
} else if (canGoLeft) {
x -= 1
y = leftPile - 1
} else {
x += 1
y = rightPile - 1
}
}
}
}
fun main() {
fun parseLines(input: List<String>): List<Line> {
val lines = mutableListOf<Line>()
input.forEach {
val parts = it
.split(" -> ")
.map { part ->
val (x, y) = part.split(',').map(String::toInt)
x to y
}
parts
.zipWithNext()
.forEach { pair ->
val (start, end) = pair
if (start.first == end.first) {
lines.add(Line.Vertical(start.first, minOf(start.second, end.second), maxOf(start.second, end.second)))
} else {
lines.add(Line.Horizontal(start.second, minOf(start.first, end.first), maxOf(start.first, end.first)))
}
}
}
return lines.toList()
}
fun part1(input: List<String>): Int {
val sandSimulator = SandSimulator(parseLines(input))
sandSimulator.dropSandUntilPiles()
return sandSimulator.sandPiled
}
fun part2(input: List<String>): Int {
val lines = parseLines(input)
val maxY = lines.maxOf {
when (it) {
is Line.HorizontalInfinite -> it.y
is Line.Horizontal -> it.y
is Line.Vertical -> it.yMax
}
}
val sandSimulator = SandSimulator(lines + Line.HorizontalInfinite(maxY + 2))
sandSimulator.dropSandUntilPiles()
return sandSimulator.sandPiled
}
val testInput = readInput("Day14_test")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 843869d19d5457dc972c98a9a4d48b690fa094a6 | 4,101 | aoc-2022 | Apache License 2.0 |
src/Day12.kt | wbars | 576,906,839 | false | {"Kotlin": 32565} | import kotlin.math.min
fun main() {
fun solve(
input: List<String>,
iStart: Int,
jStart: Int,
iEnd: Int,
jEnd: Int
): Int {
val a = Array(input.size) { IntArray(input[0].length) { Int.MAX_VALUE } }
a[iStart][jStart] = 0
val v = Array(input.size) { BooleanArray(input[0].length) { false } }
val prev = Array(input.size) { Array(input[0].length) { "." } }
while (true) {
val pp = a.findMin(v) ?: break
val i = pp.first
val j = pp.second
v[i][j] = true
for ((ii, jj) in sequenceOf(Pair(i - 1, j), Pair(i + 1, j), Pair(i, j - 1), Pair(i, j + 1))) {
if (ii in a.indices && jj in a[ii].indices && !v[ii][jj]) {
if (input.getSafe(i, j) - input.getSafe(ii, jj) >= -1) {
if (a[i][j] + 1 < a[ii][jj]) {
a[ii][jj] = min(a[ii][jj], a[i][j] + 1)
if (ii == i - 1) {
prev[i][j] = "↑"
} else if (ii == i + 1) {
prev[i][j] = "↓"
} else if (jj == j - 1) {
prev[i][j] = "←"
} else {
prev[i][j] = "→"
}
}
}
}
}
if (i == iEnd && j == jEnd) {
break
}
}
println(prev.joinToString("\n", transform = { it.joinToString("") }))
return a[iEnd][jEnd]
}
fun part1(input: List<String>): Int {
var iStart = 0
var jStart = 0
var iEnd = 0
var jEnd = 0
for (i in input.indices) {
for (j in input[i].indices) {
if (input[i][j] == 'S') {
iStart = i
jStart = j
} else if (input[i][j] == 'E') {
iEnd = i
jEnd = j
}
}
}
return solve(input, iStart, jStart, iEnd, jEnd)
}
fun part2(input: List<String>): Int {
var iEnd = 0
var jEnd = 0
for (i in input.indices) {
for (j in input[i].indices) {
if (input[i][j] == 'E') {
iEnd = i
jEnd = j
}
}
}
var res = Int.MAX_VALUE
for (i in input.indices) {
for (j in input[i].indices) {
if (input.getSafe(i, j) == 'a') {
res = min(res, solve(input, i,j,iEnd, jEnd))
}
}
}
return res
}
part1(readInput("input")).println()
part2(readInput("input")).println()
}
private fun List<String>.getSafe(i: Int, j: Int): Char {
return when (this[i][j]) {
'S' -> 'a'
'E' -> 'z'
else -> this[i][j]
}
}
fun Array<IntArray>.findMin(v: Array<BooleanArray>): Pair<Int, Int>? {
var min = Int.MAX_VALUE
var iMin = -1
var jMin = -1
for (i in indices) {
for (j in this[i].indices) {
if (!v[i][j] && min > this[i][j]) {
min = this[i][j]
iMin = i
jMin = j
}
}
}
return if (iMin >= 0) Pair(iMin, jMin) else null
}
| 0 | Kotlin | 0 | 0 | 344961d40f7fc1bb4e57f472c1f6c23dd29cb23f | 3,464 | advent-of-code-2022 | Apache License 2.0 |
2021/src/main/kotlin/Day23.kt | eduellery | 433,983,584 | false | {"Kotlin": 97092} | import java.util.PriorityQueue
import kotlin.math.abs
class Day23(val input: List<String>) {
private val initialState = State.from(input)
private val extendedState = State.from(input.take(3) + " #D#C#B#A# " + " #D#B#A#C# " + input.takeLast(2))
fun solve1() = organizePods(initialState)
fun solve2() = organizePods(extendedState)
private fun organizePods(initialState: State): Int {
val toVisit = PriorityQueue<StateWithCost>().apply { add(StateWithCost(initialState, 0)) }
val visited = mutableSetOf<StateWithCost>()
val currentCosts = mutableMapOf<State, Int>().withDefault { Int.MAX_VALUE }
while (toVisit.isNotEmpty()) {
val current = toVisit.poll().also { visited.add(it) }
current.state.nextPossibleStates().forEach { next ->
if (!visited.contains(next)) {
val newCost = current.cost + next.cost
if (newCost < currentCosts.getValue(next.state)) {
currentCosts[next.state] = newCost
toVisit.add(StateWithCost(next.state, newCost))
}
}
}
}
return currentCosts.keys.first { it.isFinished() }.let { currentCosts.getValue(it) }
}
private data class State(private val config: List<List<Char>>) {
private val hallway = config[0]
private val rooms = config.drop(1)
private val destinationRooms = mapOf(
'A' to Room('A', 2, rooms.map { row -> row[2] }),
'B' to Room('B', 4, rooms.map { row -> row[4] }),
'C' to Room('C', 6, rooms.map { row -> row[6] }),
'D' to Room('D', 8, rooms.map { row -> row[8] })
)
private val multipliers = mapOf('A' to 1, 'B' to 10, 'C' to 100, 'D' to 1000)
private val legalHallwayIndexes
get() = listOf(0, 1, 3, 5, 7, 9, 10).filter { hallway[it] == '.' }
fun isFinished() = destinationRooms.values.all { it.hasOnlyValidPods() }
fun nextPossibleStates(): List<StateWithCost> {
return buildList {
podsInHallwayThatCanMove().forEach {
val room = destinationRooms.getValue(it.value)
if (hallwayPathIsClear(it.index, room.index)) {
val y = room.content.lastIndexOf('.') + 1
val cost = (abs(it.index - room.index) + y) * multipliers.getValue(it.value)
add(StateWithCost(State(config.map { row -> row.toMutableList() }.apply {
get(0)[it.index] = '.'
get(y)[room.index] = it.value
}), cost))
}
}
roomsWithWrongPods().forEach { room ->
val toMove = room.content.withIndex().first { it.value != '.' }
legalHallwayIndexes.forEach { index ->
if (hallwayPathIsClear(index, room.index)) {
val y = toMove.index + 1
val cost = (abs(room.index - index) + y) * multipliers.getValue(toMove.value)
add(StateWithCost(State(config.map { row -> row.toMutableList() }.apply {
get(y)[room.index] = '.'
get(0)[index] = toMove.value
}), cost))
}
}
}
}
}
private fun podsInHallwayThatCanMove(): List<IndexedValue<Char>> {
return hallway.withIndex().filter {
it.value.isLetter() && destinationRooms.getValue(it.value).isEmptyOrHasAllValidPods()
}
}
private fun roomsWithWrongPods() = destinationRooms.values.filter { it.hasPodsWithWrongType() }
private fun hallwayPathIsClear(start: Int, end: Int): Boolean {
return hallway.slice(
when (start > end) {
true -> (start - 1) downTo end
false -> (start + 1)..end
}
).all { it == '.' }
}
companion object {
fun from(input: List<String>) = State(input.drop(1).dropLast(1).map { it.drop(1).dropLast(1).toList() })
}
}
private class StateWithCost(val state: State, val cost: Int) : Comparable<StateWithCost> {
override fun compareTo(other: StateWithCost) = cost.compareTo(other.cost)
}
private class Room(val char: Char, val index: Int, val content: List<Char>) {
fun hasOnlyValidPods() = content.all { it == char }
fun isEmptyOrHasAllValidPods() = content.all { it == '.' || it == char }
fun hasPodsWithWrongType() = !isEmptyOrHasAllValidPods()
}
} | 0 | Kotlin | 0 | 1 | 3e279dd04bbcaa9fd4b3c226d39700ef70b031fc | 4,831 | adventofcode-2021-2025 | MIT License |
src/main/kotlin/dev/bogwalk/batch8/Problem82.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch8
import java.util.PriorityQueue
/**
* Problem 82: Path Sum 3 Ways
*
* https://projecteuler.net/problem=82
*
* Goal: Find the minimum path sum for an NxN grid, by starting at any cell in the leftmost column
* and ending at any cell in the rightmost column, while only being able to move up, down or
* right with each step.
*
* Constraints: 1 <= N <= 1000, numbers in [1, 1e9]
*
* e.g.: N = 3
* grid = 1 0 5
* 1 0 0
* 1 1 1
* minimum = 1: {1 -> R -> D -> R -> 1 || 1 -> R -> R -> 1}
*/
class PathSum3Ways {
/**
* Solution isolates the final column of the grid & each of this array's elements iteratively
* becomes the sum bubbled up by the minimal path encountered moving backwards through the
* columns.
*
* N.B. The nested arrays have to be cloned, otherwise they will reference and alter the
* original array, causing errors when testing a single grid with multiple solutions. An
* alternative would be to provide the grid as a List<MutableList<Long>> & process as such or
* cast to a 2D array.
*
* SPEED (BETTER) 1.49ms for N = 80
*/
fun minPathSum(rows: Int, grid: Array<LongArray>): Long {
val sums = LongArray(rows) { grid[it].clone()[rows-1] }
for (i in rows - 2 downTo 0) {
sums[0] += grid[0][i]
for (j in 1 until rows) {
// i.e. between the right or down
sums[j] = minOf(sums[j], sums[j-1]) + grid[j][i]
}
for (j in rows - 2 downTo 0) {
// bubble up the minimal last sums with the rightmost element
sums[j] = minOf(sums[j], sums[j+1] + grid[j][i])
}
}
return sums.minOrNull()!!
}
/**
* Solution is identical to the Dijkstra solution used in Problem 81, except for the following
* changes:
*
* - All leftmost column elements are added to the PriorityQueue as starters.
*
* - The loop is broken when any cell in the rightmost column is reached.
*
* - An extra upwards step is added to the queue, if possible.
*
* SPEED (WORSE) 31.32ms for N = 80
*/
fun minPathSumDijkstra(rows: Int, grid: Array<IntArray>): Long {
val visited = Array(rows) { BooleanArray(rows) }
val compareByWeight = compareBy<Triple<Int, Int, Long>> { it.third }
val queue = PriorityQueue(compareByWeight).apply {
addAll(List(rows) { Triple(it, 0, grid[it][0].toLong()) })
}
var minSum = 0L
while (queue.isNotEmpty()) {
val (row, col, weight) = queue.poll()
if (visited[row][col]) continue
if (col == rows - 1) {
minSum = weight
break
}
visited[row][col] = true
if (row - 1 >= 0) {
queue.add(Triple(row - 1, col, weight + grid[row - 1][col]))
}
if (col + 1 < rows) {
queue.add(Triple(row, col + 1, weight + grid[row][col+1]))
}
if (row + 1 < rows) {
queue.add(Triple(row + 1, col, weight + grid[row + 1][col]))
}
}
return minSum
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 3,272 | project-euler-kotlin | MIT License |
src/com/kingsleyadio/adventofcode/y2021/day05/Solution.kt | kingsleyadio | 435,430,807 | false | {"Kotlin": 134666, "JavaScript": 5423} | package com.kingsleyadio.adventofcode.y2021.day05
import com.kingsleyadio.adventofcode.util.readInput
import kotlin.math.abs
fun main() {
println(solution(useDiagonals = false))
println(solution(useDiagonals = true))
}
fun solution(useDiagonals: Boolean): Int {
val points = hashSetOf<String>()
val result = hashSetOf<String>()
readInput(2021, 5).forEachLine { line ->
val (x1, y1, x2, y2) = line.split(" -> ").flatMap { it.split(",") }.map { it.toInt() }
when {
x1 == x2 -> (if (y1 < y2) y1..y2 else y2..y1).forEach { y ->
val id = "$x1-$y"
if (id in points) result.add(id) else points.add(id)
}
y1 == y2 -> (if (x1 < x2) x1..x2 else x2..x1).forEach { x ->
val id = "$x-$y1"
if (id in points) result.add(id) else points.add(id)
}
useDiagonals ->(0..abs(x1 - x2)).forEach { index ->
val x = x1 + index * if (x1 < x2) 1 else -1
val y = y1 + index * if (y1 < y2) 1 else -1
val id = "$x-$y"
if (id in points) result.add(id) else points.add(id)
}
}
}
return result.size
}
| 0 | Kotlin | 0 | 1 | 9abda490a7b4e3d9e6113a0d99d4695fcfb36422 | 1,223 | adventofcode | Apache License 2.0 |
src/Day14.kt | fedochet | 573,033,793 | false | {"Kotlin": 77129} | import kotlin.math.sign
fun main() {
data class Pos(val row: Int, val column: Int) {
fun moveLeft() = Pos(row, column - 1)
fun moveRight() = Pos(row, column + 1)
fun moveDown() = Pos(row + 1, column)
}
fun parseWall(wallLine: String): List<Pos> =
wallLine
.split(" -> ")
.map { dot ->
val (column, row) = dot.split(",", limit = 2).map { it.toInt() }
Pos(row, column)
}
fun linePositions(from: Pos, to: Pos): Sequence<Pos> = sequence {
require(from.row == to.row || from.column == to.column)
var current = from
while (current != to) {
yield(current)
val rowStep = (to.row - from.row).sign
val columnStep = (to.column - from.column).sign
current = Pos(current.row + rowStep, current.column + columnStep)
}
yield(to)
}
fun possibleMoves(pos: Pos): List<Pos> {
val down = pos.moveDown()
return listOf(down, down.moveLeft(), down.moveRight())
}
fun buildInitialSetup(walls: List<List<Pos>>): Set<Pos> {
return walls.asSequence()
.flatMap { wall ->
wall.asSequence().zipWithNext { from, to -> linePositions(from, to) }.flatten()
}
.toSet()
}
fun part1(input: List<String>): Int {
val walls = input.map { parseWall(it) }
val setup = buildInitialSetup(walls).toMutableSet()
val lowestPoint = setup.maxOf { it.row }
var sandUnits = 0
outer@while (true) {
var current = Pos(0, 500)
while (true) {
if (current.row > lowestPoint) {
break@outer
}
val next = possibleMoves(current).firstOrNull { it !in setup }
if (next != null) {
current = next
} else {
setup.add(current)
sandUnits++
break
}
}
}
return sandUnits
}
fun part2(input: List<String>): Int {
val walls = input.map { parseWall(it) }
val setup = buildInitialSetup(walls).toMutableSet()
val lowestPoint = setup.maxOf { it.row }
val bottomLine = lowestPoint + 2
fun isFree(pos: Pos): Boolean {
return pos !in setup && pos.row < bottomLine
}
var sandUnits = 0
outer@while (true) {
var current = Pos(0, 500)
while (true) {
if (current in setup) {
break@outer
}
val next = possibleMoves(current).firstOrNull { isFree(it) }
if (next != null) {
current = next
} else {
setup.add(current)
sandUnits++
break
}
}
}
return sandUnits
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 975362ac7b1f1522818fc87cf2505aedc087738d | 3,334 | aoc2022 | Apache License 2.0 |
kotlin/reader-monad/src/main/kotlin/Main.kt | enolive | 65,559,078 | false | {"Java": 150911, "Kotlin": 130819, "TypeScript": 121966, "Groovy": 76917, "JavaScript": 53147, "C#": 40972, "Haskell": 36546, "Python": 14709, "Scala": 12193, "HTML": 11513, "Clojure": 8840, "Gherkin": 8730, "Dart": 6755, "Ruby": 5800, "CSS": 3279, "Elm": 2803, "PHP": 2211, "Svelte": 1783, "Rust": 821, "Swift": 404, "PureScript": 294, "Makefile": 220, "Sass": 128, "SCSS": 80, "Objective-C": 38} | fun main() {
println("\nFunctor\n")
val inc = { n: Int -> n + 1 }
val mult2 = { n: Int -> n * 2 }
val g1 = mult2.map(inc)
explain("g1(5)", g1(5))
println("\nApplicative\n")
val isValidCommand = { c: Char -> c in "fblr" }
val isInvalidCommand = isValidCommand.map(Boolean::not)
val any = { p: (Char) -> Boolean -> { t: String -> t.any(p) } }
val and = Boolean::and.curried()
val h1 = any(isValidCommand).map(and).ap(any(isInvalidCommand))
val h2 = any(isValidCommand).zip(any(isInvalidCommand), Boolean::and)
explain("""h1("fffaaa")""", h1("fffaaa"))
explain("""h1("aaa")""", h1("aaa"))
explain("""h1("fff")""", h1("fff"))
explain("""h2("fffaaa")""", h2("fffaaa"))
explain("""h2("aaa")""", h2("aaa"))
explain("""h2("fff")""", h2("fff"))
println("\nMonad\n")
val f1 = List<*>::distinct.flatMap(List<*>::equals.curried())
explain("""f1(listOf(1, 2, 3))""", f1(listOf(1, 2, 3)))
explain("""f1(listOf(1, 1, 2, 3, 3))""", f1(listOf(1, 1, 2, 3, 3)))
println("\nApplicative variants\n")
val f2 = List<*>::distinct.map(List<*>::equals.curried()).ap(::identity)
val f3 = List<*>::distinct.zip(::identity, List<*>::equals)
explain("""f2(listOf(1, 2, 3))""", f2(listOf(1, 2, 3)))
explain("""f2(listOf(1, 1, 2, 3, 3))""", f2(listOf(1, 1, 2, 3, 3)))
explain("""f3(listOf(1, 2, 3))""", f3(listOf(1, 2, 3)))
explain("""f3(listOf(1, 1, 2, 3, 3))""", f3(listOf(1, 1, 2, 3, 3)))
println("\nAnother fun example\n")
val eqStr = { xs: String -> { ys: String -> xs == ys } }
val toLower = { xs: String -> xs.lowercase() }
val isPalindrome = toLower.map(String::reversed.flatMap(eqStr))
explain("""isPalindrome("Anna")""", isPalindrome("Anna"))
explain("""isPalindrome("Hello")""", isPalindrome("Hello"))
}
fun explain(function: String, output: Any) {
println("$function = $output")
}
fun <T> List<T>.tails() = indices.map { subList(it, size) }
fun <T> List<T>.uniquePairs() =
tails().flatMap {
val x = it.first()
val ys = it.drop(1)
ys.map { y -> x to y }
}
fun List<Int>.solve() = uniquePairs().filter { (x, y) -> x + y == 5 }
| 88 | Java | 3 | 9 | f01141469ac86352f8dc511579ead10dc7563413 | 2,109 | learning | MIT License |
src/year2022/04/Day04.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2022.`04`
import readInput
fun main() {
fun List<Int>.asRange(): IntRange {
return first()..get(1)
}
fun IntRange.contains(range: IntRange): Boolean {
return first >= range.first && last <= range.last
}
fun IntRange.overlaps(range: IntRange): Boolean {
return toSet().intersect(range.toSet()).isNotEmpty()
}
fun String.toPairOfRanges(): Pair<IntRange, IntRange> {
val list = split(",")
return list.first().split("-").map { it.toInt() }.asRange() to
list[1].split("-").map { it.toInt() }.asRange()
}
fun part1(input: List<String>): Int {
return input
.map { it.toPairOfRanges() }
.filter { (leftRange, rightRange) ->
leftRange.contains(rightRange) || rightRange.contains(leftRange)
}
.size
}
fun part2(input: List<String>): Int {
return input
.map { it.toPairOfRanges() }
.filter { (leftRange, rightRange) -> leftRange.overlaps(rightRange) }
.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
val part1Test = part2(testInput)
println(part1Test)
check(part1Test == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 1,380 | KotlinAdventOfCode | Apache License 2.0 |
src/main/kotlin/day14/Day14.kt | Mee42 | 433,459,856 | false | {"Kotlin": 42703, "Java": 824} | package dev.mee42.day14
import dev.mee42.*
fun main(part: Part): Long {
val rawInput = input(day = 14, year = 2021)
val (start, lookup) = rawInput.trim().split("\n\n").let { (a, b) ->
a.map(::id) to b.lines().map { s ->
s.split(" -> ")
}.associate { (a, b) -> (a[0] to a[1]) to (b[0]) }
}
// NNCB
// NN NC CB split into pairs
// NCN NBC CHB next step
// NC CN NB BC CH HB back to pairs
// N C N B C H +B take the first value, add B to the end
// NCNBCHB
val initial = start.zipWithNext().associateWith { 1L }
val final = (1..if(part == Part.TWO) 40 else 10).fold(initial) { pairs, _ ->
val newPairs = mutableMapOf<Pair<Char, Char>, Long>()
pairs.map { (key, count) ->
val (a, b) = key
val middleChar = lookup[key]!!
newPairs[a to middleChar] = (newPairs[a to middleChar] ?: 0) + count
newPairs[middleChar to b] = (newPairs[middleChar to b] ?: 0) + count
}
newPairs
}.map { (a, b) -> a.first to b}
val distinctChars = final.map { it.first }.distinct()
val result = distinctChars
.map {
it to final.filter { (c, _) -> c == it }.sumOf { (_, count) -> count }
}.map { (char, count) ->
char to count.apIf(char == start.last(), c_plus(1L))
}
.sortedBy { (_, b) -> b }
return result.last().second - result.first().second
}
fun main() {
println("Part 1: " + main(Part.ONE))
println("Part 2: " + main(Part.TWO))
} | 0 | Kotlin | 0 | 0 | db64748abc7ae6a92b4efa8ef864e9bb55a3b741 | 1,573 | aoc-2021 | MIT License |
src/day17.kt | miiila | 725,271,087 | false | {"Kotlin": 77215} | import java.io.File
import java.util.*
import kotlin.system.exitProcess
private const val DAY = 17
fun main() {
if (!File("./day${DAY}_input").exists()) {
downloadInput(DAY)
println("Input downloaded")
exitProcess(0)
}
val transformer = { x: String -> x.toList().map { it.digitToInt() } }
val input = loadInput(DAY, true, transformer)
println(input)
solvePart1(input)
solvePart2()
}
// Part 1
private fun solvePart1(input: List<List<Int>>): Int {
val unvisited = PriorityQueue<Node>()
for (r in (0..<input.count())) {
for (c in (0..<input.count())) {
unvisited.add(Node(Pair(r, c), if (r == 12 && c == 12) 0 else Int.MAX_VALUE, "x"))
}
}
val visited = mutableSetOf<Node>()
dijkstraSearch(input, unvisited, visited)
return 0
}
data class Node(val pos: Pair<Int, Int>, var heat: Int, var path: String) : Comparable<Node> {
override fun compareTo(other: Node): Int {
return this.heat.compareTo(other.heat)
}
}
fun dijkstraSearch(grid: List<List<Int>>, unvisited: PriorityQueue<Node>, visited: MutableSet<Node>) {
while (unvisited.isNotEmpty()) {
val current = unvisited.remove()
for (neighbor in getNext(current.pos)) {
// check grid size
if (neighbor.first.first < 0 || neighbor.first.first == grid.count() || neighbor.first.second < 0 || neighbor.first.second == grid[0].count()) {
continue
}
// check path
if (current.path.count() >= 3 && current.path.reversed().slice(0..<3).all { it == neighbor.second }) {
// three consecutive moves, skip
continue
}
if (isOpposite(current.path.last(), neighbor.second)) {
// going backwards
continue
}
val nextNode = unvisited.find { it.pos == neighbor.first } ?: continue
unvisited.remove(nextNode)
if (nextNode.heat > current.heat + grid[neighbor.first.first][neighbor.first.second]) {
nextNode.heat = current.heat + grid[neighbor.first.first][neighbor.first.second]
nextNode.path = current.path + neighbor.second
}
// trigger queue sort
unvisited.add(nextNode)
}
visited.add(current)
}
return
}
fun isOpposite(c1: Char, c2: Char): Boolean {
return when (c1) {
'v' -> c2 == '^'
'^' -> c2 == 'v'
'>' -> c2 == '<'
'<' -> c2 == '>'
'x' -> false
else -> error("")
}
}
fun getNext(pos: Pair<Int, Int>): List<Pair<Pair<Int, Int>, Char>> {
return listOf(
Pair(Pair(pos.first, pos.second + 1), '>'),
Pair(Pair(pos.first + 1, pos.second), 'v'),
Pair(Pair(pos.first - 1, pos.second), '^'),
Pair(Pair(pos.first, pos.second - 1), '<'),
)
}
// Part 2
private fun solvePart2() {
TODO()
} | 0 | Kotlin | 0 | 1 | 1cd45c2ce0822e60982c2c71cb4d8c75e37364a1 | 2,965 | aoc2023 | MIT License |
day12/src/main/kotlin/Day12.kt | bzabor | 160,240,195 | false | null |
class Day12(private val input: List<String>) {
val initialState = input[0].split(" ").takeLast(1)[0]
val rules = input.drop(2).map{ it.split(" => ")}.map{ it[0] to it[1]}.toMap()
val gens = 500
var prefixCount = 0
var initialPrefixLength = 20
fun part1(): Int {
println("Initial state: $initialState")
println("RULES: $rules")
var newString: String = ".".repeat(20) + initialState + ".".repeat(1000)
printGen(0, newString)
for (i in 1..gens) {
newString = computeNextGen(newString)
printGen(i, newString)
printPotSumByGen(i, newString)
}
return 0
}
private fun printPotSumByGen(gen: Int = gens, currentString: String) {
println("")
val negatives = currentString.take(initialPrefixLength + 2 * prefixCount).reversed()
val positives = currentString.drop(initialPrefixLength + 2 * prefixCount)
val positivesTotal = positives.mapIndexed { index, c -> if (c == '#') index else 0}.sum()
val negativesTotal = negatives.mapIndexed { index, c -> if (c == '#') index + 1 else 0}.sum()
println("Total of plant-containing pots after $gen generations is ${positivesTotal - negativesTotal}")
}
private fun printGen(gen: Int, genString: String) {
println("")
if (gen % 100 == 0) {
println("GEN: $gen")
}
print("GENERATION ${gen % 10} :")
print("-".repeat(10 - 2*prefixCount))
for (idx in genString.indices) {
if (idx < 90) continue
if (idx > 200) break
print(genString[idx])
if (idx == initialPrefixLength - 1) print("|")
}
}
private fun computeNextGen(current: String = initialState): String {
val prefix = if (current.take(2).contains("#")) {prefixCount++ ; ".."} else ""
val suffix = if (current.takeLast(2).contains("#")) ".." else ""
var nextString = ""
for ((idx, pot) in current.withIndex()) {
val view = when {
idx < 2 -> ".".repeat(2 - idx) + current.slice(0 .. idx + 2)
idx > current.lastIndex - 2 -> current.slice(idx -2 .. idx + (current.lastIndex - idx)) + ".".repeat(2 - (current.lastIndex - idx))
else -> current.slice(idx -2 .. idx + 2)
}
val nextPot = rules.getOrDefault(view, "ZZZZZ")
nextString += nextPot
}
nextString = prefix + nextString + suffix
return nextString.slice(0..nextString.lastIndex)
}
fun part2(): Int {
println("val at gen 200: ${valAtGen(200)}")
println("val at gen 202: ${valAtGen(202)}")
println("val at gen 50_000_000_000: ${valAtGen(50_000_000_000)}")
return 0
}
private fun valAtGen(gen: Long): Long {
val valAt200Generations = 9120
return (gen - 200) * 45 + valAt200Generations
}
}
| 0 | Kotlin | 0 | 0 | 14382957d43a250886e264a01dd199c5b3e60edb | 3,026 | AdventOfCode2018 | Apache License 2.0 |
kotlin/src/main/kotlin/adventofcode/day12/Day12_2.kt | thelastnode | 160,586,229 | false | null | package adventofcode.day12
import java.io.File
import java.lang.Exception
import java.lang.IllegalArgumentException
object Day12_2 {
data class Rule(val condition: String, val result: Char)
fun parse(lines: List<String>): Pair<String, List<Rule>> {
val initialState = lines[0].split(": ")[1].trim()
val rules = lines.drop(2)
.filter { it.trim().isNotEmpty() }
.map { it.split(" => ") }
.map { (condition, result) -> Rule(condition, result[0])}
return Pair(initialState, rules)
}
fun conditions(state: String): List<String> {
return ("..$state..").windowed(5)
}
private fun step(initialState: String, rules: List<Rule>): String {
val rulesMap = rules.groupBy { it.condition }
.mapValues { (_, v) ->
if (v.size != 1) {
throw IllegalArgumentException()
}
v[0]
}
return conditions(initialState)
.map {
if (it in rulesMap) {
rulesMap[it]!!.result
} else {
'.'
}
}
.joinToString("")
}
private fun score(state: String, padSize: Int): Int {
return state.withIndex().sumBy { (i, x) -> if (x == '.') 0 else i - padSize }
}
fun process(initialState: String, rules: List<Rule>): Long {
val pad = (0 until 10_000).map { '.' }.joinToString("")
var state = pad + initialState + pad
val scores = mutableListOf(score(state, pad.length))
val states = mutableListOf(state)
for (i in 0 until 1000) {
state = step(state, rules)
scores.add(score(state, pad.length))
states.add(state)
}
states.takeLast(10).forEach { println("${it.indexOf('#')}: ${it.count { it == '#' }}") }
// numbers taken from the above println
// (194 #'s, after a thousand iterations, starting at position 900, moving one position per iteration)
val start = 50_000_000_000L - 1_000L + 900L
return (start until start + 194).sum()
}
}
fun main(args: Array<String>) {
val lines = File("./day12-input").readLines()
val (initialState, rules) = Day12_2.parse(lines)
println(Day12_2.process(initialState, rules))
} | 0 | Kotlin | 0 | 0 | 8c9a3e5a9c8b9dd49eedf274075c28d1ebe9f6fa | 2,425 | adventofcode | MIT License |
src/com/mrxyx/algorithm/BinarySearchTree.kt | Mrxyx | 366,778,189 | false | null | package com.mrxyx.algorithm
import com.mrxyx.algorithm.model.TreeNode
import kotlin.math.max
/**
* 二叉搜索树
*/
class BinarySearchTree {
/**
* 寻找第 K 小的元素
* https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/
* point: BST(二叉搜索树)中序遍历就是升序排列
*/
fun kthSmallest(root: TreeNode, k: Int): Int {
traverse(root, k)
return res
}
//结果
private var res = 0
//当前节点排名
private var rank = 0
private fun traverse(root: TreeNode?, k: Int) {
if (root == null) return
traverse(root.left, k)
//中序遍历
rank++
//找到第k小元素
if (k == rank) {
res = root.`val`
return
}
traverse(root.right, k)
}
/**
* BST 转化累加树
* https://leetcode-cn.com/problems/convert-bst-to-greater-tree/
* https://leetcode-cn.com/problems/binary-search-tree-to-greater-sum-tree/
* point:BST(二叉搜索树)中序遍历就是升序排列 调整遍历顺序可降序排列
*/
fun convertBST(root: TreeNode): TreeNode {
traverse(root)
return root
}
// 累加和
private var sum = 0
private fun traverse(root: TreeNode?) {
if (root == null) return
//先遍历右子树 降序遍历
traverse(root.right)
//中序遍历
sum += root.`val`
root.`val` = sum
traverse(root.left)
}
/**
* 判断二叉搜索树是否合法
*/
fun isValidBST(root: TreeNode?): Boolean {
return dfs(root, null, null)
}
private fun dfs(root: TreeNode?, min: Int?, max: Int?): Boolean {
root ?: let {
return true
}
min?.let {
if (min >= root.`val`) return false
}
max?.let {
if (max <= root.`val`) return false
}
return dfs(root.left, min, root.`val`) && dfs(root.right, root.`val`, max)
}
/**
* 二叉搜索树中的搜索 递归解法
* https://leetcode-cn.com/problems/search-in-a-binary-search-tree
*/
fun isInBST(root: TreeNode?, target: Int): Boolean {
root ?: let {
return false
}
if (root.`val` == target) return true
if (root.`val` > target) return isInBST(root.left, target)
if (root.`val` < target) return isInBST(root.right, target)
return false
}
/**
* 二叉搜索树中的搜索 迭代解法
* https://leetcode-cn.com/problems/search-in-a-binary-search-tree
*/
fun isInBST2(root: TreeNode?, target: Int): Boolean {
var tmp: TreeNode? = root
while (tmp != null) {
if (tmp.`val` == target) return true
tmp = if (tmp.`val` > target) tmp.left else tmp.right
}
return false
}
/**
* 二叉搜索树插入 递归
* https://leetcode-cn.com/problems/insert-into-a-binary-search-tree
*/
fun insertBTS(root: TreeNode?, value: Int): TreeNode {
root ?: let {
return TreeNode(value)
}
if (root.`val` > value) root.left = insertBTS(root.left, value)
if (root.`val` < value) root.right = insertBTS(root.right, value)
return root
}
/**
* 二叉搜索树插入 迭代
* https://leetcode-cn.com/problems/insert-into-a-binary-search-tree
*/
fun insertBTS2(root: TreeNode?, value: Int): TreeNode? {
root ?: let {
return TreeNode(value)
}
var tmp = root
while (tmp != null) {
//如果大于
if (tmp.`val` > value) {
if (tmp.left != null) {
tmp = tmp.left
} else {
tmp.left = TreeNode(value)
break
}
} else if (tmp.`val` < value) {
if (tmp.right != null) {
tmp = tmp.right
} else {
tmp.right = TreeNode(value)
break
}
}
}
return root
}
/**
* 二叉搜索树 删除子节点
*/
fun deleteNode(root: TreeNode?, key: Int): TreeNode? {
root ?: let {
return null
}
when {
root.`val` == key -> {
//1、如果左右节点为空 则删除 一个非空 使用孩子节点替换自身
if (root.left == null) return root.right
if (root.right == null) return root.left
//2、寻找右节点最小子树 替换自身
val minNode = getMin(root.right)
root.`val` = minNode.`val`
//3、替换后 删除替换前的子节点
root.right = deleteNode(root.right, minNode.`val`)
}
root.`val` > key -> {
root.left = deleteNode(root.left, key)
}
root.`val` < key -> {
root.right = deleteNode(root.right, key)
}
}
return root
}
/**
* 获取当前树的最小子节点
*/
private fun getMin(right: TreeNode): TreeNode {
var tmp = right
while (tmp.left != null)
tmp = tmp.left
return tmp
}
/**
* 不同的二叉搜索树
* https://leetcode-cn.com/problems/unique-binary-search-trees/
* 迭代
*/
fun numTrees(n: Int): Int {
memo = Array(n + 1) { IntArray(n + 1) }
return count(1, n)
}
lateinit var memo: Array<IntArray>
private fun count(lo: Int, hi: Int): Int {
if (lo > hi) return 1
if (memo[lo][hi] != 0) return memo[lo][hi]
var res = 0
for (i in lo..hi) {
val left = count(lo, i - 1)
val right = count(i + 1, hi)
res += left + right
}
return res
}
/**
* 不同的二叉搜索树 II
* https://leetcode-cn.com/problems/unique-binary-search-trees-ii
*/
fun generateTrees(n: Int): List<TreeNode?> {
if (n == 0) return mutableListOf()
return generateHelper(1, n)
}
private fun generateHelper(lo: Int, hi: Int): List<TreeNode?> {
val res = mutableListOf<TreeNode?>()
if (lo > hi) {
res.add(null)
return res
}
for (i in lo..hi) {
// 左子树
val leftTrees = generateHelper(lo, i - 1)
// 右子树
val rightTrees = generateHelper(i + 1, hi)
// 遍历左右子树,和根节点i生成一棵BST
for (leftTree in leftTrees) {
for (rightTree in rightTrees) {
// 根节点
val root = TreeNode(i)
// 左子树
root.left = leftTree
// 右子树
root.right = rightTree
res.add(root)
}
}
}
return res
}
/**
* 二叉搜索子树的最大键值和
* https://leetcode-cn.com/problems/maximum-sum-bst-in-binary-tree/
*/
var maxSum = 0
fun maxSumBST(root: TreeNode?): Int {
maxSumTraverse(root)
return maxSum
}
/**
* res[0] 记录以 root 为根的二叉树是否是 BST,若为 1 则说明是 BST,若为 0 则说明不是 BST;
* res[1] 记录以 root 为根的二叉树所有节点中的最小值;
* res[2] 记录以 root 为根的二叉树所有节点中的最大值;
* res[3] 记录以 root 为根的二叉树所有节点值之和。
*/
private fun maxSumTraverse(root: TreeNode?): IntArray {
if (root == null) return intArrayOf(1, Int.MAX_VALUE, Int.MIN_VALUE, 0)
val left = maxSumTraverse(root.left)
val right = maxSumTraverse(root.right)
//后续遍历
val res = IntArray(4)
//以root为根的二叉树 是否是BST
if (left[0] == 1 && right[0] == 1 && root.`val` > left[2] && root.`val` < right[1]) {
res[0] = 1
res[1] = left[1].coerceAtMost(root.`val`)
res[2] = right[2].coerceAtLeast(root.`val`)
res[3] = left[3] + right[3] + root.`val`
maxSum = res[3].coerceAtLeast(maxSum)
} else {
res[0] = 0
}
return res
}
} | 0 | Kotlin | 0 | 0 | b81b357440e3458bd065017d17d6f69320b025bf | 8,471 | algorithm-test | The Unlicense |
plugin/src/main/kotlin/com/jraska/module/graph/DependencyGraph.kt | dafi | 230,582,038 | true | {"Kotlin": 20110} | package com.jraska.module.graph
class DependencyGraph() {
private val nodes = mutableMapOf<String, Node>()
fun findRoot(): Node {
require(nodes.isNotEmpty()) { "Dependency Tree is empty" }
val rootCandidates = nodes().toMutableSet()
nodes().flatMap { it.dependsOn }
.forEach { rootCandidates.remove(it) }
return rootCandidates.associateBy { heightOf(it.key) }
.maxBy { it.key }!!.value
}
fun nodes(): Collection<Node> = nodes.values
fun longestPath(): LongestPath {
return longestPath(findRoot().key)
}
fun longestPath(key: String): LongestPath {
val nodeNames = nodes.getValue(key)
.longestPath()
.map { it.key }
return LongestPath(nodeNames)
}
fun height(): Int {
return heightOf(findRoot().key)
}
fun heightOf(key: String): Int {
return nodes.getValue(key).height()
}
fun statistics(): GraphStatistics {
val height = height()
val edgesCount = countEdges()
return GraphStatistics(
modulesCount = nodes.size,
edgesCount = edgesCount,
height = height
)
}
fun subTree(key: String): DependencyGraph {
val dependencyTree = DependencyGraph()
addConnections(nodes.getValue(key), dependencyTree)
return dependencyTree
}
private fun addConnections(node: Node, into: DependencyGraph) {
node.dependsOn.forEach {
into.addEdge(node.key, it.key)
addConnections(it, into)
}
}
private fun addEdge(from: String, to: String) {
getOrCreate(from).dependsOn.add(getOrCreate(to))
}
private fun countEdges(): Int {
return nodes().flatMap { node -> node.dependsOn }.count()
}
private fun getOrCreate(key: String): Node {
return nodes[key] ?: Node(key).also { nodes[key] = it }
}
class Node(val key: String) {
val dependsOn = mutableSetOf<Node>()
private fun isLeaf() = dependsOn.isEmpty()
fun height(): Int {
if (isLeaf()) {
return 0
} else {
return 1 + dependsOn.map { it.height() }.max()!!
}
}
internal fun longestPath(): List<Node> {
if (isLeaf()) {
return listOf(this)
} else {
val path = mutableListOf<Node>(this)
val maxHeightNode = dependsOn.maxBy { it.height() }!!
path.addAll(maxHeightNode.longestPath())
return path
}
}
}
companion object {
fun create(dependencies: List<Pair<String, String>>): DependencyGraph {
val graph = DependencyGraph()
dependencies.forEach { graph.addEdge(it.first, it.second) }
return graph
}
}
}
| 0 | Kotlin | 0 | 0 | eee1159f56e7f8389f411b415b3a390c341e9dec | 2,572 | modules-graph-assert | Apache License 2.0 |
src/Day04.kt | achugr | 573,234,224 | false | null | fun main() {
class Interval(val left: Int, val right: Int) {
fun contain(interval: Interval): Boolean {
return (interval.left in left..right) and (interval.right in left..right)
}
fun overlap(interval: Interval): Boolean {
return (interval.left <= right) and (left <= interval.right)
}
}
fun readIntervals(input: List<String>) = input.map { line ->
line.split(",")
.map { range ->
range.split("-")
.map { it.toInt() }
.zipWithNext()
.map { Interval(it.first, it.second) }
.first()
}
.zipWithNext()
.first()
}
fun part1(input: List<String>): Int {
return readIntervals(input).count { it.first.contain(it.second) || it.second.contain(it.first) }
}
fun part2(input: List<String>): Int {
return readIntervals(input).count { it.first.overlap(it.second) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04")
println(part1(testInput))
println(part2(testInput))
}
| 0 | Kotlin | 0 | 0 | d91bda244d7025488bff9fc51ca2653eb6a467ee | 1,184 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/day07/Day07.kt | gr4cza | 572,863,297 | false | {"Kotlin": 93944} | package day07
import readInput
fun main() {
val dirs = """(\$ cd [a-zA-Z/.]+)""".toRegex()
val files = """(\d+ .*)""".toRegex()
fun parseDirContent(input: List<String>): MutableMap<String, Long> {
val dirContent = mutableMapOf<String, Long>()
val currentDirs = mutableListOf<String>()
input
.forEach {
if (dirs.matches(it)) {
val (_, _, dir) = it.split(" ")
if (dir == "..") {
currentDirs.removeLast()
} else {
currentDirs.add(currentDirs.joinToString("") + dir)
}
} else if (files.matches(it)) {
val dirValue = it.split(" ").first().toLong()
currentDirs.forEach { currentDir ->
dirContent[currentDir] = (dirContent[currentDir] ?: 0) + (dirValue)
}
}
}
return dirContent
}
fun part1(input: List<String>): Long {
val dirContent = parseDirContent(input)
return dirContent.map { (_, sizes) ->
sizes
}.filter {
it <= 100_000
}.sum()
}
fun part2(input: List<String>): Long {
val dirContent = parseDirContent(input)
val rootDir = dirContent.map { (_, sizes) -> sizes }.max()
return dirContent.map { (_, sizes) ->
sizes
}.filter {
(70_000_000 - (rootDir - it)) >= 30_000_000
}.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day07/Day07_test")
check(part1(testInput).toInt() == 95437)
val input = readInput("day07/Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ceca4b99e562b4d8d3179c0a4b3856800fc6fe27 | 1,818 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/com/hopkins/aoc/day8/main.kt | edenrox | 726,934,488 | false | {"Kotlin": 88215} | package com.hopkins.aoc.day8
import java.io.File
const val debug = true
const val part = 2
/** Advent of Code 2023: Day 8 */
fun main() {
val inputFile = File("input/input8.txt")
val lines: List<String> = inputFile.readLines()
val directions = lines[0]
val nodes: List<Node> = lines.drop(2).map { parseNode(it) }
if (debug) {
nodes.take(5).forEach { println("Node: $it") }
}
val nodeMap: Map<String, Node> = nodes.associateBy { it.name }
nodes.forEach { it.initialize(nodeMap) }
val starts: List<String> = getStarts(nodeMap.keys)
if (debug) {
println("Starts:")
println(" $starts")
}
var current: List<Node> = starts.map { nodeMap[it]!! }
var index = 0L
var cycles = starts.map { 0L }.toMutableList()
while (cycles.contains(0L)) {
val dirIndex = (index % directions.length).toInt()
val currentDirection = directions[dirIndex]
index++
current = current.map { node ->
if (currentDirection == 'L') {
node.leftNode
} else {
node.rightNode
}
}
if (debug && index < 10) {
println("index: $index, current: ${current.map { it.name }}")
}
current.mapIndexed { nodeIndex, node ->
if (cycles[nodeIndex] == 0L && node.name.endsWith("Z")) {
cycles[nodeIndex] = index
println("nodeIndex: $nodeIndex, index: $index")
}}
}
if (part == 1) {
println("Steps: ${cycles[0]}")
return
}
if (debug) {
println("Cycles: $cycles")
}
val lcm = cycles.fold(1L) { a, b -> lowestCommonMultiple(a, b) }
println("Lowest Common Multiple: $lcm")
}
fun lowestCommonMultiple(a: Long, b: Long): Long {
val larger = if (a > b) a else b
val maxLcm = a * b
var lcm = larger
while (lcm <= maxLcm) {
if (lcm % a == 0L && lcm % b == 0L) {
return lcm
}
lcm += larger
}
return maxLcm
}
fun parseNode(line: String): Node {
val name = line.substring(0, 3)
val left = line.substring(7, 10)
val right = line.substring(12, 15)
return Node(name, left, right)
}
fun getStarts(nodes: Collection<String>): List<String> {
if (part == 1) {
return listOf("AAA")
} else {
return nodes.filter { it.endsWith("A") }
}
}
fun isAtEnd(nodes: List<Node>): Boolean {
if (part == 1) {
return nodes[0].name == "ZZZ"
} else {
return nodes.all { it.name.endsWith("Z") }
}
}
class Node(val name: String, val left: String, val right: String) {
lateinit var leftNode: Node
lateinit var rightNode: Node
fun initialize(nodeMap: Map<String, Node>) {
leftNode = nodeMap[left]!!
rightNode = nodeMap[right]!!
}
override fun toString(): String = "Node {name=$name, left=$left, right=$right}"
} | 0 | Kotlin | 0 | 0 | 45dce3d76bf3bf140d7336c4767e74971e827c35 | 2,933 | aoc2023 | MIT License |
src/main/kotlin/graph/variation/ShortestPathInc.kt | yx-z | 106,589,674 | false | null | package graph.variation
import graph.core.Vertex
import graph.core.WeightedEdge
import graph.core.WeightedGraph
import graph.core.dijkstra
import util.INF
import util.Tuple2
import java.util.*
import kotlin.collections.set
// given a weighted graph G = (V, E) with each vertex having an int
// find a shortest path from s to t (s, t in V) : values of vertices included in
// this path is always increasing and report the total weight
// you may assume that each int is unique and distinct
// modify dijkstra algorithm
fun WeightedGraph<Int, Int>.shortestPathInc(s: Vertex<Int>,
// t: CVertex<Int>,
checkIdentity: Boolean = true)
: Map<Vertex<Int>, Int> {
val dist = HashMap<Vertex<Int>, Int>()
vertices.forEach {
dist[it] = INF
}
dist[s] = 0
val minHeap = PriorityQueue<Vertex<Int>>(Comparator { u, v -> dist[u]!! - dist[v]!! })
minHeap.add(s)
while (minHeap.isNotEmpty()) {
val v = minHeap.remove()
getEdgesOf(v, checkIdentity).forEach { (start, end, isDirected, weight) ->
val u = (if (isDirected || start == v) end else start)
if (dist[v]!! + weight!! < dist[u]!! && u.data > v.data) {
dist[u] = dist[v]!! + weight
minHeap.add(u)
}
}
}
// println(dist)
return dist
}
// modify graph : there exists an edge u -> v iff. u -> v in E,
// v.data > u.data, for all u, v in V
fun WeightedGraph<Int, Int>.shortestPathInc2(s: Vertex<Int>,
checkIdentity: Boolean = true)
: Tuple2<Map<Vertex<Int>, Int>, Map<Vertex<Int>, Vertex<Int>?>> {
val newEdges = weightedEdges.mapNotNull { (s, e, d, w) ->
if (d) {
if (e.data > s.data) {
WeightedEdge(s, e, true, w)
} else {
null
}
} else {
if (e.data > s.data) {
WeightedEdge(s, e, true, w)
} else {
WeightedEdge(e, s, true, w)
}
}
}
val newGraph = WeightedGraph(vertices, newEdges)
return newGraph.dijkstra(s, checkIdentity)
}
fun main(args: Array<String>) {
val vertices = setOf(
Vertex(5),
Vertex(6),
Vertex(7),
Vertex(4),
Vertex(9))
val edges = setOf(
WeightedEdge(Vertex(5), Vertex(6), weight = 1),
WeightedEdge(Vertex(5), Vertex(7), weight = 3),
WeightedEdge(Vertex(6), Vertex(7), weight = 1),
WeightedEdge(Vertex(6), Vertex(4), weight = 1),
WeightedEdge(Vertex(7), Vertex(4), weight = 5),
WeightedEdge(Vertex(7), Vertex(9), weight = 7),
WeightedEdge(Vertex(4), Vertex(9), weight = 2))
val graph = WeightedGraph(vertices, edges)
println(graph.shortestPathInc(Vertex(5), false))
println(graph.shortestPathInc2(Vertex(5), false))
} | 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 2,632 | AlgoKt | MIT License |
src/Day05.kt | AxelUser | 572,845,434 | false | {"Kotlin": 29744} | import java.util.Stack
private data class Command(val quantity: Int, val from: Int, val to: Int)
fun main() {
fun List<String>.parseStacks(): Array<Stack<Char>> {
val indices = Regex("\\d").findAll(last()).map { it.range.first }.toList()
val stacks = Array(indices.size) { Stack<Char>() }
for (i in lastIndex - 1 downTo 0) {
for (j in 0..indices.lastIndex) {
this[i][indices[j]].takeIf { it != ' ' }?.also { stacks[j].push(it) }
}
}
return stacks
}
fun List<String>.parseCommands(): Sequence<Command> {
val regex = Regex("\\d+")
return sequence {
for (s in this@parseCommands) {
yield(regex.findAll(s).map { it.value.toInt() }.toList().let { Command(it[0], it[1] - 1, it[2] - 1) })
}
}
}
fun List<String>.parseInput(): Pair<Array<Stack<Char>>, Sequence<Command>> {
val split = indexOf("")
return take(split).parseStacks() to drop(split + 1).parseCommands()
}
fun part1(input: List<String>): String {
val (stacks, commands) = input.parseInput()
for (cmd in commands) {
val sFrom = stacks[cmd.from]
val sTo = stacks[cmd.to]
repeat(cmd.quantity) {
sTo.push(sFrom.pop())
}
}
return stacks.map { it.peek() }.joinToString(separator = "")
}
fun part2(input: List<String>): String {
val (stacks, commands) = input.parseInput()
for (cmd in commands) {
val sFrom = stacks[cmd.from]
val sTo = stacks[cmd.to]
with(Stack<Char>()) {
repeat(cmd.quantity) {
push(sFrom.pop())
}
while (isNotEmpty()) {
sTo.push(pop())
}
}
}
return stacks.map { it.peek() }.joinToString(separator = "")
}
var input = readInput("Day05_test")
check(part1(input) == "CMZ")
check(part2(input) == "MCD")
input = readInput("Day05")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 1 | 042e559f80b33694afba08b8de320a7072e18c4e | 2,155 | aoc-2022 | Apache License 2.0 |
2021/kotlin/src/main/kotlin/com/pietromaggi/aoc2021/day12/Day12.kt | pfmaggi | 438,378,048 | false | {"Kotlin": 113883, "Zig": 18220, "C": 7779, "Go": 4059, "CMake": 386, "Awk": 184} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pietromaggi.aoc2021.day12
import com.pietromaggi.aoc2021.readInput
fun buildPaths(connections: Map<String, MutableList<String>>, path: List<String>, validPaths: MutableSet<List<String>>, canVisitTwice: String) {
val currentCave = path.last()
if (currentCave == "end") {
validPaths += path
return
}
val nextCavesToVisit = connections.getValue(currentCave).filter { cave ->
(cave.isLargeCave) or
(cave !in (path)) or
((cave == canVisitTwice) and (path.count { it == canVisitTwice } <= 1))
}
for (nextCave in nextCavesToVisit) {
buildPaths(connections, path + nextCave, validPaths, canVisitTwice)
}
}
fun part1(connections: Map<String, MutableList<String>>): Int {
val results = mutableSetOf<List<String>>()
buildPaths(connections, listOf("start"), results, "")
return results.count()
}
fun part2(connections: Map<String, MutableList<String>>): Int {
val results = mutableSetOf<List<String>>()
for (smallCave in connections.keys.filter { cave -> (!cave.isLargeCave) && cave !in listOf("start", "end") }) {
buildPaths(connections, listOf("start"), results, smallCave)
}
return results.count()
}
fun buildConnections(fileName: String) : Map<String, MutableList<String>> {
return buildMap {
readInput(fileName).forEach { line ->
val (cave1, cave2) = line.split("-")
this.getOrPut(cave1) { mutableListOf() }.add(cave2)
this.getOrPut(cave2) { mutableListOf() }.add(cave1)
}
}
}
val String.isLargeCave get() = this != lowercase()
fun main() {
val connections = buildConnections("Day12")
println(part1(connections))
println(part2(connections))
}
| 0 | Kotlin | 0 | 0 | 7c4946b6a161fb08a02e10e99055a7168a3a795e | 2,358 | AdventOfCode | Apache License 2.0 |
src/Day07/Day07.kt | Nathan-Molby | 572,771,729 | false | {"Kotlin": 95872, "Python": 13537, "Java": 3671} | package Day07
import readInput
class Node(val name: String, val parentNode: Node?, val size: Int?, val isDirectory: Boolean) {
var childNodes = mutableListOf<Node>()
fun addNode(node: Node) {
childNodes.add(node)
}
fun getSize(): Int {
if (size != null) {
return size
} else {
return childNodes.map{ it.getSize() }.sum()
}
}
}
class CommandParser(val commands: List<String>) {
var headNode: Node = Node("/", null, null, true)
var parentNode: Node? = null
var nodes = mutableListOf<Node>(headNode)
fun parseCommands() {
for(command in commands) {
parseCommand(command)
}
}
private fun parseCommand(command: String) {
if (command[0] == '$') {
parseExecutedCommands(command.substring(2))
} else {
parseFileOrDir(command)
}
}
private fun parseExecutedCommands(command: String) {
val commandElements = command.split(" ")
when(commandElements[0]) {
"ls" -> return
"cd" -> processCd(commandElements[1])
}
}
private fun processCd(newDirectory: String) {
when(newDirectory) {
".." -> parentNode = parentNode?.parentNode
"/" -> parentNode = headNode
else -> parentNode = parentNode?.childNodes?.first { it.name == newDirectory && it.isDirectory }
}
}
private fun parseFileOrDir(fileLine: String) {
val lineElements = fileLine.split(" ")
when(lineElements[0]) {
"dir" -> addDirectory(lineElements[1])
else -> addFile(lineElements[0], lineElements[1])
}
}
private fun addDirectory(dirName: String) {
val newNode = Node(dirName, parentNode, null, true)
addNode(newNode)
}
private fun addFile(fileSize: String, fileName: String) {
val newNode = Node(fileName, parentNode, fileSize.toInt(), false)
addNode(newNode)
}
private fun addNode(node: Node) {
nodes.add(node)
parentNode?.addNode(node)
}
}
fun main() {
fun part1(input: List<String>): Int {
val parser = CommandParser(input)
parser.parseCommands()
return parser.nodes.filter { it.isDirectory && it.getSize() <= 100000 }.sumOf { it.getSize() }
}
fun part2(input: List<String>): Int {
val parser = CommandParser(input)
parser.parseCommands()
val sizeRequired = 30000000 - (70000000 - parser.headNode.getSize())
val directoriesOfRequisiteSize = parser.nodes.filter { it.isDirectory && it.getSize() > sizeRequired }.sortedBy { it.getSize() }
return directoriesOfRequisiteSize[0].getSize()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07","Day07_test")
println(part1(testInput))
check(part1(testInput) == 95437)
println(part2(testInput))
check(part2(testInput) == 24933642)
val input = readInput("Day07","Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 750bde9b51b425cda232d99d11ce3d6a9dd8f801 | 3,115 | advent-of-code-2022 | Apache License 2.0 |
src/day9.kt | miiila | 725,271,087 | false | {"Kotlin": 77215} | import java.io.File
import kotlin.system.exitProcess
import kotlin.time.measureTime
private const val DAY = 9
fun main() {
if (!File("./day${DAY}_input").exists()) {
downloadInput(DAY)
println("Input downloaded")
exitProcess(0)
}
val transformer = { x: String -> x.split(" ").map(String::toLong) }
val input = loadInput(DAY, false, transformer)
println(measureTime { println(solvePart1(input)) })
println(measureTime { println(solvePart1Memo(input)) })
println(measureTime { println(solvePart1Rec(input)) })
println(measureTime { println(solvePart2(input)) })
}
// Part 1
private fun solvePart1(input: List<List<Long>>): Long {
val res = input.map { solveRow(it) { chunks: List<Long>, res: Long -> res + chunks.last() } }
return res.sum()
}
// Part 2
private fun solvePart2(input: List<List<Long>>): Long {
val res = input.map { solveRow(it) { chunks: List<Long>, res: Long -> chunks.first() - res } }
return res.sum()
}
fun solveRow(input: List<Long>, result: (chunks: List<Long>, current: Long) -> Long): Long {
var res: Long = 0
var found = false
// Search bottom-up
for (chunkSize in input.count() downTo 1) {
val chunks =
input.windowed(chunkSize)
.map { it.zip(getPascalCoef(it.count() - 1)).sumOf { it.first * it.second } }
// Find first row, which is not all zeros
found = found || chunks.any { it != 0.toLong() }
// Count results based on provided function - adding last values for part one, subtracting firsts for part two
if (found) {
res = result(chunks, res)
}
}
return res
}
// Returns coefficient from Pascal's triangle for a particular row, eg. 1-5-10-10-5-1 for 5th row
// Can be memoized
fun getPascalCoef(row: Int): List<Long> {
// Odd row (zero indexed) needs to repeat middle
val isEvenRow = row % 2 == 0
// Odd rows need to repeat middle item
val range = if (isEvenRow) (0 until row / 2) else (0..row / 2)
// And because we are substracting, we need to have proper sign
val sign = if (isEvenRow) 1 else -1
return (range + (row / 2 downTo 0)).map(Int::toLong).mapIndexed { i, it ->
val coef = computeCombinationNumber(row.toLong(), it)
coef * sign * if (i % 2 == 0) 1 else -1
}
}
// Computes combination number C(n,k) = n! / k!(n-k)! = (n * n-1 * n-2 * .. n-k) / k!
fun computeCombinationNumber(n: Long, k: Long): Long {
return if (k == 0.toLong())
1
else
(n downTo (n - k + 1)).reduce(Long::times) / (1..k).reduce(Long::times)
}
// EXPERIMENTS
private fun solvePart1Rec(input: List<List<Long>>): Long {
val res = input.map { solveRowRec(it) }
return res.sum()
}
private fun solvePart1Memo(input: List<List<Long>>): Long {
val mem = Memoized()
val res = input.map { solveRowMemo(it, { chunks: List<Long>, res: Long -> res + chunks.last() }, mem) }
return res.sum()
}
fun solveRowRec(input: List<Long>): Long {
var stop = false
var inp = input
val lasts = mutableListOf<Long>()
while (!stop) {
lasts.add(inp.last())
inp = inp.windowed(2).map { it[1] - it[0] }
stop = inp.all { it == 0.toLong() }
}
return lasts.sum()
}
fun solveRowMemo(input: List<Long>, result: (chunks: List<Long>, current: Long) -> Long, mem: Memoized): Long {
var res: Long = 0
var found = false
for (chunkSize in input.count() downTo 1) {
val chunks =
input.windowed(chunkSize)
.map { it.zip(mem.getPascalCoef(it.count() - 1)).sumOf { it.first * it.second } }
found = found || chunks.any { it != 0.toLong() }
if (found) {
res = result(chunks, res)
}
}
return res
}
class Memoized {
private val coefs = mutableMapOf<Int, List<Long>>()
private val combinationNumbers = mutableMapOf<Pair<Long, Long>, Long>()
private fun getCombinationNumber(n: Long, k: Long): Long {
val p = Pair(n, k)
if (p !in combinationNumbers) {
combinationNumbers[p] = computeCombinationNumber(n, k)
}
return combinationNumbers[p]!!
}
fun getPascalCoef(row: Int): List<Long> {
if (row !in coefs) {
coefs[row] = getPascalCoefMemo(row)
}
return coefs[row]!!
}
private fun getPascalCoefMemo(row: Int): List<Long> {
// Odd row (zero indexed) needs to repeat middle
val isEvenRow = row % 2 == 0
// Odd rows need to repeat middle item
val range = if (isEvenRow) (0 until row / 2) else (0..row / 2)
// And because we are substracting, we need to have proper sign
val sign = if (isEvenRow) 1 else -1
return (range + (row / 2 downTo 0)).map(Int::toLong).mapIndexed { i, it ->
val coef = getCombinationNumber(row.toLong(), it)
coef * sign * if (i % 2 == 0) 1 else -1
}
}
} | 0 | Kotlin | 0 | 1 | 1cd45c2ce0822e60982c2c71cb4d8c75e37364a1 | 4,966 | aoc2023 | MIT License |
src/Day01.kt | emersonf | 572,870,317 | false | {"Kotlin": 17689} |
fun main() {
fun part1(input: List<String>): Int {
var maxTotal = 0
var currentTotal = 0
for (calories in input) {
if (calories.isBlank()) {
if (currentTotal > maxTotal) {
maxTotal = currentTotal
}
currentTotal = 0
} else {
currentTotal += calories.toInt()
}
}
return maxTotal
}
data class ElfCalories(val elfId: Int, val calories: Int)
fun part2(input: List<String>): Int {
var elfId = 1
return input
.map { calories ->
if (calories.isBlank()) {
elfId++
ElfCalories(-1,0)
}
else {
ElfCalories(elfId, calories.toInt())
}
}
.filter { it.elfId > 0 }
.groupingBy { it.elfId }
.aggregate { _, accumulator: Int?, element, _ ->
if (accumulator == null) {
element.calories
}
else accumulator + element.calories
}
.entries
.sortedByDescending { it.value }
.take(3)
.sumOf { it.value }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24_000)
check(part2(testInput) == 45_000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 0e97351ec1954364648ec74c557e18ccce058ae6 | 1,576 | advent-of-code-2022-kotlin | Apache License 2.0 |
app/src/main/kotlin/day15/Day15.kt | KingOfDog | 433,706,881 | false | {"Kotlin": 76907} | package day15
import common.InputRepo
import common.readSessionCookie
import common.solve
import kotlin.math.pow
import kotlin.math.roundToInt
import kotlin.math.sqrt
fun main(args: Array<String>) {
val day = 15
val input = InputRepo(args.readSessionCookie()).get(day = day)
solve(day, input, ::solveDay15Part1, ::solveDay15Part2)
}
fun solveDay15Part1(input: List<String>): Int {
val grid = parseDigits(input).convertToNodes()
val start = grid[0][0]
val end = grid.last().last()
val pathfinder = DontKnowIfIRememberThisAlgorithm(grid, start, end)
val path = pathfinder.findPath()
return calculateTotalRisk(path)
}
fun solveDay15Part2(input: List<String>): Int {
val grid = parseDigits(input).repeat(5).convertToNodes()
val start = grid[0][0]
val end = grid.last().last()
val pathfinder = DontKnowIfIRememberThisAlgorithm(grid, start, end)
val path = pathfinder.findPath()
return calculateTotalRisk(path)
}
private fun calculateTotalRisk(path: List<Node>) =
path.subList(1, path.size).sumOf { it.risk }
private fun List<List<Int>>.repeat(count: Int): List<List<Int>> {
val horizontallyRepeated = map { line -> List(count) { line.increaseAllBy(it) }.flatten() }
return List(count) { horizontallyRepeated.map { line -> line.increaseAllBy(it) } }.flatten()
}
private fun List<Int>.increaseAllBy(
increase: Int,
maxValue: Int = 9
) = map { it + increase }.map { if (it > maxValue) it - maxValue else it }
private fun parseDigits(input: List<String>): List<List<Int>> =
input.map { line -> line.toCharArray().map { it.digitToInt() } }
private fun List<List<Int>>.convertToNodes(): Array<Array<Node>> =
mapIndexed { y, line -> line.mapIndexed { x, risk -> Node(x, y, risk) }.toTypedArray() }
.toTypedArray()
class DontKnowIfIRememberThisAlgorithm(
private val grid: Array<Array<Node>>,
start: Node,
private val end: Node,
) {
private val open = mutableSetOf<Node>(start)
private val closed = mutableSetOf<Node>()
private val width = grid[0].size
private val height = grid.size
fun findPath(): List<Node> {
while (open.isNotEmpty()) {
val lowestCostNode = open.minByOrNull { it.totalCost() }!!
open.removeAll { it.x == lowestCostNode.x && it.y == lowestCostNode.y }
closed.add(lowestCostNode)
if (lowestCostNode == end) {
return lowestCostNode.buildPath()
}
val neighbors = lowestCostNode.getNeighbors().filterNot { closed.contains(it) }
val openNeighbors = neighbors.filter { open.contains(it) }
neighbors.filterNot { open.contains(it) }.forEach { node ->
node.recalculateCostWithParent(lowestCostNode)
open.add(node)
}
openNeighbors.forEach { node ->
val newCost = lowestCostNode.distanceToStart + lowestCostNode.risk + node.heuristicToEnd() + node.risk
if (newCost < node.totalCost()) {
node.recalculateCostWithParent(lowestCostNode)
}
}
}
return emptyList()
}
private fun Node.recalculateCostWithParent(newParent: Node) {
parent = newParent
distanceToStart = newParent.distanceToStart + newParent.risk
}
private fun Node.totalCost(): Int {
return distanceToStart + heuristicToEnd() + risk
}
private fun Node.heuristicToEnd(): Int {
return sqrt((x - end.x).toDouble().pow(2.0) + (y - end.y.toDouble()).pow(2.0)).roundToInt()
}
private fun Node.getNeighbors(): List<Node> {
return listOf(0 to 1, 0 to -1, -1 to 0, 1 to 0)
.map { x + it.first to y + it.second }
.filterNot { it.first < 0 || it.second < 0 || it.first >= width || it.second >= height }
.map { grid[it.second][it.first] }
}
private fun Node.buildPath(): List<Node> {
return (parent?.buildPath() ?: emptyList()) + this
}
}
data class Node(val x: Int, val y: Int, val risk: Int, var distanceToStart: Int = 0, var parent: Node? = null)
| 0 | Kotlin | 0 | 0 | 576e5599ada224e5cf21ccf20757673ca6f8310a | 4,146 | advent-of-code-kt | Apache License 2.0 |
src/poyea/aoc/mmxxii/day02/Day02.kt | poyea | 572,895,010 | false | {"Kotlin": 68491} | package poyea.aoc.mmxxii.day02
import poyea.aoc.utils.readInput
import kotlin.Int.Companion.MIN_VALUE
fun part1(input: String): Int {
return input.split("\n").map { it.split(" ") }.sumOf { info ->
when (info[1]) {
"X" -> {
when (info[0]) {
"A" -> 3 + 1
"B" -> 0 + 1
"C" -> 6 + 1
else -> MIN_VALUE
}
}
"Y" -> {
when (info[0]) {
"A" -> 6 + 2
"B" -> 3 + 2
"C" -> 0 + 2
else -> MIN_VALUE
}
}
"Z" -> {
when (info[0]) {
"A" -> 0 + 3
"B" -> 6 + 3
"C" -> 3 + 3
else -> MIN_VALUE
}
}
else -> MIN_VALUE
}
}
}
fun part2(input: String): Int {
return input.split("\n").map { it.split(" ") }.sumOf { info ->
when (info[1]) {
"X" -> {
when (info[0]) {
"A" -> 3 + 0
"B" -> 1 + 0
"C" -> 2 + 0
else -> MIN_VALUE
}
}
"Y" -> {
when (info[0]) {
"A" -> 1 + 3
"B" -> 2 + 3
"C" -> 3 + 3
else -> MIN_VALUE
}
}
"Z" -> {
when (info[0]) {
"A" -> 2 + 6
"B" -> 3 + 6
"C" -> 1 + 6
else -> MIN_VALUE
}
}
else -> MIN_VALUE
}
}
}
fun main() {
println(part1(readInput("Day02")))
println(part2(readInput("Day02")))
}
| 0 | Kotlin | 0 | 1 | fd3c96e99e3e786d358d807368c2a4a6085edb2e | 1,887 | aoc-mmxxii | MIT License |
src/Day04.kt | dizney | 572,581,781 | false | {"Kotlin": 105380} | object Day04 {
const val EXPECTED_PART1_CHECK_ANSWER = 2
const val EXPECTED_PART2_CHECK_ANSWER = 4
}
fun main() {
fun String.parseToIntRangePerElf(): Pair<IntRange, IntRange> =
this
.split(",")
.map { it.split("-") }
.map { (it[0].toInt())..(it[1].toInt()) }
.let { it[0] to it[1] }
fun part1(input: List<String>): Int =
input
.map { it.parseToIntRangePerElf() }
.count { it.first.minus(it.second).isEmpty() || it.second.minus(it.first).isEmpty() }
fun part2(input: List<String>): Int =
input
.map { it.parseToIntRangePerElf() }
.count { (firstElfSections, secondElfSections) ->
firstElfSections.any { secondElfSections.contains(it) } || firstElfSections.any {
secondElfSections.contains(
it
)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == Day04.EXPECTED_PART1_CHECK_ANSWER) { "Part 1 failed" }
check(part2(testInput) == Day04.EXPECTED_PART2_CHECK_ANSWER) { "Part 2 failed" }
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f684a4e78adf77514717d64b2a0e22e9bea56b98 | 1,328 | aoc-2022-in-kotlin | Apache License 2.0 |
year2023/src/cz/veleto/aoc/year2023/Day07.kt | haluzpav | 573,073,312 | false | {"Kotlin": 164348} | package cz.veleto.aoc.year2023
import cz.veleto.aoc.core.AocDay
import kotlin.math.pow
class Day07(config: Config) : AocDay(config) {
@Suppress("SpellCheckingInspection")
private val cards = "23456789TJQKA"
@Suppress("SpellCheckingInspection")
private val jokerCards = "J23456789TQKA"
private val base = cards.length
private val maxHandCardStrength = 1_000_000 // more like 300k but whatever, 1M is readable
override fun part1(): String = solve(joker = false)
override fun part2(): String = solve(joker = true)
private fun solve(joker: Boolean): String {
val sortedHands = input
.parse()
.map { (hand, bid) -> Triple(hand, hand.getHandTotalStrength(joker = joker), bid) }
.onEach { (hand, strength, _) -> if (config.log) println("hand total strength of '$hand': $strength") }
.toList()
.sortedByDescending { (_, strength, _) -> strength }
return sortedHands
.mapIndexed { index, (hand, _, bid) -> Triple(hand, sortedHands.size - index, bid) }
.sumOf { (_, rank, bid) -> bid * rank }
.toString()
}
private fun Sequence<String>.parse(): Sequence<Pair<String, Int>> = map { line ->
line.split(' ').let { (hand, bid) -> hand.also { check(it.length == 5) } to bid.toInt() }
}
private fun String.getHandType(joker: Boolean): Int {
val allCardCounts = groupBy { it }.mapValues { (_, chars) -> chars.size }
check(allCardCounts.map { (_, count) -> count }.sum() == 5)
val jokers = if (joker) allCardCounts['J'] ?: 0 else 0
val cardCounts = allCardCounts
.filter { (char, _) -> char != 'J' || !joker }
.values
.sortedDescending()
val firstCardWithJokers = cardCounts.getOrElse(0) { 0 } + jokers
fun isPlainThreePair(): Boolean = cardCounts[0] == 3 && cardCounts[1] == 2
fun isPlainTwoPair(): Boolean = cardCounts[0] == 2 && cardCounts[1] == 2
return when {
firstCardWithJokers == 5 -> 7
firstCardWithJokers == 4 -> 6
isPlainThreePair() || isPlainTwoPair() && jokers == 1 -> 5
firstCardWithJokers == 3 -> 4
isPlainTwoPair() -> 3
firstCardWithJokers == 2 -> 2
cardCounts.all { it == 1 } -> 1.also { check(jokers == 0) }
else -> error("unknown hand type: '$this'")
}
}
// converting to base 13
private fun String.getHandCardStrength(cards: String): Int = reversed()
.map(cards::indexOf)
.mapIndexed { index, value -> value * base.toDouble().pow(index).toInt() }
.sum()
// first digit of output is type, the remaining 6 is strength of cards
private fun String.getHandTotalStrength(joker: Boolean): Int =
getHandType(joker) * maxHandCardStrength + getHandCardStrength(if (joker) jokerCards else cards)
}
| 0 | Kotlin | 0 | 1 | 32003edb726f7736f881edc263a85a404be6a5f0 | 2,929 | advent-of-pavel | Apache License 2.0 |
2022/Day18/problems.kt | moozzyk | 317,429,068 | false | {"Rust": 102403, "C++": 88189, "Python": 75787, "Kotlin": 72672, "OCaml": 60373, "Haskell": 53307, "JavaScript": 51984, "Go": 49768, "Scala": 46794} | import java.io.File
import kotlin.math.*
typealias Position = Triple<Int, Int, Int>
fun main(args: Array<String>) {
val lines = File(args[0]).readLines()
val cubes =
lines.map { it.split(",").map { it.toInt() }.toList() }.map {
Position(it[0], it[1], it[2])
}
println(problem1(cubes))
println(problem2(cubes))
}
fun problem1(cubes: List<Position>): Int {
var seen = mutableSetOf<Position>()
var result = 0
for (c in cubes) {
val numNeighbors = generateNeighbors(c).map { seen.contains(it) }.filter { it }.count()
seen.add(c)
result -= numNeighbors
result += 6 - numNeighbors
}
return result
}
fun problem2(cubes: List<Position>): Int {
var seen = cubes.toMutableSet()
seen.add(Position(0, 0, 0))
fill(Position(0, 0, 0), seen)
var subtract = 0
for (x in 0..24) {
for (y in 0..24) {
for (z in 0..24) {
val cube = Position(x, y, z)
if (!seen.contains(cube)) {
subtract +=
generateNeighbors(cube).map { seen.contains(it) }.filter { it }.count()
}
}
}
}
return problem1(cubes) - subtract
}
fun fill(cube: Position, seen: MutableSet<Position>) {
var q = ArrayDeque<Position>()
q.add(cube)
while (!q.isEmpty()) {
val c = q.removeFirst()
for (n in generateNeighbors(c)) {
val (x, y, z) = n
if (x < 0 || y < 0 || z < 0 || x > 24 || y > 24 || z > 24) {
continue
}
if (!seen.contains(n)) {
seen.add(n)
q.addLast(n)
}
}
}
}
fun generateNeighbors(cube: Position): List<Position> {
val (x, y, z) = cube
return listOf(
Position(x - 1, y, z),
Position(x + 1, y, z),
Position(x, y - 1, z),
Position(x, y + 1, z),
Position(x, y, z - 1),
Position(x, y, z + 1)
)
}
| 0 | Rust | 0 | 0 | c265f4c0bddb0357fe90b6a9e6abdc3bee59f585 | 2,056 | AdventOfCode | MIT License |
src/main/kotlin/hexogen/algorithms/Graph.kt | MiloszKrajewski | 72,345,942 | false | null | package hexogen.algorithms
import hexogen.collections.DisjointSet
interface Edge<N> {
val A: N
val B: N
}
class Hybrid<N, E : Edge<N>>(edges: Sequence<E>, threshold: Double, rng: () -> Double) {
private val rng = rng
private val threshold = threshold
private val map = mapEdges(edges)
private val kruskal = Kruskal(edges)
private val trailblazer = Trailblazer({ node: N -> getEdges(node) })
private fun mapEdges(edges: Sequence<E>): Map<N, List<E>> {
val result = mutableMapOf<N, MutableList<E>>()
fun link(node: N, edge: E) = result.getOrPut(node, { mutableListOf() }).add(edge)
for (edge in edges) {
link(edge.A, edge)
link(edge.B, edge)
}
return result
}
private fun getEdges(node: N): Sequence<E> =
map[node]?.asSequence() ?: emptySequence<E>()
private fun nextTrailblazer(): E? =
(if (rng() < threshold) null else trailblazer.next())?.apply {
kruskal.merge(A, B)
}
private fun nextKruskal(): E? =
kruskal.next()?.apply {
trailblazer.visit(A)
trailblazer.visit(B)
trailblazer.reset(if (rng() < 0.5) A else B)
}
fun next(): E? = nextTrailblazer() ?: nextKruskal()
}
class Trailblazer<N, E : Edge<N>>(edges: (N) -> Sequence<E>) {
private val edges = edges
private val visited = mutableSetOf<N>()
private var head: N? = null
private fun opposite(node: N, edge: E): N? =
when (node) {
edge.A -> edge.B
edge.B -> edge.A
else -> null
}
fun visit(node: N, reset: Boolean = false): Boolean {
val added = visited.add(node)
if (reset && added) head = node
return added
}
fun next(): E? {
val current = head ?: return null
return edges(current).firstOrNull { visit(opposite(current, it)!!, true) }
}
fun reset(node: N) {
head = node
}
}
class Kruskal<N, E : Edge<N>>(edges: Sequence<E>) {
val iterator = edges.iterator()
val sets = DisjointSet<N>()
fun merge(a: N, b: N) = sets.merge(a, b)
fun next(): E? {
if (!iterator.hasNext())
return null
val edge = iterator.next()
if (sets.test(edge.A, edge.B))
return next()
sets.merge(edge.A, edge.B)
return edge
}
}
| 0 | Kotlin | 0 | 0 | ea8437f50f0a4512b95404fa2d0780fd2ff1b924 | 2,455 | kotlinjs-hexagen-hybrid | MIT License |
src/main/kotlin/g1501_1600/s1584_min_cost_to_connect_all_points/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1501_1600.s1584_min_cost_to_connect_all_points
// #Medium #Array #Union_Find #Minimum_Spanning_Tree
// #2023_06_14_Time_331_ms_(95.12%)_Space_44.5_MB_(95.12%)
import java.util.PriorityQueue
class Solution {
fun minCostConnectPoints(points: Array<IntArray>): Int {
val v = points.size
if (v == 2) {
return getDistance(points[0], points[1])
}
val pq = PriorityQueue(v, Pair())
val mst = BooleanArray(v)
val dist = IntArray(v)
val parent = IntArray(v)
dist.fill(1000000)
parent.fill(-1)
dist[0] = 0
parent[0] = 0
for (i in 0 until v) {
pq.add(Pair(dist[i], i))
}
constructMST(parent, points, mst, pq, dist)
var cost = 0
for (i in 1 until parent.size) {
cost += getDistance(points[parent[i]], points[i])
}
return cost
}
private fun constructMST(
parent: IntArray,
points: Array<IntArray>,
mst: BooleanArray,
pq: PriorityQueue<Pair>,
dist: IntArray
) {
if (!containsFalse(mst)) {
return
}
val newPair = pq.poll()
val pointIndex: Int = newPair.v
mst[pointIndex] = true
for (i in parent.indices) {
val d = getDistance(points[pointIndex], points[i])
if (!mst[i] && d < dist[i]) {
dist[i] = d
pq.add(Pair(dist[i], i))
parent[i] = pointIndex
}
}
constructMST(parent, points, mst, pq, dist)
}
private fun containsFalse(mst: BooleanArray): Boolean {
for (b in mst) {
if (!b) {
return true
}
}
return false
}
private fun getDistance(p1: IntArray, p2: IntArray): Int {
return Math.abs(p1[0] - p2[0]) + Math.abs(p1[1] - p2[1])
}
class Pair : Comparator<Pair> {
var dis = 0
var v = 0
constructor()
constructor(dis: Int, v: Int) {
this.dis = dis
this.v = v
}
override fun compare(p1: Pair, p2: Pair): Int {
return p1.dis - p2.dis
}
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,225 | LeetCode-in-Kotlin | MIT License |
src/Day05.kt | mkulak | 573,910,880 | false | {"Kotlin": 14860} | fun main() {
val regex = "move ([0-9]+) from ([0-9]+) to ([0-9]+)".toRegex()
fun part1(input: List<String>): String {
val part1 = input.takeWhile { it.startsWith("[") || it.startsWith(" ") }
val part2 = input.drop(part1.size + 2)
val stacks = List((input[part1.size].length + 2) / 4) { ArrayDeque<Char>() }
part1.forEach { line ->
line.windowed(4, 4, partialWindows = true).forEachIndexed { index, str ->
if (str[1] != ' ') stacks[index] += str[1]
}
}
part2.forEach { line ->
val (count, from, to) = regex.matchEntire(line)!!.groupValues.drop(1).map { it.toInt() }
repeat(count) {
val move = stacks[from - 1].removeFirst()
stacks[to - 1].addFirst(move)
}
}
return stacks.joinToString("") { it.first().toString() }
}
fun part2(input: List<String>): String {
val part1 = input.takeWhile { it.startsWith("[") || it.startsWith(" ") }
val part2 = input.drop(part1.size + 2)
val stacks = List((input[part1.size].length + 2) / 4) { ArrayDeque<Char>() }
part1.forEach { line ->
line.windowed(4, 4, partialWindows = true).forEachIndexed { index, str ->
if (str[1] != ' ') stacks[index] += str[1]
}
}
val temp = ArrayDeque<Char>()
part2.forEach { line ->
val (count, from, to) = regex.matchEntire(line)!!.groupValues.drop(1).map { it.toInt() }
repeat(count) {
val move = stacks[from - 1].removeFirst()
temp.addFirst(move)
}
repeat(count) {
stacks[to - 1].addFirst(temp.removeFirst())
}
}
return stacks.joinToString("") { it.first().toString() }
}
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 3b4e9b32df24d8b379c60ddc3c007d4be3f17d28 | 1,946 | AdventOfKo2022 | Apache License 2.0 |
src/shreckye/coursera/algorithms/Course 2 Programming Assignment #3.kts | ShreckYe | 205,871,625 | false | {"Kotlin": 72136} | package shreckye.coursera.algorithms
import java.io.File
import java.util.*
import kotlin.random.Random
import kotlin.test.assertEquals
val NUM_INTEGERS = 10000
val filename = args[0]
val integers = File(filename).useLines { it.map(String::toInt).toIntArray(NUM_INTEGERS) }
fun medianSum(integers: IntArray): Int {
val less = PriorityQueue<Int>(integers.size, compareByDescending { it })
val greater = PriorityQueue<Int>(integers.size)
var medianSum = 0
for (i in 0 until integers.size) {
val integer = integers[i]
val median: Int
if (less.isNotEmpty() && integer < less.peek()) {
median = less.poll()
less.offer(integer)
} else if (greater.isNotEmpty() && integer > greater.peek()) {
median = greater.poll()
greater.offer(integer)
} else
median = integer
//println("i = $i, median = $median")
medianSum += median
if (i % 2 == 0)
greater.offer(median)
else
less.offer(median)
}
return medianSum
}
println(medianSum(integers) % 10000)
// Test cases
for (n in 1 until 1000) {
val actual = medianSum(IntArray(n) { it })
val n2 = n / 2
var expected = n2 * (n2 - 1)
if (n % 2 == 1) expected += n2
assertEquals(expected, actual, "n = $n")
}
repeat(10) {
val integers = IntArray(1000) { Random.nextInt(0, 1000) }
val actual = medianSum(integers)
val expected = (1..integers.size).sumBy { integers.take(it).sorted()[(it - 1) / 2] }
assert(actual == expected) { "integers = ${integers.contentToString()}, actual = $actual, expected = $expected" }
}
| 0 | Kotlin | 1 | 2 | 1746af789d016a26f3442f9bf47dc5ab10f49611 | 1,668 | coursera-stanford-algorithms-solutions-kotlin | MIT License |
src/Day12.kt | buongarzoni | 572,991,996 | false | {"Kotlin": 26251} | import java.util.*
fun solveDay12() {
val input = readInput("Day12_test")
solve(input)
}
private fun solve(
input: List<String>,
) {
val grid = Grid.parse(input)
println("part 1 solution: ${grid.findShortedPath('S')}")
println("part 2 solution: ${grid.findShortedPath('a')}")
}
@JvmInline
value class Grid private constructor(
val points: List<List<Point>>,
) {
private val columns
get() = points[0].lastIndex
private val rows
get() = points.lastIndex
companion object {
fun parse(lines: List<String>) = Grid(
points = lines
.mapIndexed { y, line ->
line.mapIndexed { x, char ->
Point(x, y, char)
}
}
)
}
fun findShortedPath(target: Char): Int? {
val startingPoint = points.flatten().single { it.char == 'E' }
val pointsToVisit = ArrayDeque(listOf(startingPoint to 0))
val seen = mutableSetOf(startingPoint)
while (pointsToVisit.isNotEmpty()) {
val (point, distance) = pointsToVisit.removeFirst()
if (point isAtLevel target) return distance
point
.neighbors()
.filter { it isClimbable point }
.forEach { if (seen.add(it)) pointsToVisit.add(it to distance + 1) }
}
return null
}
private fun Point.neighbors() = listOfNotNull(
getPoint(x, y - 1), getPoint(x, y + 1),
getPoint(x - 1, y), getPoint(x + 1, y),
)
private fun getPoint(x: Int, y: Int) =
if (x < 0 || x > columns || y < 0 || y > rows) null else points[y][x]
}
data class Point(
val x: Int,
val y: Int,
val char: Char,
) {
private val height = when (char) {
'S' -> 0
'E' -> 26
else -> char - 'a'
}
infix fun isAtLevel(level: Char) = char == level
infix fun isClimbable(other: Point) = height + 1 >= other.height
}
| 0 | Kotlin | 0 | 0 | 96aadef37d79bcd9880dbc540e36984fb0f83ce0 | 1,992 | AoC-2022 | Apache License 2.0 |
Problems/Algorithms/934. Shortest Bridge/ShortestBridge.kt | xuedong | 189,745,542 | false | {"Kotlin": 332182, "Java": 294218, "Python": 237866, "C++": 97190, "Rust": 82753, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65} | class Solution {
fun shortestBridge(grid: Array<IntArray>): Int {
val n = grid.size
val m = grid[0].size
val neighbors = arrayOf(intArrayOf(0, 1), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0))
val queue = ArrayDeque<IntArray>()
var flag = false
for (i in 0..n-1) {
for (j in 0..m-1) {
if (grid[i][j] == 1) {
dfs(queue, grid, neighbors, n, m, i, j)
flag = true
break
}
}
if (flag) break
}
val visited = Array(n) { IntArray(m) { 0 } }
return bfs(queue, grid, visited, neighbors, n, m)
}
private fun dfs(queue: ArrayDeque<IntArray>, grid: Array<IntArray>, neighbors: Array<IntArray>, n: Int, m: Int, r: Int, c: Int): Unit {
if (grid[r][c] == 1) {
grid[r][c] = 2
queue.add(intArrayOf(r, c, 0))
for (neighbor in neighbors) {
val x = r + neighbor[0]
val y = c + neighbor[1]
if (isValid(n, m, x, y)) {
dfs(queue, grid, neighbors, n, m, x, y)
}
}
}
}
private fun bfs(queue: ArrayDeque<IntArray>, grid: Array<IntArray>, visited: Array<IntArray>, neighbors: Array<IntArray>, n: Int, m: Int): Int {
while (!queue.isEmpty()) {
val curr = queue.removeFirst()
val r = curr[0]
val c = curr[1]
val dist = curr[2]
if (grid[r][c] == 1) {
return dist - 1
} else {
for (neighbor in neighbors) {
val x = r + neighbor[0]
val y = c + neighbor[1]
if (isValid(n, m, x, y) && visited[x][y] == 0) {
visited[x][y] = 1
queue.add(intArrayOf(x, y, dist+1))
}
}
}
}
return -1
}
private fun isValid(n: Int, m: Int, r: Int, c: Int): Boolean {
return r >= 0 && r < n && c >= 0 && c < m
}
}
| 0 | Kotlin | 0 | 1 | 5e919965b43917eeee15e4bff12a0b6bea4fd0e7 | 2,245 | leet-code | MIT License |
src/Day03.kt | shoresea | 576,381,520 | false | {"Kotlin": 29960} | fun main() {
fun part1(inputs: List<String>): Int {
var sum = 0
for (input in inputs) {
sum += getPriority(input)
}
return sum
}
fun part2(inputs: List<String>): Int {
var sum = 0
var i = 0
while (i < inputs.size) {
sum += calculateBadgePriority(inputs[i++], inputs[i++], inputs[i++])
}
return sum
}
val input = readInput("Day03")
part1(input).println()
part2(input).println()
}
fun calculateBadgePriority(g1: String, g2: String, g3: String): Int {
val chars1 = g1.toCharArray().toSet()
val chars2 = g2.toCharArray().toSet()
var commons = chars1.intersect(chars2)
val chars3 = g3.toCharArray().toSet()
commons = chars3.intersect(commons)
return priorityOf(commons.single())
}
fun getPriority(input: String): Int {
var sum = 0
val len = input.length / 2
val chars1 = input.substring(0, len).toCharArray().toSet()
val chars2 = input.substring(len, input.length).toCharArray().toSet()
for (ch in chars2) {
if (chars1.contains(ch)) {
sum += priorityOf(ch)
}
}
return sum
}
fun priorityOf(char: Char): Int {
if (char in ('a'..'z')) {
return char.code - 96
}
return char.code - 64 + 26
} | 0 | Kotlin | 0 | 0 | e5d21eac78fcd4f1c469faa2967a4fd9aa197b0e | 1,311 | AOC2022InKotlin | Apache License 2.0 |
src/main/kotlin/days/Day5.kt | hughjdavey | 725,972,063 | false | {"Kotlin": 76988} | package days
import xyz.hughjd.aocutils.Collections.split
class Day5 : Day(5) {
private val almanac = parseAlmanac()
override fun partOne(): Any {
return seedToLocationSequence()
.filter { almanac.hasInitialSeed(it.seed, false) }
.first().location
}
override fun partTwo(): Any {
return seedToLocationSequence()
.filter { almanac.hasInitialSeed(it.seed, true) }
.first().location
}
private fun seedToLocationSequence(): Sequence<SeedToLocation> {
return generateSequence(0L) { it + 1L }
.map { SeedToLocation(almanac.locationToSeed(it), it) }
}
fun parseAlmanac(): Almanac {
val seeds = inputList[0].substring(7).split(' ').map { it.toLong() }
val maps = inputList.drop(2).split("").flatMap { it.split(",") }.fold(listOf<AlmanacMap>()) { acc, elem ->
val name = elem.first().replace(" map:", "")
val ranges = elem.drop(1).map { it.trim().split(' ').map { it.toLong() } }
acc + AlmanacMap(name, ranges)
}
return Almanac(seeds, maps)
}
data class SeedToLocation(val seed: Long, val location: Long)
data class Almanac(val seeds: List<Long>, val maps: List<AlmanacMap>) {
fun seedToLocation(seed: Long): Long {
return maps.fold(seed) { value, map -> map.get(value) }
}
fun locationToSeed(location: Long): Long {
return maps.reversed().fold(location) { value, map -> map.getReversed(value) }
}
fun hasInitialSeed(seed: Long, seedRanges: Boolean): Boolean {
return if (!seedRanges) seeds.contains(seed) else {
seeds.chunked(2).any { (start, length) ->
seed >= start && seed < (start + length)
}
}
}
}
data class AlmanacMap(val name: String, val ranges: List<List<Long>>) {
fun get(n: Long): Long {
for ((destStart, srcStart, length) in ranges) {
if (n >= srcStart && n < srcStart + length) {
return destStart + (n - srcStart)
}
}
return n
}
fun getReversed(n: Long): Long {
for ((destStart, srcStart, length) in ranges) {
if (n >= destStart && n < destStart + length) {
return srcStart + (n - destStart)
}
}
return n
}
}
}
| 0 | Kotlin | 0 | 0 | 330f13d57ef8108f5c605f54b23d04621ed2b3de | 2,496 | aoc-2023 | Creative Commons Zero v1.0 Universal |
untitled/src/main/kotlin/Day8.kt | jlacar | 572,845,298 | false | {"Kotlin": 41161} | class Day8(private val fileName: String) : AocSolution {
override val description: String get() = "Day 8 - Treetop Tree House ($fileName)"
override fun part1() = visibleTrees()
override fun part2() = scenicScores().max()
private val forestRows = InputReader(fileName).lines.map { it.toCharArray() }
private val forestCols = forestRows[0].indices.map { i -> forestRows.map { it[i] }.toCharArray() }
private fun visibleTrees() = perimeter() + visibleFromOutside()
private fun perimeter() = 2 * forestRows.size + 2 * forestRows[0].size - 4
private fun visibleFromOutside() =
(1 until forestRows.lastIndex).sumOf { row ->
(1 until forestCols.lastIndex).count { col -> canSeeTreeAt(row, col) }
}
private fun canSeeTreeAt(row: Int, col: Int) =
canSeeFromOutside(forestRows[row], col) || canSeeFromOutside(forestCols[col], row)
private fun canSeeFromOutside(trees: CharArray, pos: Int) = trees[pos].let {
isNotObscured(it, front(trees, pos)) || isNotObscured(it, back(trees, pos))
}
private fun isNotObscured(tree: Char, trees: List<Char>) = trees.none { it >= tree }
private fun front(trees: CharArray, pos: Int) = trees.dropLast(trees.size - pos)
private fun back(trees: CharArray, pos: Int) = trees.drop(pos + 1)
private fun scenicScores() =
(1 until forestRows.lastIndex).map { row ->
(1 until forestCols.lastIndex).map { col ->
scenicScore(forestRows[row], col) * scenicScore(forestCols[col], row)
}
}.flatten()
private fun scenicScore(trees: CharArray, pos: Int) =
scenicScore(trees[pos], front(trees, pos).reversed()) *
scenicScore(trees[pos], back(trees, pos))
private fun scenicScore(tree: Char, otherTrees: List<Char>) =
if (otherTrees.isNotEmpty()) howManyCanBeSeen(otherTrees, tree) else 0
private fun howManyCanBeSeen(otherTrees: List<Char>, tree: Char) =
otherTrees.dropWhile { it < tree }.let { remaining ->
otherTrees.size - remaining.size + firstTree(remaining)
}
private fun firstTree(remaining: List<Char>) = if (remaining.isEmpty()) 0 else 1
}
fun main() {
Day8("Day8-sample.txt") solution {
part1() shouldBe 21
part2() shouldBe 8
}
Day8("Day8.txt") solution {
part1() shouldBe 1690
part2() shouldBe 535680
}
Day8("Day8-alt.txt") solution {
part1() shouldBe 1698
part2() shouldBe 672280
}
} | 0 | Kotlin | 0 | 2 | dbdefda9a354589de31bc27e0690f7c61c1dc7c9 | 2,520 | adventofcode2022-kotlin | The Unlicense |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.