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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2021/src/day15/Solution.kt | vadimsemenov | 437,677,116 | false | {"Kotlin": 56211, "Rust": 37295} | package day15
import java.nio.file.Files
import java.nio.file.Paths
import java.util.TreeSet
import kotlin.system.measureTimeMillis
fun main() {
fun part1(input: Input): Int {
val costs = Array(input.size) {
IntArray(input[it].size) { Int.MAX_VALUE }
}
val priorityQueue = TreeSet(
Comparator
.comparingInt<Pair<Int, Int>> { costs[it.first][it.second] }
.thenComparingInt { it.first }
.thenComparingInt { it.second }
)
costs[0][0] = 0
priorityQueue.add(0 to 0)
val dx = arrayOf(-1, 0, 1, 0)
val dy = arrayOf(0, 1, 0, -1)
while (priorityQueue.isNotEmpty()) {
val (x, y) = priorityQueue.pollFirst()!!
if (x == input.lastIndex && y == input[x].lastIndex) {
return costs[x][y]
}
for (d in 0 until 4) {
val xx = x + dx[d]
val yy = y + dy[d]
if (xx in input.indices && yy in input[xx].indices) {
val newCost = costs[x][y] + input[xx][yy]
if (newCost < costs[xx][yy]) {
priorityQueue.remove(xx to yy)
costs[xx][yy] = newCost
priorityQueue.add(xx to yy)
}
}
}
}
error("Polundra!")
}
fun part2(input: Input): Int {
val newInput = List(input.size * 5) { xx ->
val x = xx % input.size
List(input[x].size * 5) { yy ->
val y = yy % input[x].size
val diagonal = xx / input.size + yy / input[x].size
(input[x][y] - 1 + diagonal) % 9 + 1
}
}
return part1(newInput)
}
check(part1(readInput("test-input.txt")) == 40)
check(part2(readInput("test-input.txt")) == 315)
val timeSpent = measureTimeMillis {
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
System.err.println("In ${timeSpent}ms")
}
private fun readInput(s: String): Input {
return Files.newBufferedReader(Paths.get("src/day15/$s")).readLines().map { it.map { it.code - '0'.code } }
}
private typealias Input = List<List<Int>> | 0 | Kotlin | 0 | 0 | 8f31d39d1a94c862f88278f22430e620b424bd68 | 2,004 | advent-of-code | Apache License 2.0 |
arrays/AddingTwoNegabinaryNumbers/kotlin/Solution.kt | YaroslavHavrylovych | 78,222,218 | false | {"Java": 284373, "Kotlin": 35978, "Shell": 2994} | import kotlin.math.sign
import java.lang.Integer.max
/**
* 1073. Adding Two Negabinary Numbers.
* <br>
* Given two numbers arr1 and arr2 in base -2, return the result
* of adding them together.
* Each number is given in array format: as an array of 0s and 1s,
* from most significant bit to least significant bit.
* For example, arr = [1,1,0,1] represents the number
* (-2)^3 + (-2)^2 + (-2)^0 = -3. A number arr in array, format is also
* guaranteed to have no leading zeros: either arr == [0] or arr[0] == 1.
*
* Return the result of adding arr1 and arr2 in the same format:
* as an array of 0s and 1s with no leading zeros.
* <br/>
* https://leetcode.com/problems/adding-two-negabinary-numbers/
*/
fun addNegabinary(arr1: IntArray, arr2: IntArray): IntArray {
val res = IntArray(max(arr1.size, arr2.size) + 4) { 0 }
for (i in res.indices) {
val v1 = if (i < arr1.size) arr1[arr1.size - i - 1] else 0
val v2 = if (i < arr2.size) arr2[arr2.size - i - 1] else 0
if (v1 == 0 && v2 == 0) continue
if (v1 == 1 && v2 == 1) {
res.addOne(i + 1)
res.addOne(i + 2)
} else {
res.addOne(i)
}
}
val lastInd = res.indexOfLast { it == 1 }
if (lastInd == -1) return intArrayOf(0)
return res.take(lastInd + 1).reversed().toIntArray()
}
fun IntArray.addOne(pos: Int) {
if (this[pos] == 0) {
this[pos] = 1
return
}
if (this[pos + 1] == 1) { //this[pos] == 1
this[pos] = 0
this[pos + 1] = 0
return
}
this[pos] = 0
addOne(pos + 1)
addOne(pos + 2)
}
fun main() {
print("Adding Two Negabinary Numbers:")
var a = true
a = a && addNegabinary(intArrayOf(1,0 /* -2 */), intArrayOf(1,1,0 /* 2 */)).contentToString() == "[0]"
a = a && addNegabinary(intArrayOf(1,1,1,1,1 /* 11 */), intArrayOf(1,0,1 /* 5 */)).contentToString() == "[1, 0, 0, 0, 0]"
a = a && addNegabinary(intArrayOf(1 /* 1 */), intArrayOf(0 /* 0 */)).contentToString() == "[1]"
a = a && addNegabinary(intArrayOf(1 /* 1 */), intArrayOf(1 /* 1 */)).contentToString() == "[1, 1, 0]"
a = a && addNegabinary(intArrayOf(0 /* 0 */), intArrayOf(0 /* 0 */)).contentToString() == "[0]"
a = a && addNegabinary(intArrayOf(1,1,1,1,1 /* 11 */), intArrayOf(1,1,1,1,1 /* 11 */)).contentToString() == "[1, 1, 0, 1, 0, 1, 0]"
a = a && addNegabinary(intArrayOf(1,1 /* -1 */), intArrayOf(1,1 /* -1 */)).contentToString() == "[1, 0]"
println(if(a) "SUCCESS" else "FAIL")
}
| 0 | Java | 0 | 2 | cb8e6f7e30563e7ced7c3a253cb8e8bbe2bf19dd | 2,535 | codility | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem1444/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem1444
/**
* LeetCode page: [1444. Number of Ways of Cutting a Pizza](https://leetcode.com/problems/number-of-ways-of-cutting-a-pizza/);
*/
class Solution {
private val mod = 1_000_000_007
/* Complexity:
* Time O(kMN(M+N)) and Space O(MN) where M and N are the number of rows and columns;
*/
fun ways(pizza: Array<String>, k: Int): Int {
// suffixesAppleCount[r][c] ::= the number of apples on pizza[r until numRows][c until numColumns]
val suffixesAppleCount = suffixesAppleCount(pizza)
val noEnoughApples = suffixesAppleCount[0][0] < k
if (noEnoughApples) return 0
var currentPieces = 1
// subResults[r][c] ::= ways(pizza[r until numRows][c until numColumns], currentPieces)
var subResults = subResultsForSinglePiece(pizza, suffixesAppleCount)
while (currentPieces < k) {
subResults = subResultsForOneMorePieces(currentPieces, subResults, suffixesAppleCount)
currentPieces++
}
return subResults[0][0].toInt()
}
private fun suffixesAppleCount(pizza: Array<String>): Array<IntArray> {
val numRows = pizza.size
val numColumns = pizza[0].length
val suffixesAppleCount = Array(numRows + 1) { IntArray(numColumns + 1) }
for (row in numRows - 1 downTo 0) {
for (column in numColumns - 1 downTo 0) {
val cellValue = pizza[row][column]
val cellCount = if (isApple(cellValue)) 1 else 0
suffixesAppleCount[row][column] = cellCount +
suffixesAppleCount[row + 1][column] +
suffixesAppleCount[row][column + 1] -
suffixesAppleCount[row + 1][column + 1]
}
}
return suffixesAppleCount
}
private fun isApple(value: Char): Boolean = value == 'A'
private fun subResultsForSinglePiece(pizza: Array<String>, suffixAppleCounts: Array<IntArray>): Array<LongArray> {
val numRows = pizza.size
val numColumns = pizza[0].length
val subResults = Array(numRows) { LongArray (numColumns) }
for (row in numRows - 1 downTo 0) {
for (column in numColumns - 1 downTo 0) {
val isValidPiece = suffixAppleCounts[row][column] > 0
subResults[row][column] = if (isValidPiece) 1 else 0
}
}
return subResults
}
private fun subResultsForOneMorePieces(
currentPieces: Int,
currentResults: Array<LongArray>,
suffixAppleCounts: Array<IntArray>
): Array<LongArray> {
val numRows = currentResults.size
val numColumns = currentResults[0].size
val newPieces = currentPieces + 1
val newResult = Array(numRows) { LongArray(numColumns) }
for (row in numRows - 1 downTo 0) {
for (column in numColumns - 1 downTo 0) {
val noEnoughApples = suffixAppleCounts[row][column] < newPieces
if (noEnoughApples) continue
var numCuttingWays = 0L
// Examine all possible horizontal cuts
for (rowCut in row until numRows - 1) {
val isValidCut =
suffixAppleCounts[row][column] - suffixAppleCounts[rowCut + 1][column] > 0
if (isValidCut) {
numCuttingWays += currentResults[rowCut + 1][column]
}
}
// Examine all possible vertical cuts
for (columnCut in column until numColumns - 1) {
val isValidCut =
suffixAppleCounts[row][column] - suffixAppleCounts[row][columnCut + 1] > 0
if (isValidCut) {
numCuttingWays += currentResults[row][columnCut + 1]
}
}
newResult[row][column] = numCuttingWays % mod
}
}
return newResult
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 4,039 | hj-leetcode-kotlin | Apache License 2.0 |
src/main/java/com/barneyb/aoc/aoc2022/day07/NoSpaceLeftOnDevice.kt | barneyb | 553,291,150 | false | {"Kotlin": 184395, "Java": 104225, "HTML": 6307, "JavaScript": 5601, "Shell": 3219, "CSS": 1020} | package com.barneyb.aoc.aoc2022.day07
import com.barneyb.aoc.util.Solver
import com.barneyb.aoc.util.toInt
import com.barneyb.aoc.util.toSlice
import java.util.*
fun main() {
Solver.benchmark(
::parse,
::partOne,
::partTwo,
)
}
internal fun parse(input: String): IntArray {
val list = IntArray(200) // tee hee
var idx = 0
input.toSlice().trim().lines().let { lines ->
val levels = IntArray(10) // tee hee
var depth = -1
for (l in lines) {
if (l[0] == '$') { // $
if (l[2] == 'c') { // $ cd
if (l[5] == '.') { // $ cd ..
list[idx++] = levels[depth--]
} else { // $ cd <dir>
levels[++depth] = 0
}
}
} else if (l[0] != 'd') { // <size> <file>
val size = l.take(l.indexOf(' ')).toInt()
for (i in 0..depth) {
levels[i] += size
}
} // dir <dir>
}
while (depth >= 0) {
list[idx++] = levels[depth--]
}
}
Arrays.sort(list, 0, idx)
return list.copyOfRange(0, idx)
}
internal fun partOne(sizes: IntArray): Int {
var sum = 0
for (s in sizes) {
if (s > 100_000) break
sum += s
}
return sum
}
internal fun partTwo(sizes: IntArray): Int {
val needed = 30_000_000 - (70_000_000 - sizes.last())
var lo = 0
var hi = sizes.size - 1
var mid: Int
while (lo < hi) {
mid = (lo + hi) / 2
if (sizes[mid] < needed) lo = mid + 1
else if (sizes[mid] > needed) hi = mid - 1
else return needed
}
return sizes[lo]
}
| 0 | Kotlin | 0 | 0 | 8b5956164ff0be79a27f68ef09a9e7171cc91995 | 1,742 | aoc-2022 | MIT License |
src/Day2/Day02.kt | lukeqwas | 573,403,156 | false | null | package Day2
import readInput
import java.lang.IllegalArgumentException
val ROCK_POINTS = 1
val PAPER_POINTS = 2
val SCISSORS_POINTS = 3
fun main() {
val testInput = readInput("Day2/Day02")
var totalPoints = 0L
val rockNode = Node("A", null, null)
val paperNode = Node("B", rockNode, null)
val scissorsNode = Node("C", paperNode, rockNode)
paperNode.next = scissorsNode
rockNode.next = paperNode
rockNode.prev = scissorsNode
for(input in testInput) {
val opponentChoice = input.get(0).toString()
val myChoice = input.get(2).toString()
// find their node and then based on that do a tie win or loss depeneding on myChoice
val theirNode = findNode(opponentChoice, rockNode)
val myNode = findCorrespondingNode(theirNode, myChoice)
// val myNode = findNode(myChoice, rockNode)
totalPoints += calculcatePoints(myNode, opponentChoice)
}
println(totalPoints)
}
fun calculcatePoints(yourChoice: Node, opponentChoice: String): Int {
var bonusPoints = 0
if(yourChoice.prev?.value.equals(opponentChoice)){ // if you won
bonusPoints = 6
} else if(yourChoice.value == opponentChoice){
bonusPoints = 3
}
return getChoicePoints(yourChoice.value) + bonusPoints
}
fun getChoicePoints(choice: String): Int {
return when(choice) {
"A" -> ROCK_POINTS
"B" -> PAPER_POINTS
"C" -> SCISSORS_POINTS
else -> 0
}
}
class Node(val value: String, var prev: Node?, var next: Node?){}
fun findNode(yourChoice: String, head: Node): Node {
var headNode = head
val normalizedChoice = (yourChoice)
var timeout = 3
while(timeout > 0) {
if (normalizedChoice == headNode.value){
return headNode
}
headNode = headNode.next!!
timeout--
}
throw IllegalArgumentException("No node found for: ${yourChoice} -> ${normalizedChoice}")
}
fun findCorrespondingNode(theirNode: Node, myChoice: String): Node {
return when(myChoice) {
"X" -> theirNode.prev!!
"Y" -> theirNode
"Z" -> theirNode.next!!
else -> throw IllegalArgumentException("No node found for theirNode:${theirNode.value} and myChoice: ${myChoice}")
}
}
| 0 | Kotlin | 0 | 0 | 6174a8215f8d4dc6d33fce6f8300a4a8999d5431 | 2,264 | aoc-kotlin-2022 | Apache License 2.0 |
src/Day03.kt | zsmb13 | 572,719,881 | false | {"Kotlin": 32865} | fun main() {
fun Char.toPriority(): Int {
return when (this) {
in 'a'..'z' -> this - 'a' + 1
in 'A'..'Z' -> this - 'A' + 27
else -> error("Invalid char $this")
}
}
fun part1(input: List<String>): Int {
return input.sumOf { line ->
val first = line.substring(0, line.length / 2)
val second = line.substring(line.length / 2)
first.toSet()
.intersect(second.toSet())
.first()
.toPriority()
}
}
fun part2(input: List<String>): Int {
return input.chunked(3)
.sumOf { (elf1, elf2, elf3) ->
elf1.toSet()
.intersect(elf2.toSet())
.intersect(elf3.toSet())
.first()
.toPriority()
}
}
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 | 6 | 32f79b3998d4dfeb4d5ea59f1f7f40f7bf0c1f35 | 1,086 | advent-of-code-2022 | Apache License 2.0 |
2021/src/day03/Solution.kt | vadimsemenov | 437,677,116 | false | {"Kotlin": 56211, "Rust": 37295} | package day03
import java.nio.file.Files
import java.nio.file.Paths
fun main() {
fun part1(numbers: List<String>): Int {
val count = IntArray(numbers[0].length)
for (num in numbers) {
for ((index, bit) in num.withIndex()) {
count[index] += if (bit == '1') 1 else 0
}
}
val gamma = count
.map { if (it + it > numbers.size) 1 else 0 }
.joinToString("") { it.toString() }
.toInt(2)
val epsilon = count
.map { if (it + it > numbers.size) 0 else 1 }
.joinToString("") { it.toString() }
.toInt(2)
return gamma * epsilon
}
fun part2(report: List<String>): Int {
tailrec fun filter(list: List<String>, position: Int, predicate: (char: Char, mostCommon: Char) -> Boolean): String {
if (list.size == 1) return list.first()
val sum = list.sumOf { it[position].code - '0'.code }
val mostCommon = if (sum + sum >= list.size) '1' else '0'
return filter(
list.filter {
predicate(it[position], mostCommon)
},
position + 1,
predicate
)
}
val oxygenGeneratorRating = filter(report, 0) { char, mostCommon ->
char == mostCommon
}.toInt(2)
val co2ScrubberRating = filter(report, 0) { char, mostCommon ->
char != mostCommon
}.toInt(2)
return oxygenGeneratorRating * co2ScrubberRating
}
check(part1(readInput("test-input.txt")) == 198)
check(part2(readInput("test-input.txt")) == 230)
println(part1(readInput("input.txt")))
println(part2(readInput("input.txt")))
}
private fun readInput(s: String): List<String> {
return Files.newBufferedReader(Paths.get("src/day03/$s")).readLines().filterNot { it.isBlank() }.also { list ->
check(list.all { it.length == list[0].length })
}
} | 0 | Kotlin | 0 | 0 | 8f31d39d1a94c862f88278f22430e620b424bd68 | 1,776 | advent-of-code | Apache License 2.0 |
src/Day08.kt | Kbzinho-66 | 572,299,619 | false | {"Kotlin": 34500} | private typealias Forest = List<List<Int>>
private fun List<String>.toForest() = this.map { row -> row.map { it.digitToInt() } }
private fun isVisible(forest: Forest, row: Int, col: Int): Boolean {
// Árvores nas bordas são visíveis
if (row == 0 || row == forest.size - 1 || col == 0 || col == forest[row].size - 1) return true
val tree = forest[row][col]
var visibleFromLeft = true
var visibleFromRight = true
var visibleFromTop = true
var visibleFromBottom = true
// Primeiro verificar se tem alguma árvore maior na linha
var i = 0
while(i < forest[row].size) {
when {
visibleFromLeft && i < col -> if (forest[row][i] >= tree) visibleFromLeft = false
visibleFromRight && i > col -> if (forest[row][i] >= tree) visibleFromRight = false
}
i++
}
// Depois verificar a coluna
i = 0
while (i < forest.size) {
when {
visibleFromTop && i < row -> if (forest[i][col] >= tree) visibleFromTop = false
visibleFromBottom && i > row -> if (forest[i][col] >= tree) visibleFromBottom = false
}
i++
}
return (visibleFromTop || visibleFromRight || visibleFromBottom || visibleFromLeft)
}
private fun scenicScore(forest: Forest, row: Int, col: Int): Int {
if (row == 0 || row == forest.size - 1 || col == 0 || col == forest[row].size - 1) return 0
val tree = forest[row][col]
var viewingDistanceUp = 0
var viewingDistanceDown = 0
var viewingDistanceLeft = 0
var viewingDistanceRight = 0
for (i in row - 1 downTo 0) {
viewingDistanceUp++
if (forest[i][col] >= tree) break
}
for (i in row + 1 until forest.size) {
viewingDistanceDown++
if (forest[i][col] >= tree) break
}
for (i in col - 1 downTo 0) {
viewingDistanceLeft++
if (forest[row][i] >= tree) break
}
for (i in col + 1 until forest[row].size) {
viewingDistanceRight++
if (forest[row][i] >= tree) break
}
return viewingDistanceUp * viewingDistanceLeft * viewingDistanceDown * viewingDistanceRight
}
fun main() {
fun part1(forest: Forest): Int {
var total = 0
for (row in forest.indices) {
for (col in forest[row].indices) {
if ( isVisible(forest, row, col) ) {
total += 1
}
}
}
return total
}
fun part2(forest: Forest): Int {
var maxArea = 0
for (row in forest.indices) {
for (col in forest[row].indices) {
val score = scenicScore(forest, row, col)
if (score > maxArea) {
maxArea = score
}
}
}
return maxArea
}
// Testar os casos básicos
val testInput = readInput("../inputs/Day08_test").toForest()
sanityCheck(part1(testInput), 21)
sanityCheck(part2(testInput), 8)
val input = readInput("../inputs/Day08").toForest()
println("Parte 1 = ${part1(input)}")
println("Parte 2 = ${part2(input)}")
} | 0 | Kotlin | 0 | 0 | e7ce3ba9b56c44aa4404229b94a422fc62ca2a2b | 3,125 | advent_of_code_2022_kotlin | Apache License 2.0 |
year2022/src/main/kotlin/net/olegg/aoc/year2022/day18/Day18.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2022.day18
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.Vector3D
import net.olegg.aoc.utils.parseInts
import net.olegg.aoc.year2022.DayOf2022
/**
* See [Year 2022, Day 18](https://adventofcode.com/2022/day/18)
*/
object Day18 : DayOf2022(18) {
private val DIRS = listOf(
Vector3D(1, 0, 0),
Vector3D(-1, 0, 0),
Vector3D(0, 1, 0),
Vector3D(0, -1, 0),
Vector3D(0, 0, 1),
Vector3D(0, 0, -1),
)
override fun first(): Any? {
val blocks = lines
.map { it.parseInts(",") }
.map { Vector3D(it[0], it[1], it[2]) }
.toSet()
return blocks.sumOf { block ->
DIRS.count { (block + it) !in blocks }
}
}
override fun second(): Any? {
val blocks = lines
.map { it.parseInts(",") }
.map { Vector3D(it[0], it[1], it[2]) }
.toSet()
val minBlock = Vector3D(
x = blocks.minOf { it.x } - 1,
y = blocks.minOf { it.y } - 1,
z = blocks.minOf { it.z } - 1,
)
val maxBlock = Vector3D(
x = blocks.maxOf { it.x } + 1,
y = blocks.maxOf { it.y } + 1,
z = blocks.maxOf { it.z } + 1,
)
val filled = mutableSetOf<Vector3D>()
val queue = ArrayDeque(listOf(minBlock))
while (queue.isNotEmpty()) {
val curr = queue.removeFirst()
if (curr in filled) {
continue
}
filled += curr
queue += DIRS
.map { it + curr }
.filter { it.x >= minBlock.x && it.y >= minBlock.y && it.z >= minBlock.z }
.filter { it.x <= maxBlock.x && it.y <= maxBlock.y && it.z <= maxBlock.z }
.filter { it !in filled }
.filter { it !in blocks }
}
return blocks.sumOf { block ->
DIRS.count { (block + it) in filled }
}
}
}
fun main() = SomeDay.mainify(Day18)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,798 | adventofcode | MIT License |
src/aoc2021/Day12.kt | dayanruben | 433,250,590 | false | {"Kotlin": 79134} | package aoc2021
import readInput
fun main() {
val (year, day) = "2021" to "Day12"
fun buildMap(input: List<String>): Map<String, Set<String>> {
val map = mutableMapOf<String, MutableSet<String>>()
input.forEach { line ->
val (a, b) = line.split("-")
map.getOrPut(a) { mutableSetOf() }.add(b)
map.getOrPut(b) { mutableSetOf() }.add(a)
}
return map
}
fun paths(
map: Map<String, Set<String>>,
origin: String,
target: String,
visited: MutableSet<String> = mutableSetOf(),
extraVisit: Boolean = false
): Int = when {
origin == target -> 1
else -> {
visited += origin
val sum = map[origin]!!.filter {
it !in visited || it == it.uppercase()
}.sumOf {
paths(map, it, target, visited.toMutableSet(), extraVisit)
}
val extraSum = if (extraVisit) {
map[origin]!!.filter {
it in visited && it == it.lowercase() && it !in setOf("start", "end")
}.sumOf {
paths(map, it, target, visited.toMutableSet(), false)
}
} else 0
visited -= origin
sum + extraSum
}
}
fun part1(input: List<String>) =
paths(buildMap(input), origin = "start", target = "end", extraVisit = false)
fun part2(input: List<String>) =
paths(buildMap(input), origin = "start", target = "end", extraVisit = true)
val testInput1 = readInput(name = "${day}_test1", year = year)
val testInput2 = readInput(name = "${day}_test2", year = year)
val testInput3 = readInput(name = "${day}_test3", year = year)
val input = readInput(name = day, year = year)
check(part1(testInput1) == 10)
check(part1(testInput2) == 19)
check(part1(testInput3) == 226)
println(part1(input))
check(part2(testInput1) == 36)
check(part2(testInput2) == 103)
check(part2(testInput3) == 3509)
println(part2(input))
} | 1 | Kotlin | 2 | 30 | df1f04b90e81fbb9078a30f528d52295689f7de7 | 2,089 | aoc-kotlin | Apache License 2.0 |
src/main/kotlin/days/Day15.kt | andilau | 429,557,457 | false | {"Kotlin": 103829} | package days
@AdventOfCodePuzzle(
name = "Science for Hungry People",
url = "https://adventofcode.com/2015/day/15",
date = Date(day = 15, year = 2015)
)
class Day15(input: List<String>) : Puzzle {
private val ingredients = input.map(Ingredient::from)
override fun partOne(): Int =
combinations(ingredients.size, 100)
.map { amounts -> makeCookie(ingredients, amounts) }
.maxOf(Cookie::score)
override fun partTwo(): Int =
combinations(ingredients.size, 100)
.map { amounts -> makeCookie(ingredients, amounts) }
.filter { cookie -> cookie.calories() == 500 }
.maxOf(Cookie::score)
private fun makeCookie(ingredients: List<Ingredient>, amounts: IntArray) =
amounts.withIndex()
.associate { amount -> ingredients[amount.index] to amount.value }
.let { Cookie(it) }
internal fun combinations(): Int = combinations(ingredients.size, 100).size
class Cookie(private val recipe: Map<Ingredient, Int>) {
fun score(): Int =
recipe.keys.sumOf { it.capacity * recipe[it]!! }.let { if (it > 0) it else 0 } *
recipe.keys.sumOf { it.durability * recipe[it]!! }.let { if (it > 0) it else 0 } *
recipe.keys.sumOf { it.flavor * recipe[it]!! }.let { if (it > 0) it else 0 } *
recipe.keys.sumOf { it.texture * recipe[it]!! }.let { if (it > 0) it else 0 }
fun calories() = recipe.keys.sumOf { it.calories * recipe[it]!! }
}
data class Ingredient(
val name: String,
val capacity: Int,
val durability: Int,
val flavor: Int,
val texture: Int,
val calories: Int
) {
companion object {
private val PATTERN =
Regex("""^(\w+): capacity (-?\d+), durability (-?\d+), flavor (-?\d+), texture (-?\d+), calories (\d+)""")
fun from(string: String): Ingredient =
PATTERN.matchEntire(string)?.destructured?.let { (name, capacity, durability, flavor, texture, calories) ->
Ingredient(
name,
capacity.toInt(),
durability.toInt(),
flavor.toInt(),
texture.toInt(),
calories.toInt()
)
} ?: error("Invalid format: $string")
}
}
} | 0 | Kotlin | 0 | 0 | 55932fb63d6a13a1aa8c8df127593d38b760a34c | 2,465 | advent-of-code-2015 | Creative Commons Zero v1.0 Universal |
src/practice1.kt | dustinlewis | 572,792,391 | false | {"Kotlin": 29162} | fun main() {
// Works
fun part1(input: List<String>): Int {
val result: Pair<Int, String> = input.fold(Pair(0, "")) {
acc, el -> Pair(if (el > acc.second) acc.first + 1 else acc.first, el)
}
return result.first
}
// one short
// fun part1(input: List<String>): Int {
// val result: Int = input.foldIndexed(0) {
// index, acc, el -> if (index > 0 && el > input[index - 1]) acc + 1 else acc
// }
// return result
// }
// one short
// fun part1(input: List<String>): Int {
// val result: Int = input.zipWithNext().fold(0) {
// acc, el -> if (el.second > el.first) acc + 1 else acc
// }
// return result
// }
fun part2(input: List<String>): Int {
return input.windowed(3, 1) { win -> win.sumOf { it.toInt() } }
.zipWithNext().fold(0) { acc, el -> if (el.second > el.first) acc + 1 else acc }
}
// test if implementation meets criteria from the description, like:
//val testInput = readInput("Day01_test")
//check(part1(testInput) == 1)
val input = readInput("practice1")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | c8d1c9f374c2013c49b449f41c7ee60c64ef6cff | 1,206 | aoc-2022-in-kotlin | Apache License 2.0 |
kotlin/largest-series-product/src/main/kotlin/Series.kt | ikr | 147,076,927 | false | {"C++": 22451113, "Kotlin": 136005, "CMake": 90716, "Java": 30028} | data class Series(val s: String) {
init {
require(Regex("^[0-9]*$") matches s)
}
fun getLargestProduct(length: Int): Int {
require(length <= s.length)
val subSeqs = s.split("0").filter {it != ""}
val subSolutions = subSeqs.map {largestProductOfNonZeroes(digits(it), length)}
return subSolutions.max() ?: if (length == 0) 1 else 0
}
}
private fun largestProductOfNonZeroes(ds: List<Int>, length: Int): Int {
if (ds.size < length) return 0
var result = product(ds.take(length))
var runningProd = result
for (i in length..(ds.size - 1)) {
runningProd = (runningProd / (ds[i - length])) * ds[i]
if (runningProd > result) {
result = runningProd
}
}
return result
}
private fun digits(s: String) =
s.map {it.toString().toInt()}
private fun product(xs: List<Int>): Int =
xs.fold(1, {m, x -> m * x})
| 0 | C++ | 0 | 0 | 37f505476ae13dd003c1de24b5113a0d7e94aaf2 | 925 | exercism | MIT License |
leetcode/src/array/Offer11.kt | zhangweizhe | 387,808,774 | false | null | package array
fun main() {
// 剑指 Offer 11. 旋转数组的最小数字
// https://leetcode-cn.com/problems/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-lcof/
// println(minArray3(intArrayOf(3,1,1)))
// println(maxArray(intArrayOf(4,5,6,1,2,3)))
// println(maxArray(intArrayOf(1,2,3,4,5,6)))
// println(maxArray(intArrayOf(3,3,3,3,3,3)))
println(maxArray(intArrayOf(6,5,4,3,2,1)))
}
/**
* 暴力解法,直接遍历整个数据,找到最小值
*/
fun minArray(numbers: IntArray): Int {
var min = Int.MAX_VALUE
for (i in numbers) {
if (i < min) {
min = i
}
}
return min
}
/**
* 利用递增旋转数组的特性,
* 如果 numbers[i] < numbers[i-1],则 numbers[i]就是最小值;
* 如果 numbers[i] < numbers[i-1] 一直不成立,则是递增数组,第一个元素就是最小值
*/
fun minArray1(numbers: IntArray): Int {
for (i in 1 until numbers.size) {
if (numbers[i] < numbers[i-1]) {
return numbers[i]
}
}
return numbers[0]
}
/**
* 二分法
* 旋转后的数组分为左边有序数组和右边有序数组
*/
fun minArray2(numbers: IntArray): Int {
var left = 0
var right = numbers.size - 1
var mid = (left + right)/2
while (left < right) {
if (numbers[mid] > numbers[right]) {
// 旋转点在右半数组,舍弃左半数组,mid 也是可以舍弃的,因为它肯定不是最小的
left = mid+1
}else if (numbers[mid] < numbers[right]) {
// 旋转点在左半数组,舍弃右半数组,mid 不能舍弃,因为它可能是最小的
right = mid
}else {
// right 一点点往左边移动
right--
}
mid = (left + right)/2
}
return numbers[left]
}
/**
* 用 right 和 mid 比较,而不是 left 和 mid 比较,
* 是考虑当 mid > left,无法确定 mid 在哪个排序数组里面
* 比如 left = 0, mid = 2, right = 4
* 对于 1,2,3,4,5 这个数组,旋转点在0,nums[mid] > nums[left],mid 在右边排序数组(只有右数组)
* 对于 3,4,5,1,2 这个数组,旋转点在3,nums[mid] > nums[left],mid 在左边排序数组
*/
fun minArray3(numbers: IntArray): Int {
// 重点:寻找旋转点(或者说两个有序数组的交界点)
var left = 0
var right = numbers.size - 1
var mid = (left + right)/2
while (left < right) {
if (numbers[mid] > numbers[right]) {
// left ~ mid 是有序的,交界点在右边数组
// numbers[mid] 大于 numbers[right],所以 numbers[mid] 肯定不会是最小值,可以舍弃,所以 left = mid + 1
left = mid + 1
}else if (numbers[mid] < numbers[right]) {
// mid ~ right 是有序的,交界点在左边数组
// numbers[mid] 可能是最小的,所以不能舍弃
right = mid
}else {
// numbers[mid] == numbers[right],right 只能一点点往左边移动
right--
}
mid = (left + right)/2
}
return numbers[left]
}
fun maxArray(numbers: IntArray): Int {
var left = 0
var right = numbers.size - 1
var mid = (left + right) / 2
while (left < right) {
if (numbers[mid] > numbers[left]) {
// left~mid 是有序的,交界点在右边数组
left = mid
}else if (numbers[mid] < numbers[left]) {
// mid~right 是有序的,交界点在左边数组
right = mid - 1
}else {
left++
}
mid = (left + right)/2
}
return numbers[right]
} | 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 3,671 | kotlin-study | MIT License |
22.kt | pin2t | 725,922,444 | false | {"Kotlin": 48856, "Go": 48364, "Shell": 54} | import kotlin.math.max
import kotlin.math.min
val bricks = ArrayList<Brick>()
data class Brick (val s: Triple<Int, Int, Int>, val e: Triple<Int, Int, Int>) {
fun intersect(other: Brick): Boolean {
return max(s.first, other.s.first) <= min(e.first, other.e.first) &&
max(s.second, other.s.second) <= min(e.second, other.e.second) &&
max(s.third, other.s.third) <= min(e.third, other.e.third)
}
fun canFall(bricks: ArrayList<Brick>): Boolean = bricks.all { it == this || !it.intersect(fall) } && s.third > 1
val canFall: Boolean get() = canFall(bricks)
val fall: Brick get() = Brick(Triple(s.first, s.second, s.third - 1), Triple(e.first, e.second, e.third - 1))
}
val number = Regex("-?\\d+")
fun main() {
while (true) {
val line = readlnOrNull() ?: break
val numbers = number.findAll(line).map { it.value.toInt() }.toList()
bricks.add(Brick(Triple(numbers[0], numbers[1], numbers[2]),
Triple(numbers[3], numbers[4], numbers[5])))
}
bricks.sortBy { it.s.third }
for (i in 0..<bricks.size) {
while (bricks[i].canFall) bricks[i] = bricks[i].fall
}
var result1 = 0; var result2 = 0
for (i in 0..<bricks.size) {
val save = bricks[i]
bricks[i] = Brick(Triple(-1, -1, -1), Triple(-1, -1, -1))
if (!bricks.subList(i + 1, bricks.size).any { it.canFall }) {
result1++
} else {
val fall = ArrayList(bricks)
for (j in (i + 1)..<fall.size) {
if (fall[j].canFall(fall)) {
result2++
while (fall[j].canFall(fall)) fall[j] = fall[j].fall
}
}
}
bricks[i] = save
}
println(listOf(result1, result2))
}
| 0 | Kotlin | 1 | 0 | 7575ab03cdadcd581acabd0b603a6f999119bbb6 | 1,795 | aoc2023 | MIT License |
src/main/kotlin/day5/HydroVents.kt | Arch-vile | 433,381,878 | false | {"Kotlin": 57129} | package day5
import utils.Line
import utils.Point
import utils.Matrix
import utils.pointsInLine
import utils.read
fun main() {
solve()
.let { println(it) }
}
fun solve(): List<Int> {
val lines = read("./src/main/resources/day5Input.txt")
.map { it.split(" ") }
.map { line ->
val firsCoord = line[0].split(",") // ['5','6']
val secondCoord = line[2].split(",")
Line(
Point(firsCoord[0].toLong(), firsCoord[1].toLong()),
Point(secondCoord[0].toLong(), secondCoord[1].toLong()),
)
}
val onlyStraightLines = lines
.filter { it.start.x == it.end.x || it.start.y == it.end.y }
.flatMap { pointsInLine(it) }
val alsoDiagonalLines = lines
.flatMap { pointsInLine(it) }
return listOf(
countCrossing(onlyStraightLines),
countCrossing(alsoDiagonalLines))
}
private fun countCrossing(allPointsInLines: List<Point>): Int {
val seaFloor = Matrix(1000, 1000) { x, y -> 0 }
allPointsInLines.forEach { point ->
seaFloor.replace(point.x.toInt(), point.y.toInt()) { entry -> entry.value + 1 }
}
return seaFloor.findAll { it.value >= 2 }.count()
}
| 0 | Kotlin | 0 | 0 | 4cdafaa524a863e28067beb668a3f3e06edcef96 | 1,239 | adventOfCode2021 | Apache License 2.0 |
src/day03/Day03.kt | TheRishka | 573,352,778 | false | {"Kotlin": 29720} | package day03
import readInput
fun main() {
val scoringMap = buildMap {
var scoreChar = 'a'
var score = 1
while (scoreChar <= 'z') {
put(scoreChar, score)
++score
++scoreChar
}
scoreChar = 'A'
while (scoreChar <= 'Z') {
put(scoreChar, score)
++score
++scoreChar
}
}
fun calculateScore(inputMap: Map<Char, Int>) = inputMap.map {
it.value * scoringMap[it.key]!!
}.fold(0) { total, scoring ->
total + scoring
}
fun part1(input: List<String>): Int {
//jNNBMTNzvT |MIDDLE| qhQLhQLMQL
var duplicateScore = 0
input.forEach { rucksackContents ->
val firstHalfValuesCountMap = mutableMapOf<Char, Int>()
val duplicatesCountMap = mutableMapOf<Char, Int>()
val firstHalf = rucksackContents.take(rucksackContents.length / 2)
val secondHalf = rucksackContents.takeLast(rucksackContents.length / 2)
firstHalf.forEach {
firstHalfValuesCountMap[it] = firstHalfValuesCountMap.getOrDefault(it, 0) + 1
}
secondHalf.forEach {
if (firstHalfValuesCountMap.getOrDefault(it, 0) >= 1) {
duplicatesCountMap[it] = 1
firstHalfValuesCountMap[it] = firstHalfValuesCountMap[it]!! - 1
}
}
duplicateScore += calculateScore(duplicatesCountMap)
}
return duplicateScore
}
fun fillCounterMap(input: String): Map<Char, Int> {
val counterMap = mutableMapOf<Char, Int>()
return counterMap.apply {
input.forEach {
put(it, getOrDefault(it, 0) + 1)
}
}
}
fun part2(input: List<String>): Int {
/*
jNNBMTNzvTqhQLhQLMQL
VCwnVRCGHHJTdsLtrdhrGdsq
wFJZTbRcnJCbpwpFccZCBfBvPzfpgfgzzWvjSzNP
*/
val slicedInput = input.chunked(3)
var totalBadgeScore = 0
slicedInput.forEach { elvesGroupInput ->
val firstElf = fillCounterMap(elvesGroupInput[0])
val secondElf = fillCounterMap(elvesGroupInput[1])
val thirdElf = fillCounterMap(elvesGroupInput[2])
firstElf.forEach {
when {
secondElf.containsKey(it.key) && thirdElf.containsKey(it.key) -> {
totalBadgeScore += scoringMap[it.key]!!
}
}
}
}
return totalBadgeScore
}
val input = readInput("day03/Day03")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 1 | 54c6abe68c4867207b37e9798e1fdcf264e38658 | 2,686 | AOC2022-Kotlin | Apache License 2.0 |
src/day04/Day04.kt | jacobprudhomme | 573,057,457 | false | {"Kotlin": 29699} | import java.io.File
fun main() {
fun readInput(name: String) = File("src/day04", name)
.readLines()
fun processInput(line: String): Pair<Pair<Int, Int>, Pair<Int, Int>> {
val (range1, range2, _) = line.split(",").map { range ->
range.split("-").map { it.toInt() }.let { (start, end, _) ->
Pair(start, end)
}
}
return Pair(range1, range2)
}
fun sign(n: Int): Int =
if (n > 0) { 1 }
else if (n < 0) { -1 }
else { 0 }
fun Pair<Int, Int>.contains(otherRange: Pair<Int, Int>): Boolean {
val startDiff = this.first - otherRange.first
val endDiff = this.second - otherRange.second
return (sign(startDiff) >= 0) and (sign(endDiff) <= 0)
}
fun Pair<Int, Int>.overlaps(otherRange: Pair<Int, Int>): Boolean =
(this.first <= otherRange.second) and (otherRange.first <= this.second)
fun part1(input: List<String>): Int {
var count = 0
for (line in input) {
val (range1, range2) = processInput(line)
if (range1.contains(range2) or range2.contains(range1)) {
++count
}
}
return count
}
fun part2(input: List<String>): Int {
var count = 0
for (line in input) {
val (range1, range2) = processInput(line)
if (range1.overlaps(range2)) {
++count
}
}
return count
}
val input = readInput("input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 9c2b080aea8b069d2796d58bcfc90ce4651c215b | 1,604 | advent-of-code-2022 | Apache License 2.0 |
y2015/src/main/kotlin/adventofcode/y2015/Day09.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2015
import adventofcode.io.AdventSolution
import adventofcode.util.collections.permutations
object Day09 : AdventSolution(2015, 9, "All in a Single Night") {
override fun solvePartOne(input: String) = tryAllRoutes(input).minOrNull().toString()
override fun solvePartTwo(input: String) = tryAllRoutes(input).maxOrNull().toString()
private fun tryAllRoutes(input: String): Sequence<Int> {
val distanceMap = parseInput(input)
val locations = distanceMap.keys.flatMap { listOf(it.first, it.second) }.toSet().toList()
val distances = buildDistanceMatrix(locations, distanceMap)
return routes(locations, distances)
}
private fun buildDistanceMatrix(locations: List<String>, distanceMap: Map<Pair<String, String>, Int>) =
locations.map { start ->
locations.map { end ->
distanceMap[start to end]
?: distanceMap[end to start]
?: 0
}
}
private fun routes(locations: List<String>, distanceTable: List<List<Int>>) =
locations.indices.permutations()
.map { it.zipWithNext { a, b -> distanceTable[a][b] }.sum() }
private fun parseInput(distances: String) = distances.lineSequence()
.mapNotNull { Regex("([a-zA-Z]+) to ([a-zA-Z]+) = (\\d+)").matchEntire(it) }
.map { it.destructured }
.map { (start, end, distance) -> start to end to distance.toInt() }
.toMap()
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,338 | advent-of-code | MIT License |
src/main/kotlin/d22/d22.kt | LaurentJeanpierre1 | 573,454,829 | false | {"Kotlin": 118105} | package d22
import readInput
enum class Direction(val x: Int, val y:Int) {Right(1,0), Down(0,1), Left(-1,0), Up(0,-1);
fun turnRight() : Direction = values()[(ordinal+1) % 4]
fun turnLeft() : Direction = values()[(ordinal+3) % 4]
}
fun part1(input: List<String>): Int {
val (board, instructions) = readPuzzle(input)
var lg = 0
var col = board[0].indexOf('.')
var facing = Direction.Right
val forward = Regex("\\d+").findAll(instructions).map { it.value.toInt() }.iterator()
val turn = Regex("[RL]").findAll(instructions).map { it.value }.iterator()
while (forward.hasNext()) {
val distance = forward.next()
print("${lg+1},${col+1} : $distance to $facing")
println()
for(count in 1..distance) {
var nexCol = col + facing.x
var nextLg = lg + facing.y
if (facing==Direction.Left && (nexCol<0 || board[nextLg][nexCol] == ' ')) nexCol = board[lg].size-1 // white spaces not included
if (facing==Direction.Right && (nexCol>=board[nextLg].size)) nexCol = board[lg].indexOfFirst { it=='.' || it=='#' }
if (facing == Direction.Up && (nextLg < 0 || board[nextLg][col]==' ')) {
nextLg = lg
while (nextLg<board.size-1 && col<board[nextLg+1].size && board[nextLg+1][col] != ' ') {
nextLg++
}
}
if (facing == Direction.Down && (nextLg>=board.size || col>=board[nextLg].size || board[nextLg][nexCol] == ' ')) {
nextLg = lg
while (nextLg>0 && col<board[nextLg-1].size && board[nextLg-1][col] != ' ') {
nextLg--
}
}
if (board[nextLg][nexCol] == '#') break
// else
col = nexCol
lg = nextLg
}
if (turn.hasNext())
facing = if (turn.next() == "R")
facing.turnRight()
else
facing.turnLeft()
} // while forward
return 1000*(lg+1) + 4*(col+1) + facing.ordinal
}
// < 17384
data class WormHole(val col: Int, val lg: Int, val facing: Direction)
fun part2(input: List<String>, wormHoles: Map<WormHole,WormHole>): Int {
val (board, instructions) = readPuzzle(input)
var lg = 0
var col = board[0].indexOf('.')
var facing = Direction.Right
val forward = Regex("\\d+").findAll(instructions).map { it.value.toInt() }.iterator()
val turn = Regex("[RL]").findAll(instructions).map { it.value }.iterator()
while (forward.hasNext()) {
val distance = forward.next()
print("${lg+1},${col+1} : $distance to $facing")
println()
for(count in 1..distance) {
var nexCol = col + facing.x
var nextLg = lg + facing.y
val exit = wormHoles[WormHole(nexCol, nextLg, facing)]
if (exit != null) {
nextLg = exit.lg
nexCol = exit.col
}
if (board[nextLg][nexCol] == '#') break
// else
col = nexCol
lg = nextLg
if (exit != null)
facing = exit.facing
}
if (turn.hasNext())
facing = if (turn.next() == "R")
facing.turnRight()
else
facing.turnLeft()
} // while forward
return 1000*(lg+1) + 4*(col+1) + facing.ordinal
}
fun readPuzzle(input : List<String>) : Pair<List<CharArray>, String> {
val board = mutableListOf<CharArray>()
var instructions = ""
for (line in input) {
if (line.isBlank()) continue
if (line[0] in '0'..'9')
instructions = line
else
board.add(line.toCharArray())
}
return Pair(board, instructions)
}
fun main() {
//val input = readInput("d22/test"); val wormHoles = testWormholes()
val input = readInput("d22/input1"); val wormHoles = puzzleWormholes()
//println(part1(input))
println(part2(input, wormHoles))
}
fun puzzleWormholes(): Map<WormHole, WormHole> {
/*
FFEE
FFEE
DD
DD
CCBB
CCBB
AA
AA
*/
val res = mutableMapOf<WormHole, WormHole>()
repeat(50) {
//F,U -> A,R
res[WormHole(50 + it, -1, Direction.Up)] = WormHole(0, 150 + it, Direction.Right)
//E,U -> A,U
res[WormHole(100 + it, -1, Direction.Up)] = WormHole(0 + it, 199, Direction.Up)
//E,R -> B,L
res[WormHole(150, it, Direction.Right)] = WormHole(99, 149 - it, Direction.Left)
//E,D -> D,L
res[WormHole(100 + it, 50, Direction.Down)] = WormHole(99, 50 + it, Direction.Left)
//D,R -> E,U
res[WormHole(100, 50 + it, Direction.Right)] = WormHole(100 + it, 49, Direction.Up)
//B,R -> E,L
res[WormHole(100, 149 - it, Direction.Right)] = WormHole(149, it, Direction.Left)
//B,D -> A,L
res[WormHole(50 + it, 150, Direction.Down)] = WormHole(49, 150 + it, Direction.Left)
//A,R -> B,U
res[WormHole(50, 150 + it, Direction.Right)] = WormHole(50 + it, 149, Direction.Up)
//A,D -> E,D
res[WormHole(0 + it, 200, Direction.Down)] = WormHole(100 + it, 0, Direction.Down)
//A,L -> F,D
res[WormHole(-1, 150 + it, Direction.Left)] = WormHole(50 + it, 0, Direction.Down)
//C,L -> F,R
res[WormHole(-1, 100 + it, Direction.Left)] = WormHole(50, 49 - it, Direction.Right)
//C,U -> D,R
res[WormHole(0 + it, 99, Direction.Up)] = WormHole(50, 50 + it, Direction.Right)
//D,L -> C,D
res[WormHole(49, 50 + it, Direction.Left)] = WormHole(0 + it, 100, Direction.Down)
//F,L -> C,R
res[WormHole(49, 49 - it, Direction.Left)] = WormHole(0, 100 + it, Direction.Right)
}
return res
}
fun testWormholes(): Map<WormHole, WormHole> {
val res = mutableMapOf<WormHole, WormHole>()
repeat(4) {
// 1->2
res[WormHole(8+it,-1, Direction.Up)] = WormHole(3-it, 4, Direction.Down)
// 2->1
res[WormHole(3-it, 3, Direction.Up)] = WormHole(8+it,0, Direction.Down)
// 1->3
res[WormHole(7, it, Direction.Left)] = WormHole(4+it, 4, Direction.Down)
// 3->1
res[WormHole(4+it, 3, Direction.Up)] = WormHole(8, it, Direction.Right)
// 1->6
res[WormHole(12, it, Direction.Right)] = WormHole(15, 11-it, Direction.Left)
// 6->1
res[WormHole(16, 11-it, Direction.Right)] = WormHole(11, it, Direction.Left)
// 4->6
res[WormHole(12, 4+it, Direction.Right)] = WormHole(15 - it, 8, Direction.Down)
// 6->4
res[WormHole(15 - it, 7, Direction.Up)] = WormHole(11, 4+it, Direction.Left)
// 3->5
res[WormHole(4+it, 8, Direction.Down)] = WormHole(8, 11-it, Direction.Right)
// 5->3
res[WormHole(7, 11-it, Direction.Left)] = WormHole(4+it, 7, Direction.Up)
// 2->6 L-> U
res[WormHole(-1, 4+it, Direction.Left)] = WormHole(15 - it, 11, Direction.Up)
// 6->2
res[WormHole(15 - it, 12, Direction.Up)] = WormHole(0, 4+it, Direction.Right)
// 2->5 D->U
res[WormHole(it,8, Direction.Down)] = WormHole(11-it, 11, Direction.Up)
// 5->2
res[WormHole(11-it, 12, Direction.Down)] = WormHole(it,7, Direction.Up)
}
return res
}
| 0 | Kotlin | 0 | 0 | 5cf6b2142df6082ddd7d94f2dbde037f1fe0508f | 7,344 | aoc2022 | Creative Commons Zero v1.0 Universal |
src/Day03.kt | lbilger | 574,227,846 | false | {"Kotlin": 5366} | fun main() {
fun Char.priority() = if (isUpperCase()) this - 'A' + 27 else this - 'a' + 1
fun part1(input: List<String>): Int {
return input.map { it.chunked(it.length / 2) }
.map { it[0].toSet().intersect(it[1].toSet()).single() }
.sumOf { it.priority() }
}
fun part2(input: List<String>): Int {
return input.chunked(3)
.map {
it.map { it.toSet() }
.reduce { acc, chars -> acc.intersect(chars) }
.single()
}
.sumOf { it.priority() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
checkTestAnswer(part1(testInput), 157, part = 1)
checkTestAnswer(part2(testInput), 70, part = 2)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 40d94a4bb9621af822722d20675684555cbee877 | 903 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day09.kt | aneroid | 572,802,061 | false | {"Kotlin": 27313} | import kotlin.math.absoluteValue
import kotlin.math.sign
private data class Point(val x: Int, val y: Int) {
override fun toString() = "P($x, $y)"
}
class Day09(private val input: List<String>) {
private val steps = parseInput(input)
private fun Pair<Int, Int>.toPoint() = Point(first, second)
private fun Point.move(dir: Char, dist: Int = 1) =
when (dir) {
'R' -> x + dist to y
'L' -> x - dist to y
'U' -> x to y - dist
'D' -> x to y + dist
else -> throw IllegalArgumentException("Unknown direction: $dir")
}.toPoint()
private fun Point.follow(head: Point): Point =
if ((head.x - x).absoluteValue > 1 || (head.y - y).absoluteValue > 1)
Point(x + (head.x - x).sign, y + (head.y - y).sign)
else
this
private fun List<Point>.follow(actualHead: Point): List<Point> =
runningFold(actualHead) { nextHead, point ->
point.follow(nextHead)
}.drop(1)
fun partOne(): Int =
buildSet {
steps.fold(Point(0, 0) to Point(0, 0)) { (stepHead, stepTail), step ->
generateSequence(stepHead to stepTail) { (head, tail) ->
head.move(step.first)
.let { it to tail.follow(it) }
.also { add(it.second) }
}.drop(1).take(step.second).last()
}
}.size
fun genericSolver(tailKnots: Int): Int =
buildSet {
steps.fold(Point(0, 0) to List(tailKnots) { Point(0, 0) }) { (stepHead, stepKnots), step ->
generateSequence(stepHead to stepKnots) { (head, tails) ->
head.move(step.first)
.let { it to tails.follow(it) }
.also { add(it.second.last()) }
}.drop(1).take(step.second).last()
}
}.size
fun partTwo() = genericSolver(9)
private companion object {
fun parseInput(input: List<String>) =
input.map { it.substringBefore(' ').first() to it.substringAfter(' ').toInt() }
}
}
fun main() {
val testInput = readInput("Day09_test")
val testInputP2 = readInput("Day09_test_p2")
val input = readInput("Day09")
println("part One:")
assertThat(Day09(testInput).partOne()).isEqualTo(13)
println("actual: ${Day09(input).partOne()}\n")
// partOne with generic solver
assertThat(Day09(testInput).genericSolver(1)).isEqualTo(13)
println("original: ${Day09(input).genericSolver(1)}\n")
println("part Two:")
// uncomment when ready
assertThat(Day09(testInput).partTwo()).isEqualTo(1)
assertThat(Day09(testInputP2).partTwo()).isEqualTo(36)
println("actual: ${Day09(input).partTwo()}\n")
// 100 iterations of the testInput in part2 with 10 knots
val testInputP2_100 = testInputP2.flatMap { testInputP2 }
println("actual x100: ${Day09(testInputP2_100).partTwo()}")
// using 100 knots, because... why not?
println("100 knots test : ${Day09(testInput).genericSolver(99)}")
println("100 knots testP2: ${Day09(testInputP2).genericSolver(99)}")
println("100 knots actual: ${Day09(input).genericSolver(99)}")
// using 0 tail knots, doesn't work because I don't check for empty knotsList
// assertThat(Day09(testInput).genericSolver(0)).isEqualTo(20) // 20 unique Head positions in example
}
| 0 | Kotlin | 0 | 0 | cf4b2d8903e2fd5a4585d7dabbc379776c3b5fbd | 3,476 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/Day16.kt | iam-afk | 572,941,009 | false | {"Kotlin": 33272} | import kotlin.math.max
fun main() {
fun part1(input: List<String>): Int {
val tunnels = mutableMapOf<String, MutableList<String>>()
val rates = mutableMapOf<String, Int>()
val ids = mutableMapOf<String, Int>()
for ((id, line) in input.withIndex()) {
val t = line.split(" ", "=", "; ", ", ")
t.subList(10, t.size).toCollection(
tunnels.computeIfAbsent(t[1]) { mutableListOf() }
)
ids[t[1]] = id
rates.put(t[1], t[5].toInt())
}
data class S(val v: String, val opened: Long)
val d = Array(30 + 1) { HashMap<S, Int>() }
d[0].put(S("AA", 0), 0)
fun put(time: Int, valve: String, opened: Long, pressure: Int) {
val s = S(valve, opened)
d[time].compute(s) { _, current ->
if (current == null) pressure
else max(current, pressure)
}
}
for (t in 0 until 30) {
for ((s, r) in d[t]) {
val (v, m) = s
val rate = rates[v]!!
if (rate > 0 && m and (1L shl ids[v]!!) == 0L) {
put(t + 1, v, m + (1L shl ids[v]!!), r + (30 - t - 1) * rate)
}
for (u in tunnels.getOrDefault(v, emptyList())) {
put(t + 1, u, m, r)
}
}
}
return d[30].maxOf { it.value }
}
fun part2(input: List<String>): Int {
val tunnels = mutableMapOf<String, MutableList<String>>()
val rates = mutableMapOf<String, Int>()
val ids = mutableMapOf<String, Int>()
for ((id, line) in input.withIndex()) {
val t = line.split(" ", "=", "; ", ", ")
t.subList(10, t.size).toCollection(
tunnels.computeIfAbsent(t[1]) { mutableListOf() }
)
ids[t[1]] = id
rates.put(t[1], t[5].toInt())
}
data class S(val v: String, val e: String, val opened: Long)
val d = Array(26 + 1) { HashMap<S, Int>() }
d[0].put(S("AA", "AA", 0), 0)
var mx = 0
fun put(time: Int, myValve: String, elValve: String, opened: Long, pressure: Int) {
val s = S(myValve, elValve, opened)
val x = d[time].compute(s) { _, current ->
if (current == null) pressure
else max(current, pressure)
}
if (x!! > mx) {
mx = x
}
}
val all = rates.entries.fold(0L) { acc, entry -> if (entry.value > 0) acc + (1L shl ids[entry.key]!!) else acc }
for (t in 0 until 26) {
for ((s, r) in d[t]) {
val (v, e, m) = s
if (m == all) continue
val rv = rates[v]!!
val re = rates[e]!!
if (v == e) {
if (rv > 0 && m and (1L shl ids[v]!!) == 0L) {
for (u in tunnels.getOrDefault(e, emptyList())) {
put(t + 1, v, u, m + (1L shl ids[v]!!), r + (26 - t - 1) * rv)
}
}
} else {
if (rv > 0 && m and (1L shl ids[v]!!) == 0L && re > 0 && m and (1L shl ids[e]!!) == 0L) {
put(t + 1, v, e, m + (1L shl ids[v]!!) + (1L shl ids[e]!!), r + (26 - t - 1) * (rv + re))
} else if (rv > 0 && m and (1L shl ids[v]!!) == 0L) {
for (u in tunnels.getOrDefault(e, emptyList())) {
put(t + 1, v, u, m + (1L shl ids[v]!!), r + (26 - t - 1) * rv)
}
} else if (re > 0 && m and (1L shl ids[e]!!) == 0L) {
for (u in tunnels.getOrDefault(v, emptyList())) {
put(t + 1, u, e, m + (1L shl ids[e]!!), r + (26 - t - 1) * re)
}
}
}
for (uv in tunnels.getOrDefault(v, emptyList())) {
for (ue in tunnels.getOrDefault(e, emptyList())) {
put(t + 1, uv, ue, m, r)
}
}
}
d[t].clear()
}
return mx
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day16_test")
check(part1(testInput) == 1651)
check(part2(testInput) == 1707)
val input = readInput("Day16")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b30c48f7941eedd4a820d8e1ee5f83598789667b | 4,571 | aockt | Apache License 2.0 |
solutions/aockt/y2021/Y2021D05.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2021
import io.github.jadarma.aockt.core.Solution
import kotlin.math.sign
object Y2021D05 : Solution {
/** Represents a discrete point in 2D space. */
private data class Point(val x: Int, val y: Int) {
operator fun plus(delta: Delta): Point = Point(x + delta.dx, y + delta.dy)
}
/** Represents a direction vector in 2D space. */
private data class Delta(val dx: Int, val dy: Int)
/** Represents a line in 2D space. */
private data class Line(val p1: Point, val p2: Point) {
init {
require(p1 != p2) { "A line must connect two distinct points." }
}
/** Get the delta step between the two points, or the direction vector of a unitary step. */
val pointDelta: Delta get() = Delta((p2.x - p1.x).sign, (p2.y - p1.y).sign)
}
/** Holds a square map with side of give [size] of an ocean floor, used to track vents. */
private class OceanFloor(val size: Int) {
private val data = ByteArray(size * size) { 0 }
private var _intersections: Int = 0
operator fun get(point: Point): Boolean = data[point.x * size + point.y] > 0
operator fun set(point: Point, value: Boolean) {
val current = data[point.x * size + point.y]
data[point.x * size + point.y] = when (value) {
true -> {
if (current == 1.toByte()) _intersections++
if (current < Byte.MAX_VALUE) current.inc() else 0.toByte()
}
false -> {
if (current == 2.toByte()) _intersections--
maxOf(current.dec(), 0.toByte())
}
}
}
/** The number of points where at least two lines intersect, making it especially dangerous. */
fun intersections(): Int = _intersections
/** Mark the [line] as dangerous. */
fun setLine(line: Line) {
var pencil = line.p1
val delta = line.pointDelta
this[pencil] = true
while (pencil != line.p2) {
pencil += delta
this[pencil] = true
}
}
}
/** The format of each line of input. */
private val lineRegex = Regex("""^(\d+),(\d+) -> (\d+),(\d+)$""")
/** Parse the input and return a sequence of [Line]s defined in it. */
private fun parseInput(input: String): Sequence<Line> = input
.lineSequence()
.map { lineRegex.matchEntire(it)?.groupValues ?: throw IllegalArgumentException() }
.map { group -> group.drop(1).map { it.toIntOrNull() ?: throw IllegalArgumentException() } }
.map { (x1, y1, x2, y2) -> Line(Point(x1, y1), Point(x2, y2)) }
// Might be nice to determine the map bounds manually instead of defaulting to 1000x1000, but that would
// require either parsing the input twice, or holding it all in memory.
override fun partOne(input: String): Any = parseInput(input)
.filter { with(it.pointDelta) { dx == 0 || dy == 0 } }
.fold(OceanFloor(1000)) { acc, line -> acc.apply { setLine(line) } }
.intersections()
override fun partTwo(input: String): Any = parseInput(input)
.fold(OceanFloor(1000)) { acc, line -> acc.apply { setLine(line) } }
.intersections()
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 3,313 | advent-of-code-kotlin-solutions | The Unlicense |
src/day05/Day05.kt | ritesh-singh | 572,210,598 | false | {"Kotlin": 99540} | package day05
import readInput
import java.lang.StringBuilder
fun main() {
fun getMap(input:List<String>):HashMap<Int,ArrayDeque<Char>> {
val crates = input.takeWhile { it.isNotEmpty() }
val stackIndexMap = hashMapOf<Int,Int>().also { map ->
crates.last().forEachIndexed { index, c ->
if (c.isDigit()) {
map[index] = c.digitToInt()
}
}
}
val hashMap = hashMapOf<Int, ArrayDeque<Char>>()
crates.filterIndexed { index, _ -> index != crates.size - 1 }
.forEachIndexed { _, s ->
s.forEachIndexed { index, c ->
if (c.isLetter()){
val posn = stackIndexMap[index]!!
if (hashMap.containsKey(posn)){
val dequeue = hashMap[posn]
dequeue!!.addLast(c)
} else {
hashMap[posn] = ArrayDeque<Char>().also {
it.addLast(c)
}
}
}
}
}
return hashMap
}
fun solvePart1(input: List<String>): String {
val hashMap = getMap(input)
val procedure = input.takeLastWhile { it.isNotEmpty() }
procedure.forEach {
val (move, from, to) = it.split(" ")
.filter {
it.toIntOrNull() != null
}.map { it.toInt() }
hashMap[to] = hashMap[to]!!.also { dequeue ->
var copyMove = move
while (copyMove > 0){
dequeue.addFirst(hashMap[from]!!.removeFirst())
--copyMove
}
}
}
val strBuilder = StringBuilder()
for ((_,value ) in hashMap){
strBuilder.append(value.removeFirst())
}
return strBuilder.toString()
}
fun solvePart2(input: List<String>): String {
val hashMap = getMap(input)
val procedure = input.takeLastWhile { it.isNotEmpty() }
procedure.forEach {
val (move, from, to) = it.split(" ")
.filter {
it.toIntOrNull() != null
}.map { it.toInt() }
hashMap[to] = hashMap[to]!!.also { dequeue ->
var copyMove = move
val newDequeue = ArrayDeque<Char>()
while (copyMove > 0){
newDequeue.addFirst(hashMap[from]!!.removeFirst())
--copyMove
}
while (newDequeue.isNotEmpty()){
dequeue.addFirst(newDequeue.removeFirst())
}
}
}
val strBuilder = StringBuilder()
for ((_,value ) in hashMap){
strBuilder.append(value.removeFirst())
}
return strBuilder.toString()
}
val input = readInput("/day05/Day05")
println(solvePart1(input))
println(solvePart2(input))
}
| 0 | Kotlin | 0 | 0 | 17fd65a8fac7fa0c6f4718d218a91a7b7d535eab | 3,084 | aoc-2022-kotlin | Apache License 2.0 |
kotlin/day04.kt | bwestlin | 215,631,956 | false | null | package day04
import java.io.File
data class Room(val name: String, val sectorId: Int, val checkSum: String)
fun validChecksum(r: Room) = r.name
.filter { it >= 'a' }
.groupingBy { it }
.eachCount()
.toList()
.sortedWith(Comparator<Pair<Char, Int>> { (c1, n1), (c2, n2) ->
when {
n1 > n2 -> -1
n1 < n2 -> 1
else -> c1 - c2
}
})
.take(5)
.map { it.first }
.joinToString("")
.equals(r.checkSum)
fun decryptName(r: Room) = r.name
.map { c ->
when (c) {
in 'a'..'z' -> 'a' + (r.sectorId + (c - 'a')) % ('z' - 'a' + 1)
else -> ' '
}
}
.joinToString("")
fun parseRoom(l: String): Room {
val sectorIdSidx = l.lastIndexOf('-')
val checksumSidx = l.lastIndexOf('[')
return Room(
l.substring(0, sectorIdSidx),
l.substring(sectorIdSidx + 1, checksumSidx).toInt(),
l.substring(checksumSidx + 1, checksumSidx + 6)
)
}
fun main(args: Array<String>) {
helpers.measure {
val input = File(args[0]).readLines().map(::parseRoom).toList()
val part1 = input.filter(::validChecksum).sumBy { it.sectorId }
val part2 = input.find { decryptName(it) == "northpole object storage" }?.sectorId
println("Part1: ${part1}")
println("Part2: ${part2}")
}
}
| 0 | Rust | 0 | 0 | 0c5d6aba42fbbe0225877d9c84b0c7af85a35c5d | 1,364 | advent-of-code-2016-retro | MIT License |
19.kt | pin2t | 725,922,444 | false | {"Kotlin": 48856, "Go": 48364, "Shell": 54} | data class Workflow (val rules: List<List<String>>, val default: String)
fun main() {
val workflows = HashMap<String, Workflow>()
val parts = ArrayList<Map<String, Int>>()
while (true) {
val l = readlnOrNull() ?: break
if (l.startsWith('{')) {
val part = HashMap<String, Int>()
l.substring(1, l.length - 1).split(',').forEach {
part[it.split('=')[0]] = it.split('=')[1].toInt()
}
parts.add(part)
} else if (l.isNotBlank()) {
val items = l.substring(l.indexOf('{') + 1, l.length - 1).split(',')
workflows[l.substring(0, l.indexOf('{'))] = Workflow(
items.dropLast(1).map {
listOf(it[0].toString(), it[1].toString(), it.substring(2, it.indexOf(':')), it.substring(it.indexOf(':') + 1))
}.toList(),
items.last()
)
}
}
var res1 = 0; var res2: Long = 0
for (part in parts) {
var wf = "in"
do {
var matched = false
for (rule in workflows[wf]!!.rules) {
val value = part[rule[0]]!!
val arg = rule[2].toInt()
matched = if (rule[1] == "<") value < arg else value > arg
if (matched) { wf = rule[3]; break }
}
if (!matched) wf = workflows[wf]!!.default
} while (wf != "A" && wf != "R")
if (wf == "A") res1 += part["x"]!! + part["m"]!! + part["a"]!! + part["s"]!!
}
val queue = ArrayDeque<Pair<String, Map<String, IntRange>>>()
queue.add(Pair("in", hashMapOf("x" to 1..4000, "m" to 1..4000, "a" to 1..4000, "s" to 1..4000)))
while (!queue.isEmpty()) {
val r = queue.removeFirst()
if (r.first == "A") {
fun count(category: String): Long = r.second[category]!!.count().toLong()
res2 += count("x") * count("m") * count("a") * count("s")
continue
} else if (r.first == "R") {
continue
}
var ranges = r.second
for (rule in workflows[r.first]!!.rules) {
val part = rule[0]
val arg = rule[2].toInt()
val matched = HashMap(ranges); val left = HashMap(ranges)
when (rule[1]) {
"<" -> {
matched[part] = ranges[part]!!.first..<arg
left[part] = arg..ranges[part]!!.last
}
">" -> {
matched[part] = (arg + 1)..ranges[part]!!.last
left[part] = ranges[part]!!.first..arg
}
}
if (matched[part]!!.first <= matched[part]!!.last) {
queue.add(Pair(rule[3], matched))
}
if (left[part]!!.first <= left[part]!!.last) {
ranges = left
} else {
ranges = emptyMap()
break
}
}
if (ranges.isNotEmpty()) queue.add(Pair(workflows[r.first]!!.default, ranges))
}
println(listOf(res1, res2))
}
| 0 | Kotlin | 1 | 0 | 7575ab03cdadcd581acabd0b603a6f999119bbb6 | 3,080 | aoc2023 | MIT License |
src/main/kotlin/dev/tasso/adventofcode/_2022/day05/Day05.kt | AndrewTasso | 433,656,563 | false | {"Kotlin": 75030} | package dev.tasso.adventofcode._2022.day05
import dev.tasso.adventofcode.Solution
import java.util.ArrayDeque
class Day05 : Solution<String> {
override fun part1(input: List<String>): String {
val stacks = buildStacks(input.subList(0, input.indexOf("")))
val rearrangements = input.subList(input.indexOf("") + 1, input.size)
.map{ it.replaceFirst("move ", "").split(" from ", " to ") }
.map{ it.map{ value -> value.toInt()} }
rearrangements.forEach {
for(i in 1..it[0]) {
stacks[it[2]-1].push(stacks[it[1]-1].pop())
}
}
return stacks.joinToString(separator = "") { it.pop().toString()}
}
override fun part2(input: List<String>): String {
val stacks = buildStacks(input.subList(0, input.indexOf("")))
val rearrangements = input.subList(input.indexOf("") + 1, input.size)
.map{ it.replaceFirst("move ", "").split(" from ", " to ") }
.map{ it.map{ value -> value.toInt()} }
rearrangements.forEach {
val tempStack = ArrayDeque<Char>()
for(i in 1..it[0]) {
tempStack.push(stacks[it[1]-1].pop())
}
for(i in 1..tempStack.size) {
stacks[it[2]-1].push(tempStack.pop())
}
}
return stacks.joinToString(separator = "") { it.pop().toString()}
}
private fun buildStacks(rawInput: List<String>): List<ArrayDeque<Char>> {
//The last line of the raw input contains the number of stacks. Clear out white space, then parse the rightmost
//number to determine the total number of stacks
val numberOfStacks = rawInput.last().trim().replace("\\s+".toRegex(), ",").split(",").last().toInt()
val stacks = rawInput.dropLast(1)// Toss the line containing the stack IDs
.map{ List(numberOfStacks){ index -> it[(index * 4) + 1] } } //Extract crate IDs
//Create stacks and populate with crate IDs
.fold(List(numberOfStacks){ mutableListOf<Char>() }){ acc, e ->
acc.forEachIndexed{
index, element -> if(e[index] != ' ') { element.add(e[index]) }
}
acc
}.map{ ArrayDeque(it) }
return stacks
}
} | 0 | Kotlin | 0 | 0 | daee918ba3df94dc2a3d6dd55a69366363b4d46c | 2,554 | advent-of-code | MIT License |
src/test/kotlin/ch/ranil/aoc/aoc2022/Day08.kt | stravag | 572,872,641 | false | {"Kotlin": 234222} | package ch.ranil.aoc.aoc2022
import ch.ranil.aoc.aoc2022.Day08.Forrest.ViewDirection.*
import ch.ranil.aoc.AbstractDay
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
object Day08 : AbstractDay() {
@Test
fun tests() {
assertEquals(21, compute1(testInput))
assertEquals(1736, compute1(puzzleInput))
assertEquals(8, compute2(testInput))
assertEquals(268800, compute2(puzzleInput))
}
private fun compute1(input: List<String>): Int {
val forrest = input.convert()
return forrest.countTrue { coordinates ->
forrest.isTreeVisibleFromEdge(coordinates)
}
}
private fun compute2(input: List<String>): Int {
val forrest = input.convert()
return forrest.max { coordinates ->
forrest.treeViewingScore(coordinates)
}
}
private fun List<String>.convert(): Forrest {
val trees = this.map { row ->
row.map { Tree(it.digitToInt()) }
}
return Forrest(trees)
}
private data class Coordinates(val rowIdx: Int, val colIdx: Int)
private data class Forrest(
val trees: List<List<Tree>>
) {
private fun <R> map(transform: (Coordinates) -> R): List<R> {
return trees.flatMapIndexed { rowIdx, treeRow ->
List(treeRow.size) { colIdx ->
transform(Coordinates(rowIdx, colIdx))
}
}
}
fun countTrue(transform: (Coordinates) -> Boolean): Int {
return map(transform).count { it }
}
fun max(transform: (Coordinates) -> Int): Int {
return map(transform).max()
}
fun isTreeVisibleFromEdge(coordinates: Coordinates): Boolean {
val tree = treeAt(coordinates)
val leftTrees = treesFrom(coordinates, LEFT)
val rightTrees = treesFrom(coordinates, RIGHT)
val topTrees = treesFrom(coordinates, UP)
val bottomTrees = treesFrom(coordinates, DOWN)
return leftTrees.all { tree > it } ||
rightTrees.all { tree > it } ||
topTrees.all { tree > it } ||
bottomTrees.all { tree > it }
}
fun treeViewingScore(coordinates: Coordinates): Int {
fun List<Tree>.filterVisible(tree: Tree): List<Tree> {
val visibleTrees = mutableListOf<Tree>()
for (nextTree in this) {
visibleTrees.add(nextTree)
if (nextTree >= tree) {
break
}
}
return visibleTrees
}
val tree = treeAt(coordinates)
val visibleLeft = treesFrom(coordinates, LEFT).filterVisible(tree)
val visibleRight = treesFrom(coordinates, RIGHT).filterVisible(tree)
val visibleUp = treesFrom(coordinates, UP).filterVisible(tree)
val visibleDown = treesFrom(coordinates, DOWN).filterVisible(tree)
return visibleLeft.size * visibleRight.size * visibleUp.size * visibleDown.size
}
private fun treeAt(coordinates: Coordinates) = trees[coordinates.rowIdx][coordinates.colIdx]
private fun treesFrom(coordinates: Coordinates, direction: ViewDirection): List<Tree> {
val (rowIdx, colIdx) = coordinates
val width = trees[rowIdx].size
val height = trees.size
return when (direction) {
LEFT -> trees[rowIdx].sublistOrEmpty(0, colIdx).reversed()
UP -> trees.sublistOrEmpty(0, rowIdx).map { it[colIdx] }.reversed()
RIGHT -> trees[rowIdx].sublistOrEmpty(colIdx + 1, width)
DOWN -> trees.sublistOrEmpty(rowIdx + 1, height).map { it[colIdx] }
}
}
private enum class ViewDirection {
LEFT, UP,
RIGHT, DOWN
}
}
@JvmInline
value class Tree(private val height: Int) {
operator fun compareTo(it: Tree): Int = height.compareTo(it.height)
}
}
| 0 | Kotlin | 1 | 0 | dbd25877071cbb015f8da161afb30cf1968249a8 | 4,113 | aoc | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem368/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem368
/**
* LeetCode page: [368. Largest Divisible Subset](https://leetcode.com/problems/largest-divisible-subset/);
*/
class Solution {
/* Complexity:
* Time O(N^2) and Space O(N) where N is the size of nums;
*/
fun largestDivisibleSubset(nums: IntArray): List<Int> {
val sorted = nums.sorted()
/* dp[i]::= the (size, rightmost index in sorted of the second-largest element) of
* the largest divisible subset of sorted.slice(0..i) that includes sorted[i].
*/
val dp = buildDp(sorted)
return buildResult(dp, sorted)
}
private fun buildDp(numsSorted: List<Int>): Array<Properties> {
val result = Array(numsSorted.size) { Properties(1, -1) }
for (i in result.indices) {
var j = i - 1
while (j + 2 > result[i].size) {
if (numsSorted[i] % numsSorted[j] == 0 && 1 + result[j].size > result[i].size) {
result[i] = Properties(1 + result[j].size, j)
}
j -= 1
}
}
return result
}
private data class Properties(val size: Int, val prevIndex: Int)
private fun buildResult(dp: Array<Properties>, numsSorted: List<Int>): List<Int> {
val result = mutableListOf<Int>()
var prevIndex = dp.indices.maxBy { dp[it].size }
while (prevIndex != -1) {
result.add(numsSorted[prevIndex])
prevIndex = dp[prevIndex].prevIndex
}
return result
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,553 | hj-leetcode-kotlin | Apache License 2.0 |
src/com/wd/algorithm/leetcode/ALGO0005.kt | WalkerDenial | 327,944,547 | false | null | package com.wd.algorithm.leetcode
import com.wd.algorithm.test
import kotlin.math.max
import kotlin.math.min
/**
* 5. 最长回文子串
*
* 给你一个字符串 s,找到 s 中最长的回文子串。
*
*/
class ALGO0005 {
/**
* 方式一:暴力解法
* 分别遍历每一个字符,向后找回文字符串,经过所有遍历后,得到最长回文子串
* 时间复杂度 T(n³)
*/
fun longestPalindrome1(s: String): String {
val length = s.length
if (length < 2) return s
val lastIndex = length - 1
var start = 0
var maxLength = 1
var currStart: Char
var endIndex: Int
var tempLen: Int
var isPaired: Boolean
for (i in 0 until lastIndex) {
currStart = s[i]
endIndex = i + 1
for (j in lastIndex downTo endIndex) {
if (s[j] != currStart) continue
tempLen = j - i + 1
isPaired = true
for (k in 0..(tempLen / 2)) {
if (s[i + k] != s[j - k]) {
isPaired = false
break
}
}
if (isPaired && tempLen > maxLength) {
start = i
maxLength = tempLen
}
}
}
return s.substring(start, start + maxLength)
}
/**
* 方式二:中心扩散法
* 以当前字符串为中心,向两边扩散
* 时间复杂度 T(n²)
*/
fun longestPalindrome2(s: String): String {
val length = s.length
if (length < 2) return s
val lastIndex = length - 1
var start = 0
var maxLength = 1
for (i in 0 until lastIndex) {
val len1 = expandAroundCenter(s, i, i)
val len2 = expandAroundCenter(s, i, i + 1)
val tempMax = max(len1, len2)
if (tempMax > maxLength) {
maxLength = tempMax
start = i - tempMax / 2
if (tempMax % 2 == 0) start++
}
}
return s.substring(start, start + maxLength)
}
private fun expandAroundCenter(s: String, left: Int, right: Int): Int {
val len = s.length
var l = left
var r = right
while (l >= 0 && r < len && s[l] == s[r]) {
l--
r++
}
return r - l - 1
}
/**
* 方式三:Manacher 算法
* 时间复杂度 T(n)
*/
fun longestPalindrome3(s: String): String {
val length = s.length
if (length < 2) return s
val str = manacherString(s)
val p = IntArray(str.length)
var r = -1
var c = 0
var index = -1
var maxLength = 0
for (i in str.indices) {
p[i] = if (r > i) min(p[2 * index - i], r - i) else 1
while (i + p[i] < str.length && i - p[i] >= 0) {
if (str[i + p[i]] == str[i - p[i]]) p[i]++
else break
}
if (i + p[i] > r) {
r = i + p[i]
index = i
}
}
for (i in str.indices) {
if (p[i] > maxLength) {
maxLength = p[i]
c = i
}
}
maxLength--
c = (c - 1) / 2
val begin: Int = c - (maxLength - 1) / 2
return s.substring(begin, begin + maxLength)
}
private fun manacherString(s: String, flag: String = "#"): String {
val sb = StringBuffer(flag)
for (item in s) sb.append("$item$flag")
return sb.toString()
}
}
fun main() {
val clazz = ALGO0005()
val str = "ababaababa"
(clazz::longestPalindrome1).test(str)
(clazz::longestPalindrome2).test(str)
(clazz::longestPalindrome3).test(str)
} | 0 | Kotlin | 0 | 0 | 245ab89bd8bf467625901034dc1139f0a626887b | 3,867 | AlgorithmAnalyze | Apache License 2.0 |
kotlin/numbertheory/Factorization.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package numbertheory
import java.util.stream.Collectors.summingInt
object Factorization {
// returns prime_divisor -> power
// O(sqrt(n)) complexity
fun factorize(n: Long): Map<Long, Integer> {
var n = n
val factors: List<Long> = ArrayList()
var d: Long = 2
while (d * d <= n) {
while (n % d == 0L) {
factors.add(d)
n /= d
}
d++
}
if (n > 1) {
factors.add(n)
}
return factors.stream().collect(Collectors.groupingBy(Function.identity(), summingInt { v -> 1 }))
}
fun getAllDivisors(n: Int): IntArray {
val divisors: List<Integer> = ArrayList()
var d = 1
while (d * d <= n) {
if (n % d == 0) {
divisors.add(d)
if (d * d != n) divisors.add(n / d)
}
d++
}
return divisors.stream().sorted().mapToInt(Integer::valueOf).toArray()
}
// returns divisor of n or -1 if failed: https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm#Algorithm
// O(n^(1/4)) complexity
fun pollard(n: Long): Long {
val rnd = Random(1)
var x: Long = Math.abs(rnd.nextLong()) % n
var y = x
while (true) {
x = g(x, n)
y = g(g(y, n), n)
if (x == y) return -1
val d = gcd(Math.abs(x - y), n)
if (d != 1L) return d
}
}
fun gcd(a: Long, b: Long): Long {
return if (a == 0L) b else gcd(b % a, a)
}
fun g(x: Long, n: Long): Long {
return (41 * x + 1) % n
}
// returns divisor of n: https://en.wikipedia.org/wiki/Fermat%27s_factorization_method
fun ferma(n: Long): Long {
var x = Math.sqrt(n) as Long
var y: Long = 0
var r = x * x - y * y - n
while (true) {
if (r == 0L) return if (x != y) x - y else x + y else if (r > 0) {
r -= y + y + 1
++y
} else {
r += x + x + 1
++x
}
}
}
// Usage example
fun main(args: Array<String?>?) {
System.out.println(factorize(24))
System.out.println(Arrays.toString(getAllDivisors(16)))
val n = 1000003L * 100000037
System.out.println(pollard(n))
System.out.println(ferma(n))
}
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 2,409 | codelibrary | The Unlicense |
2023/day04-25/src/main/kotlin/Day13.kt | CakeOrRiot | 317,423,901 | false | {"Kotlin": 62169, "Python": 56994, "C#": 20675, "Rust": 10417} | import java.io.File
class Day13 {
val doubleNewLines = "(\r\n\r\n)|(\n\n)"
val newLines = "(\r\n)|(\n)"
fun solve1() {
val blocks = File("inputs/13.txt").inputStream().bufferedReader().use { it.readText() }
.split(doubleNewLines.toRegex()).map { it.split(newLines.toRegex()).filter { it.isNotBlank() } }
println(blocks.sumOf { processBlock(it, 0) })
}
fun solve2() {
val blocks = File("inputs/13.txt").inputStream().bufferedReader().use { it.readText() }
.split(doubleNewLines.toRegex()).map { it.split(newLines.toRegex()).filter { it.isNotBlank() } }
println(blocks.sumOf { processBlock(it, 1) })
}
fun processBlock(block: List<String>, mistakes: Int): Int {
var verticalRes = 0
var horizontalRes = 0
for (i in 0..<block.size - 1) {
val topSize = i + 1
val botSize = block.size - topSize
val topRange = if (topSize > botSize) IntRange(topSize - botSize, i) else IntRange(0, i)
val botRange = if (topSize > botSize) IntRange(i + 1, block.size - 1) else IntRange(
i + 1,
block.size - 1 - (botSize - topSize)
)
val top = block.slice(topRange)
val bot = block.slice(botRange)
if (top.zip(bot.reversed())
.sumOf { (t, b) -> t.zip(b).sumOf { (a, b) -> if (a != b) 1L else 0L } } == mistakes.toLong()
) horizontalRes += 100 * (i + 1)
}
for (i in 0..<block[0].length - 1) {
val leftSize = i + 1
val rightSize = block[0].length - leftSize
val leftRange = if (leftSize > rightSize) IntRange(leftSize - rightSize, i) else IntRange(0, i)
val rightRange = if (leftSize > rightSize) IntRange(i + 1, block[0].length - 1) else IntRange(
i + 1, block[0].length - 1 - (rightSize - leftSize)
)
val left = block.map { it.slice(leftRange) }
val right = block.map { it.slice(rightRange) }
if (left.zip(right)
.sumOf { (l, r) ->
l.zip(r.reversed()).sumOf { (a, b) -> if (a != b) 1L else 0L }
} == mistakes.toLong()
) verticalRes += i + 1
}
return verticalRes + horizontalRes
}
} | 0 | Kotlin | 0 | 0 | 8fda713192b6278b69816cd413de062bb2d0e400 | 2,357 | AdventOfCode | MIT License |
src/Day11.kt | astrofyz | 572,802,282 | false | {"Kotlin": 124466} | fun main() {
class Monkey(
var items: MutableList<Long> = mutableListOf(), var operation: String = "",
var test: Long = 1, var testTrue: Long = 0, var testFalse: Long = 1,
var business: Long = 0){
}
fun Long.update(operation: String): Long {
return if (('+' in operation)&&(operation.any{it.isDigit()})) {
this + operation.filter { it.isDigit() }.toLong()
} else if (('*' in operation)&&(operation.any{it.isDigit()})) {
this * operation.filter { it.isDigit() }.toLong()
} else if ('+' in operation) {
this + this
} else {
this * this
}
}
fun Monkey.inspectionPart1(): Pair<Long, Long> {
var worryLevel: Long = this.items[0]
this.business++
worryLevel = worryLevel.update(this.operation) / 3
if (worryLevel % this.test == 0.toLong()){
return Pair(worryLevel, this.testTrue)
}
else { return Pair(worryLevel, this.testFalse)}
}
fun Monkey.inspectionPart2(lcm: Long): Pair<Long, Long> {
var worryLevel: Long = this.items[0].toLong()
this.business++
worryLevel = worryLevel.update(this.operation)
worryLevel = worryLevel % lcm
if (worryLevel % this.test == 0.toLong()){
return Pair(worryLevel, this.testTrue)
}
else { return Pair(worryLevel, this.testFalse)}
}
fun Monkey.throwing(other: Monkey, itemWorryLevel: Long){
this.items.removeAt(0)
other.items.add(itemWorryLevel)
}
fun parseInput(input: List<String>): List<Monkey> {
var Monkeys = List((input.size+1) / 7, {Monkey()})
var currentIndex = 0
for (line in input){
with(line) {
when {
contains("Monkey") -> currentIndex = line.filter { it.isDigit() }.toInt()
contains("Starting items") ->
Monkeys[currentIndex].items = line
.split(": ")[1]
.split(", ")
.map{it.toLong()}
.toMutableList()
contains("Test") -> Monkeys[currentIndex].test = line.filter { it.isDigit() }.toLong()
contains("Operation") -> Monkeys[currentIndex].operation = line.split("= ")[1]
contains("If true") -> Monkeys[currentIndex].testTrue = line.filter { it.isDigit() }.toLong()
contains("If false") -> Monkeys[currentIndex].testFalse = line.filter { it.isDigit() }.toLong()
}
}
}
return Monkeys
}
fun part1(input: List<String>): Long{
var Monkeys = parseInput(input)
repeat(20){
for (monkey in Monkeys){
while (monkey.items.size > 0){
var (worryLevel, indexReceiver) = monkey.inspectionPart1()
monkey.throwing(Monkeys[indexReceiver.toInt()], worryLevel)
}
}
}
Monkeys.mapIndexed { index, mnk -> println("Monkey $index inspected items ${Monkeys[index].business} times") }
var business = Monkeys.map { it.business }.sortedDescending()
return business[0]*business[1]
}
fun part2(input: List<String>): Long{
var Monkeys = parseInput(input)
val lcm = Monkeys.map { it.test }.reduce{acc, testValue -> acc*testValue}
repeat(10000){
for (monkey in Monkeys){
while (monkey.items.size > 0){
var (worryLevel, indexReceiver) = monkey.inspectionPart2(lcm)
monkey.throwing(Monkeys[indexReceiver.toInt()], worryLevel)
}
}
}
Monkeys.mapIndexed { index, mnk -> println("Monkey $index inspected items ${Monkeys[index].business} times") }
var business = Monkeys.map { it.business }.sortedDescending()
return business[0]*business[1]
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a0bc190b391585ce3bb6fe2ba092fa1f437491a6 | 4,300 | aoc22 | Apache License 2.0 |
src/Day07.kt | petoS6 | 573,018,212 | false | {"Kotlin": 14258} | fun main() {
fun part1(lines: List<String>): Long {
val dirs = mutableListOf(Dir(null))
var current: Dir = dirs.first()
lines.drop(1).forEach { line ->
when {
line == "$ cd .." -> current = current.parent!!
line.startsWith("$ cd") -> { Dir(current).also { current.children += it; dirs += it; current = it} }
line[0].isDigit() -> current.filesSize += line.substringBefore(" ").toLong()
}
}
return dirs.filter { it.totalSize <= 100_000 }.sumOf { it.totalSize }
}
fun part2(lines: List<String>): Long {
val dirs = mutableListOf(Dir(null))
var current: Dir = dirs.first()
lines.drop(1).forEach { line ->
when {
line == "$ cd .." -> current = current.parent!!
line.startsWith("$ cd") -> { Dir(current).also { current.children += it; dirs += it; current = it} }
line[0].isDigit() -> current.filesSize += line.substringBefore(" ").toLong()
}
}
val missing = 30_000_000 - (70_000_000 - dirs.first().totalSize)
return dirs.filter { it.totalSize >= missing }.minOf { it.totalSize }
}
val testInput = readInput("Day07.txt")
println(part1(testInput))
println(part2(testInput))
}
class Dir(val parent: Dir?, var children: List<Dir> = emptyList()) {
var filesSize = 0L
val totalSize: Long get() = filesSize + children.sumOf { it.totalSize }
} | 0 | Kotlin | 0 | 0 | 40bd094155e664a89892400aaf8ba8505fdd1986 | 1,371 | kotlin-aoc-2022 | Apache License 2.0 |
src/main/kotlin/Day01.kt | NielsSteensma | 572,641,496 | false | {"Kotlin": 11875} | fun main() {
val input = readInput("Day01")
println("Day 01 Part 1 ${calculateDay01Part1(input)}")
println("Day 01 Part 2 ${calculateDay01Part2(input)}")
}
fun calculateDay01Part1(input: List<String>): Int {
return calculateTotalCaloriesByElve(input)
.maxOf { it } // Grab elve who took most calories with him on the trip.
}
fun calculateDay01Part2(input: List<String>): Int {
return calculateTotalCaloriesByElve(input)
.sortedDescending() // Sort in descending order.
.take(3) // Take 3 elves carrying most calories
.sum() // Get sum of the 3 elves carrying most calories.
}
private fun calculateTotalCaloriesByElve(input: List<String>): List<Int> {
return input
.splitWhen { it.isBlank() } // Elve separator
.map { it.map { caloriesPerDay -> caloriesPerDay.toInt() } } // Elve calorie per day from String to Int
.map { it.sum() } // Calculate total calories carried per elve.
}
| 0 | Kotlin | 0 | 0 | 4ef38b03694e4ce68e4bc08c390ce860e4530dbc | 963 | aoc22-kotlin | Apache License 2.0 |
src/main/kotlin/com/github/michaelbull/advent2021/day10/Day10.kt | michaelbull | 433,565,311 | false | {"Kotlin": 162839} | package com.github.michaelbull.advent2021.day10
import com.github.michaelbull.advent2021.Puzzle
object Day10 : Puzzle<Sequence<String>, Long>(day = 10) {
override fun parse(input: Sequence<String>): Sequence<String> {
return input
}
override fun solutions() = listOf(
::part1,
::part2
)
fun part1(lines: Sequence<String>): Long {
return lines.sumOf(::errorScore)
}
fun part2(lines: Sequence<String>): Long {
return lines.map(::autocompleteScore)
.filter { it != 0L }
.toList()
.sorted()
.midpoint()
}
private fun errorScore(line: String): Long {
parseOpeners(line) { unexpectedCloser ->
return CLOSERS_TO_POINTS.getValue(unexpectedCloser)
}
return 0
}
private fun autocompleteScore(line: String): Long {
val openers = parseOpeners(line) {
return 0
}
return openers.asReversed().fold(0L, ::autocompleteScore)
}
private fun autocompleteScore(totalScore: Long, opener: Char): Long {
return (totalScore * 5) + OPENERS_TO_POINTS.getValue(opener)
}
private inline fun parseOpeners(line: String, onUnexpectedCloser: (unexpectedCloser: Char) -> Nothing): ArrayDeque<Char> {
val openers = ArrayDeque<Char>()
for (char in line) {
if (char in OPENERS) {
openers += char
} else if (char !in CLOSERS) {
throw IllegalArgumentException("invalid char: $char")
} else if (openers.isEmpty() || openers.removeLast() != CLOSERS_TO_OPENERS[char]) {
onUnexpectedCloser(char)
}
}
return openers
}
private fun <T> List<T>.midpoint(): T {
return this[size / 2]
}
private val DELIMITERS = listOf(
ChunkDelimiter('(', ')'),
ChunkDelimiter('[', ']'),
ChunkDelimiter('{', '}'),
ChunkDelimiter('<', '>'),
)
private val OPENERS = DELIMITERS.map(ChunkDelimiter::opener)
private val CLOSERS = DELIMITERS.map(ChunkDelimiter::closer)
private val CLOSER_POINTS = listOf(3L, 57L, 1197L, 25137L)
private val OPENER_POINTS = listOf(1L, 2L, 3L, 4L)
private val CLOSERS_TO_OPENERS = DELIMITERS.associate { it.closer to it.opener }
private val OPENERS_TO_POINTS = DELIMITERS.mapIndexed { index, (opener, _) ->
opener to OPENER_POINTS[index]
}.toMap()
private val CLOSERS_TO_POINTS = DELIMITERS.mapIndexed { index, (_, closer) ->
closer to CLOSER_POINTS[index]
}.toMap()
}
| 0 | Kotlin | 0 | 4 | 7cec2ac03705da007f227306ceb0e87f302e2e54 | 2,619 | advent-2021 | ISC License |
src/Day01.kt | ajspadial | 573,864,089 | false | {"Kotlin": 15457} |
data class Elf(var sum: Int = 0) {
}
fun main() {
fun calculateCalories(input: List<String>): List<Elf> {
val elfs: MutableList<Elf> = mutableListOf()
var currentElf = Elf()
elfs.add(currentElf)
for (line in input) {
if (line == "") {
currentElf = Elf()
elfs.add(currentElf)
}
else {
val calories = line.toInt()
currentElf.sum += calories
}
}
return elfs
}
fun part1(input: List<String>): Int {
val elfs = calculateCalories(input)
var maxCalories = 0
for (elf in elfs) {
if (elf.sum > maxCalories) maxCalories = elf.sum
}
return maxCalories
}
fun part2(input: List<String>): Int {
val elfs = calculateCalories(input)
val top3 = mutableListOf(0,0,0)
for (elf in elfs) {
if (elf.sum > top3[0]) {
top3[2] = top3[1]
top3[1] = top3[0]
top3[0] = elf.sum
}
else if (elf.sum > top3[1]) {
top3[2] = top3[1]
top3[1] = elf.sum
}
else if (elf.sum > top3[2]) {
top3[2] = elf.sum
}
}
return top3.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ed7a2010008be17fec1330b41adc7ee5861b956b | 1,628 | adventofcode2022 | Apache License 2.0 |
src/Day04.kt | zhiqiyu | 573,221,845 | false | {"Kotlin": 20644} | import kotlin.math.max
import kotlin.math.abs
fun main() {
fun part1(input: List<String>): Int {
var result = 0
for (line in input) {
var pairs = line.split(",").map { it.split("-") }
var s1 = pairs.get(0).get(0).toInt()
var e1 = pairs.get(0).get(1).toInt()
var s2 = pairs.get(1).get(0).toInt()
var e2 = pairs.get(1).get(1).toInt()
if ((s1 <= s2 && e1 >= e2) || (s1 >= s2 && e1 <= e2)) {
result ++
}
}
return result
}
fun part2(input: List<String>): Int {
var result = 0
for (line in input) {
var pairs = line.split(",").map { it.split("-") }
var s1 = pairs.get(0).get(0).toInt()
var e1 = pairs.get(0).get(1).toInt()
var s2 = pairs.get(1).get(0).toInt()
var e2 = pairs.get(1).get(1).toInt()
if (!(e1 < s2 || s1 > e2)) {
result ++
}
}
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println("----------")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d3aa03b2ba2a8def927b94c2b7731663041ffd1d | 1,378 | aoc-2022 | Apache License 2.0 |
dcp_kotlin/src/main/kotlin/dcp/day144/day144.kt | sraaphorst | 182,330,159 | false | {"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315} | package dcp.day144
// day144.kt
// By <NAME>, 2020.
import kotlin.math.abs
/**
* Given a list of elements elems and an index idx of one of the elements, find the index of the nearest element whose
* value is greater than elems[idx]. Ties may be broken arbitrarily.
*
* This algorithm runs in time O(n log n) due to the call to sortedBy.
*/
fun List<Int>.findNextHighestBF(idx: Int): Int? =
withIndex().filter { (_, value) -> value > get(idx) }.sortedBy { abs(it.index - idx) }.firstOrNull()?.index
/**
* Preprocess the array so that we can retrieve the answer in constant time for any idx.
* This is very confusing, so lots of comments. It could probably be done more cleanly.
* At the end of this, the returned array should give a value equivalent to that given by findNextHighestBF,
* although since there may not be a unique answer, it may not be the same.
*/
fun preprocess(elems: List<Int>): List<Int?> {
val idxed = elems.withIndex().sortedBy { it.value }
// Now that we have sorted by value, for idx, we only need to find the idx of the value to the right that is
// smallest away in distance. We want to drop everything to the left, so index again. This is undoubtedly confusing
// now, but the format of each entry is:
// (idx in idxed, (idx in original list, value in original list)).
val nearest = idxed.withIndex().map { (idx2, p) ->
val (idx, _) = p
idxed.drop(idx2 + 1).minBy { abs(idx - it.index) }}
// Now convert back to the original ordering. To start doing this, create a map such that map[idx] is the answer
// for idx.
val mappedAnswer = idxed.indices.map { idxed[it].index to nearest[it]?.index }.toMap()
// Now put everything back in order.
return idxed.indices.map { mappedAnswer[it] }
}
| 0 | C++ | 1 | 0 | 5981e97106376186241f0fad81ee0e3a9b0270b5 | 1,805 | daily-coding-problem | MIT License |
src/main/kotlin/days/Day24.kt | andilau | 433,504,283 | false | {"Kotlin": 137815} | package days
@AdventOfCodePuzzle(
name = "Arithmetic Logic Unit",
url = "https://adventofcode.com/2021/day/24",
date = Date(day = 24, year = 2021)
)
class Day24(listing: List<String>) : Puzzle {
private val monad = listing.filter(String::isNotEmpty).map { Instruction.parse(it) }
override fun partOne() =
findSolution(9 downTo 1, State(0, 0, 0, 0, 0)) ?: error("No solution")
override fun partTwo() =
findSolution(1..9, State(0, 0, 0, 0, 0)) ?: error("No solution")
internal fun computeState(input: List<Int>): State {
val numbers = input.toMutableList()
return monad.fold(State(0, 0, 0, 0, 0)) { state, ins -> state.solveWithInput(ins, numbers) }
}
private fun findSolution(
order: IntProgression,
state: State,
answer: Long = 0,
done: MutableSet<State> = mutableSetOf()
): Long? {
var computedState = state
var ip = computedState.ip
while (ip in monad.indices) {
when (val instruction = monad[ip++]) {
is Input -> {
// Already computed?
if (!done.add(computedState.copy(ip = ip))) return null
var res: Long? = null
for (candidate in order) {
res = findSolution(
order,
computedState.set(instruction.first, candidate).copy(ip = ip),
answer * 10 + candidate,
done
)
if (res != null) break
}
return res
}
is Add, is Mul, is Div, is Mod, is Eql -> computedState = computedState.solve(instruction)
}
}
return if (computedState.z == 0) answer else null
}
data class State(val w: Int, val x: Int, val y: Int, val z: Int, val ip: Int) {
fun get(parameter: Char): Int = when (parameter) {
'w' -> w
'x' -> x
'y' -> y
'z' -> z
else -> error("Unknown parameter")
}
fun get(parameterOrValue: String): Int =
parameterOrValue.toIntOrNull() ?: get(parameterOrValue[0])
fun set(parameter: Char, value: Int) = when (parameter) {
'w' -> copy(w = value)
'x' -> copy(x = value)
'y' -> copy(y = value)
'z' -> copy(z = value)
else -> error("Unknown parameter")
}
fun solveWithInput(instruction: Instruction, input: MutableList<Int>): State =
when (instruction) {
is Input -> set(instruction.first, input.removeFirst())
else -> solve(instruction)
}
fun solve(instruction: Instruction): State =
when (instruction) {
is Input -> error("Cant handle input")
is Add -> set(instruction.first, get(instruction.first) + get(instruction.second))
is Mul -> set(instruction.first, get(instruction.first) * get(instruction.second))
is Div -> set(instruction.first, get(instruction.first) / get(instruction.second))
is Mod -> set(instruction.first, get(instruction.first) % get(instruction.second))
is Eql -> set(instruction.first, if (get(instruction.first) == get(instruction.second)) 1 else 0)
}
}
sealed interface Instruction {
companion object {
fun parse(line: String): Instruction {
val (cmd, args) = line.split(' ', limit = 2)
val arg1 = args.split(' ')
return when (cmd) {
"inp" -> Input(arg1[0][0])
"add" -> Add(arg1[0][0], arg1[1])
"mul" -> Mul(arg1[0][0], arg1[1])
"div" -> Div(arg1[0][0], arg1[1])
"mod" -> Mod(arg1[0][0], arg1[1])
"eql" -> Eql(arg1[0][0], arg1[1])
else -> error("Unknown command: $cmd")
}
}
}
}
data class Input(val first: Char) : Instruction
data class Add(val first: Char, val second: String) : Instruction
data class Mul(val first: Char, val second: String) : Instruction
data class Div(val first: Char, val second: String) : Instruction
data class Mod(val first: Char, val second: String) : Instruction
data class Eql(val first: Char, val second: String) : Instruction
} | 0 | Kotlin | 0 | 0 | b3f06a73e7d9d207ee3051879b83e92b049a0304 | 4,555 | advent-of-code-2021 | Creative Commons Zero v1.0 Universal |
src/Day11.kt | TheGreatJakester | 573,222,328 | false | {"Kotlin": 47612} | package day11
import utils.readInputAsText
import utils.runSolver
import utils.string.asLines
import utils.string.asParts
private typealias SolutionType = Long
private const val defaultSolution = 0
private const val dayNumber: String = "11"
private val testSolution1: SolutionType? = 10605
private val testSolution2: SolutionType? = 2713310158
class Monkey(
val id: Int,
val items: MutableList<Long>,
// True is multiplication, false is addition
val operation: Boolean,
val operationValue: Long?,
val testValue: Int,
val trueMonkeyId: Int,
val falseMonkeyId: Int
) {
var monkeyList: List<Monkey>? = null
set(value) {
field = value
universalLimit = value?.map { it.testValue.toLong() }?.reduce { acc, i -> acc * i }!!
}
private var universalLimit = 0L
val trueMonkey get() = monkeyList?.first { it.id == trueMonkeyId }!!
val falseMonkey get() = monkeyList?.first { it.id == falseMonkeyId }!!
fun doOperation(operating: Long): Long {
val operationValue = operationValue ?: operating
return if (operation) {
operating * operationValue
} else {
operating + operationValue
}
}
fun doTest(testing: Long): Boolean {
return testing % testValue == 0L
}
var count: Long = 0
private set
private fun handleOneItem(item: Long) {
count++
val newItem = doOperation(item) % universalLimit
val test = doTest(newItem)
if (test) {
trueMonkey.items.add(newItem)
} else {
falseMonkey.items.add(newItem)
}
}
fun doRound() {
items.forEach { handleOneItem(it) }
items.clear()
}
companion object {
var worryDivider = 1
}
}
fun parseMonkeys(input: String): List<Monkey> {
val mStrings = input.asParts()
fun String.lastInt(): Int? = try {
this.split(" ").last().toInt()
} catch (ex: Exception) {
null
}
val monkeys = mStrings.map {
val lines = it.asLines()
val (idLine, itemLine, opLine, testLine) = lines.take(4)
val (trueLine, falseLine) = lines.takeLast(2)
val id = idLine.split(" ")[1].dropLast(1).toInt()
val items = itemLine.split(": ").last().trim().replace(" ", "")
.split(",").map { it.toLong() }
val opChar = opLine.split(" ")[6]
val op = opChar == "*"
val opVal = opLine.lastInt()?.toLong()
val testVal = testLine.lastInt()
val truth = trueLine.lastInt()
val falsy = falseLine.lastInt()
Monkey(
id = id,
items = items.toMutableList(),
operation = op,
operationValue = opVal,
testValue = testVal!!,
trueMonkeyId = truth!!,
falseMonkeyId = falsy!!
)
}
monkeys.forEach { it.monkeyList = monkeys }
return monkeys
}
private fun part1(input: String): SolutionType {
Monkey.worryDivider = 3
val monkeys = parseMonkeys(input)
repeat(20) {
monkeys.forEach { it.doRound() }
}
val (m1, m2) = monkeys.sortedBy { it.count }.takeLast(2)
return m1.count * m2.count
}
private fun part2(input: String): SolutionType {
Monkey.worryDivider = 1
val monkeys = parseMonkeys(input)
fun round() = monkeys.forEach { it.doRound() }
repeat(10_000) {
round()
}
val (m1, m2) = monkeys.sortedBy { it.count }.takeLast(2)
return m1.count * m2.count
}
//10592276768 too low
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,922 | 2022-AOC-Kotlin | Apache License 2.0 |
2021/src/test/kotlin/Day08.kt | jp7677 | 318,523,414 | false | {"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338} | import kotlin.test.Test
import kotlin.test.assertEquals
class Day08 {
data class Note(val patterns: List<String>, val outputs: List<String>)
data class Display(val digit: Int, val segments: String)
private val displays = arrayOf(
Display(0, "abcefg".sorted()),
Display(1, "cf".sorted()),
Display(2, "acdeg".sorted()),
Display(3, "acdfg".sorted()),
Display(4, "bcdf".sorted()),
Display(5, "abdfg".sorted()),
Display(6, "abdefg".sorted()),
Display(7, "acf".sorted()),
Display(8, "abcdefg".sorted()),
Display(9, "abcdfg".sorted())
)
private val displaysWithUniqueSegmentCount = displays
.filter { displays.count { s -> s.segments.length == it.segments.length } == 1 }
@Test
fun `run part 01`() {
val count = getNotes()
.flatMap { it.outputs }
.count { output ->
displaysWithUniqueSegmentCount.any { it.segments.length == output.length }
}
assertEquals(440, count)
}
@Test
fun `run part 02`() {
val count = getNotes()
.sumOf { note ->
val mapping = mutableMapOf(
Pair("a", "abcdefg"),
Pair("b", "abcdefg"),
Pair("c", "abcdefg"),
Pair("d", "abcdefg"),
Pair("e", "abcdefg"),
Pair("f", "abcdefg"),
Pair("g", "abcdefg")
)
mapping.deduceBySegmentCountOverAllDigits(note.patterns)
mapping.deduceBySegmentCountPerDigit(note.patterns)
note.outputs.decode(mapping)
}
assertEquals(1046281, count)
}
private fun MutableMap<String, String>.deduceBySegmentCountOverAllDigits(patterns: List<String>) {
val segmentsWithUniqueCountOverAllDigits = displays.joinToString("") { it.segments }
.groupingBy { it }.eachCount()
.toList()
.groupBy { it.second }
.filterValues { it.size == 1 }
.map { it.value.first().first.toString() }
val otherSegments = displays.joinToString("") { it.segments }
.map { it.toString() }
.distinct() - segmentsWithUniqueCountOverAllDigits.toSet()
segmentsWithUniqueCountOverAllDigits
.onEach { segment ->
val count = displays.joinToString { it.segments }.count { s -> s.toString() == segment }
this[segment] = patterns.joinToString("")
.groupBy { it }
.filter { it.value.count() == count }
.keys.single()
.toString()
}
this
.filterKeys { it in segmentsWithUniqueCountOverAllDigits }
.onEach {
otherSegments.onEach { segment ->
this[segment] = this[segment]!!.replace(it.value, "")
}
}
}
private fun MutableMap<String, String>.deduceBySegmentCountPerDigit(pattern: List<String>) = pattern
.filter { p -> displaysWithUniqueSegmentCount.any { it.segments.length == p.length } }
.onEach {
displays
.filter { s -> s.segments.length == it.length }
.map { it.segments }
.single()
.let { segments ->
this.onEach { r ->
if (segments.contains(r.key))
this[r.key] = (this[r.key]!!.toSet() intersect it.toSet()).joinToString("")
else
this[r.key] = (this[r.key]!!.toSet() - it.toSet()).joinToString("")
}
}
}
private fun List<String>.decode(mapping: MutableMap<String, String>) = this
.map {
it
.map { c -> mapping.keys.single { k -> mapping[k] == c.toString() } }
.let { translated ->
displays.single { d -> d.segments == translated.joinToString("").sorted() }
}
}
.joinToString("") { it.digit.toString() }.toInt()
private fun getNotes() = Util.getInputAsListOfString("day08-input.txt")
.map {
it
.split("|")
.let { parts ->
Note(
parts.first().split(" ").filter { s -> s.isNotEmpty() }.map { s -> s.sorted() }.toList(),
parts.last().split(" ").filter { s -> s.isNotEmpty() }.map { s -> s }.toList()
)
}
}
private fun String.sorted() = this.toList().sorted().joinToString("")
}
| 0 | Kotlin | 1 | 2 | 8bc5e92ce961440e011688319e07ca9a4a86d9c9 | 4,738 | adventofcode | MIT License |
2022/src/main/kotlin/Day18.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | import kotlin.math.abs
object Day18 {
fun part1(input: String) = surfaceArea(parseInput(input))
fun part2(input: String): Int {
val droplet = parseInput(input)
// Check every location within the droplet's bounds to see if it's in an air pocket or not
//
// This is not particularly efficient (we could determine from previous searches whether
// a point is in an air pocket already) but it runs in <1s so I don't care to optimize
val bounds = Bounds(droplet)
val airPockets =
(bounds.xRange).flatMap { x ->
(bounds.yRange).flatMap { y ->
(bounds.zRange).map { z ->
Cube(x, y, z)
}
}
}.filter { it.isInAirPocket(droplet, bounds) }
// Check surface area (as if the air pocket was filled in)
return surfaceArea(droplet + airPockets)
}
private fun surfaceArea(droplet: Set<Cube>): Int {
return droplet.sumOf { cube -> 6 - droplet.count { distance(cube, it) == 1 } }
}
private fun distance(a: Cube, b: Cube) = abs(a.x - b.x) + abs(a.y - b.y) + abs(a.z - b.z)
private fun Cube.isInAirPocket(droplet: Set<Cube>, bounds: Bounds): Boolean {
if (this in droplet) return false // Quick exit - can't be an air pocket if actually part of droplet!
val queue = mutableListOf(this)
val explored = mutableSetOf(this)
while (queue.isNotEmpty()) {
val curr = queue.removeFirst()
// We found a way to get outside the bounds of the droplet, must not be in an air pocket
if (curr.x !in bounds.xRange || curr.y !in bounds.yRange || curr.z !in bounds.zRange) {
return false
}
val next = listOf(
curr.copy(x = curr.x - 1),
curr.copy(x = curr.x + 1),
curr.copy(y = curr.y - 1),
curr.copy(y = curr.y + 1),
curr.copy(z = curr.z - 1),
curr.copy(z = curr.z + 1),
).filter { it !in explored && it !in droplet }
explored.addAll(next)
queue.addAll(next)
}
// Ran out of places to go, we must be in an air pocket
return true
}
private fun parseInput(input: String): Set<Cube> {
return input.splitNewlines()
.map { it.splitCommas().map(String::toInt) }
.map { (x, y, z) -> Cube(x, y, z) }
.toSet()
}
private data class Cube(val x: Int, val y: Int, val z: Int)
private class Bounds(droplet: Set<Cube>) {
val xRange = droplet.minOf { it.x }..droplet.maxOf { it.x }
val yRange = droplet.minOf { it.y }..droplet.maxOf { it.y }
val zRange = droplet.minOf { it.z }..droplet.maxOf { it.z }
}
} | 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 2,561 | advent-of-code | MIT License |
src/main/kotlin/leetCode/39.kt | wenvelope | 692,706,194 | false | {"Kotlin": 11474, "Java": 7490} | package leetCode
/**
* 给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,
* 并以列表形式返回。你可以按 任意顺序 返回这些组合。
*
* candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
*
* 对于给定的输入,保证和为 target 的不同组合数少于 150 个。\
*
* 输入:candidates = [2,3,6,7], target = 7
* 输出:[[2,2,3],[7]]
* 解释:
* 2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
* 7 也是一个候选, 7 = 7 。
* 仅有这两种组合。
*/
fun main() {
val s = Solution()
val candidates = intArrayOf(10,1,2,7,6,1,5)
val result = s.combinationSum(candidates, 8)
println(result.toString())
}
private class Solution {
fun combinationSum(candidates: IntArray, target: Int): List<List<Int>> {
candidates.sort()
val resultList = arrayListOf<ArrayList<Int>>()
val tempList = arrayListOf<Int>()
combine(tempList, resultList, 0, candidates, target)
return resultList
}
fun combine(
tempList: ArrayList<Int>,
resultList: ArrayList<ArrayList<Int>>,
index: Int,
candidates: IntArray,
target: Int
) {
val sum = tempList.sum()
if (sum >= target) {
if (sum == target) {
val list = ArrayList(tempList)
resultList.add(list)
}
return
}
for (item in candidates) {
if (tempList.size >= 1 && item < tempList[tempList.size - 1]) {
continue
}
tempList.add(item)
combine(tempList, resultList, index + 1, candidates, target)
tempList.removeAt(index)
}
}
} | 0 | Kotlin | 0 | 1 | 4a5b2581116944c5bf8cf5ab0ed0af410669b9b6 | 1,956 | OnlineJudge | Apache License 2.0 |
src/Day07.kt | davidkna | 572,439,882 | false | {"Kotlin": 79526} | fun main() {
fun parseInput(input: List<String>): HashMap<List<String>, Int> {
val fs = HashMap<List<String>, Int>()
var pwd = ArrayList<String>()
for (line in input) {
if (line.startsWith("$ cd")) {
when (val newLocation = line.removePrefix("$ cd ")) {
".." -> {
pwd.removeLast()
}
"/" -> {
pwd = ArrayList()
}
else -> {
pwd.add(newLocation)
}
}
}
val size = line.split(' ').first()
if (size != "dir" && !size.startsWith("$")) {
for (i in 0..pwd.size) {
val cursor = pwd.subList(0, i).toList()
if (fs.containsKey(cursor)) {
fs[cursor] = fs[cursor]!! + size.toInt()
} else {
fs[cursor] = size.toInt()
}
}
}
}
return fs
}
fun part1(input: List<String>): Int {
val fs = parseInput(input)
return fs.values.filter { it < 100000 }.sum()
}
fun part2(input: List<String>): Int {
val fs = parseInput(input)
val totalSize = fs[listOf()]!!
return fs.values.filter { totalSize - it < 40000000 }.min()
}
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ccd666cc12312537fec6e0c7ca904f5d9ebf75a3 | 1,656 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/g1801_1900/s1818_minimum_absolute_sum_difference/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1801_1900.s1818_minimum_absolute_sum_difference
// #Medium #Array #Sorting #Binary_Search #Ordered_Set #Binary_Search_II_Day_7
// #2023_06_20_Time_447_ms_(100.00%)_Space_53_MB_(100.00%)
import kotlin.math.abs
class Solution {
fun minAbsoluteSumDiff(nums1: IntArray, nums2: IntArray): Int {
var min = Int.MAX_VALUE
var max = Int.MIN_VALUE
for (i in nums1.indices) {
min = min.coerceAtMost(nums1[i].coerceAtMost(nums2[i]))
max = max.coerceAtLeast(nums1[i].coerceAtLeast(nums2[i]))
}
val less = IntArray(max - min + 1)
val more = IntArray(max - min + 1)
less[0] = -max - 1
more[more.size - 1] = max + 1 shl 1
for (num in nums1) {
less[num - min] = num
more[num - min] = num
}
for (i in 1 until less.size) {
if (less[i] == 0) {
less[i] = less[i - 1]
}
}
for (i in more.size - 2 downTo 0) {
if (more[i] == 0) {
more[i] = more[i + 1]
}
}
var total = 0
var preSave = 0
for (i in nums1.indices) {
val current = abs(nums1[i] - nums2[i])
total += current
val save = (
current -
abs(less[nums2[i] - min] - nums2[i]).coerceAtMost(abs(more[nums2[i] - min] - nums2[i]))
)
if (save > preSave) {
total = total + preSave - save
preSave = save
}
total %= 1000000007
}
return total
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,623 | LeetCode-in-Kotlin | MIT License |
src/Day08.kt | ChrisCrisis | 575,611,028 | false | {"Kotlin": 31591} | import template.DailyChallenge
import template.InputData
class TreeGrid(
private val trees: Array<Array<Tree>>
){
private val sizeX by lazy { trees.first().size }
private val sizeY by lazy { trees.size }
fun getTreesVisibleFromOutside(): Int {
return trees.sumOf { treeLine ->
treeLine.count { tree ->
tree.isVisible()
}
}
}
fun getHighestScore(): Int {
return trees.maxOf {treeLine ->
treeLine.maxOf {
it.getScore()
}
}
}
class Tree(
val x: Int,
val y: Int,
val height: Int,
)
//region Extensions
private fun Tree.getScore(): Int {
val horizontalScore = getTreesInRow(this.y).getLineScore(this)
val verticalScore = getTreesInColumn(this.x).getLineScore(this)
return horizontalScore * verticalScore
}
private fun Tree.isVisible(): Boolean{
return this.isOnTheEdge()
|| this.isVerticallyVisible()
|| this.isHorizontallyVisible()
}
private fun Tree.isOnTheEdge(): Boolean =
this.x == 0 || this.x == sizeX-1 ||
this.y == 0 || this.y == sizeY-1
private fun Tree.isVerticallyVisible(): Boolean {
return getTreesInColumn(this.x).isTreeVisible(this)
}
private fun Tree.isHorizontallyVisible(): Boolean {
return getTreesInRow(this.y).isTreeVisible(this)
}
//endregion
private fun getTreesInColumn(index: Int): List<Tree>{
return trees.map { it[index] }
}
private fun getTreesInRow(index: Int): List<Tree>{
return trees[index].toList()
}
private fun List<Tree>.getSurroundingSubListsFor(tree: Tree): List<List<Tree>>{
val treeIndex = this.indexOf(tree)
return listOf(
this.subList(0, treeIndex).reversed(),
this.subList(treeIndex + 1, this.size),
)
}
private fun List<Tree>.isTreeVisible(tree: Tree): Boolean {
val surroundingSides = getSurroundingSubListsFor(tree)
return surroundingSides.any {treeLine ->
treeLine.maxOf { it.height } < tree.height
}
}
private fun List<Tree>.getLineScore(tree: Tree): Int {
val surroundingSides = getSurroundingSubListsFor(tree)
return surroundingSides.map {treeLine ->
val highTreeIndex = treeLine.indexOfFirst { it.height >= tree.height } + 1
if(highTreeIndex == 0) treeLine.size else highTreeIndex
}.fold(1) { first, second ->
first * second
}
}
}
class Day08(inputData: InputData<Int>):
DailyChallenge<TreeGrid,Int>(inputData){
override fun parseInput(data: String): TreeGrid {
val lines = data.split("\n")
val lineArray = lines.mapIndexed { y, line ->
line.mapIndexed { x, treeHeight ->
TreeGrid.Tree(
x,
y,
Character.getNumericValue(treeHeight)
)
}.toTypedArray()
}.toTypedArray()
return TreeGrid(lineArray)
}
override fun part1(input: TreeGrid): Int {
return input.getTreesVisibleFromOutside()
}
override fun part2(input: TreeGrid): Int {
return input.getHighestScore()
}
} | 1 | Kotlin | 0 | 0 | 732b29551d987f246e12b0fa7b26692666bf0e24 | 3,378 | aoc2022-kotlin | Apache License 2.0 |
src/main/kotlin/year2022/Day11.kt | simpor | 572,200,851 | false | {"Kotlin": 80923} | import AoCUtils
import AoCUtils.test
enum class OperationValue { PLUS, TIMES, SQUARE }
fun main() {
data class Monkey(
val id: Long,
val operation: OperationValue,
val operationValue: Long,
val testValue: Long,
val testTrue: Long,
val testFalse: Long,
var count: Long = 0,
val items: MutableList<Long> = mutableListOf(),
)
fun monkeyMap(input: String): Map<Long, Monkey> {
val monkeys = input.split("\n\n").map { monkeyLines ->
val lines = monkeyLines.lines()
val id = lines[0].replace("Monkey ", "").replace(":", "").toLong()
val items = lines[1].trim().replace("Starting items: ", "").split(",").map { it.trim().toLong() }
val operationValue =
if (!lines[2].contains("old * old")) lines[2].trim().replace("Operation: new = old * ", "")
.replace("Operation: new = old + ", "").toLong() else 0
val operationPlus = if (lines[2].contains("old * old")) OperationValue.SQUARE else if (lines[2].trim()
.contains("+")
) OperationValue.PLUS else OperationValue.TIMES
val testValue = lines[3].trim().replace("Test: divisible by ", "").toLong()
val testTrue = lines[4].trim().replace("If true: throw to monkey ", "").toLong()
val testfalse = lines[5].trim().replace("If false: throw to monkey ", "").toLong()
Pair(
id,
Monkey(id, operationPlus, operationValue, testValue, testTrue, testfalse, items = items.toMutableList())
)
}.toMap()
return monkeys
}
fun part1(input: String, debug: Boolean = false): Long {
val monkeys = monkeyMap(input)
repeat(20) {
monkeys.values.forEach { monkey ->
monkey.items.forEach { item ->
monkey.count += 1
val worrieLevel = when (monkey.operation) {
OperationValue.PLUS -> item + monkey.operationValue
OperationValue.TIMES -> item * monkey.operationValue
OperationValue.SQUARE -> item * item
} / 3
val test = worrieLevel % monkey.testValue == 0L
if (test) {
monkeys[monkey.testTrue]!!.items.add(worrieLevel)
} else {
monkeys[monkey.testFalse]!!.items.add(worrieLevel)
}
}
monkey.items.clear()
}
}
return monkeys.values.map { it.count }.sortedDescending().take(2).fold(1) { acc, i -> acc * i }
}
fun part2(input: String, debug: Boolean = false): Long {
val monkeys = monkeyMap(input)
val lcd = monkeys.values.map { it.testValue }.fold(1L) {acc, l -> acc * l }
repeat(10000) {
monkeys.values.forEach { monkey ->
monkey.items.forEach { item ->
monkey.count += 1
val worrieLevel = when (monkey.operation) {
OperationValue.PLUS -> item + monkey.operationValue
OperationValue.TIMES -> item * monkey.operationValue
OperationValue.SQUARE -> item * item
} % lcd
val test = worrieLevel % monkey.testValue == 0L
if (test) {
monkeys[monkey.testTrue]!!.items.add(worrieLevel)
} else {
monkeys[monkey.testFalse]!!.items.add(worrieLevel)
}
}
monkey.items.clear()
}
}
return monkeys.values.map { it.count }.sortedDescending().take(2).fold(1) { acc, i -> acc * i }
}
val testInput =
"Monkey 0:\n" +
" Starting items: 79, 98\n" +
" Operation: new = old * 19\n" +
" Test: divisible by 23\n" +
" If true: throw to monkey 2\n" +
" If false: throw to monkey 3\n" +
"\n" +
"Monkey 1:\n" +
" Starting items: 54, 65, 75, 74\n" +
" Operation: new = old + 6\n" +
" Test: divisible by 19\n" +
" If true: throw to monkey 2\n" +
" If false: throw to monkey 0\n" +
"\n" +
"Monkey 2:\n" +
" Starting items: 79, 60, 97\n" +
" Operation: new = old * old\n" +
" Test: divisible by 13\n" +
" If true: throw to monkey 1\n" +
" If false: throw to monkey 3\n" +
"\n" +
"Monkey 3:\n" +
" Starting items: 74\n" +
" Operation: new = old + 3\n" +
" Test: divisible by 17\n" +
" If true: throw to monkey 0\n" +
" If false: throw to monkey 1"
val input = AoCUtils.readText("year2022/day11.txt")
part1(testInput, false) test Pair(10605L, "test 1 part 1")
part1(input, false) test Pair(56350L, "part 1")
part2(testInput, false) test Pair(2713310158L, "test 2 part 2")
part2(input) test Pair(13954061248L, "part 2")
}
| 0 | Kotlin | 0 | 0 | 631cbd22ca7bdfc8a5218c306402c19efd65330b | 5,369 | aoc-2022-kotlin | Apache License 2.0 |
src/Day13.kt | iam-afk | 572,941,009 | false | {"Kotlin": 33272} | sealed interface Packet : Comparable<Packet> {
@JvmInline
value class Integer(val data: Int) : Packet {
override fun compareTo(other: Packet): Int = when (other) {
is Integer -> data compareTo other.data
is List -> List(listOf(this)) compareTo other
}
}
@JvmInline
value class List(val data: kotlin.collections.List<Packet>) : Packet {
override fun compareTo(other: Packet): Int {
return when (other) {
is Integer -> this compareTo List(listOf(other))
is List -> {
val it = data.iterator()
val otherIt = other.data.iterator()
while (it.hasNext() && otherIt.hasNext()) {
val compare = it.next() compareTo otherIt.next()
if (compare != 0) return compare
}
if (!it.hasNext() && !otherIt.hasNext()) return 0
if (otherIt.hasNext()) -1 else 1
}
}
}
}
companion object {
class Parser(val input: String) {
private var lookAt: Int = 0
private fun peek(): Char = input[lookAt]
private fun next() = if (lookAt + 1 < input.length) input[++lookAt] else '\n'
private fun skip(char: Char) {
check(peek() == char)
++lookAt
}
fun parse(): Packet {
when (val current = peek()) {
'[' -> {
val data = mutableListOf<Packet>()
if (next() != ']') {
while (peek() != ']') {
data += parse()
if (peek() == ']') break
skip(',')
}
}
skip(']')
return List(data)
}
in '0'..'9' -> {
var data = current.digitToInt()
while (next().isDigit()) {
data = data * 10 + peek().digitToInt()
}
return Integer(data)
}
else -> {
error("unknown token at index $lookAt: $input")
}
}
}
}
}
}
fun main() {
fun String.parse() = Packet.Companion.Parser(this).parse()
fun part1(input: List<String>): Int = input.chunked(3).withIndex()
.filter { (_, chunk) ->
val (first, second, _) = chunk
first.parse() < second.parse()
}
.sumOf { (index, _) -> index + 1 }
fun part2(input: List<String>): Int {
val d1 = "[[6]]".parse()
val d2 = "[[2]]".parse()
val signals = mutableListOf(d1, d2)
for (line in input) {
if (line.isNotEmpty()) {
signals += line.parse()
}
}
signals.sort()
return (signals.indexOf(d1) + 1) * (signals.indexOf(d2) + 1)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b30c48f7941eedd4a820d8e1ee5f83598789667b | 3,466 | aockt | Apache License 2.0 |
src/Day04.kt | gylee2011 | 573,544,473 | false | {"Kotlin": 9419} | import kotlin.math.max
import kotlin.math.min
fun main() {
fun part1(input: List<String>): Int {
return input
.map {
it.split(',')
}
.map { (elf1, elf2) ->
val range1 = elf1.toRange()
val range2 = elf2.toRange()
val newStart = min(range1.first, range2.first)
val newEnd = max(range1.last, range2.last)
val newRange = newStart..newEnd
(newRange == range1 || newRange == range2)
}
.count { it }
}
fun part2(input: List<String>): Int {
return input
.map {
it.split(',')
}
.map { elves ->
val sorted = elves.map { it.toRange() }.sortedBy { it.first }
val (elf1, elf2) = sorted
(elf1.last >= elf2.first)
}
.count { it }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
fun String.toRange(): IntRange = split('-')
.let { (start, end) ->
start.toInt()..end.toInt()
} | 0 | Kotlin | 0 | 0 | 339e0895fd2484b7f712b966a0dae8a4cfebc2fa | 1,336 | aoc2022-kotlin | Apache License 2.0 |
src/day09/Day09.kt | jacobprudhomme | 573,057,457 | false | {"Kotlin": 29699} | import java.io.File
import java.lang.IllegalArgumentException
import kotlin.math.abs
typealias Pos = Pair<Int, Int>
enum class Direction {
UP,
RIGHT,
DOWN,
LEFT,
}
fun main() {
fun readInput(name: String) = File("src/day09", name)
.readLines()
fun convertToDirection(dirStr: String): Direction =
when (dirStr) {
"U" -> Direction.UP
"R" -> Direction.RIGHT
"D" -> Direction.DOWN
"L" -> Direction.LEFT
else -> throw IllegalArgumentException("We should never get here")
}
fun moveHead(headPos: Pos, dir: Direction): Pos =
when (dir) {
Direction.UP -> headPos.let { (x, y) -> Pair(x, y+1) }
Direction.RIGHT -> headPos.let { (x, y) -> Pair(x+1, y) }
Direction.DOWN -> headPos.let { (x, y) -> Pair(x, y-1) }
Direction.LEFT -> headPos.let { (x, y) -> Pair(x-1, y) }
}
fun moveTail(headPos: Pos, tailPos: Pos): Pos {
val horizontalDist = abs(headPos.first - tailPos.first)
val verticalDist = abs(headPos.second - tailPos.second)
return if ((horizontalDist == 2) or (verticalDist == 2)) {
if (horizontalDist == 0) {
tailPos.let { (x, y) -> Pair(x, (y + headPos.second).div(2)) }
} else if (verticalDist == 0) {
tailPos.let { (x, y) -> Pair((x + headPos.first).div(2), y) }
} else if (horizontalDist == 1) {
tailPos.let { (_, y) -> Pair(headPos.first, (y + headPos.second).div(2)) }
} else if (verticalDist == 1) {
tailPos.let { (x, _) -> Pair((x + headPos.first).div(2), headPos.second) }
} else {
tailPos.let { (x, y) -> Pair((x + headPos.first).div(2), (y + headPos.second).div(2)) }
}
} else {
tailPos
}
}
fun move(headPos: Pos, tailPos: Pos, dir: Direction): Pair<Pos, Pos> {
val nextHeadPos = moveHead(headPos, dir)
val nextTailPos = moveTail(nextHeadPos, tailPos)
return Pair(nextHeadPos, nextTailPos)
}
fun part1(input: List<String>): Int {
var currHeadPosition = Pair(0, 0)
var currTailPosition = Pair(0, 0)
val seenPositions = mutableSetOf(currTailPosition)
for (line in input) {
val (dir, steps) = line.split(" ").let { (dirStr, stepsStr, _) ->
Pair(convertToDirection(dirStr), stepsStr.toInt())
}
repeat(steps) {
val (nextHeadPosition, nextTailPosition) = move(currHeadPosition, currTailPosition, dir)
currHeadPosition = nextHeadPosition
currTailPosition = nextTailPosition
seenPositions.add(currTailPosition)
}
}
return seenPositions.count()
}
fun part2(input: List<String>): Int {
val currPositions = MutableList(10) { Pair(0, 0) }
val seenPositions = mutableSetOf(currPositions.last())
for (line in input) {
val (dir, steps) = line.split(" ").let { (dirStr, stepsStr, _) ->
Pair(convertToDirection(dirStr), stepsStr.toInt())
}
repeat(steps) {
currPositions[0] = moveHead(currPositions[0], dir)
for (knotIndex in currPositions.indices.drop(1)) {
currPositions[knotIndex] = moveTail(currPositions[knotIndex-1], currPositions[knotIndex])
}
seenPositions.add(currPositions.last())
}
}
return seenPositions.count()
}
val input = readInput("input")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 1 | 9c2b080aea8b069d2796d58bcfc90ce4651c215b | 3,731 | advent-of-code-2022 | Apache License 2.0 |
2021/src/main/kotlin/day2_func.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parser
import utils.Solution
import utils.cut
import utils.mapItems
fun main() {
Day2Func.run()
}
object Day2Func : Solution<List<Pair<Day2Func.Direction, Int>>>() {
override val name = "day2"
override val parser = Parser.lines.mapItems { line -> line.cut(" ", Direction::valueOf, String::toInt) }
enum class Direction { forward, down, up }
data class State(val horizontal: Int = 0, val depth: Int = 0, val aim: Int = 0)
override fun part1(input: List<Pair<Direction, Int>>): Number {
val final = input.fold(State()) { state, cmd ->
when (cmd.first) {
Direction.forward -> state.copy(horizontal = state.horizontal + cmd.second)
Direction.down -> state.copy(depth = state.depth + cmd.second)
Direction.up -> state.copy(depth = state.depth - cmd.second)
}
}
return final.depth * final.horizontal
}
override fun part2(input: List<Pair<Direction, Int>>): Number? {
val final = input.fold(State()) { state, cmd ->
when (cmd.first) {
Direction.forward -> state.copy(
horizontal = state.horizontal + cmd.second,
depth = state.depth + state.aim * cmd.second
)
Direction.down -> state.copy(aim = state.aim + cmd.second)
Direction.up -> state.copy(aim = state.aim - cmd.second)
}
}
return final.depth * final.horizontal
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 1,374 | aoc_kotlin | MIT License |
src/Day04.kt | calindumitru | 574,154,951 | false | {"Kotlin": 20625} | fun main() {
val part1 = Implementation(
question = "In how many assignment pairs does one range fully contain the other?",
expectedAnswerForExample = 2
) { lines ->
val assignments = lines.map { convert(it) }
return@Implementation assignments.filter { it.fullyOverlaps() }.size
}
val part2 = Implementation(
question = "In how many assignment pairs do the ranges overlap?",
expectedAnswerForExample = 4
) { lines ->
val assignments = lines.map { convert(it) }
return@Implementation assignments.filter { it.havingOverlap() }.size
}
OhHappyDay(4, part1, part2).checkResults()
}
private fun convert(line: String): Assignment {
val (r1, r2) = line.split(",").toPair()
return Assignment(toElfSection(r1), toElfSection(r2))
}
private fun toElfSection(r: String): ElfSection {
val (low, high) = r.split("-").toPair()
return ElfSection(low.toInt(), high.toInt())
}
private class Assignment(private val elf1: ElfSection, private val elf2: ElfSection) {
fun fullyOverlaps(): Boolean {
return elf1.contains(elf2) || elf2.contains(elf1)
}
fun havingOverlap(): Boolean {
return elf1.overlaps(elf2)
}
}
private class ElfSection(private val min: Int, private val max: Int) {
fun contains(second: ElfSection): Boolean {
return this.min >= second.min && this.max <= second.max
}
fun overlaps(second: ElfSection): Boolean {
return this.min <= second.max && this.max >= second.min
}
}
| 0 | Kotlin | 0 | 0 | d3cd7ff5badd1dca2fe4db293da33856832e7e83 | 1,545 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/days/model/Oasis.kt | errob37 | 726,532,024 | false | {"Kotlin": 29748, "Shell": 408} | package days.model
class Oasis(
private val input: List<String>,
private val predictionMode: PredictionMode
) {
fun predictionSum() = input
.map { it.split(" ").map { s -> s.toLong() } }
.map { Report(it, predictionMode) }
.sumOf { it.predictValue() }
}
enum class PredictionMode { BACKWARD, FORWARD }
data class Report(
val history: List<Long>,
val predictionMode: PredictionMode
) {
fun predictValue() =
if (predictionMode == PredictionMode.FORWARD) predictNextValue()
else predictFirstValue()
private fun predictFirstValue(): Long {
val cumulated = reduce()
val inversed = cumulated.asReversed()
inversed.forEachIndexed { index, it ->
if (index == 0 || index == 1) inversed[index].add(0, it.first())
else {
inversed[index].add(0, inversed[index].first() - inversed[index - 1].first())
}
}
return inversed.last().first()
}
private fun predictNextValue(): Long {
val cumulated = reduce()
val inversed = cumulated.asReversed()
inversed.forEachIndexed { index, it ->
if (index == 0 || index == 1) inversed[index].add(it.last())
else {
inversed[index].add(inversed[index].last() + inversed[index - 1].last())
}
}
return inversed.last().last()
}
private fun reduce(): MutableList<MutableList<Long>> {
var current = history
val cumulated = mutableListOf(current.toMutableList())
while (!current.all { it == 0L }) {
current = current.mapIndexedNotNull { index, _ ->
if (index == current.size - 1) null
else {
current[index + 1] - current[index]
}
}.also { cumulated.add(it.toMutableList()) }
}
return cumulated
}
}
| 0 | Kotlin | 0 | 0 | 79db6f0f56d207b68fb89425ad6c91667a84d60f | 1,928 | adventofcode-2023 | Apache License 2.0 |
src/main/kotlin/_2018/Day6.kt | thebrightspark | 227,161,060 | false | {"Kotlin": 548420} | package _2018
import aocRun
import forEachPoint
import java.awt.Point
import java.awt.Rectangle
import kotlin.math.abs
fun main() {
aocRun(puzzleInput) { input ->
val locations = processLocations(input)
// Create borders - we'll use border1 but then check against border2 later
val border1 = createBorder(locations)
println("Created border $border1")
border1.grow(2, 2)
println("Expanded border $border1")
val border2 = Rectangle(border1)
border1.grow(10, 10)
// Give the coord for each point an ID
var nextId = 0
val locationsWithId = locations.associateWith { nextId++ }
val grid = mutableMapOf<Point, Int>()
val sizes = mutableMapOf<Int, Int>()
// Calculate manhattan distance for all points within border1
border1.forEachPoint { x, y ->
val p = Point(x, y)
val distances = locationsWithId.map { it.value to manhattanDistance(it.key, p) }
val nearest = distances.minByOrNull { it.second }!!
if (distances.count { it.second == nearest.second } == 1) {
grid[p] = nearest.first
sizes.compute(nearest.first) { _, count -> (count ?: 0) + 1 }
}
}
println("Calculated closest locations for all grid coords")
// Remove outliers that expand infinitely
val smallerGrid = grid.filterKeys { border2.contains(it) }
val smallerSizes = smallerGrid.entries.map { it.value }.groupingBy { it }.eachCount()
val filteredSizes = sizes.toMutableMap()
filteredSizes.entries.removeIf { smallerSizes[it.key] != it.value }
println("Removed ${sizes.size - filteredSizes.size} outliers that expand infinitely")
println(
"Sizes of remaining IDs:\n${filteredSizes.entries.sortedBy { it.value }.joinToString(
"\n",
transform = { "${it.key} -> ${it.value}" })}"
)
return@aocRun filteredSizes.maxByOrNull { it.value }!!.value
}
aocRun(puzzleInput) { input ->
val locations = processLocations(input)
val border = createBorder(locations)
var count = 0
border.forEachPoint { x, y ->
val point = Point(x, y)
val sumOfDistances = locations.map { manhattanDistance(it, point) }.sum()
if (sumOfDistances < 10000)
count++
}
return@aocRun count
}
}
private fun processLocations(input: String): List<Point> = input.split("\n").map {
val parts = it.split(",")
return@map Point(parts[0].trim().toInt(), parts[1].trim().toInt())
}
private fun createBorder(locations: List<Point>): Rectangle {
val locXs = locations.map { it.x }
val minX = locXs.minOrNull()!!
val maxX = locXs.maxOrNull()!!
val locYs = locations.map { it.y }
val minY = locYs.minOrNull()!!
val maxY = locYs.maxOrNull()!!
return Rectangle(minX, minY, maxX - minX, maxY - minY)
}
private fun manhattanDistance(point1: Point, point2: Point): Int = abs(point1.x - point2.x) + abs(point1.y - point2.y)
private val puzzleInput = """
137, 282
229, 214
289, 292
249, 305
90, 289
259, 316
134, 103
96, 219
92, 308
269, 59
141, 132
71, 200
337, 350
40, 256
236, 105
314, 219
295, 332
114, 217
43, 202
160, 164
245, 303
339, 277
310, 316
164, 44
196, 335
228, 345
41, 49
84, 298
43, 51
158, 347
121, 51
176, 187
213, 120
174, 133
259, 263
210, 205
303, 233
265, 98
359, 332
186, 340
132, 99
174, 153
206, 142
341, 162
180, 166
152, 249
221, 118
95, 227
152, 186
72, 330
""".trimIndent()
| 0 | Kotlin | 0 | 0 | ac62ce8aeaed065f8fbd11e30368bfe5d31b7033 | 3,607 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/Day02.kt | juliantoledo | 570,579,626 | false | {"Kotlin": 34375} | fun main() {
/*
A for Rock, B for Paper, and C for Scissors
X for Rock, Y for Paper, and Z for Scissors
1 for Rock, 2 for Paper, and 3 for Scissors) plus the score for the outcome of the round
(0 if you lost, 3 if the round was a draw, and 6 if you won).
X means you need to lose, Y means you need to end the round in a draw, and Z means you need to win.
*/
fun gamesList(input: List<String>): List<Pair<String, String>> {
var games = mutableListOf<Pair<String, String>>()
input.forEach { line ->
line.splitTo(" ") { a, b ->
games.add(Pair(a, b))
}
}
return games
}
fun part1(games: List<Pair<String, String>>): Int {
var totalScore = 0
games.forEach { game ->
var score = 0
when (game.first) {
"A" -> when (game.second) {
"X" -> score += 3
"Y" -> score += 6
"Z" -> score += 0
}
"B" -> when (game.second) {
"X" -> score += 0
"Y" -> score += 3
"Z" -> score += 6
}
"C" -> when (game.second) {
"X" -> score += 6
"Y" -> score += 0
"Z" -> score += 3
}
}
when (game.second) {
"X" -> score += 1
"Y" -> score += 2
"Z" -> score += 3
}
//println("$game $score")
totalScore += score
}
return totalScore
}
fun part2(games: List<Pair<String, String>>): List<Pair<String, String>> {
var newGames = mutableListOf<Pair<String, String>>()
games.forEach { game ->
var newSecond = game.second
when (game.first) {
// A for Rock, B for Paper, and C for Scissors
// X for Rock, Y for Paper, and Z for Scissors
// X means you need to lose, Y means you need to end the round in a draw, and Z means you need to win.
"A" -> when (game.second) {
"X" -> newSecond = "Z"
"Y" -> newSecond = "X"
"Z" -> newSecond = "Y"
}
"C" -> when (game.second) {
"X" -> newSecond = "Y"
"Y" -> newSecond = "Z"
"Z" -> newSecond = "X"
}
}
newGames.add(Pair(game.first, newSecond))
}
return newGames
}
fun part2(elfCalories: MutableList<Int>): Int {
elfCalories.sortDescending()
return elfCalories[0] + elfCalories[1] + elfCalories[2]
}
var input = readInput("Day02_test")
var games = gamesList(input)
println( part1(games))
input = readInput("Day02_input")
games = gamesList(input)
println( part1(games))
input = readInput("Day02_test")
games = gamesList(input)
println( part1(part2(games)))
input = readInput("Day02_input")
games = gamesList(input)
println( part1(part2(games)))
}
| 0 | Kotlin | 0 | 0 | 0b9af1c79b4ef14c64e9a949508af53358335f43 | 3,167 | advent-of-code-kotlin-2022 | Apache License 2.0 |
app/src/main/kotlin/de/tobiasdoetzer/aoc2021/Day5.kt | dobbsy | 433,868,809 | false | {"Kotlin": 13636} | package de.tobiasdoetzer.aoc2021
private fun part1(input: List<String>): Int {
val ventMap = VentMap()
for (s in input) {
val (p1String, p2String) = s.split(" -> ")
val (p1X, p1Y) = p1String.split(',').map(String::toInt)
val (p2X, p2Y) = p2String.split(',').map(String::toInt)
if (p1X == p2X || p1Y == p2Y) {
ventMap.addLine(Point(p1X, p1Y), Point(p2X, p2Y))
}
}
return ventMap.map.filter { it.value > 1 }.values.size
}
private fun part2(input: List<String>): Int {
val ventMap = VentMap()
for (s in input) {
val (p1String, p2String) = s.split(" -> ")
ventMap.addLine(Point.createPointFromString(p1String), Point.createPointFromString(p2String))
}
return ventMap.map.filter { it.value > 1 }.values.size
}
private fun main() {
val input = readInput("day5_input.txt")
println("The solution of part 1 is: ${part1(input)}")
println("The solution of part 2 is: ${part2(input)}")
}
data class Point(val x: Int, val y: Int) {
companion object {
fun createPointFromString(s: String): Point {
val (xString, yString) = s.split(',')
return Point(xString.toInt(), yString.toInt())
}
}
}
/**
* Represents a map of hydrothermal vents.
*
* The [map] property contains the actual map,
* the [addLine] function is used to add a new line of vents to the map.
*/
class VentMap {
private val _map: MutableMap<Point, Int> = HashMap()
/**
* Returns a read-only map where the keys are [Point]s through which
* at least one line of hydrothermal vents goes, and the keys is the
* total number of lines of vents that go through the respective Point.
*/
val map: Map<Point, Int>
get() = _map
/**
* Adds a line of vents between [p1] and [p2] in the map.
*
* Only call this once for each line of vents detected,
* otherwise the same line will be added multiple times
*/
fun addLine(p1: Point, p2: Point) {
for (point in getPointsOnLine(p1, p2)) {
_map[point] = _map[point]?.inc() ?: 1
}
}
// Returns a set of all points on the line between p1 and p2
// Only horizontal, vertical and diagonal at an angle of 45° can be computed
private fun getPointsOnLine(p1: Point, p2: Point): Set<Point> {
val retVal = mutableSetOf<Point>()
if (p1.x == p2.x) {
if (p1.y > p2.y) {
for (i in p2.y..p1.y) retVal += Point(p1.x, i)
} else {
for (i in p1.y..p2.y) retVal += Point(p1.x, i)
}
} else if (p1.y == p2.y) {
if (p1.x > p2.x) {
for (i in p2.x..p1.x) retVal += Point(i, p1.y)
} else {
for (i in p1.x..p2.x) retVal += Point(i, p1.y)
}
} else {
when {
p1.x > p2.x && p1.y > p2.y -> for (i in 0..(p1.x - p2.x)) {
retVal += Point(p1.x - i, p1.y - i)
}
p1.x > p2.x -> for (i in 0..(p1.x - p2.x)) { // p1.y < p2.y must also be true
retVal += Point(p1.x - i, p1.y + i)
}
// from her on forward, p1.x is guaranteed to be smaller than p2.x
p1.y > p2.y -> for (i in 0..(p2.x - p1.x)) {
retVal += Point(p1.x + i, p1.y - i)
}
else -> for (i in 0..(p2.x - p1.x)) {
retVal += Point(p1.x + i, p1.y + i)
}
}
}
return retVal
}
}
| 0 | Kotlin | 0 | 0 | 28f57accccb98d8c2949171cd393669e67789d32 | 3,604 | AdventOfCode2021 | Apache License 2.0 |
src/Day09.kt | jwklomp | 572,195,432 | false | {"Kotlin": 65103} | data class Pos(val x: Int, val y: Int)
data class Change(val x: Int, val y: Int)
data class MoveData(val knotPositions: MutableList<Pos>, var visited: MutableList<Pos>)
val directions = listOf("L", "R", "U", "D")
val directionTranslations = listOf(Change(-1, 0), Change(1, 0), Change(0, 1), Change(0, -1))
val sp = Pos(0, 0)
fun main() {
fun toMove(str: String): List<String> = str.split(" ").run { List(this[1].toInt()) { this[0] } }
// TODO rewrite to shorter using Chebyshev distance: https://iq.opengenus.org/euclidean-vs-manhattan-vs-chebyshev-distance/
fun determineTailChangeBasedOnPosDiff(headPos: Pos, oldTailPos: Pos): Change {
val diff = Pos(headPos.x - oldTailPos.x, headPos.y - oldTailPos.y)
val pd: Change =
when (diff.x) {
-2 -> when (diff.y) {
-2, -1 -> Change(-1, -1)
0 -> Change(-1, 0)
1, 2 -> Change(-1, 1)
else -> Change(0, 0)
}
-1 -> when (diff.y) {
-2 -> Change(-1, -1)
2 -> Change(-1, 1)
else -> Change(0, 0)
}
0 -> when (diff.y) {
-2 -> Change(0, -1)
2 -> Change(0, 1)
else -> Change(0, 0)
}
1 -> when (diff.y) {
-2 -> Change(1, -1)
2 -> Change(1, 1)
else -> Change(0, 0)
}
2 -> when (diff.y) {
-2, -1 -> Change(1, -1)
0 -> Change(1, 0)
1, 2 -> Change(1, 1)
else -> Change(0, 0)
}
else -> Change(0, 0)
}
return pd
}
fun doMoveForKnots(moveData: MoveData, move: String): MoveData {
fun doMoveForKnotPair(change: Change, i: Int): MoveData {
val oldHeadPos = moveData.knotPositions[i]
val oldTailPos = moveData.knotPositions[i + 1]
val newHeadPos = if (i == 0) Pos(oldHeadPos.x + change.x, oldHeadPos.y + change.y) else oldHeadPos
val newChange = determineTailChangeBasedOnPosDiff(newHeadPos, oldTailPos)
val newTailPos = Pos(oldTailPos.x + newChange.x, oldTailPos.y + newChange.y)
moveData.knotPositions[i] = newHeadPos
moveData.knotPositions[i + 1] = newTailPos
return if (i == moveData.knotPositions.size - 2) {
moveData.visited.add(newTailPos)
moveData
} else {
doMoveForKnotPair(newChange, i + 1)
}
}
val initialChange = directionTranslations[directions.indexOf(move)]
return doMoveForKnotPair(initialChange, 0)
}
fun part1(input: List<String>): Int {
val moves = input.flatMap { toMove(it) }
return moves.fold(MoveData(mutableListOf(sp, sp), mutableListOf(sp))) { acc: MoveData, move: String ->
return@fold doMoveForKnots(acc, move)
}.visited.toSet().size
}
fun part2(input: List<String>): Int {
val moves = input.flatMap { toMove(it) }
return moves.fold(
MoveData(mutableListOf(sp, sp, sp, sp, sp, sp, sp, sp, sp, sp), mutableListOf(sp))
) { acc: MoveData, move: String ->
return@fold doMoveForKnots(acc, move)
}.visited.toSet().size
}
val testInput = readInput("Day09_test")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1b1121cfc57bbb73ac84a2f58927ab59bf158888 | 3,668 | aoc-2022-in-kotlin | Apache License 2.0 |
src/2023/Day25.kt | nagyjani | 572,361,168 | false | {"Kotlin": 369497} | package `2023`
import java.io.File
import java.util.*
fun main() {
Day25().solve()
}
class Day25 {
val input1 = """
jqt: rhn xhk nvd
rsh: frs pzl lsr
xhk: hfx
cmg: qnr nvd lhk bvb
rhn: xhk bvb hfx
bvb: xhk hfx
pzl: lsr hfx nvd
qnr: nvd
ntq: jqt hfx bvb xhk
nvd: lhk
lsr: lhk
rzs: qnr cmg lsr rsh
frs: qnr lhk lsr
""".trimIndent()
val input2 = """
""".trimIndent()
// for one node
// the shortest path to another (~1500)
// remove one node from the path (K)
// find the shortest again (3)
fun Map<String, Set<String>>.findPath(source: String, target: String, removed: Set<Pair<String, String>>): List<String>? {
return findPath(target, listOf(source), removed)
}
fun Map<String, Set<String>>.findPath(target: String, path: List<String>, removed: Set<Pair<String, String>>): List<String>? {
val nextNodes = get(path.last())!!
if (nextNodes.contains(target)) {
return path.toMutableList().apply { add(target)}
}
for (n in nextNodes) {
if (path.contains(n)) {
continue
}
if (removed.contains(path.last() to n)) {
continue
}
val r = findPath(target, path.toMutableList().apply { add(n) }, removed)
if (r == null) {
continue
}
return r
}
return null
}
fun Map<String, Set<String>>.findPath2(source: String, target: String, removed: Set<Pair<String, String>>): Pair<List<Pair<String, String>>?,Int> {
val paths = mutableMapOf<String, String>()
val toCheck = get(source)!!.map { it to source }.filter{!removed.contains(it) && !removed.contains(it.second to it.first)}.toMap().toMutableMap()
if (removed.size == 3 && (removed.contains("nvd" to "jqt") || removed.contains("jqt" to "nvd")) && (removed.contains("pzl" to "hfx") || removed.contains("hfx" to "pzl")) && (removed.contains("cmg" to "bvb") || removed.contains("bvb" to "cmg"))
) {
Unit
}
while (toCheck.isNotEmpty()) {
val n = toCheck.keys.first()
val s = toCheck[n]!!
toCheck.remove(n)
if (paths.contains(n)) {
continue
}
paths[n] = s
get(n)!!.filter { it != source && !paths.contains(it) && !removed.contains(it to n) && !removed.contains(n to it) }.forEach { toCheck[it] = n }
}
if (paths.contains(target)) {
val r = mutableListOf<Pair<String,String>>()
var n = target
while (n != source) {
r.add(paths[n]!! to n)
n = paths[n]!!
}
return r.reversed() to paths.size
}
return null to paths.size
}
fun solve() {
val f = File("src/2023/inputs/day25.in")
val s = Scanner(f)
// val s = Scanner(input1)
// val s = Scanner(input2)
var sum = 0
var sum1 = 0
var lineix = 0
val lines = mutableListOf<String>()
val nodes = mutableMapOf<String, MutableSet<String>>()
while (s.hasNextLine()) {
lineix++
val line = s.nextLine().trim()
if (line.isEmpty()) {
continue
}
lines.add(line)
val t1 = line.split(Regex(": "))
val node = t1[0]
t1[1].split(" ").forEach {
if (nodes.contains(node)) {
nodes[node]!!.add(it)
} else {
nodes[node] = mutableSetOf(it)
}
if (nodes.contains(it)) {
nodes[it]!!.add(node)
} else {
nodes[it] = mutableSetOf(node)
}
}
}
val e = nodes.findPath2(nodes.keys.first(), nodes.keys.last(), setOf())
val source = nodes.keys.first()
val targets = nodes.keys.toMutableList().apply{remove(source)}
main@ for (t in targets) {
val (d, _) = nodes.findPath2(source, t, setOf())
for (removed1 in d!!) {
val (d1, _) = nodes.findPath2(source, t, setOf(removed1))
if (t == "nvd" && (removed1 == "nvd" to "jqt" || removed1 == "jqt" to "nvd")) {
Unit
}
if (d1 == null) {
println("1: $removed1")
continue
}
for (removed2 in d1!!) {
val (d2, _) = nodes.findPath2(source, t, setOf(removed1, removed2))
if (t == "nvd" && (removed1 == "nvd" to "jqt" || removed1 == "jqt" to "nvd") && (removed2 == "pzl" to "hfx" || removed2 == "hfx" to "pzl")) {
Unit
}
if (d2 == null) {
println("2: $removed1 $removed2")
continue
}
for (removed3 in d2!!) {
val (d3, s3) = nodes.findPath2(source, t, setOf(removed1, removed2, removed3))
if (d3 == null) {
val d4 = nodes.findPath2(source, t, setOf(removed1, removed2, removed3))
println("3: $removed1 $removed2 $removed3 ($s3) (${(s3 + 1) * (nodes.size - s3 -1)})")
break@main
}
}
}
}
}
print("$sum $sum1\n")
}
} | 0 | Kotlin | 0 | 0 | f0c61c787e4f0b83b69ed0cde3117aed3ae918a5 | 5,693 | advent-of-code | Apache License 2.0 |
kotlin/src/katas/kotlin/leetcode/array_to_bst/ArrayToBST.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.array_to_bst
import katas.kotlin.leetcode.TreeNode
import datsok.shouldEqual
import org.junit.Test
/**
* https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
*/
class ArrayToBSTTests {
@Test fun `convert sorted array to balanced BST`() {
arrayOf(1).toBST_() shouldEqual TreeNode(1)
arrayOf(1, 2).toBST_() shouldEqual TreeNode(2, TreeNode(1))
arrayOf(1, 2, 3).toBST_() shouldEqual TreeNode(2, TreeNode(1), TreeNode(3))
arrayOf(1, 2, 3, 4).toBST_() shouldEqual TreeNode(3, TreeNode(2, TreeNode(1)), TreeNode(4))
arrayOf(1, 2, 3, 4, 5).toBST_() shouldEqual
TreeNode(3,
TreeNode(2, TreeNode(1)),
TreeNode(4, null, TreeNode(5))
)
arrayOf(1, 2, 3, 4, 5, 6).toBST_() shouldEqual
TreeNode(4,
TreeNode(3, TreeNode(2, TreeNode(1))),
TreeNode(5, null, TreeNode(6))
)
arrayOf(1, 2, 3, 4, 5, 6, 7).toBST_() shouldEqual
TreeNode(4,
TreeNode(3, TreeNode(2, TreeNode(1))),
TreeNode(5, null, TreeNode(6, null, TreeNode(7)))
)
}
@Test fun `convert sorted array to filled balanced BST`() {
arrayOf(1).toBST() shouldEqual TreeNode(1)
arrayOf(1, 2).toBST() shouldEqual TreeNode(2, TreeNode(1))
arrayOf(1, 2, 3).toBST() shouldEqual TreeNode(2, TreeNode(1), TreeNode(3))
arrayOf(1, 2, 3, 4).toBST() shouldEqual TreeNode(3, TreeNode(2, TreeNode(1)), TreeNode(4))
arrayOf(1, 2, 3, 4, 5).toBST() shouldEqual
TreeNode(3,
TreeNode(2, TreeNode(1)),
TreeNode(5, TreeNode(4))
)
arrayOf(1, 2, 3, 4, 5, 6).toBST() shouldEqual
TreeNode(4,
TreeNode(2, TreeNode(1), TreeNode(3)),
TreeNode(6, TreeNode(5))
)
arrayOf(1, 2, 3, 4, 5, 6, 7).toBST() shouldEqual
TreeNode(4,
TreeNode(2, TreeNode(1), TreeNode(3)),
TreeNode(6, TreeNode(5), TreeNode(7))
)
}
}
private fun Array<Int>.toBST(from: Int = 0, to: Int = size): TreeNode? {
if (to <= from) return null
val mid = (from + to) / 2
val node = TreeNode(this[mid])
node.left = toBST(from, mid)
node.right = toBST(mid + 1, to)
return node
}
private fun Array<Int>.toBST_(): TreeNode {
val midIndex = size / 2
val node = TreeNode(this[midIndex])
(midIndex - 1 downTo 0).forEach { i -> node.add(this[i]) }
(midIndex + 1 until size).forEach { i -> node.add(this[i]) }
return node
}
private fun TreeNode.add(value: Int) {
if (value <= this.value) {
if (left == null) left = TreeNode(value)
else left!!.add(value)
} else {
if (right == null) right = TreeNode(value)
else right!!.add(value)
}
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 2,907 | katas | The Unlicense |
kotlin/src/x2022/day2b/Day02b.kt | freeformz | 573,924,591 | false | {"Kotlin": 43093, "Go": 7781} | package day2b
import readInput
enum class Outcome(val input: Char, val value: Int) {
Lose('X', 0) {
override fun score(op: Play): Int = op.winsAgainst().value + value
},
Draw('Y', 3) {
override fun score(op: Play): Int = op.value + value
},
Win('Z', 6) {
override fun score(op: Play): Int = op.loosesAgainst().value + value
};
abstract fun score(op: Play): Int
}
enum class Play(val value: Int, val opInput: Char) {
Rock(1, 'A') {
override fun beats(o: Play) = o == Rock.winsAgainst()
override fun winsAgainst() = Scissors
override fun loosesAgainst(): Play = Paper
},
Paper(2, 'B') {
override fun beats(o: Play) = o == Paper.winsAgainst()
override fun winsAgainst() = Rock
override fun loosesAgainst(): Play = Scissors
},
Scissors(3, 'C') {
override fun beats(o: Play) = o == Scissors.winsAgainst()
override fun winsAgainst() = Paper
override fun loosesAgainst(): Play = Rock
};
abstract fun winsAgainst(): Play
abstract fun loosesAgainst(): Play
abstract fun beats(o: Play): Boolean
}
fun main() {
val sum = readInput("day2").sumOf { input ->
val op = Play.values().first { pv ->
pv.opInput == input.first()
}
val outcome = Outcome.values().first { out ->
out.input == input.last()
}
outcome.score(op)
}
println(sum)
}
| 0 | Kotlin | 0 | 0 | 5110fe86387d9323eeb40abd6798ae98e65ab240 | 1,464 | adventOfCode | Apache License 2.0 |
src/main/kotlin/dijkstra/dijkstra.kt | vw-anton | 574,945,231 | false | {"Kotlin": 33295} | fun <T, E: Number> shortestPath(graph: Graph<T, E>, from: T, destination: T): Pair<List<T>, Double> {
return dijkstra(graph, from, destination)[destination] ?: (emptyList<T>() to Double.POSITIVE_INFINITY)
}
private fun <T, E : Number> dijkstra(graph: Graph<T, E>, from: T, destination: T? = null): Map<T, Pair<List<T>, Double>> {
val unvisitedSet = graph.getAllVertices().toMutableSet()
val distances = graph.getAllVertices().map { it to Double.POSITIVE_INFINITY }.toMap().toMutableMap()
val paths = mutableMapOf<T, List<T>>()
distances[from] = 0.0
var current = from
while (unvisitedSet.isNotEmpty() && unvisitedSet.contains(destination)) {
graph.adjacentVertices(current).forEach { adjacent ->
val distance = graph.getDistance(current, adjacent).toDouble()
if (distances[current]!! + distance < distances[adjacent]!!) {
distances[adjacent] = distances[current]!! + distance
paths[adjacent] = paths.getOrDefault(current, listOf(current)) + listOf(adjacent)
}
}
unvisitedSet.remove(current)
if (current == destination || unvisitedSet.all { distances[it]!!.isInfinite() }) {
break
}
if (unvisitedSet.isNotEmpty()) {
current = unvisitedSet.minBy { distances[it]!! }!!
}
}
return paths.mapValues { entry -> entry.value to distances[entry.key]!! }
} | 0 | Kotlin | 0 | 0 | a823cb9e1677b6285bc47fcf44f523e1483a0143 | 1,436 | aoc2022 | The Unlicense |
day04/src/main/kotlin/Main.kt | ickybodclay | 159,694,344 | false | null | import java.io.File
data class Time(val year:Int, val month: Int, val day: Int, val hour: Int, val min: Int)
data class Record(val time: Time, var guardId: Int, val action: Action)
enum class Action { START, SLEEP, WAKE }
data class Guard(val guardId: Int, var minutesSleeping: Int, val sleepList: ArrayList<Sleep>)
data class Sleep(val time: Time, val startMin: Int, val endMin: Int)
fun main() {
val input = File(ClassLoader.getSystemResource("input.txt").file)
// Write solution here!Sample Text
//[1518-11-01 00:00] Guard #10 begins shift
//[1518-11-01 00:05] falls asleep
//[1518-11-01 00:25] wakes up
val recordRegex = Regex("""\[(\d+)-(\d+)-(\d+) (\d+):(\d+)] (Guard #(\d+) begins shift|falls asleep|wakes up)""")
val recordList = ArrayList<Record>()
input.readLines().map {
val recordResult = recordRegex.matchEntire(it)!!
val time = Time(
recordResult.groups[1]!!.value.toInt(),
recordResult.groups[2]!!.value.toInt(),
recordResult.groups[3]!!.value.toInt(),
recordResult.groups[4]!!.value.toInt(),
recordResult.groups[5]!!.value.toInt())
var guardId = -1
val actionStr = recordResult.groups[6]!!.value
var action = when (actionStr) {
"falls asleep" -> Action.SLEEP
"wakes up" -> Action.WAKE
else -> {
guardId = recordResult.groups[7]!!.value.toInt()
Action.START
}
}
val record = Record(time, guardId, action)
recordList.add(record)
}
val guardMap = HashMap<Int, Guard>()
var currentGuardId = 0
var startSleepMin = 0
recordList
.sortedWith(compareBy({ it.time.year }, { it.time.month }, { it.time.day }, { it.time.hour }, { it.time.min }))
.forEach {
if (it.guardId == -1) {
it.guardId = currentGuardId
}
else {
currentGuardId = it.guardId
if (!guardMap.containsKey(currentGuardId)) {
guardMap[currentGuardId] = Guard(currentGuardId, 0, ArrayList())
}
}
when (it.action) {
Action.SLEEP -> startSleepMin = it.time.min
Action.WAKE -> {
val sleepTime = it.time.min - startSleepMin
guardMap[currentGuardId]!!.minutesSleeping += sleepTime
guardMap[currentGuardId]!!.sleepList.add(Sleep(it.time, startSleepMin, it.time.min))
}
else -> {}
}
}
val lazyGuardId = guardMap.toSortedMap(compareBy { guardMap[it]!!.minutesSleeping }).lastKey()
println("Lazy boy = ${guardMap[lazyGuardId]}")
println("[part1]")
printMinuteSleptMost(guardMap[lazyGuardId]!!)
println("\n\n[part2]")
guardMap.map {
printMinuteSleptMost(it.value)
}
}
fun printMinuteSleptMost(guard: Guard) {
//println("\t\t000000000011111111112222222222333333333344444444445555555555")
//println("\t\t012345678901234567890123456789012345678901234567890123456789")
val minuteList = ArrayList<Int>()
for (i in 0 until 60) minuteList.add(0)
guard.sleepList.forEach {
//val month = "${it.time.month}".padStart(2, '0')
//val day = "${it.time.day}".padStart(2, '0')
//print ("$month-$day\t")
//for(i in 0 until it.startMin) print ('.')
for(i in it.startMin until it.endMin) {
minuteList[i]++
//print ('#')
}
//for(i in it.endMin until 60) print ('.')
//println()
}
var maxSleptMin = -1
var maxSleptCount = -1
minuteList.forEachIndexed { index, i ->
if (i > maxSleptCount) {
maxSleptMin = index
maxSleptCount = i
}
}
println("guardId = ${guard.guardId} max slept min = $maxSleptMin, max slept count = $maxSleptCount")
//println("[part1] solution = ${maxSleptMin * guard.guardId}")
}
| 0 | Kotlin | 0 | 0 | 9a055c79d261235cec3093f19f6828997b7a5fba | 4,123 | aoc2018 | Apache License 2.0 |
src/Day02.kt | MwBoesgaard | 572,857,083 | false | {"Kotlin": 40623} | import HandType.*
import OutcomeType.*
fun main() {
fun part1(input: List<String>): Int {
/*
* opponent, me
* Rock: A, X
* Paper: B, Y
* Scissors: C, Z
*
* Rock: 1 point
* Paper: 2 points
* Scissors: 3 points
*
* Win: 6 points
* Draw: 3 points
* Loss: 0 points
*/
var totalScore = 0
for (line in input) {
val hands = line.split(" ")
val opponentsHand: String = hands[0]
val myHand: String = hands[1]
val pointsByThrow = hashMapOf("A" to 1, "B" to 2, "C" to 3, "X" to 1, "Y" to 2, "Z" to 3)
val matchPoints = when (pointsByThrow[opponentsHand]!! - pointsByThrow[myHand]!!) {
2 -> 6 // Opponent has scissors I have rock, I win.
1 -> 0 // Opponent has paper, I have rock OR opponent has scissors, I have paper, they win.
0 -> 3 // We have the same, Draw.
-1 -> 6 // Opponent has rock. I have paper OR opponent has paper, I have scissors, I win.
-2 -> 0 // Opponent has rock, I have scissors, they win.
else -> {
throw Exception("Point difference out of range.")
}
}
totalScore += pointsByThrow[myHand]!! + matchPoints
}
return totalScore
}
fun part2(input: List<String>): Int {
var totalScore = 0
for (line in input) {
val handAndOutcome = line.split(" ")
val opponentsHand = HandType.fromInnerValue(handAndOutcome[0])
val outcome = OutcomeType.fromInnerValue(handAndOutcome[1])
val pointsByThrow = hashMapOf(ROCK to 1, PAPER to 2, SCISSOR to 3)
val pointsByOutcome = hashMapOf(LOSS to 0, DRAW to 3, WIN to 6)
val myHand = when (outcome) {
LOSS -> when (opponentsHand) {
ROCK -> SCISSOR
PAPER -> ROCK
SCISSOR -> PAPER
}
DRAW -> when (opponentsHand) {
ROCK -> ROCK
PAPER -> PAPER
SCISSOR -> SCISSOR
}
WIN -> when (opponentsHand) {
ROCK -> PAPER
PAPER -> SCISSOR
SCISSOR -> ROCK
}
}
totalScore += pointsByThrow[myHand]!! + pointsByOutcome[outcome]!!
}
return totalScore
}
printSolutionFromInputLines("Day02", ::part1)
printSolutionFromInputLines("Day02", ::part2)
}
enum class HandType(private val value: String) {
ROCK("A"),
PAPER("B"),
SCISSOR("C");
companion object {
fun fromInnerValue(type: String): HandType = values().first { it.value == type }
}
}
enum class OutcomeType(private val value: String) {
LOSS("X"),
DRAW("Y"),
WIN("Z");
companion object {
fun fromInnerValue(type: String): OutcomeType = values().first { it.value == type }
}
}
| 0 | Kotlin | 0 | 0 | 3bfa51af6e5e2095600bdea74b4b7eba68dc5f83 | 3,126 | advent_of_code_2022 | Apache License 2.0 |
src/Day04.kt | Jintin | 573,640,224 | false | {"Kotlin": 30591} | import kotlin.math.max
import kotlin.math.min
fun main() {
fun String.toPoints(): Pair<List<Int>, List<Int>> {
val pair = this.split(",")
val a = pair[0].split("-").map { it.toInt() }
val b = pair[1].split("-").map { it.toInt() }
return Pair(a, b)
}
fun part1(input: List<String>): Int {
return input.map(String::toPoints)
.count { (a, b) ->
max(a[1] - a[0] + 1, b[1] - b[0] + 1) == max(a[1], b[1]) - min(a[0], b[0]) + 1
}
}
fun part2(input: List<String>): Int {
return input.map(String::toPoints)
.count { (a, b) ->
a[1] - a[0] + 1 + b[1] - b[0] + 1 > max(a[1], b[1]) - min(a[0], b[0]) + 1
}
}
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | 4aa00f0d258d55600a623f0118979a25d76b3ecb | 841 | AdventCode2022 | Apache License 2.0 |
src/Day05.kt | rinas-ink | 572,920,513 | false | {"Kotlin": 14483} | import java.lang.Character.isUpperCase
fun main() {
fun parseStacks(input: List<String>): Pair<Int, List<ArrayList<Char>>> {
var bottom = 0
while (input[bottom].contains("[")) bottom++
val numberOfStacks = input[bottom].split(' ').filter { it.isNotEmpty() }.size
// assert(numberOfStacks == 9)
val stacks = List<ArrayList<Char>>(numberOfStacks) { ArrayList() }
for (i in numberOfStacks downTo 0) input[i].replace(" ", "0")
.filter { isUpperCase(it) || it == '0' }
.mapIndexed { ind, c -> if (c != '0') stacks[ind].add(c) }
return Pair(bottom + 1, stacks)
}
fun moveOne(from: Int, to: Int, stacks: List<ArrayList<Char>>) =
stacks[to].add(stacks[from].removeLast())
fun move1(amount: Int, from: Int, to: Int, stacks: List<ArrayList<Char>>) {
for (i in 1..amount) moveOne(from, to, stacks)
}
fun getStacksTop(stacks: List<ArrayList<Char>>): String =
stacks.map { it.lastOrNull() ?: "" }.joinToString("")
fun executeCmds(
input: List<String>, func: (Int, Int, Int, List<ArrayList<Char>>) -> Unit
): String {
val (startPoint, stacks) = parseStacks(input)
for (i in startPoint..input.lastIndex) {
try {
val (amount, from, to) = Regex("[0-9]+").findAll(input[i]).map(MatchResult::value)
.map { it.toInt() }.toList()
func(amount, from - 1, to - 1, stacks)
} catch (_: Exception) {
continue
}
}
return getStacksTop(stacks)
}
fun part1(input: List<String>) = executeCmds(input, ::move1)
fun move2(amount: Int, from: Int, to: Int, stacks: List<ArrayList<Char>>) {
stacks[to].addAll(stacks[from].takeLast(amount))
for (i in 1..amount) stacks[from].removeLast()
}
fun part2(input: List<String>): String = executeCmds(input, ::move2)
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 462bcba7779f7bfc9a109d886af8f722ec14c485 | 2,232 | anvent-kotlin | Apache License 2.0 |
src/Day04.kt | frungl | 573,598,286 | false | {"Kotlin": 86423} | fun main() {
fun part1(input: List<String>): Int {
return input.count { str ->
val (l, r) = str.split(',')
val (la, lb) = l.split('-').map { it.toInt() }
val (ra, rb) = r.split('-').map { it.toInt() }
(la <= ra && rb <= lb) || (ra <= la && lb <= rb)
}
}
fun part2(input: List<String>): Int {
return input.count { str ->
val (l, r) = str.split(',')
val (la, lb) = l.split('-').map { it.toInt() }
val (ra, rb) = r.split('-').map { it.toInt() }
!(la > rb || ra > lb)
}
}
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 | d4cecfd5ee13de95f143407735e00c02baac7d5c | 814 | aoc2022 | Apache License 2.0 |
calendar/day12/Day12.kt | rocketraman | 573,845,375 | false | {"Kotlin": 45660} | package day12
import Day
import Lines
class Day12 : Day() {
data class Position(val x: Int, val y: Int)
override fun part1(input: Lines): Any {
val graph = input.map { it.toCharArray().asList() }
fun positionOf(c: Char): Position {
val y = graph.indexOfFirst { it.contains(c) }
val x = graph[y].indexOfFirst { it == c }
return Position(x, y)
}
val startPosition = positionOf('S')
val endPosition = positionOf('E')
fun Position.value() = when (val value = graph[y][x]) {
'S' -> 'a'
'E' -> 'z'
else -> value
}
fun Position.possibleMoves(previousPosition: Position?): List<Position> = listOf(
Position(x + 1, y),
Position(x - 1, y),
Position(x, y + 1),
Position(x, y - 1),
).filter {
(previousPosition == null || it != previousPosition) &&
it != startPosition &&
it.x >= 0 &&
it.y >= 0 &&
it.y < graph.size &&
it.x < graph[0].size &&
it.value() - value() <= 1
}
val unvisitedNodes = buildSet {
for (y in graph.indices) {
for (x in graph[0].indices) {
add(Position(x, y))
}
}
}.toMutableSet()
var current = startPosition
val distances = buildMap {
for (y in graph.indices) {
for (x in graph[0].indices) {
val position = Position(x, y)
if (position == current) put(position, 0)
else put(position, Int.MAX_VALUE)
}
}
}.toMutableMap()
tailrec fun djikstraStep() {
current
.possibleMoves(null)
.filter { it in unvisitedNodes }
.forEach { position ->
if (distances.getValue(current) + 1 < distances.getValue(position)) {
distances += (position to distances.getValue(current) + 1)
}
}
// mark current node as visited
unvisitedNodes -= current
if (endPosition !in unvisitedNodes) {
return
} else {
val minUnvisited = unvisitedNodes.minBy { distances.getValue(it) }
current = minUnvisited
djikstraStep()
}
}
djikstraStep()
return distances.getValue(endPosition)
}
override fun part2(input: Lines): Any {
val graph = input.map { it.toCharArray().asList() }
fun positionOf(c: Char): Position {
val y = graph.indexOfFirst { it.contains(c) }
val x = graph[y].indexOfFirst { it == c }
return Position(x, y)
}
// any node with a
val startPosition = positionOf('a')
val endPosition = positionOf('E')
fun Position.value() = when (val value = graph[y][x]) {
'S' -> 'a'
'E' -> 'z'
else -> value
}
fun Position.possibleMoves(previousPosition: Position?): List<Position> = listOf(
Position(x + 1, y),
Position(x - 1, y),
Position(x, y + 1),
Position(x, y - 1),
).filter {
(previousPosition == null || it != previousPosition) &&
it.x >= 0 &&
it.y >= 0 &&
it.y < graph.size &&
it.x < graph[0].size &&
it.value() != 'a' &&
it.value() - value() <= 1
}
val unvisitedNodes = buildSet {
for (y in graph.indices) {
for (x in graph[0].indices) {
if (Position(x, y) != startPosition) {
add(Position(x, y))
}
}
}
}.toMutableSet()
var current = startPosition
val distances = buildMap {
for (y in graph.indices) {
for (x in graph[0].indices) {
val position = Position(x, y)
// this time we initialize all nodes with a with start distance 0, as we can start from any of them
if (position.value() == 'a') put(position, 0)
else put(position, Int.MAX_VALUE)
}
}
}.toMutableMap()
tailrec fun djikstraStep() {
current
.possibleMoves(null)
.filter { it in unvisitedNodes }
.forEach { position ->
if (distances.getValue(current) + 1 < distances.getValue(position)) {
distances += (position to distances.getValue(current) + 1)
}
}
// mark current node as visited
unvisitedNodes -= current
if (endPosition !in unvisitedNodes) {
return
} else {
val minUnvisited = unvisitedNodes.minBy { distances.getValue(it) }
current = minUnvisited
djikstraStep()
}
}
djikstraStep()
return distances.getValue(endPosition)
}
}
| 0 | Kotlin | 0 | 0 | 6bcce7614776a081179dcded7c7a1dcb17b8d212 | 4,474 | adventofcode-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/LargestColorValueInDirectedGraph.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT
import java.util.Arrays
import kotlin.math.max
/**
* 1857. Largest Color Value in a Directed Graph
* @see <a href="https://leetcode.com/problems/largest-color-value-in-a-directed-graph/">Source</a>
*/
fun interface LargestColorValueInDirectedGraph {
fun largestPathValue(colors: String, edges: Array<IntArray>): Int
}
class LargestColorValueInDirectedGraphSet : LargestColorValueInDirectedGraph {
override fun largestPathValue(colors: String, edges: Array<IntArray>): Int {
val n: Int = colors.length
val indegrees = IntArray(n)
val graph: MutableList<MutableList<Int>> = ArrayList()
for (i in 0 until n) {
graph.add(ArrayList())
}
for (edge in edges) {
val u = edge[0]
val v = edge[1]
graph[u].add(v)
indegrees[v]++
}
val zeroIndegree: MutableSet<Int> = HashSet()
for (i in 0 until n) {
if (indegrees[i] == 0) {
zeroIndegree.add(i)
}
}
val counts = Array(n) { IntArray(ALPHABET_LETTERS_COUNT) }
for (i in 0 until n) {
counts[i][colors[i] - 'a']++
}
var maxCount = 0
var visited = 0
while (zeroIndegree.isNotEmpty()) {
val u = zeroIndegree.iterator().next()
zeroIndegree.remove(u)
visited++
for (v in graph[u]) {
for (i in 0 until ALPHABET_LETTERS_COUNT) {
counts[v][i] = max(counts[v][i], counts[u][i] + if (colors[v] - 'a' == i) 1 else 0)
}
indegrees[v]--
if (indegrees[v] == 0) {
zeroIndegree.add(v)
}
}
maxCount = max(maxCount, Arrays.stream(counts[u]).max().asInt)
}
return if (visited == n) maxCount else -1
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,578 | kotlab | Apache License 2.0 |
advent-of-code-2022/src/main/kotlin/year_2022/Day07.kt | rudii1410 | 575,662,325 | false | {"Kotlin": 37749} | package year_2022
import util.Runner
import kotlin.math.min
sealed class Node {
data class Dir(val root: Dir?, val name: String, var totalSize: Int = 0, val child: MutableList<Node>) : Node()
data class File(val name: String, val size: Int) : Node()
}
fun main() {
fun aTraverse(dir: Node.Dir): Int {
return dir.child.sumOf { if (it is Node.Dir) aTraverse(it) else 0 } +
(dir.totalSize.takeIf { it <= 100_000 } ?: 0)
}
fun bTraverse(dir: Node.Dir, target: Int): Int {
if (dir.totalSize < target) return Int.MAX_VALUE
return min(
dir.totalSize,
dir.child.minOfOrNull {
if (it is Node.Dir) bTraverse(it, target) else Int.MAX_VALUE
} ?: Int.MAX_VALUE
)
}
fun updateSizeToRoot(dir: Node.Dir?, size: Int) {
dir?.run {
totalSize += size
updateSizeToRoot(root, size)
}
}
fun getRoot(dir: Node.Dir?): Node.Dir {
return if (dir?.root == null) dir!! else getRoot(dir.root)
}
fun generateTree(input: List<String>): Node.Dir {
var currentDir: Node.Dir? = null
input.forEach { line ->
if (line.startsWith("$")) {
currentDir = when (val cmd = line.removeRange(0, 2)) {
"cd /" -> Node.Dir(root = null, name = "/", child = mutableListOf())
"cd .." -> currentDir?.root ?: currentDir
"ls" -> currentDir
else -> {
(currentDir?.child?.find { it is Node.Dir && it.name == cmd.split(" ")[1] } ?: currentDir) as Node.Dir
}
}
} else {
val row = line.split(" ")
currentDir?.child?.add(
if (row[0] == "dir") Node.Dir(root = currentDir, name = row[1], child = mutableListOf())
else {
val size = row[0].toInt()
updateSizeToRoot(currentDir, size)
Node.File(name = row[1], size = size)
}
)
}
}
return getRoot(currentDir)
}
/* Part 1 */
fun part1(input: List<String>): Int {
return aTraverse(generateTree(input))
}
Runner.run(::part1, 95437)
/* Part 2 */
fun part2(input: List<String>): Int {
return generateTree(input).let {
bTraverse(it, it.totalSize - 40_000_000)
}
}
Runner.run(::part2, 24933642)
}
| 1 | Kotlin | 0 | 0 | ab63e6cd53746e68713ddfffd65dd25408d5d488 | 2,551 | advent-of-code | Apache License 2.0 |
src/day04/Day04.kt | apeinte | 574,487,528 | false | {"Kotlin": 47438} | package day04
import readDayInput
private const val RESULT_EXAMPLE_PART_ONE = 2
private const val RESULT_EXAMPLE_PART_TWO = 4
private const val VALUE_OF_THE_DAY = 4
fun main() {
fun parseSectionIntoListInt(section: String): List<Int> {
val result = mutableListOf<Int>()
section.split("-").forEach {
result.add(it.toInt())
}
return result
}
fun isFullyContainInTheSectionPair(sectionOne: List<Int>, sectionTwo: List<Int>): Boolean {
return (sectionOne[0] in sectionTwo[0]..sectionTwo[1] &&
sectionOne[1] in sectionTwo[0]..sectionTwo[1]) ||
(sectionTwo[0] in sectionOne[0]..sectionOne[1] &&
sectionTwo[1] in sectionOne[0]..sectionOne[1])
}
fun isOverlappingTheSection(sectionNumber: Int, section: List<Int>): Boolean =
sectionNumber in section[0]..section[1]
fun part1(input: List<String>): Int {
var result = 0
input.forEach { sectionAssignment ->
val sectionSplit = sectionAssignment.split(",")
val sectionOne = parseSectionIntoListInt(sectionSplit[0])
val sectionTwo = parseSectionIntoListInt(sectionSplit[1])
if (isFullyContainInTheSectionPair(sectionOne, sectionTwo)) {
result++
}
}
return result
}
fun part2(input: List<String>): Int {
var result = 0
input.forEach { sectionAssignment ->
val sectionSplit = sectionAssignment.split(",")
val sectionOne = parseSectionIntoListInt(sectionSplit[0])
val sectionTwo = parseSectionIntoListInt(sectionSplit[1])
var counterOverlapping = 0
sectionOne.forEach { numberOfTheSection ->
if (isOverlappingTheSection(numberOfTheSection, sectionTwo)) {
counterOverlapping++
}
}
sectionTwo.forEach { numberOfTheSection ->
if (isOverlappingTheSection(numberOfTheSection, sectionOne)) {
counterOverlapping++
}
}
if (counterOverlapping > 0) {
result++
}
}
return result
}
val inputRead = readDayInput(VALUE_OF_THE_DAY)
val inputReadTest = readDayInput(VALUE_OF_THE_DAY, true)
if (part1(inputReadTest) == RESULT_EXAMPLE_PART_ONE) {
println(
"In how many assignment pairs does one range fully contain the other?\n${
part1(inputRead)
}"
)
}
if (part2(inputReadTest) == RESULT_EXAMPLE_PART_TWO) {
println("In how many assignment pairs do the ranges overlap?\n${part2(inputRead)}")
}
}
| 0 | Kotlin | 0 | 0 | 4bb3df5eb017eda769b29c03c6f090ca5cdef5bb | 2,749 | my-advent-of-code | Apache License 2.0 |
src/Day02.kt | uekemp | 575,483,293 | false | {"Kotlin": 69253} |
@JvmInline
value class RockPaperScissors(val points: Int) {
init {
if (points == -1) error("Invalid input: $points")
}
fun playWith(opponent: RockPaperScissors): Int {
return if (points == opponent.points) {
3 + points
} else if ((points - opponent.points % 3) == 1) {
6 + points
} else {
points
}
}
fun looser() = if (points == 1) RockPaperScissors(3) else RockPaperScissors(points - 1)
fun winner() = RockPaperScissors((points % 3) + 1)
companion object {
fun fromAbc(char: Char) = RockPaperScissors("ABC".indexOf(char) + 1)
fun fromXyz(char: Char) = RockPaperScissors("XYZ".indexOf(char) + 1)
}
}
fun main() {
fun part1(input: List<String>): Int {
return input.sumOf { line ->
RockPaperScissors.fromXyz(line[2]).playWith(RockPaperScissors.fromAbc(line[0]))
}
}
fun part2(input: List<String>): Int {
return input.sumOf { line ->
val opponent = RockPaperScissors.fromAbc(line[0])
when (line[2]) {
'X' -> opponent.looser().points
'Y' -> opponent.points + 3
'Z' -> opponent.winner().points + 6
else -> error("Invalid input")
}
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
val input = readInput("Day02")
check(part1(input) == 12586)
check(part2(input) == 13193)
}
| 0 | Kotlin | 0 | 0 | bc32522d49516f561fb8484c8958107c50819f49 | 1,580 | advent-of-code-kotlin-2022 | Apache License 2.0 |
advent23-kt/app/src/main/kotlin/dev/rockyj/advent_kt/Day2.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 buildGames(input: List<String>): MutableMap<Int, List<Pair<String, Int>>> {
val games = mutableMapOf<Int, List<Pair<String, Int>>>()
input.forEach { line ->
val game = mutableListOf<Pair<String, Int>>()
val gameParts = line.trim().split(":")
val gameId = gameParts.get(0).substring(4).trim()
val gamePlays = gameParts.get(1).split(";")
gamePlays.forEach { gamePlay ->
val cubes = gamePlay.split(",")
cubes.forEach { draw ->
val x1 = draw.trim().split(Regex("\\s"))
val pair = Pair(x1.get(1), Integer.parseInt(x1.get(0)))
game.add(pair)
}
}
games.put(Integer.parseInt(gameId), game)
}
// println(games)
return games
}
private fun part1(input: List<String>) {
val games = buildGames(input)
val possibleGames = games.filter { game ->
val pairs = game.value
pairs.all { pair ->
(pair.first == "red" && pair.second <= 12) ||
(pair.first == "green" && pair.second <= 13) ||
(pair.first == "blue" && pair.second <= 14)
}
}
println(possibleGames.keys.sum())
}
private fun part2(input: List<String>) {
val games = buildGames(input)
val powers = games.map { game ->
var pr = 0
var pg = 0
var pb = 0
game.value.forEach { pair ->
if(pair.first == "red" && pair.second >= pr) {
pr = pair.second
}
if(pair.first == "green" && pair.second >= pg) {
pg = pair.second
}
if(pair.first == "blue" && pair.second >= pb) {
pb = pair.second
}
}
pr * pg * pb
}
println(powers.sum())
}
fun main() {
val lines = fileToArr("day2_2.txt")
part1(lines)
part2(lines)
} | 0 | Kotlin | 0 | 0 | a7bc1dfad8fb784868150d7cf32f35f606a8dafe | 1,957 | advent-2023 | MIT License |
src/Day03.kt | Vincentvibe3 | 573,202,573 | false | {"Kotlin": 8454} | fun main() {
fun part1(input: List<String>): Int {
var total = 0
val mapping = HashMap<Char, Int>()
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray().forEachIndexed{ i: Int, c: Char ->
mapping[c] = i+1
}
for (line in input){
var common = arrayListOf<Char>()
val midPoint = line.length/2-1
val compartment1 = line.substring(0..midPoint)
val compartment2 = line.substring(midPoint+1 until line.length)
for (char in compartment1){
if (common.contains(char)){
continue
}
if (compartment2.contains(char)){
common.add(char)
val priority = mapping[char]
priority?.let { total+=it }
}
}
}
return total
}
fun part2(input: List<String>): Int {
var total = 0
val mapping = HashMap<Char, Int>()
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray().forEachIndexed{ i: Int, c: Char ->
mapping[c] = i+1
}
val currentGroupSacks = arrayListOf<String>()
val common = arrayListOf<Char>()
for (index in input.indices){
val line = input[index]
if (currentGroupSacks.size==2){
val groupCommon = arrayListOf<Char>()
for (char in line){
var charOk = true
for (sack in currentGroupSacks) {
if (!sack.contains(char)){
charOk = false
break
}
}
if (charOk&&!groupCommon.contains(char)){
groupCommon.add(char)
}
}
groupCommon.forEach {
common.add(it)
}
currentGroupSacks.clear()
} else {
currentGroupSacks.add(line)
}
}
common.forEach {
val priority = mapping[it]
priority?.let { value -> total+=value }
}
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 | 246c8c43a416023343b3ef518ae3e21dd826ee81 | 2,537 | advent-of-code-2022 | Apache License 2.0 |
src/Day14.kt | jbotuck | 573,028,687 | false | {"Kotlin": 42401} | import kotlin.math.max
import kotlin.math.min
fun main() {
val rockStructures = readInput("Day14").map { line ->
line.split(" -> ").map { pair ->
pair.split(",")
.map { it.toInt() }
.let { it.first() to it.last() }
}
}
val maxY = rockStructures.maxOf { structure ->
structure.maxOf { it.second }
}
run {
val cave = Cave2(maxY.inc(), false)
cave.build(rockStructures)
cave.print()
cave.fill()
println("cave filled")
cave.print()
println(cave.countTheSand())
}
val cave = Cave2(maxY + 2, true)
cave.build(rockStructures)
cave.print()
cave.fill()
println("cave filled")
cave.print()
println(cave.countTheSand())
}
private class Cave2(val floorIndex: Int, val hasFloor: Boolean) {
private val rocks = mutableSetOf<Pair<Int, Int>>()
private val sand = mutableSetOf<Pair<Int, Int>>()
fun fill() {
while (true) {
if (!generateSandParticleAndCheckIsRendered()) break
}
}
private fun Pair<Int, Int>.isBlocked() = this in sand || this in rocks || (hasFloor && second == floorIndex)
private fun generateSandParticleAndCheckIsRendered(): Boolean {
var particle = 500 to 0
if (particle.isBlocked()) return false
while (true) {
val next = sequenceOf(
particle.copy(second = particle.second.inc()),
Pair(particle.first.dec(), particle.second.inc()),
Pair(particle.first.inc(), particle.second.inc())
).firstOrNull { !it.isBlocked() }
if (next == null) {
sand.add(particle)
return true
}
if (next.second == floorIndex) return false
particle = next
}
}
fun buildSingle(structure: List<Pair<Int, Int>>) {
for (segment in structure.windowed(2)) {
@Suppress("NAME_SHADOWING")
val segment = segment.sortedWith { a, b ->
a.first.compareTo(b.first).takeIf { it != 0 } ?: a.second.compareTo(b.second)
}
rocks.addAll(
(segment.first().first..segment.last().first)
.takeIf { it.first != it.last() }
?.map { it to segment.first().second }
?: (segment.first().second..segment.last().second)
.map { segment.first().first to it }
)
}
}
fun countTheSand() = sand.size
fun print() {
val minX = min(rocks.minOf { it.first }, sand.minOfOrNull { it.first } ?: Int.MAX_VALUE)
val maxX = max(rocks.maxOf { it.first }, sand.maxOfOrNull { it.first } ?: Int.MIN_VALUE)
println()
for (y in 0..floorIndex) {
println()
for (x in minX..maxX)
print((x to y).let {
when (it) {
in rocks -> '#'
in sand -> 'o'
else -> '.'
}
})
}
println()
}
fun build(structures: List<List<Pair<Int, Int>>>) {
for (structure in structures) buildSingle(structure)
}
}
| 0 | Kotlin | 0 | 0 | d5adefbcc04f37950143f384ff0efcd0bbb0d051 | 3,273 | aoc2022 | Apache License 2.0 |
src/main/kotlin/com/dambra/adventofcode2018/day6/Grid.kt | pauldambra | 159,939,178 | false | null | package com.dambra.adventofcode2018.day6
class Grid(private val coordinates: List<Coordinate>) {
private val grid = mutableMapOf<Coordinate, Int>()
private val infiniteAreas = mutableSetOf<Coordinate>()
fun findBiggestUnsafeRegionSize(): Int {
val byX = coordinates
.groupBy { it.x }
.map { it.key to it.value.groupBy { v -> v.y } }
.toMap()
val (maxX, maxY, gridSize) = getGridSize()
(0..gridSize).forEach { y ->
(0..gridSize).forEach { x ->
val deviceCoordinate = isDeviceCoordinate(byX, x, y)
if (deviceCoordinate.isEmpty()) {
identifyRegion(x, y, maxX, maxY)
} else {
thisIsOneOfTheDeviceCoordinates(deviceCoordinate)
}
}
}
return findSizeOfLargestFiniteArea()
}
private fun findSizeOfLargestFiniteArea(): Int {
val x = grid
.filterNot { infiniteAreas.contains(it.key) }
.map { it.value to it.key }
.sortedByDescending { it.first }
.first()
println("biggest finite area is $x")
return x.first
}
private fun identifyRegion(x: Int, y: Int, maxX: Int, maxY: Int) {
val closest = findClosest(Coordinate(100, x, y)) ?: return
updateArea(closest)
if (isEdgeCoordinate(x, maxX, y, maxY)) {
infiniteAreas.add(closest)
}
}
private fun thisIsOneOfTheDeviceCoordinates(deviceCoordinate: List<Coordinate>) {
updateArea(deviceCoordinate.first())
}
private fun isDeviceCoordinate(
byX: Map<Int, Map<Int, List<Coordinate>>>,
x: Int,
y: Int
): List<Coordinate> {
val xMatches = byX.getOrDefault(x, emptyMap())
val yMatches = xMatches.getOrDefault(y, emptyList())
if (yMatches.size > 1) {
throw Exception("shouldn't have more than one match: $yMatches")
}
return yMatches
}
private fun getGridSize(): Triple<Int, Int, Int> {
val maxX = coordinates.maxBy { it.x }!!.x
val maxY = coordinates.maxBy { it.y }!!.y
val gridSize = Integer.max(maxX, maxY)
return Triple(maxX, maxY, gridSize)
}
private fun updateArea(coordinate: Coordinate) {
val current = grid.getOrDefault(coordinate, 0)
grid[coordinate] = current + 1
}
private fun isEdgeCoordinate(x: Int, maxX: Int, y: Int, maxY: Int) =
(x == 0 || x == maxX) || (y == 0 || y == maxY)
private fun findClosest(coordinate: Coordinate): Coordinate? {
val distances = coordinate.distancesTo(coordinates)
return if (distances[0].second == distances[1].second) null else distances[0].first
}
fun findSafeRegion(maxDistance: Int): Int {
val (_, _, gridSize) = getGridSize()
return (0..gridSize).fold(0) { count, y ->
count + (0..gridSize)
.map { x -> Coordinate(0, x, y) }
.filter { cell -> cell.distancesTo(coordinates).sumBy { it.second } < maxDistance }
.count()
}
}
} | 0 | Kotlin | 0 | 1 | 7d11bb8a07fb156dc92322e06e76e4ecf8402d1d | 3,161 | adventofcode2018 | The Unlicense |
src/main/kotlin/Day14.kt | lanrete | 244,431,253 | false | null | data class Component(val material: Material, val count: Long) {
override fun toString(): String {
return "$count $material"
}
}
data class Material(val name: String) {
override fun toString(): String {
return name
}
}
object Day14 : Solver() {
override val day: Int = 14
override val inputs: List<String> = getInput()
private val ORE = Material("ORE")
private val FUEL = Material("FUEL")
private val components: MutableMap<Material, List<Component>> = mutableMapOf()
private val reactionOutputs: MutableMap<Material, Int> = mutableMapOf()
private val materials: MutableSet<Material> = mutableSetOf(ORE)
private val materialLevels: MutableMap<Material, Int> = mutableMapOf(ORE to 0)
private fun processInput() {
for (reactionString in inputs) {
val inputs = reactionString.split("=>").first().trim()
val output = reactionString.split("=>").last().trim()
val outputCount = output.split(" ").first().toInt()
val outputMaterial = Material(output.split(" ").last())
val ingredient = inputs.split(",").map {
val tokens = it.trim().split(" ")
val cnt = tokens.first().toLong()
val m = Material(tokens.last())
Component(material = m, count = cnt)
}
materials.add(outputMaterial)
components[outputMaterial] = ingredient
reactionOutputs[outputMaterial] = outputCount
}
}
private fun getLevel(material: Material): Int {
return materialLevels.getOrPut(material,
{
components
.getValue(material)
.map { getLevel(it.material) }
.reduce { acc, i -> if (i > acc) i else acc } + 1
}
)
}
private fun getOre(c: Component): Long {
var currentFormula = components
.getValue(c.material)
.map { Component(it.material, it.count * c.count) }
.toMutableList()
var currentLevel = currentFormula.filter { it.count > 0 }.map { getLevel(it.material) }.max()!!
while (currentLevel > 0) {
val neededComponents = currentFormula
.filter { getLevel(it.material) == currentLevel }
.filter { it.material != ORE }
.flatMap {
currentFormula.remove(it)
val needed = it.count
val unitOutput = reactionOutputs.getValue(it.material)
val reactionCount = (needed / unitOutput) + if (needed % unitOutput == 0L) 0 else 1
val rawMaterials = components.getValue(it.material).map { comp ->
Component(comp.material, comp.count * reactionCount)
}.toMutableList()
val wasteOutput = unitOutput * reactionCount - needed
if (wasteOutput > 0) rawMaterials.add(Component(it.material, 0 - wasteOutput))
rawMaterials.toList()
}
currentFormula.addAll(neededComponents)
currentFormula = currentFormula
.groupBy { it.material }
.map { Component(it.key, it.value.map { sub -> sub.count }.sum()) }
.toMutableList()
currentLevel = currentFormula.filter { it.count > 0 }.map { getLevel(it.material) }.max()!!
}
return currentFormula.first { it.material == ORE }.count
}
override fun question1(): String {
processInput()
return getOre(Component(FUEL, 1)).toString()
}
override fun question2(): String {
val target = 1000000000000
var upperLimit = target
var lowerLimit = 0L
while (upperLimit - lowerLimit > 1) {
val candidate = (upperLimit + lowerLimit) / 2
val oreNeeded = getOre(Component(FUEL, candidate))
if (oreNeeded < target) lowerLimit = candidate
else upperLimit = candidate
}
return lowerLimit.toString()
}
}
fun main() {
Day14.solve()
} | 0 | Kotlin | 0 | 1 | 15125c807abe53230e8d0f0b2ca0e98ea72eb8fd | 4,158 | AoC2019-Kotlin | MIT License |
src/main/kotlin/g0901_1000/s0952_largest_component_size_by_common_factor/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0901_1000.s0952_largest_component_size_by_common_factor
// #Hard #Array #Math #Union_Find #2023_05_02_Time_538_ms_(100.00%)_Space_95.7_MB_(100.00%)
import kotlin.math.sqrt
class Solution {
fun largestComponentSize(nums: IntArray): Int {
var max = 0
for (a in nums) {
max = Math.max(max, a)
}
val roots = IntArray(max + 1)
val sizes = IntArray(max + 1)
for (idx in 1..max) {
roots[idx] = idx
}
for (a in nums) {
if (a == 1) {
sizes[a] = 1
continue
}
val sqrt = sqrt(a.toDouble()).toInt()
val thisRoot = getRoot(roots, a)
sizes[thisRoot]++
for (factor in 1..sqrt) {
if (a % factor == 0) {
val otherFactor = a / factor
val otherFactorRoot = getRoot(roots, otherFactor)
if (factor != 1) {
union(roots, thisRoot, factor, sizes)
}
union(roots, thisRoot, otherFactorRoot, sizes)
}
}
}
var maxConnection = 0
for (size in sizes) {
maxConnection = Math.max(maxConnection, size)
}
return maxConnection
}
private fun union(roots: IntArray, a: Int, b: Int, sizes: IntArray) {
val rootA = getRoot(roots, a)
val rootB = getRoot(roots, b)
if (rootA != rootB) {
sizes[rootA] += sizes[rootB]
roots[rootB] = rootA
}
}
private fun getRoot(roots: IntArray, a: Int): Int {
if (roots[a] == a) {
return a
}
roots[a] = getRoot(roots, roots[a])
return roots[a]
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,789 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/advent/y2018/day7.kt | IgorPerikov | 134,053,571 | false | {"Kotlin": 29606} | package advent.y2018
import misc.readAdventInput
import java.util.*
fun main(args: Array<String>) {
println(buildSequenceOfSteps(parseRawRequirements(readAdventInput(7, 2018))))
}
private fun buildSequenceOfSteps(rawRequirements: List<Requirement>): String {
val resultBuilder = StringBuilder()
val remainingSteps = TreeSet(rawRequirements.flatMap { listOf(it.prerequisite, it.step) })
val requirements = parseRequirements(rawRequirements)
while (remainingSteps.isNotEmpty()) {
val iterator = remainingSteps.iterator()
while (iterator.hasNext()) {
val currentStep = iterator.next()
val prerequisites = requirements[currentStep]
if (prerequisites == null || prerequisites.all { !remainingSteps.contains(it) }) {
iterator.remove()
resultBuilder.append(currentStep)
break
}
}
}
return resultBuilder.toString()
}
private fun parseRequirements(rawRequirements: List<Requirement>): Map<Char, List<Char>> {
return rawRequirements.groupBy({ it.step }, { it.prerequisite })
}
private fun parseRawRequirements(input: List<String>): List<Requirement> {
return input.map { Requirement(it.substringAfter("Step ")[0], it.substringAfter("step ")[0]) }
}
data class Requirement(val prerequisite: Char, val step: Char)
| 0 | Kotlin | 0 | 0 | b30cf179f7b7ae534ee55d432b13859b77bbc4b7 | 1,364 | kotlin-solutions | MIT License |
src/main/kotlin/days/Day05.kt | julia-kim | 569,976,303 | false | null | package days
import readInput
fun main() {
fun makeStacks(input: List<String>): MutableMap<Int?, MutableList<Char>> {
val blankLineIndex = input.indexOfFirst { it.isBlank() }
val stacksIndices =
input[blankLineIndex - 1].mapIndexedNotNull { i, c -> if (c.isDigit()) i to c.digitToInt() else null }
.toMap()
val stacks: MutableMap<Int?, MutableList<Char>> = mutableMapOf()
input.subList(0, blankLineIndex - 1).reversed().forEach {
it.forEachIndexed { i, c ->
if (c.isLetter()) {
val matchingIndex = stacksIndices[i]
if (stacks[matchingIndex].isNullOrEmpty()) stacks[matchingIndex] =
mutableListOf(c) else stacks[matchingIndex]!!.add(c)
}
}
}
return stacks
}
fun parseInstructions(input: List<String>): List<Triple<Int, Int, Int>> {
val blankLineIndex = input.indexOfFirst { it.isBlank() }
val rearrangementProcedure = input.subList(blankLineIndex + 1, input.size)
return rearrangementProcedure.map {
val (qty, from, to) = it.split(" ").mapNotNull {
if (it.toIntOrNull() != null) it.toInt() else
null
}
Triple(qty, from, to)
}
}
fun part1(input: List<String>): String {
var message = ""
val stacks = makeStacks(input)
val instructions = parseInstructions(input)
instructions.forEach {
var (qty, from, to) = it
while (qty > 0) {
val crate = stacks[from]!!.removeLast()
stacks[to]!!.add(crate)
qty--
}
}
stacks.forEach { message += it.value.last() }
return message
}
fun part2(input: List<String>): String {
val message: String
val stacks = makeStacks(input)
val instructions = parseInstructions(input)
instructions.forEach {
val (qty, from, to) = it
val crates = stacks[from]!!.takeLast(qty)
stacks[from] = stacks[from]!!.dropLast(qty).toMutableList()
stacks[to]!!.addAll(crates)
}
message = stacks.values.joinToString(separator = "") { it.last().toString() }
return message
}
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 65188040b3b37c7cb73ef5f2c7422587528d61a4 | 2,563 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | findusl | 574,694,775 | false | {"Kotlin": 6599} | import java.io.File
import java.util.Stack
private fun part1(input: File): String {
val (initialState, steps) = input.readText().split("\n\n")
val tower = parseTower(initialState)
tower.runSteps(steps)
return String(tower.map { it.pop() }.toCharArray())
}
private fun part2(input: File): String {
val (initialState, steps) = input.readText().split("\n\n")
val tower = parseTower(initialState)
tower.runSteps2(steps)
return String(tower.map { it.pop() }.toCharArray())
}
private fun parseTower(initialState: String): Array<Stack<Char>> {
val lines = initialState.lines().reversed().iterator()
val last = lines.next()
val stackCount = last.length/4 + 1
val result = Array(stackCount) { Stack<Char>() }
lines.forEach {
it.asSequence().chunked(4).forEachIndexed { index, chars ->
when(chars[1]) {
' ' -> {}
else -> result[index].push(chars[1])
}
}
}
return result
}
private fun Array<Stack<Char>>.runSteps(steps: String) {
steps.lineSequence().forEach { line ->
val (times, origin, target) = line.split("move ", " from ", " to ").drop(1).map(String::toInt)
for (i in 0 until times) {
get(target - 1).push(get(origin - 1).pop())
}
println("Step $line moves $times from $origin to $target. Result: ${humanReadable()}")
}
}
private fun Array<Stack<Char>>.runSteps2(steps: String) {
steps.lineSequence().forEach { line ->
val (times, origin, target) = line.split("move ", " from ", " to ").drop(1).map(String::toInt)
val intermediateStack = Stack<Char>()
for (i in 0 until times) {
intermediateStack.push(get(origin - 1).pop())
}
for (i in 0 until times) {
get(target - 1).push(intermediateStack.pop())
}
println("Step $line moves $times from $origin to $target. Result: ${humanReadable()}")
}
}
private fun Array<Stack<Char>>.humanReadable(): String = joinToString(separator = ";") { String(it.toCharArray()) }
fun main() {
runDay(5, "CMZ", ::part1)
runDay(5, "MCD", ::part2)
}
| 0 | Kotlin | 0 | 0 | 035f0667c115b09dc36a475fde779d4b74cff362 | 2,159 | aoc-kotlin-2022 | Apache License 2.0 |
src/year2021/day06/Day06.kt | kingdongus | 573,014,376 | false | {"Kotlin": 100767} | package year2021.day06
import readInputFileByYearAndDay
import readTestFileByYearAndDay
fun main() {
// move each fish one age group farther down
// for each fish that would go below 0, reset them to 6 and add one fish at 8
fun ageFishPopulation(fishByAge: MutableMap<Int, Long>, days: Int) =
repeat(days) {
val newFish = fishByAge.getOrDefault(0, 0)
(1..8).forEach { fishByAge[it - 1] = fishByAge.getOrDefault(it, 0) }
fishByAge[6] = fishByAge.getOrDefault(6, 0) + newFish
fishByAge[8] = newFish
}
// for each possible age, count the number of fish, and return as MutableMap
fun parseInputToFish(input: String) =
(0 until 8).associateWith {
input.split(",")
.map { c -> c.toInt() }
.count { c -> c == it }
.toLong()
}.toMutableMap()
fun part1(input: List<String>): Long {
val fishByAge = parseInputToFish(input[0])
ageFishPopulation(fishByAge, 80)
return fishByAge.values.sum()
}
fun part2(input: List<String>): Long {
val fishByAge = parseInputToFish(input[0])
ageFishPopulation(fishByAge, 256)
return fishByAge.values.sum()
}
val testInput = readTestFileByYearAndDay(2021, 6)
check(part1(testInput) == 5934L)
check(part2(testInput) == 26984457539)
val input = readInputFileByYearAndDay(2021, 6)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | aa8da2591310beb4a0d2eef81ad2417ff0341384 | 1,501 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/adventofcode/day6.kt | Kvest | 163,103,813 | false | null | package adventofcode
import java.io.File
import kotlin.math.abs
import kotlin.math.max
private const val DIST = 10000
fun main(args: Array<String>) {
println(first6(File("./data/day6_1.txt").readLines()))
println(second6(File("./data/day6_2.txt").readLines()))
}
fun first6(lines: List<String>): Int? {
var w = 0
var h = 0
val dots = lines.map {
val result = IJ(it)
w = max(w, result.j + 1)
h = max(h, result.i + 1)
result
}
val field = List(w * h) { index ->
val i = index / w
val j = index % w
var min = Int.MAX_VALUE
var dot = -1
dots.forEachIndexed { ix, dt ->
val dist = dt.dist(i, j)
//detect double pathes
if (dist == min) {
dot = -1
} else if (dist < min) {
min = dist
dot = ix
}
}
dot
}
val ignore = mutableSetOf(-1)
(0 until h).forEach {
ignore.add(field[it * w])
ignore.add(field[(it + 1) * w - 1])
}
(0 until w).forEach {
ignore.add(field[it])
ignore.add(field[(h - 1) * w + it])
}
return field
.filterNot { ignore.contains(it) }
.groupingBy { it }
.eachCount()
.values
.max()
}
fun second6(lines: List<String>): Int? {
val dots = lines.map { IJ(it) }
val base = dots.find {
val dist = dots.fold(0) { acc, jr -> acc + jr.dist(it.i, it.j) }
dist < DIST
} ?: return -1
var count = 1
var flag = true
var delta = 1
while (flag) {
flag = false
(-delta..delta).forEach { dt ->
if (dots.fold(0) { acc, jr -> acc + jr.dist(base.i - delta, base.j + dt) } < DIST) {
++count
flag = true
}
if (dots.fold(0) { acc, jr -> acc + jr.dist(base.i + delta, base.j + dt) } < DIST) {
++count
flag = true
}
}
(-(delta - 1)..(delta - 1)).forEach { dt ->
if (dots.fold(0) { acc, jr -> acc + jr.dist(base.i + dt, base.j - delta) } < DIST) {
++count
flag = true
}
if (dots.fold(0) { acc, jr -> acc + jr.dist(base.i + dt, base.j + delta) } < DIST) {
++count
flag = true
}
}
++delta
}
return count
}
private class IJ(str: String) {
val i = str.substringAfter(", ").toInt()
val j = str.substringBefore(", ").toInt()
fun dist(otherI: Int, otherJ: Int) = abs(i - otherI) + abs(j - otherJ)
}
| 0 | Kotlin | 0 | 0 | d94b725575a8a5784b53e0f7eee6b7519ac59deb | 2,674 | aoc2018 | Apache License 2.0 |
src/main/kotlin/07_Reccursive_Circus.kt | barta3 | 112,792,199 | false | null | val no = Node("")
class Tower {
fun findBottom(list: ArrayList<Node>): Node {
val root = list.find { n -> n.parent == no }!!
return root
}
fun createNodes(filename: String): ArrayList<Node> {
val list = ArrayList<Node>()
val reader = Tower::class.java.getResource(filename).openStream().bufferedReader()
reader.forEachLine { line ->
list.add(createNode(line))
}
// create real children Nodes
list.forEach { n ->
n.children.forEach { c ->
val childNode = list.find { n -> n.name == c }!!
childNode.parent = n
n.ch.add(childNode)
}
}
list.forEach { n -> println("Name: ${n.name} ${n.weight} Weight ") }
return list
}
private fun createNode(line: String): Node {
val name = line.split(" ")[0]
val weight = Integer.parseInt(line.split(" ")[1].trim('(', ')'))
if (line.contains("-> ")) {
val children = line.split("-> ")[1].split(", ")
return Node(name = name, children = children, weight = weight, accWeight = weight)
}
return Node(name, weight, accWeight = weight)
}
}
data class Node(val name: String,
var weight: Int = 0,
var accWeight: Int = 0,
val children: List<String> = arrayListOf(),
val ch: ArrayList<Node> = ArrayList<Node>(),
var level : Int = 0) {
var parent: Node = no
}
fun findWrong(root: Node) {
val list = ArrayList<Node>()
calcWeightOfSubTree(root, 0, list)
println(root)
val byParent = list.groupBy { n -> n.parent }
println(byParent)
for (entry in byParent.entries) {
val nodes = entry.value
val partition = nodes.partition { n -> n.accWeight == nodes.get(0).accWeight}
if(partition.first.isEmpty() || partition.second.isEmpty()) continue
var wrong: Node
var shouldBe: Node
if(partition.first.size > partition.second.size) {
wrong = partition.second.get(0)
shouldBe = partition.first.get(0)
} else {
wrong = partition.first.get(0)
shouldBe = partition.second.get(0)
}
println()
println("Error on level ${wrong.level}")
nodes.forEach { print(" " + it.weight) }
println()
val diff = wrong.accWeight - shouldBe.accWeight
println("Wrong Is ${wrong.name} ${wrong.weight}, should be ${wrong.weight -diff}")
}
}
fun calcWeightOfSubTree(n: Node, level: Int, list: ArrayList<Node>): Int {
if (n.ch.isEmpty()) {
n.level = level
list.add(n)
return n.weight
}
var sum = n.accWeight
n.ch.forEach { sum += calcWeightOfSubTree(it, level +1, list) }
println("Weight of ${n.name}: $sum Level $level")
n.level = level
n.accWeight = sum
list.add(n)
return sum
}
fun main(args: Array<String>) {
// val nodes = Tower().createNodes("07_input_example.txt")
val nodes = Tower().createNodes("07_input_part1.txt")
val root = Tower().findBottom(nodes)
println("Root is ${root}")
findWrong(root)
} | 0 | Kotlin | 0 | 0 | 51ba74dc7b922ac11f202cece8802d23011f34f1 | 3,219 | AdventOfCode2017 | MIT License |
src/main/kotlin/day02/Day02.kt | daniilsjb | 572,664,294 | false | {"Kotlin": 69004} | package day02
import java.io.File
fun main() {
val data = parse("src/main/kotlin/day02/Day02.txt")
val answer1 = part1(data)
val answer2 = part2(data)
println("🎄 Day 02 🎄")
println()
println("[Part 1]")
println("Answer: $answer1")
println()
println("[Part 2]")
println("Answer: $answer2")
}
private data class Rule(
val points: Int,
val beats: String,
val loses: String,
)
private val rules = mapOf(
"A" to Rule(points = 1, beats = "C", loses = "B"), // Rock
"B" to Rule(points = 2, beats = "A", loses = "C"), // Paper
"C" to Rule(points = 3, beats = "B", loses = "A"), // Scissors
)
private fun assignPoints(elf: String, you: String): Int = when {
rules[you]?.beats == elf -> 6
rules[elf]?.beats == you -> 0
else -> 3
}
private fun playRound(elf: String, you: String): Int =
rules[you]!!.points + assignPoints(elf, you)
@Suppress("SameParameterValue")
private fun parse(path: String): List<Pair<String, String>> =
File(path).useLines { lines ->
lines.map { it.split(" ").let { (a, b) -> a to b } }.toList()
}
private fun part1(data: List<Pair<String, String>>): Int =
data.sumOf { (elf, you) ->
playRound(elf, when (you) {
"X" -> "A"
"Y" -> "B"
"Z" -> "C"
else -> throw IllegalArgumentException()
})
}
private fun part2(data: List<Pair<String, String>>): Int =
data.sumOf { (elf, you) ->
playRound(elf, when (you) {
"X" -> rules[elf]!!.beats
"Y" -> elf
"Z" -> rules[elf]!!.loses
else -> throw IllegalArgumentException()
})
}
| 0 | Kotlin | 0 | 0 | 6f0d373bdbbcf6536608464a17a34363ea343036 | 1,687 | advent-of-code-2022 | MIT License |
calendar/day14/Day14.kt | maartenh | 572,433,648 | false | {"Kotlin": 50914} | package day14
import Day
import Lines
import tools.Parser
import tools.int
import tools.list
import tools.map
import tools.runParser
import tools.seq
import tools.string
class Day14 : Day() {
override fun part1(input: Lines): Any {
val paths = input.map { runParser(path(), it) }
val rocks = paths.flatMap { it.allPoints() }.toSet()
val sand = mutableSetOf<Point>()
val rangeX = (rocks.minOf { it.x}) .. (rocks.maxOf { it.x })
val rangeY = 0 .. rocks.maxOf { it.y }
allSand@ while (true) {
var location = Point(500, 0)
singleUnit@ while (true) {
val nextLocation = listOf(
Point(location.x, location.y + 1),
Point(location.x - 1, location.y + 1),
Point(location.x + 1, location.y + 1),
).firstOrNull { it !in rocks && it !in sand }
if (nextLocation == null) {
sand.add(location)
break@singleUnit
} else if (nextLocation.x in rangeX && nextLocation.y in rangeY) {
location = nextLocation
continue@singleUnit
} else {
break@allSand
}
}
}
return sand.size
}
override fun part2(input: Lines): Any {
val paths = input.map { runParser(path(), it) }
val rocks = paths.flatMap { it.allPoints() }.toSet()
val sand = mutableSetOf<Point>()
val floorY = rocks.maxOf { it.y } + 2
allSand@ while (true) {
var location = Point(500, 0)
singleUnit@ while (true) {
val nextLocation = listOf(
Point(location.x, location.y + 1),
Point(location.x - 1, location.y + 1),
Point(location.x + 1, location.y + 1),
).firstOrNull { it !in rocks && it !in sand && it.y < floorY }
if (nextLocation == null) {
sand.add(location)
if (location == Point(500, 0)) {
break@allSand
}
break@singleUnit
} else {
location = nextLocation
continue@singleUnit
}
}
}
return sand.size
}
data class Point(val x: Int, val y: Int)
data class Path(val points: List<Point>) {
fun allPoints(): List<Point> =
points.windowed(2).flatMap {
val rangeX = if (it[0].x <it[1].x) { it[0].x..it[1].x } else { it[1].x..it[0].x }
val rangeY = if (it[0].y <it[1].y) { it[0].y..it[1].y } else { it[1].y..it[0].y }
rangeX.flatMap { x ->
rangeY.map {y ->
Point(x, y)
}
}
}.distinct()
}
private fun path(): Parser<Path> =
point().list(string(" -> ")).map { Path(it) }
private fun point(): Parser<Point> =
(int() seq string(",") seq int()).map { Point(it.first.first, it.second) }
}
| 0 | Kotlin | 0 | 0 | 4297aa0d7addcdc9077f86ad572f72d8e1f90fe8 | 3,179 | advent-of-code-2022 | Apache License 2.0 |
src/Day03.kt | NunoPontes | 572,963,410 | false | {"Kotlin": 7416} | fun main() {
fun part1(input: List<String>): Int {
val partOneSum = input.fold(0) { acc, line ->
val middle = line.length / 2
val compA = line.slice(0 until middle).toSet()
val compB = line.slice(middle..line.lastIndex).toSet()
val commonChar = compA.intersect(compB).first()
val charValue = commonChar.toItemCode()
acc + charValue
}
return partOneSum
}
fun part2(input: List<String>): Int {
val partTwoSum = input.map { it.toSet() }.windowed(3, 3).sumOf {
it.fold(emptySet<Char>()) { acc, rucksack ->
if (acc.isEmpty()) rucksack else acc.intersect(rucksack)
}.first().toItemCode()
}
return partTwoSum
}
val inputPart1 = readInput("Day03_part1")
val inputPart2 = readInput("Day03_part2")
println(part1(inputPart1))
println(part2(inputPart2))
}
| 0 | Kotlin | 0 | 0 | 78b67b952e0bb51acf952a7b4b056040bab8b05f | 941 | advent-of-code-2022 | Apache License 2.0 |
src/day-3.kt | drademacher | 160,820,401 | false | null | import java.io.File
private data class Rectangle(val left: Int, val top: Int, val width: Int, val height: Int)
fun main(args: Array<String>) {
println("part 1: " + partOne())
println("part 2: " + partTwo())
}
private fun partOne(): Int {
val rawFile = File("res/day-3.txt").readText()
val field = Array(1000) { BooleanArray(1000) }
val conflict = Array(1000) { BooleanArray(1000) }
val commands = parseFile(rawFile)
computeConflicts(commands, field, conflict)
val numberOfConflicts = conflict.sumBy { it.count { innerBoolean -> innerBoolean } }
return numberOfConflicts
}
private fun partTwo(): Int {
val rawFile = File("res/day-3.txt").readText()
val field = Array(1000) { BooleanArray(1000) }
val conflict = Array(1000) { BooleanArray(1000) }
val rectangles = parseFile(rawFile)
computeConflicts(rectangles, field, conflict)
for ((index, command) in rectangles.withIndex()) {
var conflictFree = true
for (y in command.left until command.left + command.width) {
for (x in command.top until command.top + command.height) {
if (conflict[x][y]) {
conflictFree = false
}
}
}
if (conflictFree) {
return index + 1
}
}
return -1
}
private fun parseFile(rawFile: String): List<Rectangle> {
return rawFile
.split("\n")
.filter { it != "" }
.map { it.substring(it.indexOf('@')) }
.map { it.replace(Regex("[^0-9]"), ";") }
.map { it.split(";").filter { it != "" }.map { it.toInt() } }
.map { Rectangle(it[0], it[1], it[2], it[3]) }
}
private fun computeConflicts(rectangles: List<Rectangle>, field: Array<BooleanArray>, conflict: Array<BooleanArray>) {
for (command in rectangles) {
for (y in command.left until command.left + command.width) {
for (x in command.top until command.top + command.height) {
if (field[x][y]) {
conflict[x][y] = true
} else {
field[x][y] = true
}
}
}
}
} | 0 | Kotlin | 0 | 0 | a7f04450406a08a5d9320271148e0ae226f34ac3 | 2,197 | advent-of-code-2018 | MIT License |
src/Day05.kt | cvb941 | 572,639,732 | false | {"Kotlin": 24794} | import java.io.File
class Crates(columns: Int) {
companion object {
fun from(input: String): Crates {
val rows = input.split("\n")
val columns = rows.last().split(" ").mapNotNull { it.toIntOrNull() }.max()
val crates = Crates(columns)
// Fill out crates
rows.dropLast(1).forEach { row ->
for (i in 0 until columns) {
val char = row[1 + i * 4]
if (!char.isWhitespace()) crates.crates[i].add(0, char)
}
}
return crates
}
}
val crates = Array(columns) { mutableListOf<Char>() }
fun runCommand(command: Command) {
repeat(command.amount) {
crates[command.to - 1].add(crates[command.from - 1].removeLast())
}
}
fun runCommandPreserveOrder(command: Command) {
val cratesToMove = crates[command.from - 1].takeLast(command.amount)
crates[command.to - 1].addAll(cratesToMove)
repeat(command.amount) {
crates[command.from - 1].removeLast()
}
}
fun answer(): String {
return String(crates.map { it.last() }.toCharArray())
}
}
data class Command(
val amount: Int,
val from: Int,
val to: Int
) {
companion object {
fun parse(input: String): Command {
val splits = input.split(" ")
val amount = splits[1].toInt()
val from = splits[3].toInt()
val to = splits[5].toInt()
return Command(amount, from, to)
}
}
}
fun main() {
fun part1(input: String): String {
val (input, commandString) = input.split("\n\n")
val crates = Crates.from(input)
val commands = commandString.split("\n").map { Command.parse(it) }
commands.forEach {
crates.runCommand(it)
}
return crates.answer()
}
fun part2(input: String): String {
val (input, commandString) = input.split("\n\n")
val crates = Crates.from(input)
val commands = commandString.split("\n").map { Command.parse(it) }
commands.forEach {
crates.runCommandPreserveOrder(it)
}
return crates.answer()
}
// test if implementation meets criteria from the description, like:
val testInput = File("src", "Day05_test.txt").readText()
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = File("src", "Day05.txt").readText()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | fe145b3104535e8ce05d08f044cb2c54c8b17136 | 2,581 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day05.kt | ajmfulcher | 573,611,837 | false | {"Kotlin": 24722} | fun main() {
fun createStacks(input: List<String>): List<ArrayDeque<String>> {
var stackIndex = 0
while (input[stackIndex].substring(1,2) != "1") {
stackIndex += 1
}
val stacks = input[stackIndex]
.trim()
.split("\\s+".toRegex())
.map { ArrayDeque<String>() }
(stackIndex - 1 downTo 0).forEach { idx ->
input[idx]
.toCharArray()
.forEachIndexed { i, c ->
if(i % 4 == 1 && c.toString().isNotBlank()) {
val index = i / 4
val letter = c.toString()
stacks[index].addLast(letter)
}
}
}
return stacks
}
fun parseInstruction(instruction: String): IntArray {
// move 1 from 2 to 1
val e = instruction.split(" ")
return intArrayOf(e[1].toInt(), e[3].toInt() - 1, e[5].toInt() - 1)
}
fun applyInstruction(stacks: List<ArrayDeque<String>>, instruction: String) {
val e = parseInstruction(instruction)
(1..e[0]).forEach { _ ->
stacks[e[2]].addLast(stacks[e[1]].removeLast())
}
}
fun applyInstructionBulk(stacks: List<ArrayDeque<String>>, instruction: String) {
val e = parseInstruction(instruction)
val holder = ArrayDeque<String>()
(1..e[0]).forEach { _ ->
holder.addLast(stacks[e[1]].removeLast())
}
while(holder.isNotEmpty()) {
stacks[e[2]].addLast(holder.removeLast())
}
}
fun instructionStartIndex(input: List<String>): Int {
var idx = 0
while (input[idx].isNotEmpty()) {
idx += 1
}
return idx + 1
}
fun part1(input: List<String>): String {
val stacks = createStacks(input)
(instructionStartIndex(input)..input.lastIndex).forEach { idx ->
applyInstruction(stacks, input[idx])
}
return stacks.map { it.lastOrNull() ?: "" }.joinToString("")
}
fun part2(input: List<String>): String {
val stacks = createStacks(input)
(instructionStartIndex(input)..input.lastIndex).forEach { idx ->
applyInstructionBulk(stacks, input[idx])
}
return stacks.map { it.lastOrNull() ?: "" }.joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
println(part1(testInput))
check(part1(testInput) == "CMZ")
val input = readInput("Day05")
println(part1(input))
check(part2(testInput) == "MCD")
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 981f6014b09e347241e64ba85e0c2c96de78ef8a | 2,696 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/main/kotlin/days/Day21.kt | hughjdavey | 317,575,435 | false | null | package days
class Day21 : Day(21) {
private val foods = parseFoods()
private val unsafeIngredients = findUnsafeIngredients(foods)
// 2125
override fun partOne(): Any {
return foods.map { it.ingredients }.flatten().count { it !in unsafeIngredients.values }
}
// phc,spnd,zmsdzh,pdt,fqqcnm,lsgqf,rjc,lzvh
override fun partTwo(): Any {
return unsafeIngredients.entries.sortedBy { it.key }.joinToString(",") { it.value }
}
fun parseFoods(input: List<String> = inputList): List<Food> {
return input.map {
val (ingredients, allergens) = it.split("(contains").map { it.trim() }
Food(ingredients.split(" "), allergens.dropLast(1).split(", "))
}
}
fun findUnsafeIngredients(foods: List<Food>): Map<String, String> {
val allergensToIngredients = foods.map { it.allergens }.flatten().toSet().map { it to "" }.toMap().toMutableMap()
val commons = allergensToIngredients.keys.map { allergen ->
val containing = foods.filter { it.allergens.contains(allergen) }
val common = containing.map { it.ingredients }.fold(listOf<String>()) { acc, ingreds ->
if (acc.isEmpty()) acc.plus(ingreds) else ingreds.filter { acc.contains(it) }
}
allergen to common.toMutableList()
}
while (allergensToIngredients.values.any { it == "" }) {
commons.forEach { c ->
if (c.second.size == 1) {
val ingredient = c.second.first()
allergensToIngredients[c.first] = ingredient
commons.filterNot { it.second.isEmpty() }.forEach { it.second.removeIf { it == ingredient } }
}
}
}
return allergensToIngredients
}
data class Food(val ingredients: List<String>, val allergens: List<String>)
}
| 0 | Kotlin | 0 | 1 | 63c677854083fcce2d7cb30ed012d6acf38f3169 | 1,893 | aoc-2020 | Creative Commons Zero v1.0 Universal |
y2022/src/main/kotlin/adventofcode/y2022/Day14.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2022
import adventofcode.io.AdventSolution
import adventofcode.util.vector.Vec2
import kotlin.math.sign
object Day14 : AdventSolution(2022, 14, "<NAME>") {
override fun solvePartOne(input: String): Int {
val walls: Set<Vec2> = parse(input).toSet()
val covered = walls.toMutableSet()
val edge = walls.maxOf { it.y }
do {
val grain = generateSequence(Vec2(500, 0)) { it.fall().find { it !in covered } }
.takeWhile { it.y <= edge }
.last()
covered += grain
} while (grain.y < edge)
return covered.size - walls.size - 1
}
override fun solvePartTwo(input: String): Int {
val walls = parse(input).groupBy(Vec2::y).mapValues { it.value.mapTo(mutableSetOf(), Vec2::x) }
return (1..walls.keys.max() + 1)
.scan(setOf(500)) { prevLine, y ->
val currentLine = (-1..1).flatMapTo(mutableSetOf()) { dx -> prevLine.map(dx::plus) }
val currentWalls = walls.getOrDefault(y, emptySet())
currentLine - currentWalls
}
.sumOf { it.size }
}
private fun parse(input: String): Sequence<Vec2> {
return input.lineSequence().flatMap { line ->
line.split(" -> ")
.map { it.split(",").let { (x, y) -> Vec2(x.toInt(), y.toInt()) } }
.zipWithNext { a, b ->
val delta = (b - a).let { Vec2(it.x.sign, it.y.sign) }
generateSequence(a) { it + delta }.takeWhile { it != b } + b
}
}.flatten()
}
private fun Vec2.fall() = listOf(Vec2(x, y + 1), Vec2(x - 1, y + 1), Vec2(x + 1, y + 1))
} | 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,740 | advent-of-code | MIT License |
src/main/kotlin/org/sjoblomj/adventofcode/day3/Day3.kt | sjoblomj | 225,241,573 | false | null | package org.sjoblomj.adventofcode.day3
import org.sjoblomj.adventofcode.day3.Instruction.Direction.*
import org.sjoblomj.adventofcode.readFile
import kotlin.math.abs
private const val inputFile = "src/main/resources/inputs/day3.txt"
fun day3(): Pair<Int, Int> {
val content = readFile(inputFile)
val coordinates0 = instructionsToCoordinates(createInstructionList(content[0]))
val coordinates1 = instructionsToCoordinates(createInstructionList(content[1]))
val distance = findDistance(coordinates0, coordinates1)
val steps = findSteps(coordinates0, coordinates1)
println("Shortest distance: $distance")
println("Fewest steps: $steps")
return distance to steps
}
internal fun findSteps(coordinates0: List<Coord>, coordinates1: List<Coord>): Int {
val intersection = coordinates1.intersect(coordinates0).minus(Coord(0, 0))
val map = intersection.map { Pair(it, it.stepsTaken) }.toMap()
return coordinates0.intersect(intersection)
.map { it.stepsTaken + (map[it] ?: 0) }
.min()
?: throw RuntimeException("Failed to find fewest steps")
}
internal fun findDistance(coordinates0: List<Coord>, coordinates1: List<Coord>): Int {
return coordinates0.intersect(coordinates1.minus(Coord(0, 0)))
.map { coord -> distance(coord) }
.min()
?: throw RuntimeException("Failed to find shortest distance")
}
/**
* Manhattan distance, from (0, 0)
*/
private fun distance(coord: Coord) = abs(coord.x) + abs(coord.y)
internal fun instructionsToCoordinates(instructions: List<Instruction>): List<Coord> {
var x = 0
var y = 0
var stepsTaken = 0
val coords = mutableListOf<Coord>()
for (instruction in instructions) {
coords.addAll(
when (instruction.direction) {
R -> (0 until instruction.steps).map { Coord(x++, y, stepsTaken++) }
L -> (0 until instruction.steps).map { Coord(x--, y, stepsTaken++) }
U -> (0 until instruction.steps).map { Coord(x, y++, stepsTaken++) }
D -> (0 until instruction.steps).map { Coord(x, y--, stepsTaken++) }
})
}
coords.add(Coord(x, y, stepsTaken))
return coords
}
internal fun createInstructionList(instructions: String): List<Instruction> {
fun parseDirection(d: Char) =
when (d) {
'R' -> R
'L' -> L
'U' -> U
'D' -> D
else -> throw IllegalArgumentException("Could not parse direction '$d'")
}
return instructions.split(",")
.filter { it != "" }
.map { Instruction(parseDirection(it[0]), it.substring(1).toInt()) }
}
internal data class Instruction(val direction: Direction, val steps: Int) {
enum class Direction { R, L, U, D }
}
internal data class Coord(val x: Int, val y: Int, val stepsTaken: Int = 0) {
/**
* Ignore the stepsTaken parameter
*/
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Coord
if (x != other.x) return false
if (y != other.y) return false
return true
}
/**
* Ignore the stepsTaken parameter
*/
override fun hashCode(): Int {
var result = x
result = 31 * result + y
return result
}
}
| 0 | Kotlin | 0 | 0 | f8d03f7ef831bc7e26041bfe7b1feaaadcb40e68 | 3,038 | adventofcode2019 | MIT License |
solutions/aockt/y2022/Y2022D09.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2022
import io.github.jadarma.aockt.core.Solution
import kotlin.math.absoluteValue
object Y2022D09 : Solution {
/** The valid representation of an orthogonal rope movement. */
private val inputRegex = Regex("""^([LRUD]) ([1-9]\d*)$""")
/** Parses the [input] and returns the sequence of motions actioned on the rope head. */
private fun parseInput(input: String): Sequence<Motion> =
input
.lineSequence()
.flatMap { line ->
val (direction, times) = inputRegex.matchEntire(line)?.destructured ?: error("Invalid input")
val motion = when (direction) {
"L" -> Motion.Left
"R" -> Motion.Right
"U" -> Motion.Up
"D" -> Motion.Down
else -> error("Impossible direction.")
}
List(times.toInt()) { motion }
}
/** A position in 2D space. */
private data class Position(val x: Int, val y: Int) {
operator fun plus(delta: PositionDelta): Position = copy(x = x + delta.dx, y = y + delta.dy)
operator fun minus(delta: PositionDelta): Position = copy(x = x - delta.dx, y = y - delta.dy)
operator fun minus(other: Position): PositionDelta = PositionDelta(x - other.x, y - other.y)
}
/** The four possible directions of motions with a Planck Lengths of magnitude. */
private enum class Motion(val delta: PositionDelta) {
Left(PositionDelta(-1, 0)),
Right(PositionDelta(1, 0)),
Up(PositionDelta(0, 1)),
Down(PositionDelta(0, -1));
}
/** The difference between two [Position]s. */
private data class PositionDelta(
val dx: Int,
val dy: Int,
) {
/** Scale down the delta to a unit vector. */
val normal: PositionDelta get() = PositionDelta(dx.coerceIn(-1, 1), dy.coerceIn(-1, 1))
}
/** A rope simulation with configurable length. */
private class Rope(knots: Int, initialPosition: Position) : Iterable<Position> {
init {
require(knots >= 2) { "Rope must have at least two knots." }
}
/** Positions of the rope knots, starting from the head towards the tail. */
private val knots: Array<Position> = Array(knots) { initialPosition }
override fun iterator(): Iterator<Position> = knots.iterator()
val head: Position get() = knots.first()
val tail: Position get() = knots.last()
/** Apply this [motion] to the rope's [head] and propagate the motion towards the [tail]. */
fun move(motion: Motion) {
knots[0] = knots[0] + motion.delta
for (i in knots.indices.drop(1)) {
val link = knots[i]
val delta = knots[i - 1] - link
val step = when {
delta.dx.absoluteValue > 2 || delta.dy.absoluteValue > 2 -> error("Planck rope physics broke.")
delta.dx.absoluteValue <= 1 && delta.dy.absoluteValue <= 1 -> continue
else -> delta.normal
}
knots[i] = link + step
}
}
}
/** Simulate a rope with a given number of [knots] and return all positions visited by the tail. */
private fun simulateRopeTail(knots: Int, motions: Sequence<Motion>): Set<Position> = buildSet {
val rope = Rope(knots, Position(0, 0).also { add(it) })
motions.forEach { motion ->
rope.move(motion)
add(rope.tail)
}
}
override fun partOne(input: String) = simulateRopeTail(2, parseInput(input)).size
override fun partTwo(input: String) = simulateRopeTail(10, parseInput(input)).size
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 3,748 | advent-of-code-kotlin-solutions | The Unlicense |
src/main/kotlin/day04/Day04.kt | TheSench | 572,930,570 | false | {"Kotlin": 128505} | package day04
import runDay
import toPair
fun main() {
fun part1(input: List<String>): Int {
return input.mapToPairsOfRanges()
.count { it.oneFullyContainsOther() }
}
fun part2(input: List<String>): Int {
return input.mapToPairsOfRanges()
.count { it.overlap() }
}
(object {}).runDay(
part1 = ::part1,
part1Check = 2,
part2 = ::part2,
part2Check = 4
)
}
private fun List<String>.mapToPairsOfRanges() = map { it.split(",") }
.map { pair -> pair.map(String::toRange).toPair() }
private fun String.toRange() = split("-")
.let {
val left = it[0].toInt()
val right = it[1].toInt()
left..right
}
private fun Pair<IntRange, IntRange>.oneFullyContainsOther() =
(first.contains((second)) || second.contains(first))
private fun IntRange.contains(other: IntRange) =
first <= other.first && last >= other.last
private fun Pair<IntRange, IntRange>.overlap() =
first.intersect(second).isNotEmpty()
| 0 | Kotlin | 0 | 0 | c3e421d75bc2cd7a4f55979fdfd317f08f6be4eb | 1,037 | advent-of-code-2022 | Apache License 2.0 |
src/day08/Day08.kt | henrikrtfm | 570,719,195 | false | {"Kotlin": 31473} | package day08
import utils.Resources.resourceAsListOfString
typealias Treemap = Array<IntArray>
typealias Point = Pair<Int, Int>
fun main() {
val input = resourceAsListOfString("src/day08/Day08.txt")
val treemap: Treemap = input
.map { it.chunked(1) }
.map { it -> it.map { it -> it.toInt() }.toIntArray() }
.toTypedArray()
val maxX = treemap.first().size-1
val maxY = treemap.last().size-1
fun returnLineOfSight(point: Point): Lineofsight{
val lineOfSight = Lineofsight()
lineOfSight.up = (0 until point.first).map{Point(it,point.second)}
lineOfSight.down = (point.first+1..maxX).map{Point(it,point.second)}
lineOfSight.left = (0 until point.second).map{Point(point.first,it)}
lineOfSight.right = (point.second+1..maxY).map{Point(point.first,it)}
return lineOfSight
}
fun isVisible(point: Point): Point?{
val lineofsight = returnLineOfSight(point)
val self = treemap[point.first][point.second]
val up = lineofsight.up.map { treemap[it.first][it.second] } + self
val down = lineofsight.down.map { treemap[it.first][it.second] } + self
val left = lineofsight.left.map { treemap[it.first][it.second] } + self
val right = lineofsight.right.map { treemap[it.first][it.second] } + self
return if((up.maxOrNull() == self && up.groupingBy { it }.eachCount()[self] ==1)
|| (down.maxOrNull() == self && down.groupingBy { it }.eachCount()[self] ==1)
|| (left.maxOrNull() == self && left.groupingBy { it }.eachCount()[self] ==1)
|| (right.maxOrNull() == self && right.groupingBy { it }.eachCount()[self] ==1)){
point
}else
null
}
fun scenicScore(point:Point): Int{
val lineofsight = returnLineOfSight(point)
val self = treemap[point.first][point.second]
val viewUp = lineofsight.up.map { treemap[it.first][it.second] }.reversed().countUntil{it >= self}
val viewLeft = lineofsight.left.map { treemap[it.first][it.second] }.reversed().countUntil{it >= self}
val viewRight = lineofsight.right.map { treemap[it.first][it.second] }.countUntil{it >= self}
val viewDown = lineofsight.down.map { treemap[it.first][it.second] }.countUntil { it >= self }
return viewUp*viewLeft*viewRight*viewDown
}
fun part1(): Int{
return treemap
.flatMapIndexed{indexrow, row -> row.mapIndexed{indexcol, _ -> isVisible(Point(indexrow,indexcol))}}
.filterNotNull()
.count()
}
fun part2(): Int{
return treemap
.flatMapIndexed{indexrow, row -> row.mapIndexed{indexcol, _ -> scenicScore(Point(indexrow,indexcol))}}
.max()
}
println(part1())
println(part2())
}
data class Lineofsight(
var up: List<Point> = mutableListOf(),
var down: List<Point> = mutableListOf(),
var left: List<Point> = mutableListOf(),
var right: List<Point> = mutableListOf()
)
private fun List<Int>.countUntil(pred: (Int) -> Boolean): Int{
var res = 0
for (element in this) {
res++
if (pred(element))
return res
}
return res
}
| 0 | Kotlin | 0 | 0 | 20c5112594141788c9839061cb0de259f242fb1c | 3,224 | aoc2022 | Apache License 2.0 |
src/Day21.kt | Flame239 | 570,094,570 | false | {"Kotlin": 60685} | private fun input(): Map<String, M> {
return readInput("Day21").associate { l ->
val (id, exp) = l.split(": ")
val expS = exp.split(" ")
if (expS.size == 1) {
id to M(id, const = exp.toLong())
} else {
parent[expS[2]] = id
parent[expS[0]] = id
id to M(id, l = expS[0], r = expS[2], op = expS[1])
}
}
}
private val parent = HashMap<String, String>()
private var monkeys = input()
private fun part1(): Long {
return calc("root")
}
private fun calc(id: String): Long {
val m = monkeys[id]!!
return m.const ?: m.calc(calc(m.l!!), calc(m.r!!))
}
private fun part2(): Long {
return calculateHumn("humn")
}
private fun calculateHumn(id: String): Long {
val p = parent[id]!!
val pM = monkeys[p]!!
val left = pM.l!! == id
val other = if (left) calc(pM.r!!) else calc(pM.l!!)
return if (p == "root") other else pM.calcInv(calculateHumn(p), other, left)
}
fun main() {
measure { part1() }
measure { part2() }
}
private data class M(
val id: String,
val const: Long? = null,
val l: String? = null,
val r: String? = null,
val op: String? = null
) {
fun calc(a: Long, b: Long): Long {
return when (op) {
"+" -> a + b
"-" -> a - b
"*" -> a * b
"/" -> a / b
else -> -1
}
}
fun calcInv(value: Long, other: Long, left: Boolean): Long {
return when (op) {
"+" -> value - other
"-" -> if (left) value + other else other - value
"*" -> value / other
"/" -> if (left) value * other else other / value
else -> -1
}
}
} | 0 | Kotlin | 0 | 0 | 27f3133e4cd24b33767e18777187f09e1ed3c214 | 1,730 | advent-of-code-2022 | Apache License 2.0 |
year2017/src/main/kotlin/net/olegg/aoc/year2017/day24/Day24.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2017.day24
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.year2017.DayOf2017
import java.util.BitSet
import kotlin.math.max
/**
* See [Year 2017, Day 24](https://adventofcode.com/2017/day/24)
*/
object Day24 : DayOf2017(24) {
override fun first(): Any? {
val ports = lines
.map { line -> line.split("/").mapNotNull { it.toIntOrNull() } }
.mapIndexed { index, value ->
Triple(value.min(), value.max(), index)
}
var best = 0
val start = ports
.filter { it.first == 0 || it.second == 0 }
.map { port ->
val next = if (port.first == 0) port.second else port.first
return@map Triple(next, next, BitSet(ports.size).also { it.set(port.third) })
}
val queue = ArrayDeque(start)
val visited = queue.map { it.first to it.third }.toMutableSet()
while (queue.isNotEmpty()) {
val curr = queue.removeFirst()
best = max(best, curr.second)
ports
.filter { !curr.third[it.third] }
.filter { it.first == curr.first || it.second == curr.first }
.map { port ->
val next = if (port.first == curr.first) port.second else port.first
Triple(
next,
curr.second + port.first + port.second,
BitSet(ports.size).also { it.or(curr.third) }.also { it.set(port.third) },
)
}
.filterNot { (it.first to it.third) in visited }
.forEach { port ->
visited.add(port.first to port.third)
queue.add(port)
}
}
return best
}
override fun second(): Any? {
val ports = lines
.map { line -> line.split("/").mapNotNull { it.toIntOrNull() } }
.mapIndexed { index, value ->
Triple(value.min(), value.max(), index)
}
val start = ports
.filter { it.first == 0 || it.second == 0 }
.map { port ->
val next = if (port.first == 0) port.second else port.first
return@map Triple(next, (2 to next), BitSet(ports.size).also { it.set(port.third) })
}
val queue = ArrayDeque(start)
val visited = queue.map { it.first to it.third }.toMutableSet()
var best = 0 to 0
while (queue.isNotEmpty()) {
val curr = queue.removeFirst()
best = maxOf(best, curr.second, compareBy({ it.first }, { it.second }))
ports.filter { !curr.third[it.third] }
.filter { it.first == curr.first || it.second == curr.first }
.map { port ->
val next = if (port.first == curr.first) port.second else port.first
Triple(
next,
(curr.second.first + 1 to curr.second.second + port.first + port.second),
BitSet(ports.size).also { it.or(curr.third) }.also { it.set(port.third) },
)
}
.filterNot { (it.first to it.third) in visited }
.forEach { port ->
visited.add(port.first to port.third)
queue.addLast(port)
}
}
return best.second
}
}
fun main() = SomeDay.mainify(Day24)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 3,032 | adventofcode | MIT License |
src/main/kotlin/dev/sirch/aoc/y2022/days/Day07.kt | kristofferchr | 573,549,785 | false | {"Kotlin": 28399, "Mustache": 1231} | package dev.sirch.aoc.y2022.days
import dev.sirch.aoc.Day
class Day07(testing: Boolean = false) : Day(2022, 7, testing) {
override fun part1(): Int {
val tree = constructTree(inputLines)
return tree.getAllDirsWithLessSizeThanUpperLimit(100000)!!
}
override fun part2(): Int {
val tree = constructTree(inputLines)
val maximumSize = 70000000
val unusedSpace = maximumSize - tree.size
val updateRequiresSize = 30000000
val needsToFreeSize = updateRequiresSize - unusedSpace
return tree.getDirSizeClosestToLowerLimit(needsToFreeSize)!!
}
}
data class Node(
val name: String,
var size: Int = 0,
val parent: Node? = null,
val children: MutableMap<String, Node> = mutableMapOf()
) {
fun addChild(name: String, size: Int = 0) {
val newNode = Node(name = name, parent = this, size = size)
children[name] = newNode
}
fun getAllDirsWithLessSizeThanUpperLimit(upperLimit: Int): Int? {
val isDir = children.isNotEmpty()
if (!isDir) {
return null
}
var totalSizeOfDirsWithLessThanUpperLimit = if (size <= upperLimit) size else 0
children.forEach { (name, node) ->
val childSizes = node.getAllDirsWithLessSizeThanUpperLimit(upperLimit)
if (childSizes != null) {
totalSizeOfDirsWithLessThanUpperLimit += childSizes
}
}
return totalSizeOfDirsWithLessThanUpperLimit
}
fun getDirSizeClosestToLowerLimit(lowerLimit: Int): Int? {
if (children.isEmpty()) {
return null
}
var sizeClosestToLowerLimit = size
children.forEach { (name, node) ->
val childDirClosestToLowerLimit = node.getDirSizeClosestToLowerLimit(lowerLimit)
if (childDirClosestToLowerLimit != null) {
if (childDirClosestToLowerLimit in (lowerLimit until sizeClosestToLowerLimit)) {
sizeClosestToLowerLimit = childDirClosestToLowerLimit
}
}
}
return sizeClosestToLowerLimit
}
fun calculateDirSizes(): Int {
return if (size != 0) {
size
} else {
val sizeOfDirs = children.map { (key, node) ->
node.calculateDirSizes()
}.sum()
size = sizeOfDirs
size
}
}
fun getChild(name: String): Node? {
return children.get(name)
}
}
fun constructTree(input: List<String>): Node {
val rootNode = Node(name = "root")
var currentNode = rootNode
input.forEach {
if (it.startsWith("$")) {
val operators = it.split(" ")
if (operators[1] == "cd") {
val dir = operators[2]
currentNode = if (dir == "..") {
currentNode.parent ?: throw IllegalStateException("Root node does not have a parent")
} else {
currentNode.getChild(dir) ?: throw IllegalStateException("Could not find node iwth name=$dir")
}
}
} else {
val (prefix, name) = it.split(" ")
if (prefix == "dir") {
currentNode.addChild(name)
} else {
currentNode.addChild(name, size = prefix.toInt())
}
}
}
rootNode.calculateDirSizes()
return rootNode
}
| 0 | Kotlin | 0 | 0 | 867e19b0876a901228803215bed8e146d67dba3f | 3,437 | advent-of-code-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.