path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2021/src/Day07.kt | Bajena | 433,856,664 | false | {"Kotlin": 65121, "Ruby": 14942, "Rust": 1698, "Makefile": 454} | import kotlin.math.abs
// https://adventofcode.com/2021/day/7
fun main() {
fun part1() {
var crabPositions = listOf<Int>()
for (line in readInput("Day07")) {
crabPositions = line.split(",").map { it.toInt() }.sorted()
}
println(crabPositions.size)
var minSum = Int.MAX_VALUE
var result = 0
val min = crabPositions.minOrNull()!!
val max = crabPositions.maxOrNull()!!
for (i in min..max) {
var sum = 0
for (position in crabPositions) {
sum += abs(position - i)
}
if (sum < minSum) {
minSum = sum
result = i
}
println("Result for position $i is $sum. Current min is $minSum")
}
println(result)
println(minSum)
}
fun part2() {
var crabPositions = listOf<Int>()
for (line in readInput("Day07")) {
crabPositions = line.split(",").map { it.toInt() }.sorted()
}
println(crabPositions.size)
var minSum = Int.MAX_VALUE
var result = 0
val min = crabPositions.minOrNull()!!
val max = crabPositions.maxOrNull()!!
for (i in min..max) {
var sum = 0
for (position in crabPositions) {
val distance = abs(position - i)
sum += distance * (distance + 1) / 2
}
if (sum < minSum) {
minSum = sum
result = i
}
println("Result for position $i is $sum. Current min is $minSum")
}
println(result)
println(minSum)
}
part1()
part2()
}
| 0 | Kotlin | 0 | 0 | a5ca56b7ac8d9d48f82dc079c8ea0cf06d17109a | 1,469 | advent-of-code | Apache License 2.0 |
src/main/kotlin/days/Day03.kt | julia-kim | 435,257,054 | false | {"Kotlin": 15771} | package days
import readInput
fun main() {
fun part1(input: List<String>): Long {
var gammaRate = ""
var epsilonRate = ""
var i = 0
while (i < input[0].length) {
val bits = input.map { it[i] }.groupingBy { it }.eachCount()
gammaRate += bits.maxByOrNull { it.value }!!.key
epsilonRate += bits.minByOrNull { it.value }!!.key
i++
}
val powerConsumption = gammaRate.toLong(2) * epsilonRate.toLong(2)
return powerConsumption
}
fun part2(input: List<String>): Long {
var oxygenGeneratorRating = input
var co2ScrubberRating = input
var i = 0
while (oxygenGeneratorRating.size > 1) {
val bits = oxygenGeneratorRating.map { it[i] }
val zeroCount = bits.count { it == '0' }
val oneCount = bits.count { it == '1' }
oxygenGeneratorRating = if (zeroCount <= oneCount) {
oxygenGeneratorRating.filter { it[i] == '0' }
} else {
oxygenGeneratorRating.filter { it[i] == '1' }
}
i++
}
var j = 0
while (co2ScrubberRating.size > 1) {
val bits = co2ScrubberRating.map { it[j] }
val zeroCount = bits.count { it == '0' }
val oneCount = bits.count { it == '1' }
co2ScrubberRating = if (zeroCount > oneCount) {
co2ScrubberRating.filter { it[j] == '0' }
} else {
co2ScrubberRating.filter { it[j] == '1' }
}
j++
}
val lifeSupportRating = oxygenGeneratorRating[0].toLong(2) * co2ScrubberRating[0].toLong(2)
return lifeSupportRating
}
val testInput = readInput("Day03_test")
check(part1(testInput) == 198L)
check(part2(testInput) == 230L)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 5febe0d5b9464738f9a7523c0e1d21bd992b9302 | 1,946 | advent-of-code-2021 | Apache License 2.0 |
src/day05/day05.kt | tmikulsk1 | 573,165,106 | false | {"Kotlin": 25281} | package day05
import readInput
fun main() {
val inputFile = readInput("day05/input.txt").readLines()
val indexReference = inputFile.indexOf("")
val commands = getCommandsForStackMoves(inputFile, indexReference)
val arrayStacksForPuzzle1 = getSupplyStacks(inputFile, indexReference)
getPuzzle1TopStackFromEachColumn(commands, arrayStacksForPuzzle1)
val arrayStacksForPuzzle2 = getSupplyStacks(inputFile, indexReference)
getPuzzle2TopStackFromEachColumn(commands, arrayStacksForPuzzle2)
}
/**
* Puzzle 1: get top from column
*/
fun getPuzzle1TopStackFromEachColumn(
commands: List<List<Int>>,
arrayStacks: MutableList<MutableList<String>>
) {
val movedStacks = moveStacksAccordingToCommands(
commands,
arrayStacks,
shouldChangePileOrder = false
)
println("Formed word from puzzle 1: " + movedStacks.getTopFromEachColumn())
}
/**
* Puzzle 2: get top from column with reversed pile order
*/
fun getPuzzle2TopStackFromEachColumn(
commands: List<List<Int>>,
arrayStacks: MutableList<MutableList<String>>
) {
val movedStacks = moveStacksAccordingToCommands(
commands,
arrayStacks,
shouldChangePileOrder = true
)
println("Formed word from puzzle 2: " + movedStacks.getTopFromEachColumn())
}
fun List<List<String>>.getTopFromEachColumn(): String {
var word = ""
forEach { column ->
word += column.first()
}
return word
}
fun moveStacksAccordingToCommands(
commands: List<List<Int>>,
arrayStacks: MutableList<MutableList<String>>,
shouldChangePileOrder: Boolean
): MutableList<MutableList<String>> {
commands.forEach { command ->
val quantity = command[0]
val from = command[1] - 1
val to = command[2] - 1
val removedPart = arrayStacks[from].subList(0, quantity)
val keptPart = arrayStacks[from].subList(quantity, arrayStacks[from].size)
val stackToMove = if (shouldChangePileOrder) removedPart else removedPart.reversed()
arrayStacks[to].addAll(0, stackToMove)
arrayStacks[from] = keptPart
}
return arrayStacks
}
fun getSupplyStacks(
inputStacks: List<String>,
indexReferenceForInputSplit: Int
): MutableList<MutableList<String>> {
val fullSupplyStack = inputStacks.subList(0, indexReferenceForInputSplit).toMutableList()
val sizeForArray = fullSupplyStack.removeLast().toSet().getSizeFromDigitElements()
val supplyStackArray = MutableList<MutableList<String>>(sizeForArray) {
mutableListOf()
}
fullSupplyStack.forEach { topFromStacks ->
val singleStack = topFromStacks.chunked(4)
singleStack.forEachIndexed { index, stack ->
supplyStackArray[index].add(stack)
}
}
return supplyStackArray.removeUnnecessaryCharsFromStacks()
}
fun MutableList<MutableList<String>>.removeUnnecessaryCharsFromStacks() = map { stack ->
stack.asSequence()
.map(String::removeBracketsAndSpaces)
.mapNotNull(String::replaceEmptyForNull)
.toMutableList()
}.toMutableList()
fun String.removeBracketsAndSpaces(): String {
return replace(oldValue = " ", newValue = "")
.replace(oldValue = "[", newValue = "")
.replace(oldValue = "]", newValue = "")
}
fun String.replaceEmptyForNull() = ifEmpty { return@ifEmpty null }
fun Set<Char>.getSizeFromDigitElements() = filter(Char::isDigit).size
fun getCommandsForStackMoves(
inputStacks: List<String>,
indexReferenceForInputSplit: Int
): List<List<Int>> {
val commandsInput = inputStacks.subList(indexReferenceForInputSplit + 1, inputStacks.size)
return commandsInput.removeUnnecessaryWordsFromCommands()
}
fun List<String>.removeUnnecessaryWordsFromCommands(): List<List<Int>> = map(String::removeWords)
.map(String::splitBySpaces)
.map { commands ->
commands.toList().mapNotNull { command ->
command.replaceEmptyForNull()?.toInt()
}
}
fun String.removeWords(): String {
return replace(oldValue = "move", newValue = "")
.replace(oldValue = "from", newValue = "")
.replace(oldValue = "to", newValue = "")
}
fun String.splitBySpaces(): List<String> {
return split(" ")
}
| 0 | Kotlin | 0 | 1 | f5ad4e601776de24f9a118a0549ac38c63876dbe | 4,241 | AoC-22 | Apache License 2.0 |
src/main/kotlin/days/Day8.kt | jgrgt | 433,952,606 | false | {"Kotlin": 113705} | package days
class Day8 : Day(8) {
// 0: abcefg
// 1: cf
// 2: acdeg
// 3: acdfg
// 4: bcdf
// 5: abdfg
// 6: abdefg
// 7: acf
// 8: abcdefg
// 9: abcdfg
val sevenDigit = mapOf(
"abcefg" to 0,
"cf" to 1,
"acdeg" to 2,
"acdfg" to 3,
"bcdf" to 4,
"abdfg" to 5,
"abdefg" to 6,
"acf" to 7,
"abcdefg" to 8,
"abcdfg" to 9,
)
override fun runPartOne(lines: List<String>): Any {
val easyDigitSizes = listOf(2, 4, 3, 7)
return lines.map { line ->
val (_, digits) = line.split("|").map { it.trim() }
val digitStrings = digits.split(" ").map { it.trim() }
digitStrings.count { easyDigitSizes.contains(it.length) }
}.sum()
}
override fun runPartTwo(lines: List<String>): Any {
return lines.sumOf { line ->
val (signal, digits) = line.split("|").map { it.trim() }
val digitStrings = digits.split(" ").map { it.trim() }
val mapping = decode(signal)
val translated = digitStrings.map { translate(it, mapping) }
1000 * translated[0] + 100 * translated[1] + 10 * translated[2] + translated[3]
}
}
fun translate(digit: String, mapping: List<Char>) : Int {
val key = digit.toCharArray().map { inverseMap(it, mapping) }.sorted().joinToString("")
return sevenDigit[key]!!
}
fun inverseMap(c: Char, mapping: List<Char>) : Char {
val index = mapping.indexOf(c)
return Char('a'.code + index)
}
fun decode(signal: String): List<Char> {
val signals = signal.split(" ").map { it.trim() }
val possibilities = Possibilities()
// 1 cf
val one = signals.find { it.length == 2 }!!
val oneChars = one.toCharArray().toList()
possibilities.registerPossibilities('c', oneChars)
possibilities.registerPossibilities('f', oneChars)
// 4 bcdf
val four = signals.find { it.length == 4 }!!
val fourChars = four.toCharArray().toList()
possibilities.registerPossibilities('b', fourChars)
possibilities.registerPossibilities('c', fourChars)
possibilities.registerPossibilities('d', fourChars)
possibilities.registerPossibilities('f', fourChars)
// 7 acf
val seven = signals.find { it.length == 3 }!!
val sevenChars = seven.toCharArray().toList()
possibilities.registerPossibilities('a', sevenChars)
possibilities.registerPossibilities('c', sevenChars)
possibilities.registerPossibilities('f', sevenChars)
// F is the character that occurs 9 times
val occurences = occurences(signals)
val fIndex = occurences.indexOf(9)
val chars = listOf('a', 'b', 'c', 'd', 'e', 'f', 'g')
val fMapping = chars[fIndex]
possibilities.registerPossibilities('f', listOf(fMapping))
// E is the character that occurs 4 times
val eIndex = occurences.indexOf(4)
val eMapping = chars[eIndex]
possibilities.registerPossibilities('e', listOf(eMapping))
// B is the character that occurs 6 times
val bIndex = occurences.indexOf(6)
val bMapping = chars[bIndex]
possibilities.registerPossibilities('b', listOf(bMapping))
// Now we should be able to figure it out
return possibilities.solve()
}
fun occurences(signals: List<String>): List<Int> {
val occurences = MutableList(7) { 0 }
signals.forEach { signal ->
signal.chars().forEach { c ->
val index = c - 'a'.code
occurences[index] = occurences[index] + 1
}
}
return occurences.toList()
}
}
class Possibilities {
private val state = MutableList(7) {
MutableList(7) { true } // true means possible
}
fun registerPossibilities(c: Char, options: List<Char>) {
val inv = inverse(options)
inv.forEach {
disable(c, it)
}
}
private fun disable(c: Char, o: Char) {
disable(toIndex(c), toIndex(o))
}
private fun disable(c: Int, o: Int) {
state[c][o] = false
}
private fun inverse(options: List<Char>): List<Char> {
val candidates = mutableListOf('a', 'b', 'c', 'd', 'e', 'f', 'g')
candidates.removeAll(options)
return candidates
}
private fun toIndex(c: Char): Int {
return c.code - 'a'.code
}
fun solve(): List<Char> {
repeat(7) { // 7 times should be enough to settle things down?
checkRows()
checkColumns()
}
return (0..6).map { c ->
val o = state[c].indexOf(true)
toChar(o)
}
}
private fun checkColumns() {
(0..6).forEach { i ->
val mapping = (0..6).map { state[it][i] }
val sure = mapping.count { it } == 1
if (sure) {
val c = mapping.indexOf(true)
registerPossibilities(toChar(c), listOf(toChar(i)))
}
}
}
private fun toChar(c: Int): Char {
return Char(c + 'a'.code)
}
private fun checkRows() {
(0..6).forEach { i ->
val mapping = state[i]
val sure = mapping.count { it } == 1
if (sure) {
val o = mapping.indexOf(true)
(0..6).forEach { otherI ->
if (i != otherI) {
disable(otherI, o)
}
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | 6231e2092314ece3f993d5acf862965ba67db44f | 5,661 | aoc2021 | Creative Commons Zero v1.0 Universal |
src/Day07.kt | sjgoebel | 573,578,579 | false | {"Kotlin": 21782} | fun main() {
fun part1(input: List<String>): Int {
val directory = Folder("/", null)
var current = directory
for (line in input)
{
val commands = line.split(" ")
if (commands[0] == "$")
{
if (commands[1] == "cd") {
for (item in current.contents) {
if ((item.name == commands[2])) {
current = item as Folder
break
}
}
if (commands[2] == "..") {
if (current.parent != null) {
current = current.parent!! as Folder
}
}
}
}
else
{
if (commands[0] == "dir") {
current.contents.add(Folder(commands[1], current))
} else {
current.contents.add(File(commands[1], commands[0].toInt(), current))
}
}
//println(current.value)
}
//println(directory)
val sizes = mutableListOf<Int>()
fun recordFolderSize(item: DirectoryItem): Int {
if (item is Folder) {
var total = 0
for (content in item.contents) {
if (content is Folder) {
total += recordFolderSize(content)
} else {
total += content.sizeOf()
}
}
sizes.add(total)
return total
} else {
return item.sizeOf()
}
}
recordFolderSize(directory)
//sizes.add(sizes.sum())
//println(sizes)
val result = sizes.filter{it <= 100000}.sum()
//println(result)
return result
}
fun part2(input: List<String>): Int {
val directory = Folder("/", null)
var current = directory
for (line in input)
{
val commands = line.split(" ")
if (commands[0] == "$")
{
if (commands[1] == "cd") {
for (item in current.contents) {
if ((item.name == commands[2])) {
current = item as Folder
break
}
}
if (commands[2] == "..") {
if (current.parent != null) {
current = current.parent!! as Folder
}
}
}
}
else
{
if (commands[0] == "dir") {
current.contents.add(Folder(commands[1], current))
} else {
current.contents.add(File(commands[1], commands[0].toInt(), current))
}
}
//println(current.value)
}
//println(directory)
val sizes = mutableListOf<Int>()
fun recordFolderSize(item: DirectoryItem): Int {
if (item is Folder) {
var total = 0
for (content in item.contents) {
if (content is Folder) {
total += recordFolderSize(content)
} else {
total += content.sizeOf()
}
}
sizes.add(total)
return total
} else {
return item.sizeOf()
}
}
recordFolderSize(directory)
val spaceleft = 70000000 - sizes.last()
//sizes.add(sizes.sum())
//println(spaceleft)
val result = sizes.filter{it >= 30000000 - spaceleft}.min()
//println(result)
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
abstract class DirectoryItem(val name: String) {
abstract fun sizeOf(): Int
}
data class Folder(val n:String, val parent: DirectoryItem?) : DirectoryItem(n) {
var contents: MutableList<DirectoryItem> = mutableListOf()
override fun sizeOf(): Int {
var result = 0
for (item in contents) {
result += item.sizeOf()
}
return result
}
}
data class File(val n: String, val size: Int, val parent: DirectoryItem) : DirectoryItem(n) {
override fun sizeOf(): Int {
return size
}
}
| 0 | Kotlin | 0 | 0 | ae1588dbbb923dbcd4d19fd1495ec4ebe8f2593e | 4,781 | advent-of-code-2022-kotlin | Apache License 2.0 |
kotlin/0912-sort-an-array.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} | /*
* Merge sort
*/
class Solution {
fun sortArray(nums: IntArray): IntArray {
mergeSort(nums, 0, nums.lastIndex)
return nums
}
private fun mergeSort(nums: IntArray, left: Int, right: Int) {
if(left == right) return
val mid = (left + right) / 2
mergeSort(nums, left, mid)
mergeSort(nums, mid + 1, right)
merge(nums, left, mid, right)
return
}
private fun merge(nums: IntArray, left: Int, mid: Int, right: Int) {
val leftPart = nums.copyOfRange(left, mid + 1)
val rightPart = nums.copyOfRange(mid + 1, right + 1)
var i = left
var j = 0
var k = 0
while(j < leftPart.size && k < rightPart.size) {
if(leftPart[j] <= rightPart[k]) {
nums[i] = leftPart[j]
j++
}else{
nums[i] = rightPart[k]
k++
}
i++
}
while(j < leftPart.size) {
nums[i] = leftPart[j]
j++
i++
}
while(k < rightPart.size) {
nums[i] = rightPart[k]
k++
i++
}
}
}
/*
* Quick sort
*/
class Solution {
fun sortArray(nums: IntArray): IntArray {
quickSort(nums, 0, nums.lastIndex)
return nums
}
private fun quickSort(nums: IntArray, low: Int, high: Int) {
if (low < high) {
val pivotIndex = partition(nums, low, high)
quickSort(nums, low, pivotIndex - 1)
quickSort(nums, pivotIndex + 1, high)
}
}
private fun partition(nums: IntArray, low: Int, high: Int): Int {
val r = (low..high).random()
nums.swap(r, high)
val pivot = nums[high]
var i = low
for (j in low until high) {
if (nums[j] <= pivot) {
nums.swap(i, j)
i++
}
}
nums.swap(i, high)
return i
}
fun IntArray.swap(i: Int, j: Int) {
this[i] = this[j].also { this[j] = this[i] }
}
}
/*
* Heap sort
*/
class Solution {
fun sortArray(nums: IntArray): IntArray {
heapSort(nums)
return nums
}
private fun heapSort(nums: IntArray) {
val n = nums.size
for(i in (n/2 - 1) downTo 0)
heapify(nums, n, i)
for(i in n-1 downTo 0) {
nums.swap(0, i)
heapify(nums, i, 0)
}
}
private fun heapify(nums: IntArray, n: Int, i: Int) {
var largest = i
val left = 2 * i + 1
val right = 2 * i + 2
if(left < n && nums[left] > nums[largest])
largest = left
if(right < n && nums[right] > nums[largest])
largest = right
if(largest != i) {
nums.swap(i, largest)
heapify(nums, n, largest)
}
}
fun IntArray.swap(i: Int, j: Int) {
this[i] = this[j].also{ this[j] = this[i] }
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 3,040 | leetcode | MIT License |
kotlin/0139-word-break.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} | //DP
class Solution {
fun wordBreak(s: String, wordDict: List<String>): Boolean {
val cache = BooleanArray (s.length + 1).apply {
this[s.length] = true
}
for (i in s.lastIndex downTo 0) {
for (word in wordDict) {
if (word.length + i <= s.length) {
if (word == s.substring(i, i + word.length)) {
if (cache[i + word.length] == true)
cache[i] = true
}
}
}
}
return cache[0]
}
}
//Recursive + memoization
class Solution {
fun wordBreak(s: String, wordDict: List<String>): Boolean {
val cache = IntArray (s.length + 1) { -1 }
fun dfs(i: Int): Int {
if (i == s.length) return 1
if (cache[i] != -1) return cache[i]
cache[i] = 0
for (word in wordDict) {
if (word.length + i <= s.length &&
word == s.substring(i, i + word.length)) {
if (dfs(i + word.length) == 1) {
cache[i] = 1
return 1
}
}
}
return 0
}
return if (dfs(0) == 1) true else false
}
}
//trie
class Solution {
class TrieNode {
val child = arrayOfNulls<TrieNode>(26)
var isEnd = false
}
fun wordBreak(s: String, wordDict: List<String>): Boolean {
var root: TrieNode? = TrieNode()
for (word in wordDict) {
var cur = root
for (c in word) {
if(cur?.child?.get(c - 'a') == null)
cur?.child?.set(c - 'a', TrieNode())
cur = cur?.child?.get(c - 'a')
}
cur?.isEnd = true
}
val dp = BooleanArray (s.length + 1).apply { this[0] = true }
for (i in 0 until s.length) {
if (dp[i] == false) continue
var j = i
var cur = root
while (j < s.length && cur?.child?.get(s[j] - 'a') != null) {
cur = cur?.child?.get(s[j++] - 'a')
if (cur?.isEnd == true)
dp[j] = true
}
}
return dp[s.length]
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 2,320 | leetcode | MIT License |
src/Day01.kt | MarkTheHopeful | 572,552,660 | false | {"Kotlin": 75535} | import kotlin.math.max
fun main() {
fun part1(input: List<String>): Int {
return input.fold(Pair(0, 0)) { maxAndSum, element ->
if (element.isBlank()) Pair(max(maxAndSum.first, maxAndSum.second), 0)
else Pair(maxAndSum.first, maxAndSum.second + element.toInt())
}.first
}
fun part2(input: List<String>): Int {
return input.fold(mutableListOf(0)) { list, element ->
if (element.isBlank()) {
list.add(0)
list
} else {
list[list.size - 1] += element.toInt()
list
}
}.sortedWith(reverseOrder()).take(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8218c60c141ea2d39984792fddd1e98d5775b418 | 963 | advent-of-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/dev/bogwalk/batch7/Problem76.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch7
/**
* Problem 76: Counting Summations
*
* https://projecteuler.net/problem=76
*
* Goal: Count the number of ways (mod 1e9 + 7) that N can be written as a sum of at least 2
* positive integers.
*
* Constraints: 2 <= N <= 1000
*
* e.g.: N = 5
* count = 6 -> {4+1, 3+2, 3+1+1, 2+2+1, 2+1+1+1, 1+1+1+1+1}
*/
class CountingSummations {
/**
* Solution is identical to the bottom-up approach that found the number of ways a total could
* be achieved using coins of different values (Batch 3 - Problem 31).
*
* The amount of ways to sum [n] is determined using the previous amount calculated for a sum
* of lesser value and the previous amount calculated for the partition of [n].
*
* N.B. The final value at index[n] returns the correct result but every value in preceding
* indices will be off by 1, as they include the sum itself alone (which is not valid given the
* constraints require a minimum of 2 positive integers). So if this solution is used to
* generate all counts <= 1000 for quick-pick testing, the array must be of size 1002 & the
* loop limits must be 1001, then all results can be found by subtracting 1 from the stored
* value.
*
* SPEED (using BigInteger) 68.00ms for N = 1e3
* SPEED (using Long) 18.45ms for N = 1e3
* N.B. The original solution used BigInteger to calculate & store counts. This was replaced
* with Long values & performing modulus after every summation, resulting in a ~4x speed boost.
*/
fun countSumCombos(n: Int): Int {
val modulus = 1_000_000_007L
val combosBySum = LongArray(n + 1) { 0L }.apply { this[0] = 1L }
for (i in 1 until n) {
for (j in i..n) {
combosBySum[j] += combosBySum[j - i]
combosBySum[j] %= modulus
}
}
return combosBySum[n].toInt()
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 1,934 | project-euler-kotlin | MIT License |
day9/src/main/kotlin/com/nohex/aoc/day9/MeasureCalculator.kt | mnohe | 433,396,563 | false | {"Kotlin": 105740} | package com.nohex.aoc.day9
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.runBlocking
/**
* Methods to apply calculations to a set of height measurements.
*/
class MeasureCalculator(private val measures: Set<Measure>) {
/**
* Finds risk levels, i.e. the lowest points' heights, plus one.
*/
fun findRiskLevels(): Flow<Int> =
findLowPoints().transform { emit(it.height + 1) }
/**
* Finds risk levels, i.e. the values that are the lowest among their neighbours, plus one.
* The
*/
private fun findLowPoints(): Flow<Measure> = flow {
measures
.filter { isLowPoint(it) }
.forEach { emit(it) }
}
/**
* Finds out whether the given measurement's height is the lowest among its neighbours.
*/
private fun isLowPoint(measure: Measure) = measure.neighbours
.filterIsInstance<Measure>()
.all { it.height > measure.height }
/**
* Multiplies the sizes of the three largest basins.
*/
fun getTop3BasinSizeProduct(): Int = runBlocking {
findLowPoints()
.map { calculateBasinSize(it) }
.toList()
.sortedDescending()
.take(3)
.reduce { acc, i -> acc * i }
}
/**
* For the given [measure], find all contiguous measures whose height is lower than 9.
*/
private fun calculateBasinSize(measure: Measure): Int {
val visited = mutableSetOf<Measure>()
// Find neighbours whose height is lower than 9.
return countNeighbours(visited, measure) { it.height < 9 }
}
/**
* Recursively counts the [measure]'s neighbours that meet the [condition].
*/
private fun countNeighbours(
visited: MutableSet<Measure>, measure: Measure, condition: (Measure) -> Boolean
): Int {
// If the condition is not fulfilled,
// or the measure was already visited,
// return nothing.
if (!condition(measure) || (measure in visited)) return 0
visited.add(measure)
// Return all applicable neighbours plus the current measure.
return measure.neighbours
.filterIsInstance<Measure>()
.sumOf { countNeighbours(visited, it, condition) } + 1
}
}
| 0 | Kotlin | 0 | 0 | 4d7363c00252b5668c7e3002bb5d75145af91c23 | 2,284 | advent_of_code_2021 | MIT License |
src/main/kotlin/Day07.kt | attilaTorok | 573,174,988 | false | {"Kotlin": 26454} | open class Directory(
val name: String, val parent: Directory?, val children: MutableList<Directory> = mutableListOf(), var size: Long = 0
) {
fun calculateSize() {
for (child in children) {
size += child.size
}
}
}
fun main() {
fun createFileHierarchy(fileName: String): Directory {
val root = Directory("root", null)
readInputWithStream(fileName).useLines {
val iterator = it.iterator()
iterator.next()
iterator.next()
var currentNode = root
while (iterator.hasNext()) {
val line = iterator.next().split(" ")
if (line[0] == "$") {
if (line[1] == "cd") {
currentNode = if (line[2] == "..") {
currentNode.calculateSize()
currentNode.parent!!
} else {
currentNode.children.find { child -> child.name == line[2] }!!
}
}
} else {
if (line[0] == "dir") {
currentNode.children.add(Directory(line[1], currentNode))
} else {
currentNode.size += line[0].toLong()
}
}
}
var node: Directory? = currentNode
while (node != null) {
node.calculateSize()
node = node.parent
}
}
return root
}
fun part1(node: Directory, limit: Int): Long {
var result = 0L
if (node.size <= limit) {
result += node.size
}
for (child in node.children) {
result += part1(child, limit)
}
return result
}
fun findSmallestDirectoryWithEnoughSpace(node: Directory, lowerBound: Long, upperBound: Long): Long {
var result = node.size
for (child in node.children) {
if (child.size in lowerBound until upperBound) {
val childSize = findSmallestDirectoryWithEnoughSpace(child, lowerBound, child.size)
if (result > childSize) {
result = childSize
}
}
}
return result
}
fun part2(node: Directory): Long {
val neededDiskSpace = node.size - 40000000
return findSmallestDirectoryWithEnoughSpace(node, neededDiskSpace, node.size)
}
val testRoot = createFileHierarchy("Day07_test")
println("Test")
println("The directories with a total size of at most 100000 is 95437! Answer: ${part1(testRoot, 100000)}")
println(
"The smallest directory that, if deleted, would free up enough space on the" +
"filesystem to run the update is 24933642! Answer: ${part2(testRoot)}"
)
val root = createFileHierarchy("Day07")
println()
println("Exercise")
println("The directories with a total size of at most 100000 is 1513699! Answer: ${part1(root, 100000)}")
println(
"The smallest directory that, if deleted, would free up enough space on the" +
"filesystem to run the update is 7991939! Answer: ${part2(root)}"
)
} | 0 | Kotlin | 0 | 0 | 1799cf8c470d7f47f2fdd4b61a874adcc0de1e73 | 3,277 | AOC2022 | Apache License 2.0 |
src/main/kotlin/day17/solution.kt | bukajsytlos | 433,979,778 | false | {"Kotlin": 63913} | package day17
import java.io.File
import kotlin.math.abs
import kotlin.math.round
import kotlin.math.sqrt
fun main() {
val lines = File("src/main/kotlin/day17/input.txt").readLines()
val (x1, x2) = lines.first().substringAfter("target area: x=").substringBefore(", y=").split("..")
.map { it.toInt() }
val (y1, y2) = lines.first().substringAfter("y=").split("..").map { it.toInt() }
println(y1 * (y1 + 1) / 2)
val maxSteps = abs(2*y1)
val validSpeeds: MutableSet<Pair<Int, Int>> = mutableSetOf()
for (steps in 1..maxSteps) {
val minYSpeed = decrementalSpeed(y1, steps)
val maxYSpeed = decrementalSpeed(y2, steps)
val minXSpeed = decrementalSpeedWithFloor(x1, steps)
val maxXSpeed = decrementalSpeedWithFloor(x2, steps)
for (speedX in minXSpeed..maxXSpeed) {
for (speedY in minYSpeed..maxYSpeed) {
if (targetCoordinateY(speedY, steps) in y1..y2 && targetCoordinateX(speedX, steps) in x1..x2) {
validSpeeds.add(speedX to speedY)
}
}
}
}
println(validSpeeds.size)
}
fun targetCoordinateX(speed: Int, steps: Int): Int {
val coefficient = minOf(speed, steps)
return coefficient * speed - (coefficient - 1) * coefficient / 2
}
fun targetCoordinateY(speed: Int, steps: Int): Int = steps * speed - (steps - 1) * steps / 2
fun decrementalSpeed(targetCoordinate: Int, steps: Int): Int = (targetCoordinate.toDouble() / steps + (steps - 1).toDouble() / 2).toInt()
fun decrementalSpeedWithFloor(targetCoordinate: Int, steps: Int): Int {
val minXSpeedToReachCoordinate = minXSpeedToReach(targetCoordinate)
val speed = decrementalSpeed(targetCoordinate, steps)
return if (steps > minXSpeedToReachCoordinate) minXSpeedToReachCoordinate else speed
}
fun minXSpeedToReach(targetCoordinate: Int): Int = round(sqrt((targetCoordinate * 8 + 1).toDouble()) / 2 - 0.5).toInt() | 0 | Kotlin | 0 | 0 | f47d092399c3e395381406b7a0048c0795d332b9 | 1,950 | aoc-2021 | MIT License |
src/aoc2023/Day04.kt | dayanruben | 433,250,590 | false | {"Kotlin": 79134} | package aoc2023
import readInput
import checkValue
fun main() {
val (year, day) = "2023" to "Day04"
fun countMatches(cardLine: String): Int {
val (_, cards) = cardLine.split(": ")
val (win, mine) = cards.split("|").map { group ->
group.trim().split("\\s+".toRegex()).map { num ->
num.toInt()
}
}
val winSet = win.toSet()
return mine.count { it in winSet }
}
fun part1(input: List<String>): Int = input.sumOf { line ->
val matches = countMatches(line)
Math.pow(2.0, (matches - 1).toDouble()).toInt()
}
fun part2(input: List<String>): Int {
val cardCopies = IntArray(input.size) { 1 }
for ((index, line) in input.withIndex()) {
val matches = countMatches(line)
if (matches > 0) {
for (i in 1..matches) {
if (index + i >= cardCopies.size) break
cardCopies[index + i] += cardCopies[index]
}
}
}
return cardCopies.sum()
}
val testInput = readInput(name = "${day}_test", year = year)
val input = readInput(name = day, year = year)
checkValue(part1(testInput), 13)
println(part1(input))
checkValue(part2(testInput), 30)
println(part2(input))
} | 1 | Kotlin | 2 | 30 | df1f04b90e81fbb9078a30f528d52295689f7de7 | 1,332 | aoc-kotlin | Apache License 2.0 |
src/main/kotlin/be/swsb/aoc2021/day13/Day13.kt | Sch3lp | 433,542,959 | false | {"Kotlin": 90751} | package be.swsb.aoc2021.day13
import be.swsb.aoc2021.common.FoldInstruction
import be.swsb.aoc2021.common.Point
import be.swsb.aoc2021.common.Point.Companion.at
object Day13 {
fun solve1(input: List<String>): Int {
val (paper, instructions) = parse(input)
return paper.fold(instructions.take(1)).visibleDots
}
fun solve2(input: List<String>): String {
val (paper, instructions) = parse(input)
val foldedPaper = paper.fold(instructions)
return foldedPaper.asString()
}
fun parse(input: List<String>): Pair<Paper, List<FoldInstruction>> {
val foldInstructions = input.subList(input.indexOf("") + 1, input.size)
val paper = input.subList(0, input.indexOf(""))
return Paper(paper.map { Point.fromString(it) }.toSet()) to foldInstructions.map { it.parseToFold() }
}
}
data class Paper(private val dots: Set<Point>) {
val visibleDots: Int by lazy { dots.size }
private val dimension: Pair<Int, Int> = dots.maxOf { it.x } to dots.maxOf { it.y }
init {
println("Paper has dimension of ${dimension.first} by ${dimension.second}")
}
fun fold(instructions: List<FoldInstruction>): Paper =
instructions.fold(this) { acc, instruction -> acc.fold(instruction) }
fun fold(instruction: FoldInstruction) = instruction.run {
println("Folding $this. Middle axes: x ${dimension.first / 2}, y ${dimension.second / 2}")
Paper(dots.map { it.fold(this) }.toSet())
}
fun asString(): String {
return (0..dimension.second).joinToString("\n") { y ->
(0..dimension.first).joinToString("") { x ->
if (at(x,y) in dots) {
"◻️"
} else {
"◼️"
}
}
}
}
}
private fun String.parseToFold() = when {
contains("fold along y") -> FoldInstruction.Up(findInt())
contains("fold along x") -> FoldInstruction.Left(findInt())
else -> throw IllegalArgumentException("Could not parse $this into a FoldInstruction")
}
private fun String.findInt() = """\d+""".toRegex().find(this)?.value?.toInt()
?: throw IllegalArgumentException("Could not find a crease value in a fold along statement.") | 0 | Kotlin | 0 | 0 | 7662b3861ca53214e3e3a77c1af7b7c049f81f44 | 2,259 | Advent-of-Code-2021 | MIT License |
src/main/kotlin/day9/Day9.kt | Arch-vile | 317,641,541 | false | null | package day9
import readFile
fun pairCombinations(numbers: List<Long>): List<Pair<Long,Long>> =
numbers
.map { first ->
numbers.map { second ->
Pair(first, second)
}
}.flatten()
.filter { it.first !== it.second }
fun pairCombinationsSums(dropLast: List<Long>): List<Long> =
pairCombinations(dropLast).map { it.first + it.second }
fun main(args: Array<String>) {
val input = readFile("./src/main/resources/day9Input.txt")
.map { it.toLong() }
// Part 1
val part1Answer = input
.windowed(26)
.filter {
!pairCombinationsSums(it.dropLast(1)).contains(it[25])
}
.map { it[25] }
.first()
println(part1Answer)
// Part 2
val part2Answer = (2 until input.size).asSequence()
.map {
input.windowed(it)
.firstOrNull() { window -> window.sum() == part1Answer }
?.let { matchingWindow ->
matchingWindow.minOrNull()!! + matchingWindow.maxOrNull()!!
}
}
.filterNotNull()
.first()
println(part2Answer)
}
| 0 | Kotlin | 0 | 0 | 12070ef9156b25f725820fc327c2e768af1167c0 | 1,044 | adventOfCode2020 | Apache License 2.0 |
advent-of-code2016/src/main/kotlin/day07/Advent7.kt | REDNBLACK | 128,669,137 | false | null | package day07
import chunk
import parseInput
import splitToLines
/**
--- Day 7: Internet Protocol Version 7 ---
While snooping around the local network of EBHQ, you compile a list of IP addresses (they're IPv7, of course; IPv6 is much too limited). You'd like to figure out which IPs support TLS (transport-layer snooping).
An IP supports TLS if it has an Autonomous Bridge Bypass Annotation, or ABBA. An ABBA is any four-character sequence which consists of a pair of two different characters followed by the reverse of that pair, such as xyyx or abba. However, the IP also must not have an ABBA within any hypernet sequences, which are contained by square brackets.
For example:
abba[mnop]qrst supports TLS (abba outside square brackets).
abcd[bddb]xyyx does not support TLS (bddb is within square brackets, even though xyyx is outside square brackets).
aaaa[qwer]tyui does not support TLS (aaaa is invalid; the interior characters must be different).
ioxxoj[asdfgh]zxcvbn supports TLS (oxxo is outside square brackets, even though it's within a larger string).
How many IPs in your puzzle input support TLS?
--- Part Two ---
You would also like to know which IPs support SSL (super-secret listening).
An IP supports SSL if it has an Area-Broadcast Accessor, or ABA, anywhere in the supernet sequences (outside any square bracketed sections), and a corresponding Byte Allocation Block, or BAB, anywhere in the hypernet sequences. An ABA is any three-character sequence which consists of the same character twice with a different character between them, such as xyx or aba. A corresponding BAB is the same characters but in reversed positions: yxy and bab, respectively.
For example:
aba[bab]xyz supports SSL (aba outside square brackets with corresponding bab within square brackets).
xyx[xyx]xyx does not support SSL (xyx, but no corresponding yxy).
aaa[kek]eke supports SSL (eke in supernet with corresponding kek in hypernet; the aaa sequence is not related, because the interior character must be different).
zazbz[bzb]cdb supports SSL (zaz has no corresponding aza, but zbz has a corresponding bzb, even though zaz and zbz overlap).
How many IPs in your puzzle input support SSL?
*/
fun main(args: Array<String>) {
val test = """abba[mnop]qrst
|abcd[bddb]xyyx
|aaaa[qwer]tyui
|ioxxoj[asdfgh]zxcvbn""".trimMargin()
val test2 = """aba[bab]xyz
|xyx[xyx]xyx
|aaa[kek]eke
|zazbz[bzb]cdb""".trimMargin()
val input = parseInput("day7-input.txt")
println(findSupportingTLS(test).size == 2)
println(findSupportingTLS(input).size)
println(finsSupportingSSL(test2).size == 3)
println(finsSupportingSSL(input).size)
}
fun findSupportingTLS(input: String) = parseIP(input).filter(IP::supportsTLS)
fun finsSupportingSSL(input: String) = parseIP(input).filter(IP::supportsSSL)
data class IP(val sequences: List<String>, val hypernet: List<String>) {
fun supportsTLS() = !hypernet.any { it.hasRepeating(4) } && sequences.any { it.hasRepeating(4) }
fun supportsSSL() = sequences.filter { it.hasRepeating(3) }
.filter { aba -> hypernet.any { compare(it, aba, 3) } }
.isNotEmpty()
private fun String.hasRepeating(length: Int) = chunk(length).any {
it == it.reversed() && it.toCharArray().distinct().size > 1
}
private fun compare(str1: String, str2: String, length: Int): Boolean {
val first = str1.chunk(length)
val second = str2.chunk(length).map { if (it[0] == it[2]) it[1].toString() + it[0] + it[1] else "" }
return first.any { it in second }
}
}
private fun parseIP(input: String) = input.splitToLines()
.map {
val pattern = Regex("""\[([^\]]+)\]""")
val hypernets = pattern.findAll(it).map { it.groupValues[1] }.toList()
val sequences = pattern.split(it)
IP(sequences, hypernets)
}
| 0 | Kotlin | 0 | 0 | e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7 | 3,977 | courses | MIT License |
src/test/kotlin/days/y2022/Day11Test.kt | jewell-lgtm | 569,792,185 | false | {"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123} | package days.y2022
import days.Day
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.core.Is.`is`
import org.junit.jupiter.api.Test
class Day11 : Day(2022, 11) {
override fun partOne(input: String): Any {
val monkeys = parseInput(input)
repeat(20) {
for (monkey in monkeys) {
monkey.round(monkeys, 3)
}
}
val (most, second) = monkeys.sortedByDescending { it.inspections }
return (most.inspections * second.inspections).toString()
}
override fun partTwo(input: String): Any {
val monkeys = parseInput(input)
val monkeyProduct = monkeys.map { it.test }.product()
repeat(10_000) {
for (monkey in monkeys) {
monkey.round(monkeys, 1, monkeyProduct)
}
}
val (most, second) = monkeys.sortedByDescending { it.inspections }
return (most.inspections * second.inspections).toString()
}
private fun List<ULong>.product() = this.fold(1uL) { acc, i -> acc * i }
private fun parseInput(input: String) = input.split("\n\n")
.map { monkeyStr ->
Monkey.from(monkeyStr.trimIndent().lines())
}
class Monkey(
val index: Int,
val items: MutableList<ULong>,
val operation: (ULong) -> ULong,
val test: ULong,
val ifTrueMonkeyIndex: Int,
val ifFalseMonkeyIndex: Int,
var inspections: ULong = 0uL
) {
fun round(monkeys: List<Monkey>, relief: Int, monkeyProduct: ULong? = null) {
items.indices.forEach { index ->
items[index] = operation(items[index])
items[index] = items[index] / relief.toULong()
if (monkeyProduct != null) items[index] = items[index] % monkeyProduct
if ((items[index]) % test == 0uL) {
monkeys[ifTrueMonkeyIndex].items.add(items[index])
} else {
monkeys[ifFalseMonkeyIndex].items.add(items[index])
}
}
inspections += items.size.toULong()
items.clear()
}
companion object {
fun from(lines: List<String>) = Monkey(
monkeyNumber(lines[0]),
monkeyItems(lines[1]).map { it.toULong() }.toMutableList(),
monkeyOperation(lines[2]),
monkeyNumber(lines[3]).toULong(),
monkeyNumber(lines[4]),
monkeyNumber(lines[5]),
)
private fun monkeyNumber(s: String): Int {
val found =
Regex("(\\d+)").find(s) ?: throw IllegalArgumentException("Could not find monkey number in $s")
return found.value.toInt()
}
private fun monkeyItems(s: String) =
Regex("(\\d+)").findAll(s).map { it.value.toInt() }.toList()
private fun monkeyOperation(s: String): (ULong) -> (ULong) {
if (s.contains("old * old")) {
return { old -> old * old }
}
val operand = monkeyNumber(s).toULong()
if (s.contains("*")) return { old -> old * operand }
if (s.contains("+")) return { old -> old + operand }
error("unknown operation $s")
}
}
}
}
class Day11Test {
val exampleInput = """
Monkey 0:
Starting items: 79, 98
Operation: new = old * 19
Test: divisible by 23
If true: throw to monkey 2
If false: throw to monkey 3
Monkey 1:
Starting items: 54, 65, 75, 74
Operation: new = old + 6
Test: divisible by 19
If true: throw to monkey 2
If false: throw to monkey 0
Monkey 2:
Starting items: 79, 60, 97
Operation: new = old * old
Test: divisible by 13
If true: throw to monkey 1
If false: throw to monkey 3
Monkey 3:
Starting items: 74
Operation: new = old + 3
Test: divisible by 17
If true: throw to monkey 0
If false: throw to monkey 1
""".trimIndent()
@Test
fun testExampleOne() {
assertThat(Day11().partOne(exampleInput), `is`("10605"))
}
@Test
fun testPartOne() {
assertThat(Day11().partOne(), `is`("55458"))
}
@Test
fun testExampleTwo() {
assertThat(
Day11().partTwo(exampleInput), `is`("2713310158")
)
}
@Test
fun testPartTwo() {
assertThat(Day11().partTwo(), `is`("14508081294"))
}
}
| 0 | Kotlin | 0 | 0 | b274e43441b4ddb163c509ed14944902c2b011ab | 4,511 | AdventOfCode | Creative Commons Zero v1.0 Universal |
calendar/day16/Day16.kt | rocketraman | 573,845,375 | false | {"Kotlin": 45660} | package day16
import Day
import Lines
class Day16 : Day() {
val INPUT_PATTERN = """^Valve (.+) has flow rate=(\d+); tunnels? leads? to valves? (.*)$""".toRegex()
sealed class PathElement {
abstract val node: String
}
data class Open(override val node: String): PathElement()
data class Move(override val node: String): PathElement()
class Djikstra(
val from: String,
val flowRates: Map<String, Int>,
val tunnels: Map<String, List<String>>,
) {
val unvisitedNodes = flowRates.keys.toMutableSet()
val paths = flowRates.keys
.associateWith { if (it == from) emptyList() else unvisitedNodes.toList() }
.toMutableMap()
var current = from
tailrec fun step() {
if (paths[current] == null) {
paths[current] = emptyList()
}
tunnels.getValue(current)
.filter { it in unvisitedNodes }
.forEach { tunnel ->
val pTunnel = paths.getValue(tunnel)
val pCurrent = paths.getValue(current)
if (pCurrent.size + 1 < pTunnel.size) {
paths[tunnel] = pCurrent + tunnel
}
}
// mark current node as visited
unvisitedNodes -= current
if (unvisitedNodes.none { flowRates.getValue(it) > 0 }) {
return
} else {
val minUnvisited = unvisitedNodes.minBy { paths[it]?.size ?: -1 }
current = minUnvisited
step()
}
}
}
override fun part1(input: Lines): Any {
val (flowRates, tunnels) = parseInput(input)
val (best, _) = solveForOneAgent(flowRates, tunnels, 30)
return best
}
override fun part2(input: Lines): Any {
val (flowRates, tunnels) = parseInput(input)
val (best, bestPath) = solveForOneAgent(flowRates, tunnels, 26)
// naiive solution: reset time to 0, and then have the elephant open additional valves
// create a new graph for the elephant, with the already opened valves set to a flow rate of 0 (then the
// "additional" score calculated for the elephant will be additive
// -- interestingly, I didn't think this would work because I didn't think this would be optimal, and in
// fact for the smaller sample problem, it actually does *not* work because the first agent has time to
// go and do stuff that the elephant would have done had they been operating simultaneously!
// However, for the larger actual problem it does work!
// I guess a proper solution would be track the state of each agent through the graph at each time
bestPath.filterIsInstance<Open>().forEach { v ->
flowRates[v.node] = 0
}
val (best2, _) = solveForOneAgent(flowRates, tunnels, 26)
return best + best2
}
fun parseInput(input: Lines): Pair<MutableMap<String, Int>, MutableMap<String, List<String>>> {
val flowRates = mutableMapOf<String, Int>()
val tunnels = mutableMapOf<String, List<String>>()
input.forEach { line ->
val (iv, f, ov) = INPUT_PATTERN.matchEntire(line)!!.destructured
flowRates[iv] = f.toInt()
tunnels[iv] = ov.split(", ")
}
return flowRates to tunnels
}
fun solveForOneAgent(
flowRates: MutableMap<String, Int>,
tunnels: MutableMap<String, List<String>>,
minutes: Int,
): Pair<Int, List<PathElement>> {
val nonZeroValves = flowRates.filter { it.value > 0 }
val valveShortestPaths = (nonZeroValves.keys + "AA").associateWith { v ->
Djikstra(v, flowRates, tunnels).apply { step() }.paths
}
fun List<PathElement>.isDone() = filterIsInstance<Open>().size >= nonZeroValves.size || size >= minutes
var best = 0
var bestPath: List<PathElement> = emptyList()
fun pathsFromNode(node: String, path: List<PathElement>, depth: Int) {
if (path.isDone()) {
// cost of path
val pressureReleased = calculatePath(path, minutes, flowRates)
if (pressureReleased > best) {
best = pressureReleased
bestPath = path
}
return
}
// possible moves now are to any of the unopened valves
nonZeroValves.keys.minus(path.filterIsInstance<Open>().map { it.node }.toSet()).forEach { v ->
// move to v from wherever we are
val next = valveShortestPaths[node]!![v]!!
pathsFromNode(v,path + (next.dropLast(1).map { Move(it) } + Move(next.last()) + Open(next.last())), depth + 1)
}
}
// interesting approach explained by <NAME> -- use Dynamic Programming (DP) to
// snapshot states, and then use previously computed answers for those states
// https://youtu.be/DgqkVDr1WX8?t=449
// interestingly, my solution runs faster in Kotlin than his does on C++, I guess because I am skipping
// all the zero-flow nodes and so my search space is way smaller, so it runs faster even without DP.
pathsFromNode("AA", emptyList(), 0)
return best to bestPath
}
fun calculatePath(path: List<PathElement>, maxMinutes: Int, flowRates: Map<String, Int>): Int {
val openedValves = mutableListOf<String>()
var pressureReleased = 0
for (minute in 1..maxMinutes) {
val pressureReleasedNow = openedValves.sumOf { flowRates.getValue(it) }
pressureReleased += pressureReleasedNow
val p = path.getOrNull(minute - 1)
if (p is Open) openedValves.add(p.node)
}
return pressureReleased
}
}
| 0 | Kotlin | 0 | 0 | 6bcce7614776a081179dcded7c7a1dcb17b8d212 | 5,326 | adventofcode-2022 | Apache License 2.0 |
src/Day24Part2.kt | schoi80 | 726,076,340 | false | {"Kotlin": 83778} | import Day24Part2.part2
import com.microsoft.z3.Context
import com.microsoft.z3.Model
import com.microsoft.z3.RatNum
import com.microsoft.z3.RealExpr
import com.microsoft.z3.Status
import java.math.BigDecimal
object Day24Part2 {
data class XYZ(
val x: Long,
val y: Long,
val z: Long,
)
data class Hailstone(
val pos: XYZ,
val vel: XYZ,
) {
companion object {
fun init(line: String): Hailstone {
val (pos, vel) = line.split("@", limit = 2)
return Hailstone(
pos = pos.split(",", limit = 3).map { it.trim().toLong() }.let { (x, y, z) -> XYZ(x, y, z) },
vel = vel.split(",", limit = 3).map { it.trim().toLong() }.let { (x, y, z) -> XYZ(x, y, z) },
)
}
}
}
fun Model.getVar(x: RealExpr): BigDecimal {
val xc = getConstInterp(x) as RatNum
return xc.bigIntNumerator.toBigDecimal().divide(xc.bigIntDenominator.toBigDecimal())
}
fun part2(input: List<String>): Long = with(Context()) {
val pvs = input.map { Hailstone.init(it) }
val solver = mkSolver()
val x = mkRealConst("x")
val y = mkRealConst("y")
val z = mkRealConst("z")
val vx = mkRealConst("vx")
val vy = mkRealConst("vy")
val vz = mkRealConst("vz")
// Create 3 time variables that are greater than 0
val t = listOf(
mkRealConst("t1"),
mkRealConst("t2"),
mkRealConst("t3")
).onEach { solver.add(mkGe(it, mkReal(0))) }
// 3 time variables must be different from each other
solver.add(mkNot(mkEq(t[0], t[1])))
solver.add(mkNot(mkEq(t[1], t[2])))
solver.add(mkNot(mkEq(t[0], t[2])))
// Just need 3 points to solve
pvs.take(3).forEachIndexed { i, h ->
solver.add(mkGe(t[i], mkReal(0))) // t > 0
val rockX = mkAdd(x, mkMul(vx, t[i]))
val rockY = mkAdd(y, mkMul(vy, t[i]))
val rockZ = mkAdd(z, mkMul(vz, t[i]))
val hX = mkAdd(mkReal(h.pos.x), mkMul(mkReal(h.vel.x), t[i]))
val hY = mkAdd(mkReal(h.pos.y), mkMul(mkReal(h.vel.y), t[i]))
val hZ = mkAdd(mkReal(h.pos.z), mkMul(mkReal(h.vel.z), t[i]))
solver.add(mkEq(rockX, hX))
solver.add(mkEq(rockY, hY))
solver.add(mkEq(rockZ, hZ))
}
if (solver.check() != Status.SATISFIABLE)
error("cannot happen")
val rx = solver.model.getVar(x).toLong()
val ry = solver.model.getVar(y).toLong()
val rz = solver.model.getVar(z).toLong()
println("Solved rock($rx, $ry, $rz)")
return rx + ry + rz
}
}
fun main() {
val input = readInput("Day24")
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | ee9fb20d0ed2471496185b6f5f2ee665803b7393 | 2,848 | aoc-2023 | Apache License 2.0 |
archive/153/solve.kt | daniellionel01 | 435,306,139 | false | null | /*
=== #153 Investigating Gaussian Integers - Project Euler ===
As we all know the equation x2=-1 has no solutions for real x.
If we however introduce the imaginary number i this equation has two solutions: x=i and x=-i.
If we go a step further the equation (x-3)2=-4 has two complex solutions: x=3+2i and x=3-2i.
x=3+2i and x=3-2i are called each others' complex conjugate.
Numbers of the form a+bi are called complex numbers.
In general a+bi and a−bi are each other's complex conjugate.
A Gaussian Integer is a complex number a+bi such that both a and b are integers.
The regular integers are also Gaussian integers (with b=0).
To distinguish them from Gaussian integers with b ≠ 0 we call such integers "rational integers."
A Gaussian integer is called a divisor of a rational integer n if the result is also a Gaussian integer.
If for example we divide 5 by 1+2i we can simplify $\dfrac{5}{1 + 2i}$ in the following manner:
Multiply numerator and denominator by the complex conjugate of 1+2i: 1−2i.
The result is $\dfrac{5}{1 + 2i} = \dfrac{5}{1 + 2i}\dfrac{1 - 2i}{1 - 2i} = \dfrac{5(1 - 2i)}{1 - (2i)^2} = \dfrac{5(1 - 2i)}{1 - (-4)} = \dfrac{5(1 - 2i)}{5} = 1 - 2i$.
So 1+2i is a divisor of 5.
Note that 1+i is not a divisor of 5 because $\dfrac{5}{1 + i} = \dfrac{5}{2} - \dfrac{5}{2}i$.
Note also that if the Gaussian Integer (a+bi) is a divisor of a rational integer n, then its complex conjugate (a−bi) is also a divisor of n.
In fact, 5 has six divisors such that the real part is positive: {1, 1 + 2i, 1 − 2i, 2 + i, 2 − i, 5}.
The following is a table of all of the divisors for the first five positive rational integers:
n Gaussian integer divisors
with positive real partSum s(n) of these
divisors111
21, 1+i, 1-i, 25
31, 34
41, 1+i, 1-i, 2, 2+2i, 2-2i,413
51, 1+2i, 1-2i, 2+i, 2-i, 512
For divisors with positive real parts, then, we have: $\sum \limits_{n = 1}^{5} {s(n)} = 35$.
For $\sum \limits_{n = 1}^{10^5} {s(n)} = 17924657155$.
What is $\sum \limits_{n = 1}^{10^8} {s(n)}$?
Difficulty rating: 65%
*/
fun solve(x: Int): Int {
return x*2;
}
fun main() {
val a = solve(10);
println("solution: $a");
} | 0 | Kotlin | 0 | 1 | 1ad6a549a0a420ac04906cfa86d99d8c612056f6 | 2,160 | euler | MIT License |
src/Day17.kt | astrofyz | 572,802,282 | false | {"Kotlin": 124466} | import java.io.File
fun main() {
class Point(var x: Int, var y: Int){}
class Shape(var points: MutableList<Point>){}
fun Shape.rightmost(): Int{
return this.points.map { it.x }.max()
}
fun Shape.leftmost(): Int{
return this.points.map { it.x }.min()
}
fun Shape.lowest(): Int{
return this.points.map { it.y }.min()
}
fun Shape.updateStart(floor: Int): Shape{
val leftref = this.leftmost()
val lowref = this.lowest()
for ((i, point) in this.points.withIndex()){
this.points[i] = Point(point.x-leftref+2, point.y-lowref+floor)
}
return this
}
fun Shape.updateJet(dir: Char, chamber: MutableList<MutableList<Int>>): Shape{
if ((dir == '>')&&(this.rightmost() < 6)) {
// println("$dir ${this.points.map { chamber[it.y][it.x + 1] == 0}.toList().count{it}} ${this.points.size}")
if (this.points.map { chamber[it.y][it.x + 1] == 0 }.toList().count{it} == this.points.size) {
for ((i, point) in this.points.withIndex()) {
this.points[i] = Point(point.x + 1, point.y)
}
return this
}
else return this
}
else if ((dir == '<')&&(this.leftmost() > 0)){
// println("$dir ${this.points.map { chamber[it.y][it.x - 1] == 0 }.toList().count()} ${this.points.size}")
if (this.points.map { chamber[it.y][it.x - 1] == 0 }.toList().count{it} == this.points.size) {
for ((i, point) in this.points.withIndex()) {
this.points[i] = Point(point.x - 1, point.y)
}
return this
}
else return this
}
else return this
}
fun MutableList<MutableList<Int>>.print(n: Int = this.size){
for (k in this.size-1 downTo this.size-n){
println(this[k].joinToString(separator = "").replace('0', '.').replace('1', '#'))
}
}
fun Shape.check(chamber: MutableList<MutableList<Int>>): Boolean{
// println(this.points.map{chamber[it.y-1][it.x] == 1}.toList())
// println(this.points.map{chamber[it.y-1][it.x] == 1}.toList().all{it == false})
return this.points.map{chamber[it.y-1][it.x] == 1}.toList().all{it == false}
}
fun Shape.updateFall(chamber: MutableList<MutableList<Int>>): Pair<Boolean, Shape> {
return if (!this.check(chamber)) Pair(false, this)
else{
for ((i, point) in this.points.withIndex()){
this.points[i] = Point(point.x, point.y-1)
}
Pair(true, this)
}
}
fun MutableList<MutableList<Int>>.update(shape: Shape): MutableList<MutableList<Int>> {
for (point in shape.points){
this[point.y][point.x] = 1
}
return this
}
fun part1(input: String){
var defaultShape = Shape(mutableListOf(Point(2,0), Point(3, 0), Point(4,0), Point(5,0)))
var countShapes = 0
var floor = 0
var ystart = 0
var actionCount = 0
var chamber = MutableList(5) { MutableList<Int>(7) { 0 } }
chamber[0].mapIndexed{index, i -> chamber[0][index] = 1 }
val shapes = mutableMapOf<Int, Shape>()
shapes[0] = Shape(mutableListOf(Point(2,0), Point(3, 0), Point(4,0), Point(5,0)))
shapes[1] = Shape(mutableListOf(Point(2,1), Point(3, 1), Point(4,1), Point(3,0), Point(3, 2)))
shapes[2] = Shape(mutableListOf(Point(2,0), Point(3, 0), Point(4,0), Point(4,1), Point(4, 2)))
shapes[3] = Shape(mutableListOf(Point(2,0), Point(2, 1), Point(2,2), Point(2,3)))
shapes[4] = Shape(mutableListOf(Point(2,0), Point(3, 0), Point(2,1), Point(3,1)))
while (countShapes < 10000){
// println("number of shapes $countShapes, key of shape: ${countShapes % 5}")
var shape = shapes.getOrDefault(countShapes % 5, defaultShape)
// println("check floor ${IntRange(0, 6).map{j -> chamber.map { it[j] }.toList().indexOfLast { it > 0 }}.toList()}")
floor = IntRange(0, 6).map{j -> chamber.map { it[j] }.toList().indexOfLast { it > 0 }}.toList().max()
ystart = floor + 4
if (ystart + 4 > chamber.size){while (chamber.size <= ystart+3) chamber.add(MutableList<Int>(7) { 0 })}
shape = shape.updateStart(ystart)
// println("starting shape ${shape.lowest()} ${shape.rightmost()} ${shape.leftmost()}")
var moveFlag = true
move@while (moveFlag){
for (action in listOf("jet", "fall")){
when (action) {
"jet" -> {
// println("${input[actionCount % input.length]}")
// println("shape befor action ${shape.lowest()} ${shape.rightmost()} ${shape.leftmost()}")
shape = shape.updateJet(input[actionCount % input.length], chamber)
// println("shape after action ${shape.lowest()} ${shape.rightmost()} ${shape.leftmost()}")
moveFlag = shape.check(chamber)
// println("move? $moveFlag")
actionCount++
if (!moveFlag){
chamber = chamber.update(shape)
break@move
}
}
"fall" -> {
// println(action)
// println("shape befor action ${shape.lowest()} ${shape.rightmost()} ${shape.leftmost()}")
var res = shape.updateFall(chamber)
moveFlag = res.first
shape = res.second
// println("shape after action ${shape.lowest()} ${shape.rightmost()} ${shape.leftmost()}")
// println("move? $moveFlag")
if (!moveFlag){
chamber = chamber.update(shape)
break@move
}
}
}
}
}
// println("finished shape $countShapes")
countShapes++
// chamber.print()
}
println(IntRange(0, 6).map{j -> chamber.map { it[j] }.toList().indexOfLast { it > 0 }}.toList())
// chamber.print(20)
}
// test if implementation meets criteria from the description, like:
val testInput = File("src", "Day17.txt").readText()
part1(testInput)
// part2(testInput)
val input = readInput("Day17")
// part1(testInput)
// part2(input)
} | 0 | Kotlin | 0 | 0 | a0bc190b391585ce3bb6fe2ba092fa1f437491a6 | 6,794 | aoc22 | Apache License 2.0 |
src/main/kotlin/se/saidaspen/aoc/aoc2021/Day18.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2021
import se.saidaspen.aoc.aoc2021.SnailFishNumber.SFPair.Companion.parse
import se.saidaspen.aoc.util.Day
import se.saidaspen.aoc.util.permutations
import kotlin.math.ceil
import kotlin.math.floor
fun main() = Day18.run()
object Day18 : Day(2021, 18) {
override fun part1() = input.lines()
.map { parse(it) }
.reduce { acc, snailFishNumber -> (acc + snailFishNumber).reduce() }
.magnitude()
override fun part2() = permutations(input.lines(), length = 2)
.maxOf { (parse(it[0]) + parse(it[1])).reduce().magnitude() }
}
sealed class SnailFishNumber(var parent: SFPair? = null) {
fun magnitude(): Long = when (this) {
is Constant -> value
is SFPair -> left.magnitude() * 3 + right.magnitude() * 2
}
operator fun plus(other: SnailFishNumber) = SFPair(this, other)
fun reduce(): SnailFishNumber {
while (true) {
val beforeExplode = this.toString()
explode()
if (beforeExplode != this.toString())
continue
val beforeSplit = this.toString()
split()
if (beforeSplit != this.toString())
continue
break
}
return this
}
fun explode(): SnailFishNumber {
val candidate = findExplodeCandidate()
if (candidate != null) {
notSideParent(candidate, SFPair::left)?.left?.most(SFPair::right)?.let {
it.value += (candidate.left as Constant).value
}
notSideParent(candidate, SFPair::right)?.right?.most(SFPair::left)?.let {
it.value += (candidate.right as Constant).value
}
candidate.replace(Constant(0))
}
return this
}
private fun most(side: SFPair.() -> SnailFishNumber): Constant = when (this) {
is Constant -> this
is SFPair -> this.side().most(side)
}
private fun notSideParent(n: SnailFishNumber, side: SFPair.() -> SnailFishNumber): SFPair? {
return if (n.parent == null) null
else if (n.parent!!.side() !== n) n.parent
else notSideParent(n.parent!!, side)
}
fun split(): SnailFishNumber {
val candidate = findSplitCandidate()
if (candidate != null) {
val left = Constant(floor(candidate.value / 2.0).toLong())
val right = Constant(ceil(candidate.value / 2.0).toLong())
candidate.replace(SFPair(left, right))
}
return this
}
private fun findExplodeCandidate(lvl: Int = 0): SFPair? {
return when (this) {
is Constant -> null
is SFPair -> {
if (lvl == 4) {
this
} else {
this.left.findExplodeCandidate(lvl + 1) ?: this.right.findExplodeCandidate(lvl + 1)
}
}
}
}
private fun findSplitCandidate(): Constant? {
return when (this) {
is Constant -> if (value >= 10) this else null
is SFPair -> left.findSplitCandidate() ?: right.findSplitCandidate()
}
}
data class Constant(var value: Long) : SnailFishNumber() {
override fun toString() = value.toString()
}
fun replace(new: SnailFishNumber) {
if (this.parent!!.left == this) {
this.parent!!.left = new
} else {
this.parent!!.right = new
}
new.parent = this.parent!!
}
data class SFPair(var left: SnailFishNumber, var right: SnailFishNumber) : SnailFishNumber() {
init {
left.parent = this
right.parent = this
}
override fun toString() = "[$left,$right]"
companion object {
fun parse(str: String): SnailFishNumber {
val commaPos = findComma(str)
return if (commaPos != null) {
val left = str.substring(0, commaPos).drop(1)
val right = str.substring(commaPos + 1).dropLast(1)
return SFPair(parse(left), parse(right))
} else Constant(str.toLong())
}
private fun findComma(str: String): Int? {
var lvl = 0
for ((i, c) in str.toCharArray().withIndex()) {
when (c) {
'[' -> lvl++
']' -> lvl--
',' -> {
if (lvl == 1) {
return i
}
}
}
}
return null
}
}
}
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 4,712 | adventofkotlin | MIT License |
src/main/aoc2016/Day17.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2016
import md5
class Day17(private val input: String) {
private data class State(val x: Int, val y: Int, val history: String)
private fun walkMaze(passcode: String, findShortestRoute: Boolean = true): String {
val toCheck = mutableListOf(State(1, 1, ""))
val isOpen = "bcdef"
var longest = ""
while (toCheck.size > 0) {
val state = toCheck.removeAt(0)
if (state.x == 4 && state.y == 4) {
if (findShortestRoute) {
return state.history
}
// BFS, every new match is always at least as long as the previous one
longest = state.history
continue
}
val hash = "$passcode${state.history}".md5()
if (state.y > 1 && isOpen.contains(hash[0])) {
toCheck.add(State(state.x, state.y - 1, state.history + "U"))
}
if (state.y < 4 && isOpen.contains(hash[1])) {
toCheck.add(State(state.x, state.y + 1, state.history + "D"))
}
if (state.x > 1 && isOpen.contains(hash[2])) {
toCheck.add(State(state.x - 1, state.y, state.history + "L"))
}
if (state.x < 4 && isOpen.contains(hash[3])) {
toCheck.add(State(state.x + 1, state.y, state.history + "R"))
}
}
return longest
}
fun solvePart1(): String {
return walkMaze(input)
}
fun solvePart2(): Int {
return walkMaze(input, false).length
}
}
| 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 1,588 | aoc | MIT License |
algorithms/src/main/kotlin/io/nullables/api/playground/algorithms/MergeSort.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
/**
* Invented in 1945 by <NAME>, merge sort is an efficient algorithm using the divide and conquer approach
* which is to divide a big problem into smaller problems and solve them. Conceptually, a merge sort works as follows:
* 1) Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element is considered sorted).
* 2) Repeatedly merge sublists to produce new sorted sublists until there is only 1 sublist remaining.
*/
@ComparisonSort
@StableSort
class MergeSort : AbstractSortStrategy() {
override fun <T : Comparable<T>> perform(arr: Array<T>) {
val aux = arr.clone()
sort(arr, aux, 0, arr.size - 1)
}
private fun <T : Comparable<T>> sort(arr: Array<T>, aux: Array<T>, lo: Int, hi: Int) {
if (hi <= lo) return
val mid = (lo + hi) / 2
sort(arr, aux, lo, mid)
sort(arr, aux, mid + 1, hi)
merge(arr, aux, lo, mid, hi)
}
private fun <T : Comparable<T>> merge(
arr: Array<T>,
aux: Array<T>,
lo: Int,
mid: Int,
hi: Int
) {
System.arraycopy(arr, lo, aux, lo, hi - lo + 1)
var i = lo
var j = mid + 1
for (k in lo..hi) {
when {
i > mid -> arr[k] = aux[j++]
j > hi -> arr[k] = aux[i++]
aux[j] < aux[i] -> arr[k] = aux[j++]
else -> arr[k] = aux[i++]
}
}
}
}
| 13 | Kotlin | 2 | 2 | d7173ec1d9ef227308d926e71335b530c43c92a8 | 2,128 | gradle-kotlin-sample | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindKClosestElements.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.abs
import kotlin.math.max
/**
* 658. Find K Closest Elements
* @see <a href="https://leetcode.com/problems/find-k-closest-elements/">Source</a>
*/
object FindKClosestElements {
/**
* Approach 1: Sort With Custom Comparator
*/
fun sortWithCustomComparator(arr: IntArray, k: Int, x: Int): List<Int> {
// Convert from array to list first to make use of Collections.sort()
var sortedArr: MutableList<Int> = ArrayList()
for (num in arr) {
sortedArr.add(num)
}
// Sort using custom comparator
sortedArr.sortWith { num1: Int, num2: Int ->
abs(num1 - x) - abs(num2 - x)
}
// Only take k elements
sortedArr = sortedArr.subList(0, k)
// Sort again to have output in ascending order
sortedArr.sort()
return sortedArr
}
/**
* Approach 2: Binary Search + Sliding Window
*/
fun bsSlidingWindow(arr: IntArray, k: Int, x: Int): List<Int> {
val result: MutableList<Int> = ArrayList()
// Base case
if (arr.size == k) {
for (i in 0 until k) {
result.add(arr[i])
}
return result
}
// Binary search to find the closest element
var left = 0
var right: Int = arr.size - 1
var mid = 0
while (left <= right) {
mid = (left + right) / 2
if (arr[mid] > x) {
right = mid - 1
} else if (arr[mid] < x) {
left = mid + 1
} else {
break
}
}
// Initialize our sliding window's bounds
left = max(0, mid - 1)
right = left + 1
// While the window size is less than k
while (right - left - 1 < k) {
// Be careful to not go out of bounds
if (left == -1) {
right += 1
continue
}
// Expand the window towards the side with the closer number
// Be careful to not go out of bounds with the pointers
if (right == arr.size || abs(arr[left] - x) <= abs(arr[right] - x)) {
left -= 1
} else {
right += 1
}
}
// Build and return the window
for (i in left + 1 until right) {
result.add(arr[i])
}
return result
}
/**
* Approach 3: Binary Search To Find The Left Bound
* Time complexity: O(log(N−k)+k).
* Space complexity: O(1).
*/
fun bsFindTheLeftBound(arr: IntArray, k: Int, x: Int): List<Int> {
// Initialize binary search bounds
var left = 0
var right: Int = arr.size - k
// Binary search against the criteria described
while (left < right) {
val mid = (left + right) / 2
if (x - arr[mid] > arr[mid + k] - x) {
left = mid + 1
} else {
right = mid
}
}
// Create output in correct format
val result: MutableList<Int> = ArrayList()
for (i in left until left + k) {
result.add(arr[i])
}
return result
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,905 | kotlab | Apache License 2.0 |
src/Day07.kt | MT-Jacobs | 574,577,538 | false | {"Kotlin": 19905} | fun main() {
fun part1(input: List<String>): Int {
val system: Filesystem = traverseInfo(input)
return system.directories.map { it.dataSize }.filter { it <= 100000 }.sum()
}
fun part2(input: List<String>): Int {
val system: Filesystem = traverseInfo(input)
val totalSpace = 70000000
val requiredSpace = 30000000
val usedSpace = system.root.dataSize
val availableSpace = totalSpace - usedSpace
val neededSpaceToClear = requiredSpace - (availableSpace)
return system.directories.map { it.dataSize }.filter { it >= neededSpaceToClear }.minOrNull() ?: 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test")
val part1Result = part1(testInput)
println(part1Result)
check(part1Result == 95437)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
}
fun traverseInfo(input: List<String>): Filesystem {
val root = FilesystemObject.Root()
val objects: MutableList<FilesystemObject> = mutableListOf()
val directories: MutableList<FilesystemObject.Directory> = mutableListOf()
val files: MutableList<FilesystemObject.File> = mutableListOf()
var currentDirectory: FilesystemObject.Directory = root
input.forEach{
val command: CLIInfo = it.getCLIInfo()
println(command)
when(command) {
is CLIInfo.CD -> {
currentDirectory = if (command.name == "/") {
root
} else {
currentDirectory.cd(command.name)
}
}
is CLIInfo.DirInfo -> {
if (currentDirectory[command.name] != null) {
// Dir already exists.
} else {
// Dir doesn't exist, add it.
val dir = FilesystemObject.Directory(command.name, currentDirectory)
currentDirectory[command.name] = dir
directories.add(dir)
objects.add(dir)
}
}
is CLIInfo.FileInfo -> {
if (currentDirectory[command.name] != null) {
// File already exists.
} else {
// File doesn't exist, add it.
val file = FilesystemObject.File(command.name, currentDirectory, command.size)
currentDirectory[command.name] = file
files.add(file)
objects.add(file)
}
}
CLIInfo.LS -> {
// Nothing to do, it's just a command to start listing stuff.
}
}
}
return Filesystem(
root = root,
objects = objects,
directories = directories,
files = files,
)
}
fun String.getCLIInfo(): CLIInfo {
val tokens = this.split(' ')
return when (tokens[0]) {
"$" -> when (tokens[1]) {
"cd" -> CLIInfo.CD(tokens[2])
"ls" -> CLIInfo.LS
else -> throw RuntimeException("Elf gave me an invalid command")
}
"dir" -> CLIInfo.DirInfo(tokens[1])
else -> {
val size = tokens[0].toIntOrNull() ?:
throw RuntimeException("Elf didn't give me a valid number for file size.")
CLIInfo.FileInfo(tokens[1], size)
}
}
}
class Filesystem(
val root: FilesystemObject.Root,
val objects: List<FilesystemObject> = emptyList(),
val directories: List<FilesystemObject.Directory> = emptyList(),
val files: List<FilesystemObject.File> = emptyList(),
)
sealed interface CLIInfo {
data class CD(val name: String): CLIInfo
object LS: CLIInfo {
override fun toString(): String = "LS()"
}
data class FileInfo(
val name: String,
val size: Int
): CLIInfo
data class DirInfo(
val name: String,
): CLIInfo
}
enum class FilesystemObjectType {
DIRECTORY, FILE
}
sealed class FilesystemObject(
val parent: Directory?,
val name: String
) {
abstract val dataSize: Int
open class Directory(
name: String,
parent: Directory? = null,
private val contents: MutableMap<String, FilesystemObject> = mutableMapOf(),
): FilesystemObject(parent, name), MutableMap<String, FilesystemObject> by contents {
override val dataSize: Int
get() = contents.values.sumOf { it.dataSize }
fun cd(name: String): FilesystemObject.Directory {
return if (name == "..") {
this.parent ?: throw RuntimeException("Can't cd .. without a parent")
} else {
(contents.getOrPut(name) {
Directory(name, this)
} as? Directory) ?: throw RuntimeException("Tried to cd to something that isn't a directory.")
}
}
}
class Root: Directory("/")
class File(
name: String,
parent: Directory,
override val dataSize: Int,
): FilesystemObject(parent, name)
} | 0 | Kotlin | 0 | 0 | 2f41a665760efc56d531e56eaa08c9afb185277c | 5,126 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/days/aoc2023/Day2.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2023
import days.Day
import java.lang.Integer.min
import java.util.IllegalFormatException
import kotlin.math.max
class Day2 : Day(2023, 2) {
override fun partOne(): Any {
return calculatePartOne(inputList)
}
override fun partTwo(): Any {
return calculatePartTwo(inputList)
}
fun calculatePartOne(input: List<String>): Int {
var possibleGameSum = 0
input.map { line ->
val game = GamePartOne(12, 13, 14, line)
if (game.isPossible) {
possibleGameSum += game.gameNumber
}
}
return possibleGameSum
}
internal class GamePartOne(val maxRed: Int, val maxGreen: Int, val maxBlue: Int, gameInput: String) {
val gameNumber: Int
var isPossible: Boolean = true
init {
gameNumber = Regex("Game (\\d*):").find(gameInput, 0)?.destructured?.let { (number) -> number.toInt() } ?: throw IllegalStateException("Format unexpected")
val setsOfCubes = gameInput.dropWhile { it != ':' }.drop(1).split(';')
setsOfCubes.forEach { set ->
set.trim().split(',').forEach { cubesDrawn ->
Regex("(\\d*) (red|green|blue)").find(cubesDrawn.trim())?.destructured?.let { (cubes, color) ->
when (color) {
"red" -> if (cubes.toInt() > maxRed) {
isPossible = false
return@forEach
}
"green" -> if (cubes.toInt() > maxGreen) {
isPossible = false
return@forEach
}
"blue" -> if (cubes.toInt() > maxBlue) {
isPossible = false
return@forEach
}
}
}
}
}
}
}
fun calculatePartTwo(input: List<String>): Int {
return input.sumOf { line -> GamePartTwo(line).power }
}
internal class GamePartTwo(gameInput: String) {
val power: Int
init {
val setsOfCubes = gameInput.dropWhile { it != ':' }.drop(1).split(';')
var minRed = 0
var minGreen = 0
var minBlue = 0
setsOfCubes.forEach { set ->
set.trim().split(',').forEach { cubesDrawn ->
Regex("(\\d*) (red|green|blue)").find(cubesDrawn.trim())?.destructured?.let { (cubes, color) ->
when (color) {
"red" -> minRed = max(minRed, cubes.toInt())
"blue" -> minBlue = max(minBlue, cubes.toInt())
"green" -> minGreen = max(minGreen, cubes.toInt())
}
}
}
}
power = minRed * minGreen * minBlue
}
}
} | 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 3,042 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
src/main/kotlin/dev/shtanko/algorithms/leetcode/FourSum.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <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
fun interface FourSum {
operator fun invoke(nums: IntArray, target: Int): List<List<Int>>
}
/**
* Approach 1: Two Pointers.
* Time Complexity: O(n^{k - 1}), or O(n^3) for 4Sum. We have k - 2k−2 loops, and twoSum is O(n).
* Space Complexity: O(n).
*/
class FourSumTwoPointers : FourSum {
override operator fun invoke(nums: IntArray, target: Int): List<List<Int>> {
nums.sort()
return kSum(nums, target, 0, 4)
}
private fun kSum(nums: IntArray, target: Int, start: Int, k: Int): List<MutableList<Int>> {
val res: MutableList<MutableList<Int>> = ArrayList()
if (start == nums.size || nums[start] * k > target || target > nums[nums.size - 1] * k) return res
if (k == 2) return twoSum(nums, target, start)
for (i in start until nums.size) {
if (i == start || nums[i - 1] != nums[i]) {
for (set in kSum(nums, target - nums[i], i + 1, k - 1)) {
res.add(ArrayList(listOf(nums[i])))
res[res.size - 1].addAll(set)
}
}
}
return res
}
private fun twoSum(nums: IntArray, target: Int, start: Int): List<MutableList<Int>> {
val res: MutableList<MutableList<Int>> = ArrayList()
var lo = start
var hi = nums.size - 1
while (lo < hi) {
val sum = nums[lo] + nums[hi]
if (sum < target || lo > start && nums[lo] == nums[lo - 1]) {
++lo
} else if (sum > target || hi < nums.size - 1 && nums[hi] == nums[hi + 1]) {
--hi
} else {
res.add(mutableListOf(nums[lo++], nums[hi--]))
}
}
return res
}
}
/**
* Time Complexity: O(n^k−1), or O(n^3) for 4Sum.
* Space Complexity: O(n).
*/
class FourSumHashSet : FourSum {
override operator fun invoke(nums: IntArray, target: Int): List<List<Int>> {
nums.sort()
return kSum(nums, target, 0, 4)
}
private fun kSum(nums: IntArray, target: Int, start: Int, k: Int): List<List<Int>> {
val res: MutableList<MutableList<Int>> = ArrayList()
if (start == nums.size || nums[start] * k > target || target > nums[nums.size - 1] * k) return res
if (k == 2) return twoSum(nums, target, start)
for (i in start until nums.size) {
if (i == start || nums[i - 1] != nums[i]) {
for (set in kSum(nums, target - nums[i], i + 1, k - 1)) {
res.add(ArrayList(listOf(nums[i])))
res[res.size - 1].addAll(set)
}
}
}
return res
}
private fun twoSum(nums: IntArray, target: Int, start: Int): List<List<Int>> {
val res: MutableList<List<Int>> = ArrayList()
val s: MutableSet<Int> = HashSet()
for (i in start until nums.size) {
if (res.isEmpty() || res[res.size - 1][1] != nums[i]) {
if (s.contains(target - nums[i])) {
res.add(listOf(target - nums[i], nums[i]))
}
}
s.add(nums[i])
}
return res
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,797 | kotlab | Apache License 2.0 |
2015/src/main/kotlin/day12.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parser
import utils.Solution
fun main() {
Day12.run()
}
object Day12 : Solution<String>() {
override val name = "day12"
override val parser: Parser<String> = Parser { it }
data class VisitResult(
val sum: Int,
val redSum: Int,
val len: Int,
val red: Boolean,
)
private fun visitArray(off: Int, str: String): VisitResult {
var sum = 0
var redSum = 0
var o = off + 1
while (str[o] != ']') {
if (str[o] == ',') {
o++
}
val (s, rs, l, _) = visitValue(o, str)
o += l
sum += s
redSum += rs
}
return VisitResult(sum, redSum, o - off + 1, false)
}
private fun visitObj(off: Int, str: String): VisitResult {
var o = off + 1
var sum = 0
var redSum = 0
var red = false
while (str[o] != '}') {
if (str[o] == ',') {
o++
}
// eat key
val (_, _, l, _) = visitStr(o, str)
o += l
// eat ':'
o += 1
val value = visitValue(o, str)
red = red || value.red
sum += value.sum
redSum += value.redSum
o += value.len
}
return VisitResult(if (red) 0 else sum, if (red) sum + redSum else redSum, o - off + 1, false)
}
private fun visitStr(off: Int, str: String): VisitResult {
val end = str.indexOf('"', startIndex = off + 1)
return VisitResult(0, 0, end - off + 1, str.substring(off + 1, end) == "red")
}
private fun visitNum(off: Int, str: String): VisitResult {
val endOfNumber = str.substring(off + 1).indexOfFirst { it !in '0'..'9' } + off + 1
val num = str.substring(off, endOfNumber).toInt()
return VisitResult(num, 0, endOfNumber - off, false)
}
private fun visitValue(off: Int, str: String): VisitResult {
return when (str[off]) {
'[' -> visitArray(off, str)
'{' -> visitObj(off, str)
'"' -> visitStr(off, str)
else -> visitNum(off, str)
}
}
override fun part1(input: String): Int {
val result = visitValue(0, input)
return result.sum + result.redSum
}
override fun part2(input: String): Int {
val result = visitValue(0, input)
return result.sum
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 2,153 | aoc_kotlin | MIT License |
src/main/kotlin/P018_MaximumPathSum.kt | perihanmirkelam | 291,833,878 | false | null | /**
* P18-Maximum Path Sum
* By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.
* 3
* 7 4
* 2 4 6
* 8 5 9 3
* That is, 3 + 7 + 4 + 9 = 23.
* Find the maximum total from top to bottom of the triangle below:
* 75
* 95 64
* 17 47 82
* 18 35 87 10
* 20 04 82 47 65
* 19 01 23 75 03 34
* 88 02 77 73 07 63 67
* 99 65 04 28 06 16 70 92
* 41 41 26 56 83 40 80 70 33
* 41 48 72 33 47 32 37 16 94 29
* 53 71 44 65 25 43 91 52 97 51 14
* 70 11 33 28 77 73 17 78 39 68 17 57
* 91 71 52 38 17 14 91 43 58 50 27 29 48
* 63 66 04 68 89 53 67 30 73 16 69 87 40 31
* 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
* NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route.
* However, Problem 67, is the same challenge with a triangle containing one-hundred rows;
* it cannot be solved by brute force, and requires a clever method! ;o)
*/
const val str = "75\n" +
"95 64\n" +
"17 47 82\n" +
"18 35 87 10\n" +
"20 04 82 47 65\n" +
"19 01 23 75 03 34\n" +
"88 02 77 73 07 63 67\n" +
"99 65 04 28 06 16 70 92\n" +
"41 41 26 56 83 40 80 70 33\n" +
"41 48 72 33 47 32 37 16 94 29\n" +
"53 71 44 65 25 43 91 52 97 51 14\n" +
"70 11 33 28 77 73 17 78 39 68 17 57\n" +
"91 71 52 38 17 14 91 43 58 50 27 29 48\n" +
"63 66 04 68 89 53 67 30 73 16 69 87 40 31\n" +
"04 62 98 27 23 09 70 98 73 93 38 53 60 04 23"
val rows: List<List<Int>> = str.split("\n").map { x -> x.split(" ").map { it.toInt() } }
fun p18() {
print(getMax(0, 0, 0))
}
fun getMax(sum: Int, i: Int, j: Int): Int {
if (i > rows.lastIndex) {
println("Total: $sum")
return sum
}
println("-> ${rows[i][j]} [$i,$j] sum: ${sum + rows[i][j]}")
return maxOf(getMax(sum + rows[i][j], i+1, j), getMax(sum + rows[i][j], i+1,j+1))
}
| 0 | Kotlin | 1 | 3 | a24ac440871220c87419bfd5938f80dc22a422b2 | 2,077 | ProjectEuler | MIT License |
src/main/kotlin/adventofcode/year2015/Day15ScienceForHungryPeople.kt | pfolta | 573,956,675 | false | {"Kotlin": 199554, "Dockerfile": 227} | package adventofcode.year2015
import adventofcode.Puzzle
import adventofcode.PuzzleInput
import adventofcode.common.cartesianProduct
import kotlin.math.max
class Day15ScienceForHungryPeople(customInput: PuzzleInput? = null) : Puzzle(customInput) {
override val name = "Science for Hungry People"
private val ingredients by lazy { input.lines().map(Ingredient::invoke) }
private val recipes by lazy {
(1..ingredients.size)
.map { (0..TABLESPOON_COUNT).toList() }
.cartesianProduct()
.filter { it.sum() == TABLESPOON_COUNT }
.map { it.mapIndexed { index, amount -> ingredients[index] * amount } }
.map { it.sum() }
}
override fun partOne() = recipes.maxOf(Ingredient::score)
override fun partTwo() = recipes.filter { it.calories == CALORIE_COUNT }.maxOf(Ingredient::score)
companion object {
private val INPUT_REGEX = """capacity (-?\d+), durability (-?\d+), flavor (-?\d+), texture (-?\d+), calories (\d+)""".toRegex()
private const val TABLESPOON_COUNT = 100
private const val CALORIE_COUNT = 500
private data class Ingredient(
val capacity: Int,
val durability: Int,
val flavor: Int,
val texture: Int,
val calories: Int
) {
val score = max(0, capacity) * max(0, durability) * max(0, flavor) * max(0, texture)
operator fun times(amount: Int) =
Ingredient(amount * capacity, amount * durability, amount * flavor, amount * texture, amount * calories)
operator fun plus(other: Ingredient) = Ingredient(
capacity + other.capacity,
durability + other.durability,
flavor + other.flavor,
texture + other.texture,
calories + other.calories
)
companion object {
operator fun invoke(input: String): Ingredient {
val (capacity, durability, flavor, texture, calories) = INPUT_REGEX
.find(input)!!
.destructured
.toList()
.map(String::toInt)
return Ingredient(capacity, durability, flavor, texture, calories)
}
}
}
private fun Collection<Ingredient>.sum(): Ingredient = reduce { sum, summand -> sum + summand }
}
}
| 0 | Kotlin | 0 | 0 | 72492c6a7d0c939b2388e13ffdcbf12b5a1cb838 | 2,468 | AdventOfCode | MIT License |
src/Day02.kt | ezeferex | 575,216,631 | false | {"Kotlin": 6838} | // A and X are Rock (1 point)
// B and Y are Paper (2 points)
// C and Z are Scissors (3 points)
// 6 points if won
// 3 points if draw
// 0 point if lost
fun scoreShape(shape: String) = when(shape) {
"X" -> 1
"Y" -> 2
"Z" -> 3
else -> 0
}
fun scoreRock(shape: String) = when(shape) {
"A" -> 3
"C" -> 6
else -> 0
}
fun scorePaper(shape: String) = when(shape) {
"B" -> 3
"A" -> 6
else -> 0
}
fun scoreScissors(shape: String) = when(shape) {
"C" -> 3
"B" -> 6
else -> 0
}
fun scoreResult(result: String) = when(result) {
"Y" -> 3
"Z" -> 6
else -> 0
}
fun scoreShapeLose(shape: String) = when(shape) {
"A" -> scoreShape("Z")
"B" -> scoreShape("X")
"C" -> scoreShape("Y")
else -> 0
}
fun scoreShapeDraw(shape: String) = when(shape) {
"A" -> scoreShape("X")
"B" -> scoreShape("Y")
"C" -> scoreShape("Z")
else -> 0
}
fun scoreShapeWin(shape: String) = when(shape) {
"A" -> scoreShape("Y")
"B" -> scoreShape("Z")
"C" -> scoreShape("X")
else -> 0
}
fun scoreRoundPart1(opp: String, player: String) = scoreShape(player) + when(player) {
"X" -> scoreRock(opp)
"Y" -> scorePaper(opp)
"Z" -> scoreScissors(opp)
else -> 0
}
fun scoreRoundPart2(opp: String, result: String) = scoreResult(result) + when(result) {
"X" -> scoreShapeLose(opp)
"Y" -> scoreShapeDraw(opp)
"Z" -> scoreShapeWin(opp)
else -> 0
}
fun main() {
fun part1() = "Part 1: " + readInput("02").split("\n")
.sumOf { scoreRoundPart1(it.split(" ")[0], it.split(" ")[1]) }
fun part2() = "Part 2: " + readInput("02").split("\n")
.sumOf { scoreRoundPart2(it.split(" ")[0], it.split(" ")[1]) }
println(part1())
println(part2())
}
| 0 | Kotlin | 0 | 0 | f06f8441ad0d7d4efb9ae449c9f7848a50f3f57c | 1,766 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2021/2021-25.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2021
import com.github.ferinagy.adventOfCode.Coord2D
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputLines
fun main() {
val input = readInputLines(2021, "25-input")
val test1 = readInputLines(2021, "25-test1")
println("Part1:")
part1(test1).println()
part1(input).println()
}
private fun part1(input: List<String>): Int {
var floor = SeaFloor.parse(input)
var steps = 0
var done = false
while (!done) {
steps++
val step = floor.step()
floor = step.first
done = !step.second
}
// floor.print()
return steps
}
private data class SeaFloor(val width: Int, val height: Int, val cucumbers: Map<Coord2D, Boolean>) {
companion object {
fun parse(input: List<String>): SeaFloor {
val height = input.size
val width = input.first().length
val map = mutableMapOf<Coord2D, Boolean>()
input.forEachIndexed { y, line ->
line.forEachIndexed { x, c ->
if (c == '>') map[Coord2D(x, y)] = true
if (c == 'v') map[Coord2D(x, y)] = false
}
}
return SeaFloor(width, height, map)
}
}
}
private fun SeaFloor.print() {
for (y in 0 until height) {
for (x in 0 until width) {
when (cucumbers[Coord2D(x, y)]) {
true -> print('>')
false -> print('v')
null -> print('.')
}
}
println()
}
}
private fun SeaFloor.step(): Pair<SeaFloor, Boolean> {
var moved = false
val intermediate = cucumbers.mapKeys { (key, value) ->
if (value) {
val newPosition = eastOf(key)
if (cucumbers[newPosition] == null) newPosition.also { moved = true } else key
} else {
key
}
}
val newCucumbers = intermediate.mapKeys { (key, value) ->
if (value) {
key
} else {
val newPosition = southOf(key)
if (intermediate[newPosition] == null) newPosition.also { moved = true } else key
}
}
return copy(cucumbers = newCucumbers) to moved
}
private fun SeaFloor.eastOf(coord: Coord2D): Coord2D {
return if (coord.x + 1 < width) coord.copy(x = coord.x + 1) else coord.copy(x = 0)
}
private fun SeaFloor.southOf(coord: Coord2D): Coord2D {
return if (coord.y + 1 < height) coord.copy(y = coord.y + 1) else coord.copy(y = 0)
}
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 2,568 | advent-of-code | MIT License |
day14/kotlin/corneil/src/main/kotlin/solution.kt | tschulte | 317,661,818 | true | {"HTML": 2739009, "Java": 348790, "Kotlin": 271053, "TypeScript": 262310, "Python": 198318, "Groovy": 125347, "Jupyter Notebook": 116902, "C++": 101742, "Dart": 47762, "Haskell": 43633, "CSS": 35030, "Ruby": 27091, "JavaScript": 13242, "Scala": 11409, "Dockerfile": 10370, "PHP": 4152, "Go": 2838, "Shell": 2651, "Rust": 2082, "Clojure": 567, "Tcl": 46} | package com.github.corneil.aoc2019.day14
import java.io.File
typealias ChemicalQty = Pair<Long, String>
data class ReactionFormula(val inputs: List<ChemicalQty>, val output: ChemicalQty)
fun readChemicalQty(it: String): ChemicalQty {
val tokens = it.trim().split(" ")
require(tokens.size == 2)
return ChemicalQty(tokens[0].toLong(), tokens[1].trim())
}
fun readReaction(input: String): ReactionFormula {
val inputs = input.substringBefore("=>").split(",").map {
readChemicalQty(it)
}
return ReactionFormula(inputs, readChemicalQty(input.substringAfter("=>")))
}
fun readReactions(input: List<String>) = input.map { readReaction(it) }
fun add(value: MutableMap<String, Long>, output: ChemicalQty) {
val qty = value[output.second]
if (qty != null) {
value[output.second] = qty + output.first
} else {
value[output.second] = output.first
}
}
fun produce(
output: ChemicalQty,
formulae: Map<String, ReactionFormula>,
sideEffect: MutableMap<String, Long>,
used: MutableMap<String, Long>
) {
val remain = sideEffect[output.second]
if (remain != null && remain > 0L) {
useRemainingChemicals(remain, output, formulae, sideEffect, used)
} else {
val formula = formulae[output.second]
if (formula != null) {
applyFormula(output, formula, formulae, sideEffect, used)
} else {
// This is usually the ORE
add(used, output)
}
}
}
fun useRemainingChemicals(
remain: Long,
output: ChemicalQty,
formulae: Map<String, ReactionFormula>,
sideEffect: MutableMap<String, Long>,
used: MutableMap<String, Long>
) {
if (remain >= output.first) {
val qty = remain - output.first
sideEffect[output.second] = qty
require(qty >= 0) { "Expected Qty to be zero or greater for ${output.second} not $qty" }
} else {
sideEffect.remove(output.second)
produce(ChemicalQty(output.first - remain, output.second), formulae, sideEffect, used)
}
}
fun applyFormula(
output: ChemicalQty,
formula: ReactionFormula,
formulae: Map<String, ReactionFormula>,
sideEffect: MutableMap<String, Long>,
used: MutableMap<String, Long>
) {
val repeats = if (output.first < formula.output.first) {
1L
} else {
output.first / formula.output.first +
if (output.first % formula.output.first == 0L) 0L else 1L
}
val produced = apply(formula, repeats, formulae, sideEffect, used)
if (output.first < produced.first) {
sideEffect[output.second] = produced.first - output.first
}
}
fun apply(
formula: ReactionFormula,
repeats: Long,
formulae: Map<String, ReactionFormula>,
sideEffect: MutableMap<String, Long>,
used: MutableMap<String, Long>
): ChemicalQty {
formula.inputs.forEach {
produce(ChemicalQty(it.first * repeats, it.second), formulae, sideEffect, used)
}
return ChemicalQty(formula.output.first * repeats, formula.output.second)
}
fun determineInputForOutput(input: String, output: ChemicalQty, formulae: List<ReactionFormula>): Long {
val formula = formulae.map { it.output.second to it }.toMap()
val used = mutableMapOf<String, Long>()
val sideEffect = mutableMapOf<String, Long>()
produce(output, formula, sideEffect, used)
println("$output = $used, Side Effects = $sideEffect")
return used[input] ?: 0L
}
fun executeReactions(
increment: Long,
input: ChemicalQty,
output: String,
formula: Map<String, ReactionFormula>,
used: MutableMap<String, Long>
): Pair<Long, Long> {
val sideEffect = mutableMapOf<String, Long>()
var inc = increment
var counter = 0L
while (input.first > used[input.second] ?: 0L) {
produce(ChemicalQty(inc, output), formula, sideEffect, used)
counter += inc
if (counter % 10000L == 0L) {
print("produce $output for $input = $counter\r")
}
val usedSoFar = used[input.second] ?: 0L
if (inc == 100L && (10L * usedSoFar / input.first > 7L)) {
inc = 10L
} else if (inc == 10L && (10L * usedSoFar / input.first > 8L)) {
inc = 1L
}
}
println("Used = $used, Side Effect = $sideEffect")
return Pair(counter, inc)
}
fun determineOuputForInput(input: ChemicalQty, output: String, formulae: List<ReactionFormula>): Long {
val formula = formulae.map { it.output.second to it }.toMap()
val used = mutableMapOf<String, Long>()
var increment = 1000L // Start with 100 and drop down to save some time
var counter: Long
do {
increment /= 10L
val pair = executeReactions(increment, input, output, formula, used)
counter = pair.first
increment = pair.second
} while (increment > 1L) // If last increment isn't 1 redo
val result = if (used[input.second] == input.first) counter else counter - 1L
println("output $input = $result")
return result
}
fun main(args: Array<String>) {
val fileName = if (args.size > 1) args[0] else "input.txt"
val formulae = readReactions(File(fileName).readLines())
val output = determineInputForOutput("ORE", ChemicalQty(1L, "FUEL"), formulae)
println("Output = ORE = $output")
require(output == 612880L) // ensure check for refactoring
val fuel = determineOuputForInput(ChemicalQty(1000000000000L, "ORE"), "FUEL", formulae)
println("Fuel = $fuel")
require(fuel == 2509120L)
}
| 0 | HTML | 0 | 0 | afcaede5326b69fedb7588b1fe771fd0c0b3f6e6 | 5,516 | docToolchain-aoc-2019 | MIT License |
src/Day04.kt | i-tatsenko | 575,595,840 | false | {"Kotlin": 90644} | class Range(serialized: String) {
private val start: Int
private val end: Int
init {
val split = serialized.split('-')
start = split[0].toInt()
end = split[1].toInt()
}
fun contains(other: Range): Boolean = start <= other.start && end >= other.end
fun overlaps(other: Range): Boolean {
return if (start < other.start) end >= other.start else other.end >= start
}
}
fun main() {
fun part1(input: List<String>): Int {
var result = 0
for (line in input) {
val split = line.split(',')
val first = Range(split[0])
val second = Range(split[1])
if (first.contains(second) || second.contains(first)) result++
}
return result
}
fun part2(input: List<String>): Int {
var result = 0
for (line in input) {
val split = line.split(',')
val first = Range(split[0])
val second = Range(split[1])
if (first.overlaps(second)) result++
}
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 0a9b360a5fb8052565728e03a665656d1e68c687 | 1,317 | advent-of-code-2022 | Apache License 2.0 |
src/Day12.kt | lsimeonov | 572,929,910 | false | {"Kotlin": 66434} | import kotlin.math.abs
typealias GridPosition = Triple<Int, Int, Char>
typealias Barrier = Set<GridPosition>
const val MAX_SCORE = 99999999
abstract class Grid(private val barriers: List<Barrier>) {
open fun heuristicDistance(start: GridPosition, finish: GridPosition): Int {
val dx = abs(start.first - finish.first)
val dy = abs(start.second - finish.second)
return (dx + dy) + (-2) * minOf(dx, dy)
}
fun inBarrier(position: GridPosition) = barriers.any { it.contains(position) }
abstract fun getNeighbours(position: GridPosition): List<GridPosition>
open fun moveCost(from: GridPosition, to: GridPosition) = if (inBarrier(to)) MAX_SCORE else 1
}
class SquareGrid(private val grid: Set<GridPosition>, barriers: List<Barrier>) : Grid(barriers) {
private val costRange = 'a'..'z'
private val validMoves = listOf(Pair(1, 0), Pair(-1, 0), Pair(0, 1), Pair(0, -1))
override fun getNeighbours(position: GridPosition): List<GridPosition> = validMoves.map {
grid.find { p -> position.first + it.first == p.first && position.second + it.second == p.second }
}.filterNotNull().filter { inGrid(it) }.filter {
when (it.third) {
'S' -> {
true
}
'E' -> {
position.third == 'z'
}
else -> {
(costRange.indexOf(position.third) - costRange.indexOf(it.third)) >= -1
}
}
}
private fun inGrid(it: GridPosition) = grid.find { p -> it.first == p.first && it.second == p.second } != null
override fun moveCost(from: GridPosition, to: GridPosition): Int {
return 1
// return if ((costRange.indexOf(from.third) - costRange.indexOf(to.third)) < 0) {
// abs(costRange.indexOf(from.third) - costRange.indexOf(to.third))
// } else {
// 1
// }
}
}
/**
* Implementation of the A* Search Algorithm to find the optimum path between 2 points on a grid.
*
* The Grid contains the details of the barriers and methods which supply the neighboring vertices and the
* cost of movement between 2 cells. Examples use a standard Grid which allows movement in 8 directions
* (i.e. includes diagonals) but alternative implementation of Grid can be supplied.
*
*/
fun aStarSearch(start: GridPosition, finish: GridPosition, grid: Grid): Pair<List<GridPosition>, Int> {
/**
* Use the cameFrom values to Backtrack to the start position to generate the path
*/
fun generatePath(currentPos: GridPosition, cameFrom: Map<GridPosition, GridPosition>): List<GridPosition> {
val path = mutableListOf(currentPos)
var current = currentPos
while (cameFrom.containsKey(current)) {
current = cameFrom.getValue(current)
path.add(0, current)
}
return path.toList()
}
val openVertices = mutableSetOf(start)
val closedVertices = mutableSetOf<GridPosition>()
val costFromStart = mutableMapOf(start to 0)
val estimatedTotalCost = mutableMapOf(start to grid.heuristicDistance(start, finish))
val cameFrom = mutableMapOf<GridPosition, GridPosition>() // Used to generate path by back tracking
while (openVertices.size > 0) {
val currentPos = openVertices.minBy { estimatedTotalCost.getValue(it) }!!
// Check if we have reached the finish
if (currentPos.first == finish.first && currentPos.second == finish.second) {
// Backtrack to generate the most efficient path
val path = generatePath(currentPos, cameFrom)
return Pair(path, estimatedTotalCost.getValue(currentPos)) // First Route to finish will be optimum route
}
// Mark the current vertex as closed
openVertices.remove(currentPos)
closedVertices.add(currentPos)
val neighbours = grid.getNeighbours(currentPos);
grid.getNeighbours(currentPos).filterNot { closedVertices.contains(it) } // Exclude previous visited vertices
.forEach { neighbour ->
val score = costFromStart.getValue(currentPos) + grid.moveCost(currentPos, neighbour)
if (score < costFromStart.getOrDefault(neighbour, MAX_SCORE)) {
if (openVertices.find { it.first == neighbour.first && it.second == neighbour.second } == null) {
openVertices.add(neighbour)
}
cameFrom.put(neighbour, currentPos)
costFromStart.put(neighbour, score)
estimatedTotalCost.put(neighbour, score + grid.heuristicDistance(neighbour, finish))
}
}
}
throw IllegalArgumentException("No Path from Start $start to Finish $finish")
}
fun main() {
fun part1(input: List<String>): Int {
val start = input.mapIndexed { i, l ->
if (l.toList().indexOf('S') != -1) {
GridPosition(l.toList().indexOf('S'), i, 'a')
} else {
null
}
}.filterNotNull().first()
val end = input.mapIndexed { i, l ->
if (l.toList().indexOf('E') != -1) {
GridPosition(l.toList().indexOf('E'), i, 'a')
} else {
null
}
}.filterNotNull().first()
val gridData = input.mapIndexed { y, l ->
l.toList().mapIndexed { x, c ->
GridPosition(x, y, c)
}
}.flatten().toSet()
val result = aStarSearch(start, end, SquareGrid(gridData, listOf()))
return result.second
}
fun part2(input: List<String>): Int {
val starts = input.mapIndexed { y, l ->
l.toList().mapIndexed { x, c ->
if (c == 'S' || c == 'a') {
GridPosition(x, y, 'a')
} else {
null
}
}.filterNotNull()
}.flatten()
val end = input.mapIndexed { i, l ->
if (l.toList().indexOf('E') != -1) {
GridPosition(l.toList().indexOf('E'), i, 'a')
} else {
null
}
}.filterNotNull().first()
val gridData = input.mapIndexed { y, l ->
l.toList().mapIndexed { x, c ->
GridPosition(x, y, c)
}
}.flatten().toSet()
val min = starts.minOfOrNull { aStarSearch(it, end, SquareGrid(gridData, listOf())).second }
return min ?: 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
//check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 9d41342f355b8ed05c56c3d7faf20f54adaa92f1 | 6,798 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day2/Day02.kt | Avataw | 572,709,044 | false | {"Kotlin": 99761} | package day2
val outcomesA = mapOf(
"A X" to 4, "A Y" to 8, "A Z" to 3,
"B X" to 1, "B Y" to 5, "B Z" to 9,
"C X" to 7, "C Y" to 2, "C Z" to 6,
)
fun solveA(input: List<String>) = input.mapNotNull { outcomesA[it] }.sum()
val outcomesB = mapOf(
"A X" to 3, "A Y" to 4, "A Z" to 8,
"B X" to 1, "B Y" to 5, "B Z" to 9,
"C X" to 2, "C Y" to 6, "C Z" to 7,
)
fun solveB(input: List<String>) = input.mapNotNull { outcomesB[it] }.sum()
// Quick and Dirty Naive solution:
//
//fun solveA(input: List<String>): Int {
// var sum = 0
//
// input.map {
// val line = it.split(" ")
// when (line.first()) {
// "A" -> {
// when (line.last()) {
// "X" -> sum += 4
// "Y" -> sum += 8
// "Z" -> sum += 3
// }
// }
//
// "B" -> {
// when (line.last()) {
// "X" -> sum += 1
// "Y" -> sum += 5
// "Z" -> sum += 9
// }
// }
//
// "C" -> {
// when (line.last()) {
// "X" -> sum += 7
// "Y" -> sum += 2
// "Z" -> sum += 6
// }
// }
// }
//
// }
//
// return sum
//}
//
//fun solveB(input: List<String>): Int {
// var sum = 0
//
// input.map {
// val line = it.split(" ")
// when (line.first()) {
// "A" -> {
// when (line.last()) {
// "X" -> sum += 3
// "Y" -> sum += 4
// "Z" -> sum += 8
// }
// }
//
// "B" -> {
// when (line.last()) {
// "X" -> sum += 1
// "Y" -> sum += 5
// "Z" -> sum += 9
// }
// }
//
// "C" -> {
// when (line.last()) {
// "X" -> sum += 2
// "Y" -> sum += 6
// "Z" -> sum += 7
// }
// }
// }
//
// }
//
// return sum
//}
| 0 | Kotlin | 2 | 0 | 769c4bf06ee5b9ad3220e92067d617f07519d2b7 | 2,172 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/net/voldrich/aoc2021/Day10.kt | MavoCz | 434,703,997 | false | {"Kotlin": 119158} | package net.voldrich.aoc2021
import net.voldrich.BaseDay
import java.util.*
// https://adventofcode.com/2021/day/10
fun main() {
Day10().run()
}
class Day10 : BaseDay() {
override fun task1() : Int {
val list = input.lines().map { analyzeLine(it) }
return list.filter { it.type == Type.CORRUPTED }.sumOf { it.getCharValue() }
}
override fun task2() : Long {
val list = input.lines().map { analyzeLine(it) }
val sorted = list.filter { it.type == Type.INCOMPLETE }.map { it.calculateBracketScore() }.sorted()
return sorted[sorted.size/2]
}
private val bracketMap = mapOf(
'(' to ')',
'<' to '>',
'{' to '}',
'[' to ']')
private val valueMap = mapOf(
')' to 3,
']' to 57,
'}' to 1197,
'>' to 25137)
private val scoreMap = mapOf(
'(' to 1L,
'[' to 2L,
'{' to 3L,
'<' to 4L)
private fun analyzeLine(line: String) : LineStatus {
val bracketStack = ArrayDeque<Char>()
for ((index, ch) in line.toCharArray().withIndex()) {
if (bracketMap.contains(ch)) {
bracketStack.push(ch)
} else {
val expected = bracketStack.poll() ?: return LineStatus(Type.CORRUPTED, ch, bracketStack)
val closingBracket = bracketMap[expected] ?: throw Exception("Failed to find closing bracket for $expected on $index")
if (ch != closingBracket) {
return LineStatus(Type.CORRUPTED, ch, bracketStack)
}
}
}
// incomplete or ok
return if (bracketStack.size > 0) {
LineStatus(Type.INCOMPLETE, ' ', bracketStack)
} else {
LineStatus(Type.OK, ' ', bracketStack)
}
}
enum class Type {
OK, INCOMPLETE, CORRUPTED
}
inner class LineStatus(val type: Type, private val char : Char, private val remainingBracketStack : ArrayDeque<Char>) {
fun getCharValue() : Int {
return valueMap[char] ?: throw Exception("Unmapped character $char value")
}
fun calculateBracketScore() : Long {
return remainingBracketStack.fold(0L) { prev, ch -> prev * 5 + scoreMap[ch]!! }
}
}
}
| 0 | Kotlin | 0 | 0 | 0cedad1d393d9040c4cc9b50b120647884ea99d9 | 2,305 | advent-of-code | Apache License 2.0 |
kotlin/0779-k-th-symbol-in-grammar.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} | class Solution {
fun kthGrammar(n: Int, k: Int): Int {
var cur = 0
var left = 1
var right = 2.0.pow(n - 1).toInt()
repeat (n - 1) {
val mid = (left + right) / 2
if (k <= mid) {
right = mid
} else {
left = mid + 1
cur = if (cur == 1) 0 else 1
}
}
return cur
}
}
// another solution using the same thought but different way of coding it
class Solution {
fun kthGrammar(n: Int, k: Int): Int {
if (n == 1) return 0
if (k % 2 == 0) return if (kthGrammar(n - 1, k / 2) == 0) 1 else 0
else return if (kthGrammar(n - 1, (k + 1) / 2) == 0) 0 else 1
}
}
// another solution, recommend reading https://leetcode.com/problems/k-th-symbol-in-grammar/solutions/113705/java-one-line/ for explanation
class Solution {
fun kthGrammar(n: Int, k: Int) = Integer.bitCount(k - 1) and 1
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 959 | leetcode | MIT License |
src/day02/Day02.kt | scottpeterson | 573,109,888 | false | {"Kotlin": 15611} | enum class Opponent {
A,
B,
C
}
enum class You {
X,
Y,
Z
}
data class Round(
val opponent: Opponent,
val you: You
)
fun main() {
fun result(opponent: Opponent, you: You): Int {
return when (opponent) {
Opponent.A -> when (you) {
You.X -> 3
You.Y -> 6
You.Z -> 0
}
Opponent.B -> when (you) {
You.X -> 0
You.Y -> 3
You.Z -> 6
}
Opponent.C -> when (you) {
You.X -> 6
You.Y -> 0
You.Z -> 3
}
}
}
fun yourPlayPartTwo(opponent: Opponent, you: You): You {
return when (opponent) {
Opponent.A -> when (you) {
You.X -> You.Z
You.Y -> You.X
You.Z -> You.Y
}
Opponent.B -> when (you) {
You.X -> You.X
You.Y -> You.Y
You.Z -> You.Z
}
Opponent.C -> when (you) {
You.X -> You.Y
You.Y -> You.Z
You.Z -> You.X
}
}
}
fun roundScore(result: Int, you: You): Int {
return result + when (you) {
You.X -> 1
You.Y -> 2
You.Z -> 3
}
}
val input = readInput("day02/Day02_input")
val newDataStructure = input.map {
Round(
opponent = Opponent.valueOf(it.substring(0, 1)),
you = You.valueOf(it.substring(2, 3))
)
}
var total: Int = 0
val roundResult = newDataStructure.forEach { round ->
val result = result(round.opponent, round.you)
val score = roundScore(result, round.you)
total += score
}
val partTwoData = input.map {
Round(
opponent = Opponent.valueOf(it.substring(0, 1)),
you = yourPlayPartTwo(Opponent.valueOf(it.substring(0, 1)), You.valueOf(it.substring(2, 3)))
)
}
var partTwoTotal: Int = 0
val roundResultPartTwo = partTwoData.forEach { round ->
val result = result(round.opponent, round.you)
val score = roundScore(result, round.you)
partTwoTotal += score
}
println(partTwoTotal)
}
| 0 | Kotlin | 0 | 0 | 0d86213c5e0cd5403349366d0f71e0c09588ca70 | 2,331 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/11.kts | reitzig | 318,492,753 | false | null | @file:Include("shared.kt")
import _11.GridElement.*
import _11.Position
import java.io.File
enum class GridElement(val rep: Char) {
EmptySeat('L'),
OccupiedSeat('#'),
Floor('.');
companion object {
fun valueOfRep(rep: Char): GridElement =
values().firstOrNull { it.rep == rep }
?: throw IllegalArgumentException("No element with rep $rep")
}
}
typealias Position = Pair<Int, Int>
data class Seating(val grid: List<List<GridElement>>) {
val occupiedSeats: Int =
grid.map { row -> row.count { it == OccupiedSeat } }.sum()
fun occupiedNeighbours(position: Position): Int =
listOf(-1, 0, 1)
.combinations()
.filterNot { it == Pair(0, 0) }
.map { Position(position.first + it.first, position.second + it.second) }
.filter {
it.first in 0..grid.lastIndex
&& it.second in 0..grid[position.first].lastIndex
}
.count { grid[it.first][it.second] == OccupiedSeat }
fun occupiedVisibles(position: Position): Int =
listOf(-1, 0, 1)
.combinations()
.filterNot { it == Pair(0, 0) }
.mapNotNull { direction ->
// Get first seat (aka non-floor) in this direction
position
.projectRay(direction) {
first in 0..grid.lastIndex && second in 0..grid[position.first].lastIndex
}
.filter { it != position }
.firstOrNull { grid[it.first][it.second] != Floor }
}
.count { grid[it.first][it.second] == OccupiedSeat }
fun blink(willSitDown: (Position) -> Boolean, willGetUp: (Position) -> Boolean) =
grid.mapIndexed { rowIndex, row ->
row.mapIndexed { colIndex, it ->
if (it == EmptySeat && willSitDown(Position(rowIndex, colIndex))) {
OccupiedSeat
} else if (it == OccupiedSeat && willGetUp(Position(rowIndex, colIndex))) {
EmptySeat
} else {
it
}
}
}.let { Seating(it) }
override fun toString() =
grid.joinToString("\n") { row -> row.joinToString("") { "${it.rep}" } }
}
fun stableSeating(initial: Seating, step: (Seating).() -> Seating): Seating {
var currentSeating = initial
do {
val lastSeating = currentSeating
currentSeating = step(lastSeating)
} while (currentSeating != lastSeating)
return currentSeating
}
val seating = File(args[0])
.readLines()
.map { it.map { rep -> GridElement.valueOfRep(rep) } }
.let { Seating(it) }
// Part 1:
println(
stableSeating(seating) {
blink({ occupiedNeighbours(it) == 0 }, { occupiedNeighbours(it) >= 4 })
}.occupiedSeats
)
// Part 2:
println(
stableSeating(seating) {
blink({ occupiedVisibles(it) == 0 }, { occupiedVisibles(it) >= 5 })
}.occupiedSeats
)
| 0 | Kotlin | 0 | 0 | f17184fe55dfe06ac8897c2ecfe329a1efbf6a09 | 3,040 | advent-of-code-2020 | The Unlicense |
src/year2023/day24/Day24.kt | lukaslebo | 573,423,392 | false | {"Kotlin": 222221} | package year2023.day24
import check
import com.microsoft.z3.*
import readInput
import java.math.BigDecimal
fun main() {
val testInput = readInput("2023", "Day24_test")
check(part1(testInput, testArea = 7L..27L), 2)
check(part2(testInput), 47)
val input = readInput("2023", "Day24")
println(part1(input, testArea = 200000000000000..400000000000000))
println(part2(input))
}
private fun part1(input: List<String>, testArea: LongRange): Int {
val particles = input.parseParticles()
val pairs = mutableSetOf<Set<Particle>>()
for (p1 in particles) {
for (p2 in particles) {
if (p1 != p2) pairs += setOf(p1, p2)
}
}
return pairs.count { hasFutureCrossingInTestArea(it.first(), it.last(), testArea) }
}
private data class Pos(val x: BigDecimal, val y: BigDecimal, val z: BigDecimal)
private data class Line2D(val a: BigDecimal, val b: BigDecimal, val c: BigDecimal)
private data class Particle(val pos: Pos, val velocity: Pos, val line2D: Line2D)
private fun String.parseParticle(): Particle {
val (pos, velocity) = split(",", "@").map { it.trim().toBigDecimal() }.chunked(3).map { (x, y, z) -> Pos(x, y, z) }
val line2D = Line2D(velocity.y, -velocity.x, velocity.y * pos.x - velocity.x * pos.y)
return Particle(pos = pos, velocity = velocity, line2D = line2D)
}
private fun List<String>.parseParticles() = map { it.parseParticle() }
private fun hasFutureCrossingInTestArea(p1: Particle, p2: Particle, testArea: LongRange): Boolean {
val (a1, b1, c1) = p1.line2D
val (a2, b2, c2) = p2.line2D
if (a1 * b2 == b1 * a2) {
return false
}
val x = (c1 * b2 - c2 * b1) / (a1 * b2 - a2 * b1)
val y = (c2 * a1 - c1 * a2) / (a1 * b2 - a2 * b1)
fun Particle.isAhead() = (x - pos.x) * velocity.x >= BigDecimal.ZERO && (y - pos.y) * velocity.y >= BigDecimal.ZERO
return p1.isAhead() && p2.isAhead() && x in testArea && y in testArea
}
private operator fun LongRange.contains(num: BigDecimal) = num >= first.toBigDecimal() && num <= last.toBigDecimal()
private fun part2(input: List<String>): Long = with(Context()) {
val particles = input.parseParticles()
val solver = mkSolver()
val x = mkRealConst("x")
val y = mkRealConst("y")
val z = mkRealConst("z")
val vx = mkRealConst("vx")
val vy = mkRealConst("vy")
val vz = mkRealConst("vz")
val zero = mkReal(0)
fun BigDecimal.real() = mkReal(toLong())
operator fun <R : ArithSort> ArithExpr<R>.times(other: ArithExpr<R>) = mkMul(this, other)
operator fun <R : ArithSort> ArithExpr<R>.minus(other: ArithExpr<R>) = mkSub(this, other)
infix fun <R : ArithSort> ArithExpr<R>.eq(other: ArithExpr<R>) = mkEq(this, other)
operator fun Model.get(x: Expr<RealSort>): Long = (getConstInterp(x) as RatNum).let {
it.bigIntNumerator.toLong() / it.bigIntDenominator.toLong()
}
for (particle in particles) {
val (pos, v) = particle
solver.add((((x - pos.x.real()) * (v.y.real() - vy)) - ((y - pos.y.real()) * (v.x.real() - vx))) eq zero)
solver.add((((y - pos.y.real()) * (v.z.real() - vz)) - ((z - pos.z.real()) * (v.y.real() - vy))) eq zero)
}
if (solver.check() != Status.SATISFIABLE) error("no solution found")
return solver.model[x] + solver.model[y] + solver.model[z]
}
| 0 | Kotlin | 0 | 1 | f3cc3e935bfb49b6e121713dd558e11824b9465b | 3,335 | AdventOfCode | Apache License 2.0 |
src/Day12.kt | mpythonite | 572,671,910 | false | {"Kotlin": 29542} | import java.time.InstantSource
fun main() {
class GridSpot(val height: Int, var distance: Int = Int.MAX_VALUE)
class Move(val destX: Int, val destY: Int, val direction: String)
class Grid() {
var grid: Array<Array<GridSpot>> = arrayOf()
var moves: ArrayDeque<Move> = ArrayDeque()
fun addMoves(x: Int, y: Int, direction: String) {
var source = grid[x][y]
var dest: GridSpot
if (x > 0 && direction != "right") {
dest = grid[x-1][y]
if (dest.height + 1 >= source.height && dest.distance > source.distance + 1) {
dest.distance = source.distance + 1
moves.addFirst(Move(x-1, y, "left"))
}
}
if (x < grid.size - 1 && direction != "left") {
dest = grid[x+1][y]
if (dest.height + 1 >= source.height && dest.distance > source.distance + 1) {
dest.distance = source.distance + 1
moves.addFirst(Move(x+1, y, "right"))
}
}
if (y > 0 && direction != "down") {
dest = grid[x][y-1]
if (dest.height + 1 >= source.height && dest.distance > source.distance + 1) {
dest.distance = source.distance + 1
moves.addFirst(Move(x, y-1, "up"))
}
}
if (y < grid.first().size - 1 && direction != "up") {
dest = grid[x][y+1]
if (dest.height + 1 >= source.height && dest.distance > source.distance + 1) {
dest.distance = source.distance + 1
moves.addFirst(Move(x, y+1, "down"))
}
}
}
}
fun CreateMap(
input: List<String>,
start: Pair<Int, Int>,
end: Pair<Int, Int>,
map: Grid
): Pair<Pair<Int, Int>, Pair<Int, Int>> {
var start1 = start
var end1 = end
for (i in input.indices) {
var row = arrayOf<GridSpot>()
for (j in input[i].indices) {
val curr = input[i][j]
when (curr) {
'S' -> {
start1 = Pair(i, j)
row += GridSpot(0)
}
'E' -> {
end1 = Pair(i, j)
row += GridSpot('z' - 'a', 0)
}
else -> {
row += GridSpot(curr - 'a')
}
}
}
map.grid += row
}
return Pair(end1, start1)
}
fun part1(input: List<String>): Int {
var map = Grid()
var start: Pair<Int, Int> = Pair(-1, -1)
var end: Pair<Int, Int> = Pair(-1, -1)
val pair = CreateMap(input, start, end, map)
end = pair.first
start = pair.second
map.addMoves(end.first, end.second, "none")
while(map.moves.any()) {
val move = map.moves.removeFirst()
map.addMoves(move.destX, move.destY, move.direction)
}
return map.grid[start.first][start.second].distance
}
fun part2(input: List<String>): Int {
var map = Grid()
var start: Pair<Int, Int> = Pair(-1, -1)
var end: Pair<Int, Int> = Pair(-1, -1)
val pair = CreateMap(input, start, end, map)
end = pair.first
start = pair.second
map.addMoves(end.first, end.second, "none")
while(map.moves.any()) {
val move = map.moves.removeFirst()
map.addMoves(move.destX, move.destY, move.direction)
}
var shortest = Int.MAX_VALUE
for (row in map.grid) {
row.forEach {
if (it.height == 0 && it.distance < shortest) shortest = it.distance
}
}
return shortest
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInput("Day12")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | cac94823f41f3db4b71deb1413239f6c8878c6e4 | 4,224 | advent-of-code-2022 | Apache License 2.0 |
src/Day05.kt | ajspadial | 573,864,089 | false | {"Kotlin": 15457} | import java.util.*
fun main() {
fun loadCrates(input: List<String>): MutableList<Stack<String>> {
val stacks : MutableList<Stack<String>> = mutableListOf<Stack<String>>()
for (line in input) {
var nextCrate = line.indexOf('[')
while (nextCrate != -1) {
val crate = line.substring(nextCrate + 1, nextCrate + 2)
val stackNumber = nextCrate / 4 + 1
if (stackNumber > stacks.size) {
val currentStackSize = stacks.size
for (i in currentStackSize until stackNumber) {
stacks.add(Stack())
}
}
stacks[stackNumber - 1].push(crate)
nextCrate = line.indexOf("[", nextCrate + 1)
}
}
stacks.forEach{it.reverse()}
return stacks
}
fun part1(input: List<String>): String {
var result = ""
val stacks = loadCrates(input)
for (line in input) {
if (line.startsWith("move")) {
// then process orders
val quantity = line.substring(5, line.indexOf("from") - 1).toInt()
val origin = line.substring(line.indexOf("from") + 5, line.indexOf("to") - 1).toInt()
val destination = line.substring(line.indexOf("to") + 3).toInt()
for (i in 1..quantity) {
val crate = stacks[origin - 1].pop()
stacks[destination - 1].push(crate)
}
}
}
for (s in stacks) {
result += s.pop()
}
return result
}
fun part2(input: List<String>): String {
var result = ""
val stacks = loadCrates(input)
for (line in input) {
if (line.startsWith("move")) {
// then process orders
val quantity = line.substring(5, line.indexOf("from") - 1).toInt()
val origin = line.substring(line.indexOf("from")+5, line.indexOf("to") - 1).toInt()
val destination = line.substring(line.indexOf("to")+3).toInt()
val intermediateStack = Stack<String>()
for (i in 1 .. quantity) {
val crate = stacks[origin - 1].pop()
intermediateStack.push(crate)
}
for (i in 1 .. quantity) {
val crate = intermediateStack.pop()
stacks[destination - 1].push(crate)
}
}
}
for (s in stacks) {
result += s.pop()
}
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInput("Day05")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | ed7a2010008be17fec1330b41adc7ee5861b956b | 2,941 | adventofcode2022 | Apache License 2.0 |
leetcode-75-kotlin/src/main/kotlin/MaximumNumberOfVowelsInASubstringOfGivenLength.kt | Codextor | 751,507,040 | false | {"Kotlin": 49566} | /**
* Given a string s and an integer k, return the maximum number of vowel letters in any substring of s with length k.
*
* Vowel letters in English are 'a', 'e', 'i', 'o', and 'u'.
*
*
*
* Example 1:
*
* Input: s = "abciiidef", k = 3
* Output: 3
* Explanation: The substring "iii" contains 3 vowel letters.
* Example 2:
*
* Input: s = "aeiou", k = 2
* Output: 2
* Explanation: Any substring of length 2 contains 2 vowels.
* Example 3:
*
* Input: s = "leetcode", k = 3
* Output: 2
* Explanation: "lee", "eet" and "ode" contain 2 vowels.
*
*
* Constraints:
*
* 1 <= s.length <= 10^5
* s consists of lowercase English letters.
* 1 <= k <= s.length
* @see <a href="https://leetcode.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length/">LeetCode</a>
*/
fun maxVowels(s: String, k: Int): Int {
val setOfVowels = setOf('a', 'e', 'i', 'o', 'u')
var currentVowelCount = 0
var startIndex = 0
var endIndex = k
for (index in 0 until endIndex) {
if (s[index] in setOfVowels) {
currentVowelCount++
}
}
var maxVowelCount = currentVowelCount
while (endIndex < s.length) {
if (s[endIndex++] in setOfVowels) currentVowelCount++
if (s[startIndex++] in setOfVowels) currentVowelCount--
maxVowelCount = maxOf(maxVowelCount, currentVowelCount)
}
return maxVowelCount
}
| 0 | Kotlin | 0 | 0 | 0511a831aeee96e1bed3b18550be87a9110c36cb | 1,388 | leetcode-75 | Apache License 2.0 |
src/day03/Day03.kt | schrami8 | 572,631,109 | false | {"Kotlin": 18696} | package day03
import readInput
fun charToPriority(char: Char): Int =
when (char) {
in 'a'..'z' -> char.code - 96 // 'a' is 97 on the ascii table
in 'A'..'Z' -> char.code - 64 + 26 // 'A' is 65 on the ascii table
else -> 0
}
fun main() {
fun part1(input: List<String>): Int {
return input.map { it.chunked(it.length / 2) { str -> str.toSet() }}
.flatMap { it.reduce { acc, next -> acc.intersect(next) } }
.sumOf { charToPriority(it) }
}
fun part2(input: List<String>): Int {
return input.chunked(3) { it.map { str -> str.toSet() } }
.flatMap { it.reduce { acc, next -> acc.intersect(next) } }
.sumOf { charToPriority(it) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day03/Day03_test")
check(part1(testInput) == 157)
val input = readInput("day03/Day03")
println(part1(input))
val testInput2 = readInput("day03/Day03_test")
check(part2(testInput2) == 70)
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 215f89d7cd894ce58244f27e8f756af28420fc94 | 1,064 | advent-of-code-kotlin | Apache License 2.0 |
src/main/java/com/barneyb/aoc/aoc2022/day05/SupplyStacks.kt | barneyb | 553,291,150 | false | {"Kotlin": 184395, "Java": 104225, "HTML": 6307, "JavaScript": 5601, "Shell": 3219, "CSS": 1020} | package com.barneyb.aoc.aoc2022.day05
import com.barneyb.aoc.util.Slice
import com.barneyb.aoc.util.Solver
import com.barneyb.aoc.util.toInt
import com.barneyb.aoc.util.toSlice
import com.barneyb.util.Stack
fun main() {
Solver.benchmark(
::parse,
::crateMover9000,
::crateMover9001,
)
}
internal typealias Stacks = Array<Stack<Char>>
internal typealias Instructions = List<Ins>
internal data class Ins(val n: Int, val from: Int, val to: Int)
internal class ParseResult(
private val stacks: Stacks,
val instructions: Instructions,
) {
fun freshStacks() =
Array(stacks.size) { stacks[it].clone() }
}
internal fun parse(input: String) =
input.toSlice().let { raw ->
raw.indexOf("\n\n").let { idxSplit ->
ParseResult(
parseStacks(raw[0, idxSplit]),
parseInstructions(raw[idxSplit, raw.length])
)
}
}
internal fun parseStacks(input: Slice) =
input.lines()
.filter(Slice::isNotBlank)
.let { lines ->
lines.last()
.withIndex()
.filter { (_, c) -> c.isDigit() }
.map { (cIdx, _) ->
Stack<Char>().apply {
for (l in lines.size - 2 downTo 0) {
val v = lines[l][cIdx]
if (v.isWhitespace()) break // reached top
push(v)
}
}
}
.toTypedArray()
}
// move 2 from 2 to 1
internal fun parseInstructions(input: Slice) =
input.trim()
.lines()
.map { it.split(' ') }
.map { Ins(it[1].toInt(), it[3].toInt() - 1, it[5].toInt() - 1) }
internal fun crateMover9000(parse: ParseResult) =
parse.freshStacks().apply {
parse.instructions.forEach { ins ->
repeat(ins.n) {
this[ins.to].push(this[ins.from].pop())
}
}
}.topsAsString()
private fun Stacks.topsAsString() =
buildString {
this@topsAsString.forEach { append(it.peek()) }
}
internal fun crateMover9001(parse: ParseResult) =
parse.freshStacks().apply {
val temp = Stack<Char>()
parse.instructions.forEach { ins ->
repeat(ins.n) {
temp.push(this[ins.from].pop())
}
while (temp.isNotEmpty()) {
this[ins.to].push(temp.pop())
}
}
}.topsAsString()
| 0 | Kotlin | 0 | 0 | 8b5956164ff0be79a27f68ef09a9e7171cc91995 | 2,525 | aoc-2022 | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinimumGeneticMutation.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 java.util.LinkedList
import java.util.Queue
/**
* 433. Minimum Genetic Mutation
* @see <a href="https://leetcode.com/problems/minimum-genetic-mutation/">Source</a>
*/
fun interface MinimumGeneticMutation {
fun minMutation(start: String, end: String, bank: Array<String>): Int
}
/**
* Approach: BFS (Breadth-First Search)
*/
class MinimumGeneticMutationBFS : MinimumGeneticMutation {
override fun minMutation(start: String, end: String, bank: Array<String>): Int {
val queue: Queue<String> = LinkedList()
val seen: MutableSet<String> = HashSet()
queue.add(start)
seen.add(start)
var steps = 0
while (queue.isNotEmpty()) {
val nodesInQueue: Int = queue.size
for (j in 0 until nodesInQueue) {
val node: String = queue.remove()
if (node == end) {
return steps
}
for (c in charArrayOf('A', 'C', 'G', 'T')) {
for (i in node.indices) {
val neighbor = node.substring(0, i) + c + node.substring(i + 1)
if (!seen.contains(neighbor) && bank.contains(neighbor)) {
queue.add(neighbor)
seen.add(neighbor)
}
}
}
}
steps++
}
return -1
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,074 | kotlab | Apache License 2.0 |
src/main/kotlin/Main.kt | BrightOS | 618,253,629 | false | null | import java.io.File
const val QUANTUM_TIME = 2
private var numberOfPriorityTicks = 0
fun parseInputFile(file: File): Pair<ArrayList<Process>, Int> {
var resultNumberOfTicks = 0
val list = arrayListOf<Process>().apply {
file.forEachLine {
it.split(" ").let {
add(
Process(
name = it[0],
numberOfTicks = it[1].toInt(),
priority = it[2].toInt(),
afterWhatTick = (if (it.size > 3) it[3] else "0").toInt()
).let {
if (it.priority > 0)
numberOfPriorityTicks += it.numberOfTicks
resultNumberOfTicks += it.numberOfTicks
it
}
)
}
}
}
return Pair(list, resultNumberOfTicks)
}
fun main() {
val numberOfActualTicks: Int
var numberOfWaitTicks = 0
var numberOfAbstractTicks = 0
val processList = parseInputFile(
// File("test1")
File("test2")
// File("test3")
).let {
numberOfActualTicks = it.second
it.first
}.apply {
sortBy { it.priority }
}
val ticks = arrayListOf<String>()
repeat(numberOfActualTicks / QUANTUM_TIME) {
if (it < (numberOfActualTicks - numberOfPriorityTicks) / QUANTUM_TIME)
processList.filter { it.priority == 0 }.forEach { process ->
if (process.ticksLeft > 0) {
repeat(minOf(QUANTUM_TIME, process.ticksLeft)) {
process.ticksLeft--
ticks.add(process.name)
}
}
}
else
processList.filter { it.priority > 0 }.forEach { process ->
if (process.ticksLeft > 0) {
repeat(minOf(QUANTUM_TIME, process.ticksLeft)) {
process.ticksLeft--
ticks.add(process.afterWhatTick, process.name)
}
}
}
}
processList.forEach { process ->
print(
"${process.name} ${process.priority} ${process.numberOfTicks} "
)
ticks.subList(0, ticks.indexOfLast { it.contains(process.name) } + 1).forEach {
print(it.contains(process.name).let {
if (!it) numberOfWaitTicks++
numberOfAbstractTicks++
if (it) "И" else "Г"
})
}
println()
}
// println(ticks)
println("Efficiency: ${"%.${2}f".format(((1 - numberOfWaitTicks.toFloat() / numberOfAbstractTicks) * 100))}% | With quantum time: $QUANTUM_TIME")
}
data class Process(
val name: String,
val numberOfTicks: Int,
val priority: Int,
val afterWhatTick: Int = 0,
var ticksLeft: Int = numberOfTicks
) | 0 | Kotlin | 0 | 0 | 84f5b7175ec6a750c5c16410a8f90d3d42e09952 | 2,915 | os_2 | Apache License 2.0 |
2022/Day08.kt | amelentev | 573,120,350 | false | {"Kotlin": 87839} | fun main() {
val input = readInput("Day08")
var res1 = 0
var res2 = 0
for (i0 in input.indices) {
for (j0 in input[i0].indices) {
val t = input[i0][j0]
val visible =
(0 until i0).all { input[it][j0] < t } ||
(i0+1 until input.size).all { input[it][j0] < t } ||
(0 until j0).all { input[i0][it] < t } ||
(j0+1 until input[i0].length).all { input[i0][it] < t }
if (visible) res1 ++
fun calcDist(r: IntProgression, f: (Int) -> Char): Int {
var res = 0
for (i in r) {
if (f(i) < t) res++
else {
res++
break
}
}
return res
}
var r2 = calcDist(i0-1 downTo 0) { input[it][j0] }
r2 *= calcDist(i0+1 until input.size) { input[it][j0] }
r2 *= calcDist(j0-1 downTo 0) { input[i0][it] }
r2 *= calcDist(j0+1 until input[i0].length) { input[i0][it] }
res2 = maxOf(res2, r2)
}
}
println(res1)
println(res2)
}
| 0 | Kotlin | 0 | 0 | a137d895472379f0f8cdea136f62c106e28747d5 | 1,195 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/org/kotrix/matrix/decomp/CholeskyDecompPrototype.kt | JarnaChao09 | 285,169,397 | false | {"Kotlin": 446442, "Jupyter Notebook": 26378} | package org.kotrix.matrix.decomp
import org.kotrix.matrix.DoubleMatrix
import org.kotrix.utils.by
import kotlin.math.max
import kotlin.math.sqrt
fun List<List<Double>>.transpose(): List<List<Double>> {
val ret = MutableList(this.size) { MutableList(this.size) { 0.0 } }
for (i in this.indices) {
for (j in this.indices) {
ret[i][j] = this[j][i]
}
}
return ret.toList()
}
operator fun String.times(other: Int): String = this.run {
var ret = ""
for(i in 0 until other) {
ret += this
}
ret
}
fun List<List<Double>>.matrixString(): String {
val retString = List(size = 0) { MutableList(0) { "" } }.toMutableList()
var maxLength = 0
this.forEach { it.forEach { i -> maxLength = max(maxLength, i.toString().length) } }
for (r in this) {
val dummy = MutableList(0) { "" }
for (c in r) {
dummy.add((" " * (maxLength - c.toString().length) + c.toString()))
}
retString += dummy
}
return retString.joinToString(prefix = "[", postfix = "]", separator = ",\n ")
}
fun List<List<Double>>.LLTDecomp(): Pair<List<List<Double>>, List<List<Double>>> {
val lower = MutableList(this.size) { MutableList(this.size) { 0.0 } }
for (i in this.indices) {
for (j in this.indices) {
var sum = 0.0
if (j == i) {
for (k in 0 until j) {
sum += lower[j][k] * lower[j][k]
}
lower[i][j] = sqrt(this[j][j] - sum)
} else {
for (k in 0 until j) {
sum += lower[i][k] * lower[j][k]
}
if (lower[j][j] > 0) {
lower[i][j] = (this[i][j] - sum) / lower[j][j]
}
}
}
}
return lower to lower.transpose()
}
fun main() {
val llt_test = listOf(
listOf(4.0, 12.0, -16.0),
listOf(12.0, 37.0, -43.0),
listOf(-16.0, -43.0, 98.0),
)
val (L, L_T) = llt_test.LLTDecomp()
println("${L.matrixString()}\n${L_T.matrixString()}")
for (i in 0..1) println()
val matrix = DoubleMatrix.of(3 by 3, 4,12,-16,12,37,-43,-16,-43,98)
val (L1, L_T1) = CholeskyDecomposition(matrix)
println("$L1\n$L_T1")
}
| 0 | Kotlin | 1 | 5 | c5bb19457142ce1f3260e8fed5041a4d0c77fb14 | 2,299 | Kotrix | MIT License |
src/main/kotlin/day15/BacktrackingPathfinder.kt | Ostkontentitan | 434,500,914 | false | {"Kotlin": 73563} | package day15
class BacktrackingPathfinder : Pathfinder {
override fun searchOptimalPath(
map: Array<Array<Int>>
): Int {
val destination = CavePosition(map.lastIndex, map.first().lastIndex, map.last().last())
val start = CavePosition(0, 0, map[0][0])
val bestForPosition: Array<Array<Int?>> = (1..map.size).map {
arrayOfNulls<Int?>(map.size)
}.toTypedArray()
return findBestPath(
destination = destination,
map = map,
bestForPosition = bestForPosition
) - start.risk
}
private fun findBestPath(
destination: CavePosition,
map: Array<Array<Int>>,
bestForPosition: Array<Array<Int?>>
): Int {
val pathfinder = ArrayDeque<CavePosition>()
pathfinder.add(CavePosition(0, 0, map[0][0]))
var bestRiskToDestination = Integer.MAX_VALUE
while (pathfinder.isNotEmpty()) {
val currentItem = pathfinder.last()
val currentPath = pathfinder.toList()
val currentRisk = currentPath.sumOf { it.risk }
if (currentItem == destination && currentRisk < bestRiskToDestination) {
bestRiskToDestination = currentRisk
println("Found better path with risk $bestRiskToDestination")
}
bestForPosition[currentItem.y][currentItem.x] = currentRisk
val visitable = visitablePositionsFrom(pathfinder.last(), map).filterNot { candidate ->
isCandidateUnworthy(
candidate,
currentPath,
currentRisk,
bestForPosition,
bestRiskToDestination
)
}
if (visitable.isEmpty()) {
pathfinder.removeLast()
} else {
pathfinder.addLast(visitable.first())
}
}
return bestRiskToDestination
}
private fun isCandidateUnworthy(
candidate: CavePosition,
visited: List<CavePosition>,
currentRisk: Int,
bestForPosition: Array<Array<Int?>>,
bestTotalRisk: Int
): Boolean {
val candidatePathRisk = currentRisk + candidate.risk
if (candidatePathRisk >= bestTotalRisk) {
return true
}
val knownBest = bestForPosition[candidate.y][candidate.x]
val hasBetterOrEqualRouteTo = knownBest != null && candidatePathRisk >= knownBest
if (hasBetterOrEqualRouteTo) {
return true
}
if (visited.contains(candidate)) {
return true
}
if (visited.count { candidate.inProximityTo(it) } > 1) {
return true
}
return false
}
private fun visitablePositionsFrom(
current: CavePosition,
map: Array<Array<Int>>
): List<CavePosition> {
val x = current.x
val y = current.y
val pool = listOf(
y + 1 to x,
y to x + 1,
y to x - 1,
y - 1 to x
)
return pool.mapNotNull { (y, x) ->
val risk = map.getOrNull(y)?.getOrNull(x)
if (risk == null) {
null
} else {
CavePosition(y, x, risk)
}
}
}
} | 0 | Kotlin | 0 | 0 | e0e5022238747e4b934cac0f6235b92831ca8ac7 | 3,338 | advent-of-kotlin-2021 | Apache License 2.0 |
src/day25/Day25.kt | easchner | 572,762,654 | false | {"Kotlin": 104604} | package day25
import readInputString
import java.lang.Math.abs
import java.lang.Math.pow
import java.util.PriorityQueue
import kotlin.math.pow
import kotlin.system.measureNanoTime
fun main() {
fun snafuToDecimal(snafu: String): Long {
var total = 0L
for (i in snafu.indices) {
val power = 5.0.pow(snafu.length - i.toDouble() - 1).toLong()
total += when (snafu[i]) {
'2' -> 2L * power
'1' -> 1L * power
'0' -> 0L
'-' -> -1L * power
'=' -> -2L * power
else -> 0L
}
}
return total
}
fun decimalToSnafu(decimal: Long): String {
var remainder = decimal
var snafu = ""
// Find biggest power of 5 that fits
var fives = 1L
while (fives < decimal) {
fives *= 5
}
fives /= 5
while (fives >= 1) {
// How many fives can we pull out ?
val div = (remainder + fives / 2 * if (remainder > 0) 1 else -1) / fives
snafu += when (div.toInt()) {
0 -> "0"
1 -> "1"
2 -> "2"
-1 -> "-"
-2 -> "="
else -> ""
}
remainder -= fives * div
fives /= 5
}
return snafu
}
fun part1(input: List<String>): String {
return decimalToSnafu(input.sumOf { snafuToDecimal(it) })
}
fun part2(input: List<String>): String {
return ""
}
val testInput = readInputString("day25/test")
val input = readInputString("day25/input")
check(part1(testInput) == "2=-1=0")
val time1 = measureNanoTime { println(part1(input)) }
println("Time for part 1 was ${"%,d".format(time1)} ns")
check(part2(testInput) == "")
val time2 = measureNanoTime { println(part2(input)) }
println("Time for part 2 was ${"%,d".format(time2)} ns")
} | 0 | Kotlin | 0 | 0 | 5966e1a1f385c77958de383f61209ff67ffaf6bf | 1,986 | Advent-Of-Code-2022 | Apache License 2.0 |
src/main/kotlin/days/Day7Data.kt | yigitozgumus | 572,855,908 | false | {"Kotlin": 26037} | package days
import utils.SolutionData
import java.util.Stack
fun main() = with(Day7Data()) {
solvePart1()
solvePart2()
}
sealed interface FileSystem {
data class Dir(
val name: String,
val contents: MutableList<FileSystem> = mutableListOf()
): FileSystem
data class File(val name: String, val size: Int): FileSystem
}
class Day7Data: SolutionData(inputFile = "inputs/day7.txt") {
private lateinit var output : FileSystem.Dir
val dirList = mutableListOf<FileSystem.Dir>()
fun processCommands() {
output = FileSystem.Dir(name = rawData.first().split(" ").last())
val current: Stack<FileSystem.Dir> = Stack<FileSystem.Dir>().also { it.push(output) }
dirList.add(output)
rawData.drop(1).map { it.split(" ") }.forEach { args ->
when {
args[0] == "$" && args[1] == "ls" -> {}
args[0] == "$" && args[1] == "cd" && args[2] == ".." -> current.pop()
args[0] == "$" && args[1] == "cd" -> {
val target = current.peek().contents.find { (it as? FileSystem.Dir)?.name == args[2] }
current.push(target as FileSystem.Dir)
dirList.add(target)
}
args[0] == "dir" -> current.peek().contents.add(FileSystem.Dir(name = args[1]))
else -> current.peek().contents.add(FileSystem.File(name = args[1], size = args[0].toInt()))
}
}
}
fun findTotalSize(of: FileSystem.Dir): Int = of.contents.sumOf {
if (it is FileSystem.File) it.size else if (it is FileSystem.Dir) findTotalSize(it) else 0
}
}
fun Day7Data.solvePart1() {
processCommands()
dirList.map { findTotalSize(it) }.filter { it < 100000 }.sum().also { println(it) }
}
fun Day7Data.solvePart2() {
val needed = 70_000_000 - findTotalSize(dirList.first())
val enough = 30_000_000 - needed
println(dirList.map { findTotalSize(it) }.filter { it > enough }.minOf { it })
} | 0 | Kotlin | 0 | 0 | 9a3654b6d1d455aed49d018d9aa02d37c57c8946 | 1,781 | AdventOfCode2022 | MIT License |
src/main/kotlin/Day11.kt | i-redbyte | 433,743,675 | false | {"Kotlin": 49932} | import java.util.*
class Cavern(private val octopi: Array<IntArray>) {
constructor(lines: List<String>) :
this(lines.map { it.map { c -> c.digitToInt() }.toIntArray() }.toTypedArray())
fun step(): Pair<Cavern, Int> {
val incremented = Array(10) { IntArray(10) }
val flashSpots = LinkedList<Pair<Int, Int>>()
(0 until 10).forEach { i ->
(0 until 10).forEach { j ->
incremented[i][j] = octopi[i][j] + 1
if (incremented[i][j] == 10) {
flashSpots += i to j
}
}
}
val flashedAlready = flashSpots.toMutableSet()
while (flashSpots.isNotEmpty()) {
val (ci, cj) = flashSpots.poll()
(-1 until 2).forEach { i ->
(-1 until 2).forEach inner@{ j ->
val point = (ci + i) to (cj + j)
val (pi, pj) = point
if (point in flashedAlready) return@inner
if (pi >= 0 && pj >= 0 && pi < 10 && pj < 10) {
incremented[pi][pj]++
if (incremented[pi][pj] == 10) {
flashedAlready += point
flashSpots.add(point)
}
}
}
}
}
(0 until 10).forEach { i ->
(0 until 10).forEach { j ->
incremented[i][j] = if (incremented[i][j] > 9) 0 else incremented[i][j]
}
}
return Cavern(incremented) to flashedAlready.size
}
}
fun main() {
val data = readInputFile("day11")
fun part1(): Int {
var cavern = Cavern(data)
var flashes = 0
repeat(100) {
val (newCavern, newFlashes) = cavern.step()
cavern = newCavern
flashes += newFlashes
}
return flashes
}
fun part2(): Int {
var cavern = Cavern(data)
var i = 0
do {
val (newCavern, newFlashes) = cavern.step()
cavern = newCavern
i++
} while (newFlashes != 100)
return i
}
println("Result part1: ${part1()}")
println("Result part2: ${part2()}")
}
| 0 | Kotlin | 0 | 0 | 6d4f19df3b7cb1906052b80a4058fa394a12740f | 2,265 | AOC2021 | Apache License 2.0 |
src/day14/Day14.kt | idle-code | 572,642,410 | false | {"Kotlin": 79612} | package day14
import Position
import log
import logEnabled
import logln
import readInput
import kotlin.math.max
private const val DAY_NUMBER = 14
data class Line(val start: Position, val end: Position) {
init {
if (start >= end)
throw IllegalArgumentException("Start cannot be greater than end")
if (start.x != end.x && start.y != end.y)
throw IllegalArgumentException("Segment is not straight")
}
override fun toString(): String {
return "$start - $end"
}
fun isVertical(): Boolean {
return start.x == end.x
}
}
fun parseFile(rawInput: List<String>): List<List<Line>> {
val allSegments = mutableListOf<List<Line>>()
for (line in rawInput) {
val segmentsInLine = parseSegments(line)
allSegments.add(segmentsInLine)
}
return allSegments
}
fun parseSegments(line: String): List<Line> {
val pointsInRockLine = line.split(" -> ").map { coords ->
val x = coords.substringBefore(',')
val y = coords.substringAfter(',')
Position(x.toInt() - 1, y.toInt() - 1)
}
val rockSegments = mutableListOf<Line>()
for (i in 1..pointsInRockLine.lastIndex) {
if (pointsInRockLine[i - 1] < pointsInRockLine[i])
rockSegments.add(Line(pointsInRockLine[i - 1], pointsInRockLine[i]))
else
rockSegments.add(Line(pointsInRockLine[i], pointsInRockLine[i - 1]))
}
return rockSegments
}
val sandStart = Position(499, -1)
enum class SpaceType(val symbol: Char) {
Air('.'),
Rock('#'),
Sand('o'),
}
fun fillWithRocks(fallMap: Array<Array<SpaceType>>, rockLines: List<Line>) {
for (line in rockLines) {
if (line.isVertical()) {
val x = line.start.x
for (y in line.start.y..line.end.y)
fallMap[y][x] = SpaceType.Rock
} else {
val y = line.start.y
for (x in line.start.x..line.end.x)
fallMap[y][x] = SpaceType.Rock
}
}
}
fun addFloor(fallMap: Array<Array<SpaceType>>) {
val width = fallMap[0].size
val y = fallMap.lastIndex
for (x in 0 until width)
fallMap[y][x] = SpaceType.Rock
}
private fun Array<Array<SpaceType>>.print() {
logln("")
for (y in 0..this.lastIndex) {
for (x in 0..this[0].lastIndex)
log(this[y][x].symbol)
logln("")
}
}
private fun Position.fallPositions(): List<Position> {
return listOf(
Position(this.x, this.y + 1),
Position(this.x - 1, this.y + 1),
Position(this.x + 1, this.y + 1)
)
}
fun Array<Array<SpaceType>>.dropSandAt(start: Position): Position? {
var current = start
simulationLoop@ while (true) {
for (candidatePos in current.fallPositions()) {
if (!this.containsPosition(candidatePos))
return null
if (this[candidatePos.y][candidatePos.x] == SpaceType.Air) {
current = candidatePos
continue@simulationLoop
}
}
break
}
return current
}
private fun Array<Array<SpaceType>>.containsPosition(position: Position): Boolean {
return position.y < this.size && position.x < this[0].size && position.y >= 0 && position.x >= 0
}
fun main() {
fun part1(rawInput: List<String>): Int {
val rockLines = parseFile(rawInput)
val maxX = rockLines.maxOf { lines -> lines.maxOf { line -> kotlin.math.max(line.start.x, line.end.x) } }
val maxY = rockLines.maxOf { lines -> lines.maxOf { line -> kotlin.math.max(line.start.y, line.end.y) } }
val fallMap = Array(maxY + 1) { Array(maxX + 1) { SpaceType.Air } }
fillWithRocks(fallMap, rockLines.flatten())
// fallMap.print()
var fallenGrains = 0
while (true) {
val restPosition = fallMap.dropSandAt(sandStart)
if (restPosition == null)
break
fallMap[restPosition.y][restPosition.x] = SpaceType.Sand
++fallenGrains
}
fallMap.print()
return fallenGrains
}
fun part2(rawInput: List<String>): Int {
val rockLines = parseFile(rawInput)
val maxY = rockLines.maxOf { lines -> lines.maxOf { line -> kotlin.math.max(line.start.y, line.end.y) } }
var maxX = rockLines.maxOf { lines -> lines.maxOf { line -> kotlin.math.max(line.start.x, line.end.x) } }
maxX = max(maxX, 500 + maxY)
val fallMap = Array(maxY + 1 + 2) { Array(maxX + 10) { SpaceType.Air } }
fillWithRocks(fallMap, rockLines.flatten())
addFloor(fallMap)
fallMap.print()
var fallenGrains = 0
while (true) {
val restPosition = fallMap.dropSandAt(sandStart)!!
if (restPosition == sandStart)
break
fallMap[restPosition.y][restPosition.x] = SpaceType.Sand
++fallenGrains
// fallMap.print()
}
fallMap.print()
return fallenGrains + 1
}
val sampleInput = readInput("sample_data", DAY_NUMBER)
val mainInput = readInput("main_data", DAY_NUMBER)
logEnabled = true
// val part1SampleResult = part1(sampleInput)
// println(part1SampleResult)
// check(part1SampleResult == 24)
//
// val part1MainResult = part1(mainInput)
// println(part1MainResult)
// check(part1MainResult == 961)
val part2SampleResult = part2(sampleInput)
println(part2SampleResult)
check(part2SampleResult == 93)
val part2MainResult = part2(mainInput)
println(part2MainResult)
// check(part2MainResult == 0)
}
| 0 | Kotlin | 0 | 0 | 1b261c399a0a84c333cf16f1031b4b1f18b651c7 | 5,608 | advent-of-code-2022 | Apache License 2.0 |
src/year2022/day06/Day.kt | tiagoabrito | 573,609,974 | false | {"Kotlin": 73752} | package year2022.day06
import readInput
fun main() {
fun distinctSequence(sequence: CharSequence, size: Int): Int {
return sequence.withIndex()
.windowed(size)
.first { it.map { it.value }.distinct().size == size }
.last().index + 1
}
fun part1(input: List<CharSequence>): List<Int> {
return input.map { distinctSequence(it, 4) }
}
fun part2(input: List<String>): List<Int> {
return input.map { distinctSequence(it, 14) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("year2022/day06/test")
check(part1(testInput) == listOf(7,5,6,10,11)) { "expected ${listOf(7,5,6,10,11)} but was ${part1(testInput)}" }
val input = readInput("year2022/day06/input")
println(part1(input))
check(part2(testInput) == listOf(19,23,23,29,26)) { "expected ${listOf(19,23,23,29,26)} but was ${part1(testInput)}" }
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1f9becde3cbf5dcb345659a23cf9ff52718bbaf9 | 995 | adventOfCode | Apache License 2.0 |
src/main/kotlin/days/Day6.kt | hughjdavey | 433,597,582 | false | {"Kotlin": 53042} | package days
import java.math.BigInteger
class Day6 : Day(6) {
private val fish = inputString.split(",").map { it.replace(Regex("\\s+"), "").toInt() }
override fun partOne(): Any {
return slowWay(80)
}
override fun partTwo(): Any {
return fastWay(256)
}
private fun slowWay(daysToSimulate: Int): Int {
return generateSequence(0 to fish) { (day, state) ->
day + 1 to state.map { if (it == 0) 6 else it - 1 }.plus(List(state.count { it == 0 }) { 8 })
}.find { it.first == daysToSimulate }?.second?.size ?: 0
}
private fun fastWay(daysToSimulate: Int): Long {
var fishMap = (0..8).associateWith { daysToLive -> BigInteger.valueOf(fish.count { it == daysToLive }.toLong()) }
(0 until daysToSimulate).forEach { fishMap = simulateDay(fishMap) }
return fishMap.values.reduce { a, e -> a.add(e) }.toLong()
}
private fun simulateDay(prevDay: Map<Int, BigInteger>): Map<Int, BigInteger> {
val currDay = (0..8).associateWith { BigInteger.ZERO }.toMutableMap()
(0..8).forEach { daysToLive ->
val prevNum = prevDay[daysToLive]!!
if (daysToLive == 0) {
currDay[6] = prevNum
currDay[8] = prevNum
}
else {
currDay[daysToLive - 1] = currDay[daysToLive - 1]!! + prevNum
}
}
return currDay
}
}
| 0 | Kotlin | 0 | 0 | a3c2fe866f6b1811782d774a4317457f0882f5ef | 1,435 | aoc-2021 | Creative Commons Zero v1.0 Universal |
calendar/day07/Day7.kt | rocketraman | 573,845,375 | false | {"Kotlin": 45660} | package day07
import Day
import Lines
class Day7 : Day() {
override fun part1(input: Lines): Any {
return populateRoot(input)
.walk()
.filter { it.size() <= 100_000 }
.sumOf { it.size() }
}
override fun part2(input: Lines): Any {
val rootDirectory = populateRoot(input)
val total = 70_000_000
val needed = 30_000_000
val currentUsed = rootDirectory.size()
val currentFree = total - currentUsed
val smallest = rootDirectory.walk()
.filter { it.size() + currentFree >= needed }
.minByOrNull { it.size() }!!
return smallest.size()
}
private fun populateRoot(input: Lines): Dir {
val rootDirectory = Dir("/", mutableListOf(), null)
var cwd = rootDirectory
fun handleDir(dir: String) {
// have we already seen it?
if (cwd.inodes.any { it is Dir && it.name == dir }) return
cwd.inodes.add(Dir(dir, mutableListOf(), cwd))
}
fun handleFile(file: File) {
// have we already seen it?
if (cwd.inodes.any { it is File && it == file }) return
cwd.inodes.add(file)
}
fun handleCommand(cmdLine: String) {
val (cmd, args) = cmdLine.split(" ").let { it[0] to it.getOrNull(1) }
when (cmd) {
"ls" -> return
"cd" -> {
cwd = when (args) {
".." -> cwd.parent ?: error("Invalid navigation from root dir")
else -> cwd.inodes.filterIsInstance<Dir>().first { it.name == args }
}
}
}
}
input.drop(2).forEach { l ->
when {
l.startsWith("$ ") -> handleCommand(l.substring(2))
l.startsWith("dir ") -> handleDir(l.substring(4))
else -> handleFile(l.split(" ").let { (size, name) -> File(name, size.toInt()) })
}
}
return rootDirectory
}
sealed class Inode
data class File(val name: String, val size: Int): Inode()
data class Dir(val name: String, val inodes: MutableList<Inode>, val parent: Dir?): Inode() {
fun size(): Int = inodes.sumOf { i ->
when (i) {
is Dir -> i.size()
is File -> i.size
}
}
fun walk(): List<Dir> = inodes.filterIsInstance<Dir>().flatMap { it.walk() } + this
}
}
| 0 | Kotlin | 0 | 0 | 6bcce7614776a081179dcded7c7a1dcb17b8d212 | 2,191 | adventofcode-2022 | Apache License 2.0 |
src/main/kotlin/sschr15/aocsolutions/Day3.kt | sschr15 | 317,887,086 | false | {"Kotlin": 184127, "TeX": 2614, "Python": 446} | package sschr15.aocsolutions
import sschr15.aocsolutions.util.*
import sschr15.aocsolutions.util.watched.WatchedInt
import sschr15.aocsolutions.util.watched.product
import sschr15.aocsolutions.util.watched.sum
import sschr15.aocsolutions.util.watched.toLong
/**
* AOC 2023 [Day 3](https://adventofcode.com/2023/day/3)
* Challenge: Fix an engine, but you can't see the engine, and the blueprint is neither blue nor a print
*/
object Day3 : Challenge {
@ReflectivelyUsed
override fun solve() = challenge(2023, 3) {
// test()
val numbers: List<Triple<WatchedInt, IntRange, Int>>
val symbols: List<Triple<Char, Int, Int>>
part1 {
val number = "\\d+".toRegex()
numbers = inputLines.flatMapIndexed { i, line ->
number.findAll(line).map { Triple(it.value.toInt().w, it.range, i) }.toList()
}
symbols = inputLines.flatMapIndexed { y, line ->
line.mapIndexed { x, c -> Triple(c, x, y) }.filter { !it.first.isDigit() && it.first != '.' }
}
val touchingNumbers = numbers.filter { (n, r, ny) ->
symbols.any { (_, x, y) ->
val (nx1, nx2) = r.first to r.last
val xRange = (nx1 - 1)..(nx2 + 1)
val yRange = (ny - 1)..(ny + 1)
x in xRange && y in yRange
}
}
touchingNumbers.sumOf { it.first.toLong().value }
}
part2 {
val gears = symbols.filter { it.first == '*' }
.mapNotNull { (_, x, y) ->
val searchWidth = (x - 1)..(x + 1)
val searchHeight = (y - 1)..(y + 1)
val validNumbers = numbers.filter { (n, r, ny) ->
ny in searchHeight && (r intersect searchWidth).isNotEmpty()
}
if (validNumbers.size == 2) validNumbers.map { it.first }.product() else null
}
gears.sum()
}
}
@JvmStatic
fun main(args: Array<String>) = println("Time: ${solve()}")
}
| 0 | Kotlin | 0 | 0 | e483b02037ae5f025fc34367cb477fabe54a6578 | 2,134 | advent-of-code | MIT License |
solution/kotlin/aoc/src/main/kotlin/codes/jakob/aoc/Day10.kt | loehnertz | 573,145,141 | false | {"Kotlin": 53239} | package codes.jakob.aoc
import codes.jakob.aoc.Day10.Instruction.Type.ADD_X
import codes.jakob.aoc.Day10.Instruction.Type.NOOP
import codes.jakob.aoc.shared.splitMultiline
class Day10 : Solution() {
override fun solvePart1(input: String): Any {
var cycle = 1
var x = 1
val instructions: List<Instruction> = input.splitMultiline().map { parseInstruction(it) }
val recorded: MutableList<Pair<Int, Int>> = mutableListOf()
for (instruction in instructions) {
when (instruction.type) {
NOOP -> {
recorded += cycle to x
cycle++
}
ADD_X -> {
repeat(2) {
recorded += cycle to x
cycle++
}
x += instruction.value!!
}
}
}
return recorded.filter { it.first in signalCycles }.sumOf { it.first * it.second }
}
override fun solvePart2(input: String): Any {
TODO("Not yet implemented")
}
private fun parseInstruction(line: String): Instruction {
return if (line == "noop") {
Instruction(NOOP, null)
} else {
val (type, value) = line.split(" ")
when (type) {
"addx" -> Instruction(ADD_X, value.toInt())
else -> error("Unknown instruction type: $type")
}
}
}
data class Instruction(
val type: Type,
val value: Int?,
) {
enum class Type {
NOOP,
ADD_X
}
}
companion object {
private val signalCycles: Set<Int> = setOf(20, 60, 100, 140, 180, 220)
}
}
fun main() = Day10().solve()
| 0 | Kotlin | 0 | 0 | ddad8456dc697c0ca67255a26c34c1a004ac5039 | 1,779 | advent-of-code-2022 | MIT License |
lib/src/main/kotlin/aoc/day02/Day02.kt | Denaun | 636,769,784 | false | null | package aoc.day02
enum class Result(val score: Int) { LOSS(0), DRAW(3), WIN(6) }
enum class Shape(val score: Int) {
ROCK(1) {
override fun shapeForResult(result: Result) = when (result) {
Result.WIN -> PAPER
Result.DRAW -> this
Result.LOSS -> SCISSORS
}
},
PAPER(2) {
override fun shapeForResult(result: Result) = when (result) {
Result.WIN -> SCISSORS
Result.DRAW -> this
Result.LOSS -> ROCK
}
},
SCISSORS(3) {
override fun shapeForResult(result: Result) = when (result) {
Result.WIN -> ROCK
Result.DRAW -> this
Result.LOSS -> PAPER
}
};
/** Which [Shape] needs to be played against this to achieve [result]. */
abstract fun shapeForResult(result: Result): Shape
infix fun versus(other: Shape): Result {
return Result.values().find { this == other.shapeForResult(it) }!!
}
}
fun score(lhs: Shape, rhs: Shape): Int = rhs.score + (rhs versus lhs).score
fun score(lhs: Shape, result: Result): Int = lhs.shapeForResult(result).score + result.score
fun part1(input: String): Int = parse(input).sumOf { (lhs, rhs) -> score(lhs, toShape(rhs)) }
fun part2(input: String): Int = parse(input).sumOf { (lhs, rhs) -> score(lhs, toResult(rhs)) }
fun toShape(unknown: Unknown): Shape = when (unknown) {
Unknown.X -> Shape.ROCK
Unknown.Y -> Shape.PAPER
Unknown.Z -> Shape.SCISSORS
}
fun toResult(unknown: Unknown): Result = when (unknown) {
Unknown.X -> Result.LOSS
Unknown.Y -> Result.DRAW
Unknown.Z -> Result.WIN
} | 0 | Kotlin | 0 | 0 | 560f6e33f8ca46e631879297fadc0bc884ac5620 | 1,639 | aoc-2022 | Apache License 2.0 |
src/Day01.kt | jalex19100 | 574,686,993 | false | {"Kotlin": 19795} | fun main() {
fun part1(input: List<String>): Int {
var max = 0
var sum = 0
input.forEach { it ->
if (it.isNotBlank()) {
sum += it.toInt()
} else {
if (sum > max) {
max = sum
}
sum = 0
}
}
return max
}
fun part2(input: List<String>): Int {
val sums = mutableListOf<Int>()
var sum = 0
input.forEach { it ->
if (it.isNotBlank()) {
sum += it.toInt()
} else {
sums.add(sum)
sum = 0
}
}
sums.add(sum)
sums.sort()
println ("Sums: ${sums[sums.size-1] + sums[sums.size-2] + sums[sums.size-3]}")
return sums[sums.size-1] + sums[sums.size-2] + sums[sums.size-3]
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | a50639447a2ef3f6fc9548f0d89cc643266c1b74 | 1,160 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day02.kt | romainbsl | 572,718,344 | false | {"Kotlin": 17019} | fun main() {
fun part1(input: List<String>): Int {
return input
.map {
val (left, right) = it.split(" ")
Shape.from(left) to Shape.from(right)
}
.fold(0) { score, round ->
val (elf, me) = round
val outcome = me fight elf
score + outcome.points + me.points
}
}
fun part2(input: List<String>): Int {
return input
.map {
val (left, right) = it.split(" ")
Shape.from(left) to Outcome.from(right)
}
.fold(0) { score, round ->
val (elfMove, outcome) = round
val necessaryMove = outcome against elfMove
score + outcome.points + necessaryMove.points
}
}
val testInput = readInput("Day02")
// Part 1
assert(Outcome.Draw == Shape.Rock fight Shape.Rock)
assert(Outcome.Lost == Shape.Rock fight Shape.Paper)
assert(Outcome.Won == Shape.Rock fight Shape.Scissors)
assert(Outcome.Won == Shape.Paper fight Shape.Rock)
assert(Outcome.Draw == Shape.Paper fight Shape.Paper)
assert(Outcome.Lost == Shape.Paper fight Shape.Scissors)
assert(Outcome.Lost == Shape.Scissors fight Shape.Rock)
assert(Outcome.Won == Shape.Scissors fight Shape.Paper)
assert(Outcome.Draw == Shape.Scissors fight Shape.Scissors)
println(part1(testInput))
// Part 2
assert(Shape.Paper == Outcome.Won against Shape.Rock)
assert(Shape.Rock == Outcome.Won against Shape.Scissors)
assert(Shape.Scissors == Outcome.Won against Shape.Paper)
assert(Shape.Scissors == Outcome.Lost against Shape.Rock)
assert(Shape.Paper == Outcome.Lost against Shape.Scissors)
assert(Shape.Rock == Outcome.Lost against Shape.Paper)
assert(Shape.Rock == Outcome.Draw against Shape.Rock)
assert(Shape.Scissors == Outcome.Draw against Shape.Scissors)
assert(Shape.Paper == Outcome.Draw against Shape.Paper)
println(part2(testInput))
}
enum class Shape(val points: Int) {
Rock(1),
Paper(2),
Scissors(3);
val defeat: Shape
get() = when (this) {
Rock -> Scissors
Paper -> Rock
Scissors -> Paper
}
companion object {
fun from(key: String): Shape = when (key) {
"A", "X" -> Rock
"B", "Y" -> Paper
"C", "Z" -> Scissors
else -> error("Unknown move!")
}
}
}
infix fun Shape.fight(other: Shape): Outcome = when {
this == other -> Outcome.Draw
defeat == other -> Outcome.Won
else -> Outcome.Lost
}
infix fun Outcome.against(elfMove: Shape) = when (this) {
Outcome.Lost -> elfMove.defeat
Outcome.Draw -> elfMove
Outcome.Won -> elfMove.defeat.defeat
}
enum class Outcome(val points: Int) {
Lost(0), Draw(3), Won(6);
companion object {
fun from(key: String): Outcome = when (key) {
"X" -> Lost
"Y" -> Draw
"Z" -> Won
else -> error("Unknown outcome!")
}
}
} | 0 | Kotlin | 0 | 0 | b72036968769fc67c222a66b97a11abfd610f6ce | 3,113 | advent-of-code-kotlin-2022 | Apache License 2.0 |
2021/src/main/kotlin/day6_func.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parser
import utils.Solution
import utils.mergeToMap
import utils.withLCounts
fun main() {
Day6Func.run()
}
object Day6Func : Solution<Map<Int, Long>>() {
override val name = "day6"
override val parser = Parser.ints.map { it.withLCounts() }
override fun part1(input: Map<Int, Long>): Long {
return simulate(input, forDays = 80).values.sum()
}
override fun part2(input: Map<Int, Long>): Long {
return simulate(input, forDays = 256).values.sum()
}
private fun simulate(input: Map<Int, Long>, forDays: Int): Map<Int, Long> {
return (1 .. forDays).fold(input) { acc, _ -> simulate(acc) }
}
private fun simulate(input: Map<Int, Long>): Map<Int, Long> {
return input.entries
// split the entries into two - the ones with internal timer of 0 and the normal ones
.flatMap { (day, count) ->
if (day == 0) {
listOf(6 to count, 8 to count)
} else {
listOf(day - 1 to count)
}
}
// we've got duplicate keyed pairs in these lists now
.mergeToMap { _, c1, c2 -> c1 + c2 }
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 1,093 | aoc_kotlin | MIT License |
src/Day03.kt | Aldas25 | 572,846,570 | false | {"Kotlin": 106964} | fun main() {
fun priority(c: Char): Int {
if (c in 'a'..'z')
return (c - 'a' + 1)
return (c - 'A' + 27)
}
fun part1(input: List<String>): Int {
var ans = 0
for (s in input) {
var firstHalf: Set<Char> = emptySet<Char>()
val sz = s.length
for (i in 0..(sz/2-1)){
firstHalf += s[i]
}
var foundChars = emptySet<Char>()
for (i in (sz/2)..(sz-1)) {
if (s[i] in firstHalf) {
foundChars += s[i]
}
}
for (c in foundChars)
ans += priority(c)
}
return ans
}
fun part2(input: List<String>): Int {
var ans = 0
for (i in 0..(input.size-1)) {
if (i%3 != 0) continue
val badge: Set<Char> = input[i].toSet() intersect input[i+1].toSet() intersect input[i+2].toSet()
for (c in badge)
ans += priority(c)
}
return ans
}
val filename =
// "inputs\\day03_sample"
"inputs\\day03"
val input = readInput(filename)
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 80785e323369b204c1057f49f5162b8017adb55a | 1,254 | Advent-of-Code-2022 | Apache License 2.0 |
src/main/kotlin/dk/lessor/Day21.kt | aoc-team-1 | 317,571,356 | false | {"Java": 70687, "Kotlin": 34171} | package dk.lessor
fun main() {
val lines = readFile("day_21.txt").map {
val (ingredients, allergies) = it.split(" (contains ")
ingredients.split(" ") to allergies.dropLast(1).split(", ")
}
val translations = identifyAllergyTranslations(lines)
val count = lines.flatMap { it.first }.filter { !translations.containsKey(it) }.count()
println(count)
val dangerousIngredientsList = translations.toList().sortedBy { (_, value) -> value }.joinToString(",") { it.first }
println(dangerousIngredientsList)
}
fun identifyAllergyTranslations(menu: List<Pair<List<String>, List<String>>>): Map<String, String> {
val result = mutableMapOf<String, String>()
val words = menu.flatMap { it.second }.distinct()
while (result.size < words.size) {
for (allergy in words) {
val possible = menu.filter { it.second.contains(allergy) }.map { it.first }
var word = possible.first().toSet()
possible.forEach { word = word.intersect(it) }
word = word.filter { !result.containsKey(it) }.toSet()
if (word.size == 1) {
result[word.first()] = allergy
}
}
}
return result
}
| 0 | Java | 0 | 0 | 48ea750b60a6a2a92f9048c04971b1dc340780d5 | 1,217 | lessor-aoc-comp-2020 | MIT License |
src/day22/Day22.kt | Oktosha | 573,139,677 | false | {"Kotlin": 110908} | package day22
import readInput
typealias FlatRepresentation = List<String>
data class Position(val row: Int, val column: Int) {
operator fun plus(other: Position): Position {
return Position(row + other.row, column + other.column)
}
operator fun minus(other: Position): Position {
return Position(row - other.row, column - other.column)
}
}
enum class Direction(val code: Int, val vec: Position) {
RIGHT(0, Position(0, 1)),
DOWN(1, Position(1, 0)),
LEFT(2, Position(0, -1)),
UP(3, Position(-1, 0));
companion object {
private val codeMapping = Direction.values().associateBy(Direction::code)
fun fromCode(code: Int): Direction {
return codeMapping[code]!!
}
}
}
enum class Face {
ONE, TWO, THREE, FOUR, FIVE, SIX
}
data class State(val pos: Position, val dir: Direction) {
fun password(): Int {
return 1000 * (pos.row + 1) + 4 * (pos.column + 1) + dir.code
}
}
interface Field {
val flatMap: FlatRepresentation
fun moveForward(state: State, steps: Int): State
}
fun main() {
operator fun FlatRepresentation.get(pos: Position): Char {
return this[pos.row][pos.column]
}
fun FlatRepresentation.rows(): Int {
return this.size
}
fun FlatRepresentation.columns(): Int {
return this[0].length
}
fun simpleWrap(pos: Position, field: FlatRepresentation): Position {
return Position(
(pos.row + field.rows()) % field.rows(),
(pos.column + field.columns()) % field.columns()
)
}
fun flatPositionInFront(state: State, field: FlatRepresentation): State {
var current = state.pos
do {
current = simpleWrap(current + state.dir.vec, field)
} while (field[current] == ' ')
return State(current, state.dir)
}
fun turnDir(dir: Direction, command: String): Direction {
return when (command) {
"R" -> Direction.fromCode((dir.code + 1) % 4)
"L" -> Direction.fromCode((dir.code - 1 + 4) % 4)
else -> throw Exception("Unknown turn command")
}
}
fun turn(state: State, command: String): State {
return State(state.pos, turnDir(state.dir, command))
}
fun positionInFrontOnCube(cubeState: Pair<Face, State>, cubeSize: Int): Pair<Face, State> {
val (face, state) = cubeState
val dummyPosition = state.pos + state.dir.vec
if (dummyPosition.row < cubeSize
&& dummyPosition.column < cubeSize
&& dummyPosition.row >= 0
&& dummyPosition.column >= 0
) {
return face to State(dummyPosition, state.dir)
}
when (face) {
Face.ONE -> when (state.dir) {
Direction.RIGHT -> return Face.THREE to State(
Position(0, cubeSize - state.pos.row - 1),
Direction.DOWN
)
Direction.DOWN -> return Face.TWO to State(
Position(0, state.pos.column),
Direction.DOWN
)
Direction.LEFT -> return Face.FOUR to State(
Position(0, state.pos.row),
Direction.DOWN
)
Direction.UP -> return Face.FIVE to State(
Position(0, cubeSize - state.pos.column - 1),
Direction.DOWN
)
}
Face.TWO -> when (state.dir) {
Direction.RIGHT -> return Face.THREE to State(
Position(state.pos.row, 0),
Direction.RIGHT
)
Direction.DOWN -> return Face.SIX to State(
Position(0, state.pos.column),
Direction.DOWN
)
Direction.LEFT -> return Face.FOUR to State(
Position(state.pos.row, cubeSize - 1),
Direction.LEFT
)
Direction.UP -> return Face.ONE to State(
Position(cubeSize - 1, state.pos.column),
Direction.UP
)
}
Face.THREE -> when (state.dir) {
Direction.RIGHT -> return Face.FIVE to State(
Position(state.pos.row, 0),
Direction.RIGHT
)
Direction.DOWN -> return Face.SIX to State(
Position(state.pos.column, cubeSize - 1),
Direction.LEFT
)
Direction.LEFT -> return Face.TWO to State(
Position(state.pos.row, cubeSize - 1),
Direction.LEFT
)
Direction.UP -> return Face.ONE to State(
Position(cubeSize - 1 - state.pos.column, cubeSize - 1),
Direction.LEFT
)
}
Face.FOUR -> when (state.dir) {
Direction.RIGHT -> return Face.TWO to State(
Position(state.pos.row, 0),
Direction.RIGHT
)
Direction.DOWN -> return Face.SIX to State(
Position(cubeSize - 1 - state.pos.column, 0),
Direction.RIGHT
)
Direction.LEFT -> return Face.FIVE to State(
Position(state.pos.row, cubeSize - 1),
Direction.LEFT
)
Direction.UP -> return Face.ONE to State(
Position(state.pos.column, 0),
Direction.RIGHT
)
}
Face.FIVE -> when (state.dir) {
Direction.RIGHT -> return Face.FOUR to State(
Position(state.pos.row, 0),
Direction.RIGHT
)
Direction.DOWN -> return Face.SIX to State(
Position(cubeSize - 1, cubeSize - 1 - state.pos.column),
Direction.UP
)
Direction.LEFT -> return Face.THREE to State(
Position(state.pos.row, cubeSize - 1),
Direction.LEFT
)
Direction.UP -> return Face.ONE to State(
Position(0, cubeSize - 1 - state.pos.column),
Direction.DOWN
)
}
Face.SIX -> when (state.dir) {
Direction.RIGHT -> return Face.THREE to State(
Position(cubeSize - 1, state.pos.row),
Direction.UP
)
Direction.DOWN -> return Face.FIVE to State(
Position(cubeSize - 1, cubeSize - 1 - state.pos.column),
Direction.UP
)
Direction.LEFT -> return Face.FOUR to State(
Position(cubeSize - 1, cubeSize - 1 - state.pos.row),
Direction.UP
)
Direction.UP -> return Face.TWO to State(
Position(cubeSize - 1, state.pos.column),
Direction.UP
)
}
}
}
fun testPositionInFrontOnCube() {
val cubeSize = 7
for (face in Face.values()) {
for (row in 0 until cubeSize) {
for (column in 0 until cubeSize) {
for (direction in Direction.values()) {
val startState = State(Position(row, column), direction)
val (nextFace, nextState) = positionInFrontOnCube(face to startState, cubeSize)
val turned = turn(turn(nextState, "L"), "L")
val (returnedFace, returnedState) = positionInFrontOnCube(nextFace to turned, cubeSize)
val turnedOnStart = turn(turn(returnedState, "L"), "L")
if (returnedFace != face || turnedOnStart != startState) {
println("State $startState on face $face doesn't return back")
println("It goes to $nextState on face $nextFace")
println("Than turns to be $turned")
println("Than goes to $returnedState on face $returnedFace")
println("And after reversing rotation is $turnedOnStart")
throw Exception()
}
}
}
}
}
}
fun simpleMoveForward(steps: Int, state: State,
field: FlatRepresentation, positionInFront: (State) -> State): State {
var current = state
repeat(steps) {
if (field[positionInFront(current).pos] == '.') {
current = positionInFront(current)
}
}
return current
}
fun getStartPosition(field: FlatRepresentation): Position {
return Position(0, field[0].indexOf('.'))
}
fun normalizedField(input: List<String>): FlatRepresentation {
val desiredLengh = input.maxOf { s -> s.length }
return input.map { s -> s.padEnd(desiredLengh, ' ') }
}
class DummyField(override val flatMap: FlatRepresentation) : Field {
override fun moveForward(state: State, steps: Int): State {
return simpleMoveForward(steps, state, flatMap) {x -> flatPositionInFront(x, flatMap)}
}
}
// pos - top left corner of face on map
// dir where top looks according to ideal cube
data class Alignment(val pos: Position, val dir: Direction)
fun coordinateIsInsideFace(pos: Position, alignment: Alignment, cubeSize: Int): Boolean {
return (pos.column >= alignment.pos.column)
&& (pos.row >= alignment.pos.row)
&& (pos.column < alignment.pos.column + cubeSize)
&& (pos.row < alignment.pos.row + cubeSize)
}
fun cubeState(flatRelativePos: Position, flatDir: Direction, faceDir: Direction, cubeSize: Int): State {
var cubeDir = flatDir
var tmpFaceDir = faceDir
while (tmpFaceDir != Direction.UP) {
cubeDir = turnDir(cubeDir, "L")
tmpFaceDir = turnDir(tmpFaceDir, "L")
}
val position = when(faceDir) {
Direction.RIGHT -> Position(cubeSize - flatRelativePos.column - 1, flatRelativePos.row)
Direction.DOWN -> Position(cubeSize - flatRelativePos.row - 1,
cubeSize - flatRelativePos.column - 1)
Direction.LEFT -> Position(flatRelativePos.column, cubeSize - flatRelativePos.row - 1)
Direction.UP -> flatRelativePos
}
return State(position, cubeDir)
}
class CubeField(val cubeSize: Int,
override val flatMap: FlatRepresentation,
val alignments: Map<Face, Alignment>) : Field {
override fun moveForward(state: State, steps: Int): State {
return simpleMoveForward(steps, state, flatMap) {x ->
convertCubeToFlat(positionInFrontOnCube(convertFlatToCube(x), cubeSize))
}
}
fun convertFlatToCube(state: State): Pair<Face, State> {
val face = Face.values().find { x -> coordinateIsInsideFace(state.pos, alignments[x]!!, cubeSize) }!!
val relativePos = state.pos - alignments[face]!!.pos
return face to cubeState(relativePos, state.dir, alignments[face]!!.dir, cubeSize)
}
fun convertCubeToFlat(cubeState: Pair<Face, State>): State {
val (face, state) = cubeState
var faceDir = Direction.UP
var flatDir = state.dir
while(faceDir != alignments[face]!!.dir) {
faceDir = turnDir(faceDir, "R")
flatDir = turnDir(flatDir, "R")
}
val relativePos = when(faceDir) {
Direction.RIGHT -> Position(state.pos.column, cubeSize - state.pos.row - 1)
Direction.DOWN -> Position(cubeSize - state.pos.row - 1, cubeSize - state.pos.column - 1)
Direction.LEFT -> Position(cubeSize - state.pos.column -1, state.pos.row)
Direction.UP -> state.pos
}
return State(alignments[face]!!.pos + relativePos, flatDir)
}
}
fun createDummyField(input: List<String>): DummyField {
return DummyField(normalizedField(input))
}
fun solve(input: List<String>, createField: (List<String>)-> Field): Int {
val field = createField(input.dropLast(2))
val commandString = input.last()
val commandList = commandString
.replace(Regex("""\p{Upper}""")) { x: MatchResult -> " ${x.value} " }
.split(" ").filter { s -> s != "" }
var state = State(getStartPosition(field.flatMap), Direction.RIGHT)
for (command in commandList) {
state = if (command == "R" || command == "L") {
turn(state, command)
} else {
field.moveForward(state, command.toInt())
}
}
println(state)
return state.password()
}
fun createTestCubeField(input: List<String>): Field {
return CubeField(4, normalizedField(input), mapOf(
Face.ONE to Alignment(Position(0, 8), Direction.UP),
Face.TWO to Alignment(Position(4, 8), Direction.UP),
Face.THREE to Alignment(Position(8, 12), Direction.RIGHT),
Face.FOUR to Alignment(Position(4, 4), Direction.UP),
Face.FIVE to Alignment(Position(4, 0), Direction.UP),
Face.SIX to Alignment(Position(8, 8), Direction.UP)
))
}
fun createRealCubeField(input: List<String>): CubeField {
return CubeField(50, normalizedField(input), mapOf(
Face.ONE to Alignment(Position(0, 50), Direction.UP),
Face.TWO to Alignment(Position(50, 50), Direction.UP),
Face.THREE to Alignment(Position(0, 100), Direction.LEFT),
Face.FOUR to Alignment(Position(100, 0), Direction.LEFT),
Face.FIVE to Alignment(Position(150, 0), Direction.LEFT),
Face.SIX to Alignment(Position(100, 50), Direction.UP)
))
}
fun testRealTransformation(input: List<String>) {
val field = createRealCubeField(input)
for (row in 0 until field.flatMap.rows()) {
for (column in 0 until field.flatMap.columns()) {
val pos = Position(row, column)
if (field.flatMap[pos] != ' ') {
for (dir in Direction.values()) {
val state = State(pos, dir)
val cubeState = field.convertFlatToCube(state)
val reversedState = field.convertCubeToFlat(cubeState)
if (state != reversedState) {
println("Non consistent conversion")
println("$state != $reversedState")
println("interim cube state $cubeState")
throw Exception()
}
}
}
}
}
}
println("Day22")
val testInput = readInput("Day22-test")
val input = readInput("Day22")
testPositionInFrontOnCube()
testRealTransformation(input.dropLast(2))
println("part1 test ${solve(testInput, ::createDummyField)}")
println("part1 real ${solve(input, ::createDummyField)}")
println("part2 test ${solve(testInput, ::createTestCubeField)}")
println("part2 real ${solve(input, ::createRealCubeField)}")
} | 0 | Kotlin | 0 | 0 | e53eea61440f7de4f2284eb811d355f2f4a25f8c | 15,760 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/Day7.kt | Walop | 573,012,840 | false | {"Kotlin": 53630} | import java.io.InputStream
interface IFile {
val name: String
val size: Int
}
data class File(override val name: String, override val size: Int) : IFile
data class Directory(
override val name: String,
override var size: Int,
val children: MutableList<IFile>,
val parent: Directory?,
) : IFile
class Day7 {
companion object {
private fun sumLessThan100k(dir: Directory): Int {
val returnSize = if (dir.size <= 100_000) dir.size else 0
val subDirs = dir.children.filterIsInstance<Directory>()
if (subDirs.isNotEmpty()) {
return returnSize + subDirs.sumOf { sumLessThan100k(it) }
}
return returnSize
}
private fun dirsMoreThan(dir: Directory, min: Int): List<Int> {
val returnList = if (dir.size >= min) listOf(dir.size) else listOf()
val subDirs = dir.children.filterIsInstance<Directory>()
if (subDirs.isNotEmpty()) {
return returnList + subDirs.flatMap { dirsMoreThan(it, min) }
}
return returnList
}
fun process(input: InputStream?): Int {
if (input == null) {
throw Exception("Input missing")
}
return input
.bufferedReader()
.useLines { lines ->
val root = Directory("/", 0, mutableListOf(), null)
var current = root
for (line in lines.drop(1)) {
when (line.take(4)) {
"$ cd" -> {
val dir = line.drop(5)
if (dir == "..") {
current.size = current.children.sumOf { it.size }
current = current.parent!!
} else {
current = current.children.find { it.name == line.drop(5) } as Directory
}
}
"$ ls" -> continue
"dir " -> current.children.add(Directory(line.drop(4), 0, mutableListOf(), current))
else -> {
val split = line.split(" ")
current.children.add(File(split[1], split[0].toInt()))
}
}
}
current.size = current.children.sumOf { it.size }
root.size = root.children.sumOf { it.size }
sumLessThan100k(root)
}
}
fun process2(input: InputStream?): Int {
if (input == null) {
throw Exception("Input missing")
}
return input
.bufferedReader()
.useLines { lines ->
val root = Directory("/", 0, mutableListOf(), null)
var current = root
for (line in lines.drop(1)) {
when (line.take(4)) {
"$ cd" -> {
val dir = line.drop(5)
if (dir == "..") {
current.size = current.children.sumOf { it.size }
current = current.parent!!
} else {
current = current.children.find { it.name == line.drop(5) } as Directory
}
}
"$ ls" -> continue
"dir " -> current.children.add(Directory(line.drop(4), 0, mutableListOf(), current))
else -> {
val split = line.split(" ")
current.children.add(File(split[1], split[0].toInt()))
}
}
}
while (current.parent != null) {
current.size = current.children.sumOf { it.size }
current = current.parent!!
}
root.size = root.children.sumOf { it.size }
val toFree = 70_000_000 - 30_000_000 - root.size
dirsMoreThan(root, -toFree).min()
}
}
}
}
| 0 | Kotlin | 0 | 0 | 7a13f6500da8cb2240972fbea780c0d8e0fde910 | 4,521 | AdventOfCode2022 | The Unlicense |
src/main/kotlin/com/ginsberg/advent2022/Day22.kt | tginsberg | 568,158,721 | false | {"Kotlin": 113322} | /*
* Copyright (c) 2022 by <NAME>
*/
/**
* Advent of Code 2022, Day 22 - Monkey Map
* Problem Description: http://adventofcode.com/2022/day/22
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2022/day22/
*/
package com.ginsberg.advent2022
class Day22(input: List<String>) {
private val blockedPlaces: Set<Point2D> = parseBlockedPlaces(input)
private val instructions: List<Instruction> = Instruction.ofList(input)
fun solvePart1(): Int =
followInstructions(CubeFacing(1)).score()
fun solvePart2(): Int =
followInstructions(CubeFacing(11)).score()
private fun followInstructions(startingCube: CubeFacing): Orientation {
var cube = startingCube
var orientation = Orientation(cube.topLeft, Facing.East)
instructions.forEach { instruction ->
when (instruction) {
is Left -> orientation = orientation.copy(facing = orientation.facing.left)
is Right -> orientation = orientation.copy(facing = orientation.facing.right)
is Move -> {
var keepMoving = true
repeat(instruction.steps) {
if (keepMoving) {
var nextOrientation = orientation.move()
var nextCube = cube
if (nextOrientation.location !in cube) {
// We have moved off the face of the cube we were on, find the transition we need.
with(cube.transition(orientation.facing)) {
nextOrientation = Orientation(move(orientation.location), enter)
nextCube = destination
}
}
if (nextOrientation.location in blockedPlaces) {
// We cannot move to this spot - it is on the map but blocking us.
keepMoving = false
} else {
// We can move to this spot - it is on the map AND free
orientation = nextOrientation
cube = nextCube
}
}
}
}
}
}
return orientation
}
private fun parseBlockedPlaces(input: List<String>): Set<Point2D> =
input
.takeWhile { it.isNotBlank() }
.flatMapIndexed { y, row ->
row.mapIndexedNotNull { x, c ->
if (c == '#') Point2D(x, y) else null
}
}.toSet()
private data class Orientation(val location: Point2D, val facing: Facing) {
fun score(): Int =
(1000 * (location.y + 1)) + (4 * (location.x + 1)) + facing.points
fun move(): Orientation =
copy(location = location + facing.offset)
}
private sealed class Instruction {
companion object {
fun ofList(input: List<String>): List<Instruction> =
input
.dropWhile { it.isNotBlank() }
.drop(1)
.first()
.trim()
.let { """\d+|[LR]""".toRegex().findAll(it) }
.map { it.value }
.filter { it.isNotBlank() }
.map { symbol ->
when (symbol) {
"L" -> Left
"R" -> Right
else -> Move(symbol.toInt())
}
}.toList()
}
}
private class Move(val steps: Int) : Instruction()
private object Left : Instruction()
private object Right : Instruction()
sealed class Facing(val points: Int, val offset: Point2D) {
abstract val left: Facing
abstract val right: Facing
object North : Facing(3, Point2D(0, -1)) {
override val left = West
override val right = East
}
object East : Facing(0, Point2D(1, 0)) {
override val left = North
override val right = South
}
object South : Facing(1, Point2D(0, 1)) {
override val left = East
override val right = West
}
object West : Facing(2, Point2D(-1, 0)) {
override val left = South
override val right = North
}
}
class CubeFacing(
val id: Int,
val size: Int,
val topLeft: Point2D,
val north: Transition,
val east: Transition,
val south: Transition,
val west: Transition
) {
val minX: Int = topLeft.x
val maxX: Int = topLeft.x + size - 1
val minY: Int = topLeft.y
val maxY: Int = topLeft.y + size - 1
operator fun contains(place: Point2D): Boolean =
place.x in (minX..maxX) && place.y in (minY..maxY)
fun scaleDown(point: Point2D): Point2D =
point - topLeft
fun scaleUp(point: Point2D): Point2D =
point + topLeft
fun transition(direction: Facing): Transition =
when (direction) {
Facing.North -> north
Facing.East -> east
Facing.South -> south
Facing.West -> west
}
companion object {
private val instances = mutableMapOf<Int, CubeFacing>()
operator fun invoke(id: Int): CubeFacing =
instances.getValue(id)
private operator fun plus(instance: CubeFacing) {
instances[instance.id] = instance
}
init {
CubeFacing + CubeFacing(
id = 1,
size = 50,
topLeft = Point2D(50, 0),
north = Transition(1, 5, Facing.North, Facing.North),
east = Transition(1, 2, Facing.East, Facing.East),
south = Transition(1, 3, Facing.South, Facing.South),
west = Transition(1, 2, Facing.West, Facing.West)
)
CubeFacing + CubeFacing(
id = 2,
size = 50,
topLeft = Point2D(100, 0),
north = Transition(2, 2, Facing.North, Facing.North),
east = Transition(2, 1, Facing.East, Facing.East),
south = Transition(2, 2, Facing.South, Facing.South),
west = Transition(2, 1, Facing.West, Facing.West)
)
CubeFacing + CubeFacing(
id = 3,
size = 50,
topLeft = Point2D(50, 50),
north = Transition(3, 1, Facing.North, Facing.North),
east = Transition(3, 3, Facing.East, Facing.East),
south = Transition(3, 5, Facing.South, Facing.South),
west = Transition(3, 3, Facing.West, Facing.West)
)
CubeFacing + CubeFacing(
id = 4,
size = 50,
topLeft = Point2D(0, 100),
north = Transition(4, 6, Facing.North, Facing.North),
east = Transition(4, 5, Facing.East, Facing.East),
south = Transition(4, 6, Facing.South, Facing.South),
west = Transition(4, 5, Facing.West, Facing.West)
)
CubeFacing + CubeFacing(
id = 5,
size = 50,
topLeft = Point2D(50, 100),
north = Transition(5, 3, Facing.North, Facing.North),
east = Transition(5, 4, Facing.East, Facing.East),
south = Transition(5, 1, Facing.South, Facing.South),
west = Transition(5, 4, Facing.West, Facing.West)
)
CubeFacing + CubeFacing(
id = 6,
size = 50,
topLeft = Point2D(0, 150),
north = Transition(6, 4, Facing.North, Facing.North),
east = Transition(6, 6, Facing.East, Facing.East),
south = Transition(6, 4, Facing.South, Facing.South),
west = Transition(6, 6, Facing.West, Facing.West)
)
CubeFacing + CubeFacing(
id = 11,
size = 50,
topLeft = Point2D(50, 0),
north = Transition(11, 16, Facing.North, Facing.East),
east = Transition(11, 12, Facing.East, Facing.East),
south = Transition(11, 13, Facing.South, Facing.South),
west = Transition(11, 14, Facing.West, Facing.East)
)
CubeFacing + CubeFacing(
id = 12,
size = 50,
topLeft = Point2D(100, 0),
north = Transition(12, 16, Facing.North, Facing.North),
east = Transition(12, 15, Facing.East, Facing.West),
south = Transition(12, 13, Facing.South, Facing.West),
west = Transition(12, 11, Facing.West, Facing.West)
)
CubeFacing + CubeFacing(
id = 13,
size = 50,
topLeft = Point2D(50, 50),
north = Transition(13, 11, Facing.North, Facing.North),
east = Transition(13, 12, Facing.East, Facing.North),
south = Transition(13, 15, Facing.South, Facing.South),
west = Transition(13, 14, Facing.West, Facing.South)
)
CubeFacing + CubeFacing(
id = 14,
size = 50,
topLeft = Point2D(0, 100),
north = Transition(14, 13, Facing.North, Facing.East),
east = Transition(14, 15, Facing.East, Facing.East),
south = Transition(14, 16, Facing.South, Facing.South),
west = Transition(14, 11, Facing.West, Facing.East)
)
CubeFacing + CubeFacing(
id = 15,
size = 50,
topLeft = Point2D(50, 100),
north = Transition(15, 13, Facing.North, Facing.North),
east = Transition(15, 12, Facing.East, Facing.West),
south = Transition(15, 16, Facing.South, Facing.West),
west = Transition(15, 14, Facing.West, Facing.West)
)
CubeFacing + CubeFacing(
id = 16,
size = 50,
topLeft = Point2D(0, 150),
north = Transition(16, 14, Facing.North, Facing.North),
east = Transition(16, 15, Facing.East, Facing.North),
south = Transition(16, 12, Facing.South, Facing.South),
west = Transition(16, 11, Facing.West, Facing.South)
)
}
}
}
data class Transition(val sourceId: Int, val destinationId: Int, val exit: Facing, val enter: Facing) {
private val byDirection = Pair(exit, enter)
private val source: CubeFacing by lazy { CubeFacing(sourceId) }
val destination: CubeFacing by lazy { CubeFacing(destinationId) }
private fun Point2D.rescale(): Point2D =
destination.scaleUp(source.scaleDown(this))
private fun Point2D.flipRescaled(): Point2D =
destination.scaleUp(source.scaleDown(this).flip())
private fun Point2D.flip(): Point2D =
Point2D(y, x)
fun move(start: Point2D): Point2D = when (byDirection) {
Pair(Facing.North, Facing.North) -> Point2D(start.rescale().x, destination.maxY)
Pair(Facing.East, Facing.East) -> Point2D(destination.minX, start.rescale().y)
Pair(Facing.West, Facing.West) -> Point2D(destination.maxX, start.rescale().y)
Pair(Facing.South, Facing.South) -> Point2D(start.rescale().x, destination.minY)
Pair(Facing.North, Facing.East) -> Point2D(destination.minX, start.flipRescaled().y)
Pair(Facing.East, Facing.North) -> Point2D(start.flipRescaled().x, destination.maxY)
Pair(Facing.East, Facing.West) -> Point2D(destination.maxX, destination.maxY - source.scaleDown(start).y)
Pair(Facing.West, Facing.East) -> Point2D(destination.minX, destination.maxY - source.scaleDown(start).y)
Pair(Facing.West, Facing.South) -> Point2D(start.flipRescaled().x, destination.minY)
Pair(Facing.South, Facing.West) -> Point2D(destination.maxX, start.flipRescaled().y)
else -> throw IllegalStateException("No transition from $exit to $enter")
}
}
} | 0 | Kotlin | 2 | 26 | 2cd87bdb95b431e2c358ffaac65b472ab756515e | 13,145 | advent-2022-kotlin | Apache License 2.0 |
src/Day21.kt | l8nite | 573,298,097 | false | {"Kotlin": 105683} | class BetterMonkey(val id: String, var leftMonkey: BetterMonkey? = null, var operator: String? = null, var rightMonkey: BetterMonkey? = null, var result: Long? = null) {
var isHuman: Boolean = false
init {
if (id == "humn") { isHuman = true }
}
override fun toString(): String {
return if (result != null) {
if (operator != null) {
"$id: ${leftMonkey?.id} $operator ${rightMonkey?.id} (= $result)"
} else {
"$id: $result"
}
} else {
"$id: ${leftMonkey?.id} $operator ${rightMonkey?.id} (= ????)"
}
}
fun evaluate(left: Long, right: Long): Long {
return when (operator) {
"+" -> left + right
"-" -> left - right
"/" -> left / right
"*" -> left * right
else -> {
throw Exception("Unknown operator: $operator")
}
}
}
fun inverse(result: Long, operand: Long, isLeft: Boolean): Long {
return when (operator) {
"+" -> result - operand
"-" -> if (isLeft) result + operand else operand - result
"/" -> if (isLeft) result * operand else operand / result
"*" -> result / operand
else -> {
throw Exception("Unknown operator: $operator")
}
}
}
}
fun main() {
fun parseMonkeys(inputs: List<String>, part2: Boolean = false): Map<String, BetterMonkey> {
val monkeys = mutableMapOf<String, BetterMonkey>()
val smartMonkeyRegex = "^(\\w+): (\\w+) ([+*/-]) (\\w+)$".toRegex()
val dumbMonkeyRegex = "^(\\w+): (-?\\d+)$".toRegex()
fun fromSmartMonkey(it: String): BetterMonkey? {
if (!smartMonkeyRegex.matches(it)) { return null }
val match = smartMonkeyRegex.matchEntire(it)
var (id, left, op, right) = match!!.destructured
if (part2 && id == "root") { op = "=" }
return monkeys.getOrPut(id) {
BetterMonkey(id, operator = op)
}.also {
it.leftMonkey = monkeys.getOrPut(left) {
BetterMonkey(left)
}
it.rightMonkey = monkeys.getOrPut(right) {
BetterMonkey(right)
}
it.operator = op
}
}
fun fromDumbMonkey(it: String): BetterMonkey {
val match = dumbMonkeyRegex.matchEntire(it)
val (id, yelled) = match!!.destructured
return monkeys.getOrPut(id) {
BetterMonkey(id, result = yelled.toLong())
}.also {
it.result = yelled.toLong()
if (part2 && it.isHuman) {
it.result = null
}
it.leftMonkey = null
it.rightMonkey = null
}
}
inputs.forEach {
fromSmartMonkey(it) ?: fromDumbMonkey(it)
}
return monkeys
}
fun solvePart1(monkey: BetterMonkey, monkeys: Map<String, BetterMonkey>): Long? {
return if (monkey.result != null) {
monkey.result!!
} else {
if (monkey.operator == null) {
return null
}
val left = solvePart1(monkey.leftMonkey!!, monkeys)
val right = solvePart1(monkey.rightMonkey!!, monkeys)
if (left != null && right != null) {
monkey.result = monkey.evaluate(left, right)
}
monkey.result
}
}
fun solvePart2(monkey: BetterMonkey, monkeys: Map<String, BetterMonkey>, result: Long): Long {
monkey.result = result
return if (monkey.id == "humn") {
result
} else {
if (monkey.leftMonkey!!.result == null) {
solvePart2(monkey.leftMonkey!!, monkeys, monkey.inverse(result, monkey.rightMonkey!!.result!!, isLeft = true))
} else {
solvePart2(monkey.rightMonkey!!, monkeys, monkey.inverse(result, monkey.leftMonkey!!.result!!, isLeft = false))
}
}
}
fun part1(input: List<String>): Long {
val monkeys = parseMonkeys(input)
return solvePart1(monkeys["root"]!!, monkeys)!!
}
fun part2(input: List<String>): Long {
val monkeys = parseMonkeys(input, true)
val root = monkeys["root"]!!
solvePart1(root, monkeys)
return if (root.leftMonkey!!.result == null) {
solvePart2(root.leftMonkey!!, monkeys, root.rightMonkey!!.result!!)
} else {
solvePart2(root.rightMonkey!!, monkeys, root.leftMonkey!!.result!!)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day21_test")
check(part1(testInput) == 152L)
println("Part 1 checked out!")
check(part2(testInput) == 301L)
println("Part 2 checked out!")
val input = readInput("Day21")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f74331778fdd5a563ee43cf7fff042e69de72272 | 5,082 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/Day15.kt | clechasseur | 258,279,622 | false | null | import org.clechasseur.adventofcode2019.Day15Data
import org.clechasseur.adventofcode2019.IntcodeComputer
import org.clechasseur.adventofcode2019.Pt
import org.clechasseur.adventofcode2019.dij.Dijkstra
import org.clechasseur.adventofcode2019.dij.Graph
import org.clechasseur.adventofcode2019.manhattan
object Day15 {
private enum class Direction(val command: Long, val movement: Pt) {
NORTH(1L, Pt(0, -1)),
SOUTH(2L, Pt(0, 1)),
WEST(3L, Pt(-1, 0)),
EAST(4L, Pt(1, 0))
}
private val input = Day15Data.input
private const val wall = 0L
private const val moved = 1L
private const val movedToOxygen = 2L
fun part1(): Int {
val computer = IntcodeComputer(input)
val passable = mutableSetOf<Pt>()
val oxygen = explore(computer, Pt.ZERO, passable)!!
val pathfinding = Dijkstra.build(PassableGraph(passable), Pt.ZERO)
return Dijkstra.assemblePath(pathfinding.prev, Pt.ZERO, oxygen)!!.size - 1
}
fun part2(): Int {
val computer = IntcodeComputer(input)
val passable = mutableSetOf<Pt>()
val oxygen = explore(computer, Pt.ZERO, passable)!!
val pathfinding = Dijkstra.build(PassableGraph(passable), oxygen)
return pathfinding.dist.values.max()!!.toInt()
}
private fun explore(computer: IntcodeComputer, curPos: Pt, passable: MutableSet<Pt>): Pt? {
if (passable.contains(curPos)) {
return null
}
passable.add(curPos)
return Direction.values().map { direction ->
val snapshot = computer.snapshot()
snapshot.addInput(direction.command)
when (val moveResult = snapshot.readOutput()) {
wall -> null
moved -> explore(snapshot, curPos + direction.movement, passable)
movedToOxygen -> {
val newPos = curPos + direction.movement
explore(snapshot, newPos, passable)
newPos
}
else -> error("Wrong movement result: $moveResult")
}
}.reduce { acc, pt -> acc ?: pt }
}
private class PassableGraph(val passable: Set<Pt>) : Graph<Pt> {
override fun allPassable(): List<Pt> = passable.toList()
override fun neighbours(node: Pt): List<Pt> = Direction.values().mapNotNull { direction ->
val neighbour = node + direction.movement
passable.find { it == neighbour }
}.toList()
override fun dist(a: Pt, b: Pt): Long = manhattan(a, b).toLong()
}
}
| 0 | Kotlin | 0 | 0 | 187acc910eccb7dcb97ff534e5f93786f0341818 | 2,586 | adventofcode2019 | MIT License |
src/main/kotlin/Day25.kt | N-Silbernagel | 573,145,327 | false | {"Kotlin": 118156} | import kotlin.math.pow
fun main() {
val input = readFileAsList("Day25")
println(Day25.part1(input))
println(Day25.part2(input))
}
object Day25 {
val charNumberMap = mapOf(
'=' to -2,
'-' to -1,
'0' to 0,
'1' to 1,
'2' to 2,
)
fun part1(input: List<String>): String {
val snafuNumbers = mutableListOf<Long>()
for (s in input) {
snafuNumbers.add(snafuToDecimal(s))
}
val sum = snafuNumbers.sum()
return decimalToSnafu(sum)
}
fun part2(input: List<String>): String {
return ""
}
private fun snafuToDecimal(snafu: String): Long {
val test = snafu.reversed()
.map { charNumberMap[it]!! }
var sum = 0L
for ((index, i) in test.withIndex()) {
sum += i * 5.toDouble().pow(index).toLong()
}
return sum
}
private fun decimalToSnafu(decimal: Long): String {
return generateSequence(decimal) { (it + 2) / 5 }
.takeWhile { it != 0L }
.map { "012=-"[(it % 5).toInt()] }
.joinToString("")
.reversed()
}
}
| 0 | Kotlin | 0 | 0 | b0d61ba950a4278a69ac1751d33bdc1263233d81 | 1,168 | advent-of-code-2022 | Apache License 2.0 |
advent-of-code-2022/src/test/kotlin/Day 7 No Space Left On Device.kt | yuriykulikov | 159,951,728 | false | {"Kotlin": 1666784, "Rust": 33275} | import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
class `Day 7 No Space Left On Device` {
data class ElfFile(
val name: String,
val parent: ElfFile? = null,
val size: Int = 0,
val contents: MutableList<ElfFile> = mutableListOf(),
) {
val totalSize: Int by lazy { size + contents.sumOf { it.totalSize } }
val isDir = size == 0
fun walk(): Sequence<ElfFile> {
return sequenceOf(this) + contents.flatMap { it.walk() }
}
}
@Test
fun silverTest() {
val root = parseInput(testInput)
root.walk().filter { it.isDir && it.totalSize < 100000 }.sumOf { it.totalSize } shouldBe 95437
}
@Test
fun silver() {
val root = parseInput(loadResource("day7"))
root.walk().filter { it.isDir && it.totalSize < 100000 }.sumOf { it.totalSize } shouldBe 1334506
}
@Test
fun goldTest() {
val root = parseInput(testInput)
smallestFolderToDelete(root) shouldBe 24933642
}
@Test
fun gold() {
val root = parseInput(loadResource("day7"))
smallestFolderToDelete(root) shouldBe 7421137
}
private fun smallestFolderToDelete(root: ElfFile): Int {
val needToFree = root.totalSize + 30000000 - 70000000
return root.walk().filter { it.isDir && it.totalSize > needToFree }.map { it.totalSize }.min()
}
private fun parseInput(input: String): ElfFile {
val root = ElfFile("/")
var current = root
input.trim().lines().forEach { line ->
val left = line.substringBeforeLast(" ")
val right = line.substringAfterLast(" ")
when (left) {
"\$ ls" -> Unit
"\$ cd" -> {
current =
when (right) {
"/" -> root
".." -> current.parent ?: current
else -> current.contents.firstOrNull { it.name == right } ?: current
}
}
else -> {
// dir or file
val size = left.toIntOrNull() ?: 0
current.contents.add(ElfFile(right, parent = current, size = size))
}
}
}
return root
}
}
private val testInput =
"""
$ cd /
$ ls
dir a
14848514 b.txt
8504156 c.dat
dir d
$ cd a
$ ls
dir e
29116 f
2557 g
62596 h.lst
$ cd e
$ ls
584 i
$ cd ..
$ cd ..
$ cd d
$ ls
4060174 j
8033020 d.log
5626152 d.ext
7214296 k
""".trimIndent()
| 0 | Kotlin | 0 | 1 | f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3 | 2,305 | advent-of-code | MIT License |
src/main/kotlin/aoc23/Day07.kt | tahlers | 725,424,936 | false | {"Kotlin": 65626} | package aoc23
object Day07 {
enum class Card {
JOKER, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE,
}
enum class HandType {
HIGH_CARD, ONE_PAIR, TWO_PAIR, THREE_OF_A_KIND, FULL_HOUSE, FOUR_OF_A_KIND, FIVE_OF_A_KIND
}
data class Hand(val cards: List<Card>, val bid: Long, val isJokerPlay: Boolean = false) : Comparable<Hand> {
private val type = if (isJokerPlay) calculateJokerPlayType() else calculateType()
private fun calculateType(): HandType {
val cardMap = cards.groupBy { it }
return when {
cardMap.size == 1 -> HandType.FIVE_OF_A_KIND
cardMap.any { it.value.size == 4 } -> HandType.FOUR_OF_A_KIND
cardMap.size == 2 -> HandType.FULL_HOUSE
cardMap.any { it.value.size == 3 } -> HandType.THREE_OF_A_KIND
cardMap.size == 3 -> HandType.TWO_PAIR
cardMap.size == 4 -> HandType.ONE_PAIR
else -> HandType.HIGH_CARD
}
}
private fun calculateJokerPlayType(): HandType {
val cardMap = cards.groupBy { it }
val jokerCount = cardMap[Card.JOKER]?.size ?: 0
val normalType = calculateType()
return when {
normalType == HandType.FOUR_OF_A_KIND && jokerCount >= 1 -> HandType.FIVE_OF_A_KIND
normalType == HandType.THREE_OF_A_KIND && jokerCount == 3 && cardMap.size == 2 -> HandType.FIVE_OF_A_KIND
normalType == HandType.THREE_OF_A_KIND && jokerCount == 3 && cardMap.size == 3 -> HandType.FOUR_OF_A_KIND
normalType == HandType.THREE_OF_A_KIND && jokerCount == 2 -> HandType.FIVE_OF_A_KIND
normalType == HandType.THREE_OF_A_KIND && jokerCount == 1 -> HandType.FOUR_OF_A_KIND
normalType == HandType.FULL_HOUSE && jokerCount > 0 -> HandType.FIVE_OF_A_KIND
normalType == HandType.TWO_PAIR && jokerCount > 1 -> HandType.FOUR_OF_A_KIND
normalType == HandType.TWO_PAIR && jokerCount == 1 -> HandType.FULL_HOUSE
normalType == HandType.ONE_PAIR && jokerCount == 2 -> HandType.THREE_OF_A_KIND
normalType == HandType.ONE_PAIR && jokerCount == 1 -> HandType.THREE_OF_A_KIND
normalType == HandType.HIGH_CARD && jokerCount == 1 -> HandType.ONE_PAIR
else -> normalType
}
}
override fun compareTo(other: Hand): Int = compareBy(
Hand::type,
{ it.cards[0] },
{ it.cards[1] },
{ it.cards[2] },
{ it.cards[3] },
{ it.cards[4] },
).compare(this, other)
}
fun calculateTotalWinnings(input: String, isJokerPlay: Boolean = false): Long {
val hands = parseInput(input, isJokerPlay)
val sortedWithRanks = hands.sorted().withIndex()
val withWinnings = sortedWithRanks.map { it.value.bid * (it.index + 1) }
return withWinnings.sum()
}
private fun parseInput(input: String, isJokerPlay: Boolean = false): List<Hand> {
val lines = input.trim().lines()
return lines.map { line ->
val bid = line.substringAfter(' ').toLong()
val chars = line.substringBefore(' ')
val cards = chars.map { charToCard(it, isJokerPlay) }
Hand(cards, bid, isJokerPlay)
}
}
private fun charToCard(c: Char, isJokerPlay: Boolean = false): Card =
when (c) {
'2' -> Card.TWO
'3' -> Card.THREE
'4' -> Card.FOUR
'5' -> Card.FIVE
'6' -> Card.SIX
'7' -> Card.SEVEN
'8' -> Card.EIGHT
'9' -> Card.NINE
'T' -> Card.TEN
'J' -> if (isJokerPlay) Card.JOKER else Card.JACK
'Q' -> Card.QUEEN
'K' -> Card.KING
'A' -> Card.ACE
else -> throw IllegalArgumentException("Should never happen here!")
}
} | 0 | Kotlin | 0 | 0 | 0cd9676a7d1fec01858ede1ab0adf254d17380b0 | 4,032 | advent-of-code-23 | Apache License 2.0 |
Kotlin for Java Developers. Week 5/Games/Task/src/games/gameOfFifteen/GameOfFifteenHelper.kt | Anna-Sentyakova | 186,426,055 | false | null | package games.gameOfFifteen
/*
* This function should return the parity of the permutation.
* true - the permutation is even
* false - the permutation is odd
* https://en.wikipedia.org/wiki/Parity_of_a_permutation
* If the game of fifteen is started with the wrong parity, you can't get the correct result
* (numbers sorted in the right order, empty cell at last).
* Thus the initial permutation should be correct.
*/
fun isEven(permutation: List<Int>): Boolean {
val list = ArrayList(permutation)
val (_, count) = sort(list)
return count % 2 == 0
}
fun sort(list: List<Int>): Pair<List<Int>, Int> {
val sorted = ArrayList(list)
val size = sorted.size
var count = 0
for (i in 0 until size) {
for (j in 0 until size - i - 1) {
if (sorted[j] > sorted[j + 1]) {
val tmp = sorted[j]
sorted[j] = sorted[j + 1]
sorted[j + 1] = tmp
++count
}
}
}
return sorted to count
}
fun main() {
test(listOf(1, 2, 3))
test(listOf())
test(listOf(3, 2, 1))
test(listOf(-1, -2, -3))
test(listOf(-1, -2, -3, 0, 1, 2, 3))
}
fun test(list: List<Int>) {
val (sorted, _) = sort(list)
println(sorted.toString() == list.sorted().toString())
}
| 0 | Kotlin | 0 | 1 | e5db4940fa844aa8a5de7f90dd872909a06756e6 | 1,297 | coursera | Apache License 2.0 |
AdventOfCodeDay08/src/nativeMain/kotlin/Day08.kt | bdlepla | 451,510,571 | false | {"Kotlin": 165771} | class Day08(private val lines:List<String>) {
fun solvePart1() =
//.onEach{println(it.second)}
//.onEach{println(it)}
dataFromLines(lines)
.flatMap { it.second.trim().split(" ") }
.count { it.length in setOf(2, 3, 4, 7) }
fun solvePart2():Int = dataFromLines(lines).sumOf { decodeLine(it) }
private fun decodeLine(data:Pair<String,String>):Int {
val decodedMap = decodeInput(data.first)
return decodeOutput(decodedMap, data.second)
}
private fun decodeInput(input: String):Map<Char,Signal> {
val inputByLength = input
.split(" ")
.groupBy{it.length}
val segments = inputByLength
.map{p -> p.key to p.value.map{v -> v.toSet()}.reduce{a,b->a.intersect(b)}}
.toMap()
//println(input)
val upperSegment = segments[3]!! - segments[2]!!
//println("Upper is ${upperSegment.first()}")
val bottomSegment = segments[5]!! - upperSegment - segments[4]!!
//println("Bottom is ${bottomSegment.first()}")
val middleSegment = segments[5]!! - upperSegment - bottomSegment
//println("Middle is ${middleSegment.first()}")
val upperRightSegment = segments[2]!! - segments[6]!!
//println("UpperRight is ${upperRightSegment.first()}")
val lowerRightSegment = segments[2]!! - upperRightSegment
//println("LowerRight is ${lowerRightSegment.first()}")
val upperLeftSegment = segments[6]!! - upperSegment - bottomSegment - lowerRightSegment
//println("UpperLeft is ${upperLeftSegment.first()}")
val lowerLeftSegment = segments[7]!! - segments[6]!! - segments[4]!!
//println("LowerLeft is ${lowerLeftSegment.first()}")
return mapOf(
upperSegment.first() to Signal.UPPER ,
middleSegment.first() to Signal.MIDDLE,
bottomSegment.first() to Signal.BOTTOM,
upperLeftSegment.first() to Signal.UPPERLEFT,
lowerLeftSegment.first() to Signal.LOWERLEFT,
upperRightSegment.first() to Signal.UPPERRIGHT,
lowerRightSegment.first() to Signal.LOWERRIGHT
)
}
private val signalsToDigit = mapOf(
setOf(Signal.UPPER, Signal.UPPERLEFT, Signal.UPPERRIGHT, Signal.LOWERLEFT, Signal.LOWERRIGHT, Signal.BOTTOM) to '0',
setOf(Signal.UPPER, Signal.MIDDLE, Signal.BOTTOM, Signal.UPPERRIGHT, Signal.LOWERLEFT) to '2',
setOf(Signal.UPPER, Signal.MIDDLE, Signal.BOTTOM, Signal.UPPERRIGHT, Signal.LOWERRIGHT) to '3',
setOf(Signal.UPPER, Signal.MIDDLE, Signal.BOTTOM, Signal.UPPERLEFT, Signal.LOWERRIGHT) to '5',
setOf(Signal.UPPER, Signal.UPPERLEFT, Signal.MIDDLE, Signal.LOWERLEFT, Signal.LOWERRIGHT, Signal.BOTTOM) to '6',
setOf(Signal.UPPER, Signal.UPPERLEFT, Signal.UPPERRIGHT, Signal.MIDDLE, Signal.LOWERRIGHT, Signal.BOTTOM) to '9'
)
private fun decodeOutput(input:Map<Char,Signal>, outputDigits:String):Int {
//println(input)
val outputs = outputDigits.split(" ")
//println(outputs.joinToString(","))
val digits:String = outputs.map { output ->
when(output.length) {
2 -> '1'
3 -> '7'
4 -> '4'
7 -> '8'
else -> {
val signals = output.map{input[it]}.toSet()
//println(signals)
signalsToDigit[signals]!!
}
}
}
//.onEach { println(it) }
.joinToString("")
return digits.toInt()
}
private fun dataFromLines(lines:List<String>):List<Pair<String, String>> =
lines.map{it.substringBefore(" | ") to it.substringAfter(" | ")}
} | 0 | Kotlin | 0 | 0 | 1d60a1b3d0d60e0b3565263ca8d3bd5c229e2871 | 3,774 | AdventOfCode2021 | The Unlicense |
advent/src/test/kotlin/org/elwaxoro/advent/y2021/Dec10.kt | elwaxoro | 328,044,882 | false | {"Kotlin": 376774} | package org.elwaxoro.advent.y2021
import org.elwaxoro.advent.PuzzleDayTester
/**
* Syntax Scoring
*/
class Dec10 : PuzzleDayTester(10, 2021) {
override fun part1(): Any = parse().mapNotNull { line ->
line.analyze(scoreCorrupt = true)
}.sum()
override fun part2(): Any = parse().mapNotNull { line ->
line.analyze(scoreCorrupt = false)
}.sorted().let {
it[it.size / 2]
}
private fun parse(): List<List<Syntax>> = load().map { it.map(Syntax::parse) }
private fun List<Syntax>.analyze(scoreCorrupt: Boolean): Long? = mutableListOf<Syntax>().let { stack ->
firstOrNull { char ->
if (char.isClose()) {
!char.matches(stack.removeLast())
} else {
!stack.add(char)
}
}.let { corrupt ->
corrupt?.corruptScore.takeIf { scoreCorrupt } ?: stack.scoreIncomplete().takeIf { corrupt == null && !scoreCorrupt }
}
}
private fun List<Syntax>.scoreIncomplete(): Long = reversed().map { it.getMatch().incompleteScore }.fold(0L) { acc, char -> (acc * 5L) + char }
enum class Syntax(val char: Char, val corruptScore: Long = 0, val incompleteScore: Long = 0) {
OPEN_PAREN('('),
CLOSE_PAREN(')', 3L, 1L),
OPEN_BRACKET('['),
CLOSE_BRACKET(']', 57L, 2L),
OPEN_CURLY('{'),
CLOSE_CURLY('}', 1197L, 3L),
OPEN_ANGLE('<'),
CLOSE_ANGLE('>', 25137L, 4L);
companion object {
fun parse(char: Char): Syntax = values().single { it.char == char }
}
fun isClose(): Boolean = corruptScore > 0
fun matches(that: Syntax): Boolean = getMatch() == that
fun getMatch(): Syntax = when (this) {
OPEN_PAREN -> CLOSE_PAREN
CLOSE_PAREN -> OPEN_PAREN
OPEN_BRACKET -> CLOSE_BRACKET
CLOSE_BRACKET -> OPEN_BRACKET
OPEN_CURLY -> CLOSE_CURLY
CLOSE_CURLY -> OPEN_CURLY
OPEN_ANGLE -> CLOSE_ANGLE
CLOSE_ANGLE -> OPEN_ANGLE
}
}
}
| 0 | Kotlin | 4 | 0 | 1718f2d675f637b97c54631cb869165167bc713c | 2,075 | advent-of-code | MIT License |
src/main/kotlin/de/jball/aoc2022/day03/Day03.kt | fibsifan | 573,189,295 | false | {"Kotlin": 43681} | package de.jball.aoc2022.day03
import de.jball.aoc2022.Day
class Day03(test: Boolean = false) : Day<Long>(test, 157, 70) {
private val letterMapping = (
('a'..'z').zip(1L..26L) +
('A'..'Z').zip(27L..52L))
.toMap()
private val rucksacks = input
.map { it.toCharArray().toList() }
override fun part1(): Long {
return rucksacks
.map { rucksack -> Pair(firstCompartment(rucksack), secondCompartment(rucksack)) }
.map { (a, b) -> a.intersect(b) }
.sumOf { letterMapping[it.first()]!! }
}
private fun firstCompartment(rucksack: List<Char>) =
rucksack.subList(0, rucksack.size / 2).toSet()
private fun secondCompartment(rucksack: List<Char>) =
rucksack.subList(rucksack.size / 2, rucksack.size).toSet()
override fun part2(): Long {
return rucksacks
.map { rucksack -> rucksack.toSet() }
.chunked(3)
.map { threeRucksacks -> threeRucksacks.reduce { a, b -> a.intersect(b) } }
.sumOf { letterMapping[it.first()]!! }
}
}
fun main() {
Day03().run()
}
| 0 | Kotlin | 0 | 3 | a6d01b73aca9b54add4546664831baf889e064fb | 1,136 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/Day10.kt | SimonMarquis | 434,880,335 | false | {"Kotlin": 38178} | class Day10(raw: List<String>) {
private val input: List<String> = raw.map { it.solve() }
fun part1() = input.filter {
it.any { c -> c in CTRL.keys }
}.sumOf {
it.first { c -> c in CTRL.keys }.toInvalidScore()
}
fun part2() = input.filter {
it.none { c -> c in CTRL.keys }
}.map {
it.autocomplete().toAutocompleteScore()
}.sortedBy {
it
}.let { it[it.size / 2] }
private fun String.solve() = fold("") { acc, value ->
when {
value !in CTRL.keys -> acc + value
CTRL[value] == acc.last() -> acc.dropLast(1)
else -> acc + value
}
}
private fun Char.toInvalidScore(): Long = when (this) {
')' -> 3L
']' -> 57L
'}' -> 1197L
'>' -> 25137L
else -> TODO()
}
private fun String.autocomplete() = reversed().map { LRTC[it] }.joinToString(separator = "")
private fun String.toAutocompleteScore() = fold(0L) { acc, value ->
when (value) {
')' -> 1L
']' -> 2L
'}' -> 3L
'>' -> 4L
else -> TODO()
} + acc * 5
}
companion object {
val CTRL = mapOf(
']' to '[',
')' to '(',
'}' to '{',
'>' to '<',
)
val LRTC = CTRL.map { (k, v) -> v to k }.toMap()
}
} | 0 | Kotlin | 0 | 0 | 8fd1d7aa27f92ba352e057721af8bbb58b8a40ea | 1,393 | advent-of-code-2021 | Apache License 2.0 |
src/main/kotlin/com/chriswk/aoc/advent2020/Day24.kt | chriswk | 317,863,220 | false | {"Kotlin": 481061} | package com.chriswk.aoc.advent2020
import com.chriswk.aoc.AdventDay
import com.chriswk.aoc.util.HexDirection
import com.chriswk.aoc.util.Point2D
import com.chriswk.aoc.util.Point3D
import com.chriswk.aoc.util.report
class Day24: AdventDay(2020, 24) {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val day = Day24()
report {
day.part1()
}
report {
day.part2()
}
}
}
fun parseSingleLine(input: String): List<HexDirection> {
return input.fold((emptyList<HexDirection>() to "")) { (acc, prevChar), nextChar ->
when(prevChar) {
"s" -> when(nextChar) {
'e' -> acc + HexDirection.SouthEast to ""
'w' -> acc + HexDirection.SouthWest to ""
else -> error("Should never get here")
}
"n" -> when(nextChar) {
'e' -> acc + HexDirection.NorthEast to ""
'w' -> acc + HexDirection.NorthWest to ""
else -> error("Should never get here")
}
else -> {
when(nextChar) {
'e' -> acc + HexDirection.East to ""
'w' -> acc + HexDirection.West to ""
'n' -> acc to "n"
's' -> acc to "s"
else -> error("Should never get here")
}
}
}
}.first
}
fun move(origin: Point2D, instructions: List<HexDirection>): Point2D {
return instructions.fold(origin) { p, instruction ->
p + instruction.delta
}
}
fun flip(instructions: List<List<HexDirection>>): Map<Point2D, Boolean> {
return instructions.fold(mutableMapOf<Point2D, Boolean>()) { flippingMap, moves ->
val endAt = move(Point2D.ORIGIN, moves)
if (flippingMap.containsKey(endAt)) {
flippingMap[endAt] = !flippingMap.getValue(endAt)
} else {
flippingMap[endAt] = true
}
flippingMap
}
}
fun nextDay(tilesToCheck: List<Point2D>, tiles: Map<Point2D, Boolean>): Map<Point2D, Boolean> {
return tilesToCheck.map { tile ->
val self = tiles[tile] ?: false
val blackCount = tile.hexNeighbours.count { tiles[it] ?: false }
tile to when(self) {
true -> blackCount in 1..2
false -> blackCount == 2
}
}.toMap()
}
fun gatherTilesToCheck(tiles: Map<Point2D, Boolean>): List<Point2D> {
return tiles.entries.filter { it.value }.flatMap { it.key.hexNeighbours }.distinct().toList()
}
fun makeArt(floor: Map<Point2D, Boolean>): Sequence<Map<Point2D, Boolean>> {
return generateSequence(floor) { previousFloor ->
nextDay(gatherTilesToCheck(previousFloor), previousFloor)
}
}
fun parse(input: List<String>): List<List<HexDirection>> {
return input.map { parseSingleLine(it) }
}
fun countBlacks(tiles: Map<Point2D, Boolean>) : Int {
return tiles.count { it.value }
}
fun part1(): Int {
return countBlacks(flip(parse(inputAsLines)))
}
fun part2(): Int {
return countBlacks(makeArt(flip(parse(inputAsLines))).drop(100).first())
}
}
| 116 | Kotlin | 0 | 0 | 69fa3dfed62d5cb7d961fe16924066cb7f9f5985 | 3,555 | adventofcode | MIT License |
src/Day21.kt | jinie | 572,223,871 | false | {"Kotlin": 76283} | /*
Solution from https://todd.ginsberg.com/post/advent-of-code/2022/day21/
*/
class Day21(input: List<String>) {
private val monkeys: Set<Monkey> = parseInput(input)
private val root: Monkey = monkeys.first { it.name == "root" }
fun solvePart1(): Long =
root.yell()
fun solvePart2(): Long =
root.calculateHumanValue()
private fun parseInput(input: List<String>): Set<Monkey> {
val monkeyCache: Map<String, Monkey> = input.map { Monkey(it) }.associateBy { it.name }
monkeyCache.values.filterIsInstance<FormulaMonkey>().forEach { monkey ->
monkey.left = monkeyCache.getValue(monkey.leftName)
monkey.right = monkeyCache.getValue(monkey.rightName)
}
return monkeyCache.values.toSet()
}
private interface Monkey {
val name: String
fun yell(): Long
fun findHumanPath(): Set<Monkey>
fun calculateHumanValue(humanPath: Set<Monkey> = findHumanPath(), incoming: Long = 0L): Long
companion object {
operator fun invoke(row: String): Monkey {
val name = row.substringBefore(":")
return if (row.length == 17) {
FormulaMonkey(name, row.substring(6..9), row.substringAfterLast(" "), row[11])
} else {
NumberMonkey(name, row.substringAfter(" ").toLong())
}
}
}
}
private class NumberMonkey(
override val name: String,
val number: Long
) : Monkey {
override fun yell(): Long = number
override fun findHumanPath(): Set<Monkey> =
if (name == "humn") setOf(this) else emptySet()
override fun calculateHumanValue(humanPath: Set<Monkey>, incoming: Long): Long =
if (name == "humn") incoming else number
}
private class FormulaMonkey(
override val name: String,
val leftName: String,
val rightName: String,
val op: Char
) : Monkey {
lateinit var left: Monkey
lateinit var right: Monkey
override fun calculateHumanValue(humanPath: Set<Monkey>, incoming: Long): Long =
if (name == "root") {
if (left in humanPath) left.calculateHumanValue(humanPath, right.yell())
else right.calculateHumanValue(humanPath, left.yell())
} else if (left in humanPath) {
left.calculateHumanValue(humanPath, incoming leftAntiOp right.yell()) // Negate
} else {
right.calculateHumanValue(humanPath, incoming rightAntiOp left.yell()) // Negate
}
override fun findHumanPath(): Set<Monkey> {
val leftPath = left.findHumanPath()
val rightPath = right.findHumanPath()
return if (leftPath.isNotEmpty()) leftPath + this
else if (rightPath.isNotEmpty()) rightPath + this
else emptySet()
}
override fun yell(): Long =
left.yell() op right.yell()
private infix fun Long.op(right: Long): Long =
when (op) {
'+' -> this + right
'-' -> this - right
'*' -> this * right
else -> this / right
}
private infix fun Long.leftAntiOp(right: Long): Long =
when (op) {
'+' -> this - right
'-' -> this + right
'*' -> this / right
else -> this * right
}
private infix fun Long.rightAntiOp(right: Long): Long =
when (op) {
'+' -> this - right
'-' -> right - this
'*' -> this / right
else -> right / this
}
}
}
fun main() {
val testInput = readInput("Day21_test")
check(Day21(testInput).solvePart1() == 152L)
check(Day21(testInput).solvePart2() == 301L)
measureTimeMillisPrint {
val input = readInput("Day21")
val d21 = Day21(input)
println(d21.solvePart1())
println(d21.solvePart2())
}
} | 0 | Kotlin | 0 | 0 | 4b994515004705505ac63152835249b4bc7b601a | 4,104 | aoc-22-kotlin | Apache License 2.0 |
2018/kotlin/day4p1/src/kotlin/main.kt | sgravrock | 47,810,570 | false | {"Rust": 1263100, "Swift": 1167766, "Ruby": 641843, "C++": 529504, "Kotlin": 466600, "Haskell": 339813, "Racket": 264679, "HTML": 200276, "OpenEdge ABL": 165979, "C": 89974, "Objective-C": 50086, "JavaScript": 40960, "Shell": 33315, "Python": 29781, "Elm": 22980, "Perl": 10662, "BASIC": 9264, "Io": 8122, "Awk": 5701, "Raku": 5532, "Rez": 4380, "Makefile": 1241, "Objective-C++": 1229, "Tcl": 488} | import java.lang.Exception
import java.util.*
fun main(args: Array<String>) {
val start = Date()
val classLoader = Time::class.java.classLoader
val input = classLoader.getResource("input.txt").readText()
println(puzzleSolution(parseInput(input)))
println("in ${Date().time - start.time}ms")
}
data class Time(val hour: Int, val minute: Int) {
fun toMinutes() = hour * 60 + minute
}
data class TimeRange(val start: Time, val end: Time)
fun sleepiestGuard(sleepsByGuard: Map<Int, List<TimeRange>>): Int {
return sleepsByGuard.entries
.sortedBy { totalMinutes(it.value) }
.last().key
}
fun sleepiestMinute(sleeps: List<TimeRange>): Int {
return (0..59)
.sortedBy { minute ->
sleeps.filter {
it.start.hour == 0 &&
it.end.hour == 0 &&
it.start.minute <= minute &&
it.end.minute > minute
}.count()
}
.last()
}
fun totalMinutes(ranges: List<TimeRange>): Int {
// Offer void where prohibited or if any sleep spans midnight.
// Do not fold, spindle, or mutilate.
return ranges.map { it.end.toMinutes() - it.start.toMinutes() }.sum()
}
fun parseInput(input: String): Map<Int, List<TimeRange>> {
val result = mutableMapOf<Int, MutableList<TimeRange>>()
var curGuard: Int? = null
var curSleepStart: Time? = null
val shiftStartRe = Regex("Guard #([\\d]+) begins shift")
val sleepStartRe = Regex("([\\d]{2}):([\\d]{2})\\] falls asleep")
val sleepEndRe = Regex("([\\d]{2}):([\\d]{2})\\] wakes up")
for (line in input.lines().sorted()) {
val shiftMatch = shiftStartRe.find(line)
val sleepStartMatch = sleepStartRe.find(line)
val sleepEndMatch = sleepEndRe.find(line)
if (shiftMatch != null) {
curGuard = shiftMatch.groupValues[1].toInt()
if (!result.containsKey(curGuard)) {
result[curGuard] = mutableListOf()
}
} else if (sleepStartMatch != null) {
curSleepStart = Time(
sleepStartMatch.groupValues[1].toInt(),
sleepStartMatch.groupValues[2].toInt()
)
} else if (sleepEndMatch != null) {
result[curGuard]!!.add(TimeRange(
curSleepStart!!,
Time(
sleepEndMatch.groupValues[1].toInt(),
sleepEndMatch.groupValues[2].toInt()
)
))
} else {
throw Exception("Parse error: ${line}")
}
}
return result
}
fun puzzleSolution(sleepsByGuard: Map<Int, List<TimeRange>>): Int {
val guard = sleepiestGuard(sleepsByGuard)
return guard * sleepiestMinute(sleepsByGuard[guard]!!)
} | 0 | Rust | 0 | 0 | ea44adeb128cf1e3b29a2f0c8a12f37bb6d19bf3 | 2,872 | adventofcode | MIT License |
src/iii_conventions/MyDate.kt | michaelsergio | 92,528,745 | false | null | package iii_conventions
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int)
operator fun MyDate.rangeTo(other: MyDate): DateRange = DateRange(this, other)
operator fun MyDate.compareTo(other: MyDate): Int {
if (this.year < other.year) return -1
else if (this.year > other.year) return 1
else if (this.month < other.month) return -1
else if (this.month > other.month) return 1
else if (this.dayOfMonth < other.dayOfMonth) return -1
else if (this.dayOfMonth > other.dayOfMonth) return 1
else return 0
}
operator fun MyDate.plus(interval: TimeInterval): MyDate =
when (interval) {
TimeInterval.DAY -> this.addTimeIntervals(TimeInterval.DAY, 1)
TimeInterval.WEEK -> this.addTimeIntervals(TimeInterval.WEEK, 1)
TimeInterval.YEAR -> this.addTimeIntervals(iii_conventions .TimeInterval.YEAR, 1)
}
operator fun MyDate.plus(multipleIntervals: MultipleTimeIntervals): MyDate {
val quantity = multipleIntervals.quantity
val interval = multipleIntervals.interval
return when (interval) {
TimeInterval.DAY -> this.addTimeIntervals(TimeInterval.DAY, quantity)
TimeInterval.WEEK -> this.addTimeIntervals(TimeInterval.WEEK, quantity)
TimeInterval.YEAR -> this.addTimeIntervals(iii_conventions.TimeInterval.YEAR, quantity)
}
}
enum class TimeInterval {
DAY,
WEEK,
YEAR
}
data class MultipleTimeIntervals(val quantity:Int, val interval: TimeInterval)
operator fun TimeInterval.times(quantity: Int) : MultipleTimeIntervals = MultipleTimeIntervals(quantity, this)
operator fun Int.times(interval: TimeInterval) : MultipleTimeIntervals = MultipleTimeIntervals(this, interval)
class DateRange(val start: MyDate, val endInclusive: MyDate) : Iterator<MyDate> {
var dateIter: MyDate = start
override fun next(): MyDate {
val curDate = this.dateIter
this.dateIter = dateIter.nextDay() // advance iterator
return curDate
}
override fun hasNext(): Boolean = dateIter in this
}
operator fun DateRange.contains(date: MyDate): Boolean = start <= date && date <= endInclusive
| 0 | Kotlin | 0 | 0 | 558455d39da4a680c4ce9980a27b51963966fc99 | 2,126 | kotlinkoans | MIT License |
src/main/kotlin/Problem25.kt | jimmymorales | 496,703,114 | false | {"Kotlin": 67323} | import kotlin.math.max
/**
* 1000-digit Fibonacci number
*
* The Fibonacci sequence is defined by the recurrence relation:
* Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
* Hence the first 12 terms will be:
* F1 = 1
* F2 = 1
* F3 = 2
* F4 = 3
* F5 = 5
* F6 = 8
* F7 = 13
* F8 = 21
* F9 = 34
* F10 = 55
* F11 = 89
* F12 = 144
*
* The 12th term, F12, is the first term to contain three digits.
* What is the index of the first term in the Fibonacci sequence to contain 1000 digits?
*
* https://projecteuler.net/problem=25
*/
fun main() {
println(fibIndexOfDigitsCount(digitsCount = 3))
println(fibIndexOfDigitsCount(digitsCount = 1_000))
}
private fun fibIndexOfDigitsCount(digitsCount: Int): Int {
if (digitsCount == 1) return 1
val f1 = mutableListOf(1)
val f2 = mutableListOf(1)
var index = 2
var turn = true // true for f1, false for f2
while (f1.size != digitsCount && f2.size != digitsCount) {
if (turn) {
sum(f1, f2)
} else {
sum(f2, f1)
}
turn = !turn
index++
}
return index
}
private fun sum(list1: MutableList<Int>, list2: MutableList<Int>) {
var acc = 0
for (i in 0 until max(list1.size, list2.size)) {
val sum = list1.getOrElse(i) { 0 } + list2.getOrElse(i) { 0 } + acc
if (i < list1.size) {
list1[i] = sum % 10
} else {
list1.add(sum % 10)
}
acc = sum / 10
}
while (acc != 0) {
list1.add(acc % 10)
acc /= 10
}
}
| 0 | Kotlin | 0 | 0 | e881cadf85377374e544af0a75cb073c6b496998 | 1,619 | project-euler | MIT License |
src/Day11.kt | wbars | 576,906,839 | false | {"Kotlin": 32565} | import java.math.BigInteger
class Monkey(var items: ArrayDeque<Long>, val test: Int, val trueMonkey: Int, val falseMonkey: Int, val operation: (Long) -> Long)
fun main() {
fun part1(input: List<String>): Int {
val monkeys = listOf(
Monkey(ArrayDeque(listOf(53, 89, 62, 57, 74, 51, 83, 97)), 13, 1, 5) { it * 3 },
Monkey(ArrayDeque(listOf(85, 94, 97, 92, 56)), 19, 5, 2) { it + 2 },
Monkey(ArrayDeque(listOf(86, 82, 82)), 11, 3, 4) { it + 1 },
Monkey(ArrayDeque(listOf(94, 68)), 17, 7, 6) { it + 5 },
Monkey(ArrayDeque(listOf(83, 62, 74, 58, 96, 68, 85)), 3, 3, 6) { it + 4 },
Monkey(ArrayDeque(listOf(50, 68, 95, 82)), 7, 2, 4) { it + 8 },
Monkey(ArrayDeque(listOf(75)), 5, 7, 0) { it * 7 },
Monkey(ArrayDeque(listOf(92, 52, 85, 89, 68, 82)), 2, 0, 1) { it * it },
)
val count = IntArray(monkeys.size)
repeat(20) {
for ((index, monkey) in monkeys.withIndex()) {
while (!monkey.items.isEmpty()) {
count[index]++
val v = monkey.items.removeFirst()
val vv = monkey.operation(v) / 3
if (vv % monkey.test == 0L) {
monkeys[monkey.trueMonkey].items.addLast(vv)
} else {
monkeys[monkey.falseMonkey].items.addLast(vv)
}
}
}
}
val s = count.sortedDescending()
return s[0] * s[1]
}
fun part2(input: List<String>): Long {
val monkeys = listOf(
Monkey(ArrayDeque(listOf(53, 89, 62, 57, 74, 51, 83, 97)), 13, 1, 5) { it * 3 },
Monkey(ArrayDeque(listOf(85, 94, 97, 92, 56)), 19, 5, 2) { it + 2 },
Monkey(ArrayDeque(listOf(86, 82, 82)), 11, 3, 4) { it + 1 },
Monkey(ArrayDeque(listOf(94, 68)), 17, 7, 6) { it + 5 },
Monkey(ArrayDeque(listOf(83, 62, 74, 58, 96, 68, 85)), 3, 3, 6) { it + 4 },
Monkey(ArrayDeque(listOf(50, 68, 95, 82)), 7, 2, 4) { it + 8 },
Monkey(ArrayDeque(listOf(75)), 5, 7, 0) { it * 7 },
Monkey(ArrayDeque(listOf(92, 52, 85, 89, 68, 82)), 2, 0, 1) { it * it },
)
val gcd = monkeys.map { it.test }.reduce { a, b -> a * b }.toLong()
val count = LongArray(monkeys.size)
repeat(10000) {
for ((index, monkey) in monkeys.withIndex()) {
while (!monkey.items.isEmpty()) {
count[index]++
val v = monkey.operation(monkey.items.removeFirst()) % gcd
if (v % monkey.test == 0L) {
monkeys[monkey.trueMonkey].items.addLast(v)
} else {
monkeys[monkey.falseMonkey].items.addLast(v)
}
}
}
}
val s = count.sortedDescending()
return s[0] * s[1]
}
part1(readInput("input")).println()
part2(readInput("input")).println()
}
| 0 | Kotlin | 0 | 0 | 344961d40f7fc1bb4e57f472c1f6c23dd29cb23f | 3,137 | advent-of-code-2022 | Apache License 2.0 |
src/Day01.kt | zsmb13 | 572,719,881 | false | {"Kotlin": 32865} | import java.util.TreeSet
fun main() {
fun part1(input: List<String>): Int {
var max = 0
var sum = 0
fun checkAndUpdate() {
if (sum > max) {
max = sum
}
sum = 0
}
for (line in input) {
if (line.isEmpty()) {
checkAndUpdate()
continue
}
sum += line.toInt()
}
checkAndUpdate()
return max
}
fun <T> List<T>.split(predicate: (T) -> Boolean): List<List<T>> {
val list = mutableListOf<MutableList<T>>()
var subList = mutableListOf<T>()
forEach { element ->
when {
predicate(element) -> {
list += subList
subList = mutableListOf()
}
else -> subList += element
}
}
list += subList
return list
}
fun part2(input: List<String>): Int {
val set = TreeSet<Int>(reverseOrder())
input.split(String::isEmpty)
.map { elfInventory -> elfInventory.sumOf(String::toInt) }
.forEach(set::add)
return set.take(3).sum()
}
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 6 | 32f79b3998d4dfeb4d5ea59f1f7f40f7bf0c1f35 | 1,431 | advent-of-code-2022 | Apache License 2.0 |
kotlin/src/main/kotlin/dev/egonr/leetcode/04_MedianTwoSortedArrays.kt | egon-r | 575,970,173 | false | null | package dev.egonr.leetcode
/* Hard
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
Median: The middle number; found by ordering all data points and picking out the one in the middle
(or if there are two middle numbers, taking the mean of those two numbers)
The overall run time complexity should be O(log (m+n)).
Example 1:
Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.
Example 2:
Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
Constraints:
nums1.length == m
nums2.length == n
0 <= m <= 1000
0 <= n <= 1000
1 <= m + n <= 2000
-106 <= nums1[i], nums2[i] <= 106
*/
class MedianTwoSortedArrays {
fun test() {
println(findMedianSortedArrays(intArrayOf(1,3), intArrayOf(2))) // merged 1,2,3 -> median 2
println(findMedianSortedArrays(intArrayOf(1,2), intArrayOf(3,4))) // merged 1,2,3,4 -> median (2+3)/2 -> 2.5
}
fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double {
val merged = arrayListOf<Int>()
merged.addAll(nums1.toList())
merged.addAll(nums2.toList())
merged.sort()
val mergedLen = merged.count()
var median = 0.0
if(mergedLen % 2 == 0) {
median = (merged[mergedLen / 2] + merged[mergedLen / 2 - 1]) / 2.0
} else {
median = merged[mergedLen / 2].toDouble()
}
return median
}
} | 0 | Kotlin | 0 | 0 | b9c59e54ca2d1399d34d1ee844e03c16a580cbcb | 1,570 | leetcode | The Unlicense |
src/main/kotlin/aoc22/Day07.kt | asmundh | 573,096,020 | false | {"Kotlin": 56155} | package aoc22
import readInput
fun Char.parseToCommand(): String {
return when (this) {
'$' -> "Command"
'1', '2', '3', '4', '5', '6', '7', '8', '9', '0' -> "File"
'd' -> "Directory"
else -> throw Exception("nei nei - $this")
}
}
fun Pair<Int, String>.cdToFolder(cdDestination: String): Pair<Int, String> {
return when (cdDestination) {
"/" -> 0 to "/"
".." -> (this.first - 1) to this.second.dropLast(1).dropLastWhile { it != '/' }.let {
it.ifEmpty { "/" }
}
else -> this.first + 1 to this.second + "$cdDestination/"
}
}
fun String.getParentFolder(): String {
return if (this == "/" || this == "") "/"
else this.dropLast(1).dropLastWhile { it != '/' }
}
fun String.increaseSizeOfParentFolder(folders: MutableMap<String, Int>, size: Int) {
val parentFolder = this.getParentFolder()
if (this == "/") {
folders["/"] = folders["/"]?.plus(size)!!
return
} else {
try {
if (folders[parentFolder] == null) {
folders[parentFolder] = size
} else {
if (parentFolder != "/") folders[parentFolder] = folders[parentFolder]?.plus(size)!!
}
parentFolder.increaseSizeOfParentFolder(folders, size)
} catch (e: Exception) {
println("Nullpointer på $this, parent: $parentFolder")
}
}
}
fun day7part1(input: List<String>): Int {
var currentFolder = 0 to "/"
val inputIt = input.iterator()
val folderSizes: MutableMap<String, Int> = mutableMapOf()
var nextCommand = ""
while (inputIt.hasNext()) {
if (nextCommand != "") {
val next = nextCommand.split(" ")
if (next[1] == "cd") {
currentFolder = currentFolder.cdToFolder(next[2])
nextCommand = ""
}
}
val currentLine = inputIt.next()
val current = currentLine.split(" ")
when (current[0].first().parseToCommand()) {
"Command" -> {
if (current[1] == "cd") {
currentFolder = currentFolder.cdToFolder(current[2])
}
if (current[1] == "ls") {
var files = mutableListOf<List<String>>()
var folders = mutableListOf<List<String>>()
var keepChecking = true
while (inputIt.hasNext() && keepChecking) {
val nextLine = inputIt.next()
if (nextLine.startsWith("$")) {
nextCommand = nextLine
keepChecking = false
} else {
val content = nextLine.split(" ")
if (content[0].first().parseToCommand() == "File") {
files.add(content)
}
if (content[0].first().parseToCommand() == "Directory") {
folders.add(content)
}
}
}
val folderSize = files.sumOf { it[0].toInt() }
if (folderSizes[currentFolder.second] == null) {
folderSizes[currentFolder.second] = folderSize
} else {
folderSizes[currentFolder.second] = folderSizes[currentFolder.second]?.plus(folderSize)!!
}
if (currentFolder.second != "/") currentFolder.second.increaseSizeOfParentFolder(folderSizes, folderSize)
}
}
else -> throw Exception("Feil ved input: ${current[0].first().parseToCommand()}")
}
}
val outFolders = folderSizes.filter { it.value <= 100000 }
return outFolders.values.sum()
}
fun day7part2(input: List<String>): Int {
var currentFolder = 0 to "/"
var totalFileSize = 0
val inputIt = input.iterator()
val folderSizes: MutableMap<String, Int> = mutableMapOf()
var nextCommand = ""
while (inputIt.hasNext()) {
if (nextCommand != "") {
val next = nextCommand.split(" ")
if (next[1] == "cd") {
currentFolder = currentFolder.cdToFolder(next[2])
nextCommand = ""
}
}
val currentLine = inputIt.next()
val current = currentLine.split(" ")
when (current[0].first().parseToCommand()) {
"Command" -> {
if (current[1] == "cd") {
currentFolder = currentFolder.cdToFolder(current[2])
}
if (current[1] == "ls") {
var files = mutableListOf<List<String>>()
var folders = mutableListOf<List<String>>()
var keepChecking = true
while (inputIt.hasNext() && keepChecking) {
val nextLine = inputIt.next()
if (nextLine.startsWith("$")) {
nextCommand = nextLine
keepChecking = false
} else {
val content = nextLine.split(" ")
if (content[0].first().parseToCommand() == "File") {
files.add(content)
totalFileSize += content[0].toInt()
}
if (content[0].first().parseToCommand() == "Directory") {
folders.add(content)
}
}
}
val folderSize = files.sumOf { it[0].toInt() }
if (folderSizes[currentFolder.second] == null) {
folderSizes[currentFolder.second] = folderSize
} else {
folderSizes[currentFolder.second] = folderSizes[currentFolder.second]?.plus(folderSize)!!
}
currentFolder.second.increaseSizeOfParentFolder(folderSizes, folderSize)
}
}
else -> throw Exception("Feil ved input: ${current[0].first().parseToCommand()}")
}
}
val toDelete = folderSizes.filter { it.value >= 4965705 }.values.min()
return toDelete
}
fun main() {
val input = readInput("Day07")
println(day7part1(input))
println(day7part2(input))
}
| 0 | Kotlin | 0 | 0 | 7d0803d9b1d6b92212ee4cecb7b824514f597d09 | 6,532 | advent-of-code | Apache License 2.0 |
dataStructuresAndAlgorithms/src/main/java/dev/funkymuse/datastructuresandalgorithms/sort/HeapSort.kt | FunkyMuse | 168,687,007 | false | {"Kotlin": 1728251} | package dev.funkymuse.datastructuresandalgorithms.sort
import dev.funkymuse.datastructuresandalgorithms.swap
import dev.funkymuse.datastructuresandalgorithms.swapAt
/**
Inventor: <NAME>
Worst complexity: n*log(n)
Average complexity: n*log(n)
Best complexity: n*log(n)
Space complexity: 1
*/
private fun <T : Comparable<T>> maxHeapify(list: MutableList<T>, index: Int, heapSize: Int) {
val left = index * 2
val right = (index * 2) + 1
var largestIndex: Int = index
if (left < heapSize && list[left] > list[largestIndex]) largestIndex = left
if (right < heapSize && list[right] > list[largestIndex]) largestIndex = right
if (largestIndex != index) {
list.swap(index, largestIndex)
maxHeapify(list, largestIndex, heapSize)
}
}
private fun <T : Comparable<T>> buildMaxHeap(list: MutableList<T>) {
val length = list.size / 2
for (i in length downTo 0) maxHeapify(list, i, list.size)
}
fun <T : Comparable<T>> heapSort(list: MutableList<T>) {
buildMaxHeap(list)
var heapSize = list.size
for (i in (list.size - 1) downTo 1) {
list.swap(0, i)
maxHeapify(list, 0, --heapSize)
}
}
fun <T> Array<T>.heapSort(comparator: Comparator<T>) {
this.heapfy(comparator)
for (index in this.indices.reversed()) {
this.swapAt(0, index)
shiftDown(0, index, comparator)
}
}
fun <T> Array<T>.heapfy(comparator: Comparator<T>) {
if (this.isNotEmpty()) {
(this.size / 2 downTo 0).forEach {
this.shiftDown(it, this.size, comparator)
}
}
}
fun <T> Array<T>.shiftDown(index: Int, upTo: Int, comparator: Comparator<T>) {
var parent = index
while (true) {
val left = leftChildIndex(parent)
val right = rightChildIndex(parent)
var candidate = parent
if (left < upTo && comparator.compare(this[left], this[candidate]) > 0) {
candidate = left
}
if (right < upTo && comparator.compare(this[right], this[candidate]) > 0) {
candidate = right
}
if (candidate == parent) {
return
}
this.swapAt(parent, candidate)
parent = candidate
}
}
private fun leftChildIndex(index: Int) = (2 * index) + 1
private fun rightChildIndex(index: Int) = (2 * index) + 2 | 0 | Kotlin | 92 | 771 | e2afb0cc98c92c80ddf2ec1c073d7ae4ecfcb6e1 | 2,321 | KAHelpers | MIT License |
solutions/aockt/y2021/Y2021D03.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2021
import io.github.jadarma.aockt.core.Solution
object Y2021D03 : Solution {
/**
* Given a list of numbers, generates a mask number based on the [predicate].
* @param mask The mask of relevant bits to keep. Should always be 2^n - 1, where n is the numbers of bits in use.
* @param predicate The function that decides what the bit value for a position would be. It takes it the ratio of
* set bits for any particular column.
*/
private fun List<ULong>.generatePopCountFilter(
mask: ULong,
predicate: (popCountRatio: Double) -> Boolean,
): ULong =
fold(MutableList(ULong.SIZE_BITS) { 0 }) { acc, number ->
acc.apply {
indices.forEach { i -> acc[i] += number.shr(ULong.SIZE_BITS - i - 1).and(1uL).toInt() }
}
}
.let { count -> BooleanArray(ULong.SIZE_BITS) { predicate(count[it] / size.toDouble()) } }
.joinToString(separator = "") { if (it) "1" else "0" }
.toULong(2)
.and(mask)
/**
* Given a list of numbers, generates a mask number based on the [predicate] similar to [generatePopCountFilter],
* but instead of taking all columns at once, each column filters the candidates of the others, starting from most
* significant bit to least significant.
* @param mask The mask of relevant bits to keep. Should always be 2^n - 1, where n is the numbers of bits in use.
* @param predicate The function that decides what the bit value for a position would be. It takes it the ratio of
* set bits for any particular column.
*/
private fun List<ULong>.generateIterativePopCountFilter(
mask: ULong,
predicate: (popCountRatio: Double) -> Boolean,
): ULong {
require(isNotEmpty()) { "Nothing to filter." }
require(mask.countOneBits() + mask.countLeadingZeroBits() == ULong.SIZE_BITS) { "Invalid mask." }
val binaryColumns = mask.countOneBits()
val candidates = toMutableList()
for (index in 0 until binaryColumns) {
val indexMask = 1uL shl (ULong.SIZE_BITS - mask.countLeadingZeroBits() - index - 1)
if (candidates.size <= 1) break
val filter = candidates.generatePopCountFilter(mask, predicate)
candidates.removeAll { (it xor filter and indexMask) != 0uL }
}
require(candidates.isNotEmpty()) { "No candidate satisfies the filter." }
return candidates.first()
}
/**
* Returns the bit mask (relevant binary columns) and the list of numbers read from the binary diagnostics report.
* The mask is important because depending on what [input] you use, you might use different sized binary numbers.
*/
private fun parseInput(input: String): Pair<ULong, List<ULong>> {
var numberLength = -1
val numbers = input
.lineSequence()
.onEach { if (numberLength == -1) numberLength = it.length else require(it.length == numberLength) }
.map { it.toULongOrNull(2) ?: throw IllegalArgumentException() }
.toList()
require(numberLength <= ULong.SIZE_BITS) { "This machine is not compatible with extra wide diagnostics." }
return ULong.MAX_VALUE.shr(ULong.SIZE_BITS - numberLength) to numbers
}
override fun partOne(input: String): Any {
val (mask, numbers) = parseInput(input)
val epsilon = numbers.generatePopCountFilter(mask) { it >= 0.5 }
val gamma = numbers.generatePopCountFilter(mask) { it < 0.5 }
return epsilon * gamma
}
override fun partTwo(input: String): Any {
val (mask, numbers) = parseInput(input)
val o2gen = numbers.generateIterativePopCountFilter(mask) { it >= 0.5 }
val co2Scrub = numbers.generateIterativePopCountFilter(mask) { it < 0.5 }
return o2gen * co2Scrub
}
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 3,936 | advent-of-code-kotlin-solutions | The Unlicense |
src/main/kotlin/solutions/Day2RockPaperScissors.kt | aormsby | 571,002,889 | false | {"Kotlin": 80084} | package solutions
import utils.Input
import utils.Solution
// run only this day
fun main() {
Day2RockPaperScissors()
}
class Day2RockPaperScissors : Solution() {
private val diff = 'X' - 'A'
private val win = 'w'
private val loss = 'l'
private val draw = 'd'
private val points = mapOf(
'A' to 1, 'B' to 2, 'C' to 3,
'X' to 1, 'Y' to 2, 'Z' to 3,
loss to 0, draw to 3, win to 6,
)
init {
begin("Day 2 - Rock Paper Scissors")
val gamePairs = Input.parseToPairList<Char, Char>(
filename = "/d2_strategy_guide.txt",
pairDelimiter = " ",
groupDelimiter = "\n"
)
val sol1 = calculateTotalScore1(gamePairs)
output("Total Score 1", sol1)
val sol2 = calculateTotalScore2(gamePairs)
output("Total Score 2", sol2)
}
// subtract their char from mine, normalize with 'diff', convert to wins/losses, sum points
private fun calculateTotalScore1(input: List<Pair<Char, Char>>): Int =
input.fold(initial = 0) { acc, pair ->
val resultPoints = when (pair.second - pair.first - diff) {
0 -> points[draw]!!
1, -2 -> points[win]!!
else -> points[loss]!!
}
acc + points[pair.second]!! + resultPoints
}
// check result, convert to result to points of the correct selection, sum points
private fun calculateTotalScore2(input: List<Pair<Char, Char>>): Int =
input.fold(initial = 0) { acc, pair ->
val result = when (points[pair.second]) {
3 -> win
2 -> draw
else -> loss
}
val selectionPoints = when (result) {
win -> points[pair.first + 1] ?: points[pair.first - 2]!!
loss -> points[pair.first - 1] ?: points[pair.first + 2]!!
else -> points[pair.first]!!
}
acc + points[result]!! + selectionPoints
}
} | 0 | Kotlin | 0 | 0 | 1bef4812a65396c5768f12c442d73160c9cfa189 | 2,033 | advent-of-code-2022 | MIT License |
src/day/_7/Day07.kt | Tchorzyksen37 | 572,924,533 | false | {"Kotlin": 42709} | package day._7
import java.io.File
fun main() {
data class File(val name: String, val size: Long) {
}
data class Directory(
val name: String,
val parentDirectory: Directory?
) {
var totalSize: Long? = null
var nestedDirectories: MutableSet<Directory> = mutableSetOf()
var files: MutableSet<File> = mutableSetOf()
}
lateinit var root: Directory
fun readStructure(input: String) {
lateinit var currentDir: Directory
val instructions = input.split("$").mapNotNull { if (it.isBlank()) null else it.trim() }
for (instruction in instructions) {
val instructionLines = instruction.lines().mapNotNull { if (it.isBlank()) null else it.trim() }
val command = instructionLines[0]
if (command.startsWith("cd")) {
val commandParts = command.split(" ")
if (commandParts[1] == "/") {
root = Directory(name = "root", parentDirectory = null)
currentDir = root
} else if (commandParts[1] == "..") {
currentDir = currentDir.parentDirectory ?: throw RuntimeException("No parent directory. I can go to.")
} else {
if (!currentDir.nestedDirectories.map { it.name }.contains(commandParts[1])) {
throw RuntimeException("It happened !!! Directory ${commandParts[1]} does not exist in nested directories")
}
currentDir = currentDir.nestedDirectories.single { it.name == commandParts[1] }
}
} else if (command == "ls") {
for (index in 1 until instructionLines.size) {
val outputParts = instructionLines[index].split(" ")
if (outputParts[0] == "dir") {
currentDir.nestedDirectories.add(Directory(name = outputParts[1], parentDirectory = currentDir))
} else {
currentDir.files.add(File(name = outputParts[1], size = outputParts[0].toLong()))
}
}
} else {
throw RuntimeException("Unknown command")
}
}
}
fun findDirectorySize(root: Directory): Long {
val nestedDirectoriesTotalSize = if (root.nestedDirectories.isEmpty()) 0 else
root.nestedDirectories.mapNotNull { if (it.totalSize == null) findDirectorySize(it) else it.totalSize }.sum()
val filesTotalSize = root.files.sumOf { it.size }
root.totalSize = nestedDirectoriesTotalSize + filesTotalSize
return root.totalSize!!
}
fun getFlatDirectories(root: Directory, directories: List<Directory>): List<Directory> {
return if (root.nestedDirectories.isEmpty()) mutableListOf(root) else {
val mutableDirectories = mutableListOf<Directory>()
mutableDirectories.addAll(directories)
mutableDirectories.add(root)
mutableDirectories.addAll(root.nestedDirectories.map {
getFlatDirectories(
it,
directories
)
}.flatten())
mutableDirectories
}
}
fun part1(root: Directory): Long {
return getFlatDirectories(root, mutableListOf()).map {
it.totalSize ?: throw RuntimeException("Total Size is null")
}
.filter { it < 100000L }
.sum()
}
fun part2(root: Directory): Long {
return getFlatDirectories(root, mutableListOf()).map {
it.totalSize ?: throw RuntimeException("Total Size is null")
}
.filter { it > 30000000L - (70000000L - root.totalSize!!) }
.min()
}
val testInput = File("src/day", "_7/Day07_test.txt").readText()
readStructure(testInput)
findDirectorySize(root)
check(part1(root) == 95437L)
check(part2(root) == 24933642L)
val input = File("src/day", "_7/Day07.txt").readText()
readStructure(input)
findDirectorySize(root)
println(part1(root))
println(part2(root))
} | 0 | Kotlin | 0 | 0 | 27d4f1a6efee1c79d8ae601872cd3fa91145a3bd | 3,442 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/ShoppingOffers.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.min
/**
* 638. Shopping Offers
* @see <a href="https://leetcode.com/problems/shopping-offers/">Source</a>
*/
fun interface ShoppingOffers {
operator fun invoke(price: List<Int>, special: List<List<Int>>, needs: List<Int>): Int
}
class ShoppingOffersRecursive : ShoppingOffers {
override operator fun invoke(price: List<Int>, special: List<List<Int>>, needs: List<Int>): Int {
return backTrace(price, special, needs, 0)
}
private fun backTrace(price: List<Int>, special: List<List<Int>>, needs: List<Int>, start: Int): Int {
var res = directPurchase(price, needs)
for (i in start until special.size) {
val offer = special[i]
if (isValid(offer, needs)) { // offer is a valid one
val tempNeeds: MutableList<Int> = ArrayList()
for (j in needs.indices) { // using this valid offer
tempNeeds.add(needs[j] - offer[j])
}
res = min(res, offer[offer.size - 1] + backTrace(price, special, tempNeeds, start))
}
}
return res
}
private fun isValid(offer: List<Int>, needs: List<Int>): Boolean {
for (i in needs.indices) {
if (needs[i] < offer[i]) return false
}
return true
}
private fun directPurchase(price: List<Int>, needs: List<Int>): Int {
var total = 0
for (i in needs.indices) {
total += price[i] * needs[i]
}
return total
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,166 | kotlab | Apache License 2.0 |
13/part_two.kt | ivanilos | 433,620,308 | false | {"Kotlin": 97993} | import java.io.File
fun readInput() : Paper {
val lines = File("input.txt")
.readLines()
val dots = mutableListOf<Pair<Int, Int>>()
val instructions = mutableListOf<Pair<Char, Int>>()
parseInput(lines, dots, instructions)
return Paper(dots, instructions)
}
fun parseInput(inputLines : List<String>,
dots : MutableList<Pair<Int, Int>>,
instructions: MutableList<Pair<Char, Int>>) {
var readingInstructions = false
for (line in inputLines) {
if (line.isEmpty()) {
readingInstructions = true
} else if (readingInstructions) {
instructions.add(parseInstruction(line))
} else {
dots.add(parseDot(line))
}
}
}
fun parseDot(line : String) : Pair<Int, Int> {
val (x, y) = line.split(",").map { it.toInt() }
return Pair(x, y)
}
fun parseInstruction(line : String) : Pair<Char, Int> {
val regex = """fold along ([x|y])=(\d+)""".toRegex()
val (axis, pos) = regex.find(line)?.destructured!!
return Pair(axis[0], pos.toInt())
}
class Paper(dots : MutableList<Pair<Int, Int>>, instructions : MutableList<Pair<Char, Int>>) {
var dots : MutableSet<Pair<Int, Int>>
private var instructions : List<Pair<Char,Int>>
init {
this.dots = dots.toMutableSet()
this.instructions = instructions
}
fun fold() {
for (instruction in instructions) {
val updatedDots = mutableSetOf<Pair<Int, Int>>()
for (dot in dots) {
if (instruction.first == 'x') {
val newX = if (dot.first < instruction.second) dot.first else 2 * instruction.second - dot.first
val newY = dot.second
updatedDots.add(Pair(newX, newY))
} else {
val newX = dot.first
val newY = if (dot.second < instruction.second) dot.second else 2 * instruction.second - dot.second
updatedDots.add(Pair(newX, newY))
}
}
dots = updatedDots
}
}
fun print() {
val maxDotX = dots.maxOf { it.first }
val maxDotY = dots.maxOf { it.second }
for (y in 0..maxDotY) {
for (x in 0..maxDotX) {
if (Pair(x, y) in dots) {
print("@")
} else {
print(" ")
}
}
println()
}
}
}
fun solve(paper: Paper) {
paper.fold()
paper.print() // REUPUPKR
}
fun main() {
val paper = readInput()
solve(paper)
}
| 0 | Kotlin | 0 | 3 | a24b6f7e8968e513767dfd7e21b935f9fdfb6d72 | 2,627 | advent-of-code-2021 | MIT License |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions40.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.round1
import com.qiaoyuang.algorithm.round0.PriorityQueue
import com.qiaoyuang.algorithm.round0.partition
fun test40() {
printResult(intArrayOf(5, 4, 1, 6, 2, 7, 3, 8), 4)
}
/**
* Questions40: Find the smallest k numbers in an IntArray
*/
private infix fun IntArray.findSmallestKNumbers1(k: Int): PriorityQueue<Int> {
require(isNotEmpty() && k in 1 ..< size) { "The k must be less than size of the IntArray and greater than 0" }
val queue = PriorityQueue<Int>()
queue.enqueue(first())
for (i in 1 ..< size) {
if (this[i] > queue.peak)
continue
queue.enqueue(this[i])
if (queue.size > 4)
queue.dequeue()
}
return queue
}
private infix fun IntArray.findSmallestKNumbers2(k: Int): IntArray {
require(isNotEmpty() && k in 1 ..< size) { "The k must less than size of the IntArray and greater than 0" }
var start = 0
var end = lastIndex
var index = partition(start, end)
while (index != k - 1) {
if (index > k - 1)
end = index - 1
else
start = index + 1
index = partition(start, end)
}
return IntArray(k) { this[it] }
}
private fun printResult(array: IntArray, k: Int) {
println("The smallest k numbers in IntArray: ${array.toList()} is/are: ${array findSmallestKNumbers1 k}")
println("The smallest k numbers in IntArray: ${array.toList()} is/are: ${(array findSmallestKNumbers2 k).toList()}")
} | 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 1,490 | Algorithm | Apache License 2.0 |
src/Day22.kt | illarionov | 572,508,428 | false | {"Kotlin": 108577} | fun main() {
val testInput = readInput("Day22_test")
val input = readInput("Day22")
part1(testInput).also {
println("Part 1, test input: $it")
check(it == 6032)
}
part1(input).also {
println("Part 1, real input: $it")
check(it == 146092)
}
// part2(testInput).also {
// println("Part 2, test input: $it")
// check(it == 5031)
// }
part2(input).also {
println("Part 2, real input: $it")
check(it == 110342)
}
}
private class Board(
val tiles: List<List<Tile>>,
val position: Pos,
val path: List<PathItem>
)
private class Cube(
val facets: Map<Int, List<List<Tile>>>,
val position: PosOnCube,
val path: List<PathItem>
) {
val facetSize = facets[0]!!.size
fun printFacet(id: Int) {
println("Faced $id")
facets[id]!!.forEach { l ->
val s = l.map {
when (it) {
Tile.EMPTY -> ' '
Tile.OPEN -> '.'
Tile.WALL -> '#'
}
}.joinToString("")
println(s)
}
}
}
private sealed class Tile {
object EMPTY : Tile()
object WALL : Tile()
object OPEN : Tile()
}
private data class Pos(
val x: Int, val y: Int, val facing: Facing
)
private data class PosOnCube(
val facedId: Int, val x: Int, val y: Int, val facing: Facing
)
enum class Facing(val passwordValue: Int) {
RIGHT(0), DOWN(1), LEFT(2), UP(3);
fun clockwiseNext(): Facing {
return when (this) {
RIGHT -> DOWN
DOWN -> LEFT
LEFT -> UP
UP -> RIGHT
}
}
fun counterClockwiseNext(): Facing {
return when (this) {
RIGHT -> UP
DOWN -> RIGHT
LEFT -> DOWN
UP -> LEFT
}
}
}
sealed class PathItem {
data class Movement(val numTiles: Int) : PathItem()
data class Rotating(val clockwise: Boolean) : PathItem()
}
private fun part1(input: List<String>): Int {
val board = input.parseInputBoard()
var x = board.position.x
var y = board.position.y
var facing = board.position.facing
board.path.forEach { p ->
when (p) {
is PathItem.Movement -> {
repeat(p.numTiles) {
when (facing) {
Facing.RIGHT -> {
var testX = x + 1
if (testX >= board.tiles[y].size
|| board.tiles[y][testX] == Tile.EMPTY
) {
testX = 0
while (testX < board.tiles[y].size
&& board.tiles[y][testX] == Tile.EMPTY
) {
testX += 1
}
}
if (testX < board.tiles[y].size
&& board.tiles[y][testX] == Tile.OPEN
) {
x = testX
}
}
Facing.DOWN -> {
var testY = y + 1
if (testY >= board.tiles.size
|| board.tiles[testY][x] == Tile.EMPTY
) {
testY = 0
while (testY < board.tiles.size
&& board.tiles[testY][x] == Tile.EMPTY
) {
testY += 1
}
}
if (testY < board.tiles.size
&& board.tiles[testY][x] == Tile.OPEN
) {
y = testY
}
}
Facing.LEFT -> {
var testX = x - 1
if (testX < 0
|| board.tiles[y][testX] == Tile.EMPTY
) {
testX = board.tiles[y].lastIndex
while (testX >= 0
&& board.tiles[y][testX] == Tile.EMPTY
) {
testX -= 1
}
}
if (testX >= 0
&& board.tiles[y][testX] == Tile.OPEN
) {
x = testX
}
}
Facing.UP -> {
var testY = y - 1
if (testY < 0
|| board.tiles[testY][x] == Tile.EMPTY
) {
testY = board.tiles.lastIndex
while (testY >= 0
&& board.tiles[testY][x] == Tile.EMPTY
) {
testY -= 1
}
}
if (testY >= 0
&& board.tiles[testY][x] == Tile.OPEN
) {
y = testY
}
}
}
}
}
is PathItem.Rotating -> {
facing = if (p.clockwise) facing.clockwiseNext() else facing.counterClockwiseNext()
}
}
}
return 1000 * (y + 1) + 4 * (x + 1) + facing.passwordValue
}
private fun part2(input: List<String>): Int {
val cube = input.parseInputBoard().toCube()
var position = cube.position
cube.path.forEach { p ->
when (p) {
is PathItem.Movement -> {
for (i in 0 until p.numTiles) {
val newPosition = cube.getNextPosition(position)
if (cube.facets[newPosition.facedId]!![newPosition.y][newPosition.x] == Tile.OPEN) {
position = newPosition
} else {
break
}
}
}
is PathItem.Rotating -> {
val newFacing = if (p.clockwise) {
position.facing.clockwiseNext()
} else {
position.facing.counterClockwiseNext()
}
position = position.copy(facing = newFacing)
}
}
}
val y = position.y + (position.facedId / 3) * cube.facetSize
val x = position.x + (position.facedId % 3) * cube.facetSize
return 1000 * (y + 1) + 4 * (x + 1) + position.facing.passwordValue
}
private fun Board.toCube(): Cube {
val width = this.tiles[0].size
val height = this.tiles.size
check(width < height)
val facetSize = width / 3
check(
facetSize * 3 == width
&& facetSize * 4 == height
)
val facets: Map<Int, List<List<Tile>>> = (0 until 12).associateWith { facetId ->
val column = facetId % 3
val row = facetId / 3
this.tiles.subList(row * facetSize, (row + 1) * facetSize).map { r ->
r.subList(column * facetSize, (column + 1) * facetSize)
}
}
return Cube(
facets = facets,
position = PosOnCube(1, 0, 0, Facing.RIGHT),
path = this.path
)
}
private fun Cube.getNextPosition(position: PosOnCube): PosOnCube {
fun PosOnCube.next(): PosOnCube {
return when (this.facing) {
Facing.RIGHT -> this.copy(x = this.x + 1)
Facing.DOWN -> this.copy(y = this.y + 1)
Facing.LEFT -> this.copy(x = this.x - 1)
Facing.UP -> this.copy(y = this.y - 1)
}
}
val next = position.next()
if (next.x in 0 until facetSize
&& next.y in 0 until facetSize
) {
return next
}
return getAdjacentPosition(position)
}
private fun Cube.getAdjacentPosition(position: PosOnCube): PosOnCube {
val lastIndex = facetSize - 1
val newPosition = when (position.facedId) {
1 -> {
when (position.facing) {
// edge: x:x, y:y
Facing.RIGHT -> position.copy(
facedId = 2,
x = 0
)
Facing.LEFT -> position.copy(
// edge: x:-x, y:-y
facedId = 6,
x = 0,
y = lastIndex - position.y,
facing = Facing.RIGHT
)
Facing.DOWN -> position.copy(
// edge: x:x, y:y
facedId = 4,
y = 0
)
Facing.UP -> position.copy(
// edge: x:y, y:-x
facedId = 9,
x = 0,
y = position.x,
facing = Facing.RIGHT
)
}
}
2 -> {
when (position.facing) {
Facing.RIGHT -> position.copy(
// edge: x:-x, y:-y
facedId = 7,
x = lastIndex,
y = lastIndex - position.y,
facing = Facing.LEFT
)
Facing.LEFT -> position.copy(
// edge: x:x, y:y
facedId = 1,
x = lastIndex,
)
Facing.DOWN -> position.copy(
// edge: x:y, y:-x
facedId = 4,
y = position.x,
x = lastIndex,
facing = Facing.LEFT
)
Facing.UP -> position.copy(
// edge: x:x, y:y
facedId = 9,
y = lastIndex,
)
}
}
4 -> {
when (position.facing) {
Facing.RIGHT -> position.copy(
// edge: x:-y, y:x
facedId = 2,
y = lastIndex,
x = position.y,
facing = Facing.UP
)
Facing.LEFT -> position.copy(
// edge: x:-y, y:x
facedId = 6,
y = 0,
x = position.y,
facing = Facing.DOWN
)
Facing.DOWN -> position.copy(
// edge: x:x, y:y
facedId = 7,
y = 0,
)
Facing.UP -> position.copy(
// edge: x:x, y:y
facedId = 1,
y = lastIndex,
)
}
}
6 ->
when (position.facing) {
Facing.RIGHT -> position.copy(
// edge: x:x, y:y
facedId = 7,
x = 0,
)
Facing.LEFT -> position.copy(
// edge: x:-x, y:-y
facedId = 1,
x = 0,
y = lastIndex - position.y,
facing = Facing.RIGHT
)
Facing.DOWN -> position.copy(
// edge: x:x, y:y
facedId = 9,
y = 0,
)
Facing.UP -> position.copy(
// edge: x:y, y:-x
facedId = 4,
x = 0,
y = position.x,
facing = Facing.RIGHT
)
}
7 ->
when (position.facing) {
Facing.RIGHT -> position.copy(
// edge: x:-x, y:-y
facedId = 2,
x = lastIndex,
y = lastIndex - position.y,
facing = Facing.LEFT
)
Facing.LEFT -> position.copy(
// edge: x:x, y:y
facedId = 6,
x = lastIndex,
)
Facing.DOWN -> position.copy(
// edge: x:y, y:-x
facedId = 9,
x = lastIndex,
y = position.x,
facing = Facing.LEFT
)
Facing.UP -> position.copy(
// edge: x:x, y:y
facedId = 4,
y = lastIndex,
)
}
9 ->
when (position.facing) {
Facing.RIGHT -> position.copy(
// edge: x:-y, y:x
facedId = 7,
x = position.y,
y = lastIndex,
facing = Facing.UP
)
Facing.LEFT -> position.copy(
// edge: x:-y, y:x
facedId = 1,
x = position.y,
y = 0,
facing = Facing.DOWN
)
Facing.DOWN -> position.copy(
// edge: x:x, y:y
facedId = 2,
y = 0,
)
Facing.UP -> position.copy(
// edge: x:y, y:y
facedId = 6,
y = lastIndex,
)
}
else -> error("Unknown facet $this")
}
return newPosition
}
//private fun validateMovements(input: List<String>) {
// val cube = input.parseInputBoard().toCube()
//
// listOf(1, 2, 4, 6, 7, 9).forEach {
// listOf(
// PosOnCube(it, 5, 0, Facing.UP),
// PosOnCube(it, 5, 49, Facing.DOWN),
// PosOnCube(it, 0, 5, Facing.LEFT),
// PosOnCube(it, 49, 5, Facing.RIGHT)
// ).forEach { p ->
// var pos1 = p
// repeat(4*50) {
// pos1 = cube.getNextPosition(pos1)
// }
// check(p == pos1)
// }
// }
//}
private fun List<String>.parseInputBoard(): Board {
val board = this.dropLast(2)
val movements: String = this.takeLast(1).single()
val tiles: List<MutableList<Tile>> = board.map { l ->
l.map { t ->
when (t) {
' ' -> Tile.EMPTY
'.' -> Tile.OPEN
'#' -> Tile.WALL
else -> error("Unknown tile $t")
}
}.toMutableList()
}
val width = tiles.maxOf { it.size }
tiles.forEach { l ->
if (l.size < width) {
repeat(width - l.size) {
l += Tile.EMPTY
}
}
}
val x = tiles[0].indexOfFirst { it == Tile.OPEN }
val path = buildList {
var i = 0
while (i < movements.length) {
when (movements[i]) {
in '0'..'9' -> {
var end = i
while (end <= movements.lastIndex && movements[end] in '0'..'9') {
end += 1
}
add(PathItem.Movement(movements.substring(i, end).toInt()))
i = end
}
'R' -> {
add(PathItem.Rotating(true))
i += 1
}
'L' -> {
add(PathItem.Rotating(false))
i += 1
}
else -> {
error("Unknown symbol ${movements[i]}")
}
}
}
}
return Board(
tiles = tiles,
position = Pos(x, 0, Facing.RIGHT),
path = path
)
} | 0 | Kotlin | 0 | 0 | 3c6bffd9ac60729f7e26c50f504fb4e08a395a97 | 16,159 | aoc22-kotlin | Apache License 2.0 |
src/Day07.kt | catcutecat | 572,816,768 | false | {"Kotlin": 53001} | import kotlin.system.measureTimeMillis
fun main() {
measureTimeMillis {
Day07.run {
solve1(95437) // 1749646
solve2(24933642) // 1498966
}
}.let { println("Total: $it ms") }
}
object Day07 : Day.LineInput<Day07.Directory, Int>("07") {
class Directory(
val parent: Directory?
) {
val directories: MutableMap<String, Directory> = mutableMapOf()
val files: MutableList<File> = mutableListOf()
var totalSize = 0
fun updateTotalSize() {
val dirSize = directories.values.sumOf {
it.updateTotalSize()
it.totalSize
}
val fileSize = files.sumOf { it.size }
totalSize = dirSize + fileSize
}
fun allSize(): List<Int> = listOf(totalSize) + directories.values.flatMap(Directory::allSize)
}
data class File(val size: Int, val name: String)
override fun parse(input: List<String>) = Directory(null).also { root ->
input.fold(root) { curr, command ->
val (a, b, c) = "$command ".split(" ")
when {
a == "$" && b == "cd" && c == "/" -> root
a == "$" && b == "cd" && c == ".." -> curr.parent!!
a == "$" && b == "cd" -> curr.directories[c]!!
a == "$" && b == "ls" -> curr
a == "dir" -> curr.apply { directories[b] = Directory(curr) }
else -> curr.apply { files.add(File(a.toInt(), b)) }
}
}
}.apply { updateTotalSize() }
override fun part1(data: Directory) = data.allSize().sumOf { if (it <= 100_000) it else 0 }
override fun part2(data: Directory) = (30_000_000 - (70_000_000 - data.totalSize)).let { min ->
data.allSize().minOf { if (it >= min) it else Int.MAX_VALUE }
}
} | 0 | Kotlin | 0 | 2 | fd771ff0fddeb9dcd1f04611559c7f87ac048721 | 1,839 | AdventOfCode2022 | Apache License 2.0 |
calendar/day03/Day3.kt | divgup92 | 573,352,419 | false | {"Kotlin": 15497} | package day03
import Day
import Lines
import kotlin.streams.toList
class Day3 : Day() {
override fun part1(input: Lines): Any {
return input.stream().map { line -> getScore(line) }.toList().sum()
}
private fun getScore(input: String): Int {
val firstHalf = input.substring(0, input.length/2)
val secondHalf = input.substring(input.length/2, input.length)
val commonChar = firstHalf.chars().distinct().filter { c -> secondHalf.contains(c.toChar()) }.findAny()
return mapScore(commonChar.asInt)
}
private fun mapScore(c: Int) = when {
c >= 'a'.code && c <= 'z'.code -> c-'a'.code + 1
c >= 'A'.code && c <= 'Z'.code -> c-'A'.code + 27
else -> 0
}
override fun part2(input: Lines): Any {
var group3 = mutableListOf<String>()
var sum = 0
for(line in input) {
if(group3.size == 3) {
sum += getScoreGroup(group3)
group3 = mutableListOf()
}
group3.add(line)
}
return sum + getScoreGroup(group3)
}
private fun getScoreGroup(group3: List<String>): Int {
val commonChar = group3[0].chars().distinct().filter { c -> group3[1].contains(c.toChar()) && group3[2].contains(c.toChar()) }.findAny()
return mapScore(commonChar.asInt)
}
}
| 0 | Kotlin | 0 | 0 | dcd221197ecb374efa030a7993a0152099409f14 | 1,353 | advent-of-code-2022 | Apache License 2.0 |
src/Day09.kt | fmborghino | 573,233,162 | false | {"Kotlin": 60805} | import kotlin.math.absoluteValue
import kotlin.math.sign
fun main() {
@Suppress("unused")
fun log(message: Any?) {
println(message)
}
fun parse(input: List<String>): List<Pair<Int, Int>> {
val moves: MutableList<Pair<Int, Int>> = mutableListOf()
var x = 0
var y = 0
moves.add(Pair(x, y))
input.forEach { line ->
val d = line[0]
val c = line.drop(2).toInt()
repeat(c) {
when (d) {
'R' -> x++
'L' -> x--
'U' -> y++
'D' -> y--
}
moves.add(Pair(x, y))
}
}
return moves.toList()
}
fun List<Pair<Int, Int>>.follow(): List<Pair<Int, Int>> {
val follows: MutableList<Pair<Int, Int>> = mutableListOf()
var tailX = 0
var tailY = 0
this.forEach {
val (headX, headY) = it
val deltaX = headX - tailX
val deltaY = headY - tailY
when {
// within 1, don't move
deltaX.absoluteValue <= 1 && deltaY.absoluteValue <= 1 -> {}
// left / right move
deltaY == 0 -> tailX += deltaX.sign
deltaX == 0 -> tailY += deltaY.sign
// diagonal
deltaY.absoluteValue == 2 || deltaX.absoluteValue == 2 -> { tailY += deltaY.sign; tailX += deltaX.sign}
}
follows.add(Pair(tailX, tailY))
}
return follows.toList()
}
fun part1(input: List<String>): Int {
return parse(input).follow().toSet().size
}
fun part2(input: List<String>): Int {
return parse(input).follow().follow().follow().follow().follow().follow().follow().follow().follow()
// ... the yalow brick road
.toSet().size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day09_test.txt")
check(part1(testInput) == 13)
check(part2(readInput("Day09_test2.txt")) == 36)
val input = readInput("Day09.txt")
println(part1(input))
check(part1(input) == 6642)
println(part2(input))
check(part2(input) == 2765)
}
| 0 | Kotlin | 0 | 0 | 893cab0651ca0bb3bc8108ec31974654600d2bf1 | 2,271 | aoc2022 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.