path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/se/brainleech/adventofcode/aoc2021/Aoc2021Day02.kt | fwangel | 435,571,075 | false | {"Kotlin": 150622} | package se.brainleech.adventofcode.aoc2021
import se.brainleech.adventofcode.compute
import se.brainleech.adventofcode.readLines
import se.brainleech.adventofcode.verify
class Aoc2021Day02 {
companion object {
private const val COMMAND_DATA_SEPARATOR = " "
}
data class Command(val direction: String, val amount: Long)
class Position(var horizontal: Long = 0, var depth: Long = 0) {
private var aim: Long = 0
fun apply(command: Command) {
when (command.direction) {
"up" -> this.depth -= command.amount
"down" -> this.depth += command.amount
"forward" -> this.horizontal += command.amount
}
}
fun applyWithAim(command: Command) {
when (command.direction) {
"up" -> this.aim -= command.amount
"down" -> this.aim += command.amount
"forward" -> {
this.horizontal += command.amount
this.depth += this.aim * command.amount
}
}
}
}
private fun String.asCommand(): Command {
val (direction, amount) = this.split(COMMAND_DATA_SEPARATOR)
return Command(direction, amount.toLong())
}
fun part1(input: List<String>): Long {
val p = Position()
input.forEach { p.apply(it.asCommand()) }
return p.horizontal * p.depth
}
fun part2(input: List<String>): Long {
val p = Position()
input.forEach { p.applyWithAim(it.asCommand()) }
return p.horizontal * p.depth
}
}
fun main() {
val solver = Aoc2021Day02()
val prefix = "aoc2021/aoc2021day02"
val testData = readLines("$prefix.test.txt")
val realData = readLines("$prefix.real.txt")
verify(150L, solver.part1(testData))
compute({ solver.part1(realData) }, "$prefix.part1 = ")
verify(900L, solver.part2(testData))
compute({ solver.part2(realData) }, "$prefix.part2 = ")
}
| 0 | Kotlin | 0 | 0 | 0bba96129354c124aa15e9041f7b5ad68adc662b | 2,004 | adventofcode | MIT License |
src/main/kotlin/cz/tomasbublik/Day04.kt | tomasbublik | 572,856,220 | false | {"Kotlin": 21908} | package cz.tomasbublik
fun main() {
fun createPairsStructure(input: List<String>): ArrayList<Pair<IntRange, IntRange>> {
val duals = ArrayList<Pair<IntRange, IntRange>>()
for (line in input) {
val firstRange = line.split(",")[0].split("-")[0].toInt()..line.split(",")[0].split("-")[1].toInt()
val secondRange = line.split(",")[1].split("-")[0].toInt()..line.split(",")[1].split("-")[1].toInt()
val currentPair = Pair<IntRange, IntRange>(firstRange, secondRange)
duals.add(currentPair)
}
return duals
}
fun part1(input: List<String>): Int {
var numberOfCovers = 0
val duals = createPairsStructure(input)
// test is one contained in other
for (pair in duals) {
if (pair.first == pair.second) {
numberOfCovers++
continue
}
// the first one is contained in the second one
if (pair.second.contains(pair.first.first) && pair.second.contains(pair.first.last)) {
numberOfCovers++
}
// the second one is contained in the first one
if (pair.first.contains(pair.second.first) && pair.first.contains(pair.second.last)) {
numberOfCovers++
}
}
return numberOfCovers
}
fun part2(input: List<String>): Int {
val duals = createPairsStructure(input)
var numberOfCovers = 0
for (pair in duals) {
if (pair.second.contains(pair.first.first) || pair.second.contains(pair.first.last)) {
numberOfCovers++
continue
}
if (pair.first.contains(pair.second.first) || pair.first.contains(pair.second.last)) {
numberOfCovers++
continue
}
}
return numberOfCovers
}
// test if implementation meets criteria from the description, like:
val testInput = readFileAsLinesUsingUseLines("src/main/resources/day_4_input_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readFileAsLinesUsingUseLines("src/main/resources/day_4_input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8c26a93e8f6f7ab0f260c75a287608dd7218d0f0 | 2,266 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/jvmMain/kotlin/day05/initial/Day05.kt | liusbl | 726,218,737 | false | {"Kotlin": 109684} | package day05.initial
import util.add
import util.updateLast
import java.io.File
fun main() {
// Overslept and started at 07:43
// solvePart1() // Solution: 340994526, at 08:49
solvePart2() // Solution:
}
/**
*
seed-to-soil map:
52 50 48
50 98 2
0 -> 0 <-- key point (unmarked)
1 -> 1
..
49 -> 49
50 -> 52 <-- key point
51 -> 53
..
97 -> 99
98 -> 50 <-- key point
99 -> 51
100 -> 100 <- key point (unmarked)
100 -> 101
..
=====
soil-to-fertilizer map:
39 0 15
0 15 37
37 52 2
0 -> 39 <-- key point
1 -> 40
..
14 -> 53
15 -> 0 <-- key point
16 -> 1
..
51 -> 36
52 -> 37 <-- key point
53 -> 38
54 -> 54 <-- key point
55 -> 55
..
==========
COMBINATED seed-to-fertilizer map:
0 -> 39 <-- key point
1 -> 40
..
*/
fun solvePart2() {
val input = File("src/jvmMain/kotlin/day05/input/input_part1_test.txt")
// val input = File("src/jvmMain/kotlin/day05/input/input.txt")
val lines = input.readLines()
val seedNumbers = lines[0].split(":")[1].trim().split(" ").map { it.toLong() }
val seedList = seedNumbers.foldIndexed(emptyList<Seed>()) { index, acc, next ->
if (index % 2 == 0) {
acc.add(Seed(number = next, length = 0))
} else {
acc.updateLast { copy(length = next) }
}
}
val seeds = seedList.flatMap { List(it.length.toInt()) { index -> it.number + index } }
println("Seeds: $seeds")
val categoryList = lines.drop(2).fold(emptyList<Category>()) { acc, line ->
if (line.contains("map")) {
val name = line.split(" ")[0]
acc.add(Category(name, emptyList()))
} else if (line.isBlank()) {
acc
} else {
val (destination, source, length) = line.split(" ").map { it.toLong() }
val map = Map(destination = destination, source = source, length = length)
acc.updateLast { copy(list = list.add(map)) }
}
}.map { category -> category.copy(list = category.list.sortedBy { map -> map.source }) }
val seedCheckList = mutableListOf<Long>()
(564468486L..(564468486+ 226119074)).forEach { startSeed0 ->
val category0 = categoryList[0] // seed-to-soil
val startSources0 = category0.list.map { it.source }
val endSources0 = category0.list.map { it.source + it.length }
val endSeed0 = category0.list.find { it.contains(startSeed0) }?.next(startSeed0) ?: startSeed0
val inStartSources0 = startSources0.any { it == startSeed0 }
val inEndSources0 = endSources0.any { it == startSeed0 }
val inStartSourceText0 = if (inStartSources0) " StartSource0 " else ""
val inEndSourceText0 = if (inEndSources0) " EndSource0 " else ""
val category1 = categoryList[1] // soil-to-fertilizer
val startSources1 = category1.list.map { it.source }
val endSources1 = category1.list.map { it.source + it.length }
val endSeed1 = category1.list.find { it.contains(endSeed0) }?.next(endSeed0) ?: endSeed0
val inStartSources1 = startSources1.any { it == endSeed0 }
val inEndSources1 = endSources1.any { it == endSeed0 }
val inStartSourceText1 = if (inStartSources1) " StartSource1 " else ""
val inEndSourceText1 = if (inEndSources1) " EndSource1 " else ""
val category2 = categoryList[2] // fertilizer-to-water
val startSources2 = category2.list.map { it.source }
val endSources2 = category2.list.map { it.source + it.length }
val endSeed2 = category2.list.find { it.contains(endSeed1) }?.next(endSeed1) ?: endSeed1
val inStartSources2 = startSources2.any { it == endSeed1 }
val inEndSources2 = endSources2.any { it == endSeed1 }
val inStartSourceText2 = if (inStartSources2) " StartSource2 " else ""
val inEndSourceText2 = if (inEndSources2) " EndSource2 " else ""
val category3 = categoryList[3] // water-to-light
val startSources3 = category3.list.map { it.source }
val endSources3 = category3.list.map { it.source + it.length }
val endSeed3 = category3.list.find { it.contains(endSeed2) }?.next(endSeed2) ?: endSeed2
val inStartSources3 = startSources3.any { it == endSeed2 }
val inEndSources3 = endSources3.any { it == endSeed2 }
val inStartSourceText3 = if (inStartSources3) " StartSource3 " else ""
val inEndSourceText3 = if (inEndSources3) " EndSource3 " else ""
val category4 = categoryList[4] // light-to-temperature
val startSources4 = category4.list.map { it.source }
val endSources4 = category4.list.map { it.source + it.length }
val endSeed4 = category4.list.find { it.contains(endSeed3) }?.next(endSeed3) ?: endSeed3
val inStartSources4 = startSources4.any { it == endSeed3 }
val inEndSources4 = endSources4.any { it == endSeed3 }
val inStartSourceText4 = if (inStartSources4) " StartSource4 " else ""
val inEndSourceText4 = if (inEndSources4) " EndSource4 " else ""
val category5 = categoryList[5] // temperature-to-humidity
val startSources5 = category5.list.map { it.source }
val endSources5 = category5.list.map { it.source + it.length }
val endSeed5 = category5.list.find { it.contains(endSeed4) }?.next(endSeed4) ?: endSeed4
val inStartSources5 = startSources5.any { it == endSeed4 }
val inEndSources5 = endSources5.any { it == endSeed4 }
val inStartSourceText5 = if (inStartSources5) " StartSource5 " else ""
val inEndSourceText5 = if (inEndSources5) " EndSource5 " else ""
val category6 = categoryList[6] // humidity-to-location
val startSources6 = category6.list.map { it.source }
val endSources6 = category6.list.map { it.source + it.length }
val endSeed6 = category6.list.find { it.contains(endSeed5) }?.next(endSeed5) ?: endSeed5
val inStartSources6 = startSources6.any { it == endSeed5 }
val inEndSources6 = endSources6.any { it == endSeed5 }
val inStartSourceText6 = if (inStartSources6) " StartSource6 " else ""
val inEndSourceText6 = if (inEndSources6) " EndSource6 " else ""
println(
"$startSeed0 -> $endSeed0 -> $endSeed1 -> $endSeed2 -> " +
"$endSeed3 -> $endSeed4 -> $endSeed5 -> $endSeed6. " +
"$inStartSourceText0 $inEndSourceText0 " +
"$inStartSourceText1 $inEndSourceText1 " +
"$inStartSourceText2 $inEndSourceText2 " +
"$inStartSourceText3 $inEndSourceText3 " +
"$inStartSourceText4 $inEndSourceText4 " +
"$inStartSourceText5 $inEndSourceText5 " +
"$inStartSourceText6 $inEndSourceText6 " +
""
)
if (inStartSources0 || inEndSources0 ||
inStartSources1 || inEndSources1 ||
inStartSources2 || inEndSources2 ||
inStartSources3 || inEndSources3 ||
inStartSources4 || inEndSources4 ||
inStartSources5 || inEndSources5 ||
inStartSources6 || inEndSources6
) {
seedCheckList.add(startSeed0)
}
}
println("Minimal set of seeds that need to be checked: $seedCheckList")
}
fun thing(category: Category, seed: Long): Pair<Boolean, Long> {
val firstNextSeed = category.list.find { it.contains(seed) }?.next(seed) ?: seed
val firstKeyPoints = category.list.map { it.source to it.source + it.length }
return firstKeyPoints.any { it.first == seed || it.second == seed } to firstNextSeed
}
/**
* Experiment 5
*/
//
//
//fun thing(category: Category, seed: Long): Pair<Boolean, Long> {
// val firstNextSeed = category.list.find { it.contains(seed) }?.next(seed) ?: seed
// val firstKeyPoints = category.list.map { it.source to it.source + it.length }
// return firstKeyPoints.any { it.first == seed || it.second == seed } to firstNextSeed
//}
//
//fun solvePart2() {
// val input = File("src/jvmMain/kotlin/day05/input/input_part1_test.txt")
//// val input = File("src/jvmMain/kotlin/day05/input/input.txt")
// val lines = input.readLines()
//
// val seedNumbers = lines[0].split(":")[1].trim().split(" ").map { it.toLong() }
// val seedList = seedNumbers.foldIndexed(emptyList<Seed>()) { index, acc, next ->
// if (index % 2 == 0) {
// acc.add(Seed(number = next, length = 0))
// } else {
// acc.updateLast { copy(length = next) }
// }
// }
//
// val seeds = seedList.flatMap { List(it.length.toInt()) { index -> it.number + index } }
//
// println("Seeds: $seeds")
//
// val categoryList = lines.drop(2).fold(emptyList<Category>()) { acc, next ->
// if (next.contains("map")) {
// acc.add(Category(emptyList()))
// } else if (next.isBlank()) {
// // complete category
// acc
// } else {
// val (destination, source, length) = next.split(" ").map { it.toLong() }
// val map = Map(destination = destination, source = source, length = length)
//
// val last = acc.last()
//
// val category = Category(last.list.add(map))
//
// acc.updateLast(category)
// }
// }.map { category -> category.copy(list = category.list.sortedBy { map -> map.source }) }
//
//// val keyPoints = categoryList.map { it.list.map { it.source } }
//// println("Key points: ${keyPoints.take(2)}")
//
// println(categoryList.joinToString("\n"))
//
// /***** Experiments *////
//
//
// /**
// * Experiment 4
// */
// val listOfSeedsToCheck = listOf(50L).filter { seed ->
//// val listOfSeedsToCheck = (79..92L).filter { seed ->
// val category0 = categoryList[0]
// val (contains1, seed1) = thing(category0, seed)
//
// val category1 = categoryList[1]
// val (contains2, seed2) = thing(category1, seed1)
//
// val category2 = categoryList[2]
// val (contains3, seed3) = thing(category2, seed2)
//
// val category3 = categoryList[3]
// val (contains4, seed4) = thing(category3, seed3)
//
// val category4 = categoryList[4]
// val (contains5, seed5) = thing(category4, seed4)
//
// val category5 = categoryList[5]
// val (contains6, seed6) = thing(category5, seed5)
//
// val category6 = categoryList[6]
// val (contains7, seed7) = thing(category6, seed6)
//// println(category6)
//
// println("$seed -> $seed1 -> $seed2 -> $seed3 -> $seed4 -> $seed5 -> $seed6 -> $seed7")
// println("$contains1 $contains2 $contains3 $contains4 $contains5 $contains6 $contains7")
// println()
// true
// }
//
// println(listOfSeedsToCheck)
/**
* Experiment 3
*/
// val endSeed = 100L
// val firstCategory = categoryList[0]
// val firstKeyPoints = firstCategory.list.map { it.source to it.source + it.length }
//
// val secondCategory = categoryList[1]
//// val secondKeyPoints = secondCategory.list.map { it.source to it.source + it.length }
//
// var startSeed = 0L
//
// while (startSeed <= endSeed) {
// val firstNextSeed = firstCategory.list.find { it.contains(startSeed) }?.next(startSeed) ?: startSeed
// val secondNextSeed = secondCategory.list.find { it.contains(firstNextSeed) }?.next(firstNextSeed) ?: firstNextSeed
//
// println("startSeed: ${startSeed}")
// println(
// "firstCategory: ${firstCategory}\n" +
// "firstNextSeed: ${firstNextSeed}\n" +
// "firstKeyPoints: ${firstKeyPoints}\n" +
// "mapping: $startSeed to $firstNextSeed to $secondNextSeed"
// )
// println()
// println(
// "secondCategory: ${secondCategory}\n" +
// "secondNextSeed: ${secondNextSeed}\n" +
// "secondKeyPoints: ${secondKeyPoints}\n"
// )
// println("==================")
//
// startSeed = firstKeyPoints.find { it.first > startSeed }?.first!!
// }
/**
* Experiment 2
*/
// val endSeed = 100L
//
// val firstCategory = categoryList[0]
// val firstKeyPoints = firstCategory.list.map { it.source to it.source + it.length }
//
// val secondCategory = categoryList[1]
// val secondKeyPoints = secondCategory.list.map { it.source to it.source + it.length }
//
// var startSeed = 0L
//
// while (startSeed <= endSeed) {
// val firstNextSeed = firstCategory.list.find { it.contains(startSeed) }?.next(startSeed) ?: startSeed
// val secondNextSeed = secondCategory.list.find { it.contains(firstNextSeed) }?.next(firstNextSeed) ?: firstNextSeed
//
// println("startSeed: ${startSeed}")
// println(
// "firstCategory: ${firstCategory}\n" +
// "firstNextSeed: ${firstNextSeed}\n" +
// "firstKeyPoints: ${firstKeyPoints}\n" +
// "mapping: $startSeed to $firstNextSeed to $secondNextSeed"
// )
// println()
// println(
// "secondCategory: ${secondCategory}\n" +
// "secondNextSeed: ${secondNextSeed}\n" +
// "secondKeyPoints: ${secondKeyPoints}\n"
// )
// println("==================")
//
// startSeed = firstKeyPoints.find { it.first > startSeed }?.first!!
// /**
// * Experiment 1
// */
// val listOfSeedsToCheck = (0..100L).filter { seed ->
// val firstCategory = categoryList[0]
// val firstNextSeed = firstCategory.list.find { it.contains(seed) }?.next(seed) ?: seed
// val firstKeyPoints = firstCategory.list.map { it.source }
// val firstEndPoints = firstCategory.list.map { it.source + it.length }
//
// val secondCategory = categoryList[1]
// val secondNextSeed = secondCategory.list.find { it.contains(firstNextSeed) }?.next(firstNextSeed)
// ?: firstNextSeed
// val secondKeyPoints = secondCategory.list.map { it.source }
// val secondEndPoints = secondCategory.list.map { it.source + it.length }
//
// println(
// "$seed to $firstNextSeed to $secondNextSeed. " +
// "In List 1: ${firstKeyPoints.contains(seed).display()}. " +
// "In List 2: ${secondKeyPoints.contains(firstNextSeed).display()}. " +
// "In Endpoint 1: ${firstEndPoints.contains(seed).display()}. " +
// "In Endpoint 2: ${secondEndPoints.contains(firstNextSeed).display()}. "
// )
// firstKeyPoints.contains(seed) ||
// secondKeyPoints.contains(firstNextSeed) ||
// firstEndPoints.contains(seed) ||
// secondEndPoints.contains(firstNextSeed)
// }
//
// println(listOfSeedsToCheck)
//}
fun Boolean.display(): String {
return if (this) "_TRUE" else "false"
}
// Is there a way to combine categories so that I that instead of seed-to-soil to soil-to-fertilizer
// we could directly do seed-to-fertilizer??
fun keyNumbersToCheck() {
}
data class Category(
val name: String,
val list: List<Map>
) {
fun next(seed: Long): Long {
return list.fold(seed) { acc, map ->
map.next(acc)
}
// list.find { map ->
// map
// } ?: Map(seed, seed, 1)
// }
}
}
data class Seed(
val number: Long,
val length: Long
)
data class Map(
val destination: Long,
val source: Long,
val length: Long
) {
fun contains(seed: Long): Boolean {
return seed >= source && seed <= source + length - 1
}
fun next(seed: Long): Long =
if (contains(seed)) {
val delta = seed - source
destination + delta
} else {
seed
}
}
//fun solvePart1() {
//// val input = File("src/jvmMain/kotlin/day05/input/input_part1_test.txt")
// val input = File("src/jvmMain/kotlin/day05/input/input.txt")
// val lines = input.readLines()
//
// val seeds = lines[0].split(":")[1].trim().split(" ").map { it.toLong() }
//
// val categoryList = lines.drop(2).fold(emptyList<Category>()) { acc, next ->
// if (next.contains("map")) {
// acc.add(Category(emptyList()))
// } else if (next.isBlank()) {
// // complete category
// acc
// } else {
// val (destination, source, length) = next.split(" ").map { it.toLong() }
// val map = Map(destination = destination, source = source, length = length)
//
// val last = acc.last()
//
// val category = Category(last.list.add(map))
//
// acc.updateLast(category)
// }
// }
//
// val min = seeds.minOfOrNull { seed ->
// val res = categoryList.fold(seed) { acc, category ->
// category.list.find { it.contains(acc) }?.next(acc) ?: acc
// }
// println(res)
// println()
// res
// }
//
// println("min: $min")
//}
| 0 | Kotlin | 0 | 0 | 1a89bcc77ddf9bc503cf2f25fbf9da59494a61e1 | 16,986 | advent-of-code | MIT License |
src/day08/Day08.kt | TheRishka | 573,352,778 | false | {"Kotlin": 29720} | package day08
import readInput
fun main() {
val input = readInput("day08/Day08")
val matrixInput = arrayListOf<Int>()
input.forEach {
it.forEach { treeAsChar ->
matrixInput.add(treeAsChar.digitToInt())
}
}
val matrixCols = input[0].length
val matrixRows = input.size
/*
0 1 2 3 4 0 1 2 3 4
0 3 0 3 7 3 0 0 1 2 3 4
1 2 5 5 1 2 1 5 6 7 8 9
2 6 5 3 3 2 2 10 11 12 13 14
3 3 3 5 4 9 3 15 16 17 18 19
4 3 5 3 9 0 4 20 21 22 23 24
*/
fun part1(matrixInput: ArrayList<Int>): Int {
var visibleCounter = 0
matrixInput.forEachIndexed { index, tree ->
val treeData = calculateTreeData(
inputMatrix = matrixInput,
matrixCols = matrixCols,
matrixRows = matrixRows,
treeIndex = index
)
if (treeData.isVisible) {
visibleCounter++
}
}
return visibleCounter
}
fun part2(matrixInput: ArrayList<Int>): Int {
val scenicScoreCounter = mutableListOf<TreeData>()
matrixInput.forEachIndexed { index, tree ->
val treeData = calculateTreeData(
inputMatrix = matrixInput,
matrixCols = matrixCols,
matrixRows = matrixRows,
treeIndex = index
)
if (treeData.isVisible) {
scenicScoreCounter.add(treeData)
}
}
scenicScoreCounter.sortByDescending {
it.scenicScore
}
return scenicScoreCounter.maxBy {
it.scenicScore
}.scenicScore
}
println(part1(matrixInput = matrixInput))
println(part2(matrixInput = matrixInput))
}
fun calculateTreeData(
inputMatrix: ArrayList<Int>,
matrixCols: Int,
matrixRows: Int,
treeIndex: Int
): TreeData {
when {
treeIndex / matrixRows == 0 || treeIndex / matrixRows == matrixRows - 1 -> {
// It's on top or bottom
return TreeData(isVisible = true, scenicScore = 0)
}
treeIndex % matrixCols == 0 || treeIndex % matrixCols == matrixCols - 1 -> {
// It's on left or right
return TreeData(isVisible = true, scenicScore = 0)
}
else -> {
// Meaning it's somewhere in the middle.
var isVisibleFromLeft = true
var isVisibleFromTop = true
var isVisibleFromRight = true
var isVisibleFromBottom = true
var treesToTheLeft = 0
var treesToTheRight = 0
var treesToTheTop = 0
var treesToTheBottom = 0
val heightOfOurTree = inputMatrix[treeIndex]
var indexOfTreeToCheck = treeIndex - 1
// Check from Left:
do {
val heightOfTreeToCheck = inputMatrix[indexOfTreeToCheck]
treesToTheLeft++
if (heightOfTreeToCheck >= heightOfOurTree) {
isVisibleFromLeft = false
break
}
} while (indexOfTreeToCheck-- % matrixCols > 0)
indexOfTreeToCheck = treeIndex + 1
// Check from Right:
do {
val heightOfTreeToCheck = inputMatrix[indexOfTreeToCheck]
treesToTheRight++
if (heightOfTreeToCheck >= heightOfOurTree) {
isVisibleFromRight = false
break
}
indexOfTreeToCheck
} while (indexOfTreeToCheck++ % matrixCols < matrixCols - 1)
indexOfTreeToCheck = treeIndex - matrixCols
// Check from Top
do {
val heightOfTreeToCheck = inputMatrix[indexOfTreeToCheck]
treesToTheTop++
if (heightOfTreeToCheck >= heightOfOurTree) {
isVisibleFromTop = false
break
}
indexOfTreeToCheck -= matrixCols
} while (indexOfTreeToCheck / matrixRows >= 0 && indexOfTreeToCheck > 0)
// Check from Bottom
indexOfTreeToCheck = treeIndex + matrixCols
do {
val heightOfTreeToCheck = inputMatrix[indexOfTreeToCheck]
treesToTheBottom++
if (heightOfTreeToCheck >= heightOfOurTree) {
isVisibleFromBottom = false
break
}
indexOfTreeToCheck += matrixCols
} while (indexOfTreeToCheck / matrixRows < matrixRows && indexOfTreeToCheck > 0)
return TreeData(
isVisible = isVisibleFromBottom || isVisibleFromTop || isVisibleFromRight || isVisibleFromLeft,
scenicScore = treesToTheBottom * treesToTheLeft * treesToTheRight * treesToTheTop
)
}
}
}
data class TreeData(
val isVisible: Boolean,
val scenicScore: Int,
) | 0 | Kotlin | 0 | 1 | 54c6abe68c4867207b37e9798e1fdcf264e38658 | 5,079 | AOC2022-Kotlin | Apache License 2.0 |
src/Day19.kt | greg-burgoon | 573,074,283 | false | {"Kotlin": 120556} |
import kotlin.collections.HashMap
fun main() {
var priorityValues = HashMap<Char, Int>()
var count = 1
for(c in 'a'..'z') {
priorityValues.put(c, count)
count++
}
for(c in 'A'..'Z') {
priorityValues.put(c, count)
count++
}
fun part1(input: String): Int {
return input.split("\n")
.map {
listOf(it.substring(0, it.length/2).toSet(), it.substring(it.length/2).toSet())
}.map {(setOne, setTwo) ->
priorityValues.getOrDefault(setOne.intersect(setTwo)
.first(), 0)
}
.sum()
}
fun part2(input: String): Int {
return input.split("\n")
.windowed(3, 3)
.flatMap { (first, second, third) ->
first.toSet()
.intersect(second.toSet())
.intersect(third.toSet())
.map {
c: Char -> priorityValues.getOrDefault(c, 0)
}
}.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day19_test")
val output = part1(testInput)
check(output== 157)
val input = readInput("Day19")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 74f10b93d3bad72fa0fc276b503bfa9f01ac0e35 | 1,329 | aoc-kotlin | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem87/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem87
/**
* LeetCode page: [87. Scramble String](https://leetcode.com/problems/scramble-string/);
*/
class Solution {
/* Complexity:
* Time O(N^4) and Space O(N^3) where N is the length of s1 and s2;
*/
fun isScramble(s1: String, s2: String): Boolean {
val inputLength = s1.length
// subResults[i][j][k] ::= is s2[j until j+k] a scrambled string of s1[i until i+k]
val subResults = subResultsHolder(inputLength)
updateBaseCases(s1, s2, subResults)
updateRestCases(inputLength, subResults)
return originalProblem(subResults)
}
private fun subResultsHolder(inputLength: Int): Array<Array<BooleanArray>> {
return Array(inputLength) { startS1 ->
Array(inputLength) { startS2 ->
val maxSubLength = inputLength - maxOf(startS1, startS2)
BooleanArray(maxSubLength + 1)
}
}
}
private fun updateBaseCases(s1: String, s2: String, subResults: Array<Array<BooleanArray>>) {
for (startS1 in s1.indices) {
for (startS2 in s2.indices) {
subResults[startS1][startS2][0] = true
subResults[startS1][startS2][1] = s1[startS1] == s2[startS2]
}
}
}
private fun updateRestCases(inputLength: Int, subResults: Array<Array<BooleanArray>>) {
for (subLength in 2..inputLength) {
for (startS1 in 0..inputLength - subLength) {
for (startS2 in 0..inputLength - subLength) {
updateSubResult(startS1, startS2, subLength, subResults)
}
}
}
}
private fun updateSubResult(
startS1: Int,
startS2: Int,
subLength: Int,
subResults: Array<Array<BooleanArray>>
) {
subResults[startS1][startS2][subLength] =
(1 until subLength).any { splitLength ->
isScrambleWithoutSwap(startS1, startS2, subLength, splitLength, subResults) ||
isScrambleWithSwap(startS1, startS2, subLength, splitLength, subResults)
}
}
private fun isScrambleWithoutSwap(
startS1: Int,
startS2: Int,
subLength: Int,
splitLength: Int,
subResults: Array<Array<BooleanArray>>
): Boolean {
val isFirstScramble = subResults[startS1][startS2][splitLength]
val isSecondScramble = subResults[startS1 + splitLength][startS2 + splitLength][subLength - splitLength]
return isFirstScramble && isSecondScramble
}
private fun isScrambleWithSwap(
startS1: Int,
startS2: Int,
subLength: Int,
splitLength: Int,
subResults: Array<Array<BooleanArray>>
): Boolean {
val isFirstScramble = subResults[startS1][startS2 + subLength - splitLength][splitLength]
val isSecondScramble = subResults[startS1 + splitLength][startS2][subLength - splitLength]
return isFirstScramble && isSecondScramble
}
private fun originalProblem(subResults: Array<Array<BooleanArray>>): Boolean {
return subResults[0][0].last()
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 3,173 | hj-leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/Day16.kt | Yeah69 | 317,335,309 | false | {"Kotlin": 73241} | class Day16 : Day() {
override val label: String get() = "16"
private val ruleRegex: Regex = """^(.+): ([0-9]+)-([0-9]+) or ([0-9]+)-([0-9]+)$""".toRegex()
data class Rule(val fieldName: String, val firstRange: IntRange, val secondRange: IntRange){
fun valid(fieldValue: Int): Boolean =
this.firstRange.contains(fieldValue)
|| this.secondRange.contains(fieldValue)
}
private val rules by lazy { input
.lineSequence()
.mapNotNull { ruleRegex.find(it) }
.map {
val (fieldName, from0, to0, from1, to1) = it.destructured
Rule(fieldName, from0.toInt()..to0.toInt(), from1.toInt()..to1.toInt())
} }
private val myTicket by lazy { input
.lineSequence()
.dropWhile { it != "your ticket:" }
.drop(1)
.take(1)
.flatMap { line -> line.split(",").mapNotNull { it.toIntOrNull() } }
.toList() }
private val nearbyTickets by lazy { input
.lineSequence()
.dropWhile { it != "nearby tickets:" }
.drop(1)
.map { line -> line.split(",").mapNotNull { it.toIntOrNull() }.toList() }
.toList() }
private val validTickets by lazy { nearbyTickets
.asSequence()
.filter { it.all { fieldValue -> rules.any { rule -> rule.valid(fieldValue) } } }
.toList() }
override fun taskZeroLogic(): String =
nearbyTickets
.flatten()
.filter { rules.none { rule -> rule.valid(it) || rule.secondRange.contains(it) } }
.sum()
.toString()
override fun taskOneLogic(): String {
val map = rules
.map { Pair(
it,
(0 until validTickets.first().count())
.filter { i -> validTickets.all { ticket -> it.valid(ticket[i]) } }.toList()) }
.toMap()
val excludes = mutableSetOf<Int>()
val ruleToIndex = map
.asSequence()
.sortedBy { it.value.count() }
.map {
val i = it.value.asSequence().filter { index -> excludes.contains(index).not() }.first()
excludes.add(i)
Pair(it.key, i)
}
.toMap()
return ruleToIndex
.asSequence()
.filter { it.key.fieldName.startsWith("departure") }
.map { myTicket[it.value] }
.fold(1L) { prev, curr -> prev * curr.toLong() }
.toString()
}
} | 0 | Kotlin | 0 | 0 | 23121ede8e3e8fc7aa1e8619b9ce425b9b2397ec | 2,509 | AdventOfCodeKotlin | The Unlicense |
solutions/aockt/y2015/Y2015D24.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2015
import io.github.jadarma.aockt.core.Solution
object Y2015D24 : Solution {
/**
* Returns a sequence of all combinations of size [take] from the initial list.
* This is a refactor of a Rosetta Code snippet, available at [https://rosettacode.org/wiki/Combinations#Kotlin].
* TODO: Make Util.
*/
private fun List<Int>.combinations(take: Int): Sequence<List<Int>> = sequence {
val combination = IntArray(take) { first() }
val stack = ArrayDeque<Int>().apply { addFirst(0) }
while (stack.isNotEmpty()) {
var resIndex = stack.size - 1
var arrIndex = stack.removeFirst()
while (arrIndex < size) {
combination[resIndex++] = get(arrIndex++)
stack.addFirst(arrIndex)
if (resIndex == take) {
yield(combination.toList())
break
}
}
}
}
/**
* Returns the quantum entanglement for the best group of packages that can go in Santa's passenger compartiment,
* or `null` if there is no solution.
*
* **NOTE:** This isn't really the solution, since it only finds the ideal first group but doesn't check that the
* rest of the presents can be split in equal groups. However, it seems the input data for all advent participants
* the first ideal bucket is always part of a solution. Sadly, Santa only gets the value of the QE, not the actual
* split, and his sled would remain unbalanced.
*/
private fun minQuantumEntanglement(pool: List<Int>, buckets: Int): Long? {
if (buckets < 1) return null
val target = pool.sum() / buckets
for (bucketSize in 1..pool.size) {
return pool
.combinations(take = bucketSize)
.filter { it.sum() == target }
.minOfOrNull { it.fold(1L, Long::times) }
?: continue
}
return null
}
override fun partOne(input: String) = input.lines().map(String::toInt).let { minQuantumEntanglement(it, 3)!! }
override fun partTwo(input: String) = input.lines().map(String::toInt).let { minQuantumEntanglement(it, 4)!! }
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 2,234 | advent-of-code-kotlin-solutions | The Unlicense |
src/main/kotlin/Day10.kt | brigham | 573,127,412 | false | {"Kotlin": 59675} | sealed class Ins
object NoopIns: Ins()
data class AddxIns(val add: Int): Ins()
fun main() {
fun parse(input: List<String>): List<Ins> = input.map { it.split(" ") }
.map {
when (it[0]) {
"noop" -> NoopIns
"addx" -> AddxIns(it[1].toInt())
else -> error("Unknown ${it[0]}")
}
}.toList()
fun part1(input: List<String>, verbose: Boolean): Int {
val inx = parse(input)
println(inx.filterIsInstance<AddxIns>().sumOf { it.add })
var x = 1
var tick = 0
val inxIter = inx.iterator()
var ctr = 1
var ins: Ins? = null
var sum = 0
while (inxIter.hasNext() || tick != 0) {
if ((ctr - 20) % 40 == 0) {
println("$x * $ctr == ${x * ctr}")
sum += (x * ctr)
}
if (tick == 1) {
tick = 0
x += when (ins) {
is NoopIns -> error("impossible")
is AddxIns -> ins.add
null -> error("impossible")
}
} else {
ins = inxIter.next()
when (ins) {
is NoopIns -> {}
is AddxIns -> {
tick = 1
}
}
}
if (verbose) {
println("ctr: $ctr, x: $x, ins: $ins")
}
ctr++
}
return sum
}
fun part2(input: List<String>): Int {
val inx = parse(input)
var x = 1
var tick = 0
val inxIter = inx.iterator()
var ctr = 1
var ins2: Ins? = null
while (inxIter.hasNext() || tick != 0) {
val pixel = (ctr - 1) % 40
if (x in setOf(pixel - 1, pixel, pixel + 1)) {
print("#")
} else {
print(".")
}
if (pixel == 39) {
println()
}
if (tick == 1) {
tick = 0
x += when (ins2) {
is NoopIns -> error("impossible")
is AddxIns -> ins2.add
null -> error("impossible")
}
} else {
ins2 = inxIter.next()
when (ins2) {
is NoopIns -> {}
is AddxIns -> {
tick = 1
}
}
}
ctr++
}
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(readInput("Day10_simple"), verbose=false) == 0)
check(part1(testInput, true) == 13140)
check(part2(testInput) == 0)
val input = readInput("Day10")
println(part1(input, false))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b87ffc772e5bd9fd721d552913cf79c575062f19 | 2,931 | advent-of-code-2022 | Apache License 2.0 |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions14.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.special
fun test14() {
printlnResult("ac", "dgcaf")
printlnResult("tops", "tuacstopszpxm")
printlnResult("ac", "dgccaaf")
printlnResult("tops", "tuacstotpzpxm")
printlnResult("tops", "pots")
printlnResult("tops", "potp")
}
/**
* Questions 14: Judge whether a string s2 contain any of an anagram of string s1
*/
private fun isAnagram(s1: String, s2: String): Boolean {
require(s2.length >= s1.length) { "The input is illegal" }
val s1CharMap = HashMap<Char, Int>(s1.length)
s1.forEach {
s1CharMap[it] = if (s1CharMap.contains(it)) s1CharMap[it]!! + 1 else 1
}
val copyMap = HashMap<Char, Int>(s1.length)
for (i in 0 .. s2.length - s1.length) {
s1CharMap.forEach { (key, value) ->
copyMap[key] = value
}
for (j in i ..< i + s1.length) {
val c = s2[j]
if (copyMap.contains(c)) {
copyMap[c] = copyMap[c]!! - 1
if (copyMap[c] == 0)
copyMap.remove(c)
} else
continue
}
if (copyMap.isEmpty())
return true
}
return false
}
private fun printlnResult(s1: String, s2: String) =
println("Is $s2 contain an anagram of $s1: ${isAnagram(s1, s2)}")
| 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 1,310 | Algorithm | Apache License 2.0 |
kotlin/src/com/s13g/aoc/aoc2020/Day21.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2020
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
/**
* --- Day 21: Allergen Assessment ---
* https://adventofcode.com/2020/day/21
*/
class Day21 : Solver {
override fun solve(lines: List<String>): Result {
val foods = lines.map { parseLine(it) }
// Allergen --> the ingredient they map to.
val candidates = mutableMapOf<String, MutableSet<String>>()
// At first, an allergens can be any kind of ingredient in their food.
for (food in foods) {
for (allergen in food.allergens) {
if (allergen !in candidates) candidates[allergen] = food.ingredients.toMutableSet()
// If the ingredient has candidates, intersect with new list to narrow down the options.
else candidates[allergen] = candidates[allergen]!!.intersect(food.ingredients).toMutableSet()
}
}
// We look at allergens that have only a single candidate, then set that and remove it from the other
// candidate lists. We repeat the process until all allergens have been mapped to their incredient.
val allergenIngredient = mutableMapOf<String, String>()
while (candidates.isNotEmpty()) {
for (can in candidates) {
if (can.value.size == 1) { // We found a match!
val ingredient = can.value.first()
allergenIngredient[can.key] = ingredient
candidates.filter { ingredient in it.value }.forEach { it.value.remove(ingredient) }
}
}
// Remove the found allergen from all candidate lists.
allergenIngredient.forEach { candidates.remove(it.key) }
}
// Safe foods (non-allergens) are the ones that are not in the allergen list.
val safeFoods = foods.flatMap { it.ingredients }.subtract(allergenIngredient.values)
// Count how often safe foods are appearing in the ingredient lists.
var resultA = 0
for (food in foods) resultA += safeFoods.count { it in food.ingredients }
// Create a sorted list of the allergen names, then use that order to produce a
// comma-separated list of their matching ingredients.
val allergensSorted = allergenIngredient.keys.toSortedSet()
var resultB = allergensSorted.map { allergenIngredient[it] }.joinToString(",")
return Result("$resultA", resultB)
}
private fun parseLine(line: String): Food {
val split = line.split(" (contains ")
return Food(split[0].split(' '), split[1].substring(0, split[1].lastIndex).split(',').map { it.trim() })
}
private data class Food(val ingredients: List<String>, val allergens: List<String>)
} | 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 2,556 | euler | Apache License 2.0 |
src/Day05.kt | AlexeyVD | 575,495,640 | false | {"Kotlin": 11056} | fun main() {
fun part1(input: List<String>): String {
return process(input, CrateMover9000(input.getBucketsNumber()))
}
fun part2(input: List<String>): String {
return process(input, CrateMover9001(input.getBucketsNumber()))
}
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
fun process(input: List<String>, crateMover: CrateMover): String {
val executor = Executor(getCommands(input))
crateMover.addEntries(input)
return executor.execute(crateMover).result()
}
fun getCommands(input: List<String>): ArrayDeque<Command> {
val res = ArrayDeque<Command>()
input.takeLastWhile { it.isNotBlank() }
.forEach {
res.addLast(Command.of(it))
}
return res
}
fun List<String>.getBucketsNumber(): Int {
return takeWhile { it.isNotBlank() }.last()
.split(' ')
.filter { it.isNotBlank() }
.size
}
fun String.getEntry(buckets: Int): List<String> {
return mutableListOf<String>().apply {
for (i in 0 until buckets) {
val index = 1 + i * 4
if (length > index) {
add(this@getEntry[index].toString())
} else {
add("")
}
}
}
}
class Command(
val number: Int,
val from: Int,
val to: Int
) {
companion object {
fun of(input: String): Command {
val params = input.split(' ')
return Command(
number = params[1].toInt(),
from = params[3].toInt(),
to = params[5].toInt()
)
}
}
}
class Executor(
private val commands: ArrayDeque<Command>
) {
fun execute(crateMover: CrateMover): CrateMover {
commands.forEach { crateMover.apply(it) }
return crateMover
}
}
abstract class CrateMover(
private val bucketsNumber: Int
) {
protected val entries: List<ArrayDeque<String>> = mutableListOf<ArrayDeque<String>>().apply {
repeat(bucketsNumber) {
this.add(ArrayDeque())
}
}
private fun add(values: List<String>) {
for (i in values.indices) {
if (values[i].isNotBlank()) {
entries[i].addLast(values[i])
}
}
}
fun addEntries(input: List<String>) {
input.takeWhile { it.contains('[') }.forEach {
add(it.getEntry(bucketsNumber))
}
}
fun result(): String {
return entries.joinToString("") { it.first() }
}
abstract fun apply(command: Command)
}
class CrateMover9000(bucketsNumber: Int) : CrateMover(bucketsNumber) {
override fun apply(command: Command) {
val from = entries[command.from - 1]
val to = entries[command.to - 1]
repeat(command.number) { to.addFirst(from.removeFirst()) }
}
}
class CrateMover9001(bucketsNumber: Int) : CrateMover(bucketsNumber) {
override fun apply(command: Command) {
val from = entries[command.from - 1]
val to = entries[command.to - 1]
val tmp = ArrayDeque<String>()
repeat(command.number) {
tmp.addLast(from.removeFirst())
}
for(i in tmp.indices.reversed()) {
to.addFirst(tmp[i])
}
}
} | 0 | Kotlin | 0 | 0 | ec217d9771baaef76fa75c4ce7cbb67c728014c0 | 3,387 | advent-kotlin | Apache License 2.0 |
src/main/kotlin/day05/Day05.kt | mdenburger | 433,731,891 | false | {"Kotlin": 8573} | package day05
import java.io.File
fun main() {
val lines: List<Line> = File("src/main/kotlin/day05/day05-input.txt")
.readLines()
.map { it.split(" -> ") }
.map { Line(it.first().asPoint(), it.last().asPoint()) }
println("Part 1: " + countOverlappingPoints(lines.filter { it.isHorizontal() || it.isVertical() }))
println("Part 2: " + countOverlappingPoints(lines))
}
fun countOverlappingPoints(lines: List<Line>): Int {
val grid = mutableMapOf<Point, Int>()
lines.forEach { line ->
line.points().forEach { point ->
grid.compute(point) { _, value ->
if (value == null) 1 else value + 1
}
}
}
return grid.filter { it.value >= 2 }.count()
}
fun String.asPoint(): Point =
split(",").map { it.toInt() }.let { Point(it.first(), it.last()) }
data class Point(val x: Int, val y: Int)
data class Line(val first: Point, val last: Point) {
fun isHorizontal(): Boolean = first.x == last.x
fun isVertical(): Boolean = first.y == last.y
fun points(): Sequence<Point> {
val dx = (last.x - first.x).coerceIn(-1, 1)
val dy = (last.y - first.y).coerceIn(-1, 1)
return sequence {
var point = first
yield(point)
while (point != last) {
point = Point(point.x + dx, point.y + dy)
yield(point)
}
}
}
}
| 0 | Kotlin | 0 | 0 | e890eec2acc2eea9c0432d092679aeb9de3f51b4 | 1,456 | aoc-2021 | MIT License |
src/Day11.kt | iownthegame | 573,926,504 | false | {"Kotlin": 68002} | import kotlin.math.floor
class Inspection(val monkeyIndex: Int, private val operation: String, val divisibleByValue: Int, private val throwToMonkeys: Array<Int>) {
var inspectedItemTimes = 0
fun operateItem(worryLevel: Long): Long {
// do operation, for example: old * 19, old + 3, old * old
var newWorryLevel = doOperation(worryLevel)
// print("monkey $monkeyIndex operates $worryLevel to become $newWorryLevel ")
// println("after divided by 3 and round down: $newWorryLevel")
return newWorryLevel
}
fun inspectItemAndThrow(worryLevel: Long): Int {
inspectedItemTimes += 1
// do test operation and throw, for example: divisible by 13
// println("monkey $monkeyIndex throw $worryLevel to $throwToMonkey")
return testAndThrow(worryLevel)
}
private fun doOperation(worryLevel: Long): Long {
val splits = operation.split(" ")
val op = splits[1]
val value = if (splits[2] == "old") worryLevel else splits[2].toLong()
val newWorryLevel =
when(op) {
"*" -> worryLevel * value
"+" -> worryLevel + value
else -> { 0 }
}
return newWorryLevel
}
private fun testAndThrow(worryLevel: Long): Int {
return if (worryLevel % divisibleByValue.toLong() == 0.toLong()) {
throwToMonkeys.first()
} else {
throwToMonkeys.last()
}
}
}
class MonkeyInTheMiddle(val itemsOfMonkeys: MutableMap<Int, MutableList<Long>>, val inspections: Array<Inspection>) {
val productOfDivisibleByValue: Int?
init {
productOfDivisibleByValue = inspections.map { it.divisibleByValue }.reduce{ acc, it -> acc * it }
}
}
fun main() {
fun parseInput(input: List<String>): MonkeyInTheMiddle {
val itemsOfMonkeys = mutableMapOf<Int, MutableList<Long>>()
var inspections = arrayOf<Inspection>()
/*
Monkey 0:
Starting items: 54, 89, 94
Operation: new = old * 7
Test: divisible by 17
If true: throw to monkey 5
If false: throw to monkey 3
*/
var lineIndex = 0
while (lineIndex < input.size) {
val line = input[lineIndex]
if (line.startsWith("Monkey")) {
// parse monkey index
val monkeyIndex = line.dropLast(1).split(" ")[1].toInt()
// parse starting items
var nextLine = input[++lineIndex]
val items = nextLine.substring(" Starting items: ".length).split(", ").map { it.toLong() }
// parse operation
nextLine = input[++lineIndex]
val operation = nextLine.substring(" Operation: new = ".length)
// parse Test operation and throw to monkeys
nextLine = input[++lineIndex]
val testOperation = nextLine.substring(" Test: ".length)
val splits = testOperation.split(" ")
val divisibleByValue = splits[2].toInt()
var throwToMonkeys = arrayOf<Int>()
nextLine = input[++lineIndex]
throwToMonkeys += nextLine.split(" ").last().toInt()
nextLine = input[++lineIndex]
throwToMonkeys += nextLine.split(" ").last().toInt()
// add inspection and starting items
val inspection = Inspection(monkeyIndex, operation, divisibleByValue, throwToMonkeys)
inspections += inspection
itemsOfMonkeys[monkeyIndex] = items.toMutableList()
}
lineIndex++
}
return MonkeyInTheMiddle(itemsOfMonkeys, inspections)
}
fun doRound(itemsOfMonkeys: MutableMap<Int, MutableList<Long>>, inspections: Array<Inspection>, productOfDivisibleByValue: Int?) {
for (inspection in inspections) {
val itemsOfMonkey = itemsOfMonkeys[inspection.monkeyIndex]!!
while(itemsOfMonkey.isNotEmpty()) {
val item = itemsOfMonkey.removeFirst()
var newWorryValueOfItem = inspection.operateItem(item)
if(productOfDivisibleByValue != null) {
newWorryValueOfItem %= productOfDivisibleByValue
} else {
newWorryValueOfItem = floor((newWorryValueOfItem / 3).toDouble()).toLong() // part 1
}
val throwToMonkey = inspection.inspectItemAndThrow(newWorryValueOfItem)
if (itemsOfMonkeys.containsKey(throwToMonkey)) {
itemsOfMonkeys[throwToMonkey]!!.add(newWorryValueOfItem)
} else {
itemsOfMonkeys[throwToMonkey] = arrayOf(newWorryValueOfItem).toMutableList()
}
}
}
}
fun part1(input: List<String>): Int {
val monkeyInTheMiddle = parseInput(input)
val itemsOfMonkeys = monkeyInTheMiddle.itemsOfMonkeys
val inspections = monkeyInTheMiddle.inspections
val totalRounds = 20
for (i in 1..totalRounds) {
doRound(itemsOfMonkeys, inspections, null)
}
// get the top 2 inspectedItemTimes
val inspectedItemTimes = inspections.map { it.inspectedItemTimes }.sortedDescending()
// println("inspectedItemTimes: ${inspectedItemTimes.map { it }}")
return inspectedItemTimes[0] * inspectedItemTimes[1]
}
fun part2(input: List<String>): Long {
val monkeyInTheMiddle = parseInput(input)
val inspections = monkeyInTheMiddle.inspections
val totalRounds = 10000
for (i in 1..totalRounds) {
doRound(monkeyInTheMiddle.itemsOfMonkeys, inspections, monkeyInTheMiddle.productOfDivisibleByValue)
}
// get the top 2 inspectedItemTimes
val inspectedItemTimes = inspections.map { it.inspectedItemTimes }.sortedDescending()
// println("inspectedItemTimes: ${inspections.map { it.inspectedItemTimes }}")
return inspectedItemTimes[0].toLong() * inspectedItemTimes[1].toLong()
}
// test if implementation meets criteria from the description, like:
val testInput = readTestInput("Day11_sample")
check(part1(testInput) == 10605)
check(part2(testInput) == 2713310158)
val input = readTestInput("Day11")
println("part 1 result: ${part1(input)}")
println("part 2 result: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 4e3d0d698669b598c639ca504d43cf8a62e30b5c | 6,507 | advent-of-code-2022 | Apache License 2.0 |
src/Day02.kt | KarinaCher | 572,657,240 | false | {"Kotlin": 21749} | val LOST = 0
val DRAW = 3
val WON = 6
val ROCK = "Rock"
val PAPER = "Paper"
val SCISSORS = "Scissors"
val STRATEGY_LOST = "Lost"
val STRATEGY_DRAW = "Draw"
val STRATEGY_WON = "Won"
fun main() {
fun part1(input: List<String>): Int {
var round = 1
var reward = 0;
for (line in input) {
val part = line.split(" ")
val me = Me.valueOf(part[1])
val opponent = Opponent.valueOf(part[0])
reward += play(opponent.value, me.value)
.plus(me.reward)
round++
}
return reward
}
fun part2(input: List<String>): Int {
var round = 1
var reward = 0;
for (line in input) {
val part = line.split(" ")
val myStrategy = MyStrategy.valueOf(part[1])
val opponent = Opponent.valueOf(part[0])
val me = choice(myStrategy, opponent)
reward += play(opponent.value, me.value)
.plus(me.reward)
round++
}
return reward
}
val testInput = readInput("Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
/**
* Rock defeats Scissors, Scissors defeats Paper, and Paper defeats Rock
*/
fun play(opponent: String, me: String): Int {
if (opponent.equals(me)) {
return DRAW
}
if (opponent.equals(Opponent.A.value) && me.equals(Me.Y.value)) {
return WON
}
if (opponent.equals(Opponent.C.value) && me.equals(Me.X.value)) {
return WON
}
if (opponent.equals(Opponent.B.value) && me.equals(Me.Z.value)) {
return WON
}
return LOST
}
fun choice(myStrategy: MyStrategy, opponent: Opponent): Me {
if (myStrategy.value.equals(STRATEGY_DRAW)) {
return when (opponent.value) {
ROCK -> Me.X
PAPER -> Me.Y
SCISSORS -> Me.Z
else -> throw IllegalArgumentException()
}
}
if (myStrategy.value.equals(STRATEGY_WON)) {
return when (opponent.value) {
ROCK -> Me.Y
PAPER -> Me.Z
SCISSORS -> Me.X
else -> throw IllegalArgumentException()
}
} else {
return when (opponent.value) {
ROCK -> Me.Z
PAPER -> Me.X
SCISSORS -> Me.Y
else -> throw IllegalArgumentException()
}
}
}
enum class Opponent(val value: String) {
A(ROCK),
B(PAPER),
C(SCISSORS);
}
enum class Me(val value: String, val reward: Int) {
X(ROCK, 1),
Y(PAPER, 2),
Z(SCISSORS, 3);
}
enum class MyStrategy(val value: String, val reward: Int) {
X(STRATEGY_LOST, LOST),
Y(STRATEGY_DRAW, DRAW),
Z(STRATEGY_WON, WON);
} | 0 | Kotlin | 0 | 0 | 17d5fc87e1bcb2a65764067610778141110284b6 | 2,824 | KotlinAdvent | Apache License 2.0 |
untitled/src/main/kotlin/Day11-alt.kt | jlacar | 572,845,298 | false | {"Kotlin": 41161} | import java.math.BigInteger
val sample = InputReader("Day11-sample.txt").lines
val input = InputReader("Day11-alt.txt").lines
val monkeys = parse(input)
val bigModulo: BigInteger = monkeys.map { it.modulo }.fold(BigInteger.ONE) { acc, prime -> acc.multiply(prime) }
//.also { println("bigModulo $it") }
fun parse(lines: List<String>) = lines.chunked(7).map { Monkey(it) }
fun main() {
repeat(10000) {
monkeys.forEach { monkey -> monkey.throwItemsToOther(monkeys) { it.remainder(bigModulo) } }
}
val (a, b) = monkeys.map { it.inspections }.sorted().takeLast(2)
println("$a * $b = ${a.toLong() * b.toLong()}")
}
class Monkey(info: List<String>) {
val items: MutableList<BigInteger>
val modulo: BigInteger
val operation: (BigInteger) -> BigInteger
val throwTo: (BigInteger) -> Int
var inspections = 0
init {
items = startingItems(info[1].trim())
operation = opFun(info[2].trim())
modulo = divisibleBy(info[3])
throwTo = throwFun(modulo, info[4].trim(), info[5].trim())
}
private fun startingItems(line: String) = mutableListOf<BigInteger>().apply {
addAll(line.split(": ")[1].split(", ").map { it.toBigInteger() })
}
private fun opFun(line: String): (BigInteger) -> BigInteger {
val (_, op, x) = line.split(" = ")[1].split(" ")
fun mult(num: BigInteger) = { worryLevel: BigInteger -> worryLevel.multiply(num) }
fun incr(num: BigInteger) = { worryLevel: BigInteger -> worryLevel.add(num) }
return when {
x == "old" -> { num -> num.multiply(num) }
op == "+" -> incr(x.toBigInteger())
else -> mult(x.toBigInteger())
}
}
private fun divisibleBy(line: String) = line.trim().split(" ")[3].toBigInteger()
private fun throwFun(divisor: BigInteger, toTrue: String, toFalse: String): (BigInteger) -> Int {
val monkeyTrue = toTrue.split(" ")[5].toInt()
val monkeyFalse = toFalse.split(" ")[5].toInt()
return { item -> if (item.remainder(divisor) == BigInteger.ZERO) monkeyTrue else monkeyFalse }
}
fun catch(item: BigInteger) = items.add(item)
fun throwItemsToOther(otherMonkeys: List<Monkey>, manageWorry: (BigInteger) -> BigInteger) {
inspections += items.size
items.forEach { worryLevel ->
val newLevel = manageWorry(operation(worryLevel)) // operation(worryLevel).remainder(bigModulo)
otherMonkeys[throwTo(newLevel)].catch(newLevel)
}
items.clear()
}
override fun toString() = "$items"
} | 0 | Kotlin | 0 | 2 | dbdefda9a354589de31bc27e0690f7c61c1dc7c9 | 2,587 | adventofcode2022-kotlin | The Unlicense |
Advent-of-Code-2023/src/Day03.kt | Radnar9 | 726,180,837 | false | {"Kotlin": 93593} | private const val AOC_DAY = "Day03"
private const val PART1_TEST_FILE = "${AOC_DAY}_test_part1"
private const val PART2_TEST_FILE = "${AOC_DAY}_test_part2"
private const val INPUT_FILE = AOC_DAY
/**
* Find and sum up the numbers adjacent, including diagonal ones, to any symbol different from '.'.
* Starts by finding the symbols and then verifies the numbers that are adjacent.
* @return the sum of the adjacent numbers.
*/
private fun part1(input: List<String>): Int {
var sum = 0
for ((i, line) in input.withIndex()) {
for ((j, c) in line.withIndex()) {
if (!c.isSymbolNotDot()) continue
val possibleLines = getSubList(i, input)
val positions = getNumbersPositions(j, if (i > 0) 1 else i, possibleLines)
sum += getSumOrRatio(positions, possibleLines, isRatio = false)
}
}
return sum
}
/**
* Builds a sub list containing the possible lines where it can be found a number adjacent to a character of desired
* line, represented by mainLineIndex
*/
private fun getSubList(mainLineIndex: Int, list: List<String>): List<String> {
val initialIdx = if (mainLineIndex > 0) mainLineIndex - 1 else mainLineIndex
val lastIdx = if (mainLineIndex < list.size - 1) mainLineIndex + 1 else mainLineIndex
return list.subList(initialIdx, lastIdx + 1)
}
/**
* Find and multiply the existent gears, i.e., the '*' symbol that is adjacent to exactly two numbers.
* @return the sum of the gear ratios, i.e., the product of the numbers that constitute each gear.
*/
private fun part2(input: List<String>): Int {
var sum = 0
for ((i, line) in input.withIndex()) {
for ((j, c) in line.withIndex()) {
if (!c.isAsterisk()) continue
val possibleLines = getSubList(i, input)
val positions = getNumbersPositions(j, if (i > 0) 1 else i, possibleLines)
if (positions.size != 2) continue
sum += getSumOrRatio(positions, possibleLines, isRatio = true)
}
}
return sum
}
data class Position(val row: Int, val col: Int)
/**
* Obtains the positions of the numbers that are adjacent (including diagonally) to a symbol
* @return an array list of the numbers positions
*/
private fun getNumbersPositions(symbolCol: Int, symbolRow: Int, possibleLines: List<String>): ArrayList<Position> {
val positions = ArrayList<Position>()
// Tips
if (symbolCol > 0 && possibleLines[symbolRow][symbolCol - 1].isDigit()) {
positions.add(Position(symbolRow, symbolCol - 1))
}
if (symbolCol < possibleLines[symbolRow].length - 1 && possibleLines[symbolRow][symbolCol + 1].isDigit()) {
positions.add(Position(symbolRow, symbolCol + 1))
}
// Top
if (symbolRow > 0) {
if (possibleLines[symbolRow - 1][symbolCol].isDigit()) {
positions.add(Position(symbolRow - 1, symbolCol))
} else { // To not count the same number twice
// Diagonal
if (symbolCol > 0 && possibleLines[symbolRow - 1][symbolCol - 1].isDigit()) {
positions.add(Position(symbolRow - 1, symbolCol - 1))
}
if (symbolCol < possibleLines[symbolRow].length - 1 && possibleLines[symbolRow - 1][symbolCol + 1].isDigit()) {
positions.add(Position(symbolRow - 1, symbolCol + 1))
}
}
}
// Bottom
if (symbolRow < possibleLines.size - 1) {
if (possibleLines[symbolRow + 1][symbolCol].isDigit()) {
positions.add(Position(symbolRow + 1, symbolCol))
} else {
// Diagonal
if (symbolCol > 0 && possibleLines[symbolRow + 1][symbolCol - 1].isDigit()) {
positions.add(Position(symbolRow + 1, symbolCol - 1))
}
if (symbolCol < possibleLines[symbolRow].length - 1 && possibleLines[symbolRow + 1][symbolCol + 1].isDigit()) {
positions.add(Position(symbolRow + 1, symbolCol + 1))
}
}
}
return positions
}
/**
* Finds the numbers that constitute an adjacency with a symbol by starting on the provided index of the numbers.
* Searches the left and right side of that index until the char is not a number.
* This approach avoids starting from the start or end of the line.
* @return the sum of the found numbers or the ratio of both numbers, i.e., their product.
*/
private fun getSumOrRatio(numberPositions: ArrayList<Position>, possibleLines: List<String>, isRatio: Boolean): Int {
var result = if (isRatio) 1 else 0 // If it is the sum functionality start as 0
for (pos in numberPositions) {
val line = possibleLines[pos.row]
var startIdx = -1
var lastIdx = -1
// Find number starting index
for (i in pos.col downTo 0) {
if (line[i].isDigit() && i == 0) startIdx = i
if (line[i].isDigit()) continue
startIdx = i + 1
break
}
// Find number last index
for (i in pos.col ..< line.length) {
if (line[i].isDigit() && i == line.length - 1) lastIdx = i
if (line[i].isDigit()) continue
lastIdx = i - 1
break
}
val number = line.substring(startIdx .. lastIdx).toInt()
result = if (isRatio) result * number else result + number
}
return result
}
fun main() {
val part1ExpectedRes = 4361
val part1TestInput = readInputToList(PART1_TEST_FILE)
println("---| TEST INPUT |---")
println("* PART 1: ${part1(part1TestInput)}\t== $part1ExpectedRes")
val part2ExpectedRes = 467835
val part2TestInput = readInputToList(PART2_TEST_FILE)
println("* PART 2: ${part2(part2TestInput)}\t== $part2ExpectedRes\n")
val input = readInputToList(INPUT_FILE)
val improving = true
println("---| FINAL INPUT |---")
println("* PART 1: ${part1(input)}${if (improving) "\t== 543867" else ""}")
println("* PART 2: ${part2(input)}${if (improving) "\t== 79613331" else ""}")
}
| 0 | Kotlin | 0 | 0 | e6b1caa25bcab4cb5eded12c35231c7c795c5506 | 6,023 | Advent-of-Code-2023 | Apache License 2.0 |
tasks-2/lib/src/main/kotlin/trees/utils/DisjointSet.kt | AzimMuradov | 472,473,231 | false | {"Kotlin": 127576} | package trees.utils
/**
* Disjoint Set
*
* In computer science, a disjoint-set data structure, also called a [union]–[find] data structure or merge–find set, is a data structure that stores a collection of disjoint (non-overlapping) sets.
* Equivalently, it stores a partition of a set into disjoint subsets.
*/
internal class DisjointSet<T>(elements: Set<T>) {
private val parents = elements.associateWithTo(mutableMapOf()) { it }
private val ranks = elements.associateWithTo(mutableMapOf()) { 0 }
/**
* Find a representative member of a set with the [element].
*/
fun find(element: T): T {
if (parents[element] != element) {
parents[element] = find(parents.getValue(element))
}
return parents.getValue(element)
}
/**
* Merge two sets respectively with elements [a] and [b] (replacing them by their union).
*/
fun union(a: T, b: T) {
val aRoot = find(a)
val bRoot = find(b)
if (aRoot == bRoot) return
when {
ranks.getValue(aRoot) < ranks.getValue(bRoot) -> parents[aRoot] = bRoot
ranks.getValue(bRoot) < ranks.getValue(aRoot) -> parents[bRoot] = aRoot
else -> {
parents[bRoot] = aRoot
ranks[aRoot] = ranks.getValue(aRoot) + 1
}
}
}
}
/**
* Check if elements [a] and [b] are in the same set.
*/
internal fun <T> DisjointSet<T>.isConnected(a: T, b: T): Boolean = find(a) == find(b)
| 0 | Kotlin | 0 | 0 | 01c0c46df9dc32c2cc6d3efc48b3a9ee880ce799 | 1,509 | discrete-math-spbu | Apache License 2.0 |
src/Day03.kt | cgeesink | 573,018,348 | false | {"Kotlin": 10745} | fun main() {
fun part1(input: List<String>): Int = input.map { rucksack ->
rucksack.substring(0 until rucksack.length / 2).toCharArray() to
rucksack.substring(rucksack.length / 2).toCharArray()
}.flatMap { (first, second) -> first intersect second.toSet() }.map { item -> item.toScore() }.sum()
fun part2(input: List<String>): Int = input
.chunked(3)
.map { group ->
group.zipWithNext()
.map { (first, second) ->
first.toSet() intersect second.toSet()
}
}.flatMap { sharedItems ->
sharedItems[0] intersect sharedItems[1]
}.sumOf { it.toScore() }
// 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))
}
private fun Char.toScore(): Int = if (this.isUpperCase()) {
this.code - 38
} else {
this.code - 96
} | 0 | Kotlin | 0 | 0 | 137fb9a9561f5cbc358b7cfbdaf5562c20d6b10d | 1,079 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day14.kt | EdoFanuel | 575,561,680 | false | {"Kotlin": 80963} | fun markRocks(input: List<String>): MutableSet<Pair<Int, Int>> {
val result = mutableSetOf<Pair<Int, Int>>()
for (line in input) {
val corners = line.split("->").map { it.trim() }
for (i in 1 until corners.size) {
val (ax, ay) = corners[i - 1].split(",").map { it.toInt() }
val (bx, by) = corners[i].split(",").map { it.toInt() }
for (x in minOf(ax, bx)..maxOf(ax, bx)) {
for (y in minOf(ay, by)..maxOf(ay, by)) {
result += x to y
}
}
}
}
return result
}
fun dropRock(startPoint: Pair<Int, Int>, blockers: Set<Pair<Int, Int>>, floor: Int): Pair<Int, Int> {
var (x, y) = startPoint
var hasMove = true
while (hasMove && y < floor) {
if (x to y + 1 !in blockers) {
y++
continue
}
if (x - 1 to y + 1 !in blockers) {
x--
y++
continue
}
if (x + 1 to y + 1 !in blockers) {
x++
y++
continue
}
else hasMove = false
}
return x to y
}
fun main() {
fun part1(input: MutableSet<Pair<Int, Int>>): Int {
val startPoint = 500 to 0
val maxHeight = input.maxOf { it.second }
var result = 1
var newRock = dropRock(startPoint, input, maxHeight + 1)
while (newRock.second < maxHeight) {
input += newRock
newRock = dropRock(startPoint, input, maxHeight + 1)
result++
}
return result
}
fun part2(input: MutableSet<Pair<Int, Int>>): Int {
val startPoint = 500 to 0
var result = 1
val maxHeight = input.maxOf { it.second }
var newRock = dropRock(startPoint, input, maxHeight + 1)
while (newRock != startPoint) {
input += newRock
newRock = dropRock(startPoint, input, maxHeight + 1)
result++
}
return result
}
val test = readInput("Day14_test")
println(part1(markRocks(test)))
println(part2(markRocks(test)))
val input = readInput("Day14")
println(part1(markRocks(input)))
println(part2(markRocks(input)))
} | 0 | Kotlin | 0 | 0 | 46a776181e5c9ade0b5e88aa3c918f29b1659b4c | 2,224 | Advent-Of-Code-2022 | Apache License 2.0 |
kotlin/kotlin-by-example/std-lib/collections.kts | JafarSadik | 117,316,387 | false | {"Scala": 647948, "Java": 100704, "JavaScript": 43562, "Kotlin": 28712, "Groovy": 21124, "HTML": 16067, "Ruby": 4083, "CSS": 2531, "Shell": 2174, "SuperCollider": 961, "Dockerfile": 258} | import kotlin.math.max
// Higher Order Functions that are frequently used with collections.
// map can be used to transform collection into another collection
val numbers = listOf(-2, -1, 0, 1, 2)
check(numbers.map { it * 2 } == listOf(-4, -2, 0, 2, 4))
// flatmap maps each element into a list and flattens the result into a single list
val words = listOf("this", "is", "a", "really", "useful", "thing")
check(words.flatMap { it.toList() }.toSet() == setOf('t', 'h', 'i', 's', 'a', 'r', 'e', 'l', 'y', 'u', 'f', 'n', 'g'))
check(listOf(1, 2, 3).flatMap { listOf(it, it, it) } == listOf(1, 1, 1, 2, 2, 2, 3, 3, 3))
// filter function filters a collection using a provided predicate
val isNegative = { x: Int -> x < 0 }
val isPositive = { x: Int -> x >= 0 }
check(numbers.filter(isNegative) == listOf(-2, -1))
check(numbers.filter(isPositive) == listOf(0, 1, 2))
// find returns first element matching the given predicate
check(words.find { it.startsWith("t") } == "this")
// any checks if at least one item satisfies the predicate
check(numbers.any { it > 1 })
// all checks if all items satisfy the predicate
check(numbers.all { it < 100 })
// none checks if there is no item that satisfies the predicate
check(numbers.none { it > 100 })
// first, firstOrNull return first element or first elment matching the predicate
val list = listOf(1, 3, 5, 6, 7, 8, 9)
check(list.first() == 1)
check(list.first { it % 2 == 0 } == 6)
check(list.firstOrNull { it == 111 } == null)
// last, lastOrNull return last element or last element matching the predicate
check(list.last() == 9)
check(list.last { it % 2 == 0 } == 8)
check(list.lastOrNull { it == 111 } == null)
// count function counts total number of elements in a collection
check(list.count() == 7)
check(list.count { it % 2 == 0 } == 2)
// partition splits a collection into pair of lists
val (negatives, positives) = numbers.partition { it < 0 }
check(negatives == listOf(-2, -1) && positives == listOf(0, 1, 2))
// associateBy, groupBy create a map by indexing collection by the provided key
data class Person(val name: String, val city: String, val phone: String)
val john = Person("John", "Boston", "+1-888-123456")
val sarah = Person("Sarah", "Munich", "+49-777-789123")
val steven = Person("Steven", "Saint-Petersburg", "+7-999-456789")
val ann = Person("Ann", "Saint-Petersburg", "+7-999-123456")
val people = listOf(john, sarah, steven, ann)
check(people.associateBy { it.phone }["+7-999-456789"] == steven)
check(people.associateBy { it.city }["Saint-Petersburg"] == ann)
check(people.groupBy { it.city }["Saint-Petersburg"] == listOf(steven, ann))
check(people.groupBy { it.city } == mapOf(
Pair("Saint-Petersburg", listOf(steven, ann)),
Pair("Munich", listOf(sarah)),
Pair("Boston", listOf(john))
))
check(people.groupBy { it.city } == people.groupBy(Person::city))
// zip merges two collections by matching indexes
val animals = listOf("elephant", "lion", "mice")
val maxAge = listOf(60, 30, 2)
check(animals.zip(maxAge) == listOf(Pair("elephant", 60), Pair("lion", 30), Pair("mice", 2)))
check(animals.zip(maxAge, { animal, maxAge -> "$animal can live up to $maxAge years" }) == listOf(
"elephant can live up to 60 years",
"lion can live up to 30 years",
"mice can live up to 2 years"
))
// min, max
check(numbers.min() == -2 && numbers.max() == 2)
// sorted, sortedBy
val shuffled = listOf(3, 4, 5, 2, 1)
check(shuffled.sorted() == listOf(1, 2, 3, 4, 5))
check(shuffled.sortedBy({-it}) == listOf(5, 4, 3, 2, 1))
check(listOf(setOf(1, 2), setOf(-1, 10, 20)).sortedBy {it.min()} == listOf(setOf(-1, 10, 20), setOf(1, 2)))
| 2 | Scala | 1 | 0 | e6e02a214f973494004e1ab3d80254455c936918 | 3,651 | code-lab | Apache License 2.0 |
src/main/kotlin/com/dvdmunckhof/aoc/event2020/Day18.kt | dvdmunckhof | 318,829,531 | false | {"Kotlin": 195848, "PowerShell": 1266} | package com.dvdmunckhof.aoc.event2020
class Day18(private val input: List<String>) {
fun solvePart1(): Long {
return solve(listOf(setOf(Token.Plus, Token.Multiply)))
}
fun solvePart2(): Long {
return solve(listOf(setOf(Token.Plus), setOf(Token.Multiply)))
}
private fun solve(operatorPrecedence: List<Set<Token>>): Long {
return input.map(this::parseExpression)
.fold(0L) { sum, expression -> sum + solveExpression(expression, operatorPrecedence) }
}
private fun parseExpression(expression: String): List<Token> {
val chars = expression.toList()
val tokens = mutableListOf<Token>()
var index = 0
while (index < chars.size) {
val token = when (chars[index++]) {
in '0'..'9' -> {
val number = expression.drop(index - 1).takeWhile(Char::isDigit)
index += number.lastIndex
Token.Number(number.toLong())
}
'+' -> Token.Plus
'*' -> Token.Multiply
'(' -> Token.ParenthesesOpen
')' -> Token.ParenthesesClose
else -> continue
}
tokens.add(token)
}
return tokens
}
private fun solveExpression(tokens: List<Token>, operatorPrecedence: List<Set<Token>>): Long {
val list = tokens.toMutableList()
while (true) {
val indexClose = list.indexOfOrNull(Token.ParenthesesClose) ?: break
val indexOpen = list.subList(0, indexClose).lastIndexOf(Token.ParenthesesOpen)
val group = list.subList(indexOpen, indexClose + 1)
group.removeFirst() // open parentheses
group.removeLast() // close parentheses
val result = solveExpression(group, operatorPrecedence)
group.clear()
group.add(Token.Number(result))
}
for (operators in operatorPrecedence) {
while (true) {
val index = list.indexOfFirst { it in operators } - 1
if (index < 0) break
val numberA = list.removeAt(index) as Token.Number
val operator = list.removeAt(index)
val numberB = list.removeAt(index) as Token.Number
val result = if (operator == Token.Multiply) {
Token.Number(numberA.value * numberB.value)
} else {
Token.Number(numberA.value + numberB.value)
}
list.add(index, result)
}
}
return (list.first() as Token.Number).value
}
sealed class Token {
data class Number(val value: Long) : Token()
object Plus : Token()
object Multiply : Token()
object ParenthesesOpen : Token()
object ParenthesesClose : Token()
}
private fun <T> List<T>.indexOfOrNull(element: T): Int? {
val index = this.indexOf(element)
return if (index == -1) null else index
}
}
| 0 | Kotlin | 0 | 0 | 025090211886c8520faa44b33460015b96578159 | 3,063 | advent-of-code | Apache License 2.0 |
leetcode2/src/leetcode/IntersectionOfTwoArraysII.kt | hewking | 68,515,222 | false | null | package leetcode
import java.util.*
/**
* 两个数组的交集 II
* https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/
* Created by test
* Date 2019/5/23 0:51
* Description
* 给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2,2]
示例 2:
输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [4,9]
说明:
输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。
我们可以不考虑输出结果的顺序。
进阶:
如果给定的数组已经排好序呢?你将如何优化你的算法?
如果 nums1 的大小比 nums2 小很多,哪种方法更优?
如果 nums2 的元素存储在磁盘上,磁盘内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办?
*/
object IntersectionOfTwoArraysII{
class Solution {
/**
* 思路:
* 1.因为不需要要求不重复,所以list集合
* 2.因为是排好序的,所以下一轮排序 start = i + 1
* 这样让maxArr 指向下一个元素,不会重复判断相等
*/
fun intersect(nums1: IntArray, nums2: IntArray): IntArray {
Arrays.sort(nums1)
Arrays.sort(nums2)
val minArr = if (nums1.size > nums2.size) nums2 else nums1
val maxArr = if (nums1.size > nums2.size) nums1 else nums2
val arrList = mutableListOf<Int>()
var start = 0
for (num in minArr) {
for (i in start until maxArr.size) {
if (num == maxArr[i]) {
arrList.add(num)
start = i + 1
break
}
}
}
return arrList.toIntArray()
}
fun intersect2(nums1: IntArray, nums2: IntArray): IntArray {
val arrList = mutableListOf<Int>()
Arrays.sort(nums1)
Arrays.sort(nums2)
val minArr = if (nums1.size > nums2.size) nums2 else nums1
val maxArr = if (nums1.size > nums2.size) nums1 else nums2
var j = 0
var i = 0
while (i < minArr.size && j < maxArr.size) {
if (i != 0 ) {
while (i < minArr.size && minArr[i] == minArr[i-1]) {
i ++
}
}
while (i < minArr.size && j < maxArr.size && minArr[i] != maxArr[j]) {
j++
}
if (j >= maxArr.size || i >= maxArr.size) {
return arrList.toIntArray()
}
if(i < minArr.size){
arrList.add(minArr[i])
}
i ++
}
return arrList.toIntArray()
}
}
} | 0 | Kotlin | 0 | 0 | a00a7aeff74e6beb67483d9a8ece9c1deae0267d | 2,913 | leetcode | MIT License |
src/main/kotlin/aoc2020/day10/Joltage.kt | arnab | 75,525,311 | false | null | package aoc2020.day10
object Joltage {
fun parse(data: String): List<Int> = data.split("\n").map { it.toInt() }
fun arrange(adapters: List<Int>): List<Int> {
val sorted = adapters.sorted()
return sorted + listOf(sorted.maxOrNull()!! + 3)
}
fun calculateDiffs(chain: List<Int>): List<Int> {
val base = listOf(0) + chain
val pairs: List<Pair<Int, Int>> = base.zip(chain)
return pairs.map { (prev, next) -> next - prev }
}
fun solvePart1(differences: List<Int>): Int =
differences.groupingBy { it }
.eachCount()
.let { diffsCount -> diffsCount[1]!! * diffsCount[3]!! }
/**
* Cache of known paths for the given adapter, to avoid re-calculation of trillions of possibilities.
*/
private val knownPaths: MutableMap<Int, Long> = mutableMapOf()
fun countPaths(adapters: Set<Int>): Long {
knownPaths.clear()
return countPathsRecursively(adapters, 0, adapters.maxOrNull()!!)
}
private fun countPathsRecursively(adapters: Set<Int>, currentAdapter: Int, maxAdapter: Int): Long {
// No more paths
if (currentAdapter == maxAdapter) return 1
// memoize the path-count for the current adapter
knownPaths.getOrPut(currentAdapter) {
countPathsForAdapter(adapters, currentAdapter, maxAdapter)
}
return knownPaths[currentAdapter]!!
}
private fun countPathsForAdapter(adapters: Set<Int>, adapter: Int, maxAdapter: Int): Long =
listOfNotNull(
(adapter + 1).let { if (it in adapters) countPathsRecursively(adapters, it, maxAdapter) else null },
(adapter + 2).let { if (it in adapters) countPathsRecursively(adapters, it, maxAdapter) else null },
(adapter + 3).let { if (it in adapters) countPathsRecursively(adapters, it, maxAdapter) else null }
).sum()
}
| 0 | Kotlin | 0 | 0 | 1d9f6bc569f361e37ccb461bd564efa3e1fccdbd | 1,904 | adventofcode | MIT License |
src/main/kotlin/day02/Day02.kt | dustinconrad | 572,737,903 | false | {"Kotlin": 100547} | package day02
import readResourceAsBufferedReader
fun main() {
println("part 1: ${part1(readResourceAsBufferedReader("2_1.txt").readLines())}")
println("part 2: ${part2(readResourceAsBufferedReader("2_1.txt").readLines())}")
}
fun part1(input: List<String>): Int {
return input.map { parseRoundPart1(it) }
.sumOf { it.score }
}
fun part2(input: List<String>): Int {
return input.map { parseRoundPart2(it) }
.sumOf { it.score }
}
enum class Throw(val score: Int) {
Rock(1),
Paper(2),
Scissors(3),
}
enum class Outcome(val score: Int) {
Win(6),
Draw(3),
Lose(0),
}
val throwMap = mapOf(
"A" to Throw.Rock,
"B" to Throw.Paper,
"C" to Throw.Scissors,
"X" to Throw.Rock,
"Y" to Throw.Paper,
"Z" to Throw.Scissors
)
val outcomeMap = mapOf(
"X" to Outcome.Lose,
"Y" to Outcome.Draw,
"Z" to Outcome.Win
)
private fun parseRoundPart1(line: String): Round {
val (l, r) = line.split(" ");
return Round(throwMap[l]!!, throwMap[r]!!)
}
private fun parseRoundPart2(line: String): Round {
val (l, r) = line.split(" ");
return Round(throwMap[l]!!, outcomeMap[r]!!)
}
data class Round(val opp: Throw, private val _me: Throw?, private val _outcome: Outcome?) {
constructor(opp: Throw, right: Throw): this(opp, right, null)
constructor(opp: Throw, outcome: Outcome): this(opp, null, outcome)
val outcome: Outcome = when {
_outcome != null -> _outcome
_me == opp -> Outcome.Draw
_me == Throw.Rock && opp == Throw.Scissors -> Outcome.Win
_me == Throw.Paper && opp == Throw.Rock -> Outcome.Win
_me == Throw.Scissors && opp == Throw.Paper -> Outcome.Win
else -> Outcome.Lose
}
val me: Throw = when {
_me != null -> _me
_outcome == Outcome.Draw -> opp
_outcome == Outcome.Win && opp == Throw.Scissors -> Throw.Rock
_outcome == Outcome.Lose && opp == Throw.Paper -> Throw.Rock
_outcome == Outcome.Win && opp == Throw.Rock -> Throw.Paper
_outcome == Outcome.Lose && opp == Throw.Scissors -> Throw.Paper
else -> Throw.Scissors
}
val score = outcome.score + me.score
} | 0 | Kotlin | 0 | 0 | 1dae6d2790d7605ac3643356b207b36a34ad38be | 2,197 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/sk/topicWise/slidingwindow/hard/76. Minimum Window Substring.kt | sandeep549 | 262,513,267 | false | {"Kotlin": 530613} | package com.sk.topicWise.slidingwindow.hard
class Solution76 {
fun minWindow(s: String, t: String): String {
if (s.length < t.length) return ""
val dict = t.toCharArray().groupBy { it }.mapValues { it.value.size }.toMutableMap()
val required = dict.size
var l = 0
var r = 0
var formed = 0
val windowCounts = HashMap<Char, Int>()
var ans = Pair(0, s.length + 1)
while (r < s.length) { // Add one character from the right to the window
var c = s[r]
windowCounts[c] = windowCounts.getOrDefault(c, 0) + 1
if (dict.containsKey(c) && windowCounts[c]!! == dict[c]!!) {
formed++
}
while (l <= r && formed == required) {
if (r - l < ans.second - ans.first) {
ans = Pair(l, r) // save new smallest window
}
c = s[l]
windowCounts[c] = windowCounts[c]!! - 1
if (dict.containsKey(c) && windowCounts[c]!! < dict[c]!!) {
formed--
}
l++
}
r++
}
return if (ans.second - ans.first > s.length) "" else s.substring(ans.first, ans.second + 1)
}
fun minWindow2(s: String, t: String): String {
val map = t.toCharArray().groupBy { it }.mapValues { it.value.size }.toMutableMap()
var l = 0
var r = 0
var start = 0
var distance = Int.MAX_VALUE
var counter = t.length
while (r < s.length) {
val c1 = s[r]
if (map.contains(c1)) {
if (map[c1]!! > 0) counter--
map[c1] = map[c1]!! - 1
}
r++
while (counter == 0) {
if (distance > r - l) {
distance = r - l
start = l
}
val c2 = s[l]
if (map.contains(c2)) {
map[c2] = map[c2]!! + 1
if (map[c2]!! > 0) counter++
}
l++
}
}
return if (distance == Int.MAX_VALUE) "" else s.substring(start, start + distance)
}
}
| 1 | Kotlin | 0 | 0 | cf357cdaaab2609de64a0e8ee9d9b5168c69ac12 | 2,238 | leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/tw/gasol/aoc/aoc2022/Day12.kt | Gasol | 574,784,477 | false | {"Kotlin": 70912, "Shell": 1291, "Makefile": 59} | package tw.gasol.aoc.aoc2022
import java.lang.Exception
import java.util.*
import kotlin.Comparator
import kotlin.math.abs
enum class NodeType { Unspecific, Start, Goal }
data class Node(val x: Int, val y: Int, val z: Int, val type: NodeType) {
fun distanceTo(other: Node): Int {
return abs(x - other.x) + abs(y - other.y)
}
override fun toString(): String {
val c = Char(z)
val padStart = 0
return buildString {
append(c)
append('[')
append("$x".padStart(padStart, ' '))
append(",")
append("$y".padStart(padStart, ' '))
append("|$z]")
}
}
}
class NodeComparator(private val start: Node, private val goal: Node, var currentHeight: Int? = null) :
Comparator<Node> {
private fun costTo(node: Node): Int {
val heightCost = if (currentHeight != null) {
abs(currentHeight!! - node.z + 1)
} else 0
return start.distanceTo(node) + goal.distanceTo(node) + heightCost
}
override fun compare(a: Node, b: Node): Int {
return costTo(b) - costTo(a)
}
}
class Day12 {
fun genMap(input: String): List<List<Node>> {
return input.lines()
.filterNot { it.isBlank() }
.mapIndexed { rows, line ->
line.toCharArray()
.mapIndexed { cols, c ->
val type = when (c) {
'S' -> NodeType.Start
'E' -> NodeType.Goal
else -> NodeType.Unspecific
}
val z = when (type) {
NodeType.Start -> 'a'.code
NodeType.Goal -> 'z'.code
else -> c.code
}
Node(cols, rows, z, type)
}
}
}
fun part1(input: String): Int {
val map = genMap(input)
val start = map.map { line -> line.firstOrNull { it.type == NodeType.Start } }.firstNotNullOf { it }
val end = map.map { line -> line.firstOrNull { it.type == NodeType.Goal } }.firstNotNullOf { it }
val cost = NodeComparator(start, end)
val path = aStartSearch(start, end, cost, { findNeighbors(it, map) }) {
cost.currentHeight = it.z
}
// printMap(map, path)
return path.size - 1
}
private fun <T> aStartSearch(
start: T,
goal: T,
costComparator: Comparator<T>,
neighbors: (T) -> List<T>,
setHeight: ((T) -> Unit)? = null
): List<T> {
var frontier: PriorityQueue<T>? = PriorityQueue(costComparator)
frontier!!.add(start)
val cameFroms = mutableMapOf<T, T>()
cameFroms[start] = start
var nextFrontier: PriorityQueue<T>?
while (frontier != null) {
nextFrontier = PriorityQueue(costComparator)
while (frontier.isNotEmpty()) {
val current = frontier.poll()
if (current == goal) {
break
}
setHeight?.invoke(current)
for (next in neighbors(current)) {
if (next !in cameFroms) {
nextFrontier.add(next)
cameFroms[next] = current
}
}
}
if (nextFrontier.isEmpty()) {
break
}
frontier = nextFrontier
}
val path = mutableListOf<T>()
var current = goal
while (current != start) {
path.add(current)
current = cameFroms[current]!!
}
path.add(start)
path.reverse()
return path
}
private fun printMap(map: List<List<Node>>, pathList: List<Node>? = null) {
map.forEach { rows ->
rows.forEach { node ->
val index = pathList?.indexOf(node) ?: -1
if (index >= 0) {
val nextIndex = index + 1
if (nextIndex < pathList!!.size) {
val nextNode = pathList[nextIndex]
val c = when (nextNode.x - node.x) {
1 -> '>'
-1 -> '<'
else -> when (nextNode.y - node.y) {
1 -> 'v'
-1 -> '^'
else -> ' '
}
}
print(c)
} else {
print('*')
}
} else {
print(Char(node.z))
}
}
println()
}
}
fun part2(input: String): Int {
val map = genMap(input)
val start = map.map { line -> line.firstOrNull { it.type == NodeType.Start } }.firstNotNullOf { it }
val end = map.map { line -> line.firstOrNull { it.type == NodeType.Goal } }.firstNotNullOf { it }
val cost = NodeComparator(start, end)
val minSteps = map.flatMap { rows -> rows.filter { it.z == 'a'.code } }
.map { start ->
try {
val path = aStartSearch(start, end, cost, { findNeighbors(it, map) }) { current ->
cost.currentHeight = current.z
}
path.size
} catch (e: Exception) {
Int.MAX_VALUE
}
}.minOf { it }
return minSteps - 1
}
private fun findNeighbors(node: Node, map: List<List<Node>>): List<Node> {
val rows = map.size
val cols = map.first().size
return buildList {
if (node.x > 0) add(map[node.y][node.x - 1])
if (node.x < cols - 1) add(map[node.y][node.x + 1])
if (node.y > 0) add(map[node.y - 1][node.x])
if (node.y < rows - 1) add(map[node.y + 1][node.x])
}.filter { it.z - node.z <= 1 }
}
} | 0 | Kotlin | 0 | 0 | a14582ea15f1554803e63e5ba12e303be2879b8a | 6,150 | aoc2022 | MIT License |
src/main/kotlin/Day15.kt | clechasseur | 267,632,210 | false | null | object Day15 {
private val input = Sculpture(listOf(
Disc(17, 1),
Disc(7, 0),
Disc(19, 2),
Disc(5, 0),
Disc(3, 0),
Disc(13, 5)
), -1, 0)
fun part1(): Int = generateSequence(input) { it.moveWithNewBall() }.first { ballPassesThrough(it) }.t
fun part2(): Int = generateSequence(input.addDisc(Disc(11, 0))) {
it.moveWithNewBall()
}.first {
ballPassesThrough(it)
}.t
private data class Disc(val numPos: Int, val curPos: Int) {
fun move(): Disc = Disc(numPos, if (curPos == numPos - 1) 0 else curPos + 1)
}
private data class Sculpture(val discs: List<Disc>, val ballPos: Int, val t: Int) {
val ballBounced: Boolean
get() = ballPos in discs.indices && discs[ballPos].curPos != 0
val ballPassedThrough: Boolean
get() = ballPos == discs.size
fun move(): Sculpture = Sculpture(discs.map { it.move() }, ballPos + 1, t + 1)
fun moveWithNewBall(): Sculpture = Sculpture(discs.map { it.move() }, -1, t + 1)
fun addDisc(disc: Disc): Sculpture = Sculpture(discs + disc, ballPos, t)
}
private fun ballPassesThrough(sculpture: Sculpture): Boolean = generateSequence(sculpture) {
if (it.ballPassedThrough) {
null
} else {
val next = it.move()
if (next.ballBounced) null else next
}
}.last().ballPassedThrough
}
| 0 | Kotlin | 0 | 0 | 120795d90c47e80bfa2346bd6ab19ab6b7054167 | 1,445 | adventofcode2016 | MIT License |
kotlin/src/katas/kotlin/palindromes/Palindromes.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.palindromes
import datsok.shouldEqual
import org.junit.Test
class Palindromes {
@Test fun `palindrome example from the task`() {
findLongestPalindromes("sqrrqabccbatudefggfedvwhijkllkjihxymnnmzpop") shouldEqual listOf(
Palindrome("hijkllkjih", IntRange(23, 32)),
Palindrome("defggfed", IntRange(13, 20)),
Palindrome("abccba", IntRange(5, 10))
)
}
@Test fun `find all substrings of a string`() {
"abcd".allSubstrings().map { it.first }.toList() shouldEqual listOf(
"abcd", "abc", "ab", "a",
"bcd", "bc", "b",
"cd", "c",
"d"
)
}
@Test fun `determine if string is a palindrome`() {
"".isPalindrome() shouldEqual true
"a".isPalindrome() shouldEqual true
"aa".isPalindrome() shouldEqual true
"ab".isPalindrome() shouldEqual false
"ba".isPalindrome() shouldEqual false
"aba".isPalindrome() shouldEqual true
"abba".isPalindrome() shouldEqual true
"aabba".isPalindrome() shouldEqual false
}
data class Palindrome(val value: String, val range: IntRange) {
override fun toString() = "Text: $value, Index: ${range.first}, Length: ${value.length}"
}
fun findLongestPalindromes(s: String, maxAmount: Int = 3, minPalindromeSize: Int = 2): List<Palindrome> {
val result = ArrayList<Palindrome>()
s.allSubstrings()
.filter { (substring, _) ->
substring.length >= minPalindromeSize && substring.isPalindrome()
}
.forEach { (substring, range) ->
if (result.none { it.range.contains(range) }) {
result.add(Palindrome(substring, range))
}
}
return result.sortedBy { -it.value.length }.distinct().take(maxAmount)
}
fun String.allSubstrings(): Sequence<Pair<String, IntRange>> = sequence {
val s = this@allSubstrings
0.until(s.length).forEach { from ->
s.length.downTo(from + 1).forEach { to ->
val range = IntRange(from, to - 1)
val substring = s.substring(range)
yield(Pair(substring, range))
}
}
}
tailrec fun String.isPalindrome(): Boolean =
if (length < 2) true
else if (first() != last()) false
else substring(1, length - 1).isPalindrome()
private fun IntRange.contains(range: IntRange) = contains(range.first) && contains(range.last)
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 2,558 | katas | The Unlicense |
src/main/kotlin/Day17.kt | andrewrlee | 434,584,657 | false | {"Kotlin": 29493, "Clojure": 14117, "Shell": 398} | object Day17 {
// val targetArea = 20..30 to -10..-5
val targetArea = 248..285 to -85..-56
data class Coord(val x: Int, val y: Int) {
constructor(coord: Pair<Int, Int>) : this(coord.first, coord.second)
}
private fun Pair<IntRange, IntRange>.toCoords(): List<Coord> {
val (xs, ys) = this
return xs.flatMap { row -> ys.map { col -> Coord(row, col) } }
}
private fun Pair<IntRange, IntRange>.draw(path: List<Coord>) {
val targetArea = this.toCoords()
println("\n")
val maxCols = (path + targetArea).maxOf { it.x } + 2
val maxRows = (path + targetArea).maxOf { it.y } + 2
val minRows = (path + targetArea).minOf { it.y } - 2
(minRows..maxRows).reversed().forEach { row ->
print(row.toString().padStart(3, ' ') + " ")
(0..maxCols).forEach { col ->
print(
when {
path.contains(Coord(col, row)) -> "#"
targetArea.contains(Coord(col, row)) -> "T"
else -> "."
}
)
}
println()
}
}
private fun Pair<IntRange, IntRange>.outOfBounds(point: Coord): Boolean {
val (xs, ys) = this
val (x, y) = point
return x > xs.last || y < ys.first
}
fun Pair<IntRange, IntRange>.within(point: Coord): Boolean {
val (xs, ys) = this
val (x, y) = point
return xs.contains(x) && ys.contains(y)
}
private fun fire(x: Int, y: Int): List<Coord> {
val velocity = generateSequence(x to y) { (x, y) ->
(when {
x > 0 -> x - 1
x < 0 -> x + 1
else -> 0
}) to y - 1
}.iterator()
return generateSequence(Coord(0 to 0)) { (x, y) ->
val (x2, y2) = velocity.next()
Coord((x + x2) to (y + y2))
}
.takeWhile { targetArea.within(it) || !targetArea.outOfBounds(it) }
.toList()
}
object Part1 {
fun run() {
val paths = (0..100).flatMap { x ->
(0..100).map { y ->
(x to y) to fire(x, y)
}
}
.filter { (_, path) -> targetArea.within(path.last()) }
.sortedBy { (_, path) -> path.maxByOrNull { it.y }!!.y }
println(paths.maxOf { (_, path) -> path.maxOf{ it.y } })
targetArea.draw(fire(23, 84))
}
}
object Part2 {
fun run() {
val paths = (20..300).flatMap { x ->
(-100..100).map { y ->
(x to y) to fire(x, y)
}
}
.filter { (_, path) -> targetArea.within(path.last()) }
.map {(velocity, _) -> velocity}
println(paths.size)
}
}
}
fun main() {
Day17.Part1.run()
Day17.Part2.run()
} | 0 | Kotlin | 0 | 0 | aace0fccf9bb739d57f781b0b79f2f3a5d9d038e | 2,974 | adventOfCode2021 | MIT License |
src/Day05.kt | Sghazzawi | 574,678,250 | false | {"Kotlin": 10945} | import java.util.*
data class CraneCommand(val quantity: Int, val from: Int, val to: Int)
fun MutableMap<Int, Stack<Char>>.processCraneCommand(command: CraneCommand): MutableMap<Int, Stack<Char>> {
val fromStack = get(command.from)
val toStack = get(command.to)
for (i in 0 until command.quantity) {
toStack!!.push(fromStack!!.pop()!!)
}
return this
}
fun MutableMap<Int, Stack<Char>>.processBatchCraneCommand(command: CraneCommand): MutableMap<Int, Stack<Char>> {
val tempStack = Stack<Char>()
val fromStack = get(command.from)
val toStack = get(command.to)
for (i in 0 until command.quantity) {
tempStack.push(fromStack!!.pop()!!)
}
for (i in 0 until command.quantity) {
toStack!!.push(tempStack.pop()!!)
}
return this
}
fun MutableMap<Int, Stack<Char>>.getResult(): String {
return String(keys.sorted().map { get(it)!!.pop() }.toCharArray())
}
fun getCraneCommand(input: String): CraneCommand {
val split = input.split("from")
val quantity = split[0].split(" ")[1].trim().toInt()
val (from, to) = split[1].split("to").map { it.trim().toInt() }
return CraneCommand(quantity, from, to)
}
fun getLabelPositionMap(input: List<String>, index: Int): Map<Int, Int> {
val mutableMap = mutableMapOf<Int, Int>()
val labels = input.get(index)
for (i in (labels.indices)) {
if (labels[i].isDigit()) {
mutableMap[i] = labels[i].digitToInt()
}
}
return mutableMap.toMap()
}
fun getCharStackMap(labelPositionMap: Map<Int, Int>, characters: String): Map<Int, Char> {
val mutableMap = mutableMapOf<Int, Char>()
for (i in (characters.indices)) {
if (characters[i].isLetter()) {
mutableMap[labelPositionMap[i]!!] = characters[i]
}
}
return mutableMap
}
fun getStackMap(input: List<String>, indexOfLabelRow: Int): MutableMap<Int, Stack<Char>> {
val stackMap = mutableMapOf<Int, Stack<Char>>()
val labelPositionMap = getLabelPositionMap(input, indexOfLabelRow)
for (i in (indexOfLabelRow - 1 downTo 0)) {
val charStackMap = getCharStackMap(labelPositionMap, input[i])
for (j in charStackMap.keys) {
val stack: Stack<Char> = stackMap.getOrPut(j) { Stack<Char>() }
stack.push(charStackMap[j])
}
}
return stackMap
}
fun main() {
fun part1(input: List<String>): String {
val indexOfLabelRow = input.indexOfFirst { it.all { it.isDigit() || it.isWhitespace() } }
val stackMap = getStackMap(input, indexOfLabelRow)
(indexOfLabelRow + 2 until input.size)
.map { getCraneCommand(input[it]) }
.fold(stackMap) { acc, craneCommand -> acc.processCraneCommand(craneCommand) }
return stackMap.getResult()
}
fun part2(input: List<String>): String {
val indexOfLabelRow = input.indexOfFirst { it.all { it.isDigit() || it.isWhitespace() } }
val stackMap = getStackMap(input, indexOfLabelRow)
(indexOfLabelRow + 2 until input.size)
.map { getCraneCommand(input[it]) }
.fold(stackMap) { acc, craneCommand -> acc.processBatchCraneCommand(craneCommand) }
return stackMap.getResult()
}
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | a26111fa1bcfec28cc43a2f48877455b783acc0d | 3,330 | advent-of-code-kotlin | Apache License 2.0 |
src/Day15.kt | kenyee | 573,186,108 | false | {"Kotlin": 57550} | data class Sensor(
val x: Int,
val y: Int,
val beaconX: Int,
val beaconY: Int
) {
internal val dX = Math.abs(x - beaconX)
internal val dY = Math.abs(y - beaconY)
fun isInRange(posX: Int, posY: Int): Boolean {
return posX in (x - dX)..(x + dX) &&
posY in (y - dY)..(y + dY)
}
fun isInYRange(posY: Int): Boolean {
return posY in (y - dY)..(y + dY)
}
fun getXRangeForRow(posY: Int): IntRange {
val rowDiff = Math.abs(y - posY)
val colDiff = Math.abs(dX + dY - rowDiff)
return (x - colDiff)..(x + colDiff)
}
}
fun main() { // ktlint-disable filename
val regex = "Sensor at x=([-0-9]+), y=([-0-9]+): closest beacon is at x=([-0-9]+), y=([-0-9]+)".toRegex()
fun part1(input: List<String>): Int {
// find grid size
val sensors = mutableListOf<Sensor>()
var minX = Integer.MAX_VALUE
var maxX = Integer.MIN_VALUE
var minY = Integer.MAX_VALUE
var maxY = Integer.MIN_VALUE
for (line in input) {
val matches = regex.find(line)
val (sX, sY, bX, bY) = matches!!.groupValues.drop(1).map { it.toInt() }
val sensor = Sensor(sX, sY, bX, bY)
sensors.add(sensor)
minX = Math.min(minX, sX - sensor.dX)
maxX = Math.max(maxX, sX + sensor.dX)
minY = Math.min(minY, sY - sensor.dY)
maxY = Math.max(maxY, sY + sensor.dY)
}
val numRows = maxY - minY
val numCols = maxX - minX
val scanRow = 10
println("Grid size: ($minX,$minY) ($maxX,$maxY) numRows:$numRows, numCols:$numCols, numSensors:${sensors.size}")
val sensorsInRange = sensors.filter { it.isInYRange(scanRow) }
println("filtered Sensors: $sensorsInRange")
val row = CharArray(numCols+1) { '.' }
for (sensor in sensorsInRange) {
val xRange = sensor.getXRangeForRow(scanRow)
println("row $scanRow range for $sensor is $xRange")
for (x in xRange) {
// normalize x pos to 0
val normalizedX = x - minX
if (normalizedX in row.indices) {
row[normalizedX] = '#'
}
}
}
for (sensor in sensorsInRange) {
if (sensor.beaconY == scanRow) {
row[sensor.beaconX - minX] = 'B'
}
}
val invalid = row.count { it == '#' }
println("Row 10 is: $minX ${String(row)} $maxX")
// for each scanned beacon, get dx, dy. Fill diamond area with # corners are dx+dy
return invalid
}
fun part2(input: List<String>): Int {
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day15_test")
println("Test #no sensor positions in row 10: ${part1(testInput)}")
check(part1(testInput) == 26)
// println("Test #Sand units with floor: ${part2(testInput)}")
// check(part2(testInput) == 93)
// val input = readInput("Day15_input")
// println("#Sand units: ${part1(input)}")
// println("#Sand units with floor: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 814f08b314ae0cbf8e5ae842a8ba82ca2171809d | 3,195 | KotlinAdventOfCode2022 | Apache License 2.0 |
kotlin/1048-longest-string-chain.kt | neetcode-gh | 331,360,188 | false | {"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750} | //dfs
class Solution {
fun longestStrChain(words: Array<String>): Int {
val wordList = words.toHashSet()
val dp = HashMap<String, Int>()
fun dfs(word: String, len: Int): Int {
if (word !in wordList) return 0
if ("$word:$len" in dp) return dp["$word:$len"]!!
var res = len
for (i in 0 until 26) {
for (j in 0..word.length) {
val nextWord = word.substring(0, j) + ('a' + i) + word.substring(j, word.length)
res = maxOf(res, dfs(nextWord, len + 1))
}
}
dp["$word:$len"] = res
return res
}
var res = 1
for (word in wordList) {
res = maxOf(res, dfs(word, 1))
}
return res
}
}
//dp
class Solution {
fun longestStrChain(words: Array<String>): Int {
words.sortBy { it.length }
val dp = HashMap<String, Int>()
var res = 0
for (word in words) {
var cur = 1
for (i in 0 until word.length) {
val nextWord = word.substring(0, i) + word.substring(i + 1)
dp[nextWord]?.let {
cur = maxOf(cur, it + 1)
}
}
dp[word] = cur
res = maxOf(res, cur)
}
return res
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 1,397 | leetcode | MIT License |
algorithms/src/main/kotlin/io/nullables/api/playground/algorithms/QuadNode.kt | AlexRogalskiy | 331,076,596 | false | null | /*
* Copyright (C) 2021. <NAME>. All Rights Reserved.
*
* 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 io.nullables.api.playground.algorithms
class QuadNode<V> private constructor(
private val NW: QuadTree<V>,
private val NE: QuadTree<V>,
private val SW: QuadTree<V>,
private val SE: QuadTree<V>
) : QuadTree<V> {
override val frame: Rect = Rect(NW.frame.TL, SE.frame.BR)
constructor(frame: Rect) : this(
QuadNil<V>(Rect(frame.origin, frame.width / 2, frame.height / 2)),
QuadNil<V>(
Rect(
Point(frame.x1 + frame.width / 2 + 1, frame.y1),
frame.width / 2,
frame.height / 2
)
),
QuadNil<V>(
Rect(
Point(frame.x1, frame.y1 + frame.height / 2 + 1),
frame.width / 2,
frame.height / 2
)
),
QuadNil<V>(Rect(frame.center, frame.width / 2, frame.height / 2))
)
override fun get(rect: Rect): Iterable<V> =
(if (NW.frame.intersects(rect)) NW[rect] else emptyList()) +
(if (NE.frame.intersects(rect)) NE[rect] else emptyList()) +
(if (SW.frame.intersects(rect)) SW[rect] else emptyList()) +
(if (SE.frame.intersects(rect)) SE[rect] else emptyList())
override fun plus(pair: Pair<Point, V>): QuadTree<V> = QuadNode(
if (NW.frame.isInside(pair.first)) NW + pair else NW,
if (NE.frame.isInside(pair.first)) NE + pair else NE,
if (SW.frame.isInside(pair.first)) SW + pair else SW,
if (SE.frame.isInside(pair.first)) SE + pair else SE
)
}
class QuadLeaf<V>(override val frame: Rect, val value: Pair<Point, V>) : QuadTree<V> {
override fun get(rect: Rect): Iterable<V> =
if (rect.isInside(value.first)) listOf(value.second)
else emptyList()
override fun plus(pair: Pair<Point, V>): QuadTree<V> =
QuadNode<V>(frame.cover(pair.first)) + value + pair
}
class QuadNil<V>(override val frame: Rect) : QuadTree<V> {
override fun get(rect: Rect): Iterable<V> = emptyList()
override fun plus(pair: Pair<Point, V>): QuadLeaf<V> =
QuadLeaf(frame.cover(pair.first), value = pair)
}
interface QuadTree<V> {
val frame: Rect
operator fun get(rect: Rect): Iterable<V>
operator fun plus(pair: Pair<Point, V>): QuadTree<V>
}
fun <V> emptyQuadTree(frame: Rect): QuadTree<V> = QuadNil(frame)
fun <V> quadTreeOf(frame: Rect, vararg pairs: Pair<Point, V>): QuadTree<V> {
var empty = emptyQuadTree<V>(frame)
for (pair in pairs) {
empty += pair
}
return empty
}
| 13 | Kotlin | 2 | 2 | d7173ec1d9ef227308d926e71335b530c43c92a8 | 3,158 | gradle-kotlin-sample | Apache License 2.0 |
src/main/kotlin/me/grison/aoc/y2021/Day24.kt | agrison | 315,292,447 | false | {"Kotlin": 267552} | package me.grison.aoc.y2021
import me.grison.aoc.*
/**
* Solved it manually exactly like Day 23, with some more luck involved.
* Solution is based on the brilliant explanation you'll find here:
* https://github.com/dphilipson/advent-of-code-2021/blob/master/src/days/day24.rs
*/
class Day24 : Day(24, 2021) {
override fun title() = "Arithmetic Logic Unit"
override fun partOne() = solve(9999999 downTo 1111111)
// should start at 1111111, but speed it up starting near the correct answer
override fun partTwo() = solve(2222222..9999999)
private fun solve(range: IntProgression): Long {
val cycleSize = inputList.tail().withIndex().first { it.value.startsWith("inp") }.index + 1
val parts = inputList.chunked(cycleSize).map { Values(it) }
for (input in range) {
var (z, digitPosition, submarineNumber) = Triple(0, 0, "")
for (part in parts) {
val digit: Int
if (part.div == 1) {
digit = input.padLeft(7, '0')[digitPosition].int()
digitPosition++
} else
digit = z % 26 + part.check
z = part.computeZ(digit, z)
submarineNumber += digit
}
if (validNumber(z, submarineNumber))
return submarineNumber.toLong()
}
return 0
}
private fun validNumber(z: Int, number: String) =
z == 0 && number.length == 14 && !number.contains('0')
data class Values(val div: Int, val check: Int, val offset: Int) {
constructor(instructions: Instructions) :
this(
instructions.first { it.startsWith("div") }.firstInt(), // first DIV
instructions.second { it.startsWith("add") }.firstInt(), // second ADD
instructions.filter { it.startsWith("add") }.butLast().last().firstInt() // before last ADD
)
fun computeZ(w: Int, z: Int): Int {
val x = if ((z % 26) + check != w) 1 else 0
return (z / div) * (25 * x + 1) + ((w + offset) * x)
}
}
}
private typealias Instructions = List<String>
| 0 | Kotlin | 3 | 18 | ea6899817458f7ee76d4ba24d36d33f8b58ce9e8 | 2,201 | advent-of-code | Creative Commons Zero v1.0 Universal |
src/main/kotlin/dev/bogwalk/batch5/Problem52.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch5
import kotlin.math.pow
/**
* Problem 52: Permuted Multiples
*
* https://projecteuler.net/problem=52
*
* Goal: Find all positive integers, x <= N, such that all requested multiples (x, 2x, ..., Kx)
* are a permutation of x.
*
* Constraints: 125_875 <= N <= 2e6, 2 <= K <= 6
*
* e.g.: N = 125_875, K = 2
* output = [[125_874, 251_748]]
*/
class PermutedMultiples {
/**
* Solution optimised by limiting loops to between 10^m and 10^(m+1) / [k], where m is the
* amount of digits at the time, as any higher starting integer will gain more digits when
* multiplied & not be a permutation.
*/
fun permutedMultiples(n: Int, k: Int): List<List<Int>> {
val results = mutableListOf<List<Int>>()
var start = 125_874
var digits = 6
while (start <= n) {
val end = minOf(n + 1, (10.0).pow(digits).toInt() / k)
xLoop@for (x in start until end) {
val xString = x.toString()
val perms = mutableListOf(x)
for (m in 2..k) {
val multiple = x * m
if (xString.isPermutation((multiple).toString())) {
perms.add(multiple)
} else continue@xLoop
}
results.add(perms)
}
digits++
start = (10.0).pow(digits - 1).toInt()
}
return results
}
private fun String.isPermutation(other: String): Boolean {
return this.toCharArray().sorted() == other.toCharArray().sorted()
}
/**
* Project Euler specific implementation that finds the smallest positive integer, x, such
* that 2x, ..., 6x are all permutations of x.
*/
fun smallestPermutedMultiple(): Int {
var x = 125_875
var perms = 1
while (perms != 6) {
x++
val xString = x.toString()
for (m in 2..6) {
if (xString.isPermutation((x * m).toString())) {
perms++
} else {
perms = 1
break
}
}
}
return x
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 2,212 | project-euler-kotlin | MIT License |
src/Day17.kt | fercarcedo | 573,142,185 | false | {"Kotlin": 60181} | private const val CHAMBER_WIDTH = 7
private const val MAX_ROCKS_PART_ONE = 2022L
private const val MAX_ROCKS_PART_TWO = 1000000000000L
enum class RockType {
HORIZONTAL_LINE {
override fun getPoints(bottomLeftPosition: Pair<Long, Long>): List<Pair<Long, Long>> {
return (bottomLeftPosition.first until bottomLeftPosition.first + 4).map {
it to bottomLeftPosition.second
}
}
}, PLUS {
override fun getPoints(bottomLeftPosition: Pair<Long, Long>): List<Pair<Long, Long>> {
return listOf(
bottomLeftPosition.first + 1 to bottomLeftPosition.second,
bottomLeftPosition.first to bottomLeftPosition.second + 1,
bottomLeftPosition.first + 1 to bottomLeftPosition.second + 1,
bottomLeftPosition.first + 1 to bottomLeftPosition.second + 2,
bottomLeftPosition.first + 2 to bottomLeftPosition.second + 1
)
}
}, L {
override fun getPoints(bottomLeftPosition: Pair<Long, Long>): List<Pair<Long, Long>> {
return (bottomLeftPosition.first until bottomLeftPosition.first + 3).map {
it to bottomLeftPosition.second
} + (bottomLeftPosition.second + 1 until bottomLeftPosition.second + 3).map {
bottomLeftPosition.first + 2 to it
}
}
}, VERTICAL_LINE {
override fun getPoints(bottomLeftPosition: Pair<Long, Long>): List<Pair<Long, Long>> {
return (bottomLeftPosition.second until bottomLeftPosition.second + 4).map {
bottomLeftPosition.first to it
}
}
}, SQUARE {
override fun getPoints(bottomLeftPosition: Pair<Long, Long>): List<Pair<Long, Long>> {
return (bottomLeftPosition.first until bottomLeftPosition.first + 2).flatMap { first ->
(bottomLeftPosition.second until bottomLeftPosition.second + 2).map { second ->
first to second
}
}
}
};
abstract fun getPoints(bottomLeftPosition: Pair<Long, Long>): List<Pair<Long, Long>>
}
enum class Movement {
LEFT, RIGHT
}
fun main() {
fun parseMovements(input: List<String>) = input.first().map {
if (it == '<') {
Movement.LEFT
} else {
Movement.RIGHT
}
}
data class Data(
val rockNumber: Long,
val rockType: RockType,
val movementIndex: Int,
val towerHeight: Long
)
fun findCycle(data: List<Data>): Pair<Long, Long>? {
if (data.size < 2) {
return null
}
var tortoise = 0
var hare = 1
while (hare < data.size) {
val tortoiseData = data[tortoise]
val hareData = data[hare]
if (tortoiseData.rockType == hareData.rockType &&
tortoiseData.movementIndex == hareData.movementIndex) {
return tortoiseData.rockNumber to hareData.rockNumber
}
tortoise++
hare += 2
}
return null
}
fun findTowerSizeForRockNumber(rockNumber: Long, data: List<Data>): Long =
data.find { it.rockNumber == rockNumber }!!.towerHeight
fun calculateTowerSize(
tower: Map<Pair<Long, Long>, Boolean>,
foundCycle: Pair<Long, Long>?,
data: List<Data>,
maxRocks: Long
) = if (foundCycle != null) {
val cycleSize = foundCycle.second - foundCycle.first
val cycleHeight = findTowerSizeForRockNumber(foundCycle.second, data) -
findTowerSizeForRockNumber(foundCycle.first, data)
val cycledRocks = maxRocks - foundCycle.first
val numCycles = cycledRocks / cycleSize
val remainingRocks = cycledRocks % cycleSize
val heightBeforeCycle = findTowerSizeForRockNumber(foundCycle.first - 1, data)
val heightCycles = numCycles * cycleHeight
val remainingHeight = findTowerSizeForRockNumber(foundCycle.first - 1 + remainingRocks, data) -
findTowerSizeForRockNumber(foundCycle.first - 1, data)
heightBeforeCycle + heightCycles + remainingHeight
} else {
tower.maxOf { it.key.second } + 1
}
fun play(input: List<String>, maxRocks: Long): Long {
val movements = parseMovements(input)
val data = mutableListOf<Data>()
val tower = mutableMapOf<Pair<Long, Long>, Boolean>()
var movementIndex = 0
var rockNumber = 0L
var foundCycle: Pair<Long, Long>? = null
while (rockNumber < maxRocks && foundCycle == null) {
val rockType = RockType.values()[(rockNumber % RockType.values().size).toInt()]
var bottomLeftPosition = 2L to ((tower.maxOfOrNull { it.key.second } ?: -1L) + 1) + 3
var stop = false
while (!stop) {
val newBottomLeftPosition = when (movements[movementIndex]) {
Movement.LEFT -> bottomLeftPosition.copy(first = bottomLeftPosition.first - 1)
Movement.RIGHT -> bottomLeftPosition.copy(first = bottomLeftPosition.first + 1)
}
if (rockType.getPoints(newBottomLeftPosition).none {
it in tower ||
it.first < 0 ||
it.first >= CHAMBER_WIDTH
}) {
bottomLeftPosition = newBottomLeftPosition
}
val newFallenBottomLeftPosition = bottomLeftPosition.copy(second = bottomLeftPosition.second - 1)
if (rockType.getPoints(newFallenBottomLeftPosition).none {
it in tower ||
it.second < 0
}) {
bottomLeftPosition = newFallenBottomLeftPosition
} else {
val points = rockType.getPoints(bottomLeftPosition)
points.forEach {
tower[it] = true
}
stop = true
data.add(Data(rockNumber, rockType, movementIndex, tower.maxOf { it.key.second } + 1))
foundCycle = findCycle(data)
}
movementIndex = (movementIndex + 1) % movements.size
}
rockNumber++
}
return calculateTowerSize(tower, foundCycle, data, maxRocks)
}
fun part1(input: List<String>) = play(input, MAX_ROCKS_PART_ONE)
fun part2(input: List<String>) = play(input, MAX_ROCKS_PART_TWO)
val testInput = readInput("Day17_test")
check(part1(testInput) == 3068L)
check(part2(testInput) == 1514285714288L)
val input = readInput("Day17")
println(part1(input)) // 3157
println(part2(input)) // 1581449275319
} | 0 | Kotlin | 0 | 0 | e34bc66389cd8f261ef4f1e2b7f7b664fa13f778 | 6,820 | Advent-of-Code-2022-Kotlin | Apache License 2.0 |
jvm/src/main/kotlin/io/prfxn/aoc2021/day04.kt | prfxn | 435,386,161 | false | {"Kotlin": 72820, "Python": 362} | // Giant Squid (https://adventofcode.com/2021/day/4)
package io.prfxn.aoc2021
fun main() {
val maxRows = 5
val maxCols = 5
val (numbersToDraw, boards) =
textResourceReader("input/04.txt").useLines { lineSeq ->
val lineIter = lineSeq.iterator()
val numbersToDraw = lineIter.next().splitToSequence(",").map { it.toInt() }.toList()
val boards =
generateSequence {
if (lineIter.hasNext()) {
lineIter.next() // blank line
val board = Array(maxRows) { IntArray(maxCols) { 0 } }
lineIter.asSequence()
.take(maxRows)
.forEachIndexed { row, line ->
line.trim().split(" +".toRegex()).forEachIndexed { col, s ->
board[row][col] = s.toInt()
}
}
board
}
else null
}
.toList()
numbersToDraw to boards
}
fun boardScore(board: Array<IntArray>, nextDrawIndex: Int) =
if (
(0 until maxRows).any { row ->
(0 until maxCols).all { col ->
board[row][col] in numbersToDraw.asSequence().take(nextDrawIndex)
}
} ||
(0 until maxCols).any { col ->
(0 until maxRows).all { row ->
board[row][col] in numbersToDraw.asSequence().take(nextDrawIndex)
}
}
) {
(0 until maxRows).flatMap { row ->
(0 until maxCols).map { col ->
row to col
}
}
.filter { (row, col) ->
board[row][col] !in numbersToDraw.asSequence().take(nextDrawIndex)
}
.sumOf { (row, col) ->
board[row][col]
} *
numbersToDraw[nextDrawIndex - 1]
}
else 0
fun part1() {
var nextDrawIndex = 0
var topScore = 0
while (topScore == 0 && nextDrawIndex < numbersToDraw.size) {
nextDrawIndex++
for (board in boards) {
val score = boardScore(board, nextDrawIndex)
if (score > topScore) {
topScore = score
}
}
}
println(topScore)
}
fun part2() {
var nextDrawIndex = 0
val wonBoards = mutableListOf<Array<IntArray>>()
while (wonBoards.size < boards.size && nextDrawIndex < numbersToDraw.size) {
nextDrawIndex++
boards
.filter { it !in wonBoards }
.forEach{ board ->
val score = boardScore(board, nextDrawIndex)
if (score > 0) {
wonBoards.add(board)
if (wonBoards.size == boards.size) {
println(score)
return@forEach
}
}
}
}
}
part1()
part2()
}
/** output
* 41503
* 3178
*/
| 0 | Kotlin | 0 | 0 | 148938cab8656d3fbfdfe6c68256fa5ba3b47b90 | 3,328 | aoc2021 | MIT License |
src/cn/leetcode/codes/simple16/Simple16.kt | shishoufengwise1234 | 258,793,407 | false | {"Java": 771296, "Kotlin": 68641} | package cn.leetcode.codes.simple16
import cn.leetcode.codes.out
import java.util.*
import kotlin.math.abs
fun main() {
val nums = intArrayOf(-1,2,1,-4)
val re = threeSumClosest(nums,2)
out("re = $re")
}
/*
16. 最接近的三数之和
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
示例:
输入:nums = [-1,2,1,-4], target = 1
输出:2
解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
提示:
3 <= nums.length <= 10^3
-10^3 <= nums[i] <= 10^3
-10^4 <= target <= 10^4
*/
fun threeSumClosest(nums: IntArray, target: Int): Int {
//排序
Arrays.sort(nums)
//预定义一个值
var ans = nums[0] + nums[1] + nums[2]
for (i in nums.indices){
//内部进行双指针循环
var l = i+1
var r = nums.size - 1
while (l < r){
val sum = nums[i] + nums[l] + nums[r]
when {
abs(target - sum) < abs(target - ans) -> {
ans = sum
}
sum < target -> {
l++
}
sum > target -> {
r--
}
//距离相等的情况下 0 直接返回数据
else -> return ans
}
}
}
return ans
} | 0 | Java | 0 | 0 | f917a262bcfae8cd973be83c427944deb5352575 | 1,465 | LeetCodeSimple | Apache License 2.0 |
src/Day09.kt | lmoustak | 573,003,221 | false | {"Kotlin": 25890} | import kotlin.math.absoluteValue
import kotlin.math.sign
data class RopeKnot(var x: Int = 0, var y: Int = 0)
fun main() {
fun updatePlaces(head: RopeKnot, tail: RopeKnot) {
val horizontalDistance = tail.x - head.x
val verticalDistance = tail.y - head.y
if (horizontalDistance.absoluteValue == 2 || verticalDistance.absoluteValue == 2) {
tail.x -= horizontalDistance.sign
tail.y -= verticalDistance.sign
}
}
fun part1(input: List<String>): Int {
val head = RopeKnot()
val tail = RopeKnot()
val placesVisited = mutableSetOf(0 to 0)
for (move in input) {
val (direction, steps) = move.split(' ')
for (i in 1..steps.toInt()) {
when (direction) {
"L" -> head.x--
"R" -> head.x++
"U" -> head.y++
"D" -> head.y--
}
updatePlaces(head, tail)
placesVisited += tail.x to tail.y
}
}
return placesVisited.size
}
fun part2(input: List<String>): Int {
val knots = List(10) { _ -> RopeKnot() }
val placesVisited = mutableSetOf(0 to 0)
for (move in input) {
val (direction, steps) = move.split(' ')
for (i in 1..steps.toInt()) {
val head = knots.first()
when (direction) {
"L" -> head.x--
"R" -> head.x++
"U" -> head.y++
"D" -> head.y--
}
for (j in 0 until knots.size - 1) updatePlaces(knots[j], knots[j + 1])
val tail = knots.last()
placesVisited += tail.x to tail.y
}
}
return placesVisited.size
}
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | bd259af405b557ab7e6c27e55d3c419c54d9d867 | 1,947 | aoc-2022-kotlin | Apache License 2.0 |
03-problems-lab1/src/main/kotlin/Main.kt | iproduct | 277,474,020 | false | {"JavaScript": 3237497, "Kotlin": 545267, "Java": 110766, "HTML": 83688, "CSS": 44893, "SCSS": 32196, "Dockerfile": 58} | import java.io.File
data class LongNumberProblem(
var n: Int,
var a: String,
var fm: List<Int>,
)
fun main(args: Array<String>) {
// read input
// val n = readLine()!!.toInt()
// val a = readLine()!!
// val fm = readLine()!!.split(" ").map { it.toInt() }
// read input from file
// Using BufferedReader
val bf = File("./long-number01.txt").bufferedReader()
val problems = mutableListOf<LongNumberProblem>()
var i = 0
var n: Int = 0
var a: String = ""
var fm: List<Int> = emptyList()
bf.forEachLine {
when (i++ % 3) {
0 -> n = it.toInt()
1 -> a = it
2 -> {
fm = it.split(" ").map { c -> c.toInt() }
problems.add(LongNumberProblem(n, a, fm))
}
}
}
// bf.useLines { lines ->
// lines.forEach {
// when (i++ % 3) {
// 0 -> n = it.toInt()
// 1 -> a = it
// 2 -> {
// fm = it.split(" ").map { c -> c.toInt() }
// problems.add(LongNumberProblem(n, a, fm))
// }
// }
// }
// }
for (p in problems) {
println(solveLongNumber(p))
}
}
private fun solveLongNumber(problem: LongNumberProblem): String {
fun f(c: Char) = '0' + problem.fm[c - '1']
// greedy maximum search
val s = problem.a.indexOfFirst { f(it) > it }
.takeIf { it >= 0 } ?: problem.a.length
val e = problem.a.withIndex().indexOfFirst { (i, c) -> i > s && f(c) < c }
.takeIf { it >= 0 } ?: problem.a.length
val result = problem.a.slice(0 until s) +
problem.a.slice(s until e).map { f(it) }.joinToString("") +
problem.a.slice(e until problem.a.length)
return result
}
| 0 | JavaScript | 1 | 4 | 89884f8c29fffe6c6f0384a49ae8768c8e7ab509 | 1,805 | course-kotlin | Apache License 2.0 |
src/questions/ReorderList.kt | realpacific | 234,499,820 | false | null | package questions
import questions.common.LeetNode
import utils.assertIterableSame
import java.util.*
/**
* You are given the head of a singly linked-list. The list can be represented as `L0 → L1 → … → Ln - 1 → Ln`
*
* Reorder the list to be on the following form: `L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …`
* You may not modify the values in the list's nodes. Only nodes themselves may be changed.
*
* [Source](https://leetcode.com/problems/reorder-list)
*/
private fun reorderList(head: LeetNode?) {
if (head == null) return
if (head.next == null) return
val stack = LinkedList<LeetNode>()
var current: LeetNode? = head
while (current != null) {
stack.addLast(current) // add the nodes to a stack
current = current.next
}
val lengthToSwapsRequired = mapOf(
1 to 0, 2 to 0, // if there are 1 or 2 items, no swaps required
3 to 1, 4 to 1, // if there are 3 or 4 items, just 1 swap required
5 to 2, 6 to 2, // if there are 5 or 6 items, just 2 swap required
7 to 3, 8 to 3,
9 to 4, // case for 9 or 10 items (10 is not possible, but if totalLength=0,
10 to 4, // ...it can be safely considered that the items is in multiple of 10
)
fun numberOfSwapsRequired(totalLength: Int): Int {
if (totalLength <= 10) {
return lengthToSwapsRequired[totalLength]!!
}
// From my observation, the behavior of totalLength to swaps required is:
//
// Length | swaps
// * 1 -> 0
// * 2 -> 0
// * 9 -> 4
// * 10 -> 4
// * 11 -> 5 ( lengthToSwapsRequired[10] + lengthToSwapsRequired[11 % 10] = 4 ) + 1
// * 12 -> 5 ( lengthToSwapsRequired[10] + lengthToSwapsRequired[12 % 10] = 4 ) + 1
// * 13 -> 6 ( lengthToSwapsRequired[10] + lengthToSwapsRequired[13 % 10] = 5 ) + 1
// * 20 -> 9
// * 21 -> 10
// extra 1 for every 10
// each 10s adds a 4
// each 10s adds a 1
// subtract 10 from it and do it again
return 4 + 1 + numberOfSwapsRequired(totalLength - 10)
}
val totalSwapsRequired = numberOfSwapsRequired(stack.size)
var previous: LeetNode? = head
current = head.next
var swapsDone = 0
while (current != null) {
val toBeInserted =
stack.removeLastOrNull() ?: break // pop the stack to put it in the middle of prev and current
swapsDone++
// place [toBeInserted] in the middle
previous?.next = toBeInserted
toBeInserted.next = current
// move to next insertion point
previous = toBeInserted.next
current = previous?.next
if (swapsDone > totalSwapsRequired) {
// no more required
current?.next = null // nullify the end
break
}
}
}
fun main() {
run {
val input = LeetNode.from(IntRange(1, 49).toList().toIntArray())
reorderList(input)
assertIterableSame(
actual = input.toList(),
expected = LeetNode.from(
1,
49,
2,
48,
3,
47,
4,
46,
5,
45,
6,
44,
7,
43,
8,
42,
9,
41,
10,
40,
11,
39,
12,
38,
13,
37,
14,
36,
15,
35,
16,
34,
17,
33,
18,
32,
19,
31,
20,
30,
21,
29,
22,
28,
23,
27,
24,
26,
25
).toList()
)
}
run {
val input = LeetNode.from(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
reorderList(input)
assertIterableSame(
actual = input.toList(),
expected = LeetNode.from(1, 11, 2, 10, 3, 9, 4, 8, 5, 7, 6).toList()
)
}
run {
val input = LeetNode.from(1, 2, 3, 4)
reorderList(input)
assertIterableSame(
actual = input.toList(),
expected = LeetNode.from(1, 4, 2, 3).toList()
)
}
run {
val input = LeetNode.from(1, 2, 3, 4, 5)
reorderList(input)
assertIterableSame(
actual = input.toList(),
expected = LeetNode.from(1, 5, 2, 4, 3).toList()
)
}
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 4,898 | algorithms | MIT License |
src/main/kotlin/Day1.kt | ummen-sherry | 726,250,829 | false | {"Kotlin": 4811} | import java.io.File
private val numberRegex = Regex("""(\d|one|two|three|four|five|six|seven|eight|nine)""")
private val numberReverseRegex = Regex("""(\d|enin|thgie|neves|xis|evif|ruof|eerht|owt|eno)""")
private val validNumbers = mapOf(
"1" to 1,
"2" to 2,
"3" to 3,
"4" to 4,
"5" to 5,
"6" to 6,
"7" to 7,
"8" to 8,
"9" to 9,
"one" to 1,
"two" to 2,
"three" to 3,
"four" to 4,
"five" to 5,
"six" to 6,
"seven" to 7,
"eight" to 8,
"nine" to 9
)
fun sumOfCalibrationValues(input: List<String>): Int {
return input.sumOf {
"${it.first { it.isDigit() }}${it.last { it.isDigit() }}".toInt()
}
}
fun readFile(fileName: String): List<String> {
val resourceFile: File = File("src/main/resources/$fileName") // Adjust the path accordingly
return resourceFile.bufferedReader().use { it.readLines() }
}
fun sumOfCalibrationValuesWithStringDigits(input: List<String>): Int {
return input.mapNotNull { line ->
validNumbers[numberRegex.find(line)?.value ?: ""]
?.let { firstDigit ->
validNumbers[numberReverseRegex.find(line.reversed())?.value?.reversed() ?: ""]
?.let { secondDigit ->
"$firstDigit$secondDigit".toInt()
}
}
}.sum()
}
fun main(args: Array<String>) {
println("Advent 2023 - Day1")
// Part 1
// val input = readFile("day-1-input1.txt")
// val sumOfCalibrationValues = sumOfCalibrationValues(input)
// println("Sum: $sumOfCalibrationValues")
// Part 2
val input = readFile("day-1-input2.txt")
val sumOfCalibrationValues = sumOfCalibrationValuesWithStringDigits(input)
println("Sum: $sumOfCalibrationValues")
}
| 0 | Kotlin | 0 | 0 | c91c1b606a17a00e9efa5f2139d0efd0c1270634 | 1,771 | adventofcode2023 | MIT License |
src/main/kotlin/days/Day13.kt | hughjdavey | 433,597,582 | false | {"Kotlin": 53042} | package days
import util.Utils
class Day13 : Day(13) {
private val dots = inputList.takeWhile { it != "" }.map { it.split(",").map { it.toInt() } }.map { Utils.Coord(it[0], it[1]) }
private val folds = inputList.takeLastWhile { it != "" }.map { it.dropWhile { it != 'x' && it != 'y' }.split("=") }.map { it[0] to it[1].toInt() }
override fun partOne(): Any {
return fold(listOf(folds.first())).count { it == '#' }
}
// todo improve performance as this takes over 2s on my real input
override fun partTwo(): Any {
return "\n${fold(folds)}\n"
}
fun fold(folds: List<Pair<String, Int>>, dots: List<Utils.Coord> = this.dots): String {
return folds.fold(getPaper(dots)) { paper, fold -> fold(fold, paper) }
}
fun fold(fold: Pair<String, Int>, paper: String): String {
val paperList = paper.split("\n")
val (side1, side2) = if (fold.first == "y") {
paperList.subList(0, fold.second) to paperList.subList(fold.second + 1, paperList.size).reversed()
}
else {
paperList.map { it.substring(0, fold.second) } to paperList.map { it.substring(fold.second + 1).reversed() }
}
return side1.mapIndexed { y, row -> row.mapIndexed { x, c -> if (side2[y][x] == '#') '#' else c }.joinToString("") }.joinToString("\n")
}
fun getPaper(dots: List<Utils.Coord> = this.dots): String {
val maxX = dots.maxOf { it.x }
val maxY = dots.maxOf { it.y }
return (0..maxY).flatMap { y -> (0..maxX).map { x ->
val maybeDot = dots.find { it.x == x && it.y == y }
val char = if (maybeDot != null) "#" else "."
if (x == maxX && y != maxY) char + "\n" else char
} }.joinToString("")
}
}
| 0 | Kotlin | 0 | 0 | a3c2fe866f6b1811782d774a4317457f0882f5ef | 1,773 | aoc-2021 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/se/saidaspen/aoc/aoc2021/Day14.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2021
import se.saidaspen.aoc.util.Day
fun main() = Day14.run()
object Day14 : Day(2021, 14) {
private val template = input.lines()[0]
private val inserts = input.lines().drop(2).map { it.split("->") }.associate { it[0].trim() to it[1].trim() }
override fun part1(): Any {
var curr = template
repeat(10) {
curr = curr[0] + curr.windowed(2).map {
if (inserts.containsKey(it)) {
inserts[it]!! + it[1]
} else {
it
}
}.joinToString("")
}
return curr.groupingBy { it }.eachCount().maxOf { it.value } - curr.groupingBy { it }.eachCount().minOf { it.value }
}
override fun part2(): Any {
var count = mutableMapOf<String, Long>()
template.windowed(2).forEach { count[it] = count.getOrDefault(it, 0) + 1 }
repeat(40) {
val oldCount = count.entries.associate { it.key to it.value }
count = mutableMapOf()
oldCount.entries.forEach{
val found = inserts[it.key]!!
count[it.key[0] + found] = count.getOrDefault(it.key[0] + found, 0) + it.value
count[found + it.key[1]] = count.getOrDefault(found + it.key[1], 0) + it.value
}
}
val charCnt = mutableMapOf<Char, Long>()
count.entries.forEach { charCnt[it.key[0]] = charCnt.getOrDefault(it.key[0], 0) + it.value }
charCnt[template.last()] = charCnt[template.last()]!! + 1
return charCnt.values.maxOrNull()!! - charCnt.values.minOrNull()!!
}
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 1,650 | adventofkotlin | MIT License |
src/day16/b/day16b.kt | pghj | 577,868,985 | false | {"Kotlin": 94937} | package day16.b
import day16.a.Valve
import day16.a.read
import day16.a.simplifyGraph
import shouldBe
import kotlin.math.max
fun main() {
val graph = simplifyGraph(read())
val start = graph["AA"]!!.value
var best = 0
// The sum of the rates of unused valves is tracked to estimate the best case of the remaining valve potential.
// If opening all remaining valves in the next minute, and considering their output for the remaining
// duration, will not add up to a better result than the current best, then all efforts in the
// current search path are abandoned.
var unused = graph.nodes().map { it.value.rate }.sum()
fun stepElephant(v: Valve, t: Int, sum: Int) {
if (sum + (25-t) * unused <= best) return
for (vtx in graph[v.key]!!.connected) {
val len = vtx.distanceFrom(v.key)
val dst = vtx.other(v.key).value
if (!dst.used && dst.rate != 0) {
if (t + 1 + len < 26) {
dst.used = true
unused -= dst.rate
val s = sum + (26 - t - len) * dst.rate
best = max(best, s)
stepElephant(dst, t + 1 + len, s)
unused += dst.rate
dst.used = false
}
}
}
}
fun stepElf(v: Valve, t: Int, sum: Int) {
stepElephant(start, 1, sum)
if (sum + (50-t) * unused <= best) return
for (vtx in graph[v.key]!!.connected) {
val len = vtx.distanceFrom(v.key)
val dst = vtx.other(v.key).value
if (!dst.used && dst.rate != 0) {
if (t + 1 + len < 26) {
dst.used = true
unused -= dst.rate
val s = sum + (26 - t - len) * dst.rate
best = max(best, s)
stepElf(dst, t + 1 + len, s)
unused += dst.rate
dst.used = false
}
}
}
}
stepElf(start, 1, 0)
shouldBe(3015, best)
}
| 0 | Kotlin | 0 | 0 | 4b6911ee7dfc7c731610a0514d664143525b0954 | 2,094 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | kecolk | 572,819,860 | false | {"Kotlin": 22071} | fun main() {
data class Move(val count: Int, val from: Int, val to: Int)
fun extractStacks(input: List<String>): List<ArrayDeque<Char>> {
val result = MutableList<ArrayDeque<Char>>(9) { ArrayDeque() }
input.forEach { line ->
if (line.isEmpty() || !line.contains("[")) return result
line.chunked(4).forEachIndexed { index, part ->
if (part.startsWith("[")) {
result[index].add(part[1])
}
}
}
return result
}
fun extractMoves(input: List<String>): List<Move> {
val result: MutableList<Move> = mutableListOf()
input.forEach { line ->
if (line.startsWith("move")) {
val parts = line.split(" ")
result.add(
Move(
count = parts[1].toInt(),
from = parts[3].toInt() - 1,
to = parts[5].toInt() - 1
)
)
}
}
return result
}
fun executeMove(from: ArrayDeque<Char>, to: ArrayDeque<Char>, count: Int) {
for (i in 1..count) {
to.addFirst(from.removeFirst())
}
}
fun executeBulkMove(from: ArrayDeque<Char>, to: ArrayDeque<Char>, count: Int) {
for (i in 1..count) {
to.add(i - 1, from[i - 1])
}
for (i in 1..count) {
from.removeAt(0)
}
}
fun executeMoves(
stacks: List<ArrayDeque<Char>>,
moves: List<Move>,
executeMove: (ArrayDeque<Char>, ArrayDeque<Char>, Int) -> Unit
): String {
moves.forEach { move ->
executeMove(stacks[move.from], stacks[move.to], move.count)
}
return stacks.fold("") { acc, item -> acc + (item.firstOrNull() ?: "") }
}
fun part1(input: List<String>): String =
executeMoves(extractStacks(input), extractMoves(input), ::executeMove)
fun part2(input: List<String>): String =
executeMoves(extractStacks(input), extractMoves(input), ::executeBulkMove)
val testInput = readTextInput("Day05_test")
val input = readTextInput("Day05")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 72b3680a146d9d05be4ee209d5ba93ae46a5cb13 | 2,332 | kotlin_aoc_22 | Apache License 2.0 |
src/main/kotlin/adventofcode/year2022/Day11MonkeyInTheMiddle.kt | pfolta | 573,956,675 | false | {"Kotlin": 199554, "Dockerfile": 227} | package adventofcode.year2022
import adventofcode.Puzzle
import adventofcode.PuzzleInput
import adventofcode.common.product
class Day11MonkeyInTheMiddle(customInput: PuzzleInput? = null) : Puzzle(customInput) {
override val name = "Monkey in the Middle"
override fun partOne() = input
.parseMonkeys()
.playRounds(20) { worryLevel -> worryLevel / 3 }
.business()
override fun partTwo(): Long {
val monkeys = input.parseMonkeys()
val targetMonkeyTestProduct = monkeys.map(Monkey::targetMonkeyTest).product()
return monkeys
.playRounds(10000) { worryLevel -> worryLevel % targetMonkeyTestProduct }
.business()
}
companion object {
private data class Monkey(
val items: MutableList<Long>,
val worryLevelChange: (Long) -> Long,
val targetMonkeyTest: Long,
val trueTarget: Int,
val falseTarget: Int
) {
var itemsInspected = 0L
constructor(description: List<String>) : this(
items = description[1].split(", ", " ").mapNotNull(String::toLongOrNull).toMutableList(),
worryLevelChange = { worryLevel ->
val (operation, changeAmount) = description[2].split(" ").takeLast(2)
when {
operation == "*" && changeAmount == "old" -> worryLevel * worryLevel
operation == "*" -> worryLevel * changeAmount.toLong()
else -> worryLevel + changeAmount.toLong()
}
},
targetMonkeyTest = description[3].split(" ").last().toLong(),
trueTarget = description[4].split(" ").last().toInt(),
falseTarget = description[5].split(" ").last().toInt()
)
fun takeTurn(monkeys: List<Monkey>, worryLevelRelief: (Long) -> Long) {
items.forEach { item ->
val worryLevel = worryLevelRelief(worryLevelChange(item))
val targetMonkey = when (worryLevel % targetMonkeyTest) {
0L -> trueTarget
else -> falseTarget
}
monkeys[targetMonkey].items += worryLevel
}
itemsInspected += items.count()
items.clear()
}
}
private fun String.parseMonkeys() = lines().chunked(7).map(::Monkey)
private fun List<Monkey>.playRounds(count: Int, worryLevelRelief: (Long) -> Long): List<Monkey> {
repeat(count) {
forEach { monkey -> monkey.takeTurn(this, worryLevelRelief) }
}
return this
}
private fun List<Monkey>.business() = map(Monkey::itemsInspected).sortedDescending().take(2).product()
}
}
| 0 | Kotlin | 0 | 0 | 72492c6a7d0c939b2388e13ffdcbf12b5a1cb838 | 2,889 | AdventOfCode | MIT License |
src/main/kotlin/y2023/day01/Day01.kt | TimWestmark | 571,510,211 | false | {"Kotlin": 97942, "Shell": 1067} | package y2023.day01
fun main() {
AoCGenerics.printAndMeasureResults(
part1 = { part1() },
part2 = { part2() }
)
}
fun input(): List<String> {
return AoCGenerics.getInputLines("/y2023/day01/input.txt")
}
fun part1(): Int {
return input().sumOf {
val first = it.first { char -> char.isDigit()}
val last = it.last { char -> char.isDigit() }
(first.toString() + last.toString()).toInt()
}
}
fun part2(): Int {
val writtenToDigit = mapOf(
"one" to 1,
"two" to 2,
"three" to 3,
"four" to 4,
"five" to 5,
"six" to 6,
"seven" to 7,
"eight" to 8,
"nine" to 9,
)
val allDigits = input().map {line ->
val digits = mutableListOf<Int>()
line.forEachIndexed { i, char ->
if(char.isDigit()) {
digits.add(char.digitToInt())
} else {
writtenToDigit.forEach { (written, digit) ->
if (line.substring(i).startsWith(written)) digits.add(digit)
}
}
}
digits
}
return allDigits.sumOf {
(it.first().toString() + it.last().toString()).toInt()
}
}
| 0 | Kotlin | 0 | 0 | 23b3edf887e31bef5eed3f00c1826261b9a4bd30 | 1,233 | AdventOfCode | MIT License |
src/Day14.kt | kmes055 | 577,555,032 | false | {"Kotlin": 35314} | class Move(
val type: String,
val point: Int,
val range: IntRange
) {
private val isHorizon = type == "HORIZON"
val points: List<Pair<Int, Int>>
get() {
return if (this.isHorizon) range.map { Pair(it, point) }
else range.map { Pair(point, it) }
}
companion object {
fun ofHorizon(horizon: IntRange, depth: Int) = Move("HORIZON", depth, horizon)
fun ofVertical(vertical: IntRange, left: Int) = Move("VERTICAL", left, vertical)
}
override fun toString(): String {
return "Move(type='$type', point=$point, range=$range)"
}
}
enum class BoardContent {
ROCK, SAND, AIR
;
fun isBlocked() = (this == ROCK) or (this == SAND)
fun isEmpty() = this == AIR
}
fun BoardContent?.isNullOrEmpty() = this == null || this == BoardContent.AIR
fun main() {
fun parseLine(line: String) =
line.split(" -> ")
.map {
it.split(",")
.map { point -> point.toInt() }
}.map { points -> Pair(points[0], points[1]) }
.windowed(2, 1)
.map { it.first() moveTo it.last() }
fun part1(input: List<String>): Int {
val boards = mutableMapOf<Pair<Int, Int>, BoardContent>()
val maxY = input.map { parseLine(it) }
.flatMap { it.flatMap { move -> move.points } }
.onEach { boards[it] = BoardContent.ROCK }
.maxOf { it.second }
var sandCount = 0
val source = Pair(500, 0)
fun findNextDropPoint(): Pair<Int, Int> {
var current = source
while (true) {
if (current.second > maxY) return 0 to -1
current = if (boards[current.down()].isNullOrEmpty()) {
current.down()
} else if (boards[current.leftDiag()].isNullOrEmpty()) {
current.leftDiag()
} else if (boards[current.rightDiag()].isNullOrEmpty()) {
current.rightDiag()
} else return current
}
}
while (true) {
val nextPoint = findNextDropPoint()
if (nextPoint.second == -1 || nextPoint == source) return sandCount
sandCount += 1
boards[nextPoint] = BoardContent.SAND
}
}
fun part2(input: List<String>): Int {
val boards = mutableMapOf<Pair<Int, Int>, BoardContent>()
val maxY = input.map { parseLine(it) }
.flatMap { it.flatMap { move -> move.points } }
.onEach { boards[it] = BoardContent.ROCK }
.maxOf { it.second }
.let { it + 2 }
var sandCount = 0
val source = Pair(500, 0)
fun findNextDropPoint(): Pair<Int, Int> {
var current = source
while (true) {
if (current.second + 1 == maxY) return current
current = if (boards[current.down()].isNullOrEmpty()) {
current.down()
} else if (boards[current.leftDiag()].isNullOrEmpty()) {
current.leftDiag()
} else if (boards[current.rightDiag()].isNullOrEmpty()) {
current.rightDiag()
} else return current
}
}
while (true) {
val nextPoint = findNextDropPoint()
if (nextPoint == source) break
sandCount += 1
boards[nextPoint] = BoardContent.SAND
}
return sandCount + 1
}
val day = 14
val dayString = String.format("%02d", day)
val testInput = readInput("Day${dayString}_test")
checkEquals(part1(testInput), 24)
checkEquals(part2(testInput), 93)
val input = readInput("Day$dayString")
part1(input).println()
part2(input).println()
}
infix fun Int.rangeTo(to: Int) = if (this > to) (to..this) else (this..to)
infix fun Pair<Int, Int>.moveTo(to: Pair<Int, Int>) =
if (first == to.first) Move.ofVertical(this.second rangeTo to.second, first)
else if (second == to.second) Move.ofHorizon(this.first rangeTo to.first, second)
else throw IllegalArgumentException("Should not reach here: $this, $to")
fun Pair<Int, Int>.down() = Pair(first, second + 1)
fun Pair<Int, Int>.leftDiag() = Pair(first - 1, second + 1)
fun Pair<Int, Int>.rightDiag() = Pair(first + 1, second + 1)
operator fun Map<Pair<Int, Int>, BoardContent>.get(key: Pair<Int, Int>): BoardContent = get(key) ?: BoardContent.AIR | 0 | Kotlin | 0 | 0 | 84c2107fd70305353d953e9d8ba86a1a3d12fe49 | 4,498 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/com/github/dangerground/aoc2020/Day7.kt | dangerground | 317,439,198 | false | null | package com.github.dangerground.aoc2020
import com.github.dangerground.aoc2020.util.DayInput
class Day7(input: List<String>) {
private val bagrules = input.map { BagRule(it) }.map { it.color to it.innerBags }.toMap()
fun getInnerBagCount(color: BagColor): Int {
var total = bagrules[color]!!.entries.map { it.value }.sum()
bagrules[color]!!.forEach {
total += getInnerBagCount(it.key) * it.value
}
return total
}
private fun canContainColor(color: BagColor, searchColor: BagColor): Boolean {
if (bagrules[color]!!.containsKey(searchColor)) {
return true
}
bagrules[color]!!.forEach {
if (canContainColor(it.key, searchColor)) {
return true
}
}
return false
}
fun part1(): Int {
return bagrules.filter { canContainColor(it.key, "shiny gold") }.count()
}
fun part2(): Int {
return getInnerBagCount("shiny gold")
}
}
typealias BagColor = String
class BagRule(input: String) {
val color: BagColor
val innerBags = mutableMapOf<BagColor, Int>()
init {
val parts = input.split("contain")
color = str2Color(parts[0])
parts[1].trim().split(",").filter { it.trim() != "no other bags." }.forEach {
val result = Regex("(\\d+) (.*)").matchEntire(it.trim())
if (result != null) {
innerBags[str2Color(result.groupValues[2])] = result.groupValues[1].toInt()
}
}
}
fun str2Color(string: String) = string.replace(Regex("bags?\\.?"), "").trim()
}
fun main() {
val input = DayInput.asStringList(7)
val day7 = Day7(input)
// part 1
val part1 = day7.part1()
println("result part 1: $part1")
// part2
val part2 = day7.part2()
println("result part 2: $part2")
} | 0 | Kotlin | 0 | 0 | c3667a2a8126d903d09176848b0e1d511d90fa79 | 1,877 | adventofcode-2020 | MIT License |
2021/src/test/kotlin/Day15.kt | jp7677 | 318,523,414 | false | {"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338} | import java.lang.IllegalStateException
import java.util.PriorityQueue
import kotlin.test.Test
import kotlin.test.assertEquals
class Day15 {
data class Coord(val x: Int, val y: Int)
private val directions = listOf(Coord(1, 0), Coord(0, 1), Coord(-1, 0), Coord(0, -1))
@Test
fun `run part 01`() {
val map = getMap()
val totalRisk = map.findTotalRiskForShortestPath()
assertEquals(720, totalRisk)
}
@Test
fun `run part 02`() {
val map = getMap().repeatRight(5).repeatDownwards(5)
val totalRisk = map.findTotalRiskForShortestPath()
assertEquals(3025, totalRisk)
}
private fun Map<Coord, Int>.findTotalRiskForShortestPath(): Int {
val end = Coord(maxX(), maxY())
val queue = PriorityQueue<Pair<Coord, Int>>(1, compareBy { (_, risk) -> risk })
.apply { offer(Coord(0, 0) to 0) }
val totals = mutableMapOf(Coord(0, 0) to 0)
val visited = mutableSetOf<Coord>()
while (queue.isNotEmpty()) {
val (current, totalRisk) = queue.poll()
directions
.map { direction -> Coord(current.x + direction.x, current.y + direction.y) }
.filterNot { coord -> visited.contains(coord) }
.mapNotNull { coord -> this[coord]?.let { risk -> coord to risk } }
.forEach { (coord, risk) ->
val newTotalRisk = totalRisk + risk
val knownTotalRisk = totals[coord] ?: Int.MAX_VALUE
if (newTotalRisk < knownTotalRisk) {
totals[coord] = newTotalRisk
queue.offer(coord to newTotalRisk)
}
}
if (current == end) break
visited.add(current)
}
return totals[end] ?: throw IllegalStateException()
}
private fun Map<Coord, Int>.repeatRight(tiles: Int): Map<Coord, Int> {
val maxX = this.maxX()
return this + this
.flatMap {
(1 until tiles).map { x ->
Coord(it.key.x + (x * (maxX.inc())), it.key.y) to
if (it.value + x > 9) (it.value + x) - 9 else it.value + x
}
}
}
private fun Map<Coord, Int>.repeatDownwards(tiles: Int): Map<Coord, Int> {
val maxY = this.maxY()
return this + this
.flatMap {
(1 until tiles).map { y ->
Coord(it.key.x, it.key.y + (y * (maxY.inc()))) to
if (it.value + y > 9) (it.value + y) - 9 else it.value + y
}
}
}
private fun Map<Coord, Int>.maxX() = this.maxOf { it.key.x }
private fun Map<Coord, Int>.maxY() = this.maxOf { it.key.y }
private fun getMap() = Util.getInputAsListOfString("day15-input.txt")
.map { it.map { c -> c.digitToInt() } }
.let {
it
.first()
.indices
.flatMap { x ->
List(it.size) { y -> Coord(x, y) to it[y][x] }
}
}
.toMap()
}
| 0 | Kotlin | 1 | 2 | 8bc5e92ce961440e011688319e07ca9a4a86d9c9 | 3,141 | adventofcode | MIT License |
src/Day04.kt | becsegal | 573,649,289 | false | {"Kotlin": 9779} | import java.io.File
fun main() {
// assumes sorted
fun List<Int>.fullyContains(innerList: List<Int>): Boolean {
return this.first() <= innerList.first() && this.last() >= innerList.last()
}
// assumes sorted
fun List<Int>.overlaps(otherList: List<Int>): Boolean {
return (this.first() <= otherList.last() && this.last() >= otherList.first())
}
fun part1(filename: String): Int? {
var count: Int = 0;
File(filename).forEachLine {
val ranges = it.split(",")
val range1: List<Int> = ranges[0].split("-").map{ it.toInt() }
val range2: List<Int> = ranges[1].split("-").map{ it.toInt() }
if (range1.fullyContains(range2) || range2.fullyContains(range1)) {
count += 1
}
}
return count;
}
fun part2(filename: String): Int? {
var count: Int = 0;
File(filename).forEachLine {
val ranges = it.split(",")
val range1: List<Int> = ranges[0].split("-").map{ it.toInt() }
val range2: List<Int> = ranges[1].split("-").map{ it.toInt() }
if (range1.overlaps(range2)) {
count += 1
}
}
return count;
}
println("part 1: " + part1("input_day04.txt"))
println("part 2: " + part2("input_day04.txt"))
}
| 0 | Kotlin | 0 | 0 | a4b744a3e3c940c382aaa1d5f5c93ae0df124179 | 1,365 | advent-of-code-2022 | Apache License 2.0 |
Factorization.kt | kokic | 563,806,758 | false | {"Kotlin": 3604} |
import java.math.BigInteger
fun main(args: Array<String>) {
val m = (1003917294).toBigInteger()
println(Factorization.factor(m))
}
fun Integer.isPrime(): Boolean {
if (this < BigInteger.TWO) return false
var i = BigInteger.TWO
while (i.multiply(i) <= this)
if (mod(i++) == BigInteger.ZERO) return false
return true
}
object Factorization {
fun factor(x: Integer) = factorList(x).groupingBy { u -> u }.eachCount()
fun factorList(x: Integer): List<Integer> {
val list = mutableListOf<Integer>()
var phase = x
while (phase != BigInteger.ONE) {
val rho = pollardRho(phase)
list.add(rho)
phase /= rho
}
val hybrid = list.filter { u -> !u.isPrime() }
hybrid.forEach { u -> list.remove(u) and list.addAll(factorList(u)) }
return list
}
private val pollardRange = 0..Short.MAX_VALUE
fun pollardRho(x: Integer): Integer {
var s = BigInteger.ONE
var t = BigInteger.ZERO
val c = pollardRange.random().toBigInteger()
.mod(x - BigInteger.ONE) + BigInteger.ONE
var step = 0
var goal = 1
var phas = BigInteger.ONE
goal = 1
while (true) {
step = 1
while (step <= goal) {
t = (t * t + c).mod(x)
phas = (phas * t.subtract(s).abs()).mod(x)
if (step % 127 == 0) {
val d = x.gcd(phas)
if (d > BigInteger.ONE) return d
}
++step
}
val d = x.gcd(phas)
if (d > BigInteger.ONE) return d
goal = goal shl 1
s = t
phas = BigInteger.ONE
}
}
}
| 0 | Kotlin | 0 | 0 | 6b69f097a86eb488baf70537c52862f6391d30a4 | 1,832 | potos-flavus | MIT License |
src/main/kotlin/com/scavi/brainsqueeze/adventofcode/Day18OperationOrder.kt | Scavi | 68,294,098 | false | {"Java": 1449516, "Kotlin": 59149} | package com.scavi.brainsqueeze.adventofcode
class Day18OperationOrder {
private val formulaPattern = """(\d+\s+)([*+])(\s+\d+)""".toRegex()
private val parenthesesPattern = """\(\d+\s+[*+]\s+[\d+|\d+\s+\[*\]\s+\d+]+\)""".toRegex()
private val arithmeticPatternA = """^(\d+\s+[*+]\s+\d+)""".toRegex()
private val arithmeticPatternB = """\d+\s+\+\s+\d+""".toRegex()
private val operatorsA = """[*+]""".toRegex()
fun solve(input: List<String>, evalFunction: (String) -> String): Long {
var result = 0L
for (line in input) {
result += evaluateInput(line, evalFunction).toLong()
}
return result
}
private fun evaluateInput(line: String, evalFunction: (String) -> String): String {
val equation = StringBuilder(line)
while (equation.contains("(")) {
val inParentheses = parenthesesPattern.findAll(equation)
for (parenthesesLookup in inParentheses.iterator()) {
for (group in parenthesesLookup.groups) {
val evaluated = evalFunction(group!!.value.substring(1, group.value.length - 1))
equation.replace(group.range.first, group.range.last + 1, evaluated)
}
}
}
return evalFunction(equation.toString())
}
fun evalA(input: String): String {
var toEvaluate = input
while (operatorsA.containsMatchIn(toEvaluate)) {
val matches = arithmeticPatternA.findAll(toEvaluate)
val match = matches.map { it.groupValues[0] }.joinToString()
toEvaluate = "${calculate(match)} ${toEvaluate.substring(match.length)}".trim()
}
return toEvaluate
}
fun evalB(input: String): String {
var toEvaluate = input
while (toEvaluate.contains("+")) {
val matches = arithmeticPatternB.findAll(toEvaluate)
for (match in matches) {
for (group in match.groups) {
val value = group!!.value.trim()
toEvaluate = toEvaluate.replace(value, calculate(value).toString())
}
}
}
return evalA(toEvaluate)
}
private fun calculate(match: String) : Long {
val (a, o, b) = formulaPattern.find(match)!!.destructured
return if (o == "*") a.trim().toLong() * b.trim().toLong() else a.trim().toLong() + b.trim().toLong()
}
}
| 0 | Java | 0 | 1 | 79550cb8ce504295f762e9439e806b1acfa057c9 | 2,441 | BrainSqueeze | Apache License 2.0 |
src/Day25.kt | adrianforsius | 573,044,406 | false | {"Kotlin": 68131} | import org.assertj.core.api.Assertions.assertThat
fun main() {
fun part1(input: List<String>): Int {
val lines = input
var splitAt = lines
.withIndex()
.filter { it.value == "" }
.map { it.index }
splitAt = listOf(0) + splitAt
splitAt = splitAt + listOf(lines.size)
val split = splitAt
.windowed(2)
.map {
lines.subList(
it[0] + 1,
it[1],
)
}
val max = split.map {
it.map {
it.toInt()
}.sum()
}.max()
return max
}
fun part2(input: List<String>): Int {
val lines = input
var splitAt = lines
.withIndex()
.filter { it.value == "" }
.map { it.index }
splitAt = listOf(0) + splitAt
splitAt = splitAt + listOf(lines.size)
val split = splitAt
.windowed(2)
.map {
lines.subList(
it[0],
it[1],
)
}
val sorted = split.map {
it.map{
it.toIntOrNull() ?: 0
}.sum()
}.sortedDescending()
return sorted.slice(0..2).sum()
}
// test if implementation meets criteria from the description, like:
// Test
val testInput = readInput("Day01_test")
val output1 = part1(testInput)
assertThat(output1).isEqualTo(24000)
// Answer
val input = readInput("Day01")
val outputAnswer1 = part1(input)
assertThat(outputAnswer1).isEqualTo(67450)
// Test
val output2 = part2(testInput)
assertThat(output2).isEqualTo(45000)
// Answer
val outputAnswer2 = part2(input)
assertThat(outputAnswer2).isEqualTo(199357)
}
| 0 | Kotlin | 0 | 0 | f65a0e4371cf77c2558d37bf2ac42e44eeb4bdbb | 1,860 | kotlin-2022 | Apache License 2.0 |
src/Day02.kt | shepard8 | 573,449,602 | false | {"Kotlin": 73637} | fun main() {
fun part1(games: List<Pair<Int, Int>>) =
games.sumOf { (opponent, me) ->
val shapeScore = me + 1
val gameScore = if (me - opponent == 1 || me - opponent == -2) 6 else if (me == opponent) 3 else 0
shapeScore + gameScore
}
fun part2(games: List<Pair<Int, Int>>) =
games.sumOf { (opponent, outcome) ->
val me = (opponent + 2 + outcome) % 3
val shapeScore = me + 1
val gameScore = 3 * outcome
shapeScore + gameScore
}
val input = readInput("Day02")
val games = sequence {
input.forEach { line ->
val opponent = line[0] - 'A'
val me = line[2] - 'X'
yield(Pair(opponent, me))
}
}.toList()
println(part1(games))
println(part2(games))
}
| 0 | Kotlin | 0 | 1 | 81382d722718efcffdda9b76df1a4ea4e1491b3c | 841 | aoc2022-kotlin | Apache License 2.0 |
src/main/kotlin/de/mbdevelopment/adventofcode/year2021/solvers/day11/Day11Puzzle.kt | Any1s | 433,954,562 | false | {"Kotlin": 96683} | package de.mbdevelopment.adventofcode.year2021.solvers.day11
import de.mbdevelopment.adventofcode.year2021.solvers.PuzzleSolver
abstract class Day11Puzzle : PuzzleSolver {
final override fun solve(inputLines: Sequence<String>) = simulate(
inputLines.map { row -> row.map { it.digitToInt() } }
.map { it.toMutableList() }
.toList())
.toString()
abstract fun simulate(octopusGrid: List<MutableList<Int>>): Int
protected fun step(octopusGrid: List<MutableList<Int>>): Int {
octopusGrid.chargeOne()
val flashed = octopusGrid.flashCascading()
octopusGrid.reset(flashed)
return flashed.size
}
private fun List<MutableList<Int>>.chargeOne() {
forEachIndexed { y, row ->
row.forEachIndexed { x, energyLevel ->
this[y][x] = energyLevel + 1
}
}
}
private fun List<MutableList<Int>>.flashCascading(): Set<Point> {
val flashed = mutableSetOf<Point>()
var candidates = flashCandidates()
while (!flashed.containsAll(candidates)) {
(candidates - flashed).forEach { flash(it) }
flashed += candidates
candidates = flashCandidates()
}
return flashed
}
private fun List<MutableList<Int>>.flashCandidates() =
flatMapIndexed { y, row ->
row.mapIndexedNotNull { x, energyLevel ->
if (energyLevel > 9) Point(x, y) else null
}
}.toSet()
private fun List<MutableList<Int>>.flash(octopus: Point) {
((octopus.x - 1)..(octopus.x + 1)).forEach { x ->
((octopus.y - 1)..(octopus.y + 1)).forEach { y ->
if (x >= 0 && y >= 0 && y < size && x < first().size) {
this[y][x] = this[y][x] + 1
}
}
}
}
private fun List<MutableList<Int>>.reset(flashed: Set<Point>) {
forEachIndexed { y, row ->
row.forEachIndexed { x, _ ->
if (Point(x, y) in flashed) this[y][x] = 0
}
}
}
}
data class Point(val x: Int, val y: Int)
| 0 | Kotlin | 0 | 0 | 21d3a0e69d39a643ca1fe22771099144e580f30e | 2,150 | AdventOfCode2021 | Apache License 2.0 |
2022/src/test/kotlin/Day07.kt | jp7677 | 318,523,414 | false | {"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338} | import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
class Day07 : StringSpec({
"puzzle part 01" {
val sumOfAtMost10K = getDirectorySizes()
.filterValues { it <= 100000 }
.values.sum()
sumOfAtMost10K shouldBe 1778099
}
"puzzle part 02" {
val sizes = getDirectorySizes()
val needed = 30000000 - 70000000L + sizes.getValue("/")
val sizeOfCandidate = sizes
.filterValues { it >= needed }
.values.min()
sizeOfCandidate shouldBe 1623571
}
})
private fun getDirectorySizes(): Map<String, Long> {
val currentPath = ArrayDeque<String>(1)
val sizes = getPuzzleInput("day07-input.txt")
.mapNotNull {
when {
it.startsWith("$ ls") -> null
it.startsWith("$ cd ..") -> null.also { currentPath.removeLast() }
it.startsWith("$ cd") -> null.also { _ -> currentPath.addLast(it.dirName()) }
it.startsWith("dir") -> currentPath.toArray().plus(it.dirName()).toPath() to 0L
else -> currentPath.toArray().toPath() to it.fileSize()
}
}
.groupingBy { (path, _) -> path }
.fold(0L) { acc, (_, size) -> acc + size }
return sizes.mapValues { (path, size) ->
sizes
.filterKeys { it != path && it.startsWith(path) }
.values.sum() + size
}
}
private fun String.dirName() = drop(4).trim()
private fun String.fileSize() = split(" ").first().toLong()
private fun Array<Any?>.toPath() = joinToString("/").replace("//", "/")
| 0 | Kotlin | 1 | 2 | 8bc5e92ce961440e011688319e07ca9a4a86d9c9 | 1,619 | adventofcode | MIT License |
src/main/kotlin/dev/bogwalk/batch2/Problem27.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch2
import dev.bogwalk.util.maths.isPrime
import dev.bogwalk.util.maths.primeNumbers
/**
* Problem 27: Quadratic Primes
*
* https://projecteuler.net/problem=27
*
* Goal: Find coefficients a & b for the quadratic expression that produces the maximum number of
* primes for consecutive values of n in [0, N].
*
* Constraints: 42 <= N <= 2000
*
* Quadratic Formula: n^2 + an + b, where |a| < N & |b| <= N.
*
* Euler's Quadratic formula -> n^2 + n + 41, produces 40 primes for the consecutive values
* of [0, 39].
* The formula -> n^2 - 79n + 1601, produces 80 primes for the consecutive values of [0, 79].
*
* e.g.: N = 42
* formula -> n^2 - n + 41, produces 42 primes
* result = -1 41
*/
class QuadraticPrimes {
/**
* A brute force of all a, b combinations that is optimised based on the following:
*
* - When n = 0, formula -> 0^2 + 0 + b = b, which means that b must be a prime number itself.
*
* - When n = 1, formula -> 1^2 + a + b, so, with b being prime:
*
* - if b = 2, then a must be even for result to be an odd prime.
* - if b > 2, then a must be odd for result to be an odd prime.
*
* @return triple of (a, b, count_of_primes)
*/
fun quadPrimeCoeff(maxN: Int): Triple<Int, Int, Int> {
var bestQuadratic = Triple(0, 0, 0)
val primes = primeNumbers(maxN)
val lowestA = if (maxN % 2 == 0) -maxN - 1 else -maxN - 2
// a will only be even if b == 2, so loop through odd values only & adjust later
for (a in lowestA until maxN step 2) {
for (b in primes) {
var n = 0
val adjustedA = if (b != 2) a else a - 1
while ((n * n + adjustedA * n + b).isPrime()) {
n++
}
if (n > bestQuadratic.third) {
bestQuadratic = Triple(a, b, n + 1)
}
}
}
return bestQuadratic
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 2,015 | project-euler-kotlin | MIT License |
Collections/FlatMap/src/Task.kt | diskostu | 554,658,487 | false | {"Kotlin": 36179} | // Return all products the given customer has ordered
fun Customer.getOrderedProducts(): List<Product> =
orders.flatMap { it.products }
// Return all products that were ordered by at least one customer
fun Shop.getOrderedProducts(): Set<Product> =
customers.flatMap { it.orders }.flatMap { it.products }.toSet()
fun main() {
// demo code to find the solutions
val shop = createSampleShop()
val customer1 = shop.customers[0]
val orderedProducts = customer1.getOrderedProducts()
println("orderedProducts = $orderedProducts")
val flatMap = shop.customers.flatMap { it.orders }
println("flatMap = $flatMap")
val flatMap1 = flatMap.flatMap { it.products }.sortedBy { it.name }.toSet()
println("flatMap1 = $flatMap1")
// thast's it
val toSet = shop.customers.flatMap { it.orders }.flatMap { it.products }.toSet()
println("toSet = $toSet")
}
fun createSampleShop(): Shop {
// create some sample entities
val product1 = Product("product 1", 1.0)
val product2 = Product("product 2", 2.0)
val product3 = Product("product 3", 3.0)
val product4 = Product("product 4", 4.0)
val product5 = Product("product 4", 5.0)
val order1 = Order(listOf(product1), false)
val order2 = Order(listOf(product2, product3), false)
val order3 = Order(listOf(product1, product3, product4), false)
val customer1 = Customer(
name = "custumer1",
city = City("Berlin"),
orders = listOf(order1, order3)
)
val customer2 = Customer(
name = "custumer2",
city = City("Hamburg"),
orders = listOf(order2)
)
return Shop("myShop", listOf(customer1, customer2))
}
| 0 | Kotlin | 0 | 0 | 3cad6559e1add8d202e15501165e2aca0ee82168 | 1,689 | Kotlin_Koans | MIT License |
2017/src/main/kotlin/Day21.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | import utils.splitNewlines
import utils.splitWhitespace
import kotlin.math.sqrt
object Day21 {
/*
* Note to self: I setup pattern matching as a single row, where each cell is represented thus:
*
* 2x2
* 01
* 23
*
* 3x3
* 012
* 345
* 678
*/
private val START = listOf(
false, true, false,
false, false, true,
true, true, true
)
fun solve(inputRules: String, iterations: Int): Int {
val rules = parseRules(inputRules)
var state = START
(0 until iterations).forEach {
val size = sqrt(state.size.toFloat()).toInt()
val stepSize = if (size % 2 == 0) 2 else 3
val newStepSize = stepSize + 1
val newSize = newStepSize * (size / stepSize)
val newState = BooleanArray(newSize * newSize).toMutableList()
for (stepX in 0 until size / stepSize) {
for (stepY in 0 until size / stepSize) {
val input = slice(state, stepX * stepSize, stepY * stepSize, size, stepSize)
val output = rules[input]!!
insert(newState, stepX * newStepSize, stepY * newStepSize, newSize, newStepSize, output)
}
}
state = newState
}
return state.count { it }
}
private fun slice(state: List<Boolean>, x: Int, y: Int, size: Int, sliceSize: Int): List<Boolean> {
val result = mutableListOf<Boolean>()
for (currY in y until y + sliceSize) {
for (currX in x until x + sliceSize) {
result.add(state[currY * size + currX])
}
}
return result
}
private fun insert(state: MutableList<Boolean>, x: Int, y: Int, size: Int, insertSize: Int, insert: List<Boolean>) {
var index = 0
for (currY in y until y + insertSize) {
for (currX in x until x + insertSize) {
state[currY * size + currX] = insert[index++]
}
}
}
private fun parseRules(inputRules: String): Map<List<Boolean>, List<Boolean>> {
val rules = mutableMapOf<List<Boolean>, List<Boolean>>()
for (rule in inputRules.splitNewlines()) {
val split = rule.replace("/", "").splitWhitespace()
var input = split[0].map { it == '#' }
val output = split[2].map { it == '#' }
if (input.size == 4) {
require(output.size == 9)
(0..3).forEach {
rules[input] = output
rules[input.flip2()] = output
input = input.rotate2()
}
} else {
require(output.size == 16)
(0..3).forEach {
rules[input] = output
rules[input.flip3()] = output
input = input.rotate3()
}
}
}
return rules
}
private fun List<Boolean>.rotate2(): List<Boolean> {
require(this.size == 4)
return listOf(
this[2], this[0],
this[3], this[1]
)
}
private fun List<Boolean>.flip2(): List<Boolean> {
require(this.size == 4)
return listOf(
this[1], this[0],
this[3], this[2]
)
}
private fun List<Boolean>.rotate3(): List<Boolean> {
require(this.size == 9)
return listOf(
this[6], this[3], this[0],
this[7], this[4], this[1],
this[8], this[5], this[2]
)
}
private fun List<Boolean>.flip3(): List<Boolean> {
require(this.size == 9)
return listOf(
this[2], this[1], this[0],
this[5], this[4], this[3],
this[8], this[7], this[6]
)
}
} | 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 3,356 | advent-of-code | MIT License |
leetcode/src/offer/Q001.kt | zhangweizhe | 387,808,774 | false | null | package offer
fun main() {
// 剑指 Offer II 001. 整数除法
// https://leetcode-cn.com/problems/xoh6Oh/
println(divide(Int.MAX_VALUE, Int.MIN_VALUE))
println(divide1(Int.MAX_VALUE, Int.MIN_VALUE))
}
private fun divide(a: Int, b: Int): Int {
if (a == Int.MIN_VALUE && b == -1) {
// MIN_VALUE = -2147483648
// MAX_VALUE = 2147483647
// MIN_VALUE / (-1) = 2147483648 > 2147483647 越界
return Int.MAX_VALUE
}
val sign = if ((a < 0 && b > 0) || (a > 0 && b < 0)) {
-1
}else {
1
}
// MIN_VALUE 转成正数会越界,MAX_VALUE 转成负数不会越界,
// 而只要 a b 同为正数或负数,则结果是一样,所以将两个数同时转为负数
var tmpA = if (a > 0) {
-a
}else {
a
}
val tmpB = if (b > 0) {
-b
}else {
b
}
var count = 0
while (tmpA <= tmpB) {
var value = tmpB
var k = 1
/**
* 0xc0000000 是二进制 -2^30 次方的十六进制表示
* tmpB >= 0xc0000000 这个判断是为了保证 tmpB + tmpB 不会越界,即 tmpB + tmpB 不小于 Int.MIN_VALUE
*/
while (tmpB >= 0xc0000000 && tmpA < tmpB + tmpB) {
value.shl(2)
k.shl(2)
}
tmpA -= (value)
count += k
}
return sign * count
}
private fun divide1(a: Int, b: Int): Int {
if (a == Int.MIN_VALUE && b == -1) {
// MIN_VALUE = -2147483648
// MAX_VALUE = 2147483647
// MIN_VALUE / (-1) = 2147483648 > 2147483647 越界
return Int.MAX_VALUE
}
val sign = if ((a < 0 && b > 0) || (a > 0 && b < 0)) {
-1
}else {
1
}
var tmpA = Math.abs(a)
var tmpB = Math.abs(b)
var count = 0
for (i in 31 downTo 0) {
/**
* tmpA >= (tmpB << i),(tmpB << 1) 存在越界的可能;
* 所以改成 (tmpA >> i) >= tmpB,再怎么右移,都不会越界;
* 如果 a == Int.MIN_VALUE(-2147483648),则 tmpA = Math.abs(-2147483648) == -2147483648,
* 所以要采用无符号位移,把 -2147483648 看成 2147483648;
* 所以改为 (tmpA >>> i) >= tmpB;
* 如果 tmpB == Int.MIN_VALUE,则 (tmpA >>> i) >= tmpB 永远为 true;
* 所以改成 (tmpA >>> i) - tmpB >= 0,这个表达式可能为 false
*/
if (tmpA.ushr(i) - tmpB >= 0) {// tmpA >= (tmpB <<< i)
tmpA -= tmpB.shl(i)
count += (1 .shl(i))
}
}
return if (sign == -1) {
-count
}else {
count
}
} | 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 2,636 | kotlin-study | MIT License |
2021/src/main/kotlin/de/skyrising/aoc2021/day5/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2021.day5
import de.skyrising.aoc.*
fun coord(s: String): Pair<Int, Int> {
val (x, y) = s.split(',')
return x.toInt() to y.toInt()
}
val test = TestInput("""
0,9 -> 5,9
8,0 -> 0,8
9,4 -> 3,4
2,2 -> 2,1
7,0 -> 7,4
6,4 -> 2,0
0,9 -> 2,9
3,4 -> 1,4
0,0 -> 8,8
5,5 -> 8,2
""")
@PuzzleName("Hydrothermal Venture")
fun PuzzleInput.part1(): Any {
val width = 1000
val height = 1000
val vents = ShortArray(width * height)
for (line in lines) {
val parts = line.split(' ')
val from = coord(parts[0])
val to = coord(parts[2])
if (from.first == to.first) {
for (y in minOf(from.second, to.second) .. maxOf(from.second, to.second)) {
vents[y * width + from.first]++
}
} else if (from.second == to.second) {
for (x in minOf(from.first, to.first) .. maxOf(from.first, to.first)) {
vents[from.second * width + x]++
}
}
}
return vents.count { n -> n > 1 }
}
fun PuzzleInput.part2(): Any {
val width = 1000
val height = 1000
val vents = ShortArray(width * height)
for (line in lines) {
val parts = line.split(' ')
val from = coord(parts[0])
val to = coord(parts[2])
val min = minOf(from.first, to.first) to minOf(from.second, to.second)
val max = maxOf(from.first, to.first) to maxOf(from.second, to.second)
if (min.first == max.first) {
for (y in min.second .. max.second) {
vents[y * width + min.first]++
}
} else if (min.second == max.second) {
for (x in min.first .. max.first) {
vents[min.second * width + x]++
}
} else if (min.second - min.first == max.second - max.first) {
val dirX = if (to.first >= from.first) 1 else -1
val dirY = if (to.second >= from.second) 1 else -1
for (i in 0 .. (max.first - min.first)) {
val x = from.first + i * dirX
val y = from.second + i * dirY
vents[y * width + x]++
}
}
}
return vents.count { n -> n > 1 }
}
| 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 2,233 | aoc | MIT License |
src/leetcodeProblem/leetcode/editor/en/MinimumValueToGetPositiveStepByStepSum.kt | faniabdullah | 382,893,751 | false | null | //Given an array of integers nums, you start with an initial positive value
//startValue.
//
// In each iteration, you calculate the step by step sum of startValue plus
//elements in nums (from left to right).
//
// Return the minimum positive value of startValue such that the step by step
//sum is never less than 1.
//
//
// Example 1:
//
//
//Input: nums = [-3,2,-3,4,2]
//Output: 5
//Explanation: If you choose startValue = 4, in the third iteration your step
//by step sum is less than 1.
// step by step sum
// startValue = 4 | startValue = 5 | nums
// (4 -3 ) = 1 | (5 -3 ) = 2 | -3
// (1 +2 ) = 3 | (2 +2 ) = 4 | 2
// (3 -3 ) = 0 | (4 -3 ) = 1 | -3
// (0 +4 ) = 4 | (1 +4 ) = 5 | 4
// (4 +2 ) = 6 | (5 +2 ) = 7 | 2
//
//
// Example 2:
//
//
//Input: nums = [1,2]
//Output: 1
//Explanation: Minimum start value should be positive.
//
//
// Example 3:
//
//
//Input: nums = [1,-2,-3]
//Output: 5
//
//
//
// Constraints:
//
//
// 1 <= nums.length <= 100
// -100 <= nums[i] <= 100
// Related Topics Array Prefix Sum 👍 693 👎 181
package leetcodeProblem.leetcode.editor.en
class MinimumValueToGetPositiveStepByStepSum {
fun solution() {
}
//below code will be used for submission to leetcode (using plugin of course)
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun minStartValue(nums: IntArray): Int {
var countStartValue = if (nums[0] < 1) 1 else nums[0]
var startValue = countStartValue
var sumStep = 0
var i = 0
while (i < nums.size) {
sumStep = startValue + nums[i]
startValue = sumStep
i++
if (startValue < 1) {
countStartValue = startValue + 1
startValue = countStartValue
i = 0
}
}
return countStartValue
}
// O(n) prefix sum
fun minStarValueOn( nums: IntArray) : Int{
var minVal = 0
var total = 0
// Iterate over the array and get the minimum step-by-step total.
// Iterate over the array and get the minimum step-by-step total.
for (num in nums) {
total += num
minVal = Math.min(minVal, total)
}
// We have to let the minimum step-by-step total equals to 1,
// by increasing the startValue from 0 to -minVal + 1,
// which is just the minimum startValue we want.
// We have to let the minimum step-by-step total equals to 1,
// by increasing the startValue from 0 to -minVal + 1,
// which is just the minimum startValue we want.
return -minVal + 1
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
fun main() {}
| 0 | Kotlin | 0 | 6 | ecf14fe132824e944818fda1123f1c7796c30532 | 3,053 | dsa-kotlin | MIT License |
src/main/kotlin/se/saidaspen/aoc/aoc2018/Day13.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2018
import se.saidaspen.aoc.util.*
fun main() = Day13.run()
object Day13 : Day(2018, 13) {
private val map = toMap(input)
private var carts = mutableListOf<Cart>()
init {
map.entries.filter { it.value in mutableListOf('v', '^', '<', '>') }
.map { Cart(it.key, it.value) }.forEach { carts.add(it) }
carts.forEach { map[it.pos] = if (it.direction in mutableListOf('<', '>')) '-' else '|' }
}
class Cart(var pos : P<Int, Int>, var direction: Char) {
private var nextTurn = 0
fun move() {
pos = when(direction) {
'>' -> pos + P(1, 0)
'<' -> pos + P(-1, 0)
'^' -> pos + P(0, -1)
'v' -> pos + P(0, 1)
else -> throw java.lang.RuntimeException("Unsupported move $direction")
}
val currTile = map[pos]!!
if (direction == '^' && currTile == '/') direction = '>'
else if (direction == 'v' && currTile == '/') direction = '<'
else if (direction == '<' && currTile == '/') direction = 'v'
else if (direction == '>' && currTile == '/') direction = '^'
else if (direction == '>' && currTile == '\\') direction = 'v'
else if (direction == '^' && currTile == '\\') direction = '<'
else if (direction == 'v' && currTile == '\\') direction = '>'
else if (direction == '<' && currTile == '\\') direction = '^'
else if (currTile == '+') {
if (direction == '^') {
if (nextTurn == 0) direction = '<'
else if (nextTurn == 2) direction = '>'
} else if (direction == 'v') {
if (nextTurn == 0) direction = '>'
else if (nextTurn == 2) direction = '<'
} else if (direction == '<') {
if (nextTurn == 0) direction = 'v'
else if (nextTurn == 2) direction = '^'
} else if (direction == '>') {
if (nextTurn == 0) direction = '^'
else if (nextTurn == 2) direction = 'v'
}
nextTurn = (nextTurn + 1) % 3
}
}
}
override fun part1(): Any {
while(true) {
carts = carts.sortedWith(compareBy<Cart> { it.pos.second }.thenBy {it.pos.first}).toMutableList()
for (cart in carts) {
cart.move()
val collision = carts.map { it.pos }.histo().entries.firstOrNull { it.value == 2 }
if (collision != null) { return "" + collision.key.first + "," + collision.key.second }
}
}
}
override fun part2(): Any {
val pendingDelete = mutableSetOf<Cart>()
while(true) {
carts = carts.sortedWith(compareBy<Cart> { it.pos.second }.thenBy {it.pos.first}).toMutableList()
for (cart in carts) {
if (pendingDelete.contains(cart)) continue
cart.move()
val collisionPositions = carts.map { it.pos }.histo().entries.firstOrNull { it.value == 2 }?.key
if (collisionPositions != null ) { pendingDelete.addAll(carts.filter { it.pos == collisionPositions}.toList()) }
}
carts.removeAll(pendingDelete)
pendingDelete.clear()
if (carts.size == 1) { return "" + carts[0].pos.first + "," + carts[0].pos.second }
}
}
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 3,523 | adventofkotlin | MIT License |
src/y2015/Day05.kt | gaetjen | 572,857,330 | false | {"Kotlin": 325874, "Mermaid": 571} | package y2015
import util.readInput
object Day05 {
fun part1(input: List<String>): Int {
val nice = input.filter {
hasVowels(it)
}.filter {
hasDouble(it)
}.filter {
!hasNaughty(it)
}
return nice.size
}
private fun hasVowels(string: String): Boolean {
return string.filter {
it in "aeiou"
}.length >= 3
}
private fun hasDouble(string: String): Boolean {
return string.windowed(2, 1).any { it.first() == it[1] }
}
private fun hasNaughty(string: String): Boolean {
return string.contains(Regex("ab|cd|pq|xy"))
}
fun part2(input: List<String>): Int {
val nice = input.filter {
hasDoublePair(it)
}.filter {
hasOneRepeating(it)
}
return nice.size
}
private fun hasDoublePair(string: String): Boolean {
for (i in 0..(string.length-4)) {
if (string.substring(i, i+2) in string.substring(i+2)) {
return true
}
}
return false
}
private fun hasOneRepeating(string: String): Boolean {
return string.windowed(3, 1).any { it.first() == it.last() }
}
}
fun main() {
val testInput = """
qjhvhtzxzqqjkmpb
xxyxx
uurcxstgmygtbstg
ieodomkazucvgmuy
""".trimIndent().split("\n")
println("------Tests------")
println(Day05.part1(testInput))
println(Day05.part2(testInput))
println("------Real------")
val input = readInput("resources/2015/day05")
println(Day05.part1(input))
println(Day05.part2(input))
}
| 0 | Kotlin | 0 | 0 | d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a | 1,664 | advent-of-code | Apache License 2.0 |
year2022/src/main/kotlin/net/olegg/aoc/year2022/day14/Day14.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2022.day14
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.Directions.D
import net.olegg.aoc.utils.Directions.DL
import net.olegg.aoc.utils.Directions.DR
import net.olegg.aoc.utils.Vector2D
import net.olegg.aoc.utils.get
import net.olegg.aoc.utils.parseInts
import net.olegg.aoc.utils.set
import net.olegg.aoc.year2022.DayOf2022
/**
* See [Year 2022, Day 14](https://adventofcode.com/2022/day/14)
*/
object Day14 : DayOf2022(14) {
private val STOP = setOf('#', null)
override fun first(): Any? {
val map = fill(false)
return map.sumOf { row ->
row.count {
it == 'o'
}
}
}
override fun second(): Any? {
val map = fill(true)
return map.sumOf { row ->
row.count {
it == 'o'
}
}
}
private fun fill(addFloor: Boolean): List<List<Char>> {
val start = Vector2D(500, 0)
val rocks = lines
.flatMap { line ->
line.split(" -> ")
.map { it.parseInts(",") }
.map { Vector2D(it.first(), it.last()) }
.zipWithNext()
.flatMap { (from, to) ->
val vector = (to - from).dir()
generateSequence(from) { it + vector }
.takeWhile { it != to } + to
}
}
.toSet()
val minX = minOf(start.x - 1, rocks.minOf { it.x - 1 })
val maxX = maxOf(start.x + 1, rocks.maxOf { it.x + 1 })
val minY = minOf(start.y, rocks.minOf { it.y })
val maxY = maxOf(start.y, rocks.maxOf { it.y })
val addY = if (addFloor) 3 else 0
val extendX = if (addFloor) maxY + addY - minY + 1 else 0
val bbox = Pair(
Vector2D(minX - extendX, minY),
Vector2D(maxX + extendX, maxY + addY),
)
val map = List(bbox.second.y - bbox.first.y + 1) {
MutableList(bbox.second.x - bbox.first.x + 1) { '.' }
}
map[start - bbox.first] = '+'
rocks.forEach { rock ->
map[rock - bbox.first] = '#'
}
if (addFloor) {
map[map.lastIndex - 1].fill('#')
}
fill(map, start - bbox.first)
return map
}
private fun fill(
map: List<MutableList<Char>>,
coord: Vector2D
): Boolean {
val reachBottom = when {
map[coord] in STOP -> false
coord.y == map.lastIndex -> true
map[coord] == '~' -> true
map[coord] == 'o' -> false
else -> {
map[coord] = 'o'
fill(map, coord + D.step) || fill(map, coord + DL.step) || fill(map, coord + DR.step)
}
}
if (reachBottom) {
map[coord] = '~'
}
return reachBottom
}
}
fun main() = SomeDay.mainify(Day14)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 2,596 | adventofcode | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem934/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem934
/**
* LeetCode page: [934. Shortest Bridge](https://leetcode.com/problems/shortest-bridge/);
*/
class Solution {
/* Complexity:
* Time O(N) and Space O(N) where N is the number of cells in grid;
*/
fun shortestBridge(grid: Array<IntArray>): Int {
val visited = Array(grid.size) { BooleanArray(grid[it].size) }
val currentLayer = waterSurroundingIsland(firstLand(grid), grid, visited)
/* Search for the second island layer by layer, and return the distance
* when it is found.
*/
var result = 1
while (currentLayer.isNotEmpty()) {
repeat(currentLayer.size) {
val water = currentLayer.removeFirst()
for (cell in water.adjacentCells(grid)) {
if (cell.isVisited(visited)) {
continue
}
cell.setVisited(visited)
when {
cell.isLand(grid) -> return result
cell.isWater(grid) -> currentLayer.addLast(cell)
else -> throw NoWhenBranchMatchedException()
}
}
}
result++
}
throw IllegalStateException("Can not reach the second island.")
}
/**
* Return the water that surrounds the island containing [seedLand].
* The passed in [visited] should be all false, otherwise the behavior of this function may
* be incorrect.
*
* SIDE EFFECT:
* This function will set all lands of the island containing [seedLand] and its surrounding
* water visited.
*/
private fun waterSurroundingIsland(
seedLand: Cell,
grid: Array<IntArray>,
visited: Array<BooleanArray>
): ArrayDeque<Cell> {
require(seedLand.isLand(grid))
val result = ArrayDeque<Cell>()
val lands = ArrayDeque<Cell>()
lands.add(seedLand)
seedLand.setVisited(visited)
while (lands.isNotEmpty()) {
val land = lands.removeFirst()
for (cell in land.adjacentCells(grid)) {
if (cell.isVisited(visited)) {
continue
}
cell.setVisited(visited)
when {
cell.isLand(grid) -> lands.addLast(cell)
cell.isWater(grid) -> result.addLast(cell)
else -> throw NoWhenBranchMatchedException()
}
}
}
return result
}
private fun firstLand(grid: Array<IntArray>): Cell {
for (row in grid.indices) {
for (column in grid[row].indices) {
if (isLand(grid[row][column])) {
return Cell(row, column)
}
}
}
throw IllegalStateException("Can not find any land.")
}
private data class Cell(val row: Int, val column: Int) {
fun adjacentCells(grid: Array<IntArray>): List<Cell> {
return listOf(
Cell(row - 1, column),
Cell(row + 1, column),
Cell(row, column + 1),
Cell(row, column - 1)
).filter { it.inGrid(grid) }
}
fun inGrid(grid: Array<IntArray>): Boolean {
return row in grid.indices && column in grid[row].indices
}
fun isVisited(visited: Array<BooleanArray>): Boolean {
return visited[row][column]
}
fun setVisited(visited: Array<BooleanArray>) {
visited[row][column] = true
}
fun value(grid: Array<IntArray>): Int {
return grid[row][column]
}
}
private fun Cell.isLand(grid: Array<IntArray>): Boolean = isLand(value(grid))
private fun Cell.isWater(grid: Array<IntArray>): Boolean = isWater(value(grid))
private fun isLand(value: Int): Boolean = value == 1
private fun isWater(value: Int): Boolean = value == 0
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 4,042 | hj-leetcode-kotlin | Apache License 2.0 |
src/Day02.kt | bendh | 573,833,833 | false | {"Kotlin": 11618} | fun main() {
val scoreMap = mapOf(
"A X" to 4,
"B Y" to 5,
"C Z" to 6,
"C X" to 7,
"A Y" to 8,
"B Z" to 9,
"A Z" to 3,
"B X" to 1,
"C Y" to 2)
fun part1(input: List<String>): Int {
return input.sumOf { scoreMap.getOrDefault(it, 0) }
}
val stragetyMap = mapOf(
"A X" to 3,
"B Y" to 5,
"C Z" to 7,
"C X" to 2,
"A Y" to 4,
"B Z" to 9,
"A Z" to 8,
"B X" to 1,
"C Y" to 6)
fun part2(input: List<String>): Int {
return input.sumOf { stragetyMap.getOrDefault(it, 0) }
}
// test if implementation meets criteria from the description, like:
val testInput = readLines("Day02_test")
check(part1(testInput) == 15)
val input = readLines("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e3ef574441b63a99a99a095086a0bf025b8fc475 | 893 | advent-of-code-2022-kotlin | Apache License 2.0 |
advent-of-code-2022/src/Day20.kt | osipxd | 572,825,805 | false | {"Kotlin": 141640, "Shell": 4083, "Scala": 693} | fun main() {
val testInput = readInput("Day20_test")
val input = readInput("Day20")
"Part 1" {
part1(testInput) shouldBe 3
measureAnswer { part1(input) }
}
"Part 2" {
part2(testInput) shouldBe 1623178306
measureAnswer { part2(input) }
}
}
private fun part1(input: List<Long>): Long = mix(input, times = 1)
private fun part2(input: List<Long>): Long = mix(input, times = 10, decryptionKey = 811589153)
private fun mix(rawInput: List<Long>, times: Int, decryptionKey: Long = 1): Long {
val original = rawInput.mapIndexed { i, value -> i to value * decryptionKey }
val mixed = original.toMutableList()
repeat(times) {
for (value in original) mixed.move(value)
}
val zeroIndex = mixed.indexOfFirst { it.second == 0L }
fun groveCoordinateValue(shift: Int) = mixed[(zeroIndex + shift) % mixed.size].second
return groveCoordinateValue(1000) + groveCoordinateValue(2000) + groveCoordinateValue(3000)
}
private fun MutableList<Pair<Int, Long>>.move(value: Pair<Int, Long>) {
val index = indexOf(value)
removeAt(index)
add((index + value.second).mod(size), value)
}
private fun readInput(name: String) = readLines(name).map { it.toLong() }
| 0 | Kotlin | 0 | 5 | 6a67946122abb759fddf33dae408db662213a072 | 1,243 | advent-of-code | Apache License 2.0 |
src/aoc2022/day20/aoC20.kt | Saxintosh | 576,065,000 | false | {"Kotlin": 30013} | package aoc2022.day20
import readLines
data class Node(val value: Long) {
var prev = this
var next = this
fun addAfter(n1: Node) {
this.next = n1.next
this.prev = n1
n1.next.prev = this
n1.next = this
}
fun remove() {
this.prev.next = this.next
this.next.prev = this.prev
}
fun next(times: Int): Node {
var n = this
repeat(times) { n = n.next }
return n
}
fun prev(times: Int): Node {
var n = this
repeat(times) { n = n.prev }
return n
}
}
class CircularList : Iterable<Node> {
lateinit var firstNode: Node
private val naturalOrder = mutableListOf<Node>()
fun addNewNode(value: Long) {
val n = Node(value)
if (naturalOrder.size == 0)
firstNode = n
else
n.addAfter(firstNode.prev)
naturalOrder.add(n)
}
fun findNode(value: Long) = asSequence().first { it.value == value }
private fun move(n: Node) {
val value = n.value
if (value == 0L)
return
val n1 = n.prev
n.remove()
val n2 = if (value > 0)
n1.next((value % (naturalOrder.size - 1)).toInt())
else
n1.prev(((-value) % (naturalOrder.size - 1)).toInt())
n.addAfter(n2)
}
fun move() {
naturalOrder.forEach { move(it) }
}
override fun iterator() = object : Iterator<Node> {
var isDone = false
var n = firstNode
override fun hasNext() = !isDone
override fun next(): Node {
n = n.next
if (n == firstNode)
isDone = true
return n.prev
}
}
override fun toString() = asSequence().joinToString { it.value.toString() }
}
fun main() {
fun part1(lines: List<String>): Long {
val l = lines.map { it.toLong() }
val ll = CircularList()
l.forEach { ll.addNewNode(it) }
ll.move()
val z = ll.findNode(0)
val z1 = z.next(1000)
val z2 = z1.next(1000)
val z3 = z2.next(1000)
return listOf(
z1.value,
z2.value,
z3.value,
).sum()
}
fun part2(lines: List<String>): Long {
val l = lines.map { it.toLong() * 811589153L }
val ll = CircularList()
l.forEach { ll.addNewNode(it) }
repeat(10) { ll.move() }
val z = ll.findNode(0)
val z1 = z.next(1000)
val z2 = z1.next(1000)
val z3 = z2.next(1000)
return listOf(
z1.value,
z2.value,
z3.value,
).sum()
}
readLines(3L, 1623178306L, ::part1, ::part2)
} | 0 | Kotlin | 0 | 0 | 877d58367018372502f03dcc97a26a6f831fc8d8 | 2,218 | aoc2022 | Apache License 2.0 |
src/main/kotlin/day2.kt | gautemo | 572,204,209 | false | {"Kotlin": 78294} | import shared.getText
fun main() {
val input = getText("day2.txt")
println(day2A(input))
println(day2B(input))
}
fun day2A(input: String): Int{
val rounds = input.lines().map {
val pair = it.split(" ")
val opponent = when(pair[0]) {
"A" -> Rock()
"B" -> Paper()
"C" -> Scissors()
else -> throw Exception()
}
val you = when(pair[1]) {
"X" -> Rock()
"Y" -> Paper()
"Z" -> Scissors()
else -> throw Exception()
}
Pair(you, opponent)
}
return rounds.sumOf { it.first.fight(it.second) + it.first.points }
}
fun day2B(input: String): Int{
val rounds = input.lines().map {
val pair = it.split(" ")
when(pair[0]) {
"A" -> {
when(pair[1]) {
"X" -> return@map Pair(Scissors(), Rock())
"Y" -> return@map Pair(Rock(), Rock())
"Z" -> return@map Pair(Paper(), Rock())
else -> throw Exception()
}
}
"B" -> {
when(pair[1]) {
"X" -> return@map Pair(Rock(), Paper())
"Y" -> return@map Pair(Paper(), Paper())
"Z" -> return@map Pair(Scissors(), Paper())
else -> throw Exception()
}
}
"C" -> {
when(pair[1]) {
"X" -> return@map Pair(Paper(), Scissors())
"Y" -> return@map Pair(Scissors(), Scissors())
"Z" -> return@map Pair(Rock(), Scissors())
else -> throw Exception()
}
}
else -> throw Exception()
}
}
return rounds.sumOf { it.first.fight(it.second) + it.first.points }
}
private sealed class Item {
abstract val points: Int
abstract fun fight(item: Item): Int
}
private class Rock : Item() {
override val points = 1
override fun fight(item: Item): Int {
return when(item) {
is Rock -> 3
is Paper -> 0
is Scissors -> 6
}
}
}
private class Paper : Item() {
override val points = 2
override fun fight(item: Item): Int {
return when(item) {
is Rock -> 6
is Paper -> 3
is Scissors -> 0
}
}
}
private class Scissors : Item() {
override val points = 3
override fun fight(item: Item): Int {
return when(item) {
is Rock -> 0
is Paper -> 6
is Scissors -> 3
}
}
} | 0 | Kotlin | 0 | 0 | bce9feec3923a1bac1843a6e34598c7b81679726 | 2,664 | AdventOfCode2022 | MIT License |
src/main/kotlin/dev/bogwalk/batch0/Problem5.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch0
import dev.bogwalk.util.maths.gcd
import dev.bogwalk.util.maths.lcm
import dev.bogwalk.util.maths.primeNumbers
import kotlin.math.abs
import kotlin.math.log2
import kotlin.math.pow
/**
* Problem 5: Smallest Multiple
*
* https://projecteuler.net/problem=5
*
* Goal: Find the smallest positive number that can be evenly divided by each number in the range
* [1, N].
*
* Constraints: 1 <= N <= 40
*
* e.g.: N = 3
* {1, 2, 3} evenly divides 6 to give quotient {6, 3, 2}
*/
class SmallestMultiple {
/**
* Repeatedly calculates the lcm of 2 values (via reduce()), starting from the largest and
* stepping backwards until the middle of the range, as the smaller half of a range will
* already be factors of the larger half.
*
* SPEED (BETTER) 4.6e+04ns for N = 40
*/
fun lcmOfRange(n: Int): Long {
val rangeMax = n.toLong()
return (rangeMax downTo (rangeMax / 2 + 1)).reduce { acc, num ->
abs(acc * num) / gcd(acc, num)
}
}
/**
* Solution mimics the one above but uses top-level helper that leverages BigInteger and its
* built-in methods instead of Long.
*
* SPEED (WORST) 1.2e+05ns for N = 40
*/
fun lcmOfRangeBI(n: Int): Long {
val rangeMax = n.toLong()
val range = (rangeMax downTo (rangeMax / 2 + 1)).toList().toLongArray()
return lcm(*range)
}
/**
* Uses prime numbers to calculate the lcm of a range, based on the formula:
*
* p_i^a_i <= n
*
* a_i * log(p_i) <= log(n)
*
* a_i = floor(log(n) / log(p_i))
*
* e.g. N = 6, primes < N = {2, 3, 5};
* the exponent of the 1st prime will be 2 as 2^2 < 6 but 2^3 > 6;
* the exponent of the 2nd prime will be 1 as 3^1 < 6 but 3^2 > 6;
* the exponent of the 3rd prime will be 1 as 5^1 < 6 but 5^2 > 6;
* therefore, lcm = 2^2 * 3^1 * 5^1 = 60.
*
* This is an adaptation of the prime factorisation method for calculating the LCM.
*
* SPEED (BEST) 1.9e+04ns for N = 40
*/
fun lcmOfRangeUsingPrimes(n: Int): Long {
var lcm = 1L
val primes = primeNumbers(n)
for (prime in primes) {
lcm *= if (prime * prime <= n) {
val exponent = (log2(n.toDouble()) / log2(prime.toDouble())).toInt()
(prime.toDouble().pow(exponent)).toLong()
} else {
prime.toLong()
}
}
return lcm
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 2,558 | project-euler-kotlin | MIT License |
src/Day25.kt | jstapels | 572,982,488 | false | {"Kotlin": 74335} | import java.math.BigInteger
fun main() {
fun parseNum(line: String): Long {
var num = 0L
var multiplier = 1L
for (ch in line.reversed()) {
num += when (ch) {
'2' -> 2L * multiplier
'1' -> 1L * multiplier
'0' -> 0L
'-' -> -1L * multiplier
'=' -> -2L * multiplier
else -> throw IllegalArgumentException("Unrecognized character: $ch")
}
multiplier *= 5
}
return num
}
fun snafu(num: Long): String {
if (num == 0L) return "0"
var rem = num
var snafu = StringBuilder()
while (rem > 0L) {
val ch = when (rem % 5) {
0L -> { rem /= 5; '0' }
1L -> { rem /= 5; '1' }
2L -> { rem /= 5; '2' }
3L -> { rem = rem / 5 + 1; '=' }
else -> { rem = rem / 5 + 1; '-' }
}
snafu.insert(0, ch)
}
return snafu.toString()
}
fun parseInput(input: List<String>) =
input.asSequence()
.onEach { print("$it -> ") }
.map { parseNum(it) }
.onEach { println(it) }
fun part1(input: List<String>): String {
val data = parseInput(input)
val total = data.sum()
println("TOTAL: $total")
return snafu(total)
}
fun part2(input: List<String>): Int {
val data = parseInput(input)
return 1
}
val day = 25
println("OUTPUT FOR DAY $day")
println("-".repeat(64))
val testInput = readInput("Day${day.pad(2)}_test")
checkTest("2=-1=0") { part1(testInput) }
checkTest(1) { part2(testInput) }
println("-".repeat(64))
val input = readInput("Day${day.pad(2)}")
solution { part1(input) }
solution { part2(input) }
println("-".repeat(64))
}
| 0 | Kotlin | 0 | 0 | 0d71521039231c996e2c4e2d410960d34270e876 | 1,910 | aoc22 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/StickersToSpellWord.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT
import kotlin.math.max
import kotlin.math.min
/**
* 691. Stickers to Spell Word
* @see <a href="https://leetcode.com/problems/stickers-to-spell-word/">Source</a>
*/
fun interface StickersToSpellWord {
operator fun invoke(stickers: Array<String>, target: String): Int
}
/**
* DP + Memoization with optimization
*/
class StickersToSpellWordDP : StickersToSpellWord {
override fun invoke(stickers: Array<String>, target: String): Int {
val m: Int = stickers.size
val mp = Array(m) { IntArray(ALPHABET_LETTERS_COUNT) }
val dp: MutableMap<String, Int> = HashMap()
for (i in 0 until m) for (c in stickers[i].toCharArray()) mp[i][c - 'a']++
dp[""] = 0
return helper(dp, mp, target)
}
private fun helper(dp: MutableMap<String, Int>, mp: Array<IntArray>, target: String): Int {
if (dp.containsKey(target)) return dp[target] ?: -1
var ans = Int.MAX_VALUE
val n = mp.size
val tar = IntArray(ALPHABET_LETTERS_COUNT)
for (c in target.toCharArray()) tar[c - 'a']++
// try every sticker
for (i in 0 until n) {
// optimization
if (mp[i][target[0] - 'a'] == 0) continue
val sb = StringBuilder()
// apply a sticker on every character a-z
for (j in 0 until ALPHABET_LETTERS_COUNT) {
if (tar[j] > 0) for (k in 0 until max(0, tar[j] - mp[i][j])) sb.append(('a'.code + j).toChar())
}
val s = sb.toString()
val tmp = helper(dp, mp, s)
if (tmp != -1) ans = min(ans, 1 + tmp)
}
dp[target] = if (ans == Int.MAX_VALUE) -1 else ans
return dp[target] ?: -1
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,407 | kotlab | Apache License 2.0 |
app/src/main/kotlin/aoc2022/day07/Day07.kt | dbubenheim | 574,231,602 | false | {"Kotlin": 18742} | package aoc2022.day07
import aoc2022.day07.Day07.ResourceType.DIRECTORY
import aoc2022.day07.Day07.ResourceType.FILE
import aoc2022.day07.Day07.part1
import aoc2022.day07.Day07.part2
import aoc2022.toFile
import java.util.UUID
object Day07 {
fun part1(): Long {
val root = Directory(id = newId(), name = "/")
initDirectoryStructure(root)
return lookup.values
.filter { it.type == DIRECTORY && it.size <= 100000 }
.sumOf { it.size }
}
fun part2(): Long {
val rootDirectory = Directory(id = newId(), name = "/")
initDirectoryStructure(rootDirectory)
val freeSpace = TOTAL_DISK_SPACE - rootDirectory.size
val neededSpace = UNUSED_SPACE_NEEDED - freeSpace
return lookup.values
.filter { it.size >= neededSpace }
.minByOrNull { it.size }
?.size ?: 0
}
private val lookup = mutableMapOf<String, Resource>()
private const val TOTAL_DISK_SPACE = 70000000
private const val UNUSED_SPACE_NEEDED = 30000000
private fun initDirectoryStructure(root: Directory) {
lookup[root.id] = root
var curDir = root
"input-day07.txt".toFile()
.readLines()
.drop(1)
.forEach { line ->
if (line.startsWith("$")) {
if (line.contains("cd")) {
val name = line.substringAfterLast(" ")
curDir = if (name == "..") {
val parentId = checkNotNull(curDir.parent) { "parent of $curDir must not be null!" }
lookup[parentId] as Directory
} else {
val directoryId = curDir.directories.single { lookup[it]?.name == name }
lookup[directoryId] as Directory
}
}
} else {
if (line.startsWith("dir ")) {
val directory = Directory(id = newId(), name = line.substringAfterLast(" "), parent = curDir.id)
lookup[directory.id] = directory
curDir.directories.add(directory.id)
} else {
val (size, name) = line.split(" ")
val file = File(id = newId(), name = name, size = size.toLong())
lookup[file.id] = file
curDir.files.add(file.id)
}
}
}
}
interface Resource {
val id: String
val name: String
val parent: String?
val type: ResourceType
val size: Long
}
class File(
override val id: String,
override val name: String,
override val parent: String? = null,
override val type: ResourceType = FILE,
override val size: Long
) : Resource
class Directory(
override val id: String,
override val name: String,
override val parent: String? = null,
override val type: ResourceType = DIRECTORY,
val directories: MutableList<String> = mutableListOf(),
val files: MutableList<String> = mutableListOf()
) : Resource {
override val size: Long
get() = files.sumOf { lookup[it]?.size ?: 0 } + directories.sumOf { lookup[it]?.size ?: 0 }
}
enum class ResourceType {
FILE,
DIRECTORY
}
private fun newId() = UUID.randomUUID().toString()
}
fun main() {
println(part1())
println(part2())
}
| 8 | Kotlin | 0 | 0 | ee381bb9820b493d5e210accbe6d24383ae5b4dc | 3,600 | advent-of-code-2022 | MIT License |
src/main/kotlin/days/aoc2021/Day20.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2021
import days.Day
class Day20 : Day(2021, 20) {
override fun partOne(): Any {
val (algorithm, image) = parseInput(inputList)
return countLightPixels(image.enhance(algorithm, 2))
}
override fun partTwo(): Any {
val (algorithm, image) = parseInput(inputList)
return countLightPixels(image.enhance(algorithm, 50))
}
fun parseInput(inputLines: List<String>): Pair<String,Image> {
val algorithm = inputLines.first()
val imageData = inputLines.drop(2)
val data = Array(imageData.first().length) {
Array(imageData.size) {'.'}
}
imageData.forEachIndexed { y, line ->
line.forEachIndexed { x, c -> data[y][x] = c }
}
return Pair(algorithm, Image(data))
}
fun countLightPixels(image: Image): Int {
return image.data.sumOf { row -> row.count { it == '#' } }
}
class Image(val data: Array<Array<Char>>) {
fun enhance(algorithm: String, times: Int): Image {
var current = data
repeat (times) { step ->
val newData = Array(current.size + 4) {
Array(current.first().size + 4) { if (algorithm[0] == '#' && (step % 2 == 1)) '#' else '.' }
}
for (y in newData.indices) {
for (x in newData.first().indices) {
var binaryString = ""
neighbors(y, x).forEach {
val row = current.getOrElse(it.first - 2) { arrayOf() }
val value = if (row.indices.contains(it.second - 2)) {
row[it.second - 2]
} else {
if (algorithm[0] == '#' && (step % 2 == 1)) '#' else '.'
}
binaryString += if (value == '#') '1' else '0'
}
newData[y][x] = algorithm[convertBinaryToInt(binaryString)]
}
}
current = newData
}
return Image(current)
}
private fun neighbors(targetY: Int, targetX: Int) = sequence {
for (y in targetY - 1..targetY + 1)
for (x in targetX - 1..targetX + 1)
yield(Pair(y,x))
}
private fun convertBinaryToInt(binary: String?): Int {
return binary?.reversed()?.foldIndexed(0) { index, total, digit ->
total + 1.shl(index) * (digit - '0')
} ?: throw IllegalArgumentException()
}
}
} | 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 2,668 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
src/nativeMain/kotlin/xyz/justinhorton/aoc2022/Day12.kt | justinhorton | 573,614,839 | false | {"Kotlin": 39759, "Shell": 611} | package xyz.justinhorton.aoc2022
import kotlin.math.min
/**
* https://adventofcode.com/2022/day/12
*/
class Day12(override val input: String) : Day() {
override fun part1(): String {
val grid = Grid.fromChars(input) { it }
val start = grid.enumeratePoints().first { grid[it] == 'S' }
val goal = grid.enumeratePoints().first { grid[it] == 'E' }
val parents = bfs(start, goal, grid)
val path = buildPath(start, goal, parents)
return numSteps(path).toString()
}
override fun part2(): String {
val grid = Grid.fromChars(input) { it }
val goal = grid.enumeratePoints().first { grid[it] == 'E' }
val possibleStarts = grid.enumeratePoints().filter { grid[it] == 'a' }
var minPathLen = part1().toInt() // starting from 'S'
for (ps in possibleStarts) {
val parents = bfs(ps, goal, grid)
val path = buildPath(ps, goal, parents)
if (path.isNotEmpty()) {
minPathLen = min(minPathLen, numSteps(path))
}
}
return minPathLen.toString()
}
private fun bfs(
start: GPoint,
goal: GPoint,
grid: Grid<Char>
): Map<GPoint, GPoint> {
val visited = mutableSetOf<GPoint>().apply { add(start) }
val q = mutableListOf<GPoint>().apply { add(start) }
val parents = mutableMapOf<GPoint, GPoint>()
while (q.isNotEmpty()) {
val next = q.removeFirst()
if (next == goal) {
return parents
}
val nextCh = if (next == start) 'a' else grid[next]
val isAllowedTransition: (GPoint) -> Boolean = { (if (it == goal) 'z' else grid[it]) - nextCh <= 1 }
for (a in grid.adjacentPoints(next).filter(isAllowedTransition).filterNot { it in visited }) {
visited += a
parents[a] = next
q += a
}
}
return emptyMap()
}
private fun buildPath(start: GPoint, goal: GPoint, parents: Map<GPoint, GPoint>): List<GPoint> {
var p: GPoint? = goal
val path = mutableListOf<GPoint>()
while (p != null) {
path += p
p = parents[p]
}
return if (path.last() != start) { // not a complete path
emptyList()
} else {
path.reversed()
}
}
private fun numSteps(path: List<GPoint>) = path.size - 1
}
| 0 | Kotlin | 0 | 1 | bf5dd4b7df78d7357291c7ed8b90d1721de89e59 | 2,476 | adventofcode2022 | MIT License |
day13/src/main/kotlin/Main.kt | rstockbridge | 159,586,951 | false | null | import java.io.File
fun main() {
val input = readInputFile()
println("Part I: the solution is ${runPartI(input)}.")
println("Part II: the solution is ${runPartII(input)}.")
}
fun readInputFile(): List<String> {
return File(ClassLoader.getSystemResource("input.txt").file).readLines()
}
fun runPartI(input: List<String>): Coordinate {
val track = Track(input)
return track.runPartI()
}
fun runPartII(input: List<String>): Coordinate {
val track = Track(input)
return track.runPartII()
}
class Track(input: List<String>) {
private val numberOfRows: Int = input.size
private val numberOfCols: Int = input
.map { row -> row.length }
.max()!!
private val paths: Array<CharArray>
private var carts: MutableList<Cart>
init {
paths = Array(numberOfCols) { CharArray(numberOfRows) }
carts = mutableListOf()
for (y in 0 until numberOfRows) {
val line = input[y]
for (x in 0 until numberOfCols) {
if (x >= line.length) {
paths[x][y] = ' '
} else {
val symbol = line[x]
when {
" |-/+\\".contains(symbol) -> paths[x][y] = line[x]
// fill in path character that is covered up by a cart
symbol == '>' || symbol == '<' -> {
paths[x][y] = '-'
if (symbol == '>') {
carts.add(Cart(Direction.RIGHT, Coordinate(x, y)))
} else if (symbol == '<') {
carts.add(Cart(Direction.LEFT, Coordinate(x, y)))
}
}
symbol == '^' || symbol == 'v' -> {
paths[x][y] = '|'
if (symbol == '^') {
carts.add(Cart(Direction.UP, Coordinate(x, y)))
} else if (symbol == 'v') {
carts.add(Cart(Direction.DOWN, Coordinate(x, y)))
}
}
}
}
}
}
}
fun runPartI(): Coordinate {
while (true) {
getSortedAliveCarts().forEach { cart ->
cart.advance(getNextPath(cart))
val crashLocation = getCrashLocation()
if (crashLocation != null) {
return crashLocation
}
}
}
}
fun runPartII(): Coordinate {
while (true) {
getSortedAliveCarts().forEach { cart ->
cart.advance(getNextPath(cart))
val crashLocation = getCrashLocation()
if (crashLocation != null) {
processCrash(crashLocation)
}
}
val aliveCarts = getSortedAliveCarts()
if (aliveCarts.size == 1) {
return aliveCarts[0].location
}
}
}
private fun getSortedAliveCarts(): List<Cart> {
return carts
.filter { it.isAlive }
.sortedWith(compareBy({ it.location.y }, { it.location.x }))
.toMutableList()
}
private fun getNextPath(cart: Cart): Char {
return when (cart.direction) {
Direction.RIGHT -> paths[cart.location.x + 1][cart.location.y]
Direction.LEFT -> paths[cart.location.x - 1][cart.location.y]
Direction.UP -> paths[cart.location.x][cart.location.y - 1]
Direction.DOWN -> paths[cart.location.x][cart.location.y + 1]
}
}
private fun processCrash(crashLocation: Coordinate) {
carts.filter { it.isAlive && it.location == crashLocation }.forEach { cart ->
cart.isAlive = false
}
}
private fun getCrashLocation(): Coordinate? {
val locationCounts = getAliveCartLocations()
.groupingBy { it }
.eachCount()
for ((location, count) in locationCounts) {
// only one location will appear more than once
if (count == 2) {
return location
}
}
return null
}
private fun getAliveCartLocations(): List<Coordinate> {
return getSortedAliveCarts().map { it -> it.location }
}
private fun print() {
println()
for (y in 0 until numberOfRows) {
for (x in 0 until numberOfCols) {
val location = Coordinate(x, y)
if (location in getAliveCartLocations()) {
for (cart in carts.filter { it.location == location }) {
if (cart.isAlive) {
print(cart.direction)
} else {
print(paths[x][y])
}
}
} else {
print(paths[x][y])
}
}
println()
}
println()
}
}
data class Cart(var direction: Direction, var location: Coordinate, var isAlive: Boolean = true) {
private var numberOfIntersections = 0
fun advance(nextPath: Char) {
location = when (direction) {
Direction.RIGHT -> Coordinate(location.x + 1, location.y)
Direction.LEFT -> Coordinate(location.x - 1, location.y)
Direction.UP -> Coordinate(location.x, location.y - 1)
Direction.DOWN -> Coordinate(location.x, location.y + 1)
}
// change direction if necessary
when (nextPath) {
'/' -> direction = when (direction) {
Direction.RIGHT, Direction.LEFT -> direction.turnLeft()
else -> direction.turnRight()
}
'\\' -> direction = when (direction) {
Direction.RIGHT, Direction.LEFT -> direction.turnRight()
Direction.UP, Direction.DOWN -> direction.turnLeft()
}
'+' -> {
when (IntersectionCommand.values()[numberOfIntersections % IntersectionCommand.values().size]) {
IntersectionCommand.TURN_LEFT -> direction = direction.turnLeft()
IntersectionCommand.STRAIGHT -> {
}
IntersectionCommand.TURN_RIGHT -> direction = direction.turnRight()
}
numberOfIntersections++
}
}
}
}
data class Coordinate(val x: Int, val y: Int) {
override fun toString(): String {
return "$x,$y"
}
}
| 0 | Kotlin | 0 | 0 | c404f1c47c9dee266b2330ecae98471e19056549 | 6,728 | AdventOfCode2018 | MIT License |
src/main/kotlin/ru/timakden/aoc/year2023/Day08.kt | timakden | 76,895,831 | false | {"Kotlin": 321649} | package ru.timakden.aoc.year2023
import ru.timakden.aoc.util.lcm
import ru.timakden.aoc.util.measure
import ru.timakden.aoc.util.readInput
/**
* [Day 8: <NAME>](https://adventofcode.com/2023/day/8).
*/
object Day08 {
@JvmStatic
fun main(args: Array<String>) {
measure {
val input = readInput("year2023/Day08")
println("Part One: ${part1(input)}")
println("Part Two: ${part2(input)}")
}
}
fun part1(input: List<String>): Int {
val instructions = instructionIterator(input.first())
var currentNode = "AAA"
var steps = 0
val nodes = input.drop(2).associate { s ->
val (name, leftRight) = s.split(" = ")
val (left, right) = "\\w+".toRegex().findAll(leftRight).map { it.value }.toList()
name to (left to right)
}
while (currentNode != "ZZZ") {
val direction = instructions.next()
val (left, right) = nodes[currentNode]!!
currentNode = if (direction == 'L') left else right
steps++
}
return steps
}
fun part2(input: List<String>): Long {
val instructions = instructionIterator(input.first())
val nodes = input.drop(2).associate { s ->
val (name, leftRight) = s.split(" = ")
val (left, right) = "\\w+".toRegex().findAll(leftRight).map { it.value }.toList()
name to (left to right)
}
return nodes.keys.filter { it.endsWith("A") }.map { node ->
var currentNode = node
var s = 0L
while (!currentNode.endsWith("Z")) {
val direction = instructions.next()
val (left, right) = nodes[currentNode]!!
currentNode = if (direction == 'L') left else right
s++
}
s
}.reduce(::lcm)
}
/**
* Returns an iterator that yields characters from the given input string infinitely.
*
* @param input the input string
* @return an iterator that yields characters from the input string
*/
private fun instructionIterator(input: String) = iterator {
while (true) {
yieldAll(input.toList())
}
}
}
| 0 | Kotlin | 0 | 3 | acc4dceb69350c04f6ae42fc50315745f728cce1 | 2,278 | advent-of-code | MIT License |
src/Day04.kt | ChenJiaJian96 | 576,533,624 | false | {"Kotlin": 11529} | fun main() {
fun List<String>.checkIfFullyOverlap(): Boolean {
val firstPair = get(0).split('-').run {
get(0).toInt() to get(1).toInt()
}
val secondPair = get(1).split('-').run {
get(0).toInt() to get(1).toInt()
}
return firstPair.first <= secondPair.first && firstPair.second >= secondPair.second ||
secondPair.first <= firstPair.first && secondPair.second >= firstPair.second
}
fun List<String>.checkIfFullyNotOverlap(): Boolean {
val firstPair = get(0).split('-').run {
get(0).toInt() to get(1).toInt()
}
val secondPair = get(1).split('-').run {
get(0).toInt() to get(1).toInt()
}
return firstPair.second < secondPair.first || firstPair.first > secondPair.second
}
// fully overlapping
fun part1(input: List<String>): Int =
input.filter {
it.split(',').checkIfFullyOverlap()
}.size
// partially overlapping
fun part2(input: List<String>): Int =
input.filterNot {
it.split(',').checkIfFullyNotOverlap()
}.size
val testInput = readInput("04", true)
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("04")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | b1a88f437aee756548ac5ba422e2adf2a43dce9f | 1,347 | Advent-Code-2022 | Apache License 2.0 |
src/main/kotlin/at/mpichler/aoc/solutions/year2021/Day14.kt | mpichler94 | 656,873,940 | false | {"Kotlin": 196457} | package at.mpichler.aoc.solutions.year2021
import at.mpichler.aoc.lib.Day
import at.mpichler.aoc.lib.PartSolution
open class Part14A : PartSolution() {
private lateinit var template: String
private lateinit var rules: Map<String, String>
open val numSteps = 10
override fun parseInput(text: String) {
val parts = text.split("\n\n")
template = parts[0]
rules = parts[1].split("\n").map { it.split(" -> ") }.associate { it[0] to it[1] }
}
override fun compute(): Long {
val counter = processPolymer()
val values = counter.values.sorted()
return values.last() - values.first()
}
override fun config() {
cache = mutableMapOf()
}
private fun processPolymer(): Map<Char, Long> {
val counter = template.toList().groupingBy { it }.eachCount().mapValues { it.value.toLong() }.toMutableMap()
for (i in 0..<template.length - 1) {
counter.update(replaceAndCount(template.substring(i..i + 1), 0))
}
return counter
}
private var cache: MutableMap<Pair<String, Int>, Map<Char, Long>> = mutableMapOf()
private fun replaceAndCount(pair: String, iteration: Int): Map<Char, Long> {
if (cache.containsKey(pair to iteration)) {
return cache[pair to iteration]!!
}
val v = doReplaceAndCount(pair, iteration)
cache[pair to iteration] = v
return v
}
private fun doReplaceAndCount(pair: String, iteration: Int): Map<Char, Long> {
if (iteration >= numSteps) {
return mapOf()
}
val insert = rules[pair]!!
val pair1 = pair[0] + insert
val pair2 = insert + pair[1]
val counter = insert.toList().associateWith { 1L }.toMutableMap()
counter.update(replaceAndCount(pair1, iteration + 1))
counter.update(replaceAndCount(pair2, iteration + 1))
return counter
}
private fun <K> MutableMap<K, Long>.update(other: Map<K, Long>) {
for (entry in other) {
val v = getOrDefault(entry.key, 0L)
set(entry.key, v + entry.value)
}
}
override fun getExampleAnswer(): Long {
return 1588
}
}
class Part14B : Part14A() {
override val numSteps = 40
override fun getExampleAnswer(): Long {
return 2_188_189_693_529
}
}
fun main() {
Day(2021, 14, Part14A(), Part14B())
} | 0 | Kotlin | 0 | 0 | 69a0748ed640cf80301d8d93f25fb23cc367819c | 2,421 | advent-of-code-kotlin | MIT License |
src/Day11.kt | illarionov | 572,508,428 | false | {"Kotlin": 108577} | import java.io.File
data class Monkey(
val number: Int,
val startingItems: List<Int>,
val opp: Op,
val test: Int,
val testTrueMonkey: Int,
val testFalseMonkey: Int
) {
fun runTest(level: Long): Int = if (level % test.toLong() == 0L) testTrueMonkey else testFalseMonkey
}
data class Op(
val first: Operand,
val second: Operand,
val op: OpType
) {
fun applyTo(old: Long): Long {
val firstI = first.getValue(old)
val secondI = second.getValue(old)
return when(op) {
OpType.ADD -> firstI + secondI
OpType.SUB -> firstI - secondI
OpType.MUL -> firstI * secondI
OpType.DIV -> firstI / secondI
}
}
}
enum class OpType { ADD, SUB, MUL, DIV }
sealed class Operand {
object Old: Operand() {
override fun getValue(old: Long) = old
}
data class Num(val i: Long): Operand() {
override fun getValue(old: Long): Long = i
}
abstract fun getValue(old: Long): Long
}
fun main() {
fun part1(input: List<Monkey>): Long {
val monkeyItems: Map<Int, ArrayDeque<Long>> = input.associate {
it.number to ArrayDeque(it.startingItems.map(Int::toLong))
}
val monkeys = input.associateBy(Monkey::number)
val inspectedTimes: MutableMap<Int, Long> = mutableMapOf(
*(input.map { it.number to 0L }.toTypedArray())
)
repeat(20) {
monkeyItems.forEach { (monkeyNo, items) ->
val monkey = monkeys[monkeyNo]!!
items.forEach { level ->
val inspected = monkey.opp.applyTo(level).toInt()
val afterBored = inspected / 3L
val newMonkey = monkey.runTest(afterBored)
monkeyItems[newMonkey]!!.addLast(afterBored)
}
inspectedTimes[monkeyNo] = inspectedTimes[monkeyNo]!! + items.size
items.clear()
}
}
return inspectedTimes.values
.sorted()
.takeLast(2)
.reduce(Long::times)
}
fun part2(input: List<Monkey>): Long {
val monkeyItems: Map<Int, ArrayDeque<Long>> = input.associate {
it.number to ArrayDeque(it.startingItems.map(Int::toLong))
}
val monkeys = input.associateBy { it.number }
val inspectedTimes: MutableMap<Int, Long> = mutableMapOf(
*(input.map { it.number to 0L }.toTypedArray())
)
val max = monkeys.values.map(Monkey::test).reduce(Int::times)
repeat(10000) {
monkeyItems.forEach { (monkeyNo, items) ->
val monkey = monkeys[monkeyNo]!!
items.forEach { level ->
val inspected = monkey.opp.applyTo(level) % max
val newMonkey = monkey.runTest(inspected)
monkeyItems[newMonkey]!!.addLast(inspected)
}
inspectedTimes[monkeyNo] = inspectedTimes[monkeyNo]!! + items.size
items.clear()
}
}
return inspectedTimes.values
.sorted()
.takeLast(2)
.reduce(Long::times)
}
// test if implementation meets criteria from the description, like:
val testInput: List<Monkey> = File("src", "Day11_test.txt")
.readText()
.parseMonkeys()
val part1CheckResult = part1(testInput)
println(part1CheckResult)
check(part1CheckResult == 10605L)
val input = File("src", "Day11.txt")
.readText()
.parseMonkeys()
val part1Result = part1(input)
println(part1Result)
//check(part1Result == 61005L)
check(part2(testInput) == 2713310158L)
val part2Result = part2(input)
//check(part2Result == 20567144694L)
println(part2Result)
}
fun String.parseMonkeys(): List<Monkey> {
return this.split("\n\n").map(String::parseMonkey)
}
fun String.parseMonkey(): Monkey {
val lines = this.split("\n")
val monkeyNo = Regex("""Monkey (\d+):""").matchEntire(lines[0])!!.groups[1]!!.value.toInt()
val items = lines[1].substringAfter("Starting items: ").split(", ")
.map(String::toInt)
val operationResult = Regex("""\s+Operation: new = (\S+) (.) (\S+)""").matchEntire(lines[2])
?.groupValues ?: error("Cannot parse `${lines[2]}`")
val operation = Op(
first = operationResult[1].parseOperand(),
second = operationResult[3].parseOperand(),
op = operationResult[2].parseOperation()
)
val testDivisibleBy = lines[3].substringAfter("Test: divisible by ").toInt()
val ifTrueMonkey = lines[4].substringAfter(" If true: throw to monkey ").toInt()
val ifFalseMonkey = lines[5].substringAfter("If false: throw to monkey ").toInt()
return Monkey(number = monkeyNo,
opp = operation,
startingItems = items,
test = testDivisibleBy,
testTrueMonkey = ifTrueMonkey,
testFalseMonkey = ifFalseMonkey
)
}
private fun String.parseOperand(): Operand {
return if (this == "old") Operand.Old else Operand.Num(this.toLong())
}
private fun String.parseOperation(): OpType {
return when (this) {
"-" -> OpType.SUB
"+" -> OpType.ADD
"*" -> OpType.MUL
"/" -> OpType.DIV
else -> error("Unknown operand `$this`")
}
} | 0 | Kotlin | 0 | 0 | 3c6bffd9ac60729f7e26c50f504fb4e08a395a97 | 5,368 | aoc22-kotlin | Apache License 2.0 |
src/com/mrxyx/algorithm/BFS.kt | Mrxyx | 366,778,189 | false | null | package com.mrxyx.algorithm
import java.util.*
import kotlin.collections.HashSet
class BFS {
/**
* 二叉树的最小深度
* https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/
*/
fun minDepth(root: TreeNode?): Int {
if (root == null) return 0
val queue = LinkedList<TreeNode?>()
queue.add(root)
var depth = 1
while (!queue.isEmpty()) {
val sz = queue.size
for (i in 0 until sz) {
val node = queue.poll()
if (node?.leftChild == null && node?.rightChild == null) return depth
if (node.leftChild != null) queue += node.leftChild
if (node.rightChild != null) queue += node.rightChild
}
depth++
}
return 0
}
//节点
class TreeNode(var value: Int, var leftChild: TreeNode? = null, var rightChild: TreeNode? = null)
/**
* 打开锁的最少次数
* https://leetcode-cn.com/problems/open-the-lock/
*/
fun openLock(deads: Array<String>, target: String): Int {
val dead = HashSet<String>()
//Dead Num
for (d in deads) dead.add(d)
//已访问过密码
val visited = HashSet<String>()
val q: Queue<String> = LinkedList()
//当前步数
var step = 0
q.offer("0000")
visited.add("0000")
while (!q.isEmpty()) {
val s = q.size
var up: String
var down: String
for (i in 0 until s) {
val cur = q.poll()
if (dead.contains(cur)) continue
if (target == cur) return step
for (j in 0..4) {
up = plusOne(cur, j)
if (!visited.contains(up)) {
q.offer(up)
visited.add(up)
}
down = minusOne(cur, j)
if (!visited.contains(down)) {
q.offer(down)
visited.add(down)
}
}
}
step++
}
return -1
}
//减1
private fun minusOne(cur: String?, j: Int): String {
if (cur == null) return ""
val ch = cur.toCharArray()
ch[j] = if (ch[j] == '0') '9' else ch[j] + 1
return ch[j].toString()
}
//加1
private fun plusOne(cur: String?, j: Int): String {
if (cur == null) return ""
val ch = cur.toCharArray()
ch[j] = if (ch[j] == '9') '0' else ch[j] + 1
return ch[j].toString()
}
} | 0 | Kotlin | 0 | 0 | b81b357440e3458bd065017d17d6f69320b025bf | 2,644 | algorithm-test | The Unlicense |
src/2021/Day17_2.kts | Ozsie | 318,802,874 | false | {"Kotlin": 99344, "Python": 1723, "Shell": 975} | import java.io.File
import kotlin.math.absoluteValue
import kotlin.math.max
class Result(val initVel: Pair<Int,Int>, val maxY: Int, val hit: Boolean)
fun shoot(x: Int, y: Int, xRange: IntRange, yRange: IntRange): Result {
var maxYPos = Int.MIN_VALUE
var localYMax = Int.MIN_VALUE
var position = Pair(0,0)
var velocity = Pair(x,y)
var steps = 0
var over = false
while (true) {
steps++
val nX = position.first + velocity.first
val nY = position.second + velocity.second
position = Pair(nX, nY)
if (nY > localYMax) localYMax = nY
val inX = position.first >= xRange.first && position.first <= xRange.last
val inY = position.second >= yRange.first && position.second <= yRange.last
if (inX && inY) break
val long = nX > Math.max(xRange.last, xRange.first)
val toMuchY = nY < Math.min(yRange.last, yRange.first)
if (long || toMuchY) {
over = true
break
}
val nVX = if (velocity.first > 0) velocity.first - 1 else if (velocity.first < 0) velocity.first + 1 else velocity.first
val nVY = velocity.second - 1
velocity = Pair(nVX, nVY)
}
if (!over) maxYPos = max(localYMax, maxYPos)
return Result(Pair(x,y), maxYPos, !over)
}
File("input/2021/day17").forEachLine { line ->
val (xTarget, yTarget) = line.substring(13).split(", ")
val (xMin, xMax) = xTarget.substring(2).split("..").map { it.toInt() }.sortedBy { it }
val (yMin, yMax) = yTarget.substring(2).split("..").map { it.toInt() }.sortedBy { it }
val xRange = xMin.toInt()..xMax.toInt()
val yRange = yMin.toInt()..yMax.toInt()
var initVel = Pair(0,0)
var maxYPos = Int.MIN_VALUE
var hitCount = 0
for (x in 0..700) {
for (y in -500..500) {
val result = shoot(x,y, xRange, yRange)
hitCount += if (result.hit) 1 else 0
if (result.hit) {
maxYPos = max(result.maxY, maxYPos)
initVel = result.initVel
}
}
}
println(hitCount)
} | 0 | Kotlin | 0 | 0 | d938da57785d35fdaba62269cffc7487de67ac0a | 2,099 | adventofcode | MIT License |
src/Day03.kt | saphcarter | 573,329,337 | false | null | fun main() {
fun priorityCalc(alpha: Char): Int{
return if (alpha.isLowerCase()) {
alpha.code - 96
} else alpha.code - 38;
}
fun part1(input: List<String>): Int {
var priority = 0
input.forEach {
val inputList = it.toList()
val size = inputList.size
val comp1 = inputList.subList(0,(size/2))
val comp2 = inputList.subList(size/2,size)
val intersect = comp1 intersect comp2
//println("comp1: $comp1, comp2:$comp2, intersect: $intersect")
intersect.forEach { char: Char ->
//println("char: $char, priority: $prior")
priority += priorityCalc(char)
}
}
return priority
}
fun part2(input: List<String>): Int {
var priority = 0
for(i in 0 .. input.size step 3){
if(i < input.size-2){
val halfIntersect = input[i].toSet() intersect input[i + 1].toSet()
val fullIntersect = halfIntersect intersect input[i + 2].toSet()
priority += priorityCalc(fullIntersect.first())
}
}
return priority
}
// test if implementation meets criteria from the description, like:
val testInput = listOf("<KEY>","<KEY>", "Pmmd<KEY>",
"wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn", "ttgJtRGJQctTZtZT", "CrZsJsPPZsGzwwsLwLmpwMDw")
val test1 = part1(testInput)
check(test1 == 157)
println("Test 1 passed")
val test2 = part2(testInput)
check(test2 == 70)
println("Test 2 passed")
val input = readInput("Input03")
//println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 2037106e961dc58e75df2fbf6c31af6e0f44777f | 1,744 | aoc-2022 | Apache License 2.0 |
src/Day08/Day08.kt | Nathan-Molby | 572,771,729 | false | {"Kotlin": 95872, "Python": 13537, "Java": 3671} | package Day08
import readInput
fun findVisibleTrees(treeMatrix: List<List<Int>>): Int {
var visibleTrees = HashSet<Pair<Int, Int>>()
for (rowIndex in treeMatrix.indices) {
processRow(rowIndex, treeMatrix, visibleTrees)
}
val columnCount = treeMatrix[0].size
for(columnIndex in 0..columnCount - 1) {
processColumn(columnIndex, treeMatrix, visibleTrees)
}
return visibleTrees.size
}
fun processColumn(columnIndex: Int, treeMatrix: List<List<Int>>, visibleTrees: HashSet<Pair<Int, Int>>) {
val rowCount = treeMatrix.size
var highestTreeSoFar = -1
for (rowIndex in 0..rowCount - 1) {
val coordinateValue = treeMatrix[rowIndex][columnIndex]
if(coordinateValue > highestTreeSoFar) {
highestTreeSoFar = coordinateValue
visibleTrees.add(Pair<Int, Int>(rowIndex, columnIndex))
}
}
highestTreeSoFar = -1
for(rowIndex in rowCount - 1 downTo 0) {
val coordinateValue = treeMatrix[rowIndex][columnIndex]
if(coordinateValue > highestTreeSoFar) {
highestTreeSoFar = coordinateValue
visibleTrees.add(Pair<Int, Int>(rowIndex, columnIndex))
}
}
}
fun processRow(rowIndex: Int, treeMatrix: List<List<Int>>, visibleTrees: HashSet<Pair<Int, Int>>) {
var highestTreeSoFar = -1
for (columnIndex in treeMatrix[rowIndex].indices) {
val coordinateValue = treeMatrix[rowIndex][columnIndex]
if (coordinateValue > highestTreeSoFar) {
highestTreeSoFar = coordinateValue
visibleTrees.add(Pair<Int, Int>(rowIndex, columnIndex))
}
}
highestTreeSoFar = -1
for (columnIndex in treeMatrix[rowIndex].size - 1 downTo 0) {
val coordinateValue = treeMatrix[rowIndex][columnIndex]
if (coordinateValue > highestTreeSoFar) {
highestTreeSoFar = coordinateValue
visibleTrees.add(Pair<Int, Int>(rowIndex, columnIndex))
}
}
}
fun findScenicScore(treeMatrix: List<List<Int>>): Pair<Pair<Int, Int>, Int> {
var maxScenicScore = -1
var bestCoordinate: Pair<Int, Int> = Pair(0, 0)
for (rowIndex in treeMatrix.indices) {
if (rowIndex == 0 || rowIndex == treeMatrix.count() - 1) {
continue;
}
for (columnIndex in treeMatrix[rowIndex].indices) {
if (columnIndex == 0 || columnIndex == treeMatrix[0].count() - 1) {
continue;
}
val scenicScore = findScenicScore(treeMatrix, rowIndex, columnIndex)
if(scenicScore > maxScenicScore) {
maxScenicScore = scenicScore
bestCoordinate = Pair(rowIndex, columnIndex)
}
}
}
return Pair(bestCoordinate, maxScenicScore)
}
fun findScenicScore(treeMatrix: List<List<Int>>, initialRowIndex: Int, initialColumnIndex: Int): Int {
val treeHeight = treeMatrix[initialRowIndex][initialColumnIndex]
var xPositiveScore = 0
var xNegativeScore = 0
var yPositiveScore = 0
var yNegativeScore = 0
var rowIndex = initialRowIndex + 1
while(rowIndex < treeMatrix.count()) {
yPositiveScore++
if (treeMatrix[rowIndex][initialColumnIndex] >= treeHeight) {
break
}
rowIndex++
}
rowIndex = initialRowIndex - 1
while(rowIndex >= 0) {
yNegativeScore++
if (treeMatrix[rowIndex][initialColumnIndex] >= treeHeight) {
break
}
rowIndex--
}
var columnIndex = initialColumnIndex + 1
while(columnIndex < treeMatrix[initialRowIndex].count()) {
xPositiveScore++
if (treeMatrix[initialRowIndex][columnIndex] >= treeHeight) {
break
}
columnIndex++
}
columnIndex = initialColumnIndex - 1
while(columnIndex >= 0) {
xNegativeScore++
if (treeMatrix[initialRowIndex][columnIndex] >= treeHeight) {
break
}
columnIndex--
}
return xPositiveScore * xNegativeScore * yPositiveScore * yNegativeScore
}
fun main() {
fun part1(input: List<String>): Int {
val intMatrix = input.map {
it
.map { it.digitToInt() }
}
return findVisibleTrees(intMatrix)
}
fun part2(input: List<String>): Int {
val intMatrix = input.map {
it
.map { it.digitToInt() }
}
val result = findScenicScore(intMatrix)
return result.second
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08","Day08_test")
println(part1(testInput))
check(part1(testInput) == 21)
println(part2(testInput))
check(part2(testInput) == 8)
val input = readInput("Day08","Day08")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 750bde9b51b425cda232d99d11ce3d6a9dd8f801 | 4,862 | advent-of-code-2022 | Apache License 2.0 |
src/Day21.kt | rosyish | 573,297,490 | false | {"Kotlin": 51693} | fun main() {
open class Node(val name: String)
class ValueNode(name: String, val value: Long) : Node(name)
class ExpressionNode(
name: String,
val left: Node,
val right: Node,
val operation: (Long, Long) -> Long,
val moveRightOperand: (Long, Long) -> Long,
val moveLeftOperand: (Long, Long) -> Long
) : Node(name)
val input = readInput("Day21_input")
val nameToNode = input
.map {
val (first, second) = it.split(":")
Pair(first, second)
}
.associate { pair ->
val parts = pair.second.trim().split(' ')
if (parts.size == 1) {
pair.first to ValueNode(pair.first, parts[0].trim().toLong())
} else {
val left = Node(parts[0].trim())
val right = Node(parts[2].trim())
val operation: (Long, Long) -> Long = when (parts[1].first()) {
'+' -> { a, b -> a + b }
'-' -> { a, b -> a - b }
'*' -> { a, b -> a * b }
'/' -> { a, b -> a / b }
else -> throw IllegalArgumentException("Unexpected operator")
}
val moveRightOperand: (Long, Long) -> Long = when (parts[1].first()) {
'+' -> { a, b -> a - b }
'-' -> { a, b -> b + a }
'*' -> { a, b -> a / b }
'/' -> { a, b -> b * a }
else -> throw IllegalArgumentException("Unexpected operator")
}
val moveLeftOperand: (Long, Long) -> Long = when (parts[1].first()) {
'+' -> { a, b -> a - b }
'-' -> { a, b -> b - a }
'*' -> { a, b -> a / b }
'/' -> { a, b -> b / a }
else -> throw IllegalArgumentException("Unexpected operator")
}
pair.first to ExpressionNode(
pair.first,
left,
right,
operation,
moveRightOperand,
moveLeftOperand
)
}
}
fun solvePart1(current: Node): Long {
if (current is ValueNode) return current.value
if (current is ExpressionNode) {
return current.operation(solvePart1(current.left), solvePart1(current.right))
}
return solvePart1(nameToNode[current.name]!!)
}
println(solvePart1(nameToNode["root"]!!))
val nameToNodePart2 =
nameToNode
.filterKeys { key -> key != "humn" }
.toMutableMap().apply { this.put("humn", Node("humn")) }
fun evaluate(current: Node): Node {
if (current is ValueNode) return current
if (current is ExpressionNode) {
val left = evaluate(current.left)
val right = evaluate(current.right)
return if (left is ValueNode && right is ValueNode) {
ValueNode(current.name, current.operation(left.value, right.value))
} else {
ExpressionNode(
current.name,
left,
right,
current.operation,
current.moveRightOperand,
current.moveLeftOperand
)
}
}
if (current.name == "humn") return current
return evaluate(nameToNodePart2[current.name]!!)
}
fun solveForX(current: Node, answer: Long): Long {
if (current.name == "humn") return answer
if (current is ExpressionNode && current.left is ValueNode) {
val newAnswer = current.moveLeftOperand(answer, current.left.value)
return solveForX(current.right, newAnswer)
}
if (current is ExpressionNode && current.right is ValueNode) {
val newAnswer = current.moveRightOperand(answer, current.right.value)
return solveForX(current.left, newAnswer)
}
throw IllegalArgumentException("Unexpected node $current")
}
val root = nameToNodePart2["root"] as ExpressionNode
val left = evaluate(root.left)
val right = evaluate(root.right)
if (left is ExpressionNode) {
println(solveForX(left, (right as ValueNode).value))
} else if (right is ExpressionNode) {
println(solveForX(right, (left as ValueNode).value))
} else {
throw IllegalStateException("Evaluation failed")
}
}
| 0 | Kotlin | 0 | 2 | 43560f3e6a814bfd52ebadb939594290cd43549f | 4,565 | aoc-2022 | Apache License 2.0 |
src/Day16.kt | thorny-thorny | 573,065,588 | false | {"Kotlin": 57129} | import kotlin.math.pow
data class Valve(val id: String, val rate: Int, val connectedTo: List<String>) {
override fun equals(other: Any?): Boolean {
return when (other) {
is Valve -> id == other.id
else -> false
}
}
override fun hashCode(): Int {
return id.hashCode()
}
override fun toString(): String {
return id
}
}
fun main() {
fun parseValve(line: String): Valve {
val match = Regex("""Valve (\S+?) has flow rate=(\d+); tunnels? leads? to valves? (.+)""").matchEntire(line) ?: throw Exception("Unknown format")
val (id, rate, connectedTo) = match.destructured
return Valve(id, rate.toInt(), connectedTo.split(", "))
}
fun makeConnectionsMap(valves: List<Valve>): Map<Pair<Valve, Valve>, Int> {
val size = valves.size
val table = List(size) { from ->
MutableList(size) { to ->
when (from) {
to -> 0
else -> Int.MAX_VALUE
}
}
}
valves.forEachIndexed { index, valve ->
valve.connectedTo.forEach { connectedId ->
table[index][valves.indexOfFirst { it.id == connectedId }] = 1
}
}
do {
var updated = 0
(0 until size).forEach { from ->
(0 until size).forEach { to ->
val jumpsTo = table[from][to]
if (jumpsTo < Int.MAX_VALUE) {
(0 until size).forEach { bridge ->
val bridgeJumps = table[to][bridge]
if (bridgeJumps < Int.MAX_VALUE) {
val newJumps = jumpsTo + bridgeJumps
if (newJumps < table[from][bridge]) {
table[from][bridge] = newJumps
updated += 1
}
}
}
}
}
}
} while (updated > 0)
val map = hashMapOf<Pair<Valve, Valve>, Int>()
(0 until size).forEach { from ->
(0 until size).forEach { to ->
val jumps = table[from][to]
if (jumps < Int.MAX_VALUE) {
val fromValve = valves[from]
val toValve = valves[to]
map[fromValve to toValve] = jumps
map[toValve to fromValve] = jumps
}
}
}
return map.toMap()
}
fun getMaxPressure(targetValves: List<Valve>, tunnels: Map<Pair<Valve, Valve>, Int>, startingValve: Valve, track: List<Valve>, minutesLeft: Int): Int {
if (minutesLeft == 0) {
return 0
}
val current = track.lastOrNull() ?: startingValve
val nextFunctioningValves = targetValves.filter {
(it !in track) && tunnels[current to it] != null
}
return nextFunctioningValves.maxOfOrNull {
when (val steps = tunnels[current to it]) {
null -> 0
else -> it.rate * maxOf(minutesLeft - steps - 1, 0) + getMaxPressure(targetValves, tunnels, startingValve, track + it, maxOf(minutesLeft - steps - 1, 0))
}
} ?: 0
}
fun part1(input: List<String>): Int {
val valves = input.map(::parseValve)
val allTunnels = makeConnectionsMap(valves)
val startingValve = valves.find { it.id == "AA" } ?: throw Exception("I got lost D:")
val functioningValves = valves.filter { it.rate > 0 }
val involvedValves = functioningValves + startingValve
val tunnels = allTunnels.filter {
(it.key.first in involvedValves) && (it.key.second in involvedValves)
}
return getMaxPressure(functioningValves, tunnels, startingValve, listOf(), 30)
}
fun part2(input: List<String>): Int {
val valves = input.map(::parseValve)
val allTunnels = makeConnectionsMap(valves)
val startingValve = valves.find { it.id == "AA" } ?: throw Exception("I got lost D:")
val functioningValves = valves.filter { it.rate > 0 }
val involvedValves = functioningValves + startingValve
val tunnels = allTunnels.filter {
(it.key.first in involvedValves) && (it.key.second in involvedValves)
}
return (0 until (2.0).pow(functioningValves.size).toInt()).maxOf {
val meValves = mutableListOf<Valve>()
val elValves = mutableListOf<Valve>()
functioningValves.forEachIndexed { index, valve ->
if ((1 shl index) and it > 0) {
meValves.add(valve)
} else {
elValves.add(valve)
}
}
val mePressure = getMaxPressure(meValves, tunnels, startingValve, listOf(), 26)
val elPressure = getMaxPressure(elValves, tunnels, startingValve, listOf(), 26)
mePressure + elPressure
}
}
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 | 843869d19d5457dc972c98a9a4d48b690fa094a6 | 5,332 | aoc-2022 | Apache License 2.0 |
src/Day09.kt | ajmfulcher | 573,611,837 | false | {"Kotlin": 24722} | data class Instruction(
val direction: String,
val moves: Int
)
fun main() {
fun instructions(input: List<String>): ArrayDeque<Instruction> {
return ArrayDeque<Instruction>(input.map {
val i = it.split(" ")
Instruction(i[0], i[1].toInt())
})
}
fun Pair<Int, Int>.moveHead(direction: String): Pair<Int, Int> {
var x = 0
var y = 0
when (direction) {
"L" -> x = -1
"R" -> x = 1
"U" -> y = -1
"D" -> y = 1
}
return Pair(first + x, second + y)
}
fun Pair<Int, Int>.moveTail(h: Pair<Int, Int>): Pair<Int, Int> {
val x = h.first - first
val y = h.second - second
return when {
Math.abs(x) <= 1 && Math.abs(y) <= 1 -> this
Math.abs(x) <= 1 -> Pair(h.first, second + y / 2)
Math.abs(y) <= 1 -> Pair(first + x / 2, h.second)
Math.abs(x) == 2 && Math.abs(y) == 2 -> Pair(first + x / 2, second + y / 2)
else -> {
throw Error()
}
}
}
fun performInstruction(
instructions: ArrayDeque<Instruction>,
tailPos: MutableSet<Pair<Int,Int>>,
h: Pair<Int, Int> = Pair(0,0),
t: Pair<Int,Int> = Pair(0,0)
) {
if (instructions.isNotEmpty()) {
val instruction = instructions.removeFirst()
var head = h
var tail = t
(1..instruction.moves).forEach { _ ->
head = head.moveHead(instruction.direction)
tail = tail.moveTail(head)
tailPos.add(tail)
}
performInstruction(instructions, tailPos, head, tail)
}
}
fun part1(input: List<String>): Int {
val tailPos = hashSetOf<Pair<Int,Int>>()
val instructions = instructions(input)
performInstruction(instructions, tailPos)
return tailPos.size
}
fun moveTails(knots: Array<Pair<Int,Int>>, idx: Int = 1) {
if (idx > knots.lastIndex) return
val moved = knots[idx].moveTail(knots[idx - 1])
if(knots[idx] != moved) {
knots[idx] = moved
moveTails(knots, idx + 1)
}
}
fun performInstructionBrokenRope(
instructions: ArrayDeque<Instruction>,
tailPos: MutableSet<Pair<Int,Int>>,
knots: Array<Pair<Int,Int>> = Array(10) { Pair(0,0) }
) {
if (instructions.isNotEmpty()) {
val instruction = instructions.removeFirst()
(1..instruction.moves).forEach { _ ->
knots[0] = knots[0].moveHead(instruction.direction)
moveTails(knots)
tailPos.add(knots.last())
}
performInstructionBrokenRope(instructions, tailPos, knots)
}
}
fun part2(input: List<String>): Int {
val tailPos = hashSetOf<Pair<Int,Int>>()
val instructions = instructions(input)
performInstructionBrokenRope(instructions, tailPos)
return tailPos.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test")
println(part1(testInput))
check(part1(testInput) == 13)
val input = readInput("Day09")
println(part1(input))
println(part2(testInput))
check(part2(testInput) == 1)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 981f6014b09e347241e64ba85e0c2c96de78ef8a | 3,402 | advent-of-code-2022-kotlin | Apache License 2.0 |
advent-of-code-2021/src/main/kotlin/eu/janvdb/aoc2021/day17/Day17.kt | janvdbergh | 318,992,922 | false | {"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335} | package eu.janvdb.aoc2021.day17
import eu.janvdb.aocutil.kotlin.point2d.Point2D
import kotlin.math.max
import kotlin.math.min
//val TARGET = Target(20, 30, -10, -5)
val TARGET = Target(155, 182, -117, -67)
fun main() {
part1()
part2()
}
private fun part1() {
var startX = 1
while (true) {
val reachedX = startX * (startX + 1) / 2
if (reachedX > TARGET.x2) {
println("No startX found")
return
}
if (reachedX >= TARGET.x1) break
startX++
}
val bestTrajectory = IntRange(0, 1000)
.map { calculateTrajectory(Point2D(startX, it)) }
.filter { it.reachedTarget }
.maxByOrNull { it.maxHeight() }!!
bestTrajectory.print()
}
private fun part2() {
val result = IntRange(1, TARGET.x2)
.flatMap { x -> IntRange(TARGET.y1, 1000).map { Point2D(x, it) } }
.map { calculateTrajectory(it) }
.count { it.reachedTarget }
println(result)
}
fun calculateTrajectory(startVector: Point2D): Trajectory {
var currentPoint = Point2D(0, 0)
var currentVector = startVector
val trajectory = mutableListOf(currentPoint)
while (!TARGET.isOutOfRangeOf(currentPoint)) {
currentPoint = Point2D(currentPoint.x + currentVector.x, currentPoint.y + currentVector.y)
currentVector = Point2D(max(0, currentVector.x - 1), currentVector.y - 1)
trajectory.add(currentPoint)
if (TARGET.contains(currentPoint)) return Trajectory(startVector, trajectory, true)
}
return Trajectory(startVector, trajectory, false)
}
data class Trajectory(val startVector: Point2D, val trajectory: List<Point2D>, val reachedTarget: Boolean) {
fun print() {
val minX = min(trajectory.minOf { it.x }, TARGET.x1)
val maxX = max(trajectory.maxOf { it.x }, TARGET.x2)
val minY = min(trajectory.minOf { it.y }, TARGET.y1)
val maxY = max(maxHeight(), TARGET.y2)
for (y in maxY downTo minY) {
for (x in minX..maxX) {
val point = Point2D(x, y)
val ch = if (trajectory.contains(point)) '#' else if (TARGET.contains(point)) 'T' else '.'
print(ch)
}
println()
}
println("Reached target: $reachedTarget")
println("Max height: ${maxHeight()}")
}
fun maxHeight() = trajectory.maxOf { it.y }
}
data class Target(val x1: Int, val x2: Int, val y1: Int, val y2: Int) {
fun contains(point: Point2D): Boolean {
return (point.x in x1..x2) && (point.y in y1..y2)
}
fun isOutOfRangeOf(point: Point2D): Boolean {
return point.x > x2 || point.y < y1
}
} | 0 | Java | 0 | 0 | 78ce266dbc41d1821342edca484768167f261752 | 2,377 | advent-of-code | Apache License 2.0 |
src/main/kotlin/net/hiddevb/advent/advent2019/day08/main.kt | hidde-vb | 224,606,393 | false | null | package net.hiddevb.advent.advent2019.day08
import net.hiddevb.advent.common.initialize
/**
* --- Day 8: Space Image Format ---
*/
private const val WIDTH = 25
private const val HEIGHT = 6
fun main() {
val fileStrings = initialize("Day 8: Space Image Format", arrayOf("day8.txt"))
println("Part 1: Basic")
val solution1 = solveBasic(fileStrings[0])
println("Solved!\nSolution: $solution1\n")
println("Part 2: Advanced")
val solution2 = solveAdvanced(fileStrings[0])
println("Solved!\nSolution:\n$solution2\n")
}
// Part 1
fun solveBasic(input: String): Int {
val layer = getLeastcorruptedLayer(input.chunked(WIDTH * HEIGHT))
return layer.count { "1".contains(it) } * layer.count { "2".contains(it) }
}
private fun getLeastcorruptedLayer(chunks: List<String>): String = chunks.minBy { it.count { l -> "0".contains(l) } }!!
// Part 2
fun solveAdvanced(input: String): String {
val layers = input.chunked(WIDTH * HEIGHT)
val mergedLayer = layers.last().toCharArray()
for (l in layers.size - 1 downTo 0) {
for (c in 0 until mergedLayer.size) {
when (layers[l][c]) {
'0' -> mergedLayer[c] = '0'
'1' -> mergedLayer[c] = '1'
}
}
}
return render(mergedLayer)
}
private fun render(layer: CharArray): String {
var render = ""
for(i in 0 until layer.size) {
when (layer[i]) {
'0' -> render = "$render "
'1' -> render = "$render#"
'2' -> render = "$render "
}
if ((1+i) % WIDTH == 0) {
render = "$render\n"
}
}
return render
}
| 0 | Kotlin | 0 | 0 | d2005b1bc8c536fe6800f0cbd05ac53c178db9d8 | 1,653 | advent-of-code-2019 | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem2492/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem2492
/**
* LeetCode page: [2492. Minimum Score of a Path Between Two Cities](https://leetcode.com/problems/minimum-score-of-a-path-between-two-cities/);
*/
class Solution {
/* Complexity:
* Time O(E) and Space O(E) where E is the size of roads;
*/
fun minScore(n: Int, roads: Array<IntArray>): Int {
val roadMap = convertToRoadMap(roads)
var minScore = Int.MAX_VALUE
var isCityNReachable = false
dfs(1, roadMap) { road ->
if (road.distance < minScore) minScore = road.distance
if (road.destination == n) isCityNReachable = true
}
check(isCityNReachable)
return minScore
}
private fun convertToRoadMap(roads: Array<IntArray>): Map<Int, List<Road>> {
val roadMap = hashMapOf<Int, MutableList<Road>>()
for ((u, v, distance) in roads) {
roadMap.computeIfAbsent(u) { mutableListOf() }.add(Road(u, v, distance))
roadMap.computeIfAbsent(v) { mutableListOf() }.add(Road(v, u, distance))
}
return roadMap
}
private class Road(val origin: Int, val destination: Int, val distance: Int)
private fun dfs(
origin: Int,
roadMap: Map<Int, List<Road>>,
visited: MutableSet<Int> = hashSetOf(),
sideEffect: (road: Road) -> Unit
) {
if (origin in visited) return
visited.add(origin)
val roads = roadMap[origin] ?: emptyList()
for (road in roads) {
sideEffect(road)
dfs(road.destination, roadMap, visited, sideEffect)
}
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,627 | hj-leetcode-kotlin | Apache License 2.0 |
year2021/src/main/kotlin/net/olegg/aoc/year2021/day13/Day13.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2021.day13
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.Vector2D
import net.olegg.aoc.utils.parseInts
import net.olegg.aoc.year2021.DayOf2021
/**
* See [Year 2021, Day 13](https://adventofcode.com/2021/day/13)
*/
object Day13 : DayOf2021(13) {
override fun first(): Any? {
val (rawDots, rawFolds) = data.split("\n\n")
val points = rawDots.lines()
.map { it.parseInts(",") }
.map { Vector2D(it.first(), it.last()) }
.toSet()
val folds = rawFolds.lines()
.map { it.split("=") }
.map { it.first().last() to it.last().toInt() }
val first = folds.first()
return points.map {
when {
first.first == 'x' && it.x > first.second -> Vector2D(2 * first.second - it.x, it.y)
first.first == 'y' && it.y > first.second -> Vector2D(it.x, 2 * first.second - it.y)
else -> it
}
}.toSet().size
}
override fun second(): Any? {
val (rawDots, rawFolds) = data.split("\n\n")
val points = rawDots.lines()
.map { it.parseInts(",") }
.map { Vector2D(it.first(), it.last()) }
.toSet()
val folds = rawFolds.lines()
.map { it.split("=") }
.map { it.first().last() to it.last().toInt() }
val final = folds.fold(points) { acc, fold ->
acc.map {
when {
fold.first == 'x' && it.x > fold.second -> Vector2D(2 * fold.second - it.x, it.y)
fold.first == 'y' && it.y > fold.second -> Vector2D(it.x, 2 * fold.second - it.y)
else -> it
}
}.toSet()
}
val minX = final.minOf { it.x }
val maxX = final.maxOf { it.x }
val minY = final.minOf { it.y }
val maxY = final.maxOf { it.y }
return (minY..maxY).joinToString(prefix = "\n", separator = "\n") { y ->
(minX..maxX).joinToString(separator = "") { x ->
if (Vector2D(x, y) in final) "██" else ".."
}
}
}
}
fun main() = SomeDay.mainify(Day13)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 1,959 | adventofcode | MIT License |
src/main/kotlin/aoc2022/Day12.kt | w8mr | 572,700,604 | false | {"Kotlin": 140954} | package aoc2022
import aoc.*
import aoc.parser.*
import java.lang.IllegalArgumentException
typealias Grid<T> = Array<Array<T>>
class Day12 {
companion object {
fun <T> Grid<T>.fromCoord(coord:Coord) =
this.getOrNull(coord.y)?.getOrNull(coord.x)
}
sealed class Elevation(val level: Int)
class Level(level: Int): Elevation(level) {
override fun toString(): String = "Level $level"
}
class Start: Elevation(0) {
override fun toString(): String = "Start"
}
class End: Elevation(25) {
override fun toString(): String = "End"
}
fun elevation(char: String): Elevation {
if (char.length != 1) throw IllegalArgumentException()
return when (val c = char[0]) {
'S' -> Start()
'E' -> End()
else -> Level(c - 'a')
}
}
fun <T> Grid<T>.find(predicate: (T) -> Boolean): Coord? {
this.forEachIndexed { y, inner ->
inner.forEachIndexed { x, element ->
if (predicate(element)) {
return Coord(x, y)
}
}
}
return null
}
data class GridBackedGraphNode<T>(private val gridBack: GridBack<T>, private val coord: Coord) : GraphNode<T> {
override val neighbours by lazy { gridBack.neighbourNodes(gridBack, coord) }
override val value: T by lazy { gridBack.grid.fromCoord(coord)!! }
}
class GridBack<T>(val grid: Grid<T>, val neighbourNodes: (GridBack<T>, Coord) -> List<Pair<Int, GraphNode<T>>>)
fun <T> Grid<T>.toDAG(start:Coord, neighbourNodes: (GridBack<T>, Coord) -> List<Pair<Int, GraphNode<T>>>): GraphNode<T> {
return GridBackedGraphNode(GridBack(this, neighbourNodes), start)
}
val parser = zeroOrMore(
(zeroOrMore(
(regex("[a-zSE]") map(::elevation))) followedBy "\n").asArray()
).asArray()
fun part1(input: String): Int {
val grid = parser.parse(input)
val start = (grid.find { it is Start })!!
val dag = grid.toDAG(start) { g, c ->
val t0 = g.grid.fromCoord(c)!!
val neighbours = c.dirs4()
.map { c4 -> c4 to g.grid.fromCoord(c4) }
.filter {
(it.second?.level ?: Int.MAX_VALUE) - t0.level <= 1
}
.map { Pair(1, GridBackedGraphNode(g, it.first)) }
neighbours
}
return findShortestPath(dag) { (it as GridBackedGraphNode).value is End }!!
}
fun part2(input: String): Int? {
val grid = parser.parse(input)
val end = (grid.find { it is End })!!
val dag = grid.toDAG(end) { g, c ->
val t0 = g.grid.fromCoord(c)!!
val neighbours = c.dirs4()
.map { c4 -> c4 to g.grid.fromCoord(c4) }
.filter {
it.second != null && ((it.second?.level ?: 0) - t0.level >= -1)
}
.map { Pair(1, GridBackedGraphNode(g, it.first)) }
neighbours
}
return findShortestPath(dag) {
val node = (it as GridBackedGraphNode).value
if (node is Level) {
node.level == 0
} else {
false
}
}!!
}
}
| 0 | Kotlin | 0 | 0 | e9bd07770ccf8949f718a02db8d09daf5804273d | 3,309 | aoc-kotlin | Apache License 2.0 |
src/main/kotlin/day18.kt | Arch-vile | 572,557,390 | false | {"Kotlin": 132454} | package day18
import aoc.utils.Point
import aoc.utils.readInput
import kotlin.math.abs
fun main() {
// (0..5).forEach {x ->
// (0..5).forEach { y ->
// (0..5).forEach {z ->
//
// println()
// }
// }
// }
val rocks = points().toSet()
val emptySurface = rocks
.flatMap { rock ->
val neighbourSpots = neighbours(rock)
val neighbourRocks = neighbourRocks(rock, rocks)
val emptyNeighbours = neighbourSpots.minus(neighbourRocks)
emptyNeighbours
}.toSet()
val canSeeSpaceDirectly = emptySurface.filter { empty -> canSeeSpace(empty, rocks) }
val canAccessSpace = canSeeSpaceDirectly.toMutableSet()
val processed = mutableSetOf<Point>()
val toProcess = canSeeSpaceDirectly.toMutableSet()
while (toProcess.isNotEmpty()) {
val next = toProcess.first()
toProcess.remove(next)
processed.add(next)
val sees = sees(next, emptySurface)
canAccessSpace.addAll(sees)
toProcess.addAll(sees.minus(processed))
}
canAccessSpace.map {
neighbourRocks(it, rocks).size
}.sum().let { println(it) }
// 4044 is too low
// 2446 is too low
}
fun sees(current: Point, emptySurface: Set<Point>): Set<Point> {
return sees(current,emptySurface, Point(1,0,0))
.plus(sees(current,emptySurface,Point(-1,0,0)))
.plus(sees(current,emptySurface,Point(0,1,0)))
.plus(sees(current,emptySurface,Point(0,-1,0)))
.plus(sees(current,emptySurface,Point(0,0,1)))
.plus(sees(current,emptySurface,Point(0,0,-1)))
}
fun sees(current: Point, emptySurface: Set<Point>, direction: Point): Set<Point> {
val collected = mutableSetOf<Point>()
var next = current
while (true) {
next = next.plus(direction)
val found = emptySurface.firstOrNull { it == next }
if (found != null)
collected.add(next)
else
break
}
return collected
}
fun calculateRocks(accessible: Set<Point>, rocks: Set<Point>): Int {
return accessible.map {
neighbourRocks(it, rocks).size
}.sum()
}
fun canSeeSpace(current: Point, rocks: Set<Point>): Boolean {
val up = current.onDirection(rocks, Point(0, 1, 0))
val down = current.onDirection(rocks, Point(0, -1, 0))
val left = current.onDirection(rocks, Point(-1, 0, 0))
val right = current.onDirection(rocks, Point(1, 0, 0))
val toward = current.onDirection(rocks, Point(0, 0, 1))
val away = current.onDirection(rocks, Point(0, 0, -1))
// Can reach outer space
return (up.isEmpty() || down.isEmpty() ||
left.isEmpty() || right.isEmpty() ||
toward.isEmpty() || away.isEmpty()
)
}
fun isOuterLayer(empties: Set<Point>, rocks: Set<Point>): Boolean {
empties.forEach { empty ->
val up = empty.onDirection(rocks, Point(0, 1, 0))
val down = empty.onDirection(rocks, Point(0, -1, 0))
val left = empty.onDirection(rocks, Point(-1, 0, 0))
val right = empty.onDirection(rocks, Point(1, 0, 0))
val toward = empty.onDirection(rocks, Point(0, 0, 1))
val away = empty.onDirection(rocks, Point(0, 0, -1))
// Can reach outer space
if (up.isEmpty() || down.isEmpty() ||
left.isEmpty() || right.isEmpty() ||
toward.isEmpty() || away.isEmpty()
)
return true
}
return false
}
fun findAllAccessible(first: Point, emptySurface: Set<Point>): Set<Point> {
val accessible = mutableSetOf(first)
val toProcess = mutableSetOf(first)
val processed = mutableSetOf<Point>()
while (toProcess.isNotEmpty()) {
val point = toProcess.first()
toProcess.remove(point)
processed.add(point)
val sees = point.onDirectLine(emptySurface)
accessible.addAll(sees)
toProcess.addAll(sees.minus(processed))
}
return accessible
}
// val rocks = points().toSet()
//
// val emptySurface = rocks
// .flatMap { rock ->
// val neighbourSpots = neighbours(rock)
// val neighbourRocks = neighbourRocks(rock, rocks)
// val emptyNeighbours = neighbourSpots.minus(neighbourRocks)
// emptyNeighbours
// }.toSet()
//
// val outerSurface = mutableSetOf<Point>()
// val toCheck = emptySurface.toMutableSet()
//
// while (toCheck.isNotEmpty()) {
// val empty = toCheck.first()
//
// val up = empty.onDirection(rocks, Point(0, 1, 0))
// val down = empty.onDirection(rocks, Point(0, -1, 0))
// val left = empty.onDirection(rocks, Point(-1, 0, 0))
// val right = empty.onDirection(rocks, Point(1, 0, 0))
// val toward = empty.onDirection(rocks, Point(0, 0, 1))
// val away = empty.onDirection(rocks, Point(0, 0, -1))
//
// Can reach outer space
// if (up.isEmpty() || down.isEmpty() ||
// left.isEmpty() || right.isEmpty() ||
// toward.isEmpty() || away.isEmpty()
// ) {
// outerSurface.add(empty)
// val sees = empty.onDirectLine(emptySurface)
// outerSurface.addAll(sees)
//
//
// }
// }
// println(outerSurface.size)
//}
fun neighbourRocks(rock: Point, rocks: Set<Point>): Set<Point> {
return rocks.filter {
it.nextTo(rock)
}.toSet()
}
fun neighbours(current: Point): Set<Point> {
return setOf(
current.copy(x = current.x + 1),
current.copy(x = current.x - 1),
current.copy(y = current.y + 1),
current.copy(y = current.y - 1),
current.copy(z = current.z + 1),
current.copy(z = current.z - 1),
)
}
fun freeSidesOutside(current: Point, points: List<Point>): Int {
val onSameLine = points.filter { point ->
val isOnSameLine =
listOf(abs(current.x - point.x), abs(current.y - point.y), abs(current.z - point.z))
.filter { it != 0L }.size == 1
isOnSameLine
}
val encountersOnDirection = onSameLine.groupBy { point ->
// 0,1,0 or 0,-1,0 always only one coordinate is 1 or -1
"${toDirection(current.x - point.x)}${toDirection(current.y - point.y)}${toDirection((current.z - point.z))}"
}
return 6 - encountersOnDirection.keys.size
}
private fun toDirection(value: Long): Long {
if (value == 0L) return 0
return value / abs(value)
}
private fun points(): List<Point> {
val points = readInput("day18-input.txt")
.map { it.split(",") }
.map { Point(it[0].toLong(), it[1].toLong(), it[2].toLong()) }
return points
}
fun part1(): Int {
val points = points()
return points
.map { point ->
val neighbours = points.filter { it.nextTo(point) }
6 - neighbours.size
}
.sum()
}
fun part2(): Int {
return 1;
}
| 0 | Kotlin | 0 | 0 | e737bf3112e97b2221403fef6f77e994f331b7e9 | 6,902 | adventOfCode2022 | Apache License 2.0 |
src/main/kotlin/be/swsb/aoc2021/day11/Day11.kt | Sch3lp | 433,542,959 | false | {"Kotlin": 90751} | package be.swsb.aoc2021.day11
import be.swsb.aoc2021.common.Point
object Day11 {
fun solve1(input: List<String>) : AmountOfFlashes {
return DumboOctopusConsortium(input).step(100).amountOfFlashedOctopi
}
fun solve2(input: List<String>) : AmountOfSteps {
var dumboOctopusConsortium = DumboOctopusConsortium(input)
var stepCounter = 0
while(!dumboOctopusConsortium.allOctopiFlashSimultaneously) {
stepCounter++
dumboOctopusConsortium = dumboOctopusConsortium.step()
}
return stepCounter
}
}
typealias AmountOfFlashes = UInt
typealias AmountOfSteps = Int
data class DumboOctopusConsortium(
private val octopuses: Map<Point, DumboOctopus>,
val amountOfFlashedOctopi: UInt = 0u
) {
val allOctopiFlashSimultaneously: Boolean = octopuses.all { (_,v)-> v.energy == Energy(0u) }
constructor(input: List<String>) : this(
input.flatMapIndexed { idx, line ->
line.mapIndexed { lineIndex, char -> DumboOctopus(Point.at(lineIndex, idx), "$char".toUInt()) }
}.associateBy { it.point }
)
constructor(input: String) : this(input.split("\n"))
fun step(steps: Int = 1): DumboOctopusConsortium {
return (1..steps).fold(this) { acc, _ -> acc.step() }
}
private fun step(): DumboOctopusConsortium {
fun loop(affectedPoints: List<Point>, acc: Map<Point, DumboOctopus>): Map<Point, DumboOctopus> {
if (affectedPoints.isEmpty()) return acc
val affectedOctopuses = affectedPoints.fold(acc) { octopi, affectedPoint ->
octopi.mapValues { (k, v) -> if (k == affectedPoint) v.increaseEnergy() else v }
}
val flashedOctopuses = affectedOctopuses.filterValues { it.flashedThisStep }
val flashAffectedPoints: List<Point> =
flashedOctopuses.keys.flatMap { it.allNeighbours() } - flashedOctopuses.keys
return loop(
flashAffectedPoints,
affectedOctopuses.mapValues { (_, v) -> v.conditionallyMarkFlashedAlready() })
}
val steppedConsortium = loop(octopuses.keys.toList(), octopuses)
val amountOfFlashedOctopiInStep = steppedConsortium.filterValues { it.flashedAlready }.count().toUInt()
val resetConsortium = steppedConsortium.mapValues { (_, v) -> v.conditionallyExhaust() }
return DumboOctopusConsortium(resetConsortium, amountOfFlashedOctopi + amountOfFlashedOctopiInStep)
}
fun asString(): String {
fun octopusesToString(): String {
if (octopuses.isEmpty()) return "No Octopus in the Consortium"
val max = octopuses.maxOf { (k, _) -> k.x }
return (0..max).joinToString("\n") { y ->
(0..max).joinToString("") { x -> octopuses[Point.at(x, y)]!!.energy.toString() }.trimStart()
}
}
return "Amount of Flashed Octopi: $amountOfFlashedOctopi\n" + octopusesToString()
}
}
data class DumboOctopus(
val point: Point,
val energy: Energy,
val flashedThisStep: Boolean = false,
val flashedAlready: Boolean = false
) {
constructor(point: Point, energy: UInt) : this(point, Energy(energy))
fun conditionallyMarkFlashedAlready(): DumboOctopus =
if (flashedThisStep) {
this.copy(flashedThisStep = false, flashedAlready = true)
} else {
this
}
fun increaseEnergy(): DumboOctopus {
val increasedEnergy = energy.increase()
val flashedThisStep = increasedEnergy.isMaxed && !flashedAlready
return this.copy(energy = increasedEnergy, flashedThisStep = flashedThisStep)
}
fun conditionallyExhaust(): DumboOctopus = DumboOctopus(point = point, energy = energy.resetWhenMaxed())
}
private const val MAX_ENERGY = 10u
data class Energy(private val value: UInt) {
val isMaxed get() = value == MAX_ENERGY
fun increase() =
if (isMaxed) {
this
} else {
Energy(value + 1u)
}
fun resetWhenMaxed() =
if (!isMaxed) {
this
} else {
Energy(0u)
}
override fun toString() = value.toString()
} | 0 | Kotlin | 0 | 0 | 7662b3861ca53214e3e3a77c1af7b7c049f81f44 | 4,210 | Advent-of-Code-2021 | MIT License |
src/Day03.kt | wmichaelshirk | 573,031,182 | false | {"Kotlin": 19037} |
fun main() {
fun findPriority (c: Char): Int {
return if (c.isUpperCase()) {
c.code - 64 + 26
} else {
c.code - 96
}
}
fun part1(input: List<String>): Int {
return input
.map { it.chunked(it.length / 2) }
.map { it.first().toSet().intersect(it.last().toSet()).first() }
.sumOf { findPriority(it) }
}
fun part2(input: List<String>): Int {
return input.windowed(3, 3)
.map { it[0].toSet().intersect(it[1].toSet())
.intersect(it[2].toSet()).first() }
.sumOf { findPriority(it) }
}
// 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 | 2 | b748c43e9af05b9afc902d0005d3ba219be7ade2 | 928 | 2022-Advent-of-Code | Apache License 2.0 |
src/main/kotlin/solutions/day12/Day12.kt | Dr-Horv | 570,666,285 | false | {"Kotlin": 115643} | package solutions.day12
import solutions.Solver
import utils.Coordinate
import utils.Direction
import utils.step
class Node(
val id: Int,
val char: Char,
val start: Boolean,
val goal: Boolean,
val elevation: Int,
val neighbours: MutableMap<Direction, Node>
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Node
if (id != other.id) return false
return true
}
override fun hashCode(): Int {
return id
}
}
const val ZERO_ELEVATION = 'a'.code
fun Char.toElevation(): Int = this.code - ZERO_ELEVATION
class Day12 : Solver {
override fun solve(input: List<String>, partTwo: Boolean): String {
val map = mutableMapOf<Coordinate, Node>()
var id = 1
for ((y, line) in input.withIndex()) {
for ((x, c) in line.toList().withIndex()) {
val isStart = c == 'S'
val isGoal = c == 'E'
val elevation = if (isStart) {
'a'.toElevation()
} else if (isGoal) {
'z'.toElevation()
} else {
c.toElevation()
}
val n =
Node(
id = id,
char = c,
start = isStart,
goal = isGoal,
elevation = elevation,
neighbours = mutableMapOf()
)
id++
map[Coordinate(x, y)] = n
}
}
map.forEach { (coordinate, node) ->
Direction.values().forEach { direction ->
val neighbour = map[coordinate.step(direction)]
if (neighbour != null) {
if (neighbour.elevation <= (node.elevation + 1)) {
node.neighbours[direction] = neighbour
}
}
}
}
val path = if (!partTwo) {
breathFirstSearch(map.values.first { it.start })!!
} else {
map.values.filter { it.elevation == 0 }
.map {
breathFirstSearch(it)
}
.filterNotNull()
.minBy { it.size }
}
return (path.size - 1).toString()
}
private fun getPath(cameFrom: MutableMap<Node, Node>, goal: Node, start: Node): List<Node> {
var curr = goal
val path = mutableListOf(curr)
while (curr != start) {
curr = cameFrom[curr]!!
path.add(curr)
}
return path
}
private fun breathFirstSearch(start: Node): List<Node>? {
val cameFrom = mutableMapOf<Node, Node>()
val openSet = mutableListOf(start)
val explored = mutableSetOf(start)
while (openSet.isNotEmpty()) {
val curr = openSet.removeFirst()
if (curr.goal) {
return getPath(cameFrom, curr, start)
}
for (n in curr.neighbours.values) {
if (explored.contains(n)) {
continue
}
explored.add(n)
cameFrom[n] = curr
openSet.add(n)
}
}
return null
}
}
| 0 | Kotlin | 0 | 2 | 6c9b24de2fe2a36346cb4c311c7a5e80bf505f9e | 3,418 | Advent-of-Code-2022 | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.