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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dataStructuresAndAlgorithms/src/main/java/dev/funkymuse/datastructuresandalgorithms/graphs/djikstra/Dijkstra.kt | FunkyMuse | 168,687,007 | false | {"Kotlin": 1728251} | package dev.funkymuse.datastructuresandalgorithms.graphs.djikstra
import dev.funkymuse.datastructuresandalgorithms.graphs.Edge
import dev.funkymuse.datastructuresandalgorithms.graphs.Vertex
import dev.funkymuse.datastructuresandalgorithms.graphs.adjacency.AdjacencyList
import dev.funkymuse.datastructuresandalgorithms.queue.priority.comparator.ComparatorPriorityQueue
class Dijkstra<T>(private val graph: AdjacencyList<T>) {
private fun route(destination: Vertex<T>, paths: HashMap<Vertex<T>, Visit<T>>): ArrayList<Edge<T>> {
var vertex = destination
val path = arrayListOf<Edge<T>>()
loop@ while (true) {
val visit = paths[vertex] ?: break
when (visit.type) {
VisitType.START -> break@loop
VisitType.EDGE -> visit.edge?.let {
path.add(it)
vertex = it.source
}
}
}
return path
}
private fun distance(destination: Vertex<T>, paths: HashMap<Vertex<T>, Visit<T>>): Double {
val path = route(destination, paths)
return path.sumByDouble { it.weight ?: 0.0 }
}
fun shortestPath(start: Vertex<T>): HashMap<Vertex<T>, Visit<T>> {
val paths: HashMap<Vertex<T>, Visit<T>> = HashMap()
paths[start] = Visit(VisitType.START)
val distanceComparator = Comparator<Vertex<T>> { first, second ->
(distance(second, paths) - distance(first, paths)).toInt()
}
val priorityQueue = ComparatorPriorityQueue(distanceComparator)
priorityQueue.enqueue(start)
while (true) {
val vertex = priorityQueue.dequeue() ?: break
val edges = graph.edges(vertex)
edges.forEach {
val weight = it.weight ?: return@forEach
if (paths[it.destination] == null
|| distance(vertex, paths) + weight < distance(it.destination, paths)) {
paths[it.destination] = Visit(VisitType.EDGE, it)
priorityQueue.enqueue(it.destination)
}
}
}
return paths
}
fun shortestPath(destination: Vertex<T>, paths: HashMap<Vertex<T>, Visit<T>>): ArrayList<Edge<T>> {
return route(destination, paths)
}
fun getAllShortestPath(source: Vertex<T>): HashMap<Vertex<T>, ArrayList<Edge<T>>> {
val paths = HashMap<Vertex<T>, ArrayList<Edge<T>>>()
val pathsFromSource = shortestPath(source)
graph.allVertices.forEach {
val path = shortestPath(it, pathsFromSource)
paths[it] = path
}
return paths
}
}
| 0 | Kotlin | 92 | 771 | e2afb0cc98c92c80ddf2ec1c073d7ae4ecfcb6e1 | 2,679 | KAHelpers | MIT License |
src/main/kotlin/com/sk/set3/347. Top K Frequent Elements.kt | sandeep549 | 262,513,267 | false | {"Kotlin": 530613} | package com.sk.set3
import java.util.*
class Solution347 {
fun topKFrequent(nums: IntArray, k: Int): List<Int> {
val frequencyMap: MutableMap<Int, Int> = HashMap()
for (n in nums) {
frequencyMap[n] = frequencyMap.getOrDefault(n, 0) + 1
}
val bucket = Array<MutableList<Int>?>(nums.size + 1) { null }
for (key in frequencyMap.keys) {
val frequency = frequencyMap[key]!!
if (bucket[frequency] == null) {
bucket[frequency] = ArrayList()
}
bucket[frequency]!!.add(key)
}
val res: MutableList<Int> = ArrayList()
var pos = bucket.size - 1
while (pos >= 0 && res.size < k) {
if (bucket[pos] != null) {
res.addAll(bucket[pos]!!)
}
pos--
}
return res
}
}
private fun topKFrequent(nums: IntArray, k: Int): IntArray {
if (k == nums.size) {
return nums
}
val count = nums.groupBy { it }.mapValues { it.value.size }
val heap = PriorityQueue<Int> { n1, n2 -> (count[n1]!! - count[n2]!!) }
for (n in count.keys) {
heap.add(n)
if (heap.size > k) heap.poll()
}
val top = IntArray(k)
for (i in k - 1 downTo 0) {
top[i] = heap.poll()
}
return top
}
private fun topKFrequent2(nums: IntArray, k: Int) = nums
.groupBy { it } // Time: O(n) Space:O(n)
.toList() // Time: O(n) Space:O(n)
.sortedByDescending { it.second.size } // Time: O(nlogn) Space:O(n)
.take(k) // Time: O(k) Space:O(k)
.map { it.first } // Time: O(k) Space:O(k)
| 1 | Kotlin | 0 | 0 | cf357cdaaab2609de64a0e8ee9d9b5168c69ac12 | 1,634 | leetcode-kotlin | Apache License 2.0 |
src/Day03.kt | flex3r | 572,653,526 | false | {"Kotlin": 63192} | fun main() {
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int {
return input
.map { it.chunked(size = it.length / 2).findDuplicate() }
.sumOf { it.toPriority() }
}
private fun part2(input: List<String>): Int {
return input
.chunked(3)
.map { it.findDuplicate() }
.sumOf { it.toPriority() }
}
private fun List<String>.findDuplicate(): Char {
return map { it.toSet() }
.reduce { acc, chars ->
acc intersect chars
}.first()
}
// too lazy for char codes today
private val chars = ('a'..'z') + ('A'..'Z')
private fun Char.toPriority() = chars.indexOf(this) + 1
| 0 | Kotlin | 0 | 0 | 8604ce3c0c3b56e2e49df641d5bf1e498f445ff9 | 838 | aoc-22 | Apache License 2.0 |
src/main/kotlin/aoc2022/Day14.kt | j4velin | 572,870,735 | false | {"Kotlin": 285016, "Python": 1446} | package aoc2022
import Point
import readInput
private const val MAX_WIDTH = 1000
private val START = Point(500, 0)
private fun getMaxY(input: List<String>): Int {
return input.maxOf { path ->
path.split(" -> ").maxOf { point ->
val (x, y) = point.split(",").map { it.toInt() }
y
}
}
}
private fun getEmptyGrid(height: Int, width: Int = MAX_WIDTH): Array<CharArray> {
return Array(height + 1) { CharArray(width + 1) { '.' } }
}
private fun fillGrid(input: List<String>, grid: Array<CharArray>) {
input.forEach { path ->
val points = path.split(" -> ").map { point ->
val (x, y) = point.split(",").map { it.toInt() }
Point(x, y)
}
points.windowed(2, 1).forEach {
val start = it[0]
val end = it[1]
if (start.x == end.x) {
for (y in minOf(start.y, end.y)..maxOf(start.y, end.y)) {
grid[y][start.x] = '#'
}
} else {
for (x in minOf(start.x, end.x)..maxOf(start.x, end.x)) {
grid[start.y][x] = '#'
}
}
}
}
}
private fun addSand(grid: Array<CharArray>, start: Point = START): Int {
var rounds = 0
while (true) {
var currentY = start.y
var currentX = start.x
while (true) {
if (currentY + 1 >= grid.size) {
// falling of the edge of the grid
currentY++
break
}
if (grid[currentY + 1][currentX] == '.') {
// move downwards
currentY++
} else if (grid[currentY + 1][currentX - 1] == '.') {
// move diagonal left
currentX--
currentY++
} else if (grid[currentY + 1][currentX + 1] == '.') {
// move diagonal right
currentY++
currentX++
} else {
grid[currentY][currentX] = '+'
break
}
}
if (currentY >= grid.size) {
// falling off the edge
return rounds
} else if (currentY == start.y && currentX == start.x) {
// cave filled
return rounds + 1
}
rounds++
}
}
private fun part1(input: List<String>): Int {
val grid = getEmptyGrid(height = getMaxY(input))
fillGrid(input, grid)
return addSand(grid)
}
private fun part2(input: List<String>): Int {
val maxY = getMaxY(input) + 2
val grid = getEmptyGrid(height = maxY)
val modifiedInput = buildList {
addAll(input)
add("0,$maxY -> $MAX_WIDTH,$maxY")
}
fillGrid(modifiedInput, grid)
return addSand(grid)
}
fun main() {
val testInput = readInput("Day14_test", 2022)
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14", 2022)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f67b4d11ef6a02cba5b206aba340df1e9631b42b | 3,018 | adventOfCode | Apache License 2.0 |
src/main/kotlin/org/sjoblomj/adventofcode/day6/Day6.kt | sjoblomj | 225,241,573 | false | null | package org.sjoblomj.adventofcode.day6
import org.sjoblomj.adventofcode.readFile
private const val inputFile = "src/main/resources/inputs/day6.txt"
fun day6(): Pair<Int, Int> {
val content = readFile(inputFile)
val orbitList = getOrbitList(content)
val numberOfOrbits = calculateNumberOfOrbits(orbitList)
val minimumPathBetweenObjects = calculateMinimumPathBetweenObjects(orbitList, "YOU", "SAN")
val minimumOrbitalTransfersBetweenObjects = calculateMinimumOrbitalTransfersBetweenObjects(minimumPathBetweenObjects)
println("Total number of direct and indirect orbits: $numberOfOrbits")
println("Minimum number of orbital transfers: $minimumOrbitalTransfersBetweenObjects")
return Pair(numberOfOrbits, minimumOrbitalTransfersBetweenObjects)
}
internal fun calculateNumberOfOrbits(orbitList: List<CelestialBody>): Int {
val distanceMap = HashMap<CelestialBody, Int>()
orbitList.forEach { calculateDistance(it, distanceMap) }
return distanceMap.values.sum()
}
internal fun calculateDistance(celestialBody: CelestialBody?, distanceMap: HashMap<CelestialBody, Int>): Int {
if (celestialBody == null)
return 0
if (distanceMap.containsKey(celestialBody))
return distanceMap[celestialBody]!!
if (celestialBody.bodyRevolvingAround == null) {
distanceMap[celestialBody] = 0
return 0
}
distanceMap[celestialBody] = 1 + calculateDistance(celestialBody.bodyRevolvingAround, distanceMap)
return distanceMap[celestialBody]!!
}
internal fun getOrbitList(inputs: List<String>): List<CelestialBody> {
val celestialBodies = hashMapOf<String, CelestialBody>()
val bodyPairs = inputs.map { it.split(")") }
bodyPairs
.forEach { (parentName, childName) -> run {
celestialBodies.putIfAbsent(parentName, CelestialBody(parentName))
celestialBodies.putIfAbsent(childName, CelestialBody(childName))
} }
bodyPairs
.forEach { (parentName, childName) -> run {
celestialBodies[childName]?.bodyRevolvingAround = celestialBodies[parentName]
celestialBodies[parentName]?.satellites?.add(celestialBodies[childName]!!)
} }
return celestialBodies.values.toList()
}
internal fun calculateMinimumPathBetweenObjects(celestialBodies: List<CelestialBody>, o1: String, o2: String): List<CelestialBody> {
val b1 = celestialBodies.first { it.name == o1 }
val b2 = celestialBodies.first { it.name == o2 }
val paths = calculateMinimumPathBetweenObjects(emptyList(), b1, b2)
?: throw IllegalArgumentException("Failed to find minimum paths between $o1 and $o2")
return paths.minus(b1).minus(b2)
}
internal fun calculateMinimumPathBetweenObjects(paths: List<CelestialBody>, currNode: CelestialBody, endNode: CelestialBody): List<CelestialBody>? {
val currPath = paths.plus(currNode)
return if (currNode == endNode)
currPath
else {
val unvisitedNeighbours = currNode.satellites
.plus(currNode.bodyRevolvingAround)
.filterNotNull()
.subtract(paths)
if (unvisitedNeighbours.isEmpty())
null
else
unvisitedNeighbours
.mapNotNull { calculateMinimumPathBetweenObjects(currPath, it, endNode) }
.minBy { it.size }
}
}
internal fun calculateMinimumOrbitalTransfersBetweenObjects(path: List<CelestialBody>) = path.size - 1
class CelestialBody(val name: String, var bodyRevolvingAround: CelestialBody? = null,
val satellites: MutableList<CelestialBody> = mutableListOf())
| 0 | Kotlin | 0 | 0 | f8d03f7ef831bc7e26041bfe7b1feaaadcb40e68 | 3,338 | adventofcode2019 | MIT License |
src/main/kotlin/TwoSum.kt | mececeli | 553,346,819 | false | {"Kotlin": 9018} | /**
* Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
* You may assume that each input would have exactly one solution, and you may not use the same element twice.
* You can return the answer in any order.
*
* Example 1:
* Input: nums = [2,7,11,15], target = 9
* Output: [0,1]
* Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
* Example 2:
*
* Input: nums = [3,2,4], target = 6
* Output: [1,2]
* Example 3:
*
* Input: nums = [3,3], target = 6
* Output: [0,1]
*
* Main.kt run
* println(
* twoSumBest(
* nums = intArrayOf(7, 5, 10, 2),
* target = 12
* ).contentToString()
* )
*/
//My solution
fun twoSum(nums: IntArray, target: Int): IntArray {
var result : IntArray = intArrayOf()
nums.forEachIndexed { index, item ->
val numberWeLook = target - item
if(nums.contains(numberWeLook) && index != nums.indexOf(numberWeLook)) {
result = intArrayOf(index, nums.indexOf(numberWeLook))
return result
}
}
return result
}
//Alternative solution
fun twoSumBest(nums: IntArray, target: Int): IntArray {
val diffMap = mutableMapOf<Int, Int>()
nums.forEachIndexed { index, int ->
diffMap[int]?.let { return intArrayOf(it, index) }
diffMap[target - int] = index
}
return intArrayOf()
}
| 0 | Kotlin | 0 | 0 | d05ee9d32c42d11e71e136f4138bb0335114f360 | 1,384 | Kotlin_Exercises | Apache License 2.0 |
src/year2021/06/Day06.kt | Vladuken | 573,128,337 | false | {"Kotlin": 327524, "Python": 16475} | package year2021.`06`
import readInput
fun main() {
fun cycle(input: Map<Long, Long>): Map<Long, Long> {
val resultMap = mutableMapOf<Long, Long>()
input.keys
.sortedDescending()
.forEach {
when (it) {
0L -> {
resultMap[6] = (resultMap[6] ?: 0) + (input[0] ?: 0)
resultMap[8] = (resultMap[8] ?: 0) + (input[0] ?: 0)
}
else -> {
resultMap[it - 1] = (input[it] ?: 0)
}
}
}
return resultMap
}
fun functionWithMap(input: List<String>, cycleAmount: Int): Long {
val items = input.first().split(",").map { it.toLong() }
val initialMap = mutableMapOf<Long, Long>()
items.forEach {
if (initialMap.containsKey(it)) {
initialMap[it] = initialMap[it]!! + 1
} else {
initialMap[it] = 1
}
}
var resultMap: Map<Long, Long> = initialMap
repeat(cycleAmount) {
resultMap = cycle(resultMap)
}
return resultMap.values.sum()
}
// endregion
fun part1(input: List<String>): Long {
return functionWithMap(input, 80)
}
fun part2(input: List<String>): Long {
return functionWithMap(input, 256)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
val part1Test = part1(testInput)
println(part1Test)
check(part1Test == 5934L)
val input = readInput("Day06")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 5 | c0f36ec0e2ce5d65c35d408dd50ba2ac96363772 | 1,722 | KotlinAdventOfCode | Apache License 2.0 |
src/main/kotlin/dev/siller/aoc2023/Day02.kt | chearius | 725,594,554 | false | {"Kotlin": 50795, "Shell": 299} | package dev.siller.aoc2023
data object Day02 : AocDayTask<UInt, UInt>(
day = 2,
exampleInput =
"""
|Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
|Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue
|Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red
|Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red
|Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green
""".trimMargin(),
expectedExampleOutputPart1 = 8u,
expectedExampleOutputPart2 = 2286u
) {
private const val MAX_RED_CUBES = 12u
private const val MAX_GREEN_CUBES = 13u
private const val MAX_BLUE_CUBES = 14u
private data class CubeSet(val red: UInt, val green: UInt, val blue: UInt)
private data class Game(val id: UInt, val grabbedCubeSets: List<CubeSet>)
override fun runPart1(input: List<String>): UInt =
input.map(::toGame).filterNot { game ->
game.grabbedCubeSets.any { cs ->
cs.red > MAX_RED_CUBES || cs.green > MAX_GREEN_CUBES || cs.blue > MAX_BLUE_CUBES
}
}.sumOf(Game::id)
override fun runPart2(input: List<String>): UInt =
input.map(::toGame).sumOf { game ->
val cubes = game.grabbedCubeSets
cubes.maxOf(CubeSet::red) * cubes.maxOf(CubeSet::blue) * cubes.maxOf(CubeSet::green)
}
private fun toGame(line: String): Game {
val (gamePart, setsPart) = line.split(':', limit = 2)
val gameId = gamePart.filter { it in '0'..'9' }.toUInt()
val grabbedCubeSets =
setsPart.split(';')
.map { cubeSet ->
val cubes =
cubeSet.split(',').map(String::trim).associate { c ->
val (count, color) = c.split(' ', limit = 2)
color to count.toUInt()
}
CubeSet(
red = cubes.getOrDefault("red", 0u),
green = cubes.getOrDefault("green", 0u),
blue = cubes.getOrDefault("blue", 0u)
)
}
return Game(gameId, grabbedCubeSets)
}
}
| 0 | Kotlin | 0 | 0 | fab1dd509607eab3c66576e3459df0c4f0f2fd94 | 2,261 | advent-of-code-2023 | MIT License |
2022/src/main/kotlin/day12_imp.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Grid
import utils.Graph
import utils.Parser
import utils.Solution
import utils.Vec2i
import utils.mapParser
import java.lang.IllegalStateException
fun main() {
Day12Imp.run()
}
object Day12Imp : Solution<Grid<Char>>() {
override val name = "day12"
override val parser = Parser(String::trim).mapParser(Parser.charGrid)
data class Node(val p: Vec2i, val height: Int)
data class Edge(val weight: Int)
private fun height(c: Char): Int {
return when (c) {
'S' -> 0
'E' -> 'z' - 'a'
else -> (c - 'a')
}
}
private fun solve(input: Grid<Char>, startChars: Set<Char>): Int {
val g = Graph<Node, Edge>(
edgeFn = { v ->
val h1 = height(input[v.p])
// grab 4-way adjacent squares to the coordinate...
v.p.adjacent
// ...that are still in the input...
.filter { it in input }
.map {
val height = height(input[it])
val node = Node(it, height)
val edge = Edge(maxOf(height - h1, 0))
edge to node
}
// ...and are either lower or no more higher than 1
.filter { (edge, _) -> edge.weight <= 1 }
}
)
val starts = input.cells.filter { (_, c) -> c in startChars }.map { it.first }
val end = input.cells.first { (_, c) -> c == 'E' }.first
return starts.mapNotNull { start ->
try {
g.shortestPath(Node(start, 0), Node(end, height('E')))
} catch (e: IllegalStateException) {
null
}
}.min()
}
override fun part1(input: Grid<Char>): Int = solve(input, setOf('S'))
override fun part2(input: Grid<Char>): Int = solve(input, setOf('S', 'a'))
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 1,688 | aoc_kotlin | MIT License |
src/Day07.kt | maewCP | 579,203,172 | false | {"Kotlin": 59412} | fun main() {
val verbose = false
fun _process(input: List<String>) : Day07Folder {
val root = Day07Folder("/")
var currentFolder = root
val cdCmd = "\\$ cd (.+)".toRegex()
val folderOutput = "dir (.+)".toRegex()
val fileOutput = "(\\d+) .+".toRegex()
input.forEach { line ->
val cdMatch = cdCmd.find(line)
if (cdMatch != null) {
val folderName = cdMatch.destructured.toList()[0]
if (folderName == "/") {
currentFolder = root
} else if (folderName == "..") {
currentFolder = currentFolder.parent!!
} else {
var folder = currentFolder.subFolders.find { it.name == "folderName" }
if (folder == null) {
folder = Day07Folder(folderName)
folder.parent = currentFolder
currentFolder.subFolders.add(folder)
}
currentFolder = folder
}
return@forEach
}
val folderMatch = folderOutput.find(line)
if (folderMatch != null) {
val folderName = folderMatch.destructured.toList()[0]
var folder = currentFolder.subFolders.find { it.name == "folderName" }
if (folder == null) {
folder = Day07Folder(folderName)
folder.parent = currentFolder
currentFolder.subFolders.add(folder)
}
return@forEach
}
val fileMatch = fileOutput.find(line)
if (fileMatch != null) {
val fileSize = fileMatch.destructured.toList()[0].toInt()
currentFolder.fileSize += fileSize
return@forEach
}
}
root.calcAllFileSize()
return root
}
fun part1(input: List<String>): Int {
val root = _process(input)
return root.part1Calc(0, verbose)
}
fun part2(input: List<String>): Int {
val root = _process(input)
return root.part2Calc(0, verbose, Int.MAX_VALUE)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
part1(input).println()
part2(input).println()
}
data class Day07Folder(val name: String) {
var parent: Day07Folder? = null
val subFolders = mutableListOf<Day07Folder>()
var fileSize = 0
var allFileSize = 0
fun part1Calc(indent: Int, verbose: Boolean) : Int {
var result = 0
if (verbose) repeat(indent) { print(" ") }
if (verbose) println("dir $name (file size = $fileSize) (all file size = $allFileSize)")
if (allFileSize < 100000) result += allFileSize
subFolders.forEach { folder ->
result += folder.part1Calc(indent + 4, verbose)
}
return result
}
fun part2Calc(indent: Int, verbose: Boolean, smallestBigEnough: Int) : Int {
var result = smallestBigEnough
if (verbose) repeat(indent) { print(" ") }
if (verbose) println(allFileSize.toString() + " " + (allFileSize >= 8381165).toString() + " " + (allFileSize < result).toString())
if (allFileSize >= 8381165 && allFileSize < result) result = allFileSize
subFolders.forEach { folder ->
result = folder.part2Calc(indent + 4, verbose, result)
}
return result
}
fun calcAllFileSize(): Int {
allFileSize = fileSize + subFolders.sumOf { folder -> folder.calcAllFileSize() }
return allFileSize
}
}
| 0 | Kotlin | 0 | 0 | 8924a6d913e2c15876c52acd2e1dc986cd162693 | 3,805 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/Day09.kt | sabercon | 648,989,596 | false | null | fun main() {
fun isValid(nums: List<Long>, i: Int): Boolean {
if (i < 25) return true
val preamble = nums.subList(i - 25, i).toSet()
return preamble.any { it * 2 != nums[i] && preamble.contains(nums[i] - it) }
}
tailrec fun findRange(nums: List<Long>, target: Long, start: Int, end: Int, sum: Long): List<Long> {
return when {
end == nums.size -> error("No range found")
start + 1 == end || sum < target -> findRange(nums, target, start, end + 1, sum + nums[end])
sum > target -> findRange(nums, target, start + 1, end, sum - nums[start])
else -> nums.subList(start, end)
}
}
val input = readLines("Day09").map { it.toLong() }
val num = input.withIndex().first { (i, _) -> !isValid(input, i) }.value
num.println()
val range = findRange(input, num, 0, 2, input[0] + input[1])
println(range.min() + range.max())
}
| 0 | Kotlin | 0 | 0 | 81b51f3779940dde46f3811b4d8a32a5bb4534c8 | 940 | advent-of-code-2020 | MIT License |
src/day02/Day02.kt | wickenico | 573,158,084 | false | {"Kotlin": 7731} | package day02
import readInput
fun main() {
println(part2(readInput("day02", "input"), strategy1))
println(part2(readInput("day02", "input"), strategy2))
}
private val strategy1 = mapOf(
'A' to mapOf('X' to 1 + 3, 'Y' to 2 + 6, 'Z' to 3 + 0),
'B' to mapOf('X' to 1 + 0, 'Y' to 2 + 3, 'Z' to 3 + 6),
'C' to mapOf('X' to 1 + 6, 'Y' to 2 + 0, 'Z' to 3 + 3)
)
private val strategy2 = mapOf(
'A' to mapOf('X' to 3 + 0, 'Y' to 1 + 3, 'Z' to 2 + 6),
'B' to mapOf('X' to 1 + 0, 'Y' to 2 + 3, 'Z' to 3 + 6),
'C' to mapOf('X' to 2 + 0, 'Y' to 3 + 3, 'Z' to 1 + 6)
)
private fun part2(input: List<String>, strategy: Map<Char, Map<Char, Int>>) = input.sumOf { strategy[it[0]]?.get(it[2]) ?: 0 }
| 0 | Kotlin | 0 | 0 | bc587f433aa38c4d745c09d82b7d231462f777c8 | 720 | advent-of-code-kotlin | Apache License 2.0 |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[316]去除重复字母.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | //给你一个字符串 s ,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证 返回结果的字典序最小(要求不能打乱其他字符的相对位置)。
//
// 注意:该题与 1081 https://leetcode-cn.com/problems/smallest-subsequence-of-distinct
//-characters 相同
//
//
//
// 示例 1:
//
//
//输入:s = "bcabc"
//输出:"abc"
//
//
// 示例 2:
//
//
//输入:s = "cbacdcbc"
//输出:"acdb"
//
//
//
// 提示:
//
//
// 1 <= s.length <= 104
// s 由小写英文字母组成
//
// Related Topics 栈 贪心算法 字符串
// 👍 345 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun removeDuplicateLetters(s: String): String {
//贪心 + 栈 使用数组代替栈 时间复杂度 O(n)
//贪心 + 栈 使用数组代替栈 时间复杂度 O(n)
val visit = BooleanArray(26)
val num = IntArray(26)
for (i in s.indices) {
num[s[i] - 'a']++
}
val sb = StringBuilder()
for (element in s) {
val ch: Char = element
if (!visit[ch - 'a']) {
while (sb.isNotEmpty() && sb[sb.length - 1] > ch) {
if (num[sb[sb.length - 1] - 'a'] > 0) {
visit[sb[sb.length - 1] - 'a'] = false
sb.deleteCharAt(sb.length - 1)
} else {
break
}
}
visit[ch - 'a'] = true
sb.append(ch)
}
num[ch - 'a'] -= 1
}
return sb.toString()
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 1,736 | MyLeetCode | Apache License 2.0 |
src/Day24.kt | MarkTheHopeful | 572,552,660 | false | {"Kotlin": 75535} | private val directions = mutableListOf(-1 to 0, 1 to 0, 0 to -1, 0 to 1)
private val charToDir = buildMap(4) { (0..3).forEach { put("^v<>"[it], directions[it]) } }
private data class Blizzard(val dir: Pair<Int, Int>, var pos: Pair<Int, Int>)
private class BlizzardField(map: List<String>) {
val blizzards: MutableList<Blizzard> = mutableListOf()
val occupiedPositions: MutableMap<Pair<Int, Int>, Int> = mutableMapOf()
val n: Int
val m: Int
init {
n = map.size - 2
m = map[0].length - 2
map.drop(1).take(n).withIndex().onEach { (vx, line) ->
line.drop(1).take(m).withIndex().onEach { (vy, c) ->
if (c != '.') {
blizzards.add(Blizzard(charToDir[c] ?: error("Wrong char"), vx to vy))
occupiedPositions[vx to vy] = occupiedPositions.getOrDefault(vx to vy, 0) + 1 // With default
}
}
}
}
fun iterateBlizzards() {
blizzards.withIndex().forEach { (ind, value) ->
val (dir, pos) = value
occupiedPositions[pos] = (occupiedPositions[pos] ?: error("There must be at least one. I feel it.")) - 1
var (nx, ny) = pos + dir
nx = (nx + n) % n
ny = (ny + m) % m
blizzards[ind].pos = nx to ny
occupiedPositions[nx to ny] = occupiedPositions.getOrDefault(nx to ny, 0) + 1
}
}
fun isFree(pos: Pair<Int, Int>): Boolean {
return (pos.first == -1 && pos.second == 0) || (pos.first == n && pos.second == m - 1) ||
!(pos.first < 0 || pos.first >= n || pos.second < 0 || pos.second >= m ||
occupiedPositions.getOrDefault(pos, 0) > 0)
}
fun runBfs(start: Pair<Int, Int> = -1 to 0, final: Pair<Int, Int> = n to m - 1): Int {
val q: MutableList<MutableSet<Pair<Int, Int>>> = mutableListOf(mutableSetOf(start), mutableSetOf())
var iter = 0
while (true) {
iterateBlizzards()
q[iter % 2].forEach {
if (it == final) {
return iter
}
if (isFree(it)) {
q[(iter + 1) % 2].add(it)
}
for (dir in directions) { // Maybe somehow build set right here
if (isFree(it + dir)) {
q[(iter + 1) % 2].add(it + dir)
}
}
}
q[iter % 2].clear()
if (q[0].isEmpty() && q[1].isEmpty()) {
error("There is no way through this blizzard. Supplies and energy are running out. Goodbye.")
}
iter++
}
}
}
fun main() {
fun part1(input: List<String>): Int {
return BlizzardField(input).runBfs()
}
fun part2(input: List<String>): Int {
val field = BlizzardField(input)
val start = -1 to 0
val final = field.n to field.m - 1
// And now we should add 1. Twice.
return field.runBfs(start, final) + 1 + field.runBfs(final, start) + 1 + field.runBfs(start, final)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day24_test")
check(part1(testInput) == 18)
check(part2(testInput) == 54)
val input = readInput("Day24")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8218c60c141ea2d39984792fddd1e98d5775b418 | 3,399 | advent-of-kotlin-2022 | Apache License 2.0 |
src/Day02.kt | alexdesi | 575,352,526 | false | {"Kotlin": 9824} | import java.io.File
fun main() {
fun value(move: Char): Int {
return when (move) {
'A', 'X' -> 1
'B', 'Y' -> 2
'C', 'Z' -> 3
else -> -1
}
}
fun getScore(move1: Char, move2: Char): Int {
return when ("$move1$move2") {
"AA", "BB", "CC" -> 3 // draw
"AB", "BC", "CA" -> 6 // win
"AC", "BA", "CB" -> 0 // lose
else -> -1
} + value(move2)
}
fun choseMove(move: Char, action: Char): Char {
// X means you need to lose,
// Y means you need to end the round in a draw, and
// Z means you need to win
return when (action) {
'X' -> when (move) { // Lose
'A' -> 'C'
'B' -> 'A'
'C' -> 'B'
else -> ' '
}
'Y' -> when (move) { // Draw
'A', 'B', 'C' -> move
else -> ' '
}
'Z' -> when (move) {
'A' -> 'B' // win
'B' -> 'C'
'C' -> 'A'
else -> ' '
}
else -> ' '
}
}
fun convertToMove(wantedResult: Char): Char {
return when (wantedResult) {
'X' -> 'A'
'Y' -> 'B'
'Z' -> 'C'
else -> ' '
}
}
fun part1(input: List<String>): Int {
return input.sumOf {
getScore(
it.first(),
convertToMove(it.last())
)
}
}
fun part2(input: List<String>): Int {
return input.sumOf {
getScore(
it.first(),
choseMove(it.first(), it.last())
)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
println(testInput)
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 56a6345e0e005da09cb5e2c7f67c49f1379c720d | 2,068 | advent-of-code-kotlin | Apache License 2.0 |
src/Day14.kt | TheGreatJakester | 573,222,328 | false | {"Kotlin": 47612} | package day14
import utils.readInputAsText
import utils.runSolver
import utils.string.asLines
private typealias SolutionType = Int
private const val defaultSolution = 0
private const val dayNumber: String = "14"
private val testSolution1: SolutionType? = 24
private val testSolution2: SolutionType? = 93
typealias Point = Pair<Int, Int>
fun Point.pointsBellow() = listOf(
first to second + 1,
first - 1 to second + 1,
first + 1 to second + 1
)
val generationPoint = 500 to 0
private fun getCaveFromInput(input: String): MutableSet<Point> {
val linePairs = input.asLines().map { line ->
line.split(" -> ").map { pointText ->
val c = pointText.split(",")
c[0].toInt() to c[1].toInt()
}
}
val cavePoints = mutableSetOf<Point>()
infix fun Int.overTo(other: Int): IntRange {
if (this > other) {
return other..this
}
return this..other
}
fun addLine(from: Point, to: Point) {
// for vertical lines
if (from.first == to.first) {
for (y in from.second overTo to.second) {
cavePoints.add(from.first to y)
}
return
}
val slope = (from.second - to.second).toFloat() / (from.first - to.first)
for (x in from.first overTo to.first) {
val y = (slope * (x - from.first)).toInt() + to.second
cavePoints.add(x to y)
}
}
linePairs.forEach { line ->
line.windowed(2) {
addLine(it[0], it[1])
}
}
return cavePoints
}
private fun part1(input: String): SolutionType {
val filledPoints = getCaveFromInput(input)
var sandCount = 0
fun isSandDeep(sand: Point) = sand.second > 1000
tailrec fun nextSandPoint(sand: Point = generationPoint): Point {
if (isSandDeep(sand)) return sand
sand.pointsBellow().firstOrNull {
!filledPoints.contains(it)
}?.let {
return nextSandPoint(it)
}
return sand
}
while (true) {
val sand = nextSandPoint()
if (isSandDeep(sand)) break
filledPoints.add(sand)
sandCount += 1
}
return sandCount
}
private fun part2(input: String): SolutionType {
val filledPoints = getCaveFromInput(input)
var sandCount = 1
val floorLevel = filledPoints.maxOf { it.second } + 2
fun isSandOnFloor(sand: Point) = sand.second + 1 == floorLevel
tailrec fun nextSandPoint(sand: Point = generationPoint): Point {
if (isSandOnFloor(sand)) return sand
sand.pointsBellow().firstOrNull {
!filledPoints.contains(it)
}?.let {
return nextSandPoint(it)
}
return sand
}
while (true) {
val sand = nextSandPoint()
if (sand == generationPoint) break
filledPoints.add(sand)
sandCount += 1
}
return sandCount
}
fun main() {
runSolver("Test 1", readInputAsText("Day${dayNumber}_test"), testSolution1, ::part1)
runSolver("Part 1", readInputAsText("Day${dayNumber}"), null, ::part1)
runSolver("Test 2", readInputAsText("Day${dayNumber}_test"), testSolution2, ::part2)
runSolver("Part 2", readInputAsText("Day${dayNumber}"), null, ::part2)
}
| 0 | Kotlin | 0 | 0 | c76c213006eb8dfb44b26822a44324b66600f933 | 3,292 | 2022-AOC-Kotlin | Apache License 2.0 |
src/day05/Day05.kt | Frank112 | 572,910,492 | false | null | package day05
import assertThat
import readInput
fun main() {
val crateLineRegex: Regex = Regex("( |\\[(?<crate>[A-Z])\\]) ?")
val moveCrateCommandLineRegex = Regex("^move (\\d+) from (\\d+) to (\\d+)$")
fun <T> List<T>.splitBy(element: T): List<List<T>> {
var list = this
val listOfList = mutableListOf<List<T>>()
do {
val index = list.indexOf(element)
if (index == -1) {
listOfList.add(list)
} else {
listOfList.add(list.subList(0, index))
list = list.subList(index + 1, list.size)
}
} while (index != -1)
return listOfList
}
fun parseInput(input: List<String>): Pair<Stacks, List<MoveCratesCommand>> {
val stacksAndCommands = input.splitBy("")
val stacks = stacksAndCommands[0].last().split(" ").map { s -> Stack(s.trim().toInt(), listOf()) }
stacksAndCommands[0].subList(0, stacksAndCommands[0].size - 1)
.map { l -> crateLineRegex.findAll(l).map { m -> m.groups["crate"]?.value } }
.forEach { s -> s.forEachIndexed { index, crate -> if (crate != null) stacks[index].addBottom(crate) }}
val commands = stacksAndCommands[1].map { l -> moveCrateCommandLineRegex.matchEntire(l)!! }
.map { m ->
MoveCratesCommand(
m.groupValues[1].toInt(),
m.groupValues[2].toInt(),
m.groupValues[3].toInt()
)
}
return Pair(Stacks.of(stacks), commands)
}
fun part1(input: Pair<Stacks, List<MoveCratesCommand>>): String {
input.second.forEach{ input.first.handle(it, Stack::withdraw)}
return input.first.stacks.values.map { it.top() }.joinToString(separator = "")
}
fun part2(input: Pair<Stacks, List<MoveCratesCommand>>): String {
input.second.forEach{ input.first.handle(it, Stack::withdraw9001)}
return input.first.stacks.values.map { it.top() }.joinToString(separator = "") }
// test if implementation meets criteria from the description, like:
val testInput = parseInput(readInput("day05/Day05_test"))
println("Parsed test input: $testInput")
assertThat(part1(testInput), "CMZ")
assertThat(part2(parseInput(readInput("day05/Day05_test"))), "MCD")
println(part1(parseInput(readInput("day05/Day05"))))
println(part2(parseInput(readInput("day05/Day05"))))
} | 0 | Kotlin | 0 | 0 | 1e927c95191a154efc0fe91a7b89d8ff526125eb | 2,471 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/anahoret/aoc2022/day11/main.kt | mikhalchenko-alexander | 584,735,440 | false | null | package com.anahoret.aoc2022.day11
import java.io.File
import java.lang.IllegalArgumentException
import kotlin.math.floor
class Monkey(
startingItems: List<Long>,
val testNumber: Long,
private val operation: (Long) -> Long,
private val throwMap: Map<Boolean, Int>
) {
var inspectCount = 0L
private set
private val items = startingItems.toMutableList()
fun hasItems(): Boolean {
return items.isNotEmpty()
}
fun inspectNextAndThrow(newCalculator: (Long) -> Long, targetMonkeyGetter: (Int) -> Monkey) {
inspectCount++
val old = items.removeAt(0)
val new = newCalculator(operation(old))
val targetMonkeyIdx = throwMap.getValue(new % testNumber == 0L)
targetMonkeyGetter(targetMonkeyIdx).items.add(new)
}
companion object {
fun parse(str: String): Monkey {
val lines = str.lines()
val startingItems = lines[1].split(": ")[1]
.split(", ")
.map(String::toLong)
val operation = lines[2].takeLastWhile { it != '=' }.trim().split(" ")
.let { (a, o, b) ->
{ old: Long ->
val operand1 = if (a == "old") old else a.toLong()
val operand2 = if (b == "old") old else b.toLong()
val operation: (Long, Long) -> Long = when (o) {
"+" -> Long::plus
"*" -> Long::times
else -> throw IllegalArgumentException("Unknown operation: $o")
}
operation(operand1, operand2)
}
}
val testNumber = lines[3].takeLastWhile { it != ' ' }.toLong()
val throwIfTrue = lines[4].takeLastWhile { it != ' ' }.toInt()
val throwIfFalse = lines[5].takeLastWhile { it != ' ' }.toInt()
val throwMap = mapOf(true to throwIfTrue, false to throwIfFalse)
return Monkey(startingItems, testNumber, operation, throwMap)
}
}
}
fun main() {
val input = File("src/main/kotlin/com/anahoret/aoc2022/day11/input.txt")
.readText()
.trim()
.split("\n\n")
// Part 1
part1(input.map(Monkey.Companion::parse))
// Part 2
part2(input.map(Monkey.Companion::parse))
}
private fun part1(monkeys: List<Monkey>) {
playMonkeyInTheMiddle(monkeys, 20) { new -> floor(new / 3.0).toLong() }
}
private fun part2(monkeys: List<Monkey>) {
val testNumbersProduct = monkeys.fold(1L) { acc, m -> acc * m.testNumber }
playMonkeyInTheMiddle(monkeys, 10000) { new -> new % testNumbersProduct }
}
fun playMonkeyInTheMiddle(
monkeys: List<Monkey>,
rounds: Int,
newItemValueMapper: (Long) -> Long
) {
repeat(rounds) {
monkeys.forEach { monkey ->
while (monkey.hasItems()) {
monkey.inspectNextAndThrow(newItemValueMapper, monkeys::get)
}
}
}
monkeys
.map(Monkey::inspectCount)
.sorted()
.takeLast(2)
.reduce(Long::times)
.let(::println)
}
| 0 | Kotlin | 0 | 0 | b8f30b055f8ca9360faf0baf854e4a3f31615081 | 3,163 | advent-of-code-2022 | Apache License 2.0 |
src/Day13.kt | maciekbartczak | 573,160,363 | false | {"Kotlin": 41932} | // tbh I gave up on this one, solution heavily based on:
// https://github.com/ash42/adventofcode/tree/main/adventofcode2022/src/nl/michielgraat/adventofcode2022/day13
import kotlin.math.min
fun main() {
fun part1(input: List<String>): Int {
return input
.chunked(3)
.map {
(first, second, _) -> Packet(first) to Packet(second)
}.mapIndexed { index, pair ->
var result = 0
if (pair.first < pair.second) {
result = index + 1
}
result
}.sum()
}
fun part2(input: List<String>): Int {
val dividerPackets = listOf(
"[[2]]",
"[[6]]",
""
)
val combinedInput = input + dividerPackets
val packets = combinedInput
.filter { it.isNotEmpty() }
.map { Packet(it) }
.sorted()
val firstDividerIndex = packets.indexOfFirst { it.content == "[[2]]" }
val secondDividerIndex = packets.indexOfFirst { it.content == "[[6]]" }
return (firstDividerIndex + 1) * (secondDividerIndex + 1)
}
val testInput = readInput("Day13_test")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
private class Packet(
input: String,
): Comparable<Packet> {
private var value = 0
private var isList = false
private val childPackets = mutableListOf<Packet>()
val content: String
init {
content = input
if (!input.startsWith('[')) {
value = input.toInt()
} else {
parseList(input)
}
}
private fun parseList(input: String) {
isList = true
val packetContent = input.substring(1, input.length - 1)
var depth = 0
val currentPacket = StringBuilder()
packetContent.forEach {
// [1],[2,3,4]
if (it == ',' && depth == 0) {
childPackets.add(Packet(currentPacket.toString()))
currentPacket.clear()
} else {
when (it) {
'[' -> depth++
']' -> depth--
}
currentPacket.append(it)
}
}
if (currentPacket.isNotEmpty()) {
childPackets.add(Packet(currentPacket.toString()))
}
}
override fun compareTo(other: Packet): Int {
if (!this.isList && !other.isList) {
return this.value.compareTo(other.value)
}
if (this.isList && other.isList) {
val myChildrenSize = this.childPackets.size
val otherChildrenSize = other.childPackets.size
for (i in 0 until min(myChildrenSize, otherChildrenSize)) {
val result = this.childPackets[i].compareTo(other.childPackets[i])
if (result != 0) {
return result
}
}
return myChildrenSize.compareTo(otherChildrenSize)
}
if (this.isList && !other.isList) {
return this.compareTo(Packet("[${other.value}]"))
}
return Packet("[${this.value}]").compareTo(other)
}
} | 0 | Kotlin | 0 | 0 | 53c83d9eb49d126e91f3768140476a52ba4cd4f8 | 3,303 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/Blizzards.kt | alebedev | 573,733,821 | false | {"Kotlin": 82424} | import java.util.*
import kotlin.math.abs
fun main() = Blizzards.solve()
private object Blizzards {
fun solve() {
var board = readInput()
val start = Pos(1, 0)
val target = Pos(board.cells.last().indexOfFirst { it is Space }, board.cells.size - 1)
val initialPath = Path(
start,
target,
0
)
val bestFwd = findPath(initialPath, board)
println("Best path S->F takes $bestFwd steps")
(1..bestFwd).forEach { board = board.next() }
val backPath = Path(target, start, 0)
val bestBack = findPath(backPath, board)
println("Best path F->S takes $bestBack steps")
(1..bestBack).forEach { board = board.next() }
val bestBackAgain = findPath(initialPath, board)
println("Best path S->F (again) takes $bestBackAgain steps")
println("Total: ${bestFwd + bestBack + bestBackAgain}")
}
private fun findPath(initialPath: Path, initialBoard: Board): Int {
val boards = mutableListOf(initialBoard)
val queue = PriorityQueue<Path>()
val visited = mutableSetOf<Path>()
queue.add(initialPath)
while (queue.isNotEmpty()) {
val path = queue.remove()
if (path.pos == path.target) {
return path.turn
}
if (path in visited) continue
else visited.add(path)
val nextTurn = path.turn + 1
// println("$nextTurn $path")
if (boards.size == nextTurn) {
boards.add(boards.last().next())
}
val nextBoard = boards[nextTurn]
val nextPositions = listOf(
path.pos,
Pos(path.pos.x - 1, path.pos.y), Pos(path.pos.x + 1, path.pos.y),
Pos(path.pos.x, path.pos.y - 1), Pos(path.pos.x, path.pos.y + 1)
).filter { pos ->
(nextBoard.cells.getOrNull(pos.y)?.getOrNull(pos.x) as? Space)?.winds?.isEmpty() ?: false
}
nextPositions.forEach { pos ->
queue.add(Path(pos, path.target, nextTurn))
}
}
return -1
}
private fun readInput(): Board {
val cells = generateSequence(::readLine).map { line ->
line.toCharArray().map { char ->
when (char) {
'#' -> Wall
'.' -> Space(mutableListOf())
'^' -> Space(mutableListOf(Wind.North))
'>' -> Space(mutableListOf(Wind.East))
'<' -> Space(mutableListOf(Wind.West))
'v' -> Space(mutableListOf(Wind.South))
else -> throw Error("Failed to parse char $char")
}
}
}.toList()
return Board(cells)
}
data class Board(val cells: List<List<Cell>>) {
fun visualize() {
for (line in cells) {
for (cell in line) {
val char = when (cell) {
Wall -> '#'
is Space -> {
if (cell.winds.isEmpty()) {
'.'
} else if (cell.winds.size == 1) {
when (cell.winds.first()) {
Wind.North -> '^'
Wind.East -> '>'
Wind.South -> 'v'
Wind.West -> '<'
}
} else {
cell.winds.size
}
}
}
print(char)
}
println()
}
println()
}
fun next(): Board {
val nextCells = cells.map {
it.map { cell ->
when (cell) {
Wall -> Wall
is Space -> Space(mutableListOf())
}
}
}
cells.forEachIndexed { y, line ->
line.forEachIndexed { x, cell ->
when (cell) {
Wall -> {}
is Space -> {
cell.winds.forEach { wind ->
val nextPos = nextWindPos(wind, Pos(x, y))
val nextCell = nextCells[nextPos.y][nextPos.x]
require(nextCell is Space)
nextCell.winds.add(wind)
}
}
}
}
}
return Board(nextCells)
}
private fun nextWindPos(wind: Wind, pos: Pos): Pos {
var nextX = pos.x + wind.dx
var nextY = pos.y + wind.dy
// Simplified wrapping, assumes walls are always in outer row
if (nextX == 0) {
nextX = width() - 2
} else if (nextX >= width() - 1) {
nextX = 1
}
if (nextY == 0) {
nextY = height() - 2
} else if (nextY >= height() - 1) {
nextY = 1
}
return Pos(nextX, nextY)
}
private fun width(): Int = cells.first().size
private fun height(): Int = cells.size
}
sealed interface Cell
object Wall : Cell
data class Space(val winds: MutableList<Wind>) : Cell
enum class Wind(val dx: Int, val dy: Int) {
West(-1, 0),
North(0, -1),
East(1, 0),
South(0, 1)
}
data class Pos(val x: Int, val y: Int)
data class Path(val pos: Pos, val target: Pos, val turn: Int) : Comparable<Path> {
override fun compareTo(other: Path): Int = minTurnsToTarget().compareTo(other.minTurnsToTarget())
private fun minTurnsToTarget() = abs(target.x - pos.x) + abs(target.y - pos.y) + turn
}
} | 0 | Kotlin | 0 | 0 | d6ba46bc414c6a55a1093f46a6f97510df399cd1 | 6,086 | aoc2022 | MIT License |
src/main/kotlin/days/aoc2021/Day5.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2021
import days.Day
import java.lang.Integer.max
import kotlin.math.absoluteValue
import kotlin.math.min
class Day5 : Day(2021, 5) {
override fun partOne(): Any {
return calculateMostDangerousPoints(createMapWithNonDiagonals(inputList))
}
override fun partTwo(): Any {
return calculateMostDangerousPoints(createMapIncludingDiagonals(inputList))
}
private fun findExtentsOfMap(input: List<String>): Pair<Int,Int> {
return input.fold(Pair(0,0)) { acc, s ->
Regex("(\\d+),(\\d+) -> (\\d+),(\\d+)").matchEntire(s)?.destructured?.let { (x1,y1,x2,y2) ->
Pair(maxOf(acc.first, x1.toInt(), x2.toInt()), maxOf(acc.second, y1.toInt(), y2.toInt()))
} ?: acc
}
}
fun createMapWithNonDiagonals(input: List<String>): Array<Array<Int>> {
val extents = findExtentsOfMap(input)
val map = Array(extents.first + 1) {
Array(extents.second + 1) { 0 }
}
input.mapNotNull { line ->
Regex("(\\d+),(\\d+) -> (\\d+),(\\d+)").matchEntire(line)?.destructured?.let { (x1, y1, x2, y2) ->
Pair(Pair(x1.toInt(), y1.toInt()), Pair(x2.toInt(), y2.toInt()))
}
}.filter {
it.first.first == it.second.first || it.first.second == it.second.second
}.forEach {
for (x in min(it.first.first,it.second.first).rangeTo(max(it.first.first,it.second.first))) {
for (y in min(it.first.second,it.second.second).rangeTo(max(it.first.second,it.second.second))) {
map[x][y]++
}
}
}
return map
}
fun createMapIncludingDiagonals(input: List<String>): Array<Array<Int>> {
val extents = findExtentsOfMap(input)
val map = Array(extents.first + 1) {
Array(extents.second + 1) { 0 }
}
input.mapNotNull { line ->
Regex("(\\d+),(\\d+) -> (\\d+),(\\d+)").matchEntire(line.trim())?.destructured?.let { (x1, y1, x2, y2) ->
Pair(Pair(x1.toInt(), y1.toInt()), Pair(x2.toInt(), y2.toInt()))
}
}.forEach {
if (it.first.first == it.second.first || it.first.second == it.second.second) {
for (x in min(it.first.first,it.second.first).rangeTo(max(it.first.first,it.second.first))) {
for (y in min(it.first.second,it.second.second).rangeTo(max(it.first.second,it.second.second))) {
map[x][y]++
}
}
} else {
val steps = (it.first.first - it.second.first).absoluteValue
val deltaX = if (it.first.first < it.second.first) 1 else -1
val deltaY = if (it.first.second < it.second.second) 1 else -1
var x = it.first.first
var y = it.first.second
for (i in 0..steps) {
map[x][y]++
x += deltaX
y += deltaY
}
}
}
return map
}
fun printMap(map:Array<Array<Int>>) {
for (y in map.indices) {
for (x in map[y].indices)
print(if (map[x][y] == 0) '.' else map[x][y])
println()
}
}
fun calculateMostDangerousPoints(map: Array<Array<Int>>): Int {
return map.sumBy { it.sumBy { dangerLevel -> if (dangerLevel >= 2) 1 else 0 } }
}
} | 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 3,479 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
src/Day03.kt | azat-ismagilov | 573,217,326 | false | {"Kotlin": 75114} | fun main() {
fun Char.toNumber(): Int = when (this) {
in 'a' .. 'z' -> this - 'a' + 1
in 'A' .. 'Z' -> this - 'A' + 27
else -> 0
}
fun calcPrice(left: String, right: String) = left.toSet().intersect(right.toSet()).sumOf { it.toNumber() }
fun part1(input: List<String>): Int = input.sumOf { calcPrice(it.take(it.length / 2), it.drop(it.length / 2)) }
fun solvePart2(line: List<Set<Char>>): Int = line[0].intersect(line[1]).intersect(line[2]).sumOf { it.toNumber() }
fun part2(input: List<String>): Int = input.chunked(3).sumOf { solvePart2(it.map { it.toSet() }) }
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | abdd1b8d93b8afb3372cfed23547ec5a8b8298aa | 898 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day03.kt | MatthiasDruwe | 571,730,990 | false | {"Kotlin": 47864} |
fun main() {
fun part1(input: List<String>): Int {
val output = input.mapNotNull {
var x: Char? = null
it.substring(0, it.length / 2).forEach { char ->
if (it.substring(it.length / 2).contains(char)) {
x = char
}
}
x
}.sumOf {
if (it.isLowerCase()) {
it - 'a' + 1
} else {
it - 'A' + 27
}
}
return output
}
fun part2(input: List<String>): Int {
val output = input.withIndex().groupBy { it.index / 3 }.mapNotNull {
var x: Char? = null
it.value[0].value.forEach { char ->
if (it.value[1].value.contains(char) && it.value[2].value.contains(char)) {
x = char
}
}
x
}.sumOf {
if (it.isLowerCase()) {
it - 'a' + 1
} else {
it - 'A' + 27
}
}
return output
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_example")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f35f01cea5075cfe7b4a1ead9b6480ffa57b4989 | 1,432 | Advent-of-code-2022 | Apache License 2.0 |
src/Day04.kt | cnietoc | 572,880,374 | false | {"Kotlin": 15990} | fun main() {
fun getPairsFrom(input: List<String>) = input.map { line ->
line.split(",").map { rangeRaw ->
rangeRaw.split("-").let { IntRange(it.first().toInt(), it.last().toInt()) }
}.let {
PairOfRanges(it.first(), it.last())
}
}
fun part1(input: List<String>): Int {
return getPairsFrom(input).count { it.isFullyOverlapped() }
}
fun part2(input: List<String>): Int {
return getPairsFrom(input).count { it.isOverlapped() }
}
val testInput = readInput("Day04_test")
val input = readInput("Day04")
check(part1(testInput) == 2)
println(part1(input))
check(part2(testInput) == 4)
println(part2(input))
}
class PairOfRanges(private val firstRange: IntRange, private val secondRange: IntRange) {
fun isFullyOverlapped() =
firstRange.subtract(secondRange).isEmpty() || secondRange.subtract(firstRange).isEmpty()
fun isOverlapped() = firstRange.intersect(secondRange).isNotEmpty()
}
| 0 | Kotlin | 0 | 0 | bbd8e81751b96b37d9fe48a54e5f4b3a0bab5da3 | 1,012 | aoc-2022 | Apache License 2.0 |
src/Day02.kt | wmichaelshirk | 573,031,182 | false | {"Kotlin": 19037} |
val scores2 = mapOf<String, Int>(
"A X" to 3, // Lose = 0, Scissors = 3
"A Y" to 4, // Draw = 3, Rock = 1
"A Z" to 8, // Win = 6, Paper = 2
"B X" to 1, // Lose = 0, Rock = 1
"B Y" to 5, // Draw = 3, Paper = 2
"B Z" to 9, // Win = 6, Scissors = 3
"C X" to 2, // Lose = 0, Paper = 2,
"C Y" to 6, // Draw = 3, Scissors = 3
"C Z" to 7, // Win = 6, Rock = 1
)
val scores = mapOf<String, Int>(
"A X" to 4, // Rock = 1, Draw = 3
"A Y" to 8, // Paper = 2, Win = 6
"A Z" to 3, // Scissors = 3, Loss = 0
"B X" to 1, // Rock = 1, Loss = 0
"B Y" to 5, // Paper = 2, Draw = 3
"B Z" to 9, // Scissors = 3, Win = 6
"C X" to 7, // Rock = 1, Win = 6
"C Y" to 2, // Paper = 2, Loss = 0
"C Z" to 6, // Scissors = 3, Draw = 3
)
fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { scores.getOrDefault(it, 0) }
}
fun part2(input: List<String>): Int {
return input.sumOf { scores2.getOrDefault(it, 0) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | b748c43e9af05b9afc902d0005d3ba219be7ade2 | 1,285 | 2022-Advent-of-Code | Apache License 2.0 |
src/Day01.kt | Yasenia | 575,276,480 | false | {"Kotlin": 15232} | fun main() {
fun part1(input: List<String>): Int {
var currentCalories = 0
var mostCalories = 0
for ((i, line) in input.withIndex()) {
if (line.isNotBlank()) currentCalories += line.toInt()
if (line.isBlank() || i == input.lastIndex) {
mostCalories = mostCalories.coerceAtLeast(currentCalories)
currentCalories = 0
}
}
return mostCalories
}
fun part2(input: List<String>): Int {
var currentCalories = 0
val mostCaloriesList = mutableListOf(0, 0, 0)
for ((i, line) in input.withIndex()) {
if (line.isNotBlank()) currentCalories += line.toInt()
if (line.isBlank() || i == input.lastIndex) {
for (j in mostCaloriesList.indices) {
if (currentCalories < mostCaloriesList[j]) continue
for (k in mostCaloriesList.lastIndex downTo j + 1) mostCaloriesList[k] = mostCaloriesList[k - 1]
mostCaloriesList[j] = currentCalories
break
}
currentCalories = 0
}
}
return mostCaloriesList.sum()
}
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 9300236fa8697530a3c234e9cb39acfb81f913ba | 1,416 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaximumSubsequenceScore.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.PriorityQueue
import kotlin.math.max
/**
* 2542. Maximum Subsequence Score
* @see <a href="https://leetcode.com/problems/maximum-subsequence-score/">Source</a>
*/
fun interface MaximumSubsequenceScore {
fun maxScore(nums1: IntArray, nums2: IntArray, k: Int): Long
}
/**
* Approach: Priority Queue
*/
class MaximumSubsequenceScorePQ : MaximumSubsequenceScore {
override fun maxScore(nums1: IntArray, nums2: IntArray, k: Int): Long {
// Sort pair (nums1[i], nums2[i]) by nums2[i] in decreasing order.
val n: Int = nums1.size
val pairs = Array(n) { IntArray(2) }
for (i in 0 until n) {
pairs[i] = intArrayOf(nums1[i], nums2[i])
}
pairs.sortWith { a: IntArray, b: IntArray -> b[1] - a[1] }
// Use a min-heap to maintain the top k elements.
val topKHeap: PriorityQueue<Int> = PriorityQueue(k) { a, b -> a - b }
var topKSum: Long = 0
for (i in 0 until k) {
topKSum += pairs[i][0].toLong()
topKHeap.add(pairs[i][0])
}
// The score of the first k pairs.
var answer = topKSum * pairs[k - 1][1]
// Iterate over every nums2[i] as minimum from nums2.
for (i in k until n) {
// Remove the smallest integer from the previous top k elements
// then ddd nums1[i] to the top k elements.
topKSum += pairs[i][0] - topKHeap.poll()
topKHeap.add(pairs[i][0])
// Update answer as the maximum score.
answer = max(answer, topKSum * pairs[i][1])
}
return answer
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,267 | kotlab | Apache License 2.0 |
src/Day04.kt | lassebe | 573,423,378 | false | {"Kotlin": 33148} | fun main() {
fun solve(input: List<String>, predicate: (a: Int, b: Int, c: Int, d: Int) -> Boolean): Int {
return input.sumOf { schedule ->
val assignments = schedule.split(",")
val elf1 = assignments.first().split("-").map { it.toInt() }
val elf2 = assignments.last().split("-").map { it.toInt() }
if (predicate(elf1[0], elf1[1], elf2[0], elf2[1]))
return@sumOf 1.toInt() // Compiler silliness
return@sumOf 0
}
}
fun part1(input: List<String>) =
solve(input) { a, b, c, d -> a >= c && b <= d || c >= a && d <= b }
fun part2(input: List<String>) =
solve(input) { a, b, c, d -> !(a < c && b < c || a > d) }
val testInput = readInput("Day04_test")
println(part1(testInput))
check(part1(testInput) == 2)
val input = readInput("Day04")
println(part1(input))
check(part2(testInput) == 4)
println(part2(input))
} | 0 | Kotlin | 0 | 0 | c3157c2d66a098598a6b19fd3a2b18a6bae95f0c | 966 | advent_of_code_2022 | Apache License 2.0 |
src/main/kotlin/y2023/day11/Day11.kt | niedrist | 726,105,019 | false | {"Kotlin": 19919} | package y2023.day11
import BasicDay
import util.FileReader
import util.pairs
import kotlin.math.max
import kotlin.math.min
val d = FileReader.asStrings("2023/day11.txt").map { it.toCharArray().toList() }
fun main() = Day11.run()
object Day11 : BasicDay() {
override fun part1() = solve(1)
override fun part2() = solve(1000000)
private fun solve(distanceToExpand: Int): Long {
val galaxies = mutableListOf<Point>()
d.forEachIndexed { rowIndex, row ->
row.forEachIndexed { columnIndex, galaxy ->
if (galaxy == '#')
galaxies.add(Point(columnIndex, rowIndex))
}
}
val allPairs = galaxies.pairs()
val indicesX = d.indicesToExpandHorizontally()
val indicesY = d.indicesToExpandVertically()
return allPairs.sumOf { it.distance(indicesX, indicesY, distanceToExpand) }
}
}
private fun List<List<Char>>.indicesToExpandVertically(): List<Int> {
val matchingRows = mutableListOf<Int>()
this.forEachIndexed { rowIndex, chars ->
if (chars.all { it == '.' })
matchingRows.add(rowIndex)
}
return matchingRows
}
private fun List<List<Char>>.indicesToExpandHorizontally(): List<Int> {
val emptySpaceCounterPerColumn = mutableMapOf<Int, Int>()
this.forEach { chars ->
chars.forEachIndexed { columnIndex, char ->
if (char == '.')
emptySpaceCounterPerColumn[columnIndex] = emptySpaceCounterPerColumn[columnIndex]?.let { it + 1 }?: 1
}
}
return emptySpaceCounterPerColumn.filter { it.value == this.size }.keys.toList()
}
private data class Point(val x: Int, val y: Int)
private fun Pair<Point, Point>.distance(indicesX: List<Int>, indicesY: List<Int>, distanceToExpand: Int): Long {
var distance = 0L
val lowerX = min(this.first.x, this.second.x)
val higherX = max(this.first.x, this.second.x)
val lowerY = min(this.first.y, this.second.y)
val higherY = max(this.first.y, this.second.y)
for (x in lowerX until higherX)
distance += if(x in indicesX) distanceToExpand else 1
for (y in lowerY until higherY)
distance += if(y in indicesY) distanceToExpand else 1
return distance
} | 0 | Kotlin | 0 | 1 | 37e38176d0ee52bef05f093b73b74e47b9011e24 | 2,238 | advent-of-code | Apache License 2.0 |
src/Day03.kt | remidu | 573,452,090 | false | {"Kotlin": 22113} | fun main() {
fun duplicate(list1: List<Char>, list2: List<Char>): Char {
for (char in list1) {
if (list2.contains(char)) return char
}
return 'a' // should never happen
}
fun duplicate(list1: List<Char>, list2: List<Char>, list3: List<Char>): Char {
for (char in list1) {
if (list2.contains(char) && list3.contains(char)) return char
}
return 'a' // should never happen
}
fun priority(letter: Char): Int {
val ascii = letter.code
if (ascii <= 90) return ascii-38
else return ascii-96
}
fun part1(input: List<String>): Int {
var total = 0
for (line in input) {
val chars = line.toList()
val duplicate = duplicate(chars.subList(0, chars.size/2), chars.subList(chars.size/2, chars.size))
total += priority(duplicate)
}
return total
}
fun part2(input: List<String>): Int {
var total = 0
for (i in input.indices step 3) {
val duplicate = duplicate(input[i].toList(), input[i+1].toList(), input[i+2].toList())
total += priority(duplicate)
}
return total
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ecda4e162ab8f1d46be1ce4b1b9a75bb901bc106 | 1,492 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | monsterbrain | 572,819,542 | false | {"Kotlin": 42040} | fun main() {
fun String.firstHalf(): String {
return substring(0 until length/2)
}
fun String.secondHalf(): String {
return substring(length/2 until length)
}
fun findCommon(firstHalf: String, secondHalf: String): Char {
firstHalf.forEach {
if (secondHalf.contains(it)) {
return it
}
}
return ' '
}
fun Char.priority(): Int {
return when (this) {
in 'a'..'z' -> {
(code - 'a'.code) + 1
}
in 'A'..'Z' -> {
(code - 'A'.code) + 27
}
else -> TODO()
}
}
fun part1(input: List<String>): Int {
var prioritySum = 0
input.forEach {
val firstHalf = it.firstHalf()
val secondHalf = it.secondHalf()
val common = findCommon(firstHalf, secondHalf)
prioritySum += common.priority()
}
return prioritySum
}
fun findIn(input: String, second: String, third: String): Char {
input.forEach {
if(second.contains(it) && third.contains(it)) {
return it
}
}
TODO()
}
fun part2(input: List<String>): Int {
var prioritySum = 0
input.chunked(3) {
val common = findIn(it[0], it[1], it[2])
// println("common $common")
prioritySum += common.priority()
}
return prioritySum
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 3a1e8615453dd54ca7c4312417afaa45379ecf6b | 1,751 | advent-of-code-kotlin-2022-Solutions | Apache License 2.0 |
solutions/aockt/y2021/Y2021D04.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2021
import io.github.jadarma.aockt.core.Solution
object Y2021D04 : Solution {
/**
* A 5x5 BingoBoard.
* @constructor Sets up a new bingo board with these 25 numbers, from left to right, top to bottom.
*/
private class BingoBoard(numbers: List<Int>) {
private val grid: List<BingoSquare> = numbers.map { BingoSquare(it, false) }
init {
require(numbers.size == 25) { "A bingo board has exactly 25 numbers on it." }
}
/** Simple holder for a square and its state. */
private class BingoSquare(val number: Int, var isSet: Boolean = false)
/** If the [number] appears on the board, marks it, and returns if the board is now in BINGO! */
fun callAndCheck(number: Int): Boolean {
grid.firstOrNull { it.number == number }?.apply { isSet = true }
return isBingo()
}
/** Checks if the board is in BINGO! */
fun isBingo(): Boolean {
for (x in 0..4) {
var horizontalBingo = 0
var verticalBingo = 0
for (y in 0..4) {
if (grid[x * 5 + y].isSet) horizontalBingo++
if (grid[y * 5 + x].isSet) verticalBingo++
}
if (horizontalBingo == 5 || verticalBingo == 5) return true
}
return false
}
/** Returns the sum of all the numbers that have not been marked on this board. */
fun sumOfUnsetNumbers(): Int = grid.filterNot { it.isSet }.sumOf { it.number }
}
/** Parses the input and returns the list of numbers to be played and all the available [BingoBoard]s. */
private fun parseInput(input: String): Pair<List<Int>, List<BingoBoard>> = runCatching {
val lines = input.lines().filterNot { it.isBlank() }
val numbers = lines.first().split(",").map { it.toInt() }
val bingoBoards = lines
.drop(1).chunked(5)
.map { rows -> rows.flatMap { row -> row.trim().split(Regex("""\s+""")).map(String::toInt) } }
.map(::BingoBoard)
numbers to bingoBoards
}.getOrElse { throw IllegalArgumentException("Invalid input.") }
override fun partOne(input: String): Any {
val (numbers, boards) = parseInput(input)
numbers.forEach { number ->
val bingo = boards.firstOrNull { it.callAndCheck(number) }
if (bingo != null) {
return bingo.sumOfUnsetNumbers() * number
}
}
error("No winning board found.")
}
override fun partTwo(input: String): Any {
val (numbers, boards) = parseInput(input)
val candidates = boards.toMutableList()
numbers.forEach { number ->
while (true) {
val board = candidates.firstOrNull { it.callAndCheck(number) } ?: break
candidates.remove(board)
if (candidates.isEmpty()) return board.sumOfUnsetNumbers() * number
}
}
error("There is a tie for which board wins last.")
}
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 3,096 | advent-of-code-kotlin-solutions | The Unlicense |
src/day21/day21.kt | kacperhreniak | 572,835,614 | false | {"Kotlin": 85244} | package day21
import readInput
private fun parse(input: List<String>): Map<String, Operation> {
return input.associate {
val parts = it.split(": ")
val key = parts[0]
val operation = if (parts[1].contains(" + ")) {
val items = parts[1].split(" + ")
Operation.Add(items[0], items[1])
} else if (parts[1].contains(" - ")) {
val items = parts[1].split(" - ")
Operation.Subtract(items[0], items[1])
} else if (parts[1].contains(" / ")) {
val items = parts[1].split(" / ")
Operation.Divide(items[0], items[1])
} else if (parts[1].contains(" * ")) {
val items = parts[1].split(" * ")
Operation.Multiply(items[0], items[1])
} else Operation.Yell(parts[1].toLong())
key to operation
}
}
private fun findNumber(
data: Map<String, Operation>,
key: String
): Long {
return when (val operation = data[key]!!) {
is Operation.Yell -> operation.item
is Operation.Subtract -> {
findNumber(data, operation.first) - findNumber(data, operation.second)
}
is Operation.Add -> {
findNumber(data, operation.first) + findNumber(data, operation.second)
}
is Operation.Divide -> {
findNumber(data, operation.first) / findNumber(data, operation.second)
}
is Operation.Multiply -> {
findNumber(data, operation.first) * findNumber(data, operation.second)
}
}
}
private const val START_KEY = "root"
private fun part1(input: List<String>): Long {
val data = parse(input)
return findNumber(data, START_KEY)
}
private fun findPath(key: String, point: String, data: Map<String, Operation>, path: List<String>): List<String>? {
if (key == point) return path + key
val temp = data[point]
if (temp !is Operation.MathOperation) return null
val newpPath = path + point
return findPath(key, temp.first, data, newpPath)
?: findPath(key, temp.second, data, newpPath)
}
private const val KEY_TO_HANDLE = "humn"
private fun part2(input: List<String>): Long {
fun findNewValue(operation: Operation.MathOperation, isFirst: Boolean, result: Long, second: Long) = when (operation) {
is Operation.Add -> result - second
is Operation.Multiply -> result / second
is Operation.Subtract -> if (isFirst) result + second else second - result
is Operation.Divide -> if (isFirst) result * second else result / second
}
val data = parse(input).toMutableMap()
val rootOperation = data[START_KEY] as Operation.MathOperation
val path = findPath(KEY_TO_HANDLE, rootOperation.first, data, listOf()).orEmpty()
var value = findNumber(data, rootOperation.second)
for ((index, key) in path.withIndex()) {
if (key == KEY_TO_HANDLE) return value
val operation = data[key] as Operation.MathOperation
val isFirst = operation.first == path[index + 1]
val second = if (isFirst) {
findNumber(data, operation.second)
} else findNumber(data, operation.first)
value = findNewValue(operation, isFirst, value, second)
}
return (data[KEY_TO_HANDLE] as Operation.Yell).item
}
sealed interface Operation {
data class Yell(val item: Long) : Operation
sealed interface MathOperation : Operation {
val first: String
val second: String
}
data class Add(override val first: String, override val second: String) : MathOperation
data class Subtract(override val first: String, override val second: String) : MathOperation
data class Multiply(override val first: String, override val second: String) : MathOperation
data class Divide(override val first: String, override val second: String) : MathOperation
}
fun main() {
val input = readInput("day21/input")
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
} | 0 | Kotlin | 1 | 0 | 03368ffeffa7690677c3099ec84f1c512e2f96eb | 4,000 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/staricka/adventofcode2023/days/Day2.kt | mathstar | 719,656,133 | false | {"Kotlin": 107115} | package com.staricka.adventofcode2023.days
import com.staricka.adventofcode2023.framework.Day
import java.util.regex.Pattern
import kotlin.math.max
class Day2: Day {
data class Game(val id: Int, val reveals: List<Reveal>) {
fun possible(counts: Map<String, Int>): Boolean =
reveals.all { it.possible(counts) }
fun minCounts(): Map<String, Int> {
val result = HashMap<String, Int>()
reveals.map(Reveal::minCounts).flatMap { it.entries }.forEach {(k,v) ->
result.compute(k) {_,existing -> max(v, existing ?: 0) }
}
return result
}
fun power(): Int {
return minCounts().values.reduce { acc, i -> acc * i}
}
companion object {
val gamePattern = Pattern.compile(
"Game (?<id>[0-9]+): (?<reveals>((?<reveal>((?<element>(?<count>[0-9]+) (?<color>[a-z]+)),? ?)+);? ?)+)"
)
fun fromString(input: String): Game {
val matcher = gamePattern.matcher(input)
matcher.find()
return Game(
matcher.group("id").toInt(),
matcher.group("reveals").split(";").map(Reveal::fromString)
)
}
}
}
data class Reveal(val elements: List<Element>) {
fun possible(counts: Map<String, Int>): Boolean =
elements.all { it.possible(counts) }
fun minCounts(): Map<String, Int> = elements.associate { it.color to it.count }
companion object {
val revealPattern = Pattern.compile(
"(?<reveal>((?<element>(?<count>[0-9]+) (?<color>[a-z]+)),? ?)+)"
)
fun fromString(input: String): Reveal {
val matcher = revealPattern.matcher(input)
matcher.find()
return Reveal(matcher.group().split(",").map(Element::fromString))
}
}
}
data class Element(val count: Int, val color: String) {
fun possible(counts: Map<String, Int>): Boolean =
(counts[color]?: 0) >= count
companion object {
val elementPattern = Pattern.compile(
"(?<element>(?<count>[0-9]+) (?<color>[a-z]+))"
)
fun fromString(input: String): Element {
val matcher = elementPattern.matcher(input)
matcher.find()
return Element(matcher.group("count").toInt(), matcher.group("color"))
}
}
}
override fun part1(input: String): Int {
return input.lines().filter(String::isNotBlank)
.map(Game::fromString)
.filter{
it.possible(mapOf(
"red" to 12,
"green" to 13,
"blue" to 14
))
}.sumOf { it.id }
}
override fun part2(input: String): Any? {
return input.lines().filter(String::isNotBlank)
.map(Game::fromString)
.sumOf(Game::power)
}
} | 0 | Kotlin | 0 | 0 | 8c1e3424bb5d58f6f590bf96335e4d8d89ae9ffa | 3,079 | adventOfCode2023 | MIT License |
kotlin/src/katas/kotlin/leetcode/common_parent/CommonParent.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.common_parent
fun main() {
val root = Node("A", Node("B"), Node("C"))
require(find(root, "B", "C")?.name == "A")
val root2 = Node("A",
Node("B",
Node("D"),
Node("E", Node("H"), Node("J"))),
Node("C",
Node("F"),
Node("G", null, Node("K")))
)
require(find(root2, "A", "A")?.name == "A")
require(find(root2, "K", "G")?.name == "C")
require(find(root2, "H", "G")?.name == "A")
require(find(root2, "G", "G")?.name == "C")
require(find(root2, "H", "K")?.name == "A")
require(find(root2, "F", "K")?.name == "C")
//require(find(root2, "X", "Y")?.name == null)
println("done")
}
private fun Node.traverse(path: List<Node> = emptyList(), f: (Node, List<Node>) -> Boolean) {
val shouldContinue = f(this, path)
if (!shouldContinue) return
left?.traverse(path + this, f)
right?.traverse(path + this, f)
}
private fun find(r: Node, c1: String, c2: String): Node? {
val noList = emptyList<Node>()
var c1Path: List<Node> = noList
var c2Path: List<Node> = noList
r.traverse { n, path ->
if (n.name == c1) c1Path = path
if (n.name == c2) c2Path = path
c1Path === noList || c2Path === noList
}
//if (c1Path === noList || c2Path === noList) return null
val minSize = minOf(c1Path.size, c2Path.size)
if (minSize <= 1) return r
c1Path = c1Path.take(minSize)
c2Path = c2Path.take(minSize)
var i = 0
while (i <= minSize - 2) {
if (c1Path[i] == c2Path[i] && c1Path[i + 1] != c2Path[i + 1]) break
i++
}
return c1Path[i]
}
private data class Node(
val name: String,
val left: Node? = null,
val right: Node? = null
)
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 1,767 | katas | The Unlicense |
src/main/kotlin/io/github/clechasseur/adventofcode/y2022/Day8.kt | clechasseur | 567,968,171 | false | {"Kotlin": 493887} | package io.github.clechasseur.adventofcode.y2022
import io.github.clechasseur.adventofcode.util.Direction
import io.github.clechasseur.adventofcode.util.Pt
import io.github.clechasseur.adventofcode.y2022.data.Day8Data
object Day8 {
private val input = Day8Data.input
fun part1(): Int {
val grid = input.toGrid()
return (0 until grid.height).flatMap { y ->
(0 until grid.width).map { x -> Pt(x, y) }
}.count { grid.visible(it) }
}
fun part2(): Int {
val grid = input.toGrid()
return (0 until grid.height).flatMap { y ->
(0 until grid.width).map { x -> Pt(x, y) }
}.maxOf { grid.viewingDistance(it) }
}
private class Grid(val trees: List<List<Int>>) {
val height: Int
get() = trees.size
val width: Int
get() = trees.first().size
fun validTree(tree: Pt): Boolean = (tree.x in 0 until width) && (tree.y in 0 until height)
fun treeHeight(pt: Pt): Int = trees[pt.y][pt.x]
fun visible(tree: Pt, direction: Direction): Boolean = generateSequence(tree) {
it + direction.displacement
}.drop(1).takeWhile { validTree(it) }.all { treeHeight(it) < treeHeight(tree) }
fun visible(tree: Pt): Boolean = Direction.values().any { visible(tree, it) }
fun viewingDistance(tree: Pt, direction: Direction): Int = generateSequence(tree) {
it + direction.displacement
}.takeWhile {
validTree(it)
}.map {
treeHeight(it)
}.withIndex().windowed(2, 1).takeWhile { iHeights ->
iHeights.first().index == 0 || iHeights[0].value < treeHeight(tree)
}.count()
fun viewingDistance(tree: Pt): Int = Direction.values().fold(1) { acc, d ->
acc * viewingDistance(tree, d)
}
}
private fun String.toGrid(): Grid = Grid(lines().map { line ->
line.map { tree -> tree.toString().toInt() }
})
}
| 0 | Kotlin | 0 | 0 | 7ead7db6491d6fba2479cd604f684f0f8c1e450f | 1,986 | adventofcode2022 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/CollectApples.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
/**
* 1443. Minimum Time to Collect All Apples in a Tree
* @see <a href="https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/">Source</a>
*/
fun interface CollectApples {
fun minTime(n: Int, edges: Array<IntArray>, hasApple: List<Boolean>): Int
}
class CollectApplesDFS : CollectApples {
override fun minTime(n: Int, edges: Array<IntArray>, hasApple: List<Boolean>): Int {
val graph: Array<MutableList<Int>> = Array(n) { ArrayList() }
for (edge in edges) {
graph[edge[0]].add(edge[1])
graph[edge[1]].add(edge[0])
}
val visited = BooleanArray(n)
visited[0] = true
return dfs(graph, 0, hasApple, visited)
}
private fun dfs(graph: Array<MutableList<Int>>, curr: Int, hasApple: List<Boolean>, visited: BooleanArray): Int {
var res = 0
for (next in graph[curr]) {
if (visited[next]) continue
visited[next] = true
res += dfs(graph, next, hasApple, visited)
}
if ((res > 0 || hasApple[curr]) && curr != 0) {
res += 2
}
return res
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,785 | kotlab | Apache License 2.0 |
src/Day16.kt | astrofyz | 572,802,282 | false | {"Kotlin": 124466} | fun main(){
class Valve(var flow: Int, var next: List<String>)
fun parseInput(input: List<String>): MutableMap<String, Valve> {
val valves: MutableMap<String, Valve> = mutableMapOf()
for (line in input){
val name = line.split(" ")[1]
val flow = line.filter { it.isDigit() }.toInt()
val next = line.split("to")[1].filter { it.isUpperCase() }.chunked(2)
valves[name] = Valve(flow, next)
}
return valves
}
fun computeDistances(start: String, valves: MutableMap<String, Valve>): MutableMap<String, Int> {
val visitedPoints = mutableMapOf<String, Int>()
val distances = mutableMapOf<String, Int>()
var nextPoints = valves[start]?.next?.toMutableList()
var curPos = start
distances[curPos] = 0
while (true) {
if (nextPoints != null) {
for (point in nextPoints){
if (point in visitedPoints) {continue} else if (distances.getOrDefault(point, 100000) > distances.getOrDefault(curPos, 100000) + 1 ){
distances[point] = distances.getOrDefault(curPos, 100000) + 1
}
}
}
visitedPoints[curPos] = distances.getOrDefault(curPos, 100000)
if (visitedPoints.size == valves.size){break}
distances.remove(curPos)
if (distances.size == 0){break}
curPos = distances.filterValues { it == distances.values.min() }.keys.first()
nextPoints = valves[curPos]?.next?.toMutableList()
if (nextPoints != null) {
nextPoints = nextPoints.filter { it !in visitedPoints }.toMutableList()
}
}
visitedPoints.remove(start)
for (point in visitedPoints.keys.toList()){
if (valves[point]?.flow == 0) {visitedPoints.remove(point)}
else visitedPoints[point] = visitedPoints.getOrDefault(point, 0) + 1
}
return visitedPoints
}
fun part1(input: List<String>){
val valves = parseInput(input)
val reducedGraphs = mutableMapOf<String, MutableMap<String, Int>>()
valves.keys.forEach { reducedGraphs[it] = computeDistances(it, valves) }
val valvesOpened = mutableListOf<String>()
val pressureReleasedResult = mutableListOf<Int>()
fun trace(start: String, time: Int, valvesOpened: MutableList<String>, pressureReleased: Int): Int{
valvesOpened.add(start)
val result = mutableListOf<Int>()
if (time > 0){
for (nextValve in reducedGraphs[start]?.keys!!){
if (nextValve !in valvesOpened){
result.add(trace(nextValve, time- reducedGraphs[start]?.get(nextValve)!!, valvesOpened,
pressureReleased+(valves[start]?.flow ?: 0) *time))
}
}
}
if (result.isEmpty()) {
valvesOpened.remove(start)
pressureReleasedResult.add(pressureReleased+(valves[start]?.flow ?: 0) *time.coerceIn(0, 30))
return pressureReleased+(valves[start]?.flow ?: 0) *time.coerceIn(0, 30)
}
else {valvesOpened.remove(start); return pressureReleased}
}
println(trace("AA", 30, valvesOpened, 0))
// println(pressureReleasedResult)
println(pressureReleasedResult.max())
}
fun part2(input: List<String>){
val valves = parseInput(input)
val reducedGraphs = mutableMapOf<String, MutableMap<String, Int>>()
reducedGraphs["AA"] = computeDistances("AA", valves)
valves.keys.forEach { if (valves[it]?.flow!! > 0) {reducedGraphs[it] = computeDistances(it, valves)} }
fun trace2(start: String, time: Int, valvesOpened: MutableList<String>, pressureReleased: Int, redGraphs: MutableMap<String, MutableMap<String, Int>>): Int{
valvesOpened.add(start)
val result = mutableListOf<Int>()
if (time > 0) {
for (nextValve in redGraphs[start]?.keys!!) {
if (nextValve !in valvesOpened) {
result.add(
trace2(
nextValve, time - reducedGraphs[start]?.get(nextValve)!!, valvesOpened,
pressureReleased + (valves[start]?.flow ?: 0) * time, redGraphs
)
)
}
}
if (result.isNotEmpty()) {
valvesOpened.remove(start)
return result.max() //+ (valves[start]?.flow ?: 0) * time.coerceIn(0, 30)
} else {
return pressureReleased+(valves[start]?.flow ?: 0) *time.coerceIn(0, 30)
}
}
else {valvesOpened.remove(start); return pressureReleased}
}
// println(trace2("AA", 30, valvesOpened, 0, reducedGraphs))
fun combinationUtil(arr: MutableList<String>, data: MutableList<String>, start: Int,
end: Int, index: Int, r: Int, res: MutableList<Int>): Int {
if (index == r) {
val myValves = data
val elValves = arr.subtract(data.toSet())
val myGraph = mutableMapOf<String, MutableMap<String, Int>>()
reducedGraphs.forEach { myGraph[it.key] = it.value.filterKeys { valve -> valve in myValves }.toMutableMap() }
val elGraph = mutableMapOf<String, MutableMap<String, Int>>()
reducedGraphs.forEach { elGraph[it.key] = it.value.filterKeys { valve -> valve in elValves }.toMutableMap() }
res.add(trace2("AA", 26, mutableListOf<String>(), 0, myGraph) + trace2("AA", 26, mutableListOf<String>(), 0, elGraph))
return res.max()
}
var i = start
while (i <= end && end - i + 1 >= r - index) {
data[index] = arr[i]
combinationUtil(arr, data, i + 1, end, index + 1, r, res)
i++
}
return res.max()
}
var part2answer = 0
for (r in 1.. (reducedGraphs.keys.size - 1) / 2){
val outputList = MutableList(r) { " " }
val n = reducedGraphs.keys.size
val resR = combinationUtil(reducedGraphs.keys.subtract(listOf("AA")).toMutableList(), outputList, 0, n-2, 0, r, mutableListOf() )
part2answer = maxOf(part2answer, resR)
}
println("part2: $part2answer")
}
val testInput = readInput("Day16_test")
part1(testInput)
part2(testInput)
val input = readInput("Day16")
part1(input)
part2(input)
} | 0 | Kotlin | 0 | 0 | a0bc190b391585ce3bb6fe2ba092fa1f437491a6 | 6,808 | aoc22 | Apache License 2.0 |
src/Day05.kt | maewCP | 579,203,172 | false | {"Kotlin": 59412} | fun main() {
fun _process(inputStack: List<String>, inputCmd: List<String>, reverse: Boolean) : String {
val stacks = mutableListOf<MutableList<Char>>()
inputStack.forEachIndexed { lineIdx, line ->
(0 until (line.length + 1) / 4).forEach { i ->
if (lineIdx == 0) {
// initial list
stacks.add(mutableListOf())
}
val item = line[4 * i + 1]
if (item != ' ') stacks[i].add(item)
}
}
inputCmd.forEach { line ->
val match = "move (\\d+) from (\\d+) to (\\d+)".toRegex().find(line)!!
val (qty, from, to) = match.destructured.toList().map { it.toInt() }
val pop = stacks[from - 1].subList(0, qty).toMutableList()
if (reverse) pop.reverse()
stacks[from - 1] = stacks[from - 1].subList(qty, stacks[from - 1].size).toMutableList()
pop.addAll(stacks[to - 1])
stacks[to - 1] = pop
}
return stacks.map { it[0] }.joinToString(separator = "")
}
fun part1(inputStack: List<String>, inputCmd: List<String>): String {
return _process(inputStack, inputCmd, true)
}
fun part2(inputStack: List<String>, inputCmd: List<String>): String {
return _process(inputStack, inputCmd, false)
}
// test if implementation meets criteria from the description, like:
val testInputStack = readInput("Day05_stack_test")
val testInputCmd = readInput("Day05_cmd_test")
check(part1(testInputStack, testInputCmd) == "CMZ")
check(part2(testInputStack, testInputCmd) == "MCD")
val inputStack = readInput("Day05_stack")
val inputCmd = readInput("Day05_cmd")
part1(inputStack, inputCmd).println()
part2(inputStack, inputCmd).println()
}
| 0 | Kotlin | 0 | 0 | 8924a6d913e2c15876c52acd2e1dc986cd162693 | 1,833 | advent-of-code-2022-kotlin | Apache License 2.0 |
leetcode/UniquePathsTwo.kt | jjrodcast | 175,520,504 | false | null | /*
Enlace al problema:
https://leetcode.com/problems/unique-paths-ii/
La solución se encuentra dentro de la función `uniquePathsWithObstacles`, el resto del código es para
ejecutarlo de manera local.
Explanation:
Given the grid:
[0,0,0]
[0,1,0]
[0,0,0]
Initial information:
*) We are at position (0,0) and the target is (2,2)
*) Inside the grid there are obstacles (1's)
Question:
How many paths can we find from initial position to target position?
Solution
--------
1) Add a new `row` and `column` to the grid.
[I,0,0,0]
[0,X,0,0]
[0,0,T,0]
[0,0,0,0]
2) Check if initial position is and obstacle, if true assign `0` otherwise `1`
[1,0,0,0]
[0,X,0,0]
[0,0,T,0]
[0,0,0,0]
3) Now check for the first `row` and the first `column` and if is and
obstacle assign `0` otherwise the previous value (in this case just `row` or `column`)
[1,1,1,1]
[1,X,0,0]
[1,0,T,0]
[1,0,0,0]
4) Finally we pre-calculate all the other values to the target.
To do this we need to assign to the current value (x,y) the sum
of the paths that can lead us to the `target` which are:
(row, col-1) and (row-1, col)
* If there is an obstacle in the current position (x,y), we assign `0`
[1,1,1,1]
[1,0,1,2]
[1,1,2,4]
[1,2,4,8]
Time complexity: O(m*n)
*/
class Solution {
fun uniquePathsWithObstacles(obstacleGrid: Array<IntArray>): Int {
val rows = obstacleGrid.size
val cols = obstacleGrid[0].size
val grid = Array(rows + 1) { IntArray(cols + 1) { 0 } }
grid[0][0] = if (obstacleGrid[0][0] == 0) 1 else 0
for (i in 1 until rows) if (obstacleGrid[i][0] == 0) grid[i][0] = grid[i - 1][0]
for (i in 1 until cols) if (obstacleGrid[0][i] == 0) grid[0][i] = grid[0][i - 1]
for (i in 1 until rows) {
for (j in 1 until cols) {
grid[i][j] = if (obstacleGrid[i][j] == 0) grid[i - 1][j] + grid[i][j - 1] else 0
}
}
return grid[rows - 1][cols - 1]
}
}
fun main() {
// Class for Solution
val solution = Solution()
// Test #1: Input grid
val grid = arrayOf(
intArrayOf(0, 0, 0),
intArrayOf(0, 1, 0),
intArrayOf(0, 0, 0)
)
// Test #1: Output solution
println(solution.uniquePathsWithObstacles(grid))
} | 0 | Kotlin | 1 | 1 | a91868c3d24ad164fa637a8b3d682ec70d7ed7aa | 2,718 | CompetitiveProblems | MIT License |
src/main/kotlin/de/startat/aoc2023/Day4.kt | Arondc | 727,396,875 | false | {"Kotlin": 194620} | package de.startat.aoc2023
import kotlin.math.pow
data class Scratchcard(
val cardNumber: Int,
val winningNumbers: List<Int>,
val scratchedNumbers: List<Int>,
var numberOfCopiesOwned: Int = 1
) {
val matchingNumbers = winningNumbers.count { wn -> scratchedNumbers.contains(wn) }
fun copiesWon(numberOfCopiesWon: Int) {
numberOfCopiesOwned += numberOfCopiesWon
}
var score: Int = when {
matchingNumbers > 0 -> 2.0.pow(matchingNumbers - 1).toInt()
else -> 0
}
}
class Day4 {
private val cardRegex = Regex("Card\\W*(\\d+): ([\\d ]+) \\| ([\\d ]+)")
fun star1() {
val scratchcards = day4input.lines().map { l -> parseCard(l) }
val score = scratchcards.fold(0) { acc, card -> acc + card.score }
println("Die Gesamtpunktzahl für die Scratchcards ist $score")
}
fun star2() {
val scratchcards = day4input.lines().map { l -> parseCard(l) }
scratchcards.withIndex().onEach { (idx, sc) ->
if (sc.matchingNumbers > 0) {
(idx + 1..idx + sc.matchingNumbers).forEach { winIdx ->
scratchcards[winIdx].copiesWon(sc.numberOfCopiesOwned)
}
}
}
val scratchcardsOwned = scratchcards.fold(0) { acc, scratchcard -> acc + scratchcard.numberOfCopiesOwned }
print("Du besitzt insgesamt $scratchcardsOwned Scratchcards")
}
private fun parseCard(line: String): Scratchcard {
val cardValues = cardRegex.find(line)!!.groupValues
return Scratchcard(
cardValues[1].toInt(), cardValues[2].parseAsScratchcardNumbers(),
cardValues[3].parseAsScratchcardNumbers()
)
}
private fun String.parseAsScratchcardNumbers(): List<Int> =
this.trim().replace(" ", " ").split(" ").map { it.toInt() }.toList()
}
val day4testInput =
"""
Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53
Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19
Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1
Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83
Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36
Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11
""".trimIndent()
val day4input =
"""
Card 1: 4 16 87 61 11 37 43 25 49 17 | 54 36 14 55 83 58 43 15 87 17 97 11 62 75 37 4 49 80 42 61 20 79 25 24 16
Card 2: 15 53 49 30 36 68 76 12 2 73 | 3 18 33 27 34 75 5 29 57 89 96 51 85 41 4 46 30 79 78 43 23 36 73 53 98
Card 3: 47 63 83 92 61 40 42 46 48 45 | 48 43 8 49 77 80 56 50 7 31 13 70 74 37 92 1 20 25 76 90 81 9 52 24 16
Card 4: 67 55 70 16 95 64 27 10 48 62 | 6 36 54 22 85 27 73 29 74 96 11 62 48 38 90 94 70 12 67 17 64 95 18 37 55
Card 5: 27 94 48 79 51 46 63 69 50 84 | 15 53 62 45 21 66 84 51 29 40 25 43 27 88 79 63 3 54 48 23 90 69 94 74 36
Card 6: 46 7 45 1 65 32 37 66 51 95 | 87 61 56 84 44 25 80 37 31 23 91 92 99 47 15 96 33 14 42 89 5 3 46 59 85
Card 7: 4 1 78 46 99 72 3 79 43 54 | 22 20 16 46 27 93 81 99 56 59 10 35 91 2 77 87 19 92 54 28 17 90 4 38 79
Card 8: 63 26 3 54 44 86 19 28 79 20 | 86 33 59 15 92 73 39 28 36 13 14 97 45 43 80 50 7 12 96 38 2 79 72 10 35
Card 9: 11 96 56 3 25 87 9 20 19 67 | 84 25 9 83 67 13 95 45 72 87 58 14 43 5 52 49 93 19 42 48 18 59 3 66 20
Card 10: 74 16 70 84 4 24 46 15 86 11 | 45 72 15 88 25 27 52 65 28 96 19 50 39 40 80 6 30 89 60 8 69 79 17 41 47
Card 11: 45 38 25 87 9 41 3 35 64 77 | 15 46 14 73 7 81 61 19 51 98 70 18 9 65 57 36 37 49 34 47 89 84 16 27 53
Card 12: 40 96 29 71 34 53 67 64 78 32 | 56 55 13 62 6 89 77 25 9 80 39 12 35 3 48 36 34 18 27 79 26 41 20 23 17
Card 13: 93 5 47 17 31 80 10 99 91 4 | 59 13 55 19 99 90 39 12 82 87 5 57 84 8 3 36 11 58 35 25 95 14 16 6 30
Card 14: 4 32 1 34 27 57 33 52 90 84 | 72 9 82 23 37 78 93 95 24 50 56 69 85 81 99 62 80 63 47 68 51 17 15 14 92
Card 15: 96 89 22 38 81 6 12 44 70 30 | 64 13 60 59 47 37 43 1 21 18 66 15 98 73 49 69 33 93 68 31 36 3 51 77 28
Card 16: 96 48 58 8 40 16 61 4 99 90 | 70 60 35 29 36 37 66 27 23 59 12 85 5 52 19 38 74 50 71 31 39 98 78 77 26
Card 17: 26 68 8 27 54 67 33 70 43 36 | 94 79 34 54 68 44 40 27 12 6 84 62 29 53 38 33 61 71 97 45 65 42 4 30 55
Card 18: 51 71 13 82 33 53 47 6 52 91 | 31 38 13 76 3 39 79 49 86 68 52 6 9 33 20 23 71 51 47 96 72 88 91 82 65
Card 19: 30 40 87 47 80 51 67 56 36 91 | 3 97 96 47 64 50 16 51 25 52 94 36 81 78 83 40 84 54 55 15 91 2 74 37 80
Card 20: 86 62 88 4 52 36 46 97 50 8 | 52 2 50 80 13 16 86 31 24 34 36 46 96 62 4 48 85 97 98 33 88 8 90 89 53
Card 21: 5 51 41 45 92 12 30 53 55 46 | 5 31 88 83 97 16 41 23 32 56 63 34 73 50 51 91 40 43 14 79 58 86 30 20 45
Card 22: 13 79 51 15 67 12 86 75 37 60 | 41 62 45 40 1 48 65 15 90 64 93 80 37 14 84 86 78 22 67 71 19 91 75 53 82
Card 23: 83 38 65 66 61 68 73 45 94 37 | 61 68 80 46 58 63 57 9 29 76 7 14 43 72 88 40 92 31 48 87 21 77 20 70 19
Card 24: 68 46 99 43 94 9 59 90 7 57 | 81 36 8 9 57 52 80 88 91 67 14 30 61 46 64 32 3 17 19 47 53 37 60 34 85
Card 25: 33 62 17 70 92 78 82 65 71 29 | 32 86 68 45 40 8 6 48 90 55 81 87 70 62 99 52 2 1 15 44 18 4 47 92 66
Card 26: 30 72 85 50 56 39 73 64 74 87 | 18 79 67 19 56 74 30 50 95 77 72 94 55 42 51 38 91 66 9 17 75 97 70 85 48
Card 27: 62 44 63 58 23 75 35 2 39 98 | 71 41 79 82 51 55 38 66 91 24 3 85 16 87 17 8 22 28 19 48 11 84 90 63 65
Card 28: 21 79 50 96 63 37 12 81 7 34 | 86 46 22 94 25 35 1 97 36 2 50 79 98 5 72 49 13 78 75 84 61 54 17 44 87
Card 29: 42 33 88 19 31 10 7 40 54 75 | 82 41 93 27 37 80 6 36 76 3 24 67 16 50 98 66 35 34 49 15 1 57 25 59 92
Card 30: 30 33 68 49 25 20 81 23 39 12 | 12 16 64 76 91 58 19 9 85 30 63 7 28 71 93 38 94 70 55 13 21 56 49 11 31
Card 31: 8 71 47 52 54 84 69 12 32 31 | 97 70 29 77 95 7 51 57 4 17 34 83 79 20 80 6 75 85 26 87 84 74 92 58 76
Card 32: 3 51 74 19 76 72 95 59 46 2 | 16 87 86 83 6 60 67 29 88 75 82 62 36 35 24 92 25 44 70 93 80 23 48 7 30
Card 33: 70 73 24 26 89 13 95 76 69 31 | 55 68 7 15 16 66 78 54 80 41 6 25 23 42 20 81 19 65 39 82 56 97 2 59 48
Card 34: 88 59 60 8 58 36 90 64 72 95 | 71 64 43 14 26 60 90 88 80 44 17 37 9 72 78 95 45 7 58 82 8 93 41 59 36
Card 35: 72 14 1 41 13 91 42 43 34 54 | 80 73 57 41 38 46 85 56 49 5 28 22 18 2 3 74 58 37 61 26 16 11 70 88 48
Card 36: 78 9 94 82 98 88 49 63 83 97 | 33 11 69 5 92 60 2 19 1 40 36 20 77 84 49 45 58 12 59 97 16 65 57 32 50
Card 37: 63 59 64 90 75 24 91 25 1 72 | 19 80 3 74 55 52 73 67 30 90 75 54 60 91 31 9 79 86 20 24 95 23 63 82 1
Card 38: 16 9 96 30 88 44 98 84 25 40 | 99 84 36 91 40 9 39 41 76 24 65 1 27 10 47 73 52 3 30 53 96 44 62 92 12
Card 39: 91 51 71 58 67 29 45 8 94 39 | 44 71 69 22 58 95 8 83 52 23 82 93 39 7 45 2 78 53 75 24 91 10 68 66 67
Card 40: 82 34 28 29 77 94 24 87 18 96 | 43 81 28 22 24 11 77 32 68 97 42 80 72 34 55 96 57 73 63 29 76 87 18 54 79
Card 41: 44 55 42 71 36 54 61 15 45 60 | 45 12 33 42 94 28 97 71 80 83 47 52 57 34 13 86 60 54 43 22 15 8 82 61 55
Card 42: 35 58 38 99 31 57 51 30 26 2 | 26 32 35 59 79 36 2 39 99 78 31 57 68 90 15 30 38 96 80 51 58 56 37 75 42
Card 43: 77 10 9 64 44 90 81 98 21 59 | 13 97 80 15 81 65 50 88 23 71 46 77 90 74 87 14 76 98 16 59 72 22 40 11 58
Card 44: 49 26 55 10 47 50 86 78 61 59 | 3 52 50 91 99 45 5 36 4 62 87 98 95 76 59 37 44 33 97 88 78 92 55 9 72
Card 45: 83 29 80 15 1 49 48 88 20 85 | 67 28 18 81 33 43 86 97 58 12 48 65 3 88 98 73 13 26 29 38 32 47 31 52 23
Card 46: 92 47 60 65 43 36 88 32 83 40 | 30 23 52 72 22 57 56 77 75 11 76 63 33 45 92 70 7 91 38 14 46 25 53 47 20
Card 47: 4 34 2 20 13 60 83 22 32 29 | 53 22 74 55 44 24 7 1 3 18 9 35 23 75 79 39 49 42 29 65 83 32 33 15 60
Card 48: 66 14 21 58 99 9 84 51 75 65 | 16 6 98 94 9 80 83 87 67 25 81 8 55 52 79 32 31 73 12 14 99 2 1 61 58
Card 49: 77 15 4 39 53 69 50 67 12 88 | 80 86 39 59 88 91 40 8 6 28 71 32 52 53 78 67 68 55 18 48 36 2 10 15 46
Card 50: 14 33 20 45 94 57 44 12 4 90 | 13 61 63 38 57 23 10 69 55 8 15 92 99 5 78 75 71 32 48 14 58 27 36 84 80
Card 51: 86 37 44 80 7 64 84 83 35 45 | 57 36 92 97 40 70 39 42 95 54 91 41 84 24 83 98 94 49 45 74 68 31 11 61 47
Card 52: 2 95 75 93 52 46 16 6 73 55 | 53 34 8 13 59 93 22 54 68 24 92 71 81 99 72 25 98 66 10 77 5 43 83 57 48
Card 53: 60 77 43 57 11 65 27 58 42 14 | 31 20 34 28 15 99 95 10 68 72 54 83 40 59 49 71 37 47 78 63 53 62 81 76 89
Card 54: 58 70 34 96 18 32 28 10 56 36 | 81 83 22 51 75 39 65 7 2 63 90 54 33 66 23 91 26 15 27 13 8 85 48 59 99
Card 55: 32 57 4 1 99 46 20 31 39 83 | 33 39 99 93 4 34 7 1 28 21 2 73 84 27 86 63 46 57 20 66 83 31 12 72 32
Card 56: 40 32 42 89 27 59 11 35 19 64 | 72 34 5 33 42 11 82 35 64 59 60 19 91 57 65 1 40 43 89 32 28 14 81 27 41
Card 57: 72 82 17 11 97 99 78 4 76 32 | 50 22 14 91 70 56 2 11 28 6 96 77 49 99 20 97 68 71 52 30 78 89 65 44 7
Card 58: 34 48 17 95 85 64 21 4 69 20 | 24 33 98 35 10 65 48 83 47 58 41 69 17 97 64 42 12 20 95 4 9 34 3 21 85
Card 59: 77 23 73 74 65 5 21 46 25 7 | 89 12 70 17 73 65 41 37 5 78 62 60 15 3 72 94 14 77 38 69 83 98 24 43 56
Card 60: 12 13 25 5 33 49 9 72 24 2 | 41 93 73 2 91 44 20 81 24 52 89 50 17 92 86 11 7 60 94 12 72 63 69 38 71
Card 61: 19 91 49 95 9 34 79 69 44 53 | 5 37 78 67 29 21 40 15 52 42 54 4 99 80 9 36 22 35 32 68 19 14 23 92 95
Card 62: 4 90 51 59 40 87 28 48 73 32 | 11 85 97 8 28 79 36 72 48 40 59 54 95 73 19 78 88 31 90 5 51 4 6 91 92
Card 63: 9 71 2 3 83 4 89 24 36 58 | 6 44 77 50 89 97 9 72 37 66 78 58 57 24 27 61 63 36 14 76 99 3 25 65 12
Card 64: 24 44 18 88 34 51 20 32 74 47 | 12 20 48 92 32 24 7 11 51 96 78 45 94 44 39 29 37 97 25 59 88 31 18 89 34
Card 65: 15 94 2 23 67 77 64 63 25 27 | 82 26 73 49 74 86 32 37 5 38 97 81 19 67 7 45 70 44 22 36 6 15 27 72 75
Card 66: 87 1 49 91 70 8 25 90 50 39 | 78 83 58 60 87 95 51 21 28 36 96 32 33 92 13 47 74 65 57 82 99 39 8 86 25
Card 67: 17 4 29 90 38 28 63 31 20 14 | 47 76 39 40 68 95 41 78 6 23 50 2 30 17 58 90 35 32 85 93 31 20 59 34 52
Card 68: 56 70 83 13 54 79 65 4 53 68 | 88 23 52 45 75 26 10 74 92 40 12 81 35 82 49 5 42 11 94 78 9 97 22 48 30
Card 69: 1 5 41 3 42 91 16 71 67 95 | 39 52 33 77 89 29 2 99 62 51 79 50 15 63 66 88 8 68 18 14 25 21 75 70 32
Card 70: 70 2 33 17 56 6 65 26 59 4 | 80 60 58 61 26 62 38 79 18 71 29 65 88 40 35 50 11 22 12 83 30 44 91 21 20
Card 71: 13 9 44 91 25 28 87 46 5 29 | 76 37 86 55 3 99 98 48 88 97 89 36 83 64 56 8 22 45 43 94 60 47 78 27 95
Card 72: 41 59 54 74 23 15 25 51 96 31 | 49 55 26 80 86 83 46 6 36 4 14 85 92 47 44 61 57 40 1 60 29 65 19 87 32
Card 73: 45 76 75 41 20 38 5 79 26 58 | 7 86 27 55 25 41 78 33 59 97 43 70 66 64 44 60 74 88 29 77 76 15 62 21 30
Card 74: 85 50 86 59 33 25 10 82 19 3 | 33 82 38 88 13 85 3 84 75 27 79 74 25 91 50 59 8 19 53 58 32 2 63 86 10
Card 75: 45 41 31 38 25 77 64 33 37 70 | 38 19 40 31 53 25 30 8 33 91 6 70 42 28 54 88 77 80 69 72 37 49 41 39 45
Card 76: 8 67 35 28 65 54 74 17 40 4 | 67 79 57 73 70 32 69 18 65 54 97 4 43 17 58 48 61 3 41 13 76 8 35 22 9
Card 77: 69 54 59 52 95 91 6 89 85 16 | 13 93 66 84 18 91 15 78 64 3 6 89 4 16 94 23 85 69 33 59 87 54 52 24 98
Card 78: 47 91 89 93 94 67 76 90 26 14 | 2 3 59 19 67 41 89 12 90 26 83 94 1 93 97 76 17 32 91 10 14 48 36 47 53
Card 79: 23 92 5 91 59 75 65 84 22 57 | 16 95 71 86 75 9 10 87 81 28 20 11 43 13 19 2 63 84 5 85 61 33 23 73 99
Card 80: 78 5 13 75 9 27 21 24 45 30 | 94 28 46 2 9 66 99 36 49 6 61 26 25 15 17 74 85 97 82 11 54 34 31 10 29
Card 81: 89 33 76 53 28 58 9 75 15 92 | 20 10 40 68 16 84 15 22 9 75 69 42 34 80 92 58 45 30 67 28 52 27 71 65 33
Card 82: 90 80 73 27 72 6 41 56 3 47 | 85 26 49 70 16 4 36 60 54 12 17 32 78 94 63 44 33 39 96 1 95 55 48 7 2
Card 83: 34 29 8 1 64 95 10 44 66 46 | 94 3 58 22 26 47 29 11 97 65 1 12 64 61 66 8 16 9 99 95 24 19 91 43 52
Card 84: 51 57 90 39 83 37 54 15 94 40 | 89 39 19 78 74 47 38 1 41 71 85 31 56 46 92 30 66 96 55 83 94 51 49 95 67
Card 85: 81 68 7 66 4 5 34 74 45 87 | 5 55 87 90 42 16 45 23 86 60 69 65 72 54 14 7 17 21 8 25 56 79 32 10 44
Card 86: 41 98 47 99 76 73 38 31 8 4 | 30 36 54 79 43 34 9 27 66 97 56 85 17 21 65 11 29 51 10 77 70 48 73 55 67
Card 87: 93 11 14 33 29 89 48 13 76 60 | 37 68 19 15 12 22 53 48 16 85 26 45 95 51 89 73 25 9 8 52 70 31 84 54 65
Card 88: 75 43 74 65 80 76 79 85 29 71 | 3 77 90 22 11 16 62 7 67 26 30 14 98 12 44 87 53 45 2 13 46 76 48 60 39
Card 89: 66 21 28 73 67 61 92 76 26 35 | 9 57 60 10 91 31 19 8 47 36 6 87 50 17 59 15 33 37 22 74 51 81 85 68 34
Card 90: 31 6 89 59 34 33 38 7 11 72 | 10 35 92 37 70 53 61 56 4 82 90 21 45 54 15 17 5 25 51 74 9 86 48 40 97
Card 91: 86 51 95 84 93 32 54 20 59 92 | 87 55 74 2 33 22 14 19 77 51 12 39 43 71 47 59 38 1 92 93 20 95 16 32 36
Card 92: 41 45 50 46 43 29 19 74 58 81 | 58 19 43 93 15 23 74 40 46 79 9 42 61 10 4 41 81 12 45 50 89 98 67 96 29
Card 93: 65 60 55 39 2 76 91 71 9 96 | 54 67 26 42 90 68 40 25 88 97 51 15 41 1 83 64 20 56 53 44 16 8 63 6 17
Card 94: 91 84 97 98 45 59 89 43 81 61 | 22 58 60 69 53 68 95 51 56 87 17 3 34 70 8 19 33 16 67 29 18 31 55 40 28
Card 95: 82 45 14 97 52 48 65 96 17 93 | 64 52 92 8 17 82 27 45 83 93 9 49 74 84 91 20 13 48 96 97 56 24 14 77 57
Card 96: 49 74 18 64 58 8 61 9 22 53 | 11 68 83 90 95 8 60 71 28 91 20 13 52 62 43 87 23 46 86 88 80 59 33 19 53
Card 97: 78 22 21 96 8 84 29 51 99 53 | 89 94 18 58 21 52 92 38 35 41 5 34 7 36 77 68 20 49 80 55 87 17 8 15 86
Card 98: 63 92 3 16 80 94 36 54 98 75 | 66 51 87 27 79 84 22 20 41 99 46 40 45 39 59 63 97 15 92 36 57 7 69 54 48
Card 99: 30 95 26 13 66 67 20 52 6 19 | 66 8 92 3 88 78 37 27 39 12 28 82 30 20 52 94 26 67 2 93 91 61 48 40 11
Card 100: 48 52 64 41 32 73 49 35 27 43 | 99 3 83 10 25 13 42 47 36 67 84 71 97 55 4 53 57 95 31 29 93 19 5 62 50
Card 101: 21 35 7 98 38 72 23 87 68 2 | 19 65 60 13 2 35 72 82 74 68 86 39 27 1 93 10 66 46 88 21 84 16 25 14 48
Card 102: 14 65 49 53 15 30 74 18 24 60 | 66 73 99 20 88 13 65 18 46 71 64 4 27 92 86 84 72 94 79 67 75 43 52 1 90
Card 103: 6 5 73 80 99 12 9 59 13 89 | 56 33 74 27 1 35 78 80 66 43 81 70 51 34 39 23 62 19 65 13 71 38 37 72 12
Card 104: 65 33 18 59 73 41 63 82 75 56 | 62 92 33 14 34 23 28 86 94 63 21 96 74 99 85 30 16 66 22 43 25 93 79 44 32
Card 105: 63 43 48 30 8 82 19 54 26 4 | 56 6 46 68 51 25 13 28 17 88 49 31 77 75 61 3 87 72 89 43 90 32 7 52 57
Card 106: 47 19 75 22 94 77 8 38 96 21 | 41 35 27 58 32 29 1 39 11 76 91 92 57 52 46 97 83 53 45 20 72 95 74 56 48
Card 107: 30 73 2 37 19 56 65 47 90 72 | 40 39 27 75 3 23 82 30 17 84 57 62 53 97 12 22 36 99 98 15 46 55 52 25 78
Card 108: 28 10 38 12 59 81 76 61 1 15 | 38 14 1 93 81 98 44 87 50 5 90 28 40 76 6 41 34 21 32 19 66 49 46 15 12
Card 109: 20 60 64 19 96 99 92 97 56 50 | 47 56 44 83 91 78 7 79 58 69 22 4 5 13 88 43 23 98 59 65 85 54 61 31 68
Card 110: 48 5 91 83 38 22 37 46 12 29 | 85 88 37 98 47 48 26 29 83 72 28 5 11 90 45 12 22 38 33 46 97 21 89 82 91
Card 111: 32 18 26 70 63 28 15 59 51 21 | 70 89 40 77 31 30 24 12 63 16 97 43 66 87 44 5 96 65 34 72 11 83 59 39 15
Card 112: 23 96 39 2 63 28 57 13 45 83 | 99 82 66 18 28 46 96 70 68 15 39 20 88 21 56 23 2 17 72 44 6 57 30 83 63
Card 113: 7 12 18 90 25 4 13 19 10 47 | 47 32 25 62 21 7 24 54 3 86 4 15 10 90 29 13 67 18 89 83 12 19 84 33 96
Card 114: 3 79 92 67 56 89 69 51 88 65 | 48 35 99 69 81 18 59 5 12 50 52 63 68 88 7 25 33 51 23 3 89 94 44 49 82
Card 115: 8 47 42 94 93 89 63 12 45 25 | 13 47 92 74 94 8 25 30 53 12 29 54 28 60 11 48 20 49 91 36 69 17 44 57 23
Card 116: 91 24 4 78 51 46 36 54 33 9 | 91 57 6 53 13 9 60 3 51 24 2 72 40 46 29 4 39 77 33 78 36 44 70 68 54
Card 117: 56 17 24 77 22 39 75 99 61 84 | 61 56 98 78 99 17 63 93 7 35 77 23 67 39 76 60 15 20 5 22 24 70 6 36 75
Card 118: 29 65 49 43 98 94 14 16 95 54 | 29 12 98 17 23 15 3 69 81 34 16 27 91 1 26 2 6 82 7 32 11 72 25 58 9
Card 119: 88 15 5 72 98 69 48 42 71 94 | 24 22 47 46 73 3 40 16 51 74 18 6 72 82 41 85 52 86 4 62 58 71 30 80 67
Card 120: 80 5 74 70 13 51 2 83 90 69 | 4 62 47 51 66 74 88 49 98 76 83 80 94 75 28 5 14 99 31 2 40 6 70 81 11
Card 121: 45 32 99 18 69 28 68 16 30 88 | 28 33 37 46 11 40 86 94 22 44 48 60 23 8 25 78 54 18 67 1 61 87 42 21 63
Card 122: 32 42 18 48 4 97 8 13 41 14 | 54 35 71 90 75 31 8 27 95 61 56 43 7 5 46 51 70 74 79 3 59 93 66 57 63
Card 123: 67 87 25 96 5 53 65 33 7 93 | 24 27 90 62 19 20 15 65 43 14 78 28 91 54 57 80 84 79 76 42 47 60 25 34 86
Card 124: 65 40 9 7 77 17 91 23 93 37 | 24 29 77 56 18 88 7 86 87 8 35 31 23 58 32 51 38 66 19 12 25 13 53 85 96
Card 125: 1 42 28 43 32 85 98 21 55 91 | 93 41 80 26 98 22 46 74 16 79 51 18 11 29 15 72 94 83 27 39 2 75 60 10 97
Card 126: 80 84 95 87 74 30 48 19 33 34 | 67 21 38 63 61 69 78 28 31 17 66 60 64 86 96 77 32 10 20 26 76 18 35 97 73
Card 127: 71 5 14 49 18 92 33 82 66 48 | 65 98 25 96 17 94 45 7 43 62 60 50 27 58 16 22 24 95 47 76 51 97 84 46 69
Card 128: 87 46 34 65 24 8 25 58 53 17 | 53 35 79 93 46 33 5 75 89 10 16 55 43 52 63 61 92 57 91 13 44 68 12 1 31
Card 129: 89 51 40 43 63 19 44 15 90 83 | 73 31 89 12 44 15 9 79 83 41 43 92 90 46 51 87 63 19 3 78 40 65 58 36 10
Card 130: 23 93 46 97 56 2 84 27 90 81 | 80 7 87 82 27 73 21 69 39 84 41 74 90 31 2 56 83 15 57 79 72 94 60 78 48
Card 131: 97 72 71 26 99 87 33 15 80 42 | 55 83 73 69 42 99 56 59 12 11 8 29 95 74 47 21 41 75 7 27 52 26 98 30 97
Card 132: 42 62 27 46 10 4 25 49 71 68 | 10 49 66 47 44 68 14 42 37 60 36 48 23 20 25 51 62 4 13 21 27 70 18 86 71
Card 133: 60 92 64 94 88 8 13 29 3 73 | 51 73 72 63 81 21 90 91 64 46 53 70 60 7 39 50 41 75 36 55 29 9 65 67 78
Card 134: 58 60 72 44 62 38 12 27 69 90 | 66 82 29 95 37 54 98 31 74 2 99 35 13 11 83 1 63 14 93 21 81 39 47 77 4
Card 135: 85 74 56 48 25 73 14 20 86 16 | 73 63 35 28 50 7 66 39 3 1 91 98 69 68 56 33 93 9 86 52 15 54 71 53 44
Card 136: 72 27 4 80 71 7 15 64 13 41 | 16 52 6 95 83 5 88 21 97 99 90 87 20 43 51 10 33 3 91 26 32 69 39 22 40
Card 137: 12 53 99 38 89 1 80 18 67 90 | 92 96 95 84 36 93 73 79 31 40 44 21 53 83 59 87 13 57 50 98 33 77 22 41 34
Card 138: 29 51 61 45 18 77 65 34 56 35 | 93 73 57 76 27 87 20 61 50 71 22 54 19 82 26 13 8 97 29 12 36 42 56 47 18
Card 139: 9 86 94 52 84 53 65 87 92 73 | 62 89 19 92 43 44 51 42 65 20 24 26 22 2 76 67 95 6 97 87 74 72 75 27 23
Card 140: 84 93 8 15 50 67 90 66 89 59 | 79 50 10 30 31 35 5 97 77 34 37 67 47 83 27 55 62 40 6 24 57 54 53 71 7
Card 141: 91 20 24 58 99 61 53 81 18 30 | 59 40 14 97 60 31 72 9 25 95 12 37 75 88 92 73 16 41 67 98 51 32 23 66 96
Card 142: 34 10 96 5 31 35 51 50 6 42 | 49 60 77 83 47 39 23 81 79 7 99 13 82 59 24 98 35 57 72 69 86 76 18 55 61
Card 143: 78 41 71 76 61 47 1 55 75 99 | 80 44 11 31 50 28 62 12 45 40 70 27 9 4 86 15 56 91 79 85 25 67 63 64 88
Card 144: 8 60 75 55 87 31 66 86 97 61 | 97 35 30 84 53 8 44 22 86 85 61 46 87 10 37 55 34 27 25 31 20 70 50 11 66
Card 145: 82 53 79 77 33 30 72 17 97 81 | 53 11 29 30 81 35 97 77 72 25 46 89 82 79 73 61 45 17 33 41 23 98 76 69 87
Card 146: 28 9 7 73 46 10 79 78 92 72 | 94 86 72 67 13 91 57 12 30 60 85 59 34 35 62 76 43 2 93 46 96 41 84 51 90
Card 147: 32 43 57 10 92 4 97 78 15 81 | 92 96 13 57 15 58 52 89 10 35 47 31 81 4 32 39 70 55 5 97 68 78 2 83 43
Card 148: 12 25 92 23 7 26 39 53 1 31 | 83 23 98 42 53 92 45 25 26 63 7 40 12 47 55 64 66 14 60 75 13 34 85 21 15
Card 149: 99 65 4 47 72 98 43 84 60 41 | 36 58 1 52 65 79 90 71 43 49 6 5 99 28 16 50 18 93 42 56 86 23 59 92 14
Card 150: 63 66 75 98 88 74 73 90 44 78 | 49 77 33 69 7 65 32 9 93 66 42 73 50 11 92 68 64 88 31 34 74 20 19 8 13
Card 151: 32 5 78 85 56 90 29 66 50 68 | 46 90 89 5 14 75 13 66 1 29 32 35 68 47 22 42 78 23 63 44 50 73 83 56 85
Card 152: 73 75 40 67 61 86 93 71 20 15 | 4 9 13 30 14 75 68 76 79 24 34 32 98 93 23 50 20 36 33 72 88 82 89 51 31
Card 153: 45 64 17 72 24 34 87 40 31 84 | 50 83 19 81 64 54 45 17 35 41 2 79 76 24 30 92 65 20 43 38 75 84 29 40 53
Card 154: 42 68 35 21 46 87 71 52 65 74 | 33 22 74 87 96 65 46 94 42 35 6 80 53 71 7 85 90 27 49 52 47 41 16 58 98
Card 155: 65 80 15 4 31 74 60 71 38 97 | 45 22 43 66 15 99 17 26 49 65 93 48 74 4 57 38 91 71 39 37 11 31 80 67 68
Card 156: 60 44 95 98 59 42 56 20 1 50 | 57 88 20 56 26 84 42 95 98 44 50 35 59 30 41 34 14 10 54 92 6 48 1 63 60
Card 157: 86 26 6 43 83 10 63 79 23 80 | 71 10 25 30 49 73 93 29 55 13 61 34 37 20 48 3 95 96 28 82 5 12 18 62 38
Card 158: 25 90 71 67 30 62 3 44 70 64 | 26 18 25 5 90 22 36 71 64 21 79 1 82 93 14 67 19 45 80 44 40 63 20 87 91
Card 159: 52 17 61 50 12 31 10 96 6 82 | 47 50 31 2 53 85 43 80 10 30 13 56 67 19 12 6 7 96 86 61 16 94 52 66 49
Card 160: 40 29 83 42 41 87 26 15 39 31 | 28 42 95 96 87 78 40 48 26 41 85 84 89 83 82 27 98 68 73 53 24 4 29 32 58
Card 161: 22 17 1 83 37 87 41 64 90 70 | 40 6 91 68 22 1 52 94 84 5 72 21 3 37 80 17 51 24 50 9 61 79 99 95 35
Card 162: 77 35 2 19 78 14 3 94 56 39 | 44 66 3 25 58 55 24 38 16 54 89 1 60 43 72 68 79 22 65 69 86 21 76 18 91
Card 163: 89 21 76 57 18 31 82 42 83 36 | 16 64 59 84 29 18 48 99 5 2 97 50 73 42 46 30 92 57 9 87 10 89 65 27 83
Card 164: 63 66 76 23 39 3 83 50 74 47 | 15 75 36 6 55 85 90 10 84 14 7 57 35 95 40 49 31 42 70 65 1 72 62 92 25
Card 165: 3 87 50 13 90 51 68 34 73 99 | 35 6 24 4 27 57 39 31 88 56 95 14 85 36 15 5 59 86 66 11 76 29 19 30 38
Card 166: 38 40 32 54 73 11 63 3 47 98 | 82 1 72 93 17 25 69 85 57 75 27 89 22 88 61 78 59 3 95 71 70 28 53 41 35
Card 167: 65 76 70 32 57 71 66 53 8 16 | 31 2 56 82 21 69 59 94 36 44 93 51 15 91 48 99 1 55 68 14 19 7 27 5 85
Card 168: 58 95 66 45 85 56 8 97 82 50 | 53 49 46 88 59 78 90 96 2 76 43 83 1 17 21 19 41 91 32 51 27 89 65 34 7
Card 169: 56 19 4 48 97 63 2 88 98 66 | 71 19 39 34 2 48 35 88 8 4 63 97 65 28 12 92 37 55 83 66 56 59 3 72 7
Card 170: 24 94 50 99 33 97 75 86 35 65 | 79 13 50 15 97 99 33 8 35 6 76 17 38 21 73 86 75 24 30 10 69 65 11 90 94
Card 171: 32 49 8 61 74 78 30 72 54 2 | 86 25 72 47 59 29 44 35 82 61 77 5 42 43 15 53 33 57 27 83 71 30 63 56 37
Card 172: 71 41 56 85 78 2 61 72 32 20 | 58 8 56 15 34 82 25 54 48 41 10 6 27 2 72 30 52 9 14 40 68 5 78 62 19
Card 173: 51 21 69 26 46 44 94 16 72 2 | 58 74 89 26 31 21 62 36 79 83 2 28 87 51 72 10 73 12 7 37 4 69 8 29 44
Card 174: 72 51 17 66 87 44 86 95 34 75 | 86 51 76 44 82 23 56 26 18 54 22 28 61 38 27 66 75 42 96 41 13 34 33 95 43
Card 175: 98 99 68 95 29 23 22 28 3 10 | 19 99 22 50 48 82 95 39 86 40 69 28 41 29 24 36 46 78 85 54 60 32 96 61 37
Card 176: 16 84 47 66 30 85 37 89 25 53 | 39 57 94 95 78 81 5 85 34 56 26 98 73 80 96 15 86 54 20 59 9 33 8 87 29
Card 177: 62 5 80 3 9 97 32 81 17 23 | 3 97 38 5 23 42 48 60 9 57 50 92 84 75 32 62 7 8 81 80 49 78 52 64 17
Card 178: 89 60 24 84 47 34 32 31 9 98 | 89 22 85 24 78 40 86 34 29 79 46 83 32 1 77 68 93 31 12 60 98 7 5 65 2
Card 179: 87 70 18 66 65 37 84 95 4 21 | 36 39 57 21 54 17 96 95 72 53 16 45 73 81 38 70 6 18 87 9 8 59 12 7 41
Card 180: 96 21 90 20 72 75 47 83 59 42 | 9 52 61 97 51 80 65 28 23 18 84 6 99 15 53 92 45 3 58 91 81 73 32 17 16
Card 181: 69 49 79 61 19 76 34 54 30 52 | 59 70 37 41 67 21 84 50 89 20 17 9 74 72 7 45 11 92 47 42 32 73 10 82 76
Card 182: 80 88 66 69 51 8 65 28 92 18 | 18 91 16 94 92 21 38 10 88 95 86 22 32 80 12 93 71 28 37 40 67 1 39 60 19
Card 183: 3 83 17 55 42 4 99 52 8 28 | 37 19 68 46 63 14 71 34 6 20 62 65 67 66 77 29 80 74 39 7 75 56 82 4 94
Card 184: 72 20 13 43 1 6 70 15 86 16 | 6 34 50 73 43 28 99 64 24 59 15 37 29 81 69 9 13 1 16 71 20 32 83 67 10
Card 185: 70 15 2 44 20 32 99 71 97 84 | 84 82 66 15 97 21 34 90 71 35 96 31 10 58 20 40 19 16 13 48 44 55 88 32 99
Card 186: 57 49 47 23 51 73 24 13 99 97 | 83 79 62 57 91 78 54 90 17 26 42 87 3 56 51 13 23 27 85 58 73 72 99 61 9
Card 187: 98 37 70 99 40 51 26 24 9 38 | 92 83 10 87 77 57 89 37 27 12 6 13 95 14 82 1 43 81 29 21 74 28 51 30 98
Card 188: 95 92 24 42 63 84 14 49 32 12 | 56 5 32 34 68 43 70 58 83 62 31 40 42 72 49 86 19 65 77 64 53 84 51 36 14
Card 189: 6 73 64 8 38 87 46 22 49 90 | 8 17 62 47 59 24 9 95 46 81 41 35 40 72 73 18 39 78 28 98 3 88 4 66 86
Card 190: 26 75 89 96 83 78 16 3 45 97 | 32 73 53 21 65 25 17 58 51 49 84 24 96 40 35 20 7 77 64 97 67 99 61 52 46
Card 191: 15 47 16 32 63 94 33 85 74 26 | 14 43 66 6 92 7 10 22 88 1 29 91 64 84 83 48 42 54 60 35 96 82 49 9 90
Card 192: 29 68 86 19 93 50 55 5 12 41 | 83 36 30 69 40 16 38 54 99 61 21 79 81 41 65 3 26 27 31 35 39 8 25 49 70
Card 193: 53 40 5 39 13 12 27 57 68 45 | 67 10 87 64 22 6 77 17 20 24 78 52 19 18 99 88 66 31 65 47 11 61 90 9 92
""".trimIndent() | 0 | Kotlin | 0 | 0 | 660d1a5733dd533aff822f0e10166282b8e4bed9 | 26,435 | AOC2023 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/_2022/Day4.kt | thebrightspark | 227,161,060 | false | {"Kotlin": 548420} | package _2022
import aoc
import parseInput
import java.util.regex.Pattern
private val REGEX = Pattern.compile("(\\d+)-(\\d+),(\\d+)-(\\d+)")
fun main() {
aoc(2022, 4) {
aocRun { input ->
process(input, ::hasFullyContainedSections)
}
aocRun { input ->
process(input, ::hasOverlappedSections)
}
}
}
private fun process(input: String, comparison: (elf1: Pair<Int, Int>, elf2: Pair<Int, Int>) -> Boolean): Long =
parseInput(REGEX, input) {
(it.group(1).toInt() to it.group(2).toInt()) to (it.group(3).toInt() to it.group(4).toInt())
}.sumOf { pair -> if (comparison(pair.first, pair.second)) 1L else 0L }
private fun hasFullyContainedSections(elf1: Pair<Int, Int>, elf2: Pair<Int, Int>): Boolean =
(elf1.first >= elf2.first && elf1.second <= elf2.second) || (elf2.first >= elf1.first && elf2.second <= elf1.second)
private fun hasOverlappedSections(elf1: Pair<Int, Int>, elf2: Pair<Int, Int>): Boolean =
hasFullyContainedSections(elf1, elf2)
|| isBetween(elf1.first, elf2) || isBetween(elf1.second, elf2)
|| isBetween(elf2.first, elf1) || isBetween(elf2.second, elf1)
private fun isBetween(num: Int, pair: Pair<Int, Int>): Boolean = num >= pair.first && num <= pair.second
| 0 | Kotlin | 0 | 0 | ac62ce8aeaed065f8fbd11e30368bfe5d31b7033 | 1,202 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/Utils.kt | buczebar | 572,864,830 | false | {"Kotlin": 39213} | import java.io.File
import java.lang.IllegalArgumentException
import kotlin.math.abs
/**
* Reads lines from the given input txt file.
*/
fun readInput(name: String) = File("src", "$name.txt")
.readLines()
/**
* Reads input separated by empty line
*/
fun readGroupedInput(name: String) = File("src", "$name.txt").readText().split("\n\n")
fun List<String>.splitLinesToInts() = map { it.split("\n").toListOfInts() }
fun List<String>.toListOfInts() = map { it.toInt() }
fun <T> List<T>.allDistinct() = distinct().size == size
fun <T> List<T>.pair(): Pair<T, T> =
if (size == 2) Pair(this[0], this[1]) else throw IllegalArgumentException("Input array has wrong size")
fun String.remove(regex: Regex) = replace(regex, "")
fun String.splitWords() = split(" ")
fun <T> List<List<T>>.transpose(): List<List<T>> {
val desiredSize = maxOf { it.size }
val resultList = List<MutableList<T>>(desiredSize) { mutableListOf() }
forEach { list ->
list.forEachIndexed { index, item ->
resultList[index].add(item)
}
}
return resultList
}
fun <T> List<T>.head() = first()
fun <T> List<T>.dropHead() = drop(1)
fun String.getAllInts() = "(-?\\d+)".toRegex().findAll(this).map { it.value.toInt() }.toList()
fun String.getAllByRegex(regex: Regex) = regex.findAll(this).map { it.value }.toList()
fun List<Long>.factorial() = reduce { acc, it -> acc * it }
fun List<Int>.factorial() = reduce { acc, it -> acc * it }
typealias Position = Pair<Int, Int>
operator fun Position.plus(other: Position) = Position(x + other.x, y + other.y)
operator fun Position.minus(other: Position) = Position(x - other.x, y - other.y)
val Position.x: Int
get() = first
val Position.y: Int
get() = second
fun Position.manhattanDistanceTo(other: Position) = abs(x - other.x) + abs(y - other.y)
fun <T> MutableList<T>.popHead(): T {
val head = head()
removeFirst()
return head
}
fun IntRange.limitValuesInRange(valueRange: IntRange): IntRange {
return first.coerceAtLeast(valueRange.first)..last.coerceAtMost(valueRange.last)
}
fun List<Int>.valueRange(): IntRange {
return min()..max()
}
| 0 | Kotlin | 0 | 0 | cdb6fe3996ab8216e7a005e766490a2181cd4101 | 2,144 | advent-of-code | Apache License 2.0 |
src/aoc22/Day16.kt | mihassan | 575,356,150 | false | {"Kotlin": 123343} | @file:Suppress("PackageDirectoryMismatch")
package aoc22.day16
import kotlin.math.max
import kotlin.math.min
import lib.Collections.headTail
import lib.Solution
import lib.Strings.extractLongs
typealias RoomLabel = String
typealias Distance = Long
data class Room(val label: RoomLabel, val flowRate: Long, val tunnels: Map<RoomLabel, Distance>) {
val hasPositiveFlow by lazy { flowRate > 0 }
val initialRoom by lazy { label == INITIAL_ROOM_LABEL }
companion object {
private const val INITIAL_ROOM_LABEL = "AA"
fun parse(line: String): Room {
val flowRate = line.extractLongs().single()
val (label, connectedRooms) = Regex("[A-Z]{2}")
.findAll(line)
.map(MatchResult::value)
.toList()
.headTail()
val tunnels = connectedRooms.associateWith { 1L }
return Room(label!!, flowRate, tunnels)
}
}
}
typealias Input = Map<RoomLabel, Room>
typealias Output = String
private val solution = object : Solution<Input, Output>(2022, "Day16") {
override fun parse(input: String): Input =
input.lines().map { Room.parse(it) }.associateBy { it.label }
override fun format(output: Output): String {
return output
}
override fun part1(input: Input): Output {
val selectiveRooms = getSelectiveRooms(input).associateBy { it.label }
return "${calculateMaxPressureRelease(selectiveRooms, 30L, false)}"
}
override fun part2(input: Input): Output {
val selectiveRooms = getSelectiveRooms(input).associateBy { it.label }
return "${calculateMaxPressureRelease(selectiveRooms, 26L, true)}"
}
}
/**
* Use Floyd–Warshall algorithm to compute the shortest path distance between all pair of rooms.
*/
private fun getShortestPaths(input: Input): Map<Pair<RoomLabel, RoomLabel>, Long> {
val distances = mutableMapOf<Pair<RoomLabel, RoomLabel>, Long>().withDefault { 1_000_000_000 }
input.keys.forEach {
distances[it to it] = 0
}
input.forEach { (fromLabel, fromRoom) ->
fromRoom.tunnels.forEach { (toLabel, distance) ->
distances[fromLabel to toLabel] = distance
}
}
input.keys.forEach { k ->
input.keys.forEach { i ->
input.keys.forEach { j ->
distances[i to j] = min(
distances.getValue(i to j),
distances.getValue(i to k) + distances.getValue(k to j)
)
}
}
}
return distances
}
/**
* Get rooms with positive flows or the initial room and shortest distance to all other rooms.
*/
private fun getSelectiveRooms(input: Input): List<Room> {
val shortestPaths = getShortestPaths(input)
val selectedRoomLabels = input.values
.filter { it.initialRoom || it.hasPositiveFlow }
.map { it.label }
return selectedRoomLabels.map { fromLabel ->
val tunnels = selectedRoomLabels.associateWith { toLabel ->
shortestPaths[fromLabel to toLabel]!!
}
input[fromLabel]!!.copy(tunnels = tunnels)
}
}
private fun calculateMaxPressureRelease(
input: Input,
totalMinutes: Long,
extraHelper: Boolean,
): Long {
var result = 0L
data class Location(val roomLabel: RoomLabel, val remainingDistance: Distance) {
val room by lazy { input[roomLabel]!! }
}
fun releasePressure(
minutesLeft: Long,
pressureReleased: Map<RoomLabel, Long>,
location: Location,
): Map<RoomLabel, Long> {
if (location.remainingDistance > 0L)
return pressureReleased
val nextPressureReleased =
pressureReleased + (location.roomLabel to (location.room.flowRate * minutesLeft))
result = max(result, nextPressureReleased.values.sum())
return nextPressureReleased
}
fun openLocations(
seenRooms: Set<RoomLabel>,
minutesLeft: Long,
location: Location,
): List<Location> {
return location.room.tunnels
.mapNotNull { (nextRoomLabel, distance) ->
if (nextRoomLabel !in seenRooms && minutesLeft > distance + 1) {
Location(nextRoomLabel, distance + 1)
} else {
null
}
}
}
fun dfs(
seenRooms: Set<RoomLabel>,
minutesLeft: Long,
pressureReleased: Map<RoomLabel, Long>,
extraHelper: Boolean,
location: Location,
) {
val nextPressureReleased = releasePressure(minutesLeft, pressureReleased, location)
val nextSeenRooms = seenRooms + location.roomLabel
if (location.remainingDistance > 0) {
val nextMinutesLeft = minutesLeft - location.remainingDistance
val nextLocation = location.copy(remainingDistance = 0L)
dfs(nextSeenRooms, nextMinutesLeft, nextPressureReleased, extraHelper, nextLocation)
} else {
openLocations(nextSeenRooms, minutesLeft, location)
.forEach { nextLocation ->
dfs(nextSeenRooms, minutesLeft, nextPressureReleased, extraHelper, nextLocation)
}
if (extraHelper) {
openLocations(nextSeenRooms, totalMinutes, Location("AA", 0L))
.forEach { nextLocation ->
dfs(nextSeenRooms, totalMinutes, nextPressureReleased, false, nextLocation)
}
}
}
}
dfs(emptySet(), totalMinutes, emptyMap(), extraHelper, Location("AA", 0L))
return result
}
fun main() = solution.run()
| 0 | Kotlin | 0 | 0 | 698316da8c38311366ee6990dd5b3e68b486b62d | 5,146 | aoc-kotlin | Apache License 2.0 |
src/Day03.kt | BjornstadThomas | 572,616,128 | false | {"Kotlin": 9666} | fun main() {
fun getValueOfChar(char: Char): Int {
// println(char)
if (char.toInt() in 97..122)
return char.toInt() - 96 //Fjerner 96 fra verdien, da ASCII for Liten bokstav, starter på 97 (a)
else
return char.toInt() - 38 //Fjerner kun 38, da ASCII for Stor bokstav, starter på 65 (A)
}
fun checkForCommonCharAndGetValue(firstPart: String, secondPart: String): Int {
var commonChars = ' '
for (i in 0 until firstPart.length) {
for (j in 0 until secondPart.length) {
if (firstPart[i] == secondPart[j]) {
commonChars = firstPart[i]
}
}
if (commonChars.isLetter()) {
return getValueOfChar(commonChars)
}
}
println("Fant INGEN?!?!?!? i: " + firstPart + " | " + secondPart)
return 0
}
fun checkForCommonCharInThreeStrings (input: List<String>): Char {
return input
.map { it.toSet() }
.reduce { left, right -> left intersect right }
.first()
}
fun splitString(input: String): String {
val inputSplit = input.split("\r\n")
var score = 0
inputSplit
.map {
val mid = it.length / 2
val part1 = it.substring(0, mid)
val part2 = it.substring(mid)
// println("Del 1: " + part1)
// println("Del 2: " + part2)
val valueOfChar = checkForCommonCharAndGetValue(part1, part2)
score += valueOfChar
}
return score.toString()
}
fun splitStringPart2(input: String): String {
val inputSplit = input.split("\r\n")
var score = 0
val chunked = inputSplit.chunked(3)
// println(chunked)
chunked.forEachIndexed { index, strings ->
// println("Index $index med $strings ")
val common = checkForCommonCharInThreeStrings(strings)
// println("Common: " + common)
score += getValueOfChar(common)
}
return score.toString()
}
fun part1(input: String): String {
return splitString(input)
}
fun part2(input: String): String {
return splitStringPart2(input)
}
val input = readInput("input_Day03")
println("Sum av bokstaver (Del 1): " + part1(input))
println("Sum av authentication-badge (Del 2): " + part2(input))
}
| 0 | Kotlin | 0 | 0 | 553e3381ca26e1e316ecc6c3831354928cf7463b | 2,499 | AdventOfCode-2022-Kotlin | Apache License 2.0 |
src/Day13.kt | zfz7 | 573,100,794 | false | {"Kotlin": 53499} | import java.lang.Exception
fun main() {
println(day13A(readFile("Day13")))
println(day13B(readFile("Day13")))
}
private fun sort(a: List<Any>, b: List<Any>): Int {
try {
isSmaller(a, b)
} catch (e: Exception) {
if (e.message == "true") {
return -1
}
if (e.message == "false") {
return 1
}
if (e.message == "help") {
throw e
}
}
return 0
}
private fun isSmaller(a: List<Any>, b: List<Any>) {
if (a.isEmpty() && b.isEmpty()) {
return
} else if (a.isNotEmpty() && b.isEmpty()) {
throw Exception("false")
} else if (a.isEmpty() && b.isNotEmpty()) {
throw Exception("true")
}
if (a.getOrNull(0) is Int && b.getOrNull(0) is Int) {
if (a[0] as Int == b[0] as Int) {
isSmaller(a.subList(1, a.size), b.subList(1, b.size))
} else {
throw Exception("${(a[0] as Int) < (b[0] as Int)}")
}
} else if (a.getOrNull(0) is List<*> && b.getOrNull(0) is List<*>) {
isSmaller((a[0] as List<Any>), (b[0] as List<Any>))
isSmaller(a.subList(1, a.size), b.subList(1, b.size))
} else if (a.getOrNull(0) is Int && b.getOrNull(0) is List<*>) {
isSmaller(listOf(a[0]), b[0] as List<Any>)
isSmaller(a.subList(1, a.size), b.subList(1, b.size))
} else if (a.getOrNull(0) is List<*> && b.getOrNull(0) is Int) {
isSmaller(a[0] as List<Any>, listOf(b[0]))
isSmaller(a.subList(1, a.size), b.subList(1, b.size))
}
// throw Exception("help")
}
fun day13B(input: String): Int {
var packets: List<List<Any>> = input.trim().split("\n\n").flatMap { pair ->
val a: List<Any> = toList(pair.split("\n")[0])
val b: List<Any> = toList(pair.split("\n")[1])
if (a.toString().replace(" ", "") != pair.split("\n")[0].trim().replace(" ", "")) {
println(a.toString().replace(" ", ""))
println(pair.split("\n")[0])
}
if (b.toString().replace(" ", "") != pair.split("\n")[1].trim().replace(" ", "")) {
println(b.toString().replace(" ", ""))
println(pair.split("\n")[1])
}
listOf(a,b)
}
packets = packets + listOf(listOf(listOf(2))) +listOf(listOf(listOf(6)))
val sorted = packets.sortedWith{a,b->sort(a,b)}
// sorted.forEach{println(it)}
// println(sorted.indexOf(listOf(listOf(2))))
// println(sorted.indexOf(listOf(listOf(6))))
return (sorted.indexOf(listOf(listOf(2))) +1) * (sorted.indexOf(listOf(listOf(6)))+1)
}
fun day13A(input: String): Int {
var sum = 0
input.trim().split("\n\n").mapIndexed { idx, pair ->
val a: List<Any> = toList(pair.split("\n")[0])
val b: List<Any> = toList(pair.split("\n")[1])
if (a.toString().replace(" ", "") != pair.split("\n")[0].trim().replace(" ", "")) {
println(a.toString().replace(" ", ""))
println(pair.split("\n")[0])
}
if (b.toString().replace(" ", "") != pair.split("\n")[1].trim().replace(" ", "")) {
println(b.toString().replace(" ", ""))
println(pair.split("\n")[1])
}
if (sort(a, b) < 0)
sum += (idx + 1)
}
return sum
}
fun toList(s: String): List<Any> {
var currentIdx = 0;
return s.removePrefix("[").removeSuffix("]").mapIndexedNotNull { idx, it ->
if (idx < currentIdx) {
null
} else if (it == '[') {
var i = idx + 2
var count = 1
while (count != 0) {
if (s[i] == ']') {
count--
} else if (s[i] == '[') {
count++
}
i++
}
currentIdx = i
toList(s.substring(idx + 1, i))
} else if (it == ',' || it == ']') {
null
} else {
currentIdx = idx + s.substring(idx + 1).split(",", "]")[0].length
s.substring(idx + 1).split(",", "]")[0].toInt()
}
}
}
| 0 | Kotlin | 0 | 0 | c50a12b52127eba3f5706de775a350b1568127ae | 4,059 | AdventOfCode22 | Apache License 2.0 |
src/Day03.kt | undermark5 | 574,819,802 | false | {"Kotlin": 67472} | fun main() {
fun part1(input: List<String>): Int {
val intList = input.flatMap {
val size = it.length / 2
val first = it.take(size).toSet()
val second = it.takeLast(size).toSet()
val intersect = first.intersect(second)
check(intersect.size == 1)
intersect.map {
when (it) {
in 'a'..'z' -> it - 'a' + 1
in 'A'..'Z' -> it - 'A' + 27
else -> 0
}
}
}
return intList.sum()
}
fun part2(input: List<String>): Int {
val groups = input.windowed(3, 3)
return groups.flatMap {
it.map { it.toSet() }.reduce(Set<Char>::intersect).map {
when (it) {
in 'a'..'z' -> it - 'a' + 1
in 'A'..'Z' -> it - 'A' + 27
else -> 0
}
}
}.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
val part1 = part1(testInput)
check(part1 == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | e9cf715b922db05e1929f781dc29cf0c7fb62170 | 1,271 | AoC_2022_Kotlin | Apache License 2.0 |
src/main/kotlin/com/chriswk/aoc/advent2015/Day13.kt | chriswk | 317,863,220 | false | {"Kotlin": 481061} | package com.chriswk.aoc.advent2015
import com.chriswk.aoc.AdventDay
import com.chriswk.aoc.util.permutations
import com.chriswk.aoc.util.report
class Day13 : AdventDay(2015, 13) {
companion object {
val happinessLine = """(.+) would (lose|gain) (\d+) happiness units by sitting next to (.+).""".toRegex()
@JvmStatic
fun main(args: Array<String>) {
val day = Day13()
report {
day.part1()
}
report {
day.part2()
}
}
}
val inputRelationships: List<Match> = inputAsLines.map { Match.fromLine(it) }
fun calculateHappiness(seatings: List<String>, relations: Map<Pair<String, String>, Match>): Int {
val pairs = seatings.windowed(2).map { it.first() to it.last() } + (seatings.first() to seatings.last())
return pairs.sumOf { relations[it.first to it.second]!!.happinessDelta + relations[it.second to it.first]!!.happinessDelta }
}
fun maxHappinessDelta(relationShips: List<Match>): Int {
val people = relationShips.map { it.person1 }.distinct().toList()
val allRelations = relationShips.associateBy { (it.person1 to it.person2) }
return people.permutations().maxOfOrNull { calculateHappiness(it, allRelations) } ?: 0
}
fun part1(): Int {
return maxHappinessDelta(inputRelationships)
}
fun addSelf(relationShips: List<Match>, name: String = "CWK"): List<Match> {
return relationShips + relationShips.map { it.person1 }.distinct()
.flatMap { listOf(Match(name, it, 0), Match(it, name, 0)) }
}
fun part2(): Int {
return maxHappinessDelta(addSelf(inputRelationships))
}
data class Match(val person1: String, val person2: String, val happinessDelta: Int) {
companion object {
fun fromLine(line: String): Match {
val (p1, result, delta, p2) = happinessLine.find(line)!!.destructured
val deltaInt = delta.toInt()
val happinessDelta = when (result) {
"gain" -> deltaInt
"lose" -> -deltaInt
else -> 0
}
return Match(p1, p2, happinessDelta)
}
}
}
}
| 116 | Kotlin | 0 | 0 | 69fa3dfed62d5cb7d961fe16924066cb7f9f5985 | 2,284 | adventofcode | MIT License |
src/main/kotlin/Excercise03.kt | underwindfall | 433,989,850 | false | {"Kotlin": 55774} | private fun part1() {
val input = getInputAsTest("03") { split("\n") }
val length = input.first().length
val gamma =
(0 until length).map { input.countBits(it) }.joinToString("") { (zeros, ones) ->
if (zeros > ones) "0" else "1"
}
val epsilon = gamma.map { if (it == '0') "1" else "0" }.joinToString("")
println(gamma.toInt(2) * epsilon.toInt(2))
}
private fun part2() {
val input = getInputAsTest("03") { split("\n") }
val length = input.first().length
var oxygen = input.map { it }
var i = 0
while (oxygen.size > 1) {
val (zeros, ones) = oxygen.countBits(i)
oxygen = oxygen.filter { it[i] == if (zeros > ones) '0' else '1' }
i = (i + 1) % length
}
var co2 = input.map { it }
i = 0
while (co2.size > 1) {
val (zeros, ones) = co2.countBits(i)
co2 = co2.filter { it[i] == if (zeros <= ones) '0' else '1' }
i = (i + 1) % length
}
println(oxygen.first().toInt(2) * co2.first().toInt(2))
}
private fun List<String>.countBits(index: Int): Pair<Int, Int> {
var zeros = 0
var ones = 0
this.forEach {
when (it[index]) {
'0' -> zeros++
'1' -> ones++
}
}
return zeros to ones
}
fun main() {
part1()
part2()
}
| 0 | Kotlin | 0 | 0 | 4fbee48352577f3356e9b9b57d215298cdfca1ed | 1,211 | advent-of-code-2021 | MIT License |
codechef/snackdown2021/preelim/decsubk.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codechef.snackdown2021.preelim
private fun solve(): IntArray {
val (_, k) = readInts()
val a = readInts().sorted()
val b = IntArray(a.size)
val used = BooleanArray(a.size)
for (x in a.indices) {
fun isGood(i: Int): Boolean {
b[x] = a[i]
var y = x + 1
for (j in a.indices) if (!used[j] && j != i) b[y++] = a[j]
val max = longestNondecreasingSubsequence(b)
b.reverse(x + 1, b.size)
val min = longestNondecreasingSubsequence(b)
return k in min..max
}
val i = a.indices.firstOrNull { !used[it] && isGood(it) } ?: return intArrayOf(-1)
used[i] = true
}
return b
}
private fun longestNondecreasingSubsequence(a: IntArray): Int {
val dp = IntArray(a.size)
for (i in a.indices) {
for (j in 0 until i) if (a[j] <= a[i]) dp[i] = maxOf(dp[i], dp[j])
dp[i]++
}
return dp.maxOrNull()!!
}
@Suppress("UNUSED_PARAMETER") // Kotlin 1.2
fun main(args: Array<String>) = repeat(readInt()) { println(solve().joinToString(" ")) }
private fun readLn() = readLine()!!.trim()
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,154 | competitions | The Unlicense |
src/Day03.kt | Feketerig | 571,677,145 | false | {"Kotlin": 14818} | fun main(){
fun priority(char: Char): Int{
return if (char < 'a') char - 'A' + 1 + 26 else char - 'a' + 1
}
fun findCommonElement(line: String): Int {
val firstHalf = line.subSequence(0, line.length / 2).toSet()
val secondHalf = line.subSequence(line.length / 2, line.length).toSet()
val commonChar = firstHalf.intersect(secondHalf).first()
return priority(commonChar)
}
fun part1(input: List<String>): Int{
return input.sumOf { findCommonElement(it) }
}
fun findCommonInThreeLine(lines: List<String>): Int{
val commonChar = lines[0].toSet().intersect(lines[1].toSet()).intersect(lines[2].toSet()).first()
return priority(commonChar)
}
fun part2(input: List<String>): Int{
val lines = mutableListOf<String>()
var sum = 0
input.forEachIndexed { index, line ->
lines.add(line)
if ((index + 1) % 3 == 0){
sum += findCommonInThreeLine(lines)
lines.clear()
}
}
return sum
}
val testInput = readInput("Day03_test_input")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03_input")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | c65e4022120610d930293788d9584d20b81bc4d7 | 1,301 | Advent-of-Code-2022 | Apache License 2.0 |
src/Day07.kt | emanguy | 573,113,840 | false | {"Kotlin": 17921} | import java.lang.IllegalArgumentException
import java.util.Stack
sealed class FSEntity {
data class Directory(
val name: String,
val parent: Directory? = null,
val children: MutableList<FSEntity> = mutableListOf()
) : FSEntity() {
private var cachedSize: Long? = null
fun size(): Long {
if (cachedSize == null) {
cachedSize = children.sumOf {
when (it) {
is Directory -> it.size()
is File -> it.size
}
}
}
return cachedSize!!
}
}
data class File(val name: String, val size: Long) : FSEntity()
}
fun main() {
fun parseInput(inputs: List<String>): FSEntity.Directory {
var workingDirectory = FSEntity.Directory("/")
for (input in inputs) {
// The initial cd / and ls commands are effectively no-ops in terms of parsing
if (input == "$ cd /" || input == "$ ls") continue
// Doing a command
if (input.startsWith("$")) { // Handle a directory change
val targetDirectory = input.removePrefix("$ cd ")
workingDirectory = if (targetDirectory == "..") {
// We can't go higher than root
workingDirectory.parent ?: workingDirectory
} else {
workingDirectory.children.find { it is FSEntity.Directory && it.name == targetDirectory } as FSEntity.Directory?
?: throw IllegalArgumentException("Cannot enter nonexistent directory: $targetDirectory")
}
} else if (input.startsWith("dir ")) { // Handling a directory
workingDirectory.children += FSEntity.Directory(input.removePrefix("dir "), workingDirectory)
} else { // Handling a file
val (size, name) = input.split(" ")
workingDirectory.children += FSEntity.File(name, size.toLong())
}
}
while (workingDirectory.parent != null) {
workingDirectory = workingDirectory.parent!!
}
return workingDirectory
}
fun allDirectoriesInFs(directoryRoot: FSEntity.Directory): MutableList<FSEntity.Directory> {
val allDirectories = mutableListOf(directoryRoot)
val directoriesToCheck = Stack<FSEntity.Directory>()
directoriesToCheck += directoryRoot
while (directoriesToCheck.isNotEmpty()) {
val currentDirectory = directoriesToCheck.pop()
val childDirectories = currentDirectory.children.filterIsInstance<FSEntity.Directory>()
allDirectories.addAll(childDirectories)
directoriesToCheck.addAll(childDirectories)
}
return allDirectories
}
fun part1(inputs: List<String>): Long {
val directoryRoot = parseInput(inputs)
val allDirectories = allDirectoriesInFs(directoryRoot)
return allDirectories.filter { it.size() <= 100_000 }.sumOf { it.size() }
}
fun part2(inputs: List<String>): Long {
val directoryRoot = parseInput(inputs)
val allDirectories = allDirectoriesInFs(directoryRoot)
val totalDiskSize = 70_000_000L
val requiredEmptySpace = 30_000_000L
val currentDiskUsage = directoryRoot.size()
val currentFreeSpace = totalDiskSize - currentDiskUsage
val amountToDelete = requiredEmptySpace - currentFreeSpace
allDirectories.sortBy { it.size() }
return allDirectories.first { it.size() >= amountToDelete }.size()
}
// Verify the sample input works
val inputs = readInput("Day07_test")
check(part1(inputs) == 95437L)
check(part2(inputs) == 24933642L)
val finalInputs = readInput("Day07")
println(part1(finalInputs))
println(part2(finalInputs))
}
| 0 | Kotlin | 0 | 1 | 211e213ec306acc0978f5490524e8abafbd739f3 | 3,898 | advent-of-code-2022 | Apache License 2.0 |
aoc-2022/src/main/kotlin/nerok/aoc/aoc2022/day07/Day07_alt.kt | nerok | 572,862,875 | false | {"Kotlin": 113337} | package nerok.aoc.aoc2022.day07
import nerok.aoc.utils.Input
import kotlin.time.DurationUnit
import kotlin.time.measureTime
fun main() {
fun part1(input: String): Long {
val root = Directory("/", null, emptyList<FSNode>().toMutableList())
var pwd = root
input.lines().drop(1).forEach { line ->
when {
line == "$ cd /" -> {
pwd = root
}
line == "$ cd .." -> {
pwd = pwd.parent ?: root
}
line.startsWith("$ cd ") -> {
val name = line.removePrefix("$ cd ")
pwd = pwd.children.filterIsInstance<Directory>().find { it.name == name }!!
}
line.isEmpty() -> {}
line == "$ ls" -> {}
line.startsWith("dir ") -> {
pwd.children.add(Directory(line.removePrefix("dir "), pwd, emptyList<FSNode>().toMutableList()))
}
else -> pwd.children.add(Files(line.split(" ").last(), pwd, line.split(" ").first().toLong()))
}
}
return input.length.toLong()
}
// test if implementation meets criteria from the description, like:
val testInput = Input.getInput("Day07_test")
check(part1(testInput) == 95437L)
val input = Input.getInput("Day07")
println(measureTime { println(part1(input)) }.toString(DurationUnit.SECONDS, 3))
}
abstract class FSNode(
val name: String,
val parent: Directory?
) {
abstract fun size(): Long
}
class Directory(
name: String,
parent: Directory?,
val children: MutableList<FSNode>,
) : FSNode(name, parent) {
override fun size(): Long {
return children.sumOf { it.size() }
}
}
class Files(
name: String,
parent: Directory,
private var size: Long
) : FSNode(name, parent) {
override fun size() = size
}
| 0 | Kotlin | 0 | 0 | 7553c28ac9053a70706c6af98b954fbdda6fb5d2 | 1,933 | AOC | Apache License 2.0 |
src/Day04.kt | mpylypovych | 572,998,434 | false | {"Kotlin": 6455} | fun main() {
fun contains(x: List<Int>, y: List<Int>) = y.all { x.first() <= it && x.last() >= it }
fun containsAny(x: List<Int>, y: List<Int>) = y.any { x.first() <= it && x.last() >= it }
fun solve(input: List<String>, pred : (List<Int>, List<Int>) -> Boolean) =
input.map {
it.split(',')
.map {
it.split('-').map { it.toInt() }
}
}
.sumOf { row -> if(pred(row.first(), row.last()) || pred(row.last(), row.first())) 1 else 0.toInt() }
fun part1(input: List<String>) = solve(input, ::contains)
fun part2(input: List<String>) = solve(input, ::containsAny)
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 733b35c3f4eea777a5f666c804f3c92d0cc9854b | 869 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day17.kt | cypressious | 572,898,685 | false | {"Kotlin": 77610} | fun main() {
data class P(val x: Int, val y: Int)
val rocks = listOf(
// -
listOf(P(0, 0), P(1, 0), P(2, 0), P(3, 0)),
// +
listOf(P(1, 0), P(0, 1), P(1, 1), P(2, 1), P(1, 2)),
// reverse L
listOf(P(0, 0), P(1, 0), P(2, 0), P(2, 1), P(2, 2)),
// reverse I
listOf(P(0, 0), P(0, 1), P(0, 2), P(0, 3)),
// square
listOf(P(0, 0), P(1, 0), P(0, 1), P(1, 1)),
)
fun compute(jets: String, maxRocks: Long): Long {
var jet = 0
val settled = mutableListOf<BooleanArray>()
var rockIndex = 0
var dx = 2
var dy = 3
var fallenRocks = 0L
var lastRock = 0
var lastSize = 0
var lastRocks = 0L
var skipped = 0L
while (fallenRocks < maxRocks) {
// very sorry
if (jet == 0 && rockIndex == 3) {
val remainingRocks = maxRocks - fallenRocks
val iterations = remainingRocks / 1715
skipped = iterations * 2574
fallenRocks += iterations * 1715
println("rock: $lastRock, fallen: ${fallenRocks - lastRocks}, growth: ${settled.size - lastSize}")
lastRock = rockIndex
lastSize = settled.size
lastRocks = fallenRocks
}
val rock = rocks[rockIndex]
// jet
val offset = if (jets[jet] == '>') 1 else -1
jet = (jet + 1) % jets.length
var collision = rock.any { p ->
val newX = p.x + dx + offset
newX < 0 || newX >= 7 || settled.getOrNull(p.y + dy)?.get(newX) ?: false
}
if (!collision) dx += offset
// falling
val lowestRockY = rock[0].y + dy - 1
collision = lowestRockY == -1 || (lowestRockY in settled.indices && rock.any { p ->
val newY = p.y + dy - 1
newY in settled.indices && settled[newY][p.x + dx]
})
if (!collision) {
dy--
} else {
// settling
val targetHeight = rock.last().y + dy
while (settled.lastIndex < targetHeight) {
settled += BooleanArray(7)
}
for (p in rock) {
settled[p.y + dy][p.x + dx] = true
}
fallenRocks++
rockIndex = (rockIndex + 1) % rocks.size
dx = 2
dy = settled.lastIndex + 4
}
}
return settled.size + skipped
}
fun part1(input: List<String>): Long {
return compute(input[0], 2022)
}
fun part2(input: List<String>): Long {
return compute(input[0], 1000000000000)
}
// test if implementation meets criteria from the description, like:
// val testInput = readInput("Day17_test")
// check(part1(testInput) == 3068L)
// check(part2(testInput) == 1_514_285_714_288)
//
val input = readInput("Day17")
// println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 7b4c3ee33efdb5850cca24f1baa7e7df887b019a | 3,136 | AdventOfCode2022 | Apache License 2.0 |
src/day11/Code.kt | ldickmanns | 572,675,185 | false | {"Kotlin": 48227} | package day11
import readInput
import java.util.*
fun main() {
val input = readInput("day11/input")
// val input = readInput("day11/input_test")
println(part1(input))
println(part2(input))
}
typealias WorryLevel = Long
data class Monkey(
val items: Deque<WorryLevel>,
val operation: (WorryLevel) -> WorryLevel,
val divisor: Int,
val onTrueMonkeyIndex: Int,
val onFalseMonkeyIndex: Int,
var numberOfInspections: Int = 0,
)
fun part1(input: List<String>): Int {
val monkeys = getMonkeys(input)
repeat(20) {
monkeys.forEach { monkey ->
while (monkey.items.isNotEmpty()) {
val item = monkey.items.pop()
val updatedWorryLevel = monkey.operation(item)
++monkey.numberOfInspections
val lostInterest = updatedWorryLevel / 3
val recipient = if (lostInterest % monkey.divisor == 0L) {
monkeys[monkey.onTrueMonkeyIndex]
} else monkeys[monkey.onFalseMonkeyIndex]
recipient.items.add(lostInterest)
}
}
}
return monkeys.map { it.numberOfInspections }.sortedDescending().take(2).reduce(Int::times)
}
private fun getMonkeys(input: List<String>) = input
.filter { it.isNotEmpty() }
.chunked(6) { monkeyChunk ->
Monkey(
items = getStartingItems(monkeyChunk[1]),
operation = getOperation(monkeyChunk[2]),
divisor = getDivisor(monkeyChunk[3]),
onTrueMonkeyIndex = getTrueMonkey(monkeyChunk[4]),
onFalseMonkeyIndex = getFalseMonkey(monkeyChunk[5]),
)
}
private const val STARTING_ITEMS = "Starting items: "
private const val COMMA = ", "
fun getStartingItems(
string: String
): Deque<WorryLevel> {
val trimmed = string.trim()
val withoutPrefix = trimmed.removePrefix(STARTING_ITEMS)
val split = withoutPrefix.split(COMMA)
val worryLevelList = split.map { it.toLong() }
return LinkedList(worryLevelList)
}
private const val OPERATION = "Operation: new = old "
fun getOperation(
string: String
): (WorryLevel) -> WorryLevel {
val trimmed = string.trim()
val withoutPrefix = trimmed.removePrefix(OPERATION)
val operation: WorryLevel.(WorryLevel) -> WorryLevel = when (withoutPrefix.substringBefore(' ')) {
"+" -> WorryLevel::plus
"*" -> WorryLevel::times
else -> error("Invalid operator")
}
val secondOperand = when (val secondOperandString = withoutPrefix.substringAfter(' ')) {
"old" -> null
else -> secondOperandString.toLong()
}
return { it.operation(secondOperand ?: it) }
}
private const val TEST = "Test: divisible by "
fun getDivisor(
string: String
): Int {
val trimmed = string.trim()
val withoutPrefix = trimmed.removePrefix(TEST)
return withoutPrefix.toInt()
}
private const val TRUE_MONKEY = "If true: throw to monkey "
fun getTrueMonkey(
string: String
): Int {
val trimmed = string.trim()
val withoutPrefix = trimmed.removePrefix(TRUE_MONKEY)
return withoutPrefix.toInt()
}
private const val FALSE_MONKEY = "If false: throw to monkey "
fun getFalseMonkey(
string: String
): Int {
val trimmed = string.trim()
val withoutPrefix = trimmed.removePrefix(FALSE_MONKEY)
return withoutPrefix.toInt()
}
fun part2(input: List<String>): Long {
val monkeys = getMonkeys(input)
val greatestCommonMultiple = monkeys.map { it.divisor.toLong() }.reduce(WorryLevel::times)
repeat(10000) {
monkeys.forEach { monkey ->
while (monkey.items.isNotEmpty()) {
val item = monkey.items.pop()
val updatedWorryLevel = monkey.operation(item) % greatestCommonMultiple
++monkey.numberOfInspections
val recipient = if (updatedWorryLevel % monkey.divisor == 0L) {
monkeys[monkey.onTrueMonkeyIndex]
} else monkeys[monkey.onFalseMonkeyIndex]
recipient.items.add(updatedWorryLevel)
}
}
}
return monkeys
.asSequence()
.map { it.numberOfInspections.toLong() }
.sortedDescending()
.take(2)
.reduce(Long::times)
}
| 0 | Kotlin | 0 | 0 | 2654ca36ee6e5442a4235868db8174a2b0ac2523 | 4,263 | aoc-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/day12/Day12.kt | daniilsjb | 572,664,294 | false | {"Kotlin": 69004} | package day12
import java.io.File
fun main() {
val data = parse("src/main/kotlin/day12/Day12.txt")
val answer1 = part1(data)
val answer2 = part2(data)
println("🎄 Day 12 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private data class Heightmap(
val nodes: String,
val width: Int,
val height: Int,
)
@Suppress("SameParameterValue")
private fun parse(path: String): Heightmap {
val data = File(path).readLines()
val width = data[0].length
val height = data.size
return Heightmap(data.joinToString(separator = ""), width, height)
}
private fun Char.toElevation(): Char =
when (this) {
'S' -> 'a'
'E' -> 'z'
else -> this
}
private fun Char.reaches(other: Char): Boolean =
(other.toElevation() - this.toElevation()) <= 1
private fun Heightmap.neighborsOf(index: Int): List<Int> {
val x = index % width
val y = index / width
val current = nodes[index]
val result = mutableListOf<Int>()
if (x > 0 && current.reaches(nodes[index - 1])) {
result.add(index - 1)
}
if (y > 0 && current.reaches(nodes[index - width])) {
result.add(index - width)
}
if (x < width - 1 && current.reaches(nodes[index + 1])) {
result.add(index + 1)
}
if (y < height - 1 && current.reaches(nodes[index + width])) {
result.add(index + width)
}
return result
}
private fun Heightmap.solve(source: Int): Int? {
val queue = ArrayDeque<Int>()
val distances = Array(nodes.length) { Int.MAX_VALUE }
queue.add(source)
distances[source] = 0
while (queue.isNotEmpty()) {
val vertex = queue.removeFirst()
for (neighbor in neighborsOf(vertex)) {
if (nodes[neighbor] == 'E') {
return distances[vertex] + 1
}
if (distances[neighbor] > distances[vertex] + 1) {
distances[neighbor] = distances[vertex] + 1
queue.add(neighbor)
}
}
}
return null
}
private fun part1(graph: Heightmap): Int {
val source = graph.nodes.indexOfFirst { it == 'S' }
return graph.solve(source) ?: error("Path not found.")
}
private fun part2(graph: Heightmap): Int {
val distances = mutableListOf<Int>()
for ((source, c) in graph.nodes.withIndex()) {
if (c == 'a' || c == 'S') {
distances.add(graph.solve(source) ?: continue)
}
}
return distances.min()
}
| 0 | Kotlin | 0 | 0 | 6f0d373bdbbcf6536608464a17a34363ea343036 | 2,573 | advent-of-code-2022 | MIT License |
src/Day03.kt | maewCP | 579,203,172 | false | {"Kotlin": 59412} | fun main() {
fun getPriority(itemType: Char): Int {
return if (itemType >= 'a') itemType - 'a' + 1 else itemType - 'A' + 27
}
fun part1(input: List<String>): Int {
var priorities = 0
input.forEach { line ->
val first = line.substring(0, line.length / 2)
val second = line.substring(line.length / 2, line.length)
val itemType = first.toSet().intersect(second.toSet()).first()
priorities += getPriority(itemType)
}
return priorities
}
fun part2(input: List<String>): Int {
var priorities = 0
val input2 = input.toMutableList()
while (input2.size > 0) {
val first = input2.removeAt(0)
val second = input2.removeAt(0)
val third = input2.removeAt(0)
val itemType = first.toSet().intersect(second.toSet()).intersect(third.toSet()).first()
priorities += getPriority(itemType)
}
return priorities
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 8924a6d913e2c15876c52acd2e1dc986cd162693 | 1,285 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/Day14.kt | illarionov | 572,508,428 | false | {"Kotlin": 108577} | fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test")
.parseScanReport()
val testInputResult = part1(testInput)
println(testInputResult)
check(testInputResult == 24)
val input = readInput("Day14")
.parseScanReport()
val part1Result = part1(input)
println(part1Result)
//check(part1Result == 832)
val testInputResult2 = part2(testInput)
println(testInputResult2)
//check(testInputResult2 == 93)
val part2Result = part2(input)
println(part2Result)
//check(part2Result == 27601)
}
private const val FIELD_SIZE: Int = 1000
private enum class Point {
AIR, ROCK, SAND
}
private fun part1(input: List<List<Point>>): Int {
val field: List<MutableList<Point>> = input.copy()
var c = 0
var restPoint = getNextRestPoint(field)
while (restPoint != null) {
c += 1
field[restPoint.second][restPoint.first] = Point.SAND
restPoint = getNextRestPoint(field)
}
return c
}
private fun part2(input: List<List<Point>>): Int {
val field: List<MutableList<Point>> = input.copy()
val maxY = (field.size - 1 downTo 0)
.takeWhile { i ->
field[i].all { it == Point.AIR }
}
.last() + 1
field[maxY].indices.forEach { x -> field[maxY][x] = Point.ROCK }
var c = 0
var restPoint2 = getNextRestPoint(field)
while (restPoint2 != null) {
c += 1
field[restPoint2.second][restPoint2.first] = Point.SAND
restPoint2 = getNextRestPoint(field)
}
return c
}
private val directions = listOf(
0 to +1,
-1 to +1,
+1 to +1
)
private fun getNextRestPoint(field: List<List<Point>>): Pair<Int, Int>? {
var x = 500
var y = 0
if (field[y][x] != Point.AIR) return null
while (y < field.lastIndex) {
val d = directions.firstOrNull { d ->
field[y + d.second][x + d.first] == Point.AIR
} ?: break
x += d.first
y += d.second
}
return if (y < field.lastIndex) x to y else null
}
private fun String.parsePath(): List<Pair<Int, Int>> {
return this.split(""" -> """)
.map { p ->
val (start, length) = p.split(",")
start.toInt() to length.toInt()
}
}
private fun List<List<Point>>.copy(): List<MutableList<Point>> {
return List(FIELD_SIZE) { y -> this[y].toMutableList() }
}
private fun List<String>.parseScanReport(): List<List<Point>> {
val field = List(FIELD_SIZE) { MutableList(FIELD_SIZE) { Point.AIR } }
fun range(v1: Int, v2: Int): IntRange {
return if (v1 < v2) v1..v2 else v2..v1
}
this
.map(String::parsePath)
.forEach { path ->
path.zipWithNext()
.forEach { (pred, next) ->
for (y in range(pred.second, next.second)) {
for (x in range(pred.first, next.first)) {
field[y][x] = Point.ROCK
}
}
}
}
return field
}
private fun List<List<Point>>.printField() {
for (y in 0..12) {
for (x in 490..506) {
val p = when (this[y][x]) {
Point.AIR -> '.'
Point.ROCK -> '#'
Point.SAND -> 'o'
}
print(p)
}
println()
}
}
| 0 | Kotlin | 0 | 0 | 3c6bffd9ac60729f7e26c50f504fb4e08a395a97 | 3,422 | aoc22-kotlin | Apache License 2.0 |
src/Day03.kt | l8nite | 573,298,097 | false | {"Kotlin": 105683} | fun main() {
fun score(c: Char): Int {
return if (c.isLowerCase()) {
c.code - 'a'.code + 1 // 1-26
} else {
c.code - 'A'.code + 27 // 27-52
}
}
fun shareChar(list: List<String>): Set<Char> {
val frequencyMap = mutableMapOf<Char, Int>()
list.forEach {
it.toCharArray().toSet().forEach { c ->
frequencyMap.merge(c, 1) { a, b -> a + b }
}
}
return frequencyMap.filter { it.value == list.size }.keys
}
fun part1(input: List<String>): Int {
var score = 0
input.forEach {
score += score(shareChar(it.chunked(it.length/2)).first())
}
return score
}
fun part2(input: List<String>): Int {
var score = 0
input.chunked(3).forEach {
score += score(shareChar(it).first())
}
return score
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f74331778fdd5a563ee43cf7fff042e69de72272 | 1,202 | advent-of-code-2022 | Apache License 2.0 |
src/day08/Day08.kt | martin3398 | 572,166,179 | false | {"Kotlin": 76153} | package day08
import readInput
fun main() {
fun part1(input: Array<IntArray>): Int {
val width = input.size
val height = input[0].size
val visible = Array(height) {
BooleanArray(width) {
false
}
}
for (i in 0 until height) {
visible[i][0] = true
visible[i][width - 1] = true
}
for (i in 0 until width) {
visible[0][i] = true
visible[height - 1][i] = true
}
var maximum: Int
for (i in 1 until height - 1) {
maximum = input[i][0]
for (j in 1 until width - 1) {
if (input[i][j] > maximum) {
maximum = input[i][j]
visible[i][j] = true
}
}
maximum = input[i][width - 1]
for (j in width - 2 downTo 1) {
if (input[i][j] > maximum) {
maximum = input[i][j]
visible[i][j] = true
}
}
}
for (j in 1 until width - 1) {
maximum = input[0][j]
for (i in 1 until height - 1) {
if (input[i][j] > maximum) {
maximum = input[i][j]
visible[i][j] = true
}
}
maximum = input[height - 1][j]
for (i in height - 2 downTo 1) {
if (input[i][j] > maximum) {
maximum = input[i][j]
visible[i][j] = true
}
}
}
return visible.map { it.map { x -> if (x) 1 else 0 }.sum() }.sum()
}
fun part2(input: Array<IntArray>): Int {
val width = input.size
val height = input[0].size
val viewingDistances = Array(height) {
IntArray(width) {
1
}
}
for (i in 0 until height) {
viewingDistances[i][0] = 0
viewingDistances[i][width - 1] = 0
}
for (j in 0 until width) {
viewingDistances[0][j] = 0
viewingDistances[height - 1][j] = 0
}
for (i in 1 until height - 1) {
for (j in 1 until width - 1) {
var dist = 1
while (j - dist > 0 && input[i][j] > input[i][j - dist]) {
dist++
}
viewingDistances[i][j] *= dist
dist = 1
while (j + dist < width - 1 && input[i][j] > input[i][j + dist]) {
dist++
}
viewingDistances[i][j] *= dist
dist = 1
while (i - dist > 0 && input[i][j] > input[i - dist][j]) {
dist++
}
viewingDistances[i][j] *= dist
dist = 1
while (i + dist < height - 1 && input[i][j] > input[i + dist][j]) {
dist++
}
viewingDistances[i][j] *= dist
}
}
return viewingDistances.maxOf { it.max() }
}
fun preprocess(input: List<String>): Array<IntArray> =
input.map { it.map { char -> char.digitToInt() }.toIntArray() }.toTypedArray()
// test if implementation meets criteria from the description, like:
val testInput = readInput(8, true)
check(part1(preprocess(testInput)) == 21)
val input = readInput(8)
println(part1(preprocess(input)))
check(part2(preprocess(testInput)) == 8)
println(part2(preprocess(input)))
}
| 0 | Kotlin | 0 | 0 | 4277dfc11212a997877329ac6df387c64be9529e | 3,605 | advent-of-code-2022 | Apache License 2.0 |
2022/src/day21/Day21.kt | scrubskip | 160,313,272 | false | {"Kotlin": 198319, "Python": 114888, "Dart": 86314} | package day21
import java.io.File
fun main() {
val monkeys = Monkey.parse(File("src/day21/day21input.txt").readLines())
val rootMonkey = monkeys["root"]
println("${monkeys.size}")
println(rootMonkey!!.getValue(monkeys))
println(findHumanValue(monkeys))
}
fun findHumanValue(monkeys: Map<String, Monkey>): Long {
val humanMonkey = monkeys["humn"] as HumanMonkey
val rootMonkey = monkeys["root"] as DependentMonkey
while (!rootMonkey.getEqualValue(monkeys)) {
humanMonkey.currentValue = humanMonkey.getValue(monkeys) + 1
}
return humanMonkey.getValue(monkeys)
}
abstract class Monkey(val key: String) {
abstract fun getValue(monkeys: Map<String, Monkey>): Long
companion object {
fun parse(input: String): Monkey {
// First 4 characters are the key
val key = input.substring(0, 4)
val value = input.substring(6)
val number = value.toLongOrNull()
return if ("humn" == key) {
return HumanMonkey(key)
} else if (number != null) {
NumberMonkey(key, number)
} else {
val key1 = input.substring(6, 6 + 4)
val operation = input.substring(11, 11 + 1)
val key2 = input.substring(13, 13 + 4)
DependentMonkey(key, key1, key2, operation)
}
}
fun parse(input: List<String>): Map<String, Monkey> {
return input.map { parse(it) }.associateBy { monkey -> monkey.key }
}
}
}
class NumberMonkey(key: String, private val value: Long) : Monkey(key) {
override fun getValue(monkeys: Map<String, Monkey>): Long {
return value
}
}
class DependentMonkey(
key: String,
val monkeyKey1: String,
val monkeyKey2: String,
val operation: String
) : Monkey(key) {
override fun getValue(monkeys: Map<String, Monkey>): Long {
val monkeyVal1 = monkeys[monkeyKey1]!!.getValue(monkeys)
val monkeyVal2 = monkeys[monkeyKey2]!!.getValue(monkeys)
return when (operation) {
"+" -> monkeyVal1 + monkeyVal2
"-" -> monkeyVal1 - monkeyVal2
"*" -> monkeyVal1 * monkeyVal2
"/" -> monkeyVal1 / monkeyVal2
else -> throw Exception("Invalid operation $operation")
}
}
fun getEqualValue(monkeys: Map<String, Monkey>): Boolean {
val monkeyVal1 = monkeys[monkeyKey1]!!.getValue(monkeys)
val monkeyVal2 = monkeys[monkeyKey2]!!.getValue(monkeys)
return monkeyVal1 == monkeyVal2
}
}
class HumanMonkey(
key: String
) : Monkey(key) {
var currentValue: Long = 0
override fun getValue(monkeys: Map<String, Monkey>): Long {
return currentValue
}
} | 0 | Kotlin | 0 | 0 | a5b7f69b43ad02b9356d19c15ce478866e6c38a1 | 2,783 | adventofcode | Apache License 2.0 |
src/Day23.kt | fedochet | 573,033,793 | false | {"Kotlin": 77129} | import java.util.Set.of as setOf
object Day23 {
private data class Pos(val x: Int, val y: Int) {
fun move(direction: Direction): Pos {
return when (direction) {
Direction.SOUTH -> Pos(x, y + 1)
Direction.WEST -> Pos(x - 1, y)
Direction.NORTH -> Pos(x, y - 1)
Direction.EAST -> Pos(x + 1, y)
}
}
fun move(first: Direction, second: Direction): Pos = move(first).move(second)
fun lookToSide(direction: Direction): Set<Pos> {
return when (direction) {
Direction.SOUTH -> setOf(move(Direction.SOUTH, Direction.EAST), move(Direction.SOUTH), move(Direction.SOUTH, Direction.WEST))
Direction.WEST -> setOf(move(Direction.WEST, Direction.SOUTH), move(Direction.WEST), move(Direction.WEST, Direction.NORTH))
Direction.NORTH -> setOf(move(Direction.NORTH, Direction.WEST), move(Direction.NORTH), move(Direction.NORTH, Direction.EAST))
Direction.EAST -> setOf(move(Direction.EAST, Direction.NORTH), move(Direction.EAST), move(Direction.EAST, Direction.SOUTH))
}
}
fun lookAround(): Set<Pos> = setOf(
move(Direction.SOUTH),
move(Direction.SOUTH, Direction.WEST),
move(Direction.WEST),
move(Direction.WEST, Direction.NORTH),
move(Direction.NORTH),
move(Direction.NORTH, Direction.EAST),
move(Direction.EAST),
move(Direction.EAST, Direction.SOUTH)
)
}
private enum class Direction {
SOUTH, WEST, NORTH, EAST
}
private fun chooseStep(pos: Pos, setup: Set<Pos>, lookupOrder: List<Direction>): Pos? {
if (pos.lookAround().none { it in setup }) return null
val next = lookupOrder.firstOrNull { direction ->
pos.lookToSide(direction).none { it in setup }
}
return next?.let { pos.move(it) }
}
private fun performStep(current: Set<Pos>, lookupOrder: List<Direction>): Set<Pos> {
val nextSteps = current.associateWith { (chooseStep(it, current, lookupOrder) ?: it) }
val nextStepsCounts = nextSteps.values.groupingBy { it }.eachCount()
return current.map { pos ->
val nextStep = nextSteps.getValue(pos)
if (nextStepsCounts.getValue(nextStep) == 1) nextStep else pos
}.toSet()
}
private fun countUncoveredArea(setup: Set<Pos>): Int {
val minX = setup.minOf { it.x }
val maxX = setup.maxOf { it.x }
val minY = setup.minOf { it.y }
val maxY = setup.maxOf { it.y }
val xRange = minX..maxX
val yRange = minY..maxY
return xRange.flatMap { x ->
yRange.map { y ->
Pos(x, y)
}
}.count { it !in setup }
}
private fun parsePositions(input: List<String>): List<Pos> {
val positions = input.flatMapIndexed { y, line ->
line.mapIndexedNotNull { x, c ->
when (c) {
'#' -> Pos(x, y)
'.' -> null
else -> error("Unknown tile: $c")
}
}
}
return positions
}
private fun part1(input: List<String>): Int {
val positions = parsePositions(input)
val lookups = ArrayDeque(listOf(Direction.NORTH, Direction.SOUTH, Direction.WEST, Direction.EAST))
var current = positions.toSet()
repeat(10) {
current = performStep(current, lookups)
lookups.addLast(lookups.removeFirst())
}
return countUncoveredArea(current)
}
fun part2(input: List<String>): Int {
val positions = parsePositions(input)
val lookups = ArrayDeque(listOf(Direction.NORTH, Direction.SOUTH, Direction.WEST, Direction.EAST))
var current = positions.toSet()
var count = 0
while (true) {
count++
val newState = performStep(current, lookups)
lookups.addLast(lookups.removeFirst())
if (newState == current) break
current = newState
}
return count
}
@JvmStatic
fun main(args: Array<String>) {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day23_test")
check(part1(testInput) == 110)
check(part2(testInput) == 20)
val input = readInput("Day23")
println(part1(input))
println(part2(input))
}
}
| 0 | Kotlin | 0 | 1 | 975362ac7b1f1522818fc87cf2505aedc087738d | 4,576 | aoc2022 | Apache License 2.0 |
src/Day10.kt | nguyendanv | 573,066,311 | false | {"Kotlin": 18026} | fun main() {
fun part1(input: List<String>): Int {
var cycle = 1
var x = 1
return input
.map { it.split(" ") }
.flatMap { instr ->
val cyclesToExecute = when (instr[0]) {
"noop" -> 1
"addx" -> 2
else -> 0
}
val arg = when (instr[0]) {
"addx" -> instr[1].toInt()
else -> 0
}
(0 until cyclesToExecute)
.map {
cycle++
if (it==cyclesToExecute - 1) x += arg
cycle to x
}
}
.toMap()
.filter { (k, v) -> (k - 20) % 40==0 }
.map { (k, v) -> k * v }
.sum()
}
fun part2(input: List<String>): String {
var cycle = 0
var x = 1
return input
.map { it.split(" ") }
.flatMap { instr ->
val cyclesToExecute = when (instr[0]) {
"noop" -> 1
"addx" -> 2
else -> 0
}
val arg = when (instr[0]) {
"addx" -> instr[1].toInt()
else -> 0
}
(0 until cyclesToExecute)
.map {
val thisCycle = cycle
val isLit = (cycle % 40 in x - 1..x + 1)
cycle++
if (it==cyclesToExecute - 1) x += arg
thisCycle to isLit
}
}
.filter { (k, v) -> k <= 240 }
.map { (k, v) -> if (v) "#" else "." }
.joinToString("")
.windowed(40, 40)
.joinToString("\n")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput)==13140)
check(part2(testInput)=="""
##..##..##..##..##..##..##..##..##..##..
###...###...###...###...###...###...###.
####....####....####....####....####....
#####.....#####.....#####.....#####.....
######......######......######......####
#######.......#######.......#######.....
""".trimIndent())
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 376512583af723b4035b170db1fa890eb32f2f0f | 2,477 | advent2022 | Apache License 2.0 |
src/Day02.kt | RusticFlare | 574,508,778 | false | {"Kotlin": 78496} | fun main() {
fun part1(input: List<String>): Int {
return input.sumOf {
when (it.last()) {
'X' -> 1 + when (it.first()) {
'A' -> 3
'B' -> 0
'C' -> 6
else -> error("first: ${it.first()}")
}
'Y' -> 2 + when (it.first()) {
'A' -> 6
'B' -> 3
'C' -> 0
else -> error("first: ${it.first()}")
}
'Z' -> 3 + when (it.first()) {
'A' -> 0
'B' -> 6
'C' -> 3
else -> error("first: ${it.first()}")
}
else -> error("last: ${it.last()}")
}
}
}
fun part2(input: List<String>): Int {
return input.sumOf {
when (it.last()) {
'X' -> 0 + when (it.first()) {
'A' -> 3
'B' -> 1
'C' -> 2
else -> error("first: ${it.first()}")
}
'Y' -> 3 + when (it.first()) {
'A' -> 1
'B' -> 2
'C' -> 3
else -> error("first: ${it.first()}")
}
'Z' -> 6 + when (it.first()) {
'A' -> 2
'B' -> 3
'C' -> 1
else -> error("first: ${it.first()}")
}
else -> error("last: ${it.last()}")
}
}
}
// test if implementation meets criteria from the description, like:
val testInput = readLines("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readLines("Day02")
check(part1(input) == 11767)
println(part1(input))
check(part2(input) == 13886)
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 10df3955c4008261737f02a041fdd357756aa37f | 1,984 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/2021/Day4_2.kts | Ozsie | 318,802,874 | false | {"Kotlin": 99344, "Python": 1723, "Shell": 975} | import java.io.File
import kotlin.collections.HashMap
import kotlin.collections.ArrayList
class Box(val value: Int, val x: Int, val y: Int, var selected: Boolean = false)
class Board(val boxes: ArrayList<Box>, var order: Int = -1, var winningNumber: Int = 1) {
public var competing = true
fun selectIf(number: Int) = boxes.filter { it.value == number }.forEach { it.selected = true }
fun bingo(): Boolean {
for (rowOrColumn in 0..5) {
if (boxes.filter { it.x == rowOrColumn }.filter { it.selected }.size == 5 ||
boxes.filter { it.y == rowOrColumn }.filter { it.selected }.size == 5) {
competing = false
return true
}
}
return false
}
fun won() = println(boxes.filter { !it.selected }.map { it.value }.sum() * winningNumber)
}
var numbers = ArrayList<Int>()
var boards = ArrayList<Board>()
var currentBoardY = 0
File("input/2021/day4").forEachLine { line ->
if (numbers.isEmpty()) {
numbers.addAll(line.split(",").map { it.toInt() })
} else if (line.isBlank()) {
currentBoardY = 0
var currentBoard = Board(ArrayList<Box>())
boards.add(currentBoard)
} else {
var split = line.split(" ")
var row = split.filter { it.isNotBlank() }.mapIndexed { index, s -> Box(s.trim().toInt(), index, currentBoardY) }
boards.last().boxes.addAll(row)
currentBoardY++
}
}
var winOrder = 1
for (number in numbers) {
val competingBoards = boards.filter { it.competing }
for (board in competingBoards) {
board.selectIf(number)
if (board.bingo()) {
board.order = winOrder++
board.winningNumber = number
}
}
}
boards.filter { it.order == winOrder - 1 }.first().won()
| 0 | Kotlin | 0 | 0 | d938da57785d35fdaba62269cffc7487de67ac0a | 1,803 | adventofcode | MIT License |
src/main/kotlin/com/github/michaelbull/advent2023/day22/BrickSnapshot.kt | michaelbull | 726,012,340 | false | {"Kotlin": 195941} | package com.github.michaelbull.advent2023.day22
import com.github.michaelbull.advent2023.math.Vector3
fun Sequence<String>.toBrickSnapshot(): BrickSnapshot {
return BrickSnapshot(this.map(String::toBrick).toList())
}
data class BrickSnapshot(
val bricks: List<Brick>,
) {
private val bricksSortedUpwards = bricks.sortedBy(Brick::minZ)
fun disintegratableBrickCount(): Int {
return disintegrate().count { fallen ->
fallen == 0
}
}
fun fallenBrickCount(): Int {
return disintegrate().sum()
}
private fun disintegrate(): List<Int> {
val moved = step().map(NextBrick::brick).toList()
return moved.map { brick ->
val before = BrickSnapshot(moved.minusElement(brick))
before.step().count(NextBrick::fallen)
}
}
private fun step(): Sequence<NextBrick> = sequence {
val visited = mutableSetOf<Vector3>()
for (brick in bricksSortedUpwards) {
val changed = brick.step(visited)
visited += changed
yield(NextBrick(changed, changed != brick))
}
}
private fun Brick.step(visited: Set<Vector3>): Brick {
var current = this
while (true) {
val moved = current.map(Vector3::moveDownwards).toSet()
val fallen = moved.any { it in visited || it.z <= 0 }
if (fallen) {
return current
} else {
current = moved
}
}
}
private data class NextBrick(
val brick: Brick,
val fallen: Boolean,
)
}
private val DOWNWARDS = Vector3(0, 0, -1)
private fun Vector3.moveDownwards(): Vector3 {
return this + DOWNWARDS
}
private fun Iterable<Vector3>.minZ(): Int {
return minOf(Vector3::z)
}
| 0 | Kotlin | 0 | 1 | ea0b10a9c6528d82ddb481b9cf627841f44184dd | 1,814 | advent-2023 | ISC License |
implementation/src/main/kotlin/io/github/tomplum/aoc/map/forest/ForestMap.kt | TomPlum | 724,225,748 | false | {"Kotlin": 141244} | package io.github.tomplum.aoc.map.forest
import io.github.tomplum.libs.math.Direction
import io.github.tomplum.libs.math.map.AdventMap2D
import io.github.tomplum.libs.math.point.Point2D
class ForestMap(data: List<String>): AdventMap2D<ForestTile>() {
private val startingPosition: Point2D
private val targetDestination: Point2D
private val visited = mutableMapOf<Point2D, Boolean>()
init {
var x = 0
var y = 0
data.forEach { row ->
row.forEach { column ->
val tile = ForestTile(column)
val position = Point2D(x, y)
visited[position] = false
addTile(position, tile)
x++
}
x = 0
y++
}
startingPosition = getDataMap().entries
.filter { (pos) -> pos.y == 0 }
.single { (_, tile) -> tile.isTraversable() }
.key
targetDestination = getDataMap().entries
.filter { (pos) -> pos.y == yMax()!! }
.single { (_, tile) -> tile.isTraversable() }
.key
}
fun longestHikeSteps() = findLongestPath(
currentPosition = startingPosition,
visited = visited,
findTraversableTiles = { currentPosition ->
val tile = getTile(currentPosition)
when {
tile.isSteepSlope() -> listOf(currentPosition.getIcySlopeDestination(tile.value) to 1)
else -> currentPosition.orthogonallyAdjacent()
.filter { pos -> getTile(pos, ForestTile('#')).isTraversable() }
.map { pos -> pos to 1 }
}
}
)
fun longestHikeStepsNoSlopes(): Int {
val junctions = mutableMapOf(
startingPosition to mutableListOf<Pair<Point2D, Int>>(),
targetDestination to mutableListOf()
)
filterTiles { tile -> tile.isPath() }
.filter { (pos) -> pos.orthogonallyAdjacent().filter { getTile(it, ForestTile('#')).isTraversable() }.size > 2 }
.forEach { (pos) -> junctions[pos] = mutableListOf() }
junctions.keys.forEach { junction ->
var current = setOf(junction)
val visited = mutableSetOf(junction)
var distance = 0
while (current.isNotEmpty()) {
distance++
current = buildSet {
current.forEach { currentPosition ->
currentPosition.orthogonallyAdjacent()
.filter { getTile(currentPosition, ForestTile('*')).isTraversable() }
.filter { pos -> pos !in visited }
.forEach { pos ->
if (pos in junctions) {
junctions.getValue(junction).add(pos to distance)
} else {
add(pos)
visited.add(pos)
}
}
}
}
}
}
return findLongestPath(
currentPosition = startingPosition,
visited = visited,
findTraversableTiles = { currentPosition ->
junctions.getValue(currentPosition)
}
)
}
private fun findLongestPath(
currentPosition: Point2D,
visited: MutableMap<Point2D, Boolean>,
distance: Int = 0,
findTraversableTiles: (currentPosition: Point2D) -> List<Pair<Point2D, Int>>
): Int {
if (currentPosition == targetDestination) {
return distance
}
visited[currentPosition] = true
val longestHike = findTraversableTiles(currentPosition)
.filterNot { (pos) -> visited[pos] == true }
.maxOfOrNull { (nextPosition, pathWeight) ->
findLongestPath(nextPosition, visited, distance + pathWeight, findTraversableTiles)
}
visited[currentPosition] = false
return longestHike ?: 0
}
private fun Point2D.getIcySlopeDestination(slope: Char) = when(slope) {
'>' -> this.shift(Direction.RIGHT)
'<' -> this.shift(Direction.LEFT)
'v' -> this.shift(Direction.UP)
'^' -> this.shift(Direction.DOWN)
else -> throw IllegalArgumentException("$slope is not a valid slope identifier.")
}
} | 0 | Kotlin | 0 | 1 | d1f941a3c5bacd126177ace6b9f576c9af07fed6 | 4,472 | advent-of-code-2023 | Apache License 2.0 |
advent23-kt/app/src/main/kotlin/dev/rockyj/advent_kt/Day11.kt | rocky-jaiswal | 726,062,069 | false | {"Kotlin": 41834, "Ruby": 2966, "TypeScript": 2848, "JavaScript": 830, "Shell": 455, "Dockerfile": 387} | package dev.rockyj.advent_kt
private fun maxX(symbols: MutableMap<Pair<Int, Int>, String>): Int {
var x = 0
symbols.forEach {
if (it.key.second > x) {
x = it.key.second
}
}
return x
}
private fun maxY(symbols: MutableMap<Pair<Int, Int>, String>): Int {
var y = 0
symbols.forEach {
if (it.key.first > y) {
y = it.key.first
}
}
return y
}
private fun part1(input: List<String>) {
val symbols = mutableMapOf<Pair<Int, Int>, String>()
input.forEachIndexed { idx, line ->
val sls = line.trim().split("")
sls.subList(1, sls.size - 1).forEachIndexed { idx2, s -> symbols.put(Pair(idx, idx2), s.trim()) }
}
// find expansions
val expRows = (0..maxX(symbols)).filter { x ->
(0..maxY(symbols)).all { y ->
symbols[Pair(x, y)] == "."
}
}
val expCols = (0..maxY(symbols)).filter { x ->
(0..maxX(symbols)).all { y ->
symbols[Pair(y, x)] == "."
}
}
// println(expRows)
// println(expCols)
val galaxies = symbols.filter {
it.value == "#"
}
val pairs = mutableListOf<Pair<Pair<Int, Int>, Pair<Int, Int>>>()
galaxies.forEach { gal1 ->
galaxies.forEach { gal2 ->
if ((gal1.key != gal2.key)) { // && !pairs.contains(Pair(gal2.key, gal1.key))) {
pairs.plusAssign(Pair(gal1.key, gal2.key))
}
}
}
// println(galaxies)
// println(pairs)
// println(pairs.size)
val dist = pairs.map {
val pair1 = it.first
val pair2 = it.second
val left = if (pair1.second < pair2.second) {
pair1
} else {
pair2
}
val right = if (pair1.second > pair2.second) {
pair1
} else {
pair2
}
val up = if (pair1.first < pair2.first) {
pair1
} else {
pair2
}
val down = if (pair1.first > pair2.first) {
pair1
} else {
pair2
}
val exp1 = expCols.filter { cols -> cols > left.second && cols < right.second }.size
val exp2 = expRows.filter { rows -> rows > up.first && rows < down.first }.size
val mul = 1000000 - 1 // or 1
val res =
Math.abs(right.second - left.second).toLong() + Math.abs(down.first - up.first)
.toLong() + ((exp1 + exp2) * mul).toLong()
res
}.sum()
println(dist / 2)
}
fun main() {
val lines = fileToArr("day11_2.txt")
timed {
part1(lines)
}
} | 0 | Kotlin | 0 | 0 | a7bc1dfad8fb784868150d7cf32f35f606a8dafe | 2,633 | advent-2023 | MIT License |
src/main/kotlin/day02/Solution.kt | kcchoate | 683,597,644 | false | {"Kotlin": 25162} | package day02
class Solution {
fun navigate(input: List<String>) =
input.map { it.split(' ') }
.map { Instruction(it[0], it[1].toInt()) }
.fold(Result(0, 0)) { acc, instruction ->
when (instruction.direction) {
"up" -> Result(acc.horizontal, acc.depth - instruction.distance)
"down" -> Result(acc.horizontal, acc.depth + instruction.distance)
"forward" -> Result(acc.horizontal + instruction.distance, acc.depth)
else -> throw IllegalArgumentException("Unknown direction: ${instruction.direction}")
}
}
.calculateFinalValue()
private data class Instruction(val direction: String, val distance: Int)
private data class Result(val horizontal: Int, val depth: Int) {
fun calculateFinalValue() = horizontal * depth
}
private data class Result2(val horizontal: Int, val depth: Int, val aim: Int = 0) {
fun calculateFinalValue() = horizontal * depth
fun process(instruction: Instruction): Result2 {
return when (instruction.direction) {
"up" -> UpCommand(instruction.distance)
"down" -> DownCommand(instruction.distance)
"forward" -> ForwardCommand(instruction.distance)
else -> throw IllegalArgumentException("Unknown direction: ${instruction.direction}")
}.process(this)
}
}
private data class UpCommand(val distance: Int): Command {
override fun process(state: Result2): Result2 {
return Result2(state.horizontal, state.depth, state.aim - distance)
}
}
private class DownCommand(val distance: Int): Command {
override fun process(state: Result2): Result2 {
return Result2(state.horizontal, state.depth, state.aim + distance)
}
}
private class ForwardCommand(val distance: Int): Command {
override fun process(state: Result2): Result2 {
return Result2(state.horizontal + distance, state.depth + state.aim * distance, state.aim)
}
}
private interface Command {
fun process(state: Result2): Result2
}
fun navigate2(input: List<String>) =
input.map { it.split(' ') }
.map { Instruction(it[0], it[1].toInt()) }
.fold(Result2(0, 0, 0)) { acc, instruction -> acc.process(instruction) }
.calculateFinalValue()
}
| 0 | Kotlin | 0 | 1 | 3e7c24bc69a4de168ce0bdff855323c803b9a9a8 | 2,494 | advent-of-kotlin | MIT License |
src/algorithmsinanutshell/LineSweepAlgorithm.kt | realpacific | 234,499,820 | false | null | package algorithmsinanutshell
import kotlin.math.max
import kotlin.math.min
import kotlin.test.assertTrue
/**
* Given a number of lines, find the lines that intersects with each other
*
* Starting from left, sweep a vertical line through each point. Find the intersection of lines with each other
* that the vertical lines touches. If the sweep line has moved past a line (both points are to its left),
* this can be ignored.
*
* [link](https://www.geeksforgeeks.org/given-a-set-of-line-segments-find-if-any-two-segments-intersect/)
*/
class LineSweepAlgorithm(private val lines: List<Line>) {
// Sort by x-coordinate
private var _lines = lines.sortedBy { line -> line.p1.x }
/**
* Find active lines w.r.t [vLine]
*/
private fun findLinesWithOnePointToLeftOfVerticalLine(vLine: Line): List<Line> {
// return _lines.filter { line ->
// min(line.p1.x, line.p2.x) <= vLine.p1.x && max(line.p2.x, line.p1.x) >= vLine.p1.x
// }
val result = mutableListOf<Line>()
for (line in _lines) {
// Since _lines is sorted, no need to go through all
if (min(line.p1.x, line.p2.x) <= vLine.p1.x && max(line.p2.x, line.p1.x) >= vLine.p1.x) {
result.add(line)
} else {
return result
}
}
return result
}
fun execute(): Map<Line, Set<Line>> {
val intersectionMap = mapOf(*lines.map { l -> Pair(l, mutableSetOf<Line>()) }.toTypedArray())
// Could be optimized
// Find minY and maxY to find the length of vertical line that moves from minX to maxX
// OR GO with top to bottom instead of left to right, _lines is already sorted
val (minY, maxY) = Pair(
_lines.minOf { line -> min(line.p1.y, line.p2.y) },
_lines.maxOf { line -> max(line.p1.y, line.p2.y) }
)
for (line in _lines) {
val sweepLine = Line(line.p1.x fromTo minY, line.p1.x fromTo maxY)
val activeLines = findLinesWithOnePointToLeftOfVerticalLine(sweepLine)
for (i in 0..activeLines.lastIndex) {
for (j in 0..activeLines.lastIndex) {
if (i == j) {
continue
}
val l1 = activeLines[i]
val l2 = activeLines[j]
// Already exists
if (intersectionMap[l1]!!.contains(l2)) {
continue
}
if (IntersectionOfLines(l1, l2).hasIntersection()) {
intersectionMap[l1]!!.add(l2)
intersectionMap[l2]!!.add(l1)
}
}
}
}
intersectionMap.forEach { (t, u) ->
println("$t: $u")
}
return intersectionMap
}
}
fun main() {
run {
val lines = listOf(
Line(1 fromTo 5, 4 fromTo 5),
Line(6 fromTo 4, 9 fromTo 4),
Line(3 fromTo 2, 10 fromTo 3),
Line(7 fromTo 1, 8 fromTo 1),
Line(2 fromTo 5, 10 fromTo 1),
)
val intersections = LineSweepAlgorithm(lines).execute()
intersections.forEach { (currentLine, intersectingLines) ->
intersectingLines.forEach {
assertTrue { IntersectionOfLines(it, currentLine).hasIntersection() }
}
}
}
run {
// Has no intersection
val lines = listOf(
Line(0 fromTo 0, 10 fromTo 0),
Line(5 fromTo 3, 10 fromTo 3),
Line(3 fromTo 4, 10 fromTo 4)
)
val intersections = LineSweepAlgorithm(lines).execute()
intersections.forEach { (_, intersectingLines) ->
assertTrue { intersectingLines.isEmpty() }
}
}
run {
//
// * * *
// \ | /
// x
// / | \
// * * *
val lines = listOf(
Line(1 fromTo 6, 4 fromTo 8),
Line(1 fromTo 8, 4 fromTo 6),
Line(3 fromTo 10, 3 fromTo 4)
)
val intersections = LineSweepAlgorithm(lines).execute()
intersections.forEach { (currentLine, intersectingLines) ->
assertTrue { intersectingLines.size == 2 }
intersectingLines.forEach {
assertTrue { IntersectionOfLines(it, currentLine).hasIntersection() }
}
}
}
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 4,492 | algorithms | MIT License |
src/Day07.kt | li-xin-yi | 573,617,763 | false | {"Kotlin": 23422} | import java.util.*
class Dir {
val children = mutableMapOf<String, Dir>()
var size = -1
}
fun main() {
fun getRootDir(input: List<String>): Dir {
val root = Dir()
val stack = Stack<Dir>()
var cur: Dir = root
for (line in input) {
val words = line.split(" ")
if (words[0] == "$" && words[1] == "cd") {
when (words[2]) {
"/" -> {
stack.clear()
stack.push(root)
}
".." -> stack.pop()
else -> stack.push(cur.children[words[2]]!!)
}
cur = stack.peek()
} else if (words[0] != "$") {
if (cur.children.containsKey(words[1])) continue
cur.children[words[1]] = Dir()
if (words[0] != "dir") {
cur.children[words[1]]!!.size = words[0].toInt()
}
}
}
return root
}
fun solvePart1(input: List<String>): Int {
var res = 0
val root = getRootDir(input)
fun dfs(root: Dir): Int {
if (root.size != -1) return root.size
root.size = root.children.values.sumOf { dfs(it) }
if (root.size <= 100000) res += root.size
return root.size
}
dfs(root)
return res
}
fun solvePart2(input: List<String>): Int {
val root = getRootDir(input)
val lst = mutableListOf<Int>()
fun dfs(root: Dir): Int {
if (root.size != -1) return root.size
root.size = root.children.values.sumOf { dfs(it) }
lst.add(root.size)
return root.size
}
val target = 30000000 - (70000000 - dfs(root))
return lst.filter { it >= target }.minOrNull()!!
}
val testInput = readInput("input/Day07_test")
check(solvePart1(testInput) == 95437)
check(solvePart2(testInput) == 24933642)
val input = readInput("input/Day07_input")
println(solvePart1(input))
println(solvePart2(input))
} | 0 | Kotlin | 0 | 1 | fb18bb7e462b8b415875a82c5c69962d254c8255 | 2,132 | AoC-2022-kotlin | Apache License 2.0 |
src/main/kotlin/g1201_1300/s1292_maximum_side_length_of_a_square_with_sum_less_than_or_equal_to_threshold/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1201_1300.s1292_maximum_side_length_of_a_square_with_sum_less_than_or_equal_to_threshold
// #Medium #Array #Binary_Search #Matrix #Prefix_Sum #Binary_Search_II_Day_15
// #2023_06_08_Time_376_ms_(100.00%)_Space_50.6_MB_(100.00%)
class Solution {
fun maxSideLength(mat: Array<IntArray>, threshold: Int): Int {
val m = mat.size
val n = mat[0].size
val prefix = Array(m) { IntArray(n) }
for (i in 0 until m) {
for (j in 0 until n) {
if (i == 0 && j == 0) {
prefix[i][j] = mat[i][j]
} else if (i == 0) {
prefix[i][j] = mat[i][j] + prefix[0][j - 1]
} else if (j == 0) {
prefix[i][j] = mat[i][j] + prefix[i - 1][0]
} else {
prefix[i][j] = mat[i][j] + prefix[i][j - 1] + prefix[i - 1][j] - prefix[i - 1][j - 1]
}
}
}
var low = 1
var high = Math.min(m, n)
var ans = 0
while (low <= high) {
val mid = (low + high) / 2
if (min(mid, prefix) > threshold) {
high = mid - 1
} else {
ans = mid
low = mid + 1
}
}
return ans
}
fun min(length: Int, prefix: Array<IntArray>): Int {
var min = 0
for (i in length - 1 until prefix.size) {
for (j in length - 1 until prefix[0].size) {
min = if (i == length - 1 && j == length - 1) {
prefix[i][j]
} else if (i - length < 0) {
Math.min(min, prefix[i][j] - prefix[i][j - length])
} else if (j - length < 0) {
Math.min(min, prefix[i][j] - prefix[i - length][j])
} else {
Math.min(
min,
(
prefix[i][j] -
prefix[i][j - length] -
prefix[i - length][j]
) +
prefix[i - length][j - length]
)
}
}
}
return min
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,257 | LeetCode-in-Kotlin | MIT License |
src/Day04.kt | Totwart123 | 573,119,178 | false | null | fun main() {
fun String.getRangeFromElf() : IntRange{
val elf = this.split("-").map { it.toInt() }
return IntRange(elf[0], elf[1])
}
fun part1(input: List<String>): Int {
var doubleCount = 0
input.forEach { pair->
val splitted = pair.split(",").map { it.getRangeFromElf() }
val firstElf = splitted[0]
val secondElf = splitted[1]
if(firstElf.contains(secondElf.first) && firstElf.contains(secondElf.last)||
secondElf.contains(firstElf.first) && secondElf.contains(firstElf.last)){
doubleCount++
}
}
return doubleCount
}
fun part2(input: List<String>): Int {
var doubleCount = 0
input.forEach { pair->
val splitted = pair.split(",").map { it.getRangeFromElf() }
val firstElf = splitted[0]
val secondElf = splitted[1]
if(firstElf.contains(secondElf.first) || firstElf.contains(secondElf.last)||
secondElf.contains(firstElf.first) || secondElf.contains(firstElf.last)){
doubleCount++
}
}
return doubleCount
}
val testInput = readInput("Day04_test")
check(part1(testInput) == 3)
check(part2(testInput) == 5)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 33e912156d3dd4244c0a3dc9c328c26f1455b6fb | 1,411 | AoC | Apache License 2.0 |
src/main/kotlin/day4.kt | danielfreer | 297,196,924 | false | null | import kotlin.time.ExperimentalTime
@ExperimentalTime
fun day4(input: List<String>): List<Solution> {
val range = input.first().split("-").map(String::toInt).let { it.first()..it.last() }
return listOf(
solve(4, 1) { possiblePasswords(range).size },
solve(4, 2) { possiblePasswordsRedux(range).size }
)
}
private typealias Rule<T> = (T) -> Boolean
private fun Int.toList() = toString().map(Char::toString).map(String::toInt)
@Suppress("SameParameterValue")
private fun isLength(length: Int): Rule<Int> = { it.toString().length == length }
private fun isWithinRange(range: IntRange): Rule<Int> = { it in range }
private val isTwoAdjacentDigitsTheSame: Rule<Int> = {
var isTwoAdjacentDigitsTheSame = false
it.toList().reduce { acc, i ->
if (acc == i) isTwoAdjacentDigitsTheSame = true
i
}
isTwoAdjacentDigitsTheSame
}
private val isIncreasingOrSame: Rule<Int> = {
var isIncreasingOrSame = true
it.toList().reduce { acc, i ->
if (i < acc) isIncreasingOrSame = false
i
}
isIncreasingOrSame
}
fun possiblePasswords(range: IntRange): Set<Int> {
return range.asSequence()
.filter(isLength(6))
.filter(isWithinRange(range))
.filter(isTwoAdjacentDigitsTheSame)
.filter(isIncreasingOrSame)
.toSet()
}
private val hasExactlyTwoAdjacentDigitsTheSame: Rule<Int> = { password ->
val adjacentDigitsCounts = mutableMapOf<Int, Int>()
password.toList().reduce { acc, i ->
if (acc == i) adjacentDigitsCounts.compute(i) { _, value -> value?.inc() ?: 2 }
i
}
adjacentDigitsCounts.values.any { it == 2 }
}
fun possiblePasswordsRedux(range: IntRange): Set<Int> {
return range.asSequence()
.filter(isLength(6))
.filter(isWithinRange(range))
.filter(hasExactlyTwoAdjacentDigitsTheSame)
.filter(isIncreasingOrSame)
.toSet()
}
| 0 | Kotlin | 0 | 0 | 74371d15f95492dee1ac434f0bfab3f1160c5d3b | 1,920 | advent2019 | The Unlicense |
kotlin/src/main/kotlin/com/github/jntakpe/aoc2022/days/Day2.kt | jntakpe | 572,853,785 | false | {"Kotlin": 72329, "Rust": 15876} | package com.github.jntakpe.aoc2022.days
import com.github.jntakpe.aoc2022.shared.Day
import com.github.jntakpe.aoc2022.shared.readInputLines
object Day2 : Day {
override val input: List<Pair<Char, Char>> = readInputLines(2).map { l -> l.split("\\s".toRegex()).let { it.first().first() to it.last().first() } }
override fun part1(): Int {
return input
.map { (a, b) -> Shape.fromA(a) to Shape.fromB(b) }
.sumOf { (a, b) -> b.score(a) }
}
override fun part2(): Int {
return input
.map { (a, b) -> Shape.fromA(a) to Outcome.fromB(b) }
.sumOf { (a, b) -> a.score(b) }
}
enum class Shape(private val score: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3);
companion object {
fun fromA(char: Char): Shape {
return when (char) {
'A' -> ROCK
'B' -> PAPER
'C' -> SCISSORS
else -> throw IllegalArgumentException("Unsupported char $char for shapes")
}
}
fun fromB(char: Char): Shape {
return when (char) {
'X' -> ROCK
'Y' -> PAPER
'Z' -> SCISSORS
else -> throw IllegalArgumentException("Unsupported char $char for shapes")
}
}
}
fun score(a: Shape): Int {
return when (a) {
this -> Outcome.DRAW
wins() -> Outcome.WIN
else -> Outcome.LOSS
}.score + score
}
fun score(outcome: Outcome): Int {
val shape = when (outcome) {
Outcome.WIN -> loss()
Outcome.DRAW -> this
Outcome.LOSS -> wins()
}
return shape.score + outcome.score
}
private fun wins(): Shape {
return when (this) {
ROCK -> SCISSORS
SCISSORS -> PAPER
PAPER -> ROCK
}
}
private fun loss(): Shape {
return when (this) {
ROCK -> PAPER
SCISSORS -> ROCK
PAPER -> SCISSORS
}
}
}
enum class Outcome(val score: Int) {
LOSS(0),
DRAW(3),
WIN(6);
companion object {
fun fromB(char: Char) : Outcome {
return when (char) {
'X' -> LOSS
'Y' -> DRAW
'Z' -> WIN
else -> throw IllegalArgumentException("Unsupported char $char for shapes")
}
}
}
}
}
| 1 | Kotlin | 0 | 0 | 63f48d4790f17104311b3873f321368934060e06 | 2,735 | aoc2022 | MIT License |
src/Day15.kt | mikemac42 | 573,071,179 | false | {"Kotlin": 45264} | import java.io.File
import kotlin.math.abs
fun main() {
val testInput = """Sensor at x=2, y=18: closest beacon is at x=-2, y=15
Sensor at x=9, y=16: closest beacon is at x=10, y=16
Sensor at x=13, y=2: closest beacon is at x=15, y=3
Sensor at x=12, y=14: closest beacon is at x=10, y=16
Sensor at x=10, y=20: closest beacon is at x=10, y=16
Sensor at x=14, y=17: closest beacon is at x=10, y=16
Sensor at x=8, y=7: closest beacon is at x=2, y=10
Sensor at x=2, y=0: closest beacon is at x=2, y=10
Sensor at x=0, y=11: closest beacon is at x=2, y=10
Sensor at x=20, y=14: closest beacon is at x=25, y=17
Sensor at x=17, y=20: closest beacon is at x=21, y=22
Sensor at x=16, y=7: closest beacon is at x=15, y=3
Sensor at x=14, y=3: closest beacon is at x=15, y=3
Sensor at x=20, y=1: closest beacon is at x=15, y=3"""
val realInput = File("src/Day15.txt").readText()
val part1TestOutput = numNonBeaconPoints(testInput, row = 10)
println("Part 1 Test Output: $part1TestOutput")
check(part1TestOutput == 26)
val part1RealOutput = numNonBeaconPoints(realInput, row = 2000000)
println("Part 1 Real Output: $part1RealOutput")
val part2TestOutput = distressBeaconFrequency(testInput, 0..20)
println("Part 2 Test Output: $part2TestOutput")
check(part2TestOutput == 56000011L)
val part2RealOutput = distressBeaconFrequency(realInput, 0..4000000)
println("Part 2 Real Output: $part2RealOutput")
}
/**
* Sensors and beacons always exist at integer coordinates.
* Sensors detect the closest beacon based on Manhattan distance.
* How many positions in the given row that cannot contain a beacon?
*/
fun numNonBeaconPoints(input: String, row: Int): Int =
parseSensors(input).flatMap { it.nonBeaconPoints(row) }.toSet().size
/**
* The distress beacon must have x and y coordinates each no lower than 0 and no larger than 4000000.
* Tuning frequency is found by multiplying its x coordinate by 4000000 and then adding its y coordinate.
* What is the tuning frequency of the distress beacon?
*/
fun distressBeaconFrequency(input: String, range: IntRange): Long {
val sensors = parseSensors(input)
fun pointOrNull(x: Int, y: Int): Point? =
if (x in range && y in range) Point(x, y) else null
val possiblePoints = sensors.flatMap { sensor ->
sensor.possibleDistressBeaconPoints(::pointOrNull)
}.toSet()
possiblePoints.forEach { point ->
if (sensors.all { it.isValidBeacon(point) }) {
return point.x.toLong() * 4000000L + point.y.toLong()
}
}
throw IllegalStateException()
}
private data class Sensor(
val sensorPoint: Point,
val beaconPoint: Point,
val beaconDistance: Int = manhattanDistance(sensorPoint, beaconPoint)
) {
fun nonBeaconPoints(row: Int? = null): List<Point> =
(sensorPoint.x - beaconDistance..sensorPoint.x + beaconDistance).flatMap { x ->
val possiblePoints = row?.let { listOf(Point(x, it)) }
?: (sensorPoint.y - beaconDistance..sensorPoint.y + beaconDistance).map { y -> Point(x, y) }
possiblePoints.minus(beaconPoint).mapNotNull { point ->
if (manhattanDistance(sensorPoint, point) <= beaconDistance) {
point
} else {
null
}
}
}
fun possibleDistressBeaconPoints(pointOrNull: (Int, Int) -> Point?): List<Point> {
val topRight = (sensorPoint.x..sensorPoint.x + beaconDistance).mapIndexedNotNull { index, x ->
pointOrNull(x, sensorPoint.y - beaconDistance - 1 + index)
}
val rightBottom = (sensorPoint.y..sensorPoint.y + beaconDistance).mapIndexedNotNull { index, y ->
pointOrNull(sensorPoint.x + beaconDistance + 1 - index, y)
}
val bottomLeft = (sensorPoint.x..sensorPoint.x - beaconDistance).mapIndexedNotNull { index, x ->
pointOrNull(x, sensorPoint.y + beaconDistance + 1 - index)
}
val leftTop = (sensorPoint.y..sensorPoint.y - beaconDistance).mapIndexedNotNull { index, y ->
pointOrNull(sensorPoint.x - beaconDistance - 1 + index, y)
}
return topRight + rightBottom + bottomLeft + leftTop
}
fun isValidBeacon(point: Point): Boolean =
manhattanDistance(sensorPoint, point) > beaconDistance
}
private fun manhattanDistance(p1: Point, p2: Point): Int =
abs(p1.x - p2.x) + abs(p1.y - p2.y)
private fun parseSensors(input: String): List<Sensor> {
val regex = Regex("""Sensor at x=(-?\d*), y=(-?\d*): closest beacon is at x=(-?\d*), y=(-?\d*)""")
return input.lines().map { line ->
val coordinates = regex.find(line)!!.groups.drop(1).map { it!!.value.toInt() }
Sensor(Point(coordinates[0], coordinates[1]), Point(coordinates[2], coordinates[3]))
}
}
| 0 | Kotlin | 1 | 0 | 909b245e4a0a440e1e45b4ecdc719c15f77719ab | 4,609 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/adventofcode2022/solution/day_13.kt | dangerground | 579,293,233 | false | {"Kotlin": 51472} | package adventofcode2022.solution
import adventofcode2022.util.batchedList
import adventofcode2022.util.readDay
fun main() {
Day13("13").solve()
}
class Day13(private val num: String) {
private val inputText = readDay(num)
fun solve() {
println("Day $num Solution")
println("* Part 1: ${solution1()}")
println("* Part 2: ${solution2()}")
}
fun solution1(): Int {
return batchedList(inputText.lines()).mapIndexed { index, it ->
println("\n== Pair ${index + 1} ==")
val left = it[0].parsePacket()
val right = it[1].parsePacket()
// println("compare: = $left vs $right")
val x = left.compareTo(right)
if (x < 0) println("- Left side is smaller, so inputs are in the right order")
else println("- Right side is smaller, so inputs are not in the right order")
x
}.mapIndexed { index, it -> if (it < 0) index + 1 else 0 }
.sum()
}
fun solution2(): Int {
val first = "[[2]]".parsePacket()
val second = "[[6]]".parsePacket()
val sorted = batchedList(inputText.lines()).flatMap {
val left = it[0].parsePacket()
val right = it[1].parsePacket()
listOf(left, right)
}.toMutableList()
.also { it.add(first); it.add(second) }
.sorted()
val result = sorted
.mapIndexed { index, it -> Pair(index+1, it.compareTo(first) == 0 || it.compareTo(second) == 0) }
.filter { it.second }
return result.first().first * result.last().first
}
}
fun String.parsePacket(): Entry {
var current = Entry()
var currentNum = ""
toCharArray().forEach {
when {
it.isDigit() -> {
currentNum += "$it"
}
it == '[' -> {
val next = Entry(list = mutableListOf())
current.add(next)
current = next
}
it == ']' -> {
if (currentNum.isNotBlank()) {
current.add(currentNum)
currentNum = ""
}
current = current.parent!!
}
it == ',' -> {
if (currentNum.isNotBlank()) {
current.add(currentNum)
currentNum = ""
}
}
else -> {
throw UnsupportedOperationException("should not happen: $it")
}
}
}
return current.list!!.first()
}
data class Entry(
val num: Int? = null,
var list: MutableList<Entry>? = null,
var parent: Entry? = null
) : Comparable<Entry> {
fun add(num: String) {
if (list == null) {
list = mutableListOf()
}
list?.add(Entry(num = num.toInt()))
}
fun add(entry: Entry) {
entry.parent = this
if (list == null) {
list = mutableListOf()
}
list?.add(entry)
}
override fun compareTo(other: Entry): Int {
// println("- Compare $this vs $other")
if (num != null && other.num != null) {
//println("num ${num.compareTo(other.num)}")
return num.compareTo(other.num)
}
if (num != null && list?.isEmpty() == true) {
//println("none")
return -1
}
if (list == null) {
// println("- Mixed types; convert left to [$this] and retry comparison")
return Entry(list = mutableListOf(this)).compareTo(other)
}
if (other.list == null) {
// println("- Mixed types; convert right to [$other] and retry comparison")
return this.compareTo(Entry(list = mutableListOf(other)))
}
//println("left vs right: $left vs $right")
//println("sub $this vs $other")
var index = 0
while (list?.getOrNull(index) != null) {
//println("next $list [$index] (${other.list?.getOrNull(index)})")
val right = other.list?.getOrNull(index) ?: return 1
//println("next $list [$index]")
val result = (list?.get(index))!!.compareTo(right)
if (result < 0) {
//println("return -1")
return -1
} else if (result > 0) {
//println("return 1")
return 1
}
//println("next $index ")
index++
}
//println("fail $list")
return if (other.list?.getOrNull(index) != null) -1 else 0
}
override fun toString(): String {
return if (num != null) "$num" else if (list != null) "$list" else ""
}
} | 0 | Kotlin | 0 | 0 | f1094ba3ead165adaadce6cffd5f3e78d6505724 | 4,745 | adventofcode-2022 | MIT License |
src/main/kotlin/Day002.kt | ruffCode | 398,923,968 | false | null | object Day002 {
val sample = "1-3 b: cdefg"
private val passwordList = PuzzleInput("day002.txt").readLines()
@JvmStatic
fun main(args: Array<String>) {
println(partOne(passwordList))
println(partOneBetter(passwordList))
println(partTwo(passwordList))
println(partTwoBetter(passwordList))
}
private fun lineToPassword(line: String): Password {
return line.split(" ").let {
val (min, max) = it.first().split("-").map(String::toInt)
Password(
range = min..max,
letter = it[1].replace(":", "").first(),
password = it.last()
)
}
}
internal fun partOne(input: List<String>): Int =
input.map(::lineToPassword).count { it.isValid }
internal fun partOneBetter(input: List<String>): Int =
input.mapNotNull { Password(it) }.count { it.isValid }
internal fun partTwo(input: List<String>): Int =
input.map(::lineToPassword).count { it.isValidPart2 }
internal fun partTwoBetter(input: List<String>): Int =
input.mapNotNull { Password(it) }.count { it.isValidPart2Cleaner }
private data class Password(
val range: IntRange,
val letter: Char,
val password: String,
) {
val isValid: Boolean by lazy {
password.count { it == letter } in range
}
val isValidPart2: Boolean by lazy {
val p1 = range.first - 1
val p2 = range.last - 1
(
(password[p1] == letter && password[p2] != letter) ||
(password[p1] != letter) && password[p2] == letter
)
}
val isValidPart2Cleaner: Boolean by lazy {
(password[range.first - 1] == letter) xor (password[range.last - 1] == letter)
}
companion object {
operator fun invoke(line: String): Password? {
val regex = Regex("""(\d+)-(\d+) ([a-z]): ([a-z]+)""")
return regex.matchEntire(line)
?.destructured
?.let { (start, end, letter, password) ->
Password(start.toInt()..end.toInt(), letter.single(), password)
}
}
}
}
}
data class PasswordWithPolicy(
val password: String,
val range: IntRange,
val letter: Char,
) {
fun validatePartOne() =
password.count { it == letter } in range
fun validatePartTwo() =
(password[range.first - 1] == letter) xor (password[range.last - 1] == letter)
companion object {
fun parse(line: String) = PasswordWithPolicy(
password = line.substringAfter(": "),
letter = line.substringAfter(" ").substringBefore(":").single(),
range = line.substringBefore(" ").let {
val (start, end) = it.split("-")
start.toInt()..end.toInt()
},
)
private val regex = Regex("""(\d+)-(\d+) ([a-z]): ([a-z]+)""")
fun parseUsingRegex(line: String): PasswordWithPolicy =
regex.matchEntire(line)!!
.destructured
.let { (start, end, letter, password) ->
PasswordWithPolicy(password, start.toInt()..end.toInt(), letter.single())
}
}
}
| 0 | Kotlin | 0 | 0 | 477510cd67dac9653fc61d6b3cb294ac424d2244 | 3,357 | advent-of-code-2020-kt | MIT License |
src/Day11.kt | cypressious | 572,916,585 | false | {"Kotlin": 40281} | fun main() {
fun parse(input: List<String>) =
input.map { it.toCharArray().mapTo(mutableListOf()) { c -> c - '0' } }
fun runCycle(grid: List<MutableList<Int>>): Int {
var sum = 0
val flashing = grid.map { BooleanArray(it.size) }
fun flash(y: Int, x: Int) {
sum++
flashing[y][x] = true
for (dy in -1..1) {
for (dx in -1..1) {
if (dy == 0 && dx == 0) continue
val neighbor = grid.getOrNull(y + dy)?.getOrNull(x + dx) ?: continue
grid[y + dy][x + dx] = neighbor + 1
if (neighbor + 1 > 9 && !flashing[y + dy][x + dx]) flash(y + dy, x + dx)
}
}
}
for (y in grid.indices) {
for (x in grid[y].indices) {
grid[y][x]++
}
}
for (y in grid.indices) {
for (x in grid[y].indices) {
if (grid[y][x] > 9 && !flashing[y][x]) {
flash(y, x)
}
}
}
for (y in grid.indices) {
for (x in grid[y].indices) {
if (flashing[y][x]) {
grid[y][x] = 0
}
}
}
return sum
}
fun part1(input: List<String>): Int {
val grid = parse(input)
var sum = 0
repeat(100) {
sum += runCycle(grid)
}
return sum
}
fun part2(input: List<String>): Int {
val grid = parse(input)
var count = 0
while (grid.any { row -> row.any { it != 0 } }) {
runCycle(grid)
count++
}
return count
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
check(part1(testInput) == 1656)
check(part2(testInput) == 195)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 169fb9307a34b56c39578e3ee2cca038802bc046 | 2,017 | AdventOfCode2021 | Apache License 2.0 |
src/main/kotlin/Day5.kt | ueneid | 575,213,613 | false | null | class Day5(inputs: String) {
private val parsedInput = parse(inputs)
data class Command(val value: Int, val from: Int, val to: Int)
data class Input(val stackList: List<ArrayDeque<Char>>, val commandList: List<Command>)
private fun parse(inputs: String): Input {
val stackRegex = """(\[[A-Z]\]|\s{3})(?:\s|$)""".toRegex()
val stackCrateRegex = """^\[[A-Z]\]$""".toRegex()
return inputs.split("\n\n").let { it ->
val stackList = it[0].split("\n").let { lines ->
val stackNumber = """(\d+)""".toRegex().findAll(lines.last()).count()
val stacks = List<ArrayDeque<Char>>(stackNumber) { ArrayDeque() }
lines.dropLast(1).forEach { line ->
val matches = stackRegex.findAll(line)
if (matches.count() == 0) {
throw IllegalArgumentException("Invalid format for stacks: $matches")
}
matches.forEachIndexed { index, matchResult ->
if (stackCrateRegex.matches(matchResult.groupValues[1])) {
stacks[index].addFirst(matchResult.groupValues[1][1])
}
}
}
stacks
}
val commandRegex = """^move (\d+) from (\d+) to (\d+)$""".toRegex()
val commandList = it[1].split("\n").map { line ->
val (value, from, to) = commandRegex.matchEntire(line)!!.destructured
Command(value.toInt(), from.toInt(), to.toInt())
}
Input(stackList, commandList)
}
}
private fun clone(): Input {
val stackList = mutableListOf<ArrayDeque<Char>>().apply {
addAll(parsedInput.stackList.map { chars ->
val charQueue = ArrayDeque<Char>()
chars.forEach { charQueue.add(it) }
charQueue
})
}
return Input(stackList, parsedInput.commandList)
}
fun solve1(): String {
val (stackList, commandList) = clone()
commandList.forEachIndexed { _, (value, from, to) ->
repeat(value) {
stackList[to - 1].add(stackList[from - 1].removeLast())
}
}
return stackList.map {
it.removeLast()
}.joinToString("")
}
fun solve2(): String {
val (stackList, commandList) = clone()
commandList.forEachIndexed { _, (value, from, to) ->
stackList[to - 1] += (0 until value).map { stackList[from - 1].removeLast() }.reversed()
}
return stackList.map { it.removeLast() }.joinToString("")
}
}
fun main() {
val obj = Day5(Resource.resourceAsText("day5/input.txt"))
println(obj.solve1())
println(obj.solve2())
}
| 0 | Kotlin | 0 | 0 | 743c0a7adadf2d4cae13a0e873a7df16ddd1577c | 2,837 | adventcode2022 | MIT License |
src/main/kotlin/com/richodemus/advent_of_code/two_thousand_sixteen/day4_rooms/Main.kt | RichoDemus | 75,489,317 | false | null | package com.richodemus.advent_of_code.two_thousand_sixteen.day4_rooms
import com.richodemus.advent_of_code.two_thousand_sixteen.toFile
import org.assertj.core.api.Assertions.assertThat
fun main(args: Array<String>) {
val validRooms = "day4/rooms.txt".toFile().readLines().map(::Room).filter(Room::valid)
val sum = validRooms.map(Room::sectorId).sum()
println("The sum of the sector IDs of all valid rooms is $sum")
assertThat(sum).isEqualTo(278221)
val id = validRooms.filter { it.decrypt() == "northpole object storage" }
.map(Room::sectorId)
.first()
println("The room with the North Pole Objects is: $id")
assertThat(id).isEqualTo(257)
}
private class Room(raw: String) {
val name: String
val sectorId: Int
val checksum: String
init {
val (name, sectorId, checksum) = raw.parse()
this.name = name
this.sectorId = sectorId
this.checksum = checksum
}
override fun toString() = "$name-$sectorId[$checksum]"
fun valid(): Boolean {
val characterOccourances = name.toSortedListOfCharacterOccurrences()
checksum.toList().forEachIndexed { i, c ->
if (c != characterOccourances[i]) {
return false
}
}
return true
}
fun decrypt(): String {
return name.toList()
.map { it.rotate(sectorId) }
.map { it.toString() }
.reduce { string, char -> string + char }
}
}
// qfkkj-nsznzwlep-dstaatyr-223[aknst]
private fun String.parse(): Triple<String, Int, String> {
val regex = "([\\w-]*)-(\\d+)\\[(\\w+)\\]"
val parser = Regex(regex)
val parsed = parser.findAll(this).toList()[0]
val b = parsed.groups[1]!!.value
val c = parsed.groups[2]!!.value
val d = parsed.groups[3]!!.value
return Triple(b, c.toInt(), d)
}
private fun String.toSortedListOfCharacterOccurrences() = this.toList()
.filterNot { it == '-' }
.sorted()
.groupBy { it }
.map { Pair(it.key, it.value) }
.map { Pair(it.first, it.second.size) }
.sortedByDescending { it.second }
.map { it.first }
private fun Char.rotate(steps: Int): Char {
if (this == '-') {
return ' '
}
var rotated = this
1.rangeTo(steps).forEach {
rotated++
if (rotated > 'z') {
rotated = 'a'
}
}
return rotated
}
| 0 | Kotlin | 0 | 0 | 32655174f45808eb1530f00c4c49692310036395 | 2,447 | advent-of-code | Apache License 2.0 |
src/Day13.kt | illarionov | 572,508,428 | false | {"Kotlin": 108577} | fun main() {
fun part1(input: List<Pair<ListOrNumber, ListOrNumber>>): Int {
return input.withIndex()
.filter { (_, p) -> isInRightOrder(p.first, p.second) >= 0
}
.sumOf { it.index + 1 }
}
fun part2(input: List<Pair<ListOrNumber, ListOrNumber>>): Int {
val packet2 = ListOrNumber.Sublist(ListOrNumber.Sublist(2))
val packet6 = ListOrNumber.Sublist(ListOrNumber.Sublist(6))
val packets = input.flatMap { p ->
p.toList() + listOf(packet2, packet6)
}
val sorted = packets.sortedWith { o1, o2 -> isInRightOrder(o2, o1) }
return (sorted.indexOf(packet2) + 1) * (sorted.indexOf(packet6) + 1)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test")
.parse13Input()
val test1Result = part1(testInput)
println(test1Result)
check(test1Result == 13)
val input = readInput("Day13")
.parse13Input()
println(part1(input))
val check2 = part2(testInput)
println(check2)
check(check2 == 140)
println(part2(input))
}
private sealed class Symbol {
object LeftBrace : Symbol()
object RightBrace : Symbol()
data class Number(val i: Int) : Symbol() {
override fun toString(): String {
return "$i"
}
}
}
private fun String.tokenize(): List<Symbol> {
val s: ArrayDeque<Symbol> = ArrayDeque()
val chars = this.toCharArray()
var i = 0
while (i <= chars.lastIndex) {
when (chars[i]) {
'[' -> {
s.addLast(Symbol.LeftBrace)
i += 1
}
']' -> {
i += 1
s.addLast(Symbol.RightBrace)
}
',' -> {
i += 1
}
in '0'..'9' -> {
var n = chars[i].digitToInt()
i += 1
while (i <= chars.lastIndex) {
when (chars[i]) {
in '0'..'9' -> {
n = n * 10 + chars[i].digitToInt()
i += 1
}
',' -> {
s.addLast(Symbol.Number(n))
n = 0
i += 1
}
'[', ']' -> {
s.addLast(Symbol.Number(n))
n = 0
break
}
else -> {
error("Unknown symbol in `$this` at position $i")
}
}
}
if (i > chars.lastIndex) {
s.addLast(Symbol.Number(n))
}
}
else -> {
error("Unknown symbol in `$this` at position $i")
}
}
}
return s
}
private fun String.parseListOrNumber(): ListOrNumber {
val symbols = this.tokenize()
val s: ArrayDeque<ListOrNumber.Sublist> = ArrayDeque()
if (symbols.size == 1 && symbols[0] is Symbol.Number) {
return ListOrNumber.Number((symbols[0] as Symbol.Number).i)
}
check(symbols[0] == Symbol.LeftBrace)
val root: ListOrNumber.Sublist = ListOrNumber.Sublist()
s.addLast(root)
symbols.drop(1).forEach { symbol ->
when (symbol) {
Symbol.LeftBrace -> ListOrNumber.Sublist().let { l ->
s.last().add(l)
s.addLast(l)
}
is Symbol.Number -> s.last().add(ListOrNumber.Number(symbol.i))
Symbol.RightBrace -> s.removeLast()
}
}
return root
}
// < 0: wrong order, 0: equals, 1: right order
private fun isInRightOrder(left: ListOrNumber, right: ListOrNumber): Int {
if (left is ListOrNumber.Number && right is ListOrNumber.Number) {
return right.v - left.v
} else if (left is ListOrNumber.Sublist && right is ListOrNumber.Sublist) {
left.forEachIndexed { index, listOrNumber ->
if (index > right.lastIndex) {
return -1
}
val cmp = isInRightOrder(listOrNumber, right[index])
if (cmp != 0) return cmp
}
return if (left.size == right.size) 0 else 1
} else {
return isInRightOrder(
if (left is ListOrNumber.Number) ListOrNumber.Sublist(left) else left,
if (right is ListOrNumber.Number) ListOrNumber.Sublist(right) else right,
)
}
}
private sealed class ListOrNumber {
data class Number(var v: Int) : ListOrNumber() {
override fun toString(): String = v.toString()
}
class Sublist : MutableList<ListOrNumber> by mutableListOf(), ListOrNumber() {
companion object {
operator fun invoke(i: ListOrNumber): Sublist = Sublist().apply {
add(i)
}
operator fun invoke(i: Int): Sublist = Sublist(Number(i))
}
}
}
private fun List<String>.parse13Input(): List<Pair<ListOrNumber, ListOrNumber>> {
return this
.filter(String::isNotEmpty)
.map(String::parseListOrNumber)
.chunked(2)
.map { l -> Pair(l[0], l[1]) }
} | 0 | Kotlin | 0 | 0 | 3c6bffd9ac60729f7e26c50f504fb4e08a395a97 | 5,309 | aoc22-kotlin | Apache License 2.0 |
src/main/kotlin/nl/tiemenschut/aoc/y2023/day4.kt | tschut | 723,391,380 | false | {"Kotlin": 61206} | package nl.tiemenschut.aoc.y2023
import nl.tiemenschut.aoc.lib.dsl.aoc
import nl.tiemenschut.aoc.lib.dsl.day
import nl.tiemenschut.aoc.lib.dsl.parser.AsListOfStrings
import java.math.BigDecimal
import java.math.BigInteger
fun main() {
aoc(AsListOfStrings) {
puzzle { 2023 day 4 }
val whitespace = "\\s+".toRegex()
fun String.splitToNumbers() = trim().split(whitespace).map { num -> num.toInt() }
fun String.parseNumbers() = split("|").let {
it.first().splitToNumbers() to it.last().splitToNumbers()
}
fun matchesForCard(winningNumbers: List<Int>, myNumbers: List<Int>): Int = myNumbers.map {
if (it in winningNumbers) 1 else 0
}.sum()
fun pointsForCard(winningNumbers: List<Int>, myNumbers: List<Int>): Int {
val matches = matchesForCard(winningNumbers, myNumbers)
return if (matches > 0) 1 shl (matches - 1) else 0
}
part1 { input ->
input.sumOf { card ->
val (winningNumbers, myNumbers) = card.split(":").last().parseNumbers()
pointsForCard(winningNumbers, myNumbers)
}
}
part2 { input ->
val pointsPerCard = input.map { card ->
val (winningNumbers, myNumbers) = card.split(":").last().parseNumbers()
matchesForCard(winningNumbers, myNumbers)
}
val totalCards = MutableList(input.size) { 1 }
for (i in totalCards.indices) {
if (pointsPerCard[i] > 0) {
for (p in 0 until pointsPerCard[i]) {
if (i + p + 1 < totalCards.size) totalCards[i + p + 1] += totalCards[i]
}
}
}
totalCards.sum()
}
}
}
| 0 | Kotlin | 0 | 1 | a1ade43c29c7bbdbbf21ba7ddf163e9c4c9191b3 | 1,822 | aoc-2023 | The Unlicense |
2022/Day13/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.min
fun main(args: Array<String>) {
val lines = File(args[0]).readLines()
println(problem1(lines))
println(problem2(lines))
}
fun problem1(lines: List<String>): Int {
val results = lines.windowed(3, 3).map { runCompare(it[0], it[1]) }
return results
.mapIndexed { idx, v ->
if (v) {
idx + 1
} else {
0
}
}
.sum()
}
fun problem2(lines: List<String>): Int {
val divider1 = "[[2]]"
val divider2 = "[[6]]"
val newLines = lines.filter { it != "" }.toMutableList()
newLines.add(divider1)
newLines.add(divider2)
newLines.sortWith(
Comparator<String> { a, b ->
val result = compare(a, b)
when (result) {
Result.GOOD -> -1
Result.BAD -> 1
Result.CONTINUE -> 0
}
}
)
return (newLines.indexOf(divider1) + 1) * (newLines.indexOf(divider2) + 1)
}
enum class Result {
GOOD,
BAD,
CONTINUE
}
fun runCompare(s1: String, s2: String): Boolean {
val result = compare(s1, s2)
return result != Result.BAD
}
fun compare(s1: String, s2: String): Result {
if (s1[0] == '[' && s2[0] == '[') {
return compareLists(s1, s2)
}
if (s1[0].isDigit() && s2[0].isDigit()) {
return compareScalars(s1, s2)
}
return compareMixed(s1, s2)
}
fun compareLists(s1: String, s2: String): Result {
val items1 = getListItems(s1)
val items2 = getListItems(s2)
for (i in 0 until min(items1.size, items2.size)) {
val res = compare(items1[i], items2[i])
if (res != Result.CONTINUE) {
return res
}
}
return when {
items1.size < items2.size -> Result.GOOD
items1.size > items2.size -> Result.BAD
else -> Result.CONTINUE
}
}
fun compareScalars(s1: String, s2: String): Result {
val n1 = s1.toInt()
val n2 = s2.toInt()
return when {
n1 < n2 -> Result.GOOD
n1 > n2 -> Result.BAD
else -> Result.CONTINUE
}
}
fun compareMixed(s1: String, s2: String): Result {
if (s1[0].isDigit()) {
return compareLists("[${s1}]", s2)
}
return compareLists(s1, "[${s2}]")
}
fun getListItems(s: String): List<String> {
var i = 1
var items = mutableListOf<String>()
while (i < s.length - 1) {
if (s[i].isDigit()) {
var numLen = extractNum(s, i)
items.add(s.substring(i, i + numLen))
i += numLen
} else {
var sublistLen = extractList(s, i)
items.add(s.substring(i, i + sublistLen))
i += sublistLen
}
i++ // skip ',' or ']'
}
return items
}
fun extractList(s: String, startIndex: Int): Int {
var numParens = 0
var i = startIndex
while (i < s.length) {
if (s[i] == '[') {
numParens++
} else if (s[i] == ']') {
if (--numParens == 0) {
return i + 1 - startIndex
}
}
i++
}
return -1
}
fun extractNum(s: String, _i: Int): Int {
var i = _i
while (s[i].isDigit()) {
i++
}
return i - _i
}
fun compare1(s1: String, s2: String): Boolean {
var i = 0
var j = 0
while (i < s1.length && j < s2.length) {
println("$i $j")
if (s1[i] == '[' && s2[j] == '[') {
i++
j++
} else if (s1[i] == '[' && s2[j].isDigit()) {
i++
} else if (s1[i].isDigit() && s2[j] == '[') {
j++
} else if (s1[i] == ']' && s2[j] == ']') {
i++
j++
} else if (s1[i] == ',' && s2[j] == ',') {
i++
j++
} else if (s1[i].isDigit() && s2[j].isDigit()) {
val n1Len = numLength(s1, i)
val n2Len = numLength(s2, j)
val n1 = s1.substring(i, i + n1Len).toInt()
val n2 = s2.substring(j, j + n2Len).toInt()
i += n1Len
j += n2Len
if (n1 < n2) return true
if (n1 > n2) return false
if (s1[i] == ']' && s2[j] != ']') return true
if (s1[i] != ']' && s2[j] == ']') return false
// both are ',' or both are ']'
i++
j++
} else if (s1[i] == ']' && s2[j] != ']') {
return true
} else if (s1[i] != ']' && s2[j] == ']') {
return false
} else {
throw Exception("Unexpected state: ${i} ${j}")
}
}
return true
}
fun numLength(s: String, _i: Int): Int {
var i = _i
while (s[i].isDigit()) {
i++
}
return i - _i
}
| 0 | Rust | 0 | 0 | c265f4c0bddb0357fe90b6a9e6abdc3bee59f585 | 4,797 | AdventOfCode | MIT License |
src/main/kotlin/day-05.kt | warriorzz | 434,696,820 | false | {"Kotlin": 16719} | package com.github.warriorzz.aoc
import java.nio.file.Files
import java.nio.file.Path
private fun main() {
println("Day 05:")
val ventMap: VentMap = Files.readAllLines(Path.of("./input/day-05.txt")).map {
val split = it.split(" ")
Vent(
split[0].split(",")[0].toInt(), split[0].split(",")[1].toInt(),
split[2].split(",")[0].toInt(), split[2].split(",")[1].toInt()
)
}.toMutableList()
val map = mutableMapOf<Pair<Int, Int>, Int>()
ventMap.forEach {
it.getAllLocations().forEach { location ->
map[location.first to location.second] = map[location.first to location.second]?.plus(1) ?: 1
}
}
val hotspots = map.map {
if (it.value >= 2) 1 else 0
}.reduce { acc, i -> acc + i }
println("Solution part 1: $hotspots")
val map2 = mutableMapOf<Pair<Int, Int>, Int>()
ventMap.forEach {
it.getAllLocations(true).forEach { location ->
map2[location.first to location.second] = map2[location.first to location.second]?.plus(1) ?: 1
}
}
val hotspots2 = map2.map {
if (it.value >= 2) 1 else 0
}.reduce { acc, i -> acc + i }
println("Solution part 1: $hotspots2")
}
typealias VentMap = MutableList<Vent>
data class Vent(val x1: Int, val x2: Int, val y1: Int, val y2: Int) {
fun getAllLocations(includeDiagonal: Boolean = false): List<Pair<Int, Int>> {
val list = ArrayList<Pair<Int, Int>>()
if (x1 == y1) {
(if (x2 < y2) (x2..y2) else (y2..x2)).forEach { xy2 ->
list.add(x1 to xy2)
}
} else if (x2 == y2) {
(if (x1 < y1) (x1..y1) else (y1..x1)).forEach { xy1 ->
list.add(xy1 to x2)
}
} else if (includeDiagonal) {
if (x1 <= y1) {
(x1..y1).forEachIndexed { index, i ->
list.add(i to if (x2 < y2) x2 + index else x2 - index)
}
} else {
(y1..x1).forEachIndexed { index, i ->
list.add(i to if (y2 < x2) y2 + index else y2 - index)
}
}
}
return list
}
}
fun day05() = main()
| 0 | Kotlin | 1 | 0 | 0143f59aeb8212d4ff9d65ad30c7d6456bf28513 | 2,290 | aoc-21 | MIT License |
src/Day18.kt | schoi80 | 726,076,340 | false | {"Kotlin": 83778} | import java.util.LinkedList
import kotlin.math.abs
data class DigPlan(
val d: Direction,
val v: Long,
val c: String? = null
)
fun String.toDirection(): Direction {
return when (this) {
"L", "2" -> Direction.LEFT
"R", "0" -> Direction.RIGHT
"U", "3" -> Direction.UP
"D", "1" -> Direction.DOWN
else -> error("Asdasd")
}
}
fun Char.toDirection(): Direction {
return when (this) {
'2' -> Direction.LEFT
'0' -> Direction.RIGHT
'3' -> Direction.UP
'1' -> Direction.DOWN
else -> error("Asdasd")
}
}
fun String.parse(): DigPlan {
return split(" ", limit = 3).let {
DigPlan(
d = it[0].toDirection(),
v = it[1].toLong(),
c = it[2]
)
}
}
fun String.parseV2(): DigPlan {
return split(" ", limit = 3).let {
val c = it[2].drop(2).dropLast(1)
DigPlan(
d = c.last().toDirection(),
v = c.take(5).toLong(16),
)
}
}
fun RowCol.move(d: Direction): RowCol {
return when (d) {
Direction.LEFT -> first to second - 1
Direction.RIGHT -> first to second + 1
Direction.UP -> first - 1 to second
Direction.DOWN -> first + 1 to second
}
}
fun Pair<Long, Long>.move(d: Direction, v: Long): Pair<Long, Long> {
return when (d) {
Direction.LEFT -> first to second - v
Direction.RIGHT -> first to second + v
Direction.UP -> first - v to second
Direction.DOWN -> first + v to second
}
}
fun MutableInput<Char>.mark(start: RowCol, p: DigPlan): RowCol {
var count = 0
var curr = start
while (count < p.v) {
curr = curr.move(p.d)
this.set(curr, '#')
count++
}
return curr
}
fun MutableInput<Char>.fill(pos: RowCol) {
val q = LinkedList<RowCol>()
q.add(pos)
while (q.isNotEmpty()) {
val p = q.pop()
if (this.get(p) == '#')
continue
if (this.get(p) == ' ') {
this.set(p, '#')
q.addAll(this.adjacent(p).filter { this.get(it) == ' ' })
}
}
}
fun main() {
// Brute forcing this at first...
fun part1(input: List<String>): Long {
var grid = Array(500) { Array<Char>(300) { ' ' } }
input.map { it.parse() }.fold(150 to 50) { acc, it ->
grid.mark(acc, it)
}
grid = grid.filter { it.joinToString("").trim() != "" }.toTypedArray()
grid.fill(1 to 192)
/**
grid.map { it.joinToString("") }.onEach { println(it) }
grid.onEachIndexed { index, chars -> println("$index: ${chars.toList()}") }
**/
return grid.sumOf { line ->
line.count { it == '#' }.toLong()
}
}
// Okay.. I got some help from here
// https://www.reddit.com/r/adventofcode/comments/18l0qtr/comment/kduu02z
fun part2(input: List<String>): Long {
val plans = input.map { it.parseV2() }
val polygon: List<Pair<Long, Long>> = plans.runningFold(0L to 0L) { curr, plan -> curr.move(plan.d, plan.v) }
// https://en.wikipedia.org/wiki/Shoelace_formula#Trapezoid_formula_2
val area = polygon.indices.sumOf { i ->
val curr = polygon[i]
// If curr is last coordinate, it must wrap back to origin
val next = if (i + 1 == polygon.size) polygon[0] else polygon[i + 1]
(curr.first + next.first) * (curr.second - next.second)
}.let { abs(it / 2) }
// This is essentially the perimeter,
// aka, every coordinate that represents the boundary of the polygon
val boundaryPoints = plans.sumOf { it.v }
// https://en.wikipedia.org/wiki/Pick%27s_theorem#Formula
// A = i + (b/2) - 1
// i = A - (b/2) + 1
val interiorPoints = area - (boundaryPoints / 2) + 1
// Cubic meter of lava is just the sum of boundary + interior points
return boundaryPoints + interiorPoints
}
val input = readInput("Day18")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | ee9fb20d0ed2471496185b6f5f2ee665803b7393 | 4,098 | aoc-2023 | Apache License 2.0 |
src/main/kotlin/me/grison/aoc/y2021/Day08.kt | agrison | 315,292,447 | false | {"Kotlin": 267552} | package me.grison.aoc.y2021
import me.grison.aoc.*
class Day08 : Day(8, 2021) {
override fun title() = "Seven Segment Search"
private val knownSegments = mapOf(2 to 1, 3 to 7, 4 to 4, 7 to 8)
override fun partOne() =
inputList.map { it.after(" | ").words() }
.fold(0) { acc, it ->
acc + it.map { it.length }.count { it in knownSegments.keys }
}
// faster solution
override fun partTwo(): Int {
return inputList.map { it.normalSplit(" | ").map { it.words() } }
.fold(0) { accu, (left, right) ->
val segments = left.associate { it.length to it.set() }
accu + right.fold("") { code, segment ->
segment.set().let { set ->
code + digit(segment.length, set.intersect(segments[4]!!).size, set.intersect(segments[2]!!).size)
}
}.int()
}
}
private fun digit(length: Int, second: Int, third: Int) =
if (length in knownSegments)
knownSegments[length]!!
else if (length == 5)
if (second == 2) 2 else if (third == 1) 5 else 3
else
if (second == 4) 9 else if (third == 1) 6 else 0
/* initial solution, but 50 times slower
override fun partTwo(): Int {
return inputList.map { it.normalSplit(" | ") }
.fold(0) { accu, (left, right) ->
val permutation = findPermutation(left.words())
accu + right.words()
.map { segment -> findDigitCode(segment, permutation) }
.fold("") { number, code -> number + "${digitCodes.indexOf(code)}" }
.int()
}
}
private val digitCodes =
listOf("abcefg", "cf", "acdeg", "acdfg", "bcdf", "abdfg", "abdefg", "acf", "abcdefg", "abcdfg").map { it.set() }
private val letters = "abcdefg".list()
private val permutations = letters.permutations()
private fun findDigitCode(segment: String, permutation: List<String>) =
segment.stringList()
.map { permutation.indexOf(it) }
.filter { it.pos() }
.map { letters[it] }
.toSet()
private fun findPermutation(displays: List<String>) =
permutations.first { permutation ->
displays.all { segment -> digitCodes.contains(findDigitCode(segment, permutation)) }
}
*/
} | 0 | Kotlin | 3 | 18 | ea6899817458f7ee76d4ba24d36d33f8b58ce9e8 | 2,455 | advent-of-code | Creative Commons Zero v1.0 Universal |
src/questions/SortLinkedList.kt | realpacific | 234,499,820 | false | null | package questions
import _utils.UseCommentAsDocumentation
import questions.common.LeetNode
import utils.assertIterableSame
/**
* Given the head of a linked list, return the list after sorting it in ascending order.
*
* [Source](https://leetcode.com/problems/sort-list/)
*/
@UseCommentAsDocumentation
private fun sortList(head: LeetNode?): LeetNode? {
if (head == null) return null
if (head.next == null) return head // just one node
// finding the mid of linked list using fast-slow pointer
// fast moves by 2
// slow moves by 1
var slowPointer: LeetNode? = head
var fastPointer: LeetNode? = slowPointer!!.next?.next
if (fastPointer == null) { // only two nodes, this can be sorted by comparing with each other
return if (slowPointer.`val` > slowPointer.next!!.`val`) swap(head, head.next!!)
else head
}
// find the mid of linked list
while (fastPointer != null) {
slowPointer = slowPointer!!.next // when fastPointer=null, slowPointer=mid point
fastPointer = fastPointer.next?.next
}
val anotherHalf = slowPointer!!.next // keep another half of linked list
slowPointer.next = null // detach the linked list
val firstHalf = sortList(head) // sort the first half (head ---> ... ---> slowPointer )
val secondHalf = sortList(anotherHalf) // sort the second half (slowPointer ---> ... ---> null)
if (firstHalf == null) return secondHalf
else if (secondHalf == null) return firstHalf
var newHead: LeetNode? = null
if (firstHalf.`val` <= secondHalf.`val`) { // lowest element is in the first half
newHead = firstHalf // make it the head
sort(
newHead,
firstHalf.next,
secondHalf
) // since head starts with first node of firstHalf, so compare with firstHalf.next
} else { // lowest in the second half
newHead = secondHalf
sort(newHead, firstHalf, secondHalf.next)
}
return newHead
}
/**
* @param head [LeetNode] where the sorted nodes are to be attached
* @param node1 [LeetNode] to be compared
* @param node2 [LeetNode] to be compared
*/
private fun sort(head: LeetNode, node1: LeetNode?, node2: LeetNode?) {
if (node1 == null && node2 == null) return
if (node1 == null) { // node1 is done
head.next = node2
return
}
if (node2 == null) { // node2 is done
head.next = node1
return
}
if (node1.`val` <= node2.`val`) {
head.next = node1 // attach the lowest to the [head]
sort(head.next!!, node1.next, node2) // compare next
} else if (node1.`val` > node2.`val`) {
head.next = node2 // attach the lowest to the [head]
sort(head.next!!, node1, node2.next) // compare next
}
}
private fun swap(prev: LeetNode, next: LeetNode): LeetNode {
val temp = next.next
next.next = prev
prev.next = temp
return next
}
fun main() {
run {
val input = intArrayOf(-1, 5, 4, 2, 0, 9, 3, 4)
assertIterableSame(
expected = input.sorted(),
sortList(LeetNode.from(input))!!.toList(),
)
}
assertIterableSame(
LeetNode.from(-1, 0, 3, 4, 5).toList(),
sortList(LeetNode.from(-1, 5, 3, 4, 0))!!.toList(),
)
assertIterableSame(
LeetNode.from(1, 2, 3, 4).toList(),
sortList(LeetNode.from(4, 2, 1, 3))!!.toList(),
)
assertIterableSame(
LeetNode.from(1, 2).toList(),
sortList(LeetNode.from(1, 2))!!.toList(),
)
assertIterableSame(
LeetNode.from(1).toList(),
sortList(LeetNode.from(1))!!.toList(),
)
assertIterableSame(
LeetNode.from(2, 100).toList(),
sortList(LeetNode.from(100, 2))!!.toList(),
)
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 3,773 | algorithms | MIT License |
y2019/src/main/kotlin/adventofcode/y2019/Day19.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2019
import adventofcode.io.AdventSolution
import adventofcode.language.intcode.IntCodeProgram
import adventofcode.util.collections.cartesian
import adventofcode.util.vector.Direction
import adventofcode.util.vector.Vec2
fun main() = Day19.solve()
object Day19 : AdventSolution(2019, 19, "Tractor Beam") {
override fun solvePartOne(input: String): Int {
val baseprogram = IntCodeProgram.fromData(input)
return (0 until 50).cartesian().count { baseprogram.isPartOfBeam(Vec2(it.first, it.second)) }
}
override fun solvePartTwo(input: String): Int {
val baseprogram = IntCodeProgram.fromData(input)
fun walk(p: Vec2, delta: Vec2, ontoBeam: Boolean) =
generateSequence(p) { it + delta }
.takeWhile { baseprogram.isPartOfBeam(it) != ontoBeam }
fun startOfBeam(a: Vec2) = walk(a, Vec2(1, -1), true).lastOrNull() ?: Vec2.origin
fun beamSizeAtLeast(a: Vec2, target: Int) = baseprogram.isPartOfBeam(startOfBeam(a) + Vec2(target, -target))
fun approximation(start: Vec2, step: Int) = generateSequence(startOfBeam(start)) { startOfBeam(it + Vec2(0, step)) }
.takeWhile { !beamSizeAtLeast(it, 99) }
.last()
val approx = generateSequence(1024) { it / 2 }
.takeWhile { it > 0 }
.fold(Vec2(0, 5)) { acc, step -> approximation(acc, step) }
return generateSequence(startOfBeam(approx)) { it + Direction.DOWN.vector }
.map { startOfBeam(it) }
.first { beamSizeAtLeast(it, 100) }
.let { 10000 * (it.x + 1) + it.y - 100 }
}
private fun IntCodeProgram.isPartOfBeam(p: Vec2) =
duplicate().run {
input(p.x.toLong())
input(p.y.toLong())
execute()
output() == 1L
}
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,912 | advent-of-code | MIT License |
src/Day04.kt | wedrychowiczbarbara | 573,185,235 | false | null | fun main() {
fun isOverlapCompletely(r: List<String>): Boolean{
return if (r[0].toInt() >= r[2].toInt() && r[1].toInt() <= r[3].toInt())
true
else
r[2].toInt() >= r[0].toInt() && r[3].toInt() <= r[1].toInt()
}
fun part1(input: List<String>): Int {
var suma=0
input.forEach{
val l = it.replace("-", ",").split(",")
if(isOverlapCompletely(l)){
suma++
}
}
return suma
}
fun isOverlap(r: List<String>): Boolean{
return r[2].toInt() in r[0].toInt()..r[1].toInt()
|| r[3].toInt() in r[0].toInt()..r[1].toInt()
|| r[0].toInt() in r[2].toInt()..r[3].toInt()
|| r[1].toInt() in r[2].toInt()..r[3].toInt()
}
fun part2(input: List<String>): Int {
var suma=0
input.forEach{
val l = it.replace("-", ",").split(",")
if(isOverlap(l)){
suma++
}
}
return suma
}
val input = readInput("input4")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 04abc035c51649dffe1dde8a115d98640552a99d | 1,133 | AOC_2022_Kotlin | Apache License 2.0 |
src/year_2023/day_03/Day03.kt | scottschmitz | 572,656,097 | false | {"Kotlin": 240069} | package year_2023.day_03
import readInput
import kotlin.math.max
import kotlin.math.min
data class PartNumber(
val lineNumber: Int,
val startPos: Int,
val endPos: Int,
val number: Int
)
fun String.containsSymbol(): Boolean {
return this.any { !it.isDigit() && it != '.' }
}
object Day03 {
/**
*
*/
fun solutionOne(text: List<String>): Int {
val numbers = mutableSetOf<PartNumber>()
text.forEachIndexed { y, line ->
line.forEachIndexed { x, _ ->
getNumberAtLocation(line, y, x)?.let { numbers.add(it) }
}
}
val partNumbers = mutableSetOf<PartNumber>()
numbers.forEach { partNumber ->
val start = max(0, partNumber.startPos - 1)
val end = min(text.first().length - 1, partNumber.endPos + 1)
if (partNumber.lineNumber > 0) {
if (text[partNumber.lineNumber - 1].substring(start, end + 1).containsSymbol()) {
partNumbers.add(partNumber)
}
}
if (text[partNumber.lineNumber].substring(start, end + 1).containsSymbol()) {
partNumbers.add(partNumber)
}
if (partNumber.lineNumber + 1 < text.size) {
if (text[partNumber.lineNumber + 1].substring(start, end + 1).containsSymbol()) {
partNumbers.add(partNumber)
}
}
}
return partNumbers.sumOf { it.number }
}
/**
*
*/
fun solutionTwo(text: List<String>): Int {
var total = 0
text.forEachIndexed { y, line ->
line.forEachIndexed { x, character ->
if (character == '*') {
val parts = mutableSetOf<PartNumber>()
// above
if (y > 0) {
getNumberAtLocation(text[y - 1], y-1,x - 1)?.let { parts.add(it) }
getNumberAtLocation(text[y - 1], y-1, x)?.let { parts.add(it) }
getNumberAtLocation(text[y - 1], y-1, x + 1)?.let { parts.add(it) }
}
// same line
getNumberAtLocation(line, y, x - 1)?.let { parts.add(it) }
getNumberAtLocation(line, y, x + 1)?.let { parts.add(it) }
// below
if (y + 1 < text.size) {
getNumberAtLocation(text[y + 1], y + 1, x - 1)?.let { parts.add(it) }
getNumberAtLocation(text[y + 1], y+1, x)?.let { parts.add(it) }
getNumberAtLocation(text[y + 1], y+1, x + 1)?.let { parts.add(it) }
}
if (parts.size == 2) {
val partsList = parts.toList()
total += partsList[0].number * partsList[1].number
}
}
}
}
return total
}
private fun getNumberAtLocation(line: String, y: Int, x: Int): PartNumber? {
if (!line[x].isDigit()) {
return null
}
var startPos = x
var endPos = x
var fullString = line[x].toString()
while (startPos > 0) {
if (line[startPos -1].isDigit()) {
startPos -= 1
fullString = "${line[startPos]}$fullString"
}
else {
break
}
}
while (endPos < line.length - 1) {
if (line[endPos + 1].isDigit()) {
endPos += 1
fullString = "$fullString${line[endPos]}"
} else {
break
}
}
return PartNumber(y, startPos, endPos, fullString.toInt())
}
}
fun main() {
val text = readInput("year_2023/day_03/Day03.txt")
val solutionOne = Day03.solutionOne(text)
println("Solution 1: $solutionOne")
val solutionTwo = Day03.solutionTwo(text)
println("Solution 2: $solutionTwo")
}
| 0 | Kotlin | 0 | 0 | 70efc56e68771aa98eea6920eb35c8c17d0fc7ac | 4,033 | advent_of_code | Apache License 2.0 |
src/twentytwo/Day09.kt | Monkey-Matt | 572,710,626 | false | {"Kotlin": 73188} | package twentytwo
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInputLines("Day09_test")
val part1 = part1(testInput)
println(part1)
check(part1 == 13)
val part2 = part2(testInput)
println(part2)
check(part2 == 1)
val testInputPart2 = readInputLines("Day09_test_part2")
val part2SecondInput = part2(testInputPart2)
println(part2SecondInput)
check(part2SecondInput == 36)
println("---")
val input = readInputLines("Day09_input")
println(part1(input))
println(part2(input))
}
private data class Position9(val x: Int, val y: Int)
private enum class Direction {
LEFT, RIGHT, UP, DOWN
}
private fun part1(input: List<String>): Int {
val visitedPositions = mutableSetOf<Position9>()
var headPosition = Position9(0, 0)
var tailPosition = Position9(0, 0)
val moves = input.toMoves()
moves.forEach { (direction, distance) ->
for (i in 0 until distance) {
val oldHeadPosition = headPosition
headPosition = when (direction) {
Direction.LEFT -> Position9(headPosition.x-1, headPosition.y)
Direction.RIGHT -> Position9(headPosition.x+1, headPosition.y)
Direction.UP -> Position9(headPosition.x, headPosition.y+1)
Direction.DOWN -> Position9(headPosition.x, headPosition.y-1)
}
when (direction) {
Direction.LEFT -> {
if (tailPosition.x == headPosition.x + 2) {
tailPosition = oldHeadPosition
}
}
Direction.RIGHT -> {
if (tailPosition.x == headPosition.x - 2) {
tailPosition = oldHeadPosition
}
}
Direction.UP -> {
if (tailPosition.y == headPosition.y - 2) {
tailPosition = oldHeadPosition
}
}
Direction.DOWN -> {
if (tailPosition.y == headPosition.y + 2) {
tailPosition = oldHeadPosition
}
}
}
visitedPositions.add(tailPosition)
}
}
return visitedPositions.size
}
private fun moveTail(
direction: Direction,
oldHeadPosition: Position9,
newHeadPosition: Position9,
oldTailPosition: Position9
): Position9 {
when (direction) {
Direction.LEFT -> {
if (oldTailPosition.x == newHeadPosition.x + 2) {
return oldHeadPosition
}
}
Direction.RIGHT -> {
if (oldTailPosition.x == newHeadPosition.x - 2) {
return oldHeadPosition
}
}
Direction.UP -> {
if (oldTailPosition.y == newHeadPosition.y - 2) {
return oldHeadPosition
}
}
Direction.DOWN -> {
if (oldTailPosition.y == newHeadPosition.y + 2) {
return oldHeadPosition
}
}
}
return oldTailPosition
}
private fun List<String>.toMoves(): List<Pair<Direction, Int>> {
return this.map {
val dir = when (it[0]) {
'R' -> Direction.RIGHT
'L' -> Direction.LEFT
'U' -> Direction.UP
'D' -> Direction.DOWN
else -> error("unexpected input ${it[0]}")
}
val distance = it.split(" ")[1].toInt()
dir to distance
}
}
private fun part2(input: List<String>): Int {
val visitedPositions = mutableSetOf<Position9>()
var headPosition = Position9(0, 0)
val tailPositions = MutableList(9) { Position9(0, 0) }
val moves = input.toMoves()
moves.forEach { (direction, distance) ->
for (i in 0 until distance) {
val oldHeadPosition = headPosition
headPosition = when (direction) {
Direction.LEFT -> Position9(headPosition.x-1, headPosition.y)
Direction.RIGHT -> Position9(headPosition.x+1, headPosition.y)
Direction.UP -> Position9(headPosition.x, headPosition.y+1)
Direction.DOWN -> Position9(headPosition.x, headPosition.y-1)
}
val oldTailPositions = tailPositions.toList()
tailPositions[0] = moveTail(direction, oldHeadPosition, headPosition, tailPositions[0])
tailPositions[1] = moveTailSpecial(oldTailPositions[0], tailPositions[0], tailPositions[1])
tailPositions[2] = moveTailSpecial(oldTailPositions[1], tailPositions[1], tailPositions[2])
tailPositions[3] = moveTailSpecial(oldTailPositions[2], tailPositions[2], tailPositions[3])
tailPositions[4] = moveTailSpecial(oldTailPositions[3], tailPositions[3], tailPositions[4])
tailPositions[5] = moveTailSpecial(oldTailPositions[4], tailPositions[4], tailPositions[5])
tailPositions[6] = moveTailSpecial(oldTailPositions[5], tailPositions[5], tailPositions[6])
tailPositions[7] = moveTailSpecial(oldTailPositions[6], tailPositions[6], tailPositions[7])
tailPositions[8] = moveTailSpecial(oldTailPositions[7], tailPositions[7], tailPositions[8])
visitedPositions.add(tailPositions[8])
}
}
return visitedPositions.size
}
private enum class DirectionSpecial {
NONE, LEFT, RIGHT, UP, DOWN, UP_RIGHT, UP_LEFT, DOWN_RIGHT, DOWN_LEFT
}
private fun moveTailSpecial(
oldHeadPosition: Position9,
newHeadPosition: Position9,
oldTailPosition: Position9
): Position9 {
if (oldTailPosition.x <= newHeadPosition.x + 1 && oldTailPosition.x >= newHeadPosition.x - 1 &&
oldTailPosition.y <= newHeadPosition.y + 1 && oldTailPosition.y >= newHeadPosition.y - 1) {
return oldTailPosition
}
when (oldHeadPosition.directionTo(newHeadPosition)) {
DirectionSpecial.LEFT -> {
if (oldTailPosition.x == newHeadPosition.x + 2) {
return oldHeadPosition
}
}
DirectionSpecial.RIGHT -> {
if (oldTailPosition.x == newHeadPosition.x - 2) {
return oldHeadPosition
}
}
DirectionSpecial.UP -> {
if (oldTailPosition.y == newHeadPosition.y - 2) {
return oldHeadPosition
}
}
DirectionSpecial.DOWN -> {
if (oldTailPosition.y == newHeadPosition.y + 2) {
return oldHeadPosition
}
}
DirectionSpecial.NONE -> return oldTailPosition
DirectionSpecial.UP_RIGHT -> {
if (oldTailPosition.y <= oldHeadPosition.y && oldTailPosition.x <= oldHeadPosition.x) {
return Position9(oldTailPosition.x+1, oldTailPosition.y+1)
}
if (oldTailPosition.y == newHeadPosition.y - 2) {
return Position9(oldTailPosition.x, oldTailPosition.y + 1)
}
if (oldTailPosition.x == newHeadPosition.x - 2) {
return Position9(oldTailPosition.x + 1, oldTailPosition.y)
}
}
DirectionSpecial.UP_LEFT -> {
if (oldTailPosition.y <= oldHeadPosition.y && oldTailPosition.x >= oldHeadPosition.x) {
return Position9(oldTailPosition.x-1, oldTailPosition.y+1)
}
if (oldTailPosition.y == newHeadPosition.y - 2) {
return Position9(oldTailPosition.x, oldTailPosition.y + 1)
}
if (oldTailPosition.x == newHeadPosition.x + 2) {
return Position9(oldTailPosition.x - 1, oldTailPosition.y)
}
}
DirectionSpecial.DOWN_RIGHT -> {
if (oldTailPosition.y >= oldHeadPosition.y && oldTailPosition.x <= oldHeadPosition.x) {
return Position9(oldTailPosition.x+1, oldTailPosition.y-1)
}
if (oldTailPosition.y == newHeadPosition.y + 2) {
return Position9(oldTailPosition.x, oldTailPosition.y - 1)
}
if (oldTailPosition.x == newHeadPosition.x - 2) {
return Position9(oldTailPosition.x + 1, oldTailPosition.y)
}
}
DirectionSpecial.DOWN_LEFT -> {
if (oldTailPosition.y >= oldHeadPosition.y && oldTailPosition.x >= oldHeadPosition.x) {
return Position9(oldTailPosition.x-1, oldTailPosition.y-1)
}
if (oldTailPosition.y == newHeadPosition.y + 2) {
return Position9(oldTailPosition.x, oldTailPosition.y - 1)
}
if (oldTailPosition.x == newHeadPosition.x + 2) {
return Position9(oldTailPosition.x - 1, oldTailPosition.y)
}
}
}
return oldTailPosition
}
private fun Position9.directionTo(other: Position9): DirectionSpecial {
if (this == other) return DirectionSpecial.NONE
if (this.x == other.x && this.y == other.y - 1) return DirectionSpecial.UP
if (this.x == other.x && this.y == other.y + 1) return DirectionSpecial.DOWN
if (this.x <= other.x - 1 && this.y <= other.y - 1) return DirectionSpecial.UP_RIGHT
if (this.x >= other.x + 1 && this.y <= other.y - 1) return DirectionSpecial.UP_LEFT
if (this.x <= other.x - 1 && this.y >= other.y + 1) return DirectionSpecial.DOWN_RIGHT
if (this.x >= other.x + 1 && this.y >= other.y + 1) return DirectionSpecial.DOWN_LEFT
if (this.x == other.x - 1 && this.y == other.y) return DirectionSpecial.RIGHT
if (this.x == other.x + 1 && this.y == other.y) return DirectionSpecial.LEFT
error("direction missing from calc. $this - $other")
}
| 1 | Kotlin | 0 | 0 | 600237b66b8cd3145f103b5fab1978e407b19e4c | 9,717 | advent-of-code-solutions | Apache License 2.0 |
src/Day20.kt | janbina | 112,736,606 | false | null | package Day20
import getInput
import kotlin.math.abs
import kotlin.test.assertEquals
fun main(args: Array<String>) {
val input = getInput(20).readLines()
.map { Regex("-?\\d+")
.findAll(it)
.map { it.value.toLong() }
.toList()
}
.mapIndexed { index, it -> Point(index, Triple(it[0], it[1], it[2]), Triple(it[3], it[4], it[5]), Triple(it[6], it[7], it[8])) }
assertEquals(125, part1(input))
assertEquals(461, part2(input))
}
data class Point(
val id: Int,
var position: Triple<Long, Long, Long>,
var velocity: Triple<Long, Long, Long>,
val acceleration: Triple<Long, Long, Long>
) {
fun tick() {
velocity += acceleration
position += velocity
}
}
fun part1(input: List<Point>): Int {
return input.sortedWith(compareBy({it.acceleration.absSum()}, {it.velocity.absSum()}, {it.position.absSum()}))
.first().id
}
fun part2(input: List<Point>): Int {
var particles = input
var lastValue = -1
var sameCount = 0
val sameThreshold = 30
while (true) {
particles = particles.groupBy { it.position }
.filter { it.value.size == 1 }
.values
.map { it.first() }
if (particles.size == lastValue) {
sameCount++
if (sameCount > sameThreshold) {
return particles.size
}
} else {
sameCount = 0
lastValue = particles.size
}
input.forEach { it.tick() }
}
}
operator fun Triple<Long, Long, Long>.plus(other: Triple<Long, Long, Long>): Triple<Long, Long, Long> {
return Triple(this.first + other.first, this.second + other.second, this.third + other.third)
}
fun Triple<Long, Long, Long>.absSum(): Long {
return abs(this.first) + abs(this.second) + abs(this.third)
} | 0 | Kotlin | 0 | 0 | 71b34484825e1ec3f1b3174325c16fee33a13a65 | 1,930 | advent-of-code-2017 | MIT License |
src/Day14.kt | brigittb | 572,958,287 | false | {"Kotlin": 46744} |
private val sourceOfSand = Point(x = 500, y = 0)
private const val X_MAX_THRESHOLD = 1000
fun main() {
fun parse(input: List<String>) = input
.filter { it.isNotEmpty() }
.map {
it
.split(" -> ")
.map { coordinates ->
val (x, y) = coordinates.split(",")
Point(x = x.toInt(), y = y.toInt())
}
}
fun getXRange(parsedInput: List<Point>): Pair<Int, Int> {
val xCoordinates = parsedInput.map { it.x }
val highest = xCoordinates.maxOf { it }
val lowest = xCoordinates.minOf { it }
return lowest to highest
}
fun getRange(from: Int, to: Int): IntProgression =
if (from <= to) from..to else from downTo to
fun setupInitialState(
highestY: Int,
highestX: Int,
rockPositions: List<List<Point>>,
): Array<Array<Point>> {
val grid = Array(highestY + 1) { y -> Array(highestX + 1) { x -> Point(x = x, y = y) } }
rockPositions
.map {
it
.windowed(2)
.map { (first, second) -> first to second }
}
.forEach { coordinates ->
coordinates.forEach { (from, to) ->
for (y in getRange(from.y, to.y)) {
for (x in getRange(from.x, to.x)) {
with(grid[y][x]) {
this.x = x
this.y = y
this.type = '#'
}
}
}
}
}
grid[sourceOfSand.y][sourceOfSand.x].type = '+'
return grid
}
fun printState(grid: Array<Array<Point>>, lowestX: Int) {
grid.forEachIndexed { _, columns ->
columns.forEachIndexed { _, point ->
if (point.x >= lowestX) {
print(point.type)
}
}
println()
}
}
fun moveSand(sourceOfSand: Point, grid: Array<Array<Point>>, lowestX: Int): Point {
var sand = sourceOfSand
do {
sand = sand.move(grid, lowestX)
} while (sand.nextPoint(grid, lowestX) != null)
grid[sand.y][sand.x] = sand
return sand
}
fun part1(input: List<String>): Int {
val rockPositions = parse(input)
val availableRockPositions = rockPositions.flatten()
val (lowestX, highestX) = getXRange(availableRockPositions)
val highestY = availableRockPositions
.map { it.y }
.maxOf { it }
val grid = setupInitialState(highestY, highestX, rockPositions)
var round = 0
do {
val sand = moveSand(sourceOfSand = sourceOfSand.copy(type = 'o'), grid = grid, lowestX = lowestX)
round++
} while (!sand.fallingDown(grid, lowestX))
println("-- result --")
printState(grid, lowestX)
return round - 1
}
fun part2(input: List<String>): Int {
val rockPositions = parse(input)
val availableRockPositions = rockPositions.flatten()
val (_, highestX) = getXRange(availableRockPositions)
val highestY = availableRockPositions
.map { it.y }
.maxOf { it }
.plus(2)
val grid = setupInitialState(highestY, highestX + X_MAX_THRESHOLD, rockPositions)
grid[highestY].forEach { grid[it.y][it.x].type = '#' }
var round = 0
do {
val sourceOfSandIsBlocked = grid[sourceOfSand.y][sourceOfSand.x].type == 'o'
moveSand(sourceOfSand = sourceOfSand.copy(type = 'o'), grid = grid, lowestX = 0)
round++
} while (!sourceOfSandIsBlocked)
println("-- result --")
printState(grid, 0)
return round - 1
}
// 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))
}
data class Point(
var x: Int,
var y: Int,
var type: Char = '.',
) {
fun move(grid: Array<Array<Point>>, lowestX: Int): Point {
val target = this.nextPoint(grid, lowestX)
if (target != null)
return Point(x = target.x, y = target.y, type = type)
if (this == sourceOfSand.copy(type = 'o'))
return this
error("sand should not flow into the abyss at this point.")
}
fun nextPoint(grid: Array<Array<Point>>, lowestX: Int): Point? {
if (fallingDown(grid, lowestX))
return null
val leftDown = grid[this.y + 1][this.x - 1]
val rightDown = grid[this.y + 1][this.x + 1]
val down = grid[this.y + 1][this.x]
return listOf(down, leftDown, rightDown).firstOrNull { it.type == '.' }
}
fun fallingDown(
grid: Array<Array<Point>>,
lowestX: Int,
): Boolean =
this.y >= grid.size - 1 || this.x >= grid[0].size - 1 || this.x < lowestX
}
| 0 | Kotlin | 0 | 0 | 470f026f2632d1a5147919c25dbd4eb4c08091d6 | 5,216 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/day21/Solution2.kt | janneri | 572,969,955 | false | {"Kotlin": 99028} | package day21
import day21.MonkeyMath.calculateLeftValue
import day21.MonkeyMath.calculateRightValue
import util.readInput
data class MonkeyValue(
var name: String,
var leftName: String? = null,
var rightName: String? = null,
var mathOperation: String? = null,
var number: ULong? = null
)
data class TreeNode(var monkeyValue: MonkeyValue) {
var left: TreeNode? = null
var right: TreeNode? = null
fun isLeafNode() = left == null && right == null
}
object MonkeyParser {
private val numberMonkeyRegex = Regex("""([a-z]+): (\d+)""")
private val mathOperationMonkeyRegex = Regex("""([a-z]+): ([a-z]+) (.) ([a-z]+)""")
fun parseMonkeys(inputLines: List<String>): Map<String, TreeNode> {
val nodes = inputLines.map { inputLine ->
if (numberMonkeyRegex.containsMatchIn(inputLine)) {
numberMonkeyRegex.matchEntire(inputLine)!!.destructured.let {
(name, number) -> TreeNode(MonkeyValue(name, number = number.toULong())) }
}
else {
val groups = mathOperationMonkeyRegex.matchEntire(inputLine)!!.groupValues
TreeNode(MonkeyValue(name = groups[1], leftName = groups[2], mathOperation = groups[3], rightName = groups[4]))
}
}
val nodesByMonkeyName = nodes.associateBy { it.monkeyValue.name }
nodes
.filter { it.monkeyValue.leftName != null }
.forEach {
it.left = nodesByMonkeyName[it.monkeyValue.leftName]
it.right = nodesByMonkeyName[it.monkeyValue.rightName]
}
return nodesByMonkeyName
}
}
object MonkeyMath {
fun calculate(operation: String, leftValue: ULong, rightValue: ULong): ULong =
when (operation) {
"+" -> leftValue + rightValue
"-" -> leftValue - rightValue
"*" -> leftValue * rightValue
else -> leftValue / rightValue
}
/** returns the unknown left value when the right value is known */
fun calculateLeftValue(operation: String, expectedResult: ULong, rightValue: ULong) =
when (operation) {
"+" -> expectedResult - rightValue // ? + rightValue = expectedResult
"-" -> expectedResult + rightValue // ? - rightValue = expectedResult
"*" -> expectedResult / rightValue // ? * rightValue = expectedResult
else -> expectedResult * rightValue // ? / rightValue = expectedResult
}
/** returns the unknown right value when the left value is known */
fun calculateRightValue(operation: String, expectedResult: ULong, leftValue: ULong) =
when (operation) {
"+" -> expectedResult - leftValue // leftValue + ? = expectedResult
"-" -> leftValue - expectedResult // leftValue - ? = expectedResult
"*" -> expectedResult / leftValue // leftValue * ? = expectedResult
else -> leftValue / expectedResult // leftValue / ? = expectedResult
}
}
class MonkeyTree(val root: TreeNode) {
// Calculate values of all the nodes down the tree
fun calculateValue(node: TreeNode): ULong {
if (node.isLeafNode()) {
return node.monkeyValue.number!!
}
return MonkeyMath.calculate(node.monkeyValue.mathOperation!!, calculateValue(node.left!!), calculateValue(node.right!!))
}
// Find the humn-node and pass down the expected value of it
fun calculateValuePart2(node: TreeNode, humnPath: Set<TreeNode>, expectedResult: ULong): ULong {
if (node.isLeafNode()) {
return if (node.monkeyValue.name == "humn") expectedResult else node.monkeyValue.number!!
}
return if (node.left in humnPath) {
calculateValuePart2(node.left!!, humnPath, calculateLeftValue(
node.monkeyValue.mathOperation!!, expectedResult, calculateValue(node.right!!)
))
}
else {
calculateValuePart2(node.right!!, humnPath, calculateRightValue(
node.monkeyValue.mathOperation!!, expectedResult, calculateValue(node.left!!)
))
}
}
fun findPathToNode(predicate: (TreeNode) -> Boolean): Set<TreeNode> {
fun findPath(node: TreeNode?, path: MutableList<TreeNode>): Boolean {
if (node == null) return false
path += node
if (predicate(node) || findPath(node.left, path) || findPath(node.right, path)) {
return true
}
path.removeLast()
return false
}
val path = mutableListOf<TreeNode>()
findPath(root, path)
return path.toSet()
}
}
fun main() {
val nodesByMonkeyName: Map<String, TreeNode> = MonkeyParser.parseMonkeys(readInput("day21"))
val monkeyTree = MonkeyTree(nodesByMonkeyName["root"]!!)
// part 1
println("part1: ${monkeyTree.calculateValue(monkeyTree.root)}")
// part 2
val humnPath = monkeyTree.findPathToNode { it.monkeyValue.name == "humn" }
val part2Result = if (monkeyTree.root.left in humnPath) {
monkeyTree.calculateValuePart2(monkeyTree.root.left!!, humnPath, monkeyTree.calculateValue(monkeyTree.root.right!!))
} else {
monkeyTree.calculateValuePart2(monkeyTree.root.right!!, humnPath, monkeyTree.calculateValue(monkeyTree.root.left!!))
}
println("part2: $part2Result")
} | 0 | Kotlin | 0 | 0 | 1de6781b4d48852f4a6c44943cc25f9c864a4906 | 5,406 | advent-of-code-2022 | MIT License |
dataStructuresAndAlgorithms/src/main/java/dev/funkymuse/datastructuresandalgorithms/sort/MergeSortSentinel.kt | FunkyMuse | 168,687,007 | false | {"Kotlin": 1728251} | package dev.funkymuse.datastructuresandalgorithms.sort
/**
* Merge Sort using Sentinels - Int.MAX_VALUE entries when merging lists.
* Allows to eliminate checks for whether the left/right list are fully added to the original list.
* Performs better than plain merge sort at the cost of extra O(2 (log N)) auxiliary memory.
*
* Time complexity per case:
* Best, Average, Worst - O(n log n), logarithmic.
*
* Space complexity:
* Auxiliary O(n) memory.
*/
/**
* To sort a list, this method calls mergeSortSentinel with start = 0 and end = the index of the last element in the list.
*/
fun mergeSortSentinel(list: MutableList<Int>) = mergeSortSentinel(list, 0, list.size - 1)
private fun mergeSortSentinel(list: MutableList<Int>, start: Int, end: Int) {
/**
* While the list has more than 1 element, split it in two and recursively sort those two lists.
* After they have been sorted, merge them together.
*/
if (end > start) {
val mid = (end + start) / 2
mergeSortSentinel(list, start, mid)
mergeSortSentinel(list, mid + 1, end)
merge(list, start, mid, end)
}
}
/**
* Merging two sorted lists takes O(n) time, which is the reason behind merge sort's efficiency.
* Merging is separated in two parts:
* 1. Putting all elements from both sublists into new lists, called left and right respectively.
* 2. Putting the smallest remaining element from both the lists into the original list to be sorted at index k,
* where k is equal to start + number of elements put so far into the original list.
*/
private fun merge(list: MutableList<Int>, start: Int, mid: Int, end: Int) {
val numLeft = mid - start + 1
val numRight = end - mid
val leftArray = IntArray(numLeft + 1)
val rightArray = IntArray(numRight + 1)
// Lines 50-55 put the elements into the new sublists.
for (i in 1..numLeft) {
leftArray[i - 1] = list[start + i - 1]
}
for (i in 1..numRight) {
rightArray[i - 1] = list[mid + i]
}
/* Lines 57-58 put two special values—called sentinels—into the lists. This is done to further improve
the performance on lines 64-66, when actual merging happens.
*/
leftArray[numLeft] = Int.MAX_VALUE
rightArray[numRight] = Int.MAX_VALUE
var i = 0
var j = 0
for (k in start..end) {
list[k] = if (leftArray[i] < rightArray[j]) leftArray[i++] else rightArray[j++]
}
}
| 0 | Kotlin | 92 | 771 | e2afb0cc98c92c80ddf2ec1c073d7ae4ecfcb6e1 | 2,462 | KAHelpers | MIT License |
src/main/kotlin/Day8.kt | i-redbyte | 433,743,675 | false | {"Kotlin": 49932} | private const val SHOW_1_COUNT = 2
private const val SHOW_4_COUNT = 4
private const val SHOW_7_COUNT = 3
private const val SHOW_8_COUNT = 7
private typealias Display = Pair<List<String>, List<String>>
fun main() {
val data = readInputFile("day8")
val initialState: List<Display> = data.map { line ->
line.split("|").let { it[0].trim().split(" ") to it[1].trim().split(" ")}
}
fun part1(): Int = initialState.flatMap { it.second }.count {
it.length in listOf(SHOW_1_COUNT, SHOW_4_COUNT, SHOW_7_COUNT, SHOW_8_COUNT)
}
fun part2(): Int =
initialState.sumOf { (wires, output) ->
val oneDisplay = wires.first { it.length == SHOW_1_COUNT }
val fourDisplay = wires.first { it.length == SHOW_4_COUNT }
val sevenDisplay = wires.first { it.length == SHOW_7_COUNT }
val eightDisplay = wires.first { it.length == SHOW_8_COUNT }
val rightSegments = oneDisplay.toCharArray()
val middleSegments = fourDisplay.filterNot { it in sevenDisplay }.toCharArray()
val bottomSegments = eightDisplay.filterNot { it in sevenDisplay + fourDisplay }.toCharArray()
output.map { show ->
when (show.length) {
SHOW_1_COUNT -> 1
SHOW_4_COUNT -> 4
SHOW_7_COUNT -> 7
SHOW_8_COUNT -> 8
5 -> when {
show.containsAll(*middleSegments) -> 5
show.containsAll(*bottomSegments) -> 2
else -> 3
}
6 -> when {
show.containsAll(*middleSegments, *rightSegments) -> 9
show.containsAll(*middleSegments) -> 6
else -> 0
}
else -> error("Error $show")
}
}.joinToString("") { it.toString() }.toInt()
}
println("Result part1: ${part1()}")
println("Result part2: ${part2()}")
}
private fun String.containsAll(vararg chars: Char): Boolean = chars.all { it in this } | 0 | Kotlin | 0 | 0 | 6d4f19df3b7cb1906052b80a4058fa394a12740f | 2,146 | AOC2021 | Apache License 2.0 |
src/year2023/day01/Day.kt | tiagoabrito | 573,609,974 | false | {"Kotlin": 73752} | package year2023.day01
import year2023.solveIt
fun main() {
val day = "01"
val expectedTest1 = 142L
val expectedTest2 = 281L
fun part1(input: List<String>): Long {
return input.sumOf { line -> Integer.valueOf(line.first { it in '0'..'9' }.toString() + line.last { it in '0'..'9' }.toString()) }.toLong()
}
fun part2(input: List<String>): Long {
val possible = mapOf(
"one" to 1,
"two" to 2,
"three" to 3,
"four" to 4,
"five" to 5,
"six" to 6,
"seven" to 7,
"eight" to 8,
"nine" to 9,
"0" to 0,
"1" to 1,
"2" to 2,
"3" to 3,
"4" to 4,
"5" to 5,
"6" to 6,
"7" to 7,
"8" to 8,
"9" to 9
)
return input.map { line ->
possible.map { it to line.indexOf(it.key) }.filter { it.second>=0 }.sortedBy { it.second }.first().first.value * 10 +
possible.map { it to line.lastIndexOf(it.key) }.filter { it.second>=0 }.sortedBy { it.second }.asReversed().first().first.value
}.sum().toLong()
}
solveIt(day, ::part1, expectedTest1, ::part2, expectedTest2, "test2")
}
| 0 | Kotlin | 0 | 0 | 1f9becde3cbf5dcb345659a23cf9ff52718bbaf9 | 1,297 | adventOfCode | Apache License 2.0 |
src/Day10.kt | aaronbush | 571,776,335 | false | {"Kotlin": 34359} | fun main() {
fun process(input: List<String>): List<Int> {
var xreg = 1
var cycleCount = 0
val regHistory = mutableListOf(xreg)
input.forEach { line ->
when (val op = line.substringBefore(" ")) {
"addx" -> {
val arg = line.substringAfter(" ").toInt()
cycleCount++
regHistory += xreg
cycleCount++
xreg += arg
regHistory += xreg
}
"noop" -> {
regHistory += xreg
cycleCount++
}
else -> throw UnsupportedOperationException("$op not recognized")
}
}
return regHistory
}
fun part1(input: List<String>): Int {
val regHistory = process(input)
val signals = mutableListOf(regHistory.take(20).last() * 20)
regHistory.drop(20).chunked(40).forEachIndexed { i, l ->
if (l.size == 40)
signals += l.last() * (20 + (i + 1) * 40)
}
println("signals = $signals")
return signals.sum()
}
fun part2(input: List<String>): Int {
val regHistory = process(input)
val screenBuffer = mutableListOf<Array<Array<String>>>()
fun render(crt: Array<Array<String>>): String {
return crt.mapIndexed { index, line ->
"$index: " + line.joinToString(separator = "")
}.joinToString(separator = "\n")
}
regHistory.windowed(40 * 6, 40 * 6) { regWindow ->
val crtContents = Array(6) { _ -> Array(40) { _ -> "." } }
regWindow.forEachIndexed { index, regValue ->
val row = index / 40
val col = index - row * 40
val spritePos = regValue - 1..regValue + 1
if (col in spritePos) {
crtContents[row][col] = "#"
}
}
screenBuffer += crtContents
}
screenBuffer.forEach {
println(render(it))
}
// F C J A P J R E
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
// check(part1(testInput) == 13140)
// check(part2(testInput) == 0)
val input = readInput("Day10")
// println("p1: ${part1(input)}")
println("p2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | d76106244dc7894967cb8ded52387bc4fcadbcde | 2,477 | aoc-2022-kotlin | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.