path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/Day06.kt | inssein | 573,116,957 | false | {"Kotlin": 47333} | fun main() {
fun naive(input: String, capacity: Int): Int {
return input.windowedSequence(capacity).indexOfFirst {
it.toSet().size == capacity
} + capacity
}
fun trackDuplicate(input: String, capacity: Int): Int {
val duplicateMap = IntArray(26)
var lastDuplicateIndex = 0
for (i in input.indices) {
val key = input[i] - 'a'
val lastSeenIndex = duplicateMap[key]
// track the last time we saw a duplicate
if (lastDuplicateIndex < lastSeenIndex) {
lastDuplicateIndex = lastSeenIndex
}
// end condition
if (i - lastDuplicateIndex >= capacity) {
return i + 1
}
// track duplicate
duplicateMap[key] = i
}
return -1
}
fun part1(input: String): Int {
return trackDuplicate(input, 4)
}
fun part2(input: String): Int {
return trackDuplicate(input, 14)
}
val testInput = readInput("Day06_test")
check(part1(testInput[0]) == 7)
check(part1(testInput[1]) == 5)
check(part1(testInput[2]) == 6)
check(part1(testInput[3]) == 10)
check(part1(testInput[4]) == 11)
check(part2(testInput[0]) == 19)
check(part2(testInput[1]) == 23)
check(part2(testInput[2]) == 23)
check(part2(testInput[3]) == 29)
check(part2(testInput[4]) == 26)
val input = readInput("Day06").first()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 095d8f8e06230ab713d9ffba4cd13b87469f5cd5 | 1,533 | advent-of-code-2022 | Apache License 2.0 |
y2018/src/main/kotlin/adventofcode/y2018/Day07.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2018
import adventofcode.io.AdventSolution
import java.util.*
object Day07 : AdventSolution(2018, 7, "The Sum of Its Parts") {
override fun solvePartOne(input: String): String {
val prerequisites = parse(input)
val open = ('A'..'Z').toSortedSet()
val completed = mutableListOf<Char>()
while (open.isNotEmpty()) {
val newTask = open.first { prerequisites[it].orEmpty().none(open::contains) }
open -= newTask
completed += newTask
}
return completed.joinToString("")
}
override fun solvePartTwo(input: String): Int {
val prerequisites: Map<Char, SortedSet<Char>> = parse(input)
val open = ('A'..'Z').toSortedSet()
val tasksInProgress = mutableMapOf<Char, Int>()
val completed = mutableSetOf<Char>()
var currentTime = 0
while (completed.size < 26) {
//assign new tasks to waiting elves if possible
open
.filter { prerequisites[it].orEmpty().all(completed::contains) }
.take(5 - tasksInProgress.size)
.forEach { newTaskId ->
open -= newTaskId
tasksInProgress[newTaskId] = currentTime + 61 + (newTaskId - 'A')
}
//advance the time to the completion of the next task
currentTime = tasksInProgress.values.minOrNull() ?: currentTime
//move all completed tasks to 'complete'
tasksInProgress.keys
.filter { tasksInProgress[it] == currentTime }
.forEach { completedTaskId ->
tasksInProgress -= completedTaskId
completed += completedTaskId
}
}
return currentTime
}
private fun parse(input: String) = input
.lineSequence()
.map {
val required = it.substringAfter("Step ")[0]
val next = it.substringAfter("before step ")[0]
next to required
}
.groupBy({ it.first }, { it.second })
.mapValues { it.value.toSortedSet() }
}
| 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 2,149 | advent-of-code | MIT License |
src/Day05.kt | kprow | 573,685,824 | false | {"Kotlin": 23005} | fun main() {
fun part1(input: List<String>, stackListLocation: Int): String {
val stack = Stack(input[stackListLocation])
for (i in 0..stackListLocation - 1) {
val row = input[i]
for (x in 1..row.length step 4) {
val stackNum = ((x - 1) / 4) + 1
if (row[x].isLetter()) {
stack.stacks[stackNum] = stack.stacks[stackNum] + row[x]
}
}
}
for (i in stackListLocation + 2 .. input.count() -1 ) {
val moveInput = input[i].replace("move ", "").replace("from ", "").replace("to ", "")
val move = moveInput.split(" ")
val amount = move[0].toInt()
val from = move[1].toInt()
val to = move[2].toInt()
for(char in 0..amount-1) {
stack.stacks[to] = stack.stacks[from]!![char] + stack.stacks[to]!!
}
stack.stacks[from] = stack.stacks[from]!!.removeRange(0, amount)
// println("---")
// println(stack.stacks[1])
// println(stack.stacks[2])
// println(stack.stacks[3])
}
var topOfEachStack = ""
for (current in stack.stackNumbers) {
if (!stack.stacks[current.digitToInt()]!!.isBlank()) {
topOfEachStack += stack.stacks[current.digitToInt()]!![0].toString()
}
}
return topOfEachStack
}
fun part2(input: List<String>, stackListLocation: Int): String {
val stack = Stack(input[stackListLocation])
for (i in 0..stackListLocation - 1) {
val row = input[i]
for (x in 1..row.length step 4) {
val stackNum = ((x - 1) / 4) + 1
if (row[x].isLetter()) {
stack.stacks[stackNum] = stack.stacks[stackNum] + row[x]
}
}
}
for (i in stackListLocation + 2 .. input.count() -1 ) {
val moveInput = input[i].replace("move ", "").replace("from ", "").replace("to ", "")
val move = moveInput.split(" ")
val amount = move[0].toInt()
val from = move[1].toInt()
val to = move[2].toInt()
val rangeToMove = IntRange(0, amount-1)
stack.stacks[to] = stack.stacks[from]!!.substring(rangeToMove) + stack.stacks[to]!!
stack.stacks[from] = stack.stacks[from]!!.removeRange(rangeToMove)
// println("---")
// println(stack.stacks[1])
// println(stack.stacks[2])
// println(stack.stacks[3])
}
var topOfEachStack = ""
for (current in stack.stackNumbers) {
if (!stack.stacks[current.digitToInt()]!!.isBlank()) {
topOfEachStack += stack.stacks[current.digitToInt()]!![0].toString()
}
}
return topOfEachStack
}
val testInput = readInput("Day05_test")
check(part1(testInput, 3) == "CMZ")
val input = readInput("Day05")
println(part1(input, 8))
check(part2(testInput, 3) == "MCD")
println(part2(input, 8))
}
class Stack {
var stackNumbers: String = ""
var stacks = mutableMapOf<Int, String>()
constructor(stackList: String) {
stackNumbers = stackList.filter { it.isDigit() }
for (stack in stackNumbers) {
stacks[stack.digitToInt()] = ""
}
}
}
| 0 | Kotlin | 0 | 0 | 9a1f48d2a49aeac71fa948656ae8c0a32862334c | 3,413 | AdventOfCode2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/WordSearch2.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT
/**
* 212. Word Search II
* @see <a href="https://leetcode.com/problems/word-search-ii/">Source</a>
*/
fun interface WordSearch2 {
operator fun invoke(board: Array<CharArray>, words: Array<String>): List<String>
}
/**
* Backtracking + Trie
*/
class WordSearch2Trie : WordSearch2 {
override fun invoke(board: Array<CharArray>, words: Array<String>): List<String> {
val res: MutableList<String> = ArrayList()
val root: TrieNode = buildTrie(words)
for (i in board.indices) {
for (j in 0 until board[0].size) {
dfs(board, i, j, root, res)
}
}
return res
}
fun dfs(board: Array<CharArray>, i: Int, j: Int, p: TrieNode, res: MutableList<String>) {
var p0 = p
val c = board[i][j]
if (c == '#' || p0.next[c.code - 'a'.code] == null) return
p0 = p0.next[c.code - 'a'.code]!!
if (p0.word != null) {
res.add(p0.word!!)
p0.word = null
}
board[i][j] = '#'
if (i > 0) dfs(board, i - 1, j, p0, res)
if (j > 0) dfs(board, i, j - 1, p0, res)
if (i < board.size - 1) dfs(board, i + 1, j, p0, res)
if (j < board[0].size - 1) dfs(board, i, j + 1, p0, res)
board[i][j] = c
}
private fun buildTrie(words: Array<String>): TrieNode {
val root = TrieNode()
for (w in words) {
var p: TrieNode? = root
for (c in w.toCharArray()) {
val i = c.code - 'a'.code
if (p?.next?.get(i) == null) p?.next?.set(i, TrieNode())
p = p?.next?.get(i)
}
p?.word = w
}
return root
}
class TrieNode {
var next = arrayOfNulls<TrieNode>(ALPHABET_LETTERS_COUNT)
var word: String? = null
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,526 | kotlab | Apache License 2.0 |
src/Day21.kt | Kietyo | 573,293,671 | false | {"Kotlin": 147083} | import java.text.NumberFormat
fun main() {
fun part1(input: List<String>): Unit {
val monkeyMathWorld = mutableMapOf<String, () -> Long>()
input.forEach { line ->
val (monkeyName, calcString) = line.split(": ")
val calcSplit = calcString.split(" ")
when (calcSplit.size) {
1 -> monkeyMathWorld[monkeyName] = { calcSplit[0].toLong() }
3 -> {
val leftCalc = { monkeyMathWorld[calcSplit[0]]!!() }
val rightCalc = { monkeyMathWorld[calcSplit[2]]!!() }
monkeyMathWorld[monkeyName] = when (calcSplit[1]) {
"+" -> { { leftCalc() + rightCalc() } }
"-" -> { { leftCalc() - rightCalc() } }
"*" -> { { leftCalc() * rightCalc() } }
"/" -> { { leftCalc() / rightCalc() } }
else -> TODO()
}
}
}
}
println("root: " + monkeyMathWorld["root"]!!())
}
fun part2(input: List<String>): Unit {
val monkeyMathWorld = mutableMapOf<String, () -> Long>()
input.forEach {
val line = it
val (monkeyName, calcString) = line.split(": ")
val calcSplit = calcString.split(" ")
when (calcSplit.size) {
1 -> monkeyMathWorld[monkeyName] = { calcSplit[0].toLong() }
3 -> {
val leftCalc = { monkeyMathWorld[calcSplit[0]]!!() }
val rightCalc = { monkeyMathWorld[calcSplit[2]]!!() }
monkeyMathWorld[monkeyName] = when (calcSplit[1]) {
"+" -> { { leftCalc() + rightCalc() } }
"-" -> { { leftCalc() - rightCalc() } }
"*" -> { { leftCalc() * rightCalc() } }
"/" -> { { leftCalc() / rightCalc() } }
else -> TODO()
}
}
}
}
val rootLeft = "bjgs"
val rootRight = "tjtt"
var delta = 1000000000
var currComp = monkeyMathWorld[rootLeft]!!().compareTo(monkeyMathWorld[rootRight]!!())
while (true) {
val leftRootCalc = monkeyMathWorld[rootLeft]!!()
val rightRootCalc = monkeyMathWorld[rootRight]!!()
val compareTo = leftRootCalc.compareTo(rightRootCalc)
val humnCalc = monkeyMathWorld["humn"]!!()
println(
"leftRootCalc: ${
NumberFormat.getInstance().format(leftRootCalc)
}, rightRootCalc: ${
NumberFormat.getInstance().format(rightRootCalc)
}, humnCalc: $humnCalc, compareTo: $compareTo, delta: $delta"
)
if (leftRootCalc == rightRootCalc) break
if (currComp != compareTo) {
currComp = compareTo
delta /= 10
}
monkeyMathWorld["humn"] = { humnCalc + (delta * compareTo) }
}
}
val dayString = "day21"
// test if implementation meets criteria from the description, like:
val testInput = readInput("${dayString}_test") // part1(testInput)
// part2(testInput)
val input = readInput("${dayString}_input")
// part1(input) // 3330805295851 too high
// Actually answer is 3330805295850, likely due to integer division rounding.
part2(input)
}
| 0 | Kotlin | 0 | 0 | dd5deef8fa48011aeb3834efec9a0a1826328f2e | 3,503 | advent-of-code-2022-kietyo | Apache License 2.0 |
src/Day20.kt | joy32812 | 573,132,774 | false | {"Kotlin": 62766} | import kotlin.math.abs
fun main() {
fun solve(input: List<String>, repeatTimes: Int, multiplier: Int): Long {
val raw = input.map { it.toLong() * multiplier}
val arr = raw.withIndex().map { "${it.value}_${it.index}" }.toTypedArray()
val posMap = arr.withIndex().associate { it.value to it.index }.toMutableMap()
fun swap(i: Int, j: Int) {
val tmp = arr[i]
arr[i] = arr[j]
arr[j] = tmp
posMap[arr[i]] = i
posMap[arr[j]] = j
}
repeat(repeatTimes) {
for (k in raw.indices) {
val key = "${raw[k]}_${k}"
val steps = (raw[k] % (raw.size - 1)).toInt()
repeat(abs(steps)) {
val i = posMap[key]!!
val diff = if (steps > 0) 1 else -1
val j = (i + diff + raw.size) % raw.size
swap(i, j)
}
}
}
fun getByPos(x: Int): Long {
val index = raw.indexOf(0)
val key = "0_${index}"
var i = (posMap[key]!! + x) % raw.size
return arr[i].split("_")[0].toLong()
}
return getByPos(1000) + getByPos(2000) + getByPos(3000)
}
fun part1(input: List<String>): Long {
return solve(input, 1, 1)
}
fun part2(input: List<String>): Long {
return solve(input, 10, 811589153)
}
println(part1(readInput("data/Day20_test")))
println(part1(readInput("data/Day20")))
println(part2(readInput("data/Day20_test")))
println(part2(readInput("data/Day20")))
} | 0 | Kotlin | 0 | 0 | 5e87958ebb415083801b4d03ceb6465f7ae56002 | 1,434 | aoc-2022-in-kotlin | Apache License 2.0 |
src/utils/OutputFun.kt | ShMPMat | 414,333,726 | false | null | package shmp.utils
import kotlin.math.max
import kotlin.math.pow
/**
* Adds right text to the left text. right text will be lined up with
* consideration to longest line from the left text.
*
* @param guarantiedLength if left fragment is already has equal length of lines.
* @return left and right text merged in one.
*/
fun addToRight(left: String, right: String, guarantiedLength: Boolean): StringBuilder {
if (left.isEmpty())
return StringBuilder(right)
val stringBuilder = StringBuilder()
val lineLength: Int = (left.lines().map { it.length }.maxOrNull() ?: 0) + 4
val linesAmount = max(left.lines().count(), right.lines().count())
val list1 = left.lines() + ((0 until linesAmount - left.lines().size).map { "" })
val list2 = right.lines() + ((0 until linesAmount - right.lines().size).map { "" })
for (i in 0 until linesAmount) {
val ss1 = list1[i]
val ss2 = list2[i]
stringBuilder
.append(ss1)
.append(" ".repeat(if (guarantiedLength) 4 else lineLength - ss1.length))
.append(ss2)
if (i != linesAmount - 1)
stringBuilder.append("\n")
}
return stringBuilder
}
fun addToRight(left: StringBuilder, right: StringBuilder, guarantiedLength: Boolean) =
addToRight(left.toString(), right.toString(), guarantiedLength)
/**
* Edits text via carrying lines which are longer than size.
* @param text text which will be edited.
* @param size maximal acceptable length of a line.
* @return edited text, each line in it is not longer than size. Words can be cut in the middle.
*/
fun chompToSize(text: String, size: Int): StringBuilder {
val stringBuilder = StringBuilder()
for (_line in text.lines()) {
var line = _line
while (line.isNotEmpty())
if (size >= line.length) {
stringBuilder.append(line)
break
} else {
var part = line.substring(0, size)
if (part.lastIndexOf(" ") != -1) {
line = line.substring(part.lastIndexOf(" ") + 1)
part = (if (part.lastIndexOf(" ") == 0)
part.substring(1)
else
part.substring(0, part.lastIndexOf(" ")))
} else
line = line.substring(size)
stringBuilder.append(part).append("\n")
}
stringBuilder.append("\n")
}
return stringBuilder
}
/**
* Edits text via adding lines after size + 1 recursively to the right.
* @param text text which will be modified.
* @param size maximal acceptable number of lines.
* @return edited text, has no more than size lines, greater lines added to the right.
*/
fun chompToLines(text: String, size: Int): StringBuilder {
val prefix = text.lines().take(size).joinToString("\n")
val postfix = text.lines().drop(size).joinToString("\n")
if (postfix == "")
return java.lang.StringBuilder(prefix)
return addToRight(
prefix,
chompToLines(postfix, size).toString(),
false
)
}
fun chompToLines(text: StringBuilder, size: Int) = chompToLines(text.toString(), size)
fun getTruncated(t: Double, signs: Int) = 10.0.pow(signs).toInt().let { p ->
(t * p).toInt().toDouble() / p
}.toString()
fun <E> E.addLinePrefix(prefix: String = " ") = this.toString().lines()
.joinToString("\n") { prefix + it }
| 0 | Kotlin | 0 | 0 | c5368fa0c9786fe5c957b2e5edf706dd7ebf8014 | 3,495 | GenerationUtils | MIT License |
src/main/kotlin/g0901_1000/s0907_sum_of_subarray_minimums/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0901_1000.s0907_sum_of_subarray_minimums
// #Medium #Array #Dynamic_Programming #Stack #Monotonic_Stack
// #2023_04_14_Time_341_ms_(100.00%)_Space_44.3_MB_(100.00%)
class Solution {
private fun calculateRight(i: Int, start: Int, right: IntArray, arr: IntArray, len: Int): Int {
if (start >= len) {
return 0
}
return if (arr[start] < arr[i]) {
0
} else (1 + right[start] + calculateRight(i, start + right[start] + 1, right, arr, len)) % MOD
}
private fun calculateLeft(i: Int, start: Int, left: IntArray, arr: IntArray, len: Int): Int {
if (start < 0) {
return 0
}
return if (arr[start] <= arr[i]) {
0
} else (1 + left[start] + calculateLeft(i, start - left[start] - 1, left, arr, len)) % MOD
}
fun sumSubarrayMins(arr: IntArray): Int {
val len = arr.size
val right = IntArray(len)
val left = IntArray(len)
right[len - 1] = 0
for (i in len - 2 downTo 0) {
right[i] = calculateRight(i, i + 1, right, arr, len)
}
left[0] = 0
for (i in 1 until len) {
left[i] = calculateLeft(i, i - 1, left, arr, len)
}
var answer = 0
for (i in 0 until len) {
val model: Long = 1000000007
answer += ((1 + left[i]) * (1 + right[i]).toLong() % model * arr[i] % model).toInt()
answer %= MOD
}
return answer
}
companion object {
private const val MOD = 1000000007
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,573 | LeetCode-in-Kotlin | MIT License |
src/Day09.kt | pimtegelaar | 572,939,409 | false | {"Kotlin": 24985} | fun main() {
data class Knot(var x: Int, var y: Int, val follower: Knot? = null) {
val tail: Knot = follower?.tail ?: this
fun move(direction: String) {
when (direction) {
"R" -> x++
"L" -> x--
"U" -> y--
"D" -> y++
}
follower?.follow(this)
}
fun followDiagonalY(other: Knot) {
if (y - other.y > 0) {
y--
} else if (other.y - y > 0) {
y++
}
}
fun followDiagonalX(other: Knot) {
if (x - other.x > 0) {
x--
} else if (other.x - x > 0) {
x++
}
}
fun follow(other: Knot) {
when {
x - other.x > 1 -> {
x--
followDiagonalY(other)
}
other.x - x > 1 -> {
x++
followDiagonalY(other)
}
y - other.y > 1 -> {
y--
followDiagonalX(other)
}
other.y - y > 1 -> {
y++
followDiagonalX(other)
}
}
follower?.follow(this)
}
}
fun move(input: List<String>, head: Knot): Int {
val tail = head.tail
val visited = mutableSetOf(Pair(tail.x, tail.y))
input.forEach {
val (direction, steps) = it.split(" ")
for (i in 1..steps.toInt()) {
head.move(direction)
visited.add(Pair(tail.x, tail.y))
}
}
return visited.size
}
fun rope(length: Int, startX: Int, startY: Int): Knot {
var current = Knot(startX, startY)
repeat(length - 1) {
current = Knot(startX, startY, follower = current)
}
return current
}
fun part1(input: List<String>) = move(input, rope(length = 2, startX = 30, startY = 30))
fun part2(input: List<String>) = move(input, rope(length = 10, startX = 30, startY = 30))
val testInput = readInput("Day09_test")
val input = readInput("Day09")
val part1 = part1(testInput)
check(part1 == 13) { part1 }
println(part1(input))
val part2 = part2(testInput)
check(part2 == 1) { part2 }
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 16ac3580cafa74140530667413900640b80dcf35 | 2,444 | aoc-2022 | Apache License 2.0 |
src/Day01.kt | winnerwinter | 573,917,144 | false | {"Kotlin": 20685} | fun main() {
fun separateElves(input: List<String>): List<List<Int>> {
val elfSeparators = input.mapIndexedNotNull { i, str -> i.takeIf { str.isEmpty() } }
val elfSeparatorsWithEnds = listOf(0, *elfSeparators.toTypedArray(), input.size)
val elfIndices = elfSeparatorsWithEnds.windowed(2)
return elfIndices.map { (low, high) ->
input.subList(low, high).filter { it.isNotEmpty() }.map { it.toInt() }
}
}
fun returnMaxCalories(input: List<String>, topN: Int): Int {
val caloriesPerItem = separateElves(input)
val calorieTotals = caloriesPerItem.map { it.sum() }
return calorieTotals.sortedDescending().take(topN).sum()
}
fun part1(): Int {
val testInput = readInput("Day01_test")
val test_ans = returnMaxCalories(testInput, 1)
check(test_ans == 24000)
val input = readInput("Day01")
val ans = returnMaxCalories(input, 1)
return ans
}
fun part2(): Int {
val testInput = readInput("Day01_test")
val test_ans = returnMaxCalories(testInput, 3)
check(test_ans == 45000)
val input = readInput("Day01")
val ans = returnMaxCalories(input, 3)
return ans
}
println(part1())
println(part2())
}
| 0 | Kotlin | 0 | 0 | a019e5006998224748bcafc1c07011cc1f02aa50 | 1,301 | advent-of-code-22 | Apache License 2.0 |
src/main/kotlin/dec23/Main.kt | dladukedev | 318,188,745 | false | null | package dec23
import kotlin.collections.HashMap
class CupList<T>(input: List<T>) {
val map = input.mapIndexed { index, self ->
val next = if(index+1 == input.count()) {
0
} else {
index+1
}
self to input[next]
}.toMap() as HashMap
data class Node<T> (
val self: T,
val next: T
)
operator fun get(value: T): Node<T> {
val next = map[value] ?: throw Exception("Invalid State, List Missing Link - $value not in $map")
return Node(value, next)
}
fun removeCups(removeAfter: T, count: Int): List<T> {
val removed = mutableListOf<T>()
var pointer = this[removeAfter].next
while(removed.count() < count) {
val toRemove = pointer
removed.add(pointer)
pointer = this[pointer].next
map.remove(toRemove)
}
map[removeAfter] = pointer
return removed
}
fun insertCups(insertAfter: T, cups: List<T>) {
val end = this[insertAfter].next
map[insertAfter] = cups.first()
cups.forEachIndexed { index, cup ->
when(index) {
cups.count() - 1 -> {
map[cup] = end
}
else -> {
map[cup] = cups[index + 1]
}
}
}
}
}
data class CupGameState(
val currentCup: Int,
val cups: CupList<Int>
) {
constructor(input: List<Int>): this(input.first(), CupList(input))
}
fun findDestination(currentCup: Int, removedCups: List<Int>, max: Int): Int {
val distanceFromCurrentCup = (1 until currentCup).find {
removedCups.all { cup -> cup != currentCup - it }
}
return if(distanceFromCurrentCup != null) {
currentCup - distanceFromCurrentCup
} else {
val distanceFromMax = (0..removedCups.count()).first {
!removedCups.contains(max - it)
}
return max - distanceFromMax
}
}
fun getNextCurrentCup(currentCup: Int, cupList: CupList<Int>): Int {
return cupList[currentCup].next
}
fun playGame(state: CupGameState, max: Int): CupGameState {
val removedCups = state.cups.removeCups(state.currentCup, 3)
val destination = findDestination(state.currentCup, removedCups, max)
state.cups.insertCups(destination, removedCups)
val nextCup = getNextCurrentCup(state.currentCup, state.cups)
return state.copy(currentCup = nextCup)
}
fun getResultPart1(cupList: CupList<Int>): String {
var result = ""
var next = cupList[1].next
while(next != 1) {
result += next
next = cupList[next].next
}
return result
}
fun getResultPart2(cupList: CupList<Int>): Long {
val nextCup = cupList[1].next
val twoOver = cupList[nextCup].next
return nextCup.toLong() * twoOver.toLong()
}
fun main() {
println("------------ PART 1 ------------")
val initialGameState = CupGameState(input)
val finalState = (1..100).fold(initialGameState) { acc, i ->
playGame(acc, 9)
}
val result = getResultPart1(finalState.cups)
println("result: $result")
println("------------ PART 2 ------------")
val updatedInput = input + (input.max()!!+1..1_000_000)
val updatedInitialState = CupGameState(updatedInput)
val finalUpdatedState = (1..10_000_000).fold(updatedInitialState) { acc, i ->
playGame(acc, 1_000_000)
}
val result2 = getResultPart2(finalUpdatedState.cups)
println("result: $result2")
} | 0 | Kotlin | 0 | 0 | d4591312ddd1586dec6acecd285ac311db176f45 | 3,540 | advent-of-code-2020 | MIT License |
src/day17/day17.kt | kacperhreniak | 572,835,614 | false | {"Kotlin": 85244} | package day17
import readInput
private const val WIDTH = 7
private const val COL_INDEX = 2
private const val HEIGHT_OFFSET = 4
private enum class Rock(val field: Array<Pair<Int, Int>>) {
HORIZONTAL_LINE(field = arrayOf(Pair(0, 0), Pair(0, 1), Pair(0, 2), Pair(0, 3))),
CROSS(field = arrayOf(Pair(0, 1), Pair(1, 0), Pair(1, 1), Pair(1, 2), Pair(2, 1))),
L_SHAPE(field = arrayOf(Pair(0, 0), Pair(0, 1), Pair(0, 2), Pair(1, 2), Pair(2, 2))),
VERTICAL_LINE(field = arrayOf(Pair(0, 0), Pair(1, 0), Pair(2, 0), Pair(3, 0))),
SQUARE(field = arrayOf(Pair(0, 0), Pair(0, 1), Pair(1, 0), Pair(1, 1)));
fun next(): Rock = values()[(ordinal + 1) % values().size]
}
private fun Pair<Int, Int>.fall() = copy(first = first - 1)
private fun Pair<Int, Int>.applyJet(direction: Char) = when (direction) {
'>' -> copy(second = second + 1)
'<' -> copy(second = second - 1)
else -> throw IllegalArgumentException()
}
private fun game(
jets: String,
startRock: Rock = Rock.HORIZONTAL_LINE,
limit: Int,
): Int {
var jetIndex = 0
val cave = HashSet<Pair<Int, Int>>()
var rock = startRock
fun startPosition(): Pair<Int, Int> {
val row = cave.maxOfOrNull { it.first } ?: 0
return Pair(row + HEIGHT_OFFSET, COL_INDEX)
}
fun canMove(current: Pair<Int, Int>, rock: Rock, direction: Char): Boolean {
val items = rock.field.map {
Pair(
first = it.first + current.first,
second = it.second + current.second
)
}
return when (direction) {
'<' -> items.minOf { it.second } > 0 && items.none { cave.contains(it.copy(second = it.second - 1)) }
'>' -> items.maxOf { it.second } < WIDTH - 1 && items.none { cave.contains(it.copy(second = it.second + 1)) }
else -> throw IllegalArgumentException()
}
}
fun canFall(current: Pair<Int, Int>, rock: Rock): Boolean {
return current.first > 1 && rock.field.map {
Pair(
first = current.first + it.first - 1,
second = current.second + it.second
)
}.none { cave.contains(it) }
}
fun singleRound(): Pair<Int, Int> {
var position = startPosition()
while (true) {
val jet = jets[jetIndex % jets.length]
if (canMove(position, rock, jet)) {
position = position.applyJet(jet)
}
jetIndex++
if (canFall(position, rock).not()) {
return position
}
position = position.fall()
}
}
fun Pair<Int, Int>.updateCave(rock: Rock) {
rock.field.map { copy(first = first + it.first, second = second + it.second) }
.forEach { cave.add(it) }
}
repeat(limit) {
singleRound().updateCave(rock)
rock = rock.next()
}
return cave.maxOf { it.first }
}
private fun part1(input: List<String>): Int {
val rocks = 2022
return game(
jets = input[0],
limit = rocks
)
}
private fun part2(input: List<String>): Long {
val limit = 1000000000000L
val startPoint = 2024
val cycleCount = 1705
val cycleHeight = 2582
val allCycleHeight = ((limit - startPoint) / cycleCount) * cycleHeight
val newRocksLimit = startPoint + (limit - startPoint) % cycleCount
return allCycleHeight + game(jets = input[0], limit = newRocksLimit.toInt())
}
fun main() {
val input = readInput("day17/input")
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
/* Magic numbers
How I found a these magic numbers?
I decided to store difference between heights in adjacent columns with information about current rock type and jet index, for an instance, `SQUARE_1919_022-500`
to find out startPoint for cycle. I took first key and re-run code to find all indexes when cycles begin.
For my input, the cycle starts for rock: `2024`, cycle is created by `1705` incoming rocks, and each cycle increases height by `2582`.
Part of the code used to find cycles\
fun createKey(): String {
val temp = IntArray(WIDTH)
repeat(WIDTH) { col ->
temp[col] = cave.filter { it.second == col }.maxOfOrNull { it.first } ?: 0
}
var result = "${rock}_${jetIndex % jets.length}_"
for (index in 1 until WIDTH) {
result += temp[index] - temp[index - 1]
}
return result
}
val cache = hashSetOf<String>()
repeat(limit) {
singleRound().updateCave(rock)
val key = createKey()
if (cache.contains(key) && key == "SQUARE_1919_022-500") {
println("$rock, $it, $key, ${cave.maxOf { it.first }}")
} else {
cache.add(key)
}
rock = rock.next()
}
*/ | 0 | Kotlin | 1 | 0 | 03368ffeffa7690677c3099ec84f1c512e2f96eb | 4,853 | aoc-2022 | Apache License 2.0 |
src/Day18.kt | mrugacz95 | 572,881,300 | false | {"Kotlin": 102751} | import java.util.LinkedList
private val neighbours = listOf(
Vec3(1, 0, 0),
Vec3(-1, 0, 0),
Vec3(0, 1, 0),
Vec3(0, -1, 0),
Vec3(0, 0, 1),
Vec3(0, 0, -1),
)
private fun vectorInRange(vector: Vec3, space: List<List<List<Boolean>>>): Boolean {
return vector.z in space.indices &&
vector.y in space[vector.z].indices &&
vector.x in space[vector.z][vector.y].indices
}
fun main() {
fun List<String>.parse(): List<Vec3> {
return map { line ->
val (z, y, x) = line.split(",").map { it.toInt() }
Vec3(x, y, z)
}.sorted()
}
fun part1(input: List<String>): Int {
val vectors = input.parse()
var visibleSides = 0
for (vec in vectors) {
var sides = 6
for (other in vectors) {
if (vec.dist(other) == 1) {
sides -= 1
}
}
visibleSides += sides
}
return visibleSides
}
fun BFS3d(space: List<List<List<Boolean>>>): Set<Vec3> {
val start = Vec3(0, 0, 0)
val queue = LinkedList<Vec3>()
queue.add(start)
val visited = mutableSetOf<Vec3>()
while (!queue.isEmpty()) {
val current = queue.pop()
if (current in visited) continue
visited.add(current)
for (neighbour in neighbours) {
val n = current + neighbour
if (vectorInRange(n, space) &&
!space[n.z][n.y][n.x]
) {
queue.add(n)
}
}
}
return visited
}
fun printSpace(space: List<List<List<Boolean>>>) {
println()
for (z in space.indices) {
print(" ")
for (x in space.first().first().indices) {
print(x)
}
println()
for (y in space[z].indices) {
print("$y ")
for (x in space[z][y].indices) {
print(if (space[z][y][x]) "#" else ".")
}
println()
}
println()
}
println()
}
fun part2(input: List<String>, debug: Boolean = false): Int {
val vectors = input.parse()
val maxX = vectors.maxBy { it.x }.x + 1
val maxY = vectors.maxBy { it.y }.y + 1
val maxZ = vectors.maxBy { it.z }.z + 1
val space = List(maxZ) {
List(maxY) {
MutableList(maxX) { false }
}
}
for (v in vectors) {
space[v.z][v.y][v.x] = true
}
if (debug) printSpace(space)
val visited = BFS3d(space)
for (z in space.indices) {
for (y in space.first().indices) {
for (x in space.first().first().indices) {
space[z][y][x] = Vec3(z, y, x) !in visited
}
}
}
if (debug) printSpace(space)
var visibleSides = 0
for (z in space.indices) {
for (y in space.first().indices) {
for (x in space.first().first().indices) {
for (n in neighbours) {
if (space[z][y][x]) {
val other = Vec3(z + n.z, y + n.y, x + n.x)
if (vectorInRange(other, space)) {
if (!space[other.z][other.y][other.x]) {
visibleSides += 1
}
} else {
visibleSides += 1
}
}
}
}
}
}
return visibleSides
}
val testInput = readInput("Day18_test")
val input = readInput("Day18")
assert(part1(testInput), 64)
println(part1(input))
assert(part2(testInput, debug = true), 58)
println(part2(input))
}
// Time: 01:18 | 0 | Kotlin | 0 | 0 | 29aa4f978f6507b182cb6697a0a2896292c83584 | 4,037 | advent-of-code-2022 | Apache License 2.0 |
src/Day10.kt | achugr | 573,234,224 | false | null | import kotlin.math.abs
fun main() {
fun getOperationPerCycle(input: List<String>) = input.flatMap {
when {
it.startsWith("noop") -> listOf(0)
it.startsWith("addx") -> listOf(0, it.replace("addx", "").trim().toInt())
else -> throw IllegalArgumentException("Unexpected input")
}
}
.fold(mutableListOf(Pair(1, 1))) { acc, value ->
val previous = acc.last()
acc.add(Pair(previous.first + 1, previous.second + value))
acc
}
fun part1(input: List<String>): Int {
return getOperationPerCycle(input)
.filter {
it.first in setOf(20, 60, 100, 140, 180, 220)
}
.map {
it.first * it.second
}
.sum()
}
fun part2(input: List<String>): String {
return getOperationPerCycle(input)
.windowed(40, 40)
.joinToString(separator = "\n") { window ->
window
.map { it.second }
.mapIndexed { idx, value ->
if (idx in (value - 1..value + 1)) {
"#"
} else {
"."
}
}
.joinToString(separator = "")
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10")
println(part1(testInput))
println(part2(testInput))
}
| 0 | Kotlin | 0 | 0 | d91bda244d7025488bff9fc51ca2653eb6a467ee | 1,544 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/aoc2019/day03_crossed_wires/CrossedWires.kt | barneyb | 425,532,798 | false | {"Kotlin": 238776, "Shell": 3825, "Java": 567} | package aoc2019.day03_crossed_wires
import geom2d.Dir
import geom2d.Point
import geom2d.toDir
fun main() {
util.solve(1084, ::partOne)
util.solve(9240, ::partTwo)
}
data class Step(val dir: Dir, val n: Long)
private fun String.toStep() =
Step(
this.first().toDir(),
this.substring(1).toLong()
)
private fun String.toSteps() =
this.trim()
.split(",")
.map(String::toStep)
private fun walkForPositionsAndDistance(steps: List<Step>): Map<Point, Long> {
// deliberately not including origin, even though the wire starts there,
// as the theme is "crossed wires" and the shared origin appears like a
// cross, even though it isn't. So just ignore it here. Fingers crossed.
val points = mutableMapOf<Point, Long>()
var distance = 0L
steps.fold(Point.ORIGIN) { base, s ->
(0 until s.n).fold(base) { curr, _ ->
val next = curr.step(s.dir)
points.putIfAbsent(next, ++distance)
next
}
}
return points
}
fun partOne(input: String): Long {
val (a, b) = input
.lines()
.map(String::toSteps)
.map(::walkForPositionsAndDistance)
return a.keys.intersect(b.keys)
.minOf(Point::manhattanDistance)
}
fun partTwo(input: String): Long {
val (a, b) = input
.lines()
.map(String::toSteps)
.map(::walkForPositionsAndDistance)
return a.keys.intersect(b.keys)
.minOf { a[it]!! + b[it]!! }
}
| 0 | Kotlin | 0 | 0 | a8d52412772750c5e7d2e2e018f3a82354e8b1c3 | 1,489 | aoc-2021 | MIT License |
src/main/kotlin/treesandgraphs/LongestIncreasingPathInMatrix.kt | e-freiman | 471,473,372 | false | {"Kotlin": 78010} | package treesandgraphs
private var memo: Array<IntArray>? = null
private fun dfs(matrix: Array<IntArray>, i: Int, j: Int): Int {
if (memo!![i][j] != -1) {
return memo!![i][j]
}
var maxLength = 0
if (i > 0 && matrix[i - 1][j] > matrix[i][j])
maxLength = maxOf(maxLength, dfs(matrix, i - 1, j))
if (j > 0 && matrix[i][j - 1] > matrix[i][j])
maxLength = maxOf(maxLength, dfs(matrix, i, j - 1))
if (i < matrix.lastIndex && matrix[i + 1][j] > matrix[i][j])
maxLength = maxOf(maxLength, dfs(matrix, i + 1, j))
if (j < matrix[i].lastIndex && matrix[i][j + 1] > matrix[i][j])
maxLength = maxOf(maxLength, dfs(matrix, i, j + 1))
memo!![i][j] = maxLength + 1
return maxLength + 1
}
fun longestIncreasingPath(matrix: Array<IntArray>): Int {
memo = Array<IntArray>(matrix.size) { IntArray(matrix[it].size) { -1 } }
var maxLength = 0
for (i in matrix.indices) {
for (j in matrix[i].indices) {
maxLength = maxOf(maxLength, dfs(matrix, i, j))
}
}
return maxLength
}
| 0 | Kotlin | 0 | 0 | fab7f275fbbafeeb79c520622995216f6c7d8642 | 1,086 | LeetcodeGoogleInterview | Apache License 2.0 |
src/main/kotlin/codes/jakob/aoc/solution/Day04.kt | The-Self-Taught-Software-Engineer | 433,875,929 | false | {"Kotlin": 56277} | package codes.jakob.aoc.solution
object Day04 : Solution() {
override fun solvePart1(input: String): Any {
val lines: List<String> = input.split("\n\n")
val numberDrawer: ListIterator<Int> = lines.first().split(",").map { it.toInt() }.listIterator()
val boards: Collection<BingoBoard> = parseBoards(lines.drop(1))
while (numberDrawer.hasNext()) {
val drawnNumber: Int = numberDrawer.next()
val winnerGrouping: Map<Boolean, List<BingoBoard>> = boards.groupBy { it.markNumber(drawnNumber) }
if (winnerGrouping.containsKey(true)) {
val winnerGroup: List<BingoBoard> = winnerGrouping[true]!!
require(winnerGroup.count() == 1) { "Expected only a single winner board" }
val winnerBoard: BingoBoard = winnerGroup.first()
val allUnmarkedNumbers: Collection<Int> = winnerBoard.getAllUnmarkedNumbers()
return allUnmarkedNumbers.sum() * drawnNumber
}
}
throw IllegalStateException("No winning board was found")
}
override fun solvePart2(input: String): Any {
val lines: List<String> = input.split("\n\n")
val numberDrawer: ListIterator<Int> = lines.first().split(",").map { it.toInt() }.listIterator()
val boards: MutableList<BingoBoard> = parseBoards(lines.drop(1)).toMutableList()
while (numberDrawer.hasNext()) {
val drawnNumber: Int = numberDrawer.next()
val winnerGrouping: Map<Boolean, List<BingoBoard>> = boards.groupBy { it.markNumber(drawnNumber) }
if (winnerGrouping.containsKey(true)) {
val winnerGroup: List<BingoBoard> = winnerGrouping[true]!!
boards.removeAll(winnerGroup)
if (boards.isEmpty()) {
val lastBoardToWin: BingoBoard = winnerGroup.first()
val allUnmarkedNumbers: Collection<Int> = lastBoardToWin.getAllUnmarkedNumbers()
return allUnmarkedNumbers.sum() * drawnNumber
}
}
}
throw IllegalStateException("No last winning board was found")
}
private fun parseBoards(boards: List<String>): Collection<BingoBoard> {
return boards.map { board ->
BingoBoard(
board.split("\n").map { row ->
row.split(" ").filter { it.isNotBlank() }.map { it.toInt() }
}
)
}
}
class BingoBoard(grid: List<List<Int>>) {
private val board: List<List<Cell>> = grid.map { row -> row.map { Cell(it) } }
private val transposedBoard: List<List<Cell>> = board.transpose()
private val numbersMap: Map<Int, Cell> = board.flatten().associateBy { it.value }
/**
* Returns if the given [value] is in any [Cell] on the [BingoBoard].
*/
operator fun contains(value: Int): Boolean = numbersMap.containsKey(value)
/**
* Marks the given [number] if it exists on the board.
*
* @return A boolean signifying if the [BingoBoard] won.
*/
fun markNumber(number: Int): Boolean {
if (number !in this) {
return false
}
numbersMap[number]!!.mark()
return checkIfWon()
}
fun getAllUnmarkedNumbers(): Collection<Int> {
return board.flatten().filterNot { it.isMarked }.map { it.value }
}
/**
* Checks if there is either a row or a column on the board that has all marked numbers.
* Note that this method can short-circuit in terms of both checking within a row or column, and between them.
*/
private fun checkIfWon(): Boolean {
return (board.asSequence().map { row -> row.all { it.isMarked } }.any { it }
|| transposedBoard.asSequence().map { column -> column.all { it.isMarked } }.any { it })
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as BingoBoard
if (board != other.board) return false
return true
}
override fun hashCode(): Int {
return board.hashCode()
}
private data class Cell(
val value: Int,
var isMarked: Boolean = false,
) {
fun mark() {
isMarked = true
}
}
}
}
fun main() {
Day04.solve()
}
| 0 | Kotlin | 0 | 6 | d4cfb3479bf47192b6ddb9a76b0fe8aa10c0e46c | 4,584 | advent-of-code-2021 | MIT License |
src/Day11.kt | andrikeev | 574,393,673 | false | {"Kotlin": 70541, "Python": 18310, "HTML": 5558} | fun main() {
fun List<String>.parseMonkeys(): List<Monkey> {
return plus("").chunked(7).map { strings ->
Monkey(
items = strings[1]
.substringAfter("Starting items: ")
.split(", ")
.map(String::toLong)
.toMutableList(),
operation = MonkeyOp.parse(strings[2]),
test = MonkeyTest.parse(strings.subList(3, 6)),
)
}
}
fun part1(input: List<String>): Int {
val monkeys = input.parseMonkeys()
repeat(20) {
monkeys.forEach { monkey ->
monkey.items.apply {
forEach { item ->
val newWorryLevel = monkey.operation(item) / 3
val direction = monkey.test(newWorryLevel)
monkey.counter++
monkeys[direction].items.add(newWorryLevel)
}
clear()
}
}
}
return monkeys
.sortedByDescending(Monkey::counter)
.take(2)
.map(Monkey::counter)
.let { (first, second) -> first * second }
}
fun part2(input: List<String>): Long {
val monkeys = input.parseMonkeys()
val modulo = monkeys.fold(1) { acc, monkey -> acc * monkey.test.modulo }
repeat(10000) {
monkeys.forEach { monkey ->
monkey.items.apply {
forEach { item ->
val newWorryLevel = monkey.operation(item) % modulo
val direction = monkey.test(newWorryLevel)
monkey.counter++
monkeys[direction].items.add(newWorryLevel)
}
clear()
}
}
}
return monkeys
.sortedByDescending(Monkey::counter)
.take(2)
.map(Monkey::counter)
.let { (first, second) -> first.toLong() * second }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test")
check(part1(testInput).also { println("part1 test: $it") } == 10605)
check(part2(testInput).also { println("part2 test: $it") } == 2713310158)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
private class Monkey(
val items: MutableList<Long>,
val operation: MonkeyOp,
val test: MonkeyTest,
var counter: Int = 0,
)
private sealed interface MonkeyOp {
operator fun invoke(worryLevel: Long): Long
class Add(private val addition: Int) : MonkeyOp {
override fun invoke(worryLevel: Long) = worryLevel + addition
companion object {
val regex = Regex("new = old [+] (\\d+)")
}
}
class Multiply(private val multiplyer: Int) : MonkeyOp {
override fun invoke(worryLevel: Long) = worryLevel * multiplyer
companion object {
val regex = Regex("new = old [*] (\\d+)")
}
}
object Square : MonkeyOp {
override fun invoke(worryLevel: Long) = worryLevel * worryLevel
val regex = Regex("new = old [*] old")
}
companion object {
fun parse(input: String): MonkeyOp {
val findAdd = Add.regex.find(input)
val findMultiply = Multiply.regex.find(input)
val findSquare = Square.regex.find(input)
return when {
findAdd != null -> Add(findAdd.groups[1]!!.value.toInt())
findMultiply != null -> Multiply(findMultiply.groups[1]!!.value.toInt())
findSquare != null -> Square
else -> error("not known operation: $input")
}
}
}
}
private class MonkeyTest(
val modulo: Int,
private val positiveResult: Int,
private val negativeResult: Int,
) {
operator fun invoke(worryLevel: Long): Int = if (worryLevel % modulo == 0L) {
positiveResult
} else {
negativeResult
}
companion object {
fun parse(input: List<String>): MonkeyTest {
return MonkeyTest(
modulo = input[0].split(" ").last().toInt(),
positiveResult = input[1].split(" ").last().toInt(),
negativeResult = input[2].split(" ").last().toInt(),
)
}
}
} | 0 | Kotlin | 0 | 1 | 1aedc6c61407a28e0abcad86e2fdfe0b41add139 | 4,450 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/g0301_0400/s0327_count_of_range_sum/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0301_0400.s0327_count_of_range_sum
// #Hard #Array #Binary_Search #Ordered_Set #Divide_and_Conquer #Segment_Tree #Binary_Indexed_Tree
// #Merge_Sort #2022_11_12_Time_638_ms_(100.00%)_Space_63.6_MB_(25.00%)
class Solution {
fun countRangeSum(nums: IntArray, lower: Int, upper: Int): Int {
val n = nums.size
val sums = LongArray(n + 1)
for (i in 0 until n) {
sums[i + 1] = sums[i] + nums[i]
}
return countWhileMergeSort(sums, 0, n + 1, lower, upper)
}
private fun countWhileMergeSort(sums: LongArray, start: Int, end: Int, lower: Int, upper: Int): Int {
if (end - start <= 1) {
return 0
}
val mid = (start + end) / 2
var count = (
countWhileMergeSort(sums, start, mid, lower, upper) +
countWhileMergeSort(sums, mid, end, lower, upper)
)
var j = mid
var k = mid
var t = mid
val cache = LongArray(end - start)
var r = 0
for (i in start until mid) {
while (k < end && sums[k] - sums[i] < lower) {
k++
}
while (j < end && sums[j] - sums[i] <= upper) {
j++
}
while (t < end && sums[t] < sums[i]) {
cache[r++] = sums[t++]
}
cache[r] = sums[i]
count += j - k
r++
}
System.arraycopy(cache, 0, sums, start, t - start)
return count
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,516 | LeetCode-in-Kotlin | MIT License |
dcp_kotlin/src/main/kotlin/dcp/day229/day229.kt | sraaphorst | 182,330,159 | false | {"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315} | package dcp.day229
// day229.kt
// By <NAME>, 2019.
import java.util.LinkedList
import kotlin.math.min
typealias ID = Int
typealias Moves = Int
typealias Edges = Map<ID, Moves>
// Snakes and ladders are both just different forms of transporters.
typealias Transporters = Map<ID, ID>
data class Node(val id: ID, val edges: Edges)
// Snakes and ladders are equivalent: they just take you in different directions towards the end of the board.
fun snakesAndLadders(size: Int, transporters: Transporters): Int {
// Create the board.
val numNodes = size * size
val board = (0 until numNodes).map {id ->
// First determine the edges. If there is a snake here, there is only one edge.
val edges: Edges
val teleporter = transporters[id]
edges = if (teleporter != null) {
mapOf(teleporter to 0)
} else {
(1..6).filter { id + it < numNodes }.map { id + it to 1 }.toMap()
}
Node(id, edges)
}
// Now we do a BFS on the board.
val visited = (0 until numNodes).map{false}.toMutableList()
val shortestDistance = (0 until numNodes).map{-1}.toMutableList()
shortestDistance[0] = 0
val queue = LinkedList<ID>()
queue.push(0)
while (queue.isNotEmpty()) {
val nodeID = queue.pop()
val node = board[nodeID]
node.edges.forEach{ (dID, dist) ->
// We either have a distance or we don't
// If we don't, the distance is shortestDistance[node] + dist
// Otherwise, it is min(that, existing)
val newDistance = shortestDistance[nodeID] + dist
shortestDistance[dID] = if (shortestDistance[dID] == -1) newDistance else min(newDistance, shortestDistance[dID])
if (!visited[dID])
queue.push(dID)
visited[nodeID] = true
}
}
return shortestDistance.last()
}
fun main() {
val snakes = mapOf(16 to 6, 48 to 26, 49 to 11, 56 to 53, 62 to 19, 64 to 60, 87 to 24, 93 to 73, 95 to 75, 98 to 78)
val ladders = mapOf(1 to 38, 4 to 14, 9 to 31, 21 to 42, 28 to 84, 36 to 44, 51 to 67, 71 to 91, 80 to 100)
// We play from 0 to 99 instead of 1 to 100, so drop all the transporters by 1.
val transporters = (snakes + ladders).map { it.key - 1 to it.value - 1}.toMap()
println("Number of moves required: ${snakesAndLadders(10, transporters)}.")
} | 0 | C++ | 1 | 0 | 5981e97106376186241f0fad81ee0e3a9b0270b5 | 2,409 | daily-coding-problem | MIT License |
gcj/y2022/kickstart_c/c.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package gcj.y2022.kickstart_c
private fun solve(): String {
val (n, len) = readInts()
val ants = List(n) { readInts() }
val falls = ants.map { ant ->
(if (ant[1] == 0) ant[0] else len - ant[0]) to ant[1]
}.sortedBy { it.first }
val order = ants.withIndex().sortedBy { it.value[0] }.map { it.index }
var low = 0
var high = n
val timeOfFall = IntArray(n)
for (fall in falls) {
if (fall.second == 0) {
timeOfFall[order[low]] = fall.first
low++
} else {
high--
timeOfFall[order[high]] = fall.first
}
}
return timeOfFall.indices.sortedBy { timeOfFall[it] }.map { it + 1 }.joinToString(" ")
}
fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 878 | competitions | The Unlicense |
src/Day05.kt | makohn | 571,699,522 | false | {"Kotlin": 35992} | import java.util.Stack
fun main() {
fun part1(input: String): String {
val stacks = mutableListOf<Stack<Char>>()
val (vis, moves) = input.split("\n\n")
vis.lines()
.reversed()
.drop(1)
.forEach {
it.filterIndexed { i, _ -> i % 4 == 1
}.forEachIndexed { i, s ->
if (i >= stacks.size) stacks.add(Stack<Char>())
if (s.isLetter()) stacks[i].push(s)
}
}
for (move in moves.lines()) {
val comp = move.split(" ")
val count = comp[1].toInt()
val src = comp[3].toInt() - 1
val dst = comp[5].toInt() - 1
repeat(count) {
stacks[dst].push(stacks[src].pop())
}
}
return stacks.map { it.last() }.joinToString("")
}
fun part2(input: String): String {
val stacks = mutableListOf<Stack<Char>>()
val (vis, moves) = input.split("\n\n")
vis.lines()
.reversed()
.drop(1)
.forEach {
it.filterIndexed { i, _ -> i % 4 == 1
}.forEachIndexed { i, s ->
if (i >= stacks.size) stacks.add(Stack<Char>())
if (s.isLetter()) stacks[i].push(s)
}
}
for (move in moves.lines()) {
val comp = move.split(" ")
val count = comp[1].toInt()
val src = comp[3].toInt() - 1
val dst = comp[5].toInt() - 1
val els = mutableListOf<Char>()
repeat(count) {
els.add(stacks[src].pop())
}
els.reversed().forEach {
stacks[dst].push(it)
}
}
return stacks.map { it.last() }.joinToString("")
}
// test if implementation meets criteria from the description, like:
val testInput = readInputFull("Day05_test")
check(part1(testInput) == "CMZ")
check(part2(testInput) == "MCD")
val input = readInputFull("Day05")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 2734d9ea429b0099b32c8a4ce3343599b522b321 | 2,145 | aoc-2022 | Apache License 2.0 |
src/Day03.kt | Yasenia | 575,276,480 | false | {"Kotlin": 15232} | import java.util.BitSet
fun main() {
fun Char.priority(): Int = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(this) + 1
fun part1(input: List<String>): Int {
var totalPriority = 0
for (rucksack in input) {
val compartment1 = rucksack.substring(0, rucksack.length / 2)
val compartment2 = rucksack.substring(rucksack.length / 2, rucksack.length)
val flags = BitSet(52)
for (item in compartment1) flags.set(item.priority() - 1, true)
for (item in compartment2) {
val priority = item.priority()
if (flags.get(priority - 1)) {
flags.set(priority - 1, false)
totalPriority += priority
}
}
}
return totalPriority
}
fun part2(input: List<String>): Int {
var totalPriority = 0
for (groupIndex in 0 until (input.size / 3)) {
val compartment1 = input[groupIndex * 3]
val compartment2 = input[groupIndex * 3 + 1]
val compartment3 = input[groupIndex * 3 + 2]
val flags = IntArray(52)
for (item in compartment1) flags[item.priority() - 1] = 1
for (item in compartment2) {
val priority = item.priority()
if (flags[priority - 1] == 1) flags[priority - 1] = 2
}
for (item in compartment3) {
val priority = item.priority()
if (flags[priority - 1] == 2) {
flags[priority - 1] = 3
totalPriority += priority
}
}
}
return totalPriority
}
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 9300236fa8697530a3c234e9cb39acfb81f913ba | 1,914 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day07.kt | iam-afk | 572,941,009 | false | {"Kotlin": 33272} | fun main() {
fun List<String>.parse(): Map<String, Int> {
val cwd = mutableListOf<String>()
val result = hashMapOf<String, Int>()
for (line in this) {
val args = line.split(' ')
when (args[0]) {
"$" -> when (args[1]) {
"cd" -> when (args[2]) {
"/" -> cwd.clear()
".." -> cwd.removeLast()
else -> cwd.add(args[2])
}
"ls" -> {}
}
"dir" -> {}
else -> {
result.compute("/") { _, size -> (size ?: 0) + args[0].toInt() }
var path = ""
for (dir in cwd) {
path += "/$dir"
result.compute(path) { _, size -> (size ?: 0) + args[0].toInt() }
}
}
}
}
return result
}
fun part1(input: Map<String, Int>): Int = input.values.filter { it <= 100000 }.sum()
fun part2(input: Map<String, Int>): Int {
val unused = 70000000 - input["/"]!!
return input.values.filter { it + unused >= 30000000 }.min()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day07_test").parse()
check(part1(testInput) == 95437)
check(part2(testInput) == 24933642)
val input = readInput("Day07").parse()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | b30c48f7941eedd4a820d8e1ee5f83598789667b | 1,537 | aockt | Apache License 2.0 |
src/Day06.kt | davedupplaw | 573,042,501 | false | {"Kotlin": 29190} | fun main() {
fun findFirstPositionAndCharsOfN(input: String, n: Int): Pair<Int, String> {
return input.windowed(n, 1).asSequence()
.mapIndexed { i, s -> (i + n) to s }
.first { it.second.toHashSet().size == it.second.length && it.second.length == n }
}
fun part1(input: String): Int {
return findFirstPositionAndCharsOfN(input, 4).first
}
fun part2(input: String): Int {
return findFirstPositionAndCharsOfN(input, 14).first
}
val test = readInput("Day06.test")
val part1test1 = part1(test[0])
println("part1 test (1): $part1test1")
check(part1test1 == 7)
val part1test2 = part1(test[1])
println("part1 test (2): $part1test2")
check(part1test2 == 5)
val part1test3 = part1(test[2])
println("part1 test (3): $part1test3")
check(part1test3 == 6)
val part1test4 = part1(test[3])
println("part1 test (4): $part1test4")
check(part1test4 == 10)
val part1test5 = part1(test[4])
println("part1 test (5): $part1test5")
check(part1test5 == 11)
val part2test1 = part2(test[0])
println("part2 test (1): $part2test1")
check(part2test1 == 19)
val part2test2 = part2(test[1])
println("part2 test (2): $part2test2")
check(part2test2 == 23)
val part2test3 = part2(test[2])
println("part2 test (3): $part2test3")
check(part2test3 == 23)
val part2test4 = part2(test[3])
println("part2 test (4): $part2test4")
check(part2test4 == 29)
val part2test5 = part2(test[4])
println("part2 test (5): $part2test5")
check(part2test5 == 26)
val input = readInput("Day06")
val part1 = part1(input[0])
println("Part1: $part1")
val part2 = part2(input[0])
println("Part2: $part2")
}
| 0 | Kotlin | 0 | 0 | 3b3efb1fb45bd7311565bcb284614e2604b75794 | 1,779 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/groundsfam/advent/y2023/d14/Day14.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2023.d14
import com.groundsfam.advent.DATAPATH
import com.groundsfam.advent.Direction
import com.groundsfam.advent.Direction.DOWN
import com.groundsfam.advent.Direction.LEFT
import com.groundsfam.advent.Direction.RIGHT
import com.groundsfam.advent.Direction.UP
import com.groundsfam.advent.grids.Grid
import com.groundsfam.advent.grids.copy
import com.groundsfam.advent.points.go
import com.groundsfam.advent.grids.containsPoint
import com.groundsfam.advent.points.Point
import com.groundsfam.advent.grids.readGrid
import com.groundsfam.advent.timed
import kotlin.io.path.div
private fun Grid<Char>.toKey() = joinToString("") { it.joinToString("") }
private class Solution(private val originalPlatform: Grid<Char>) {
val platform = originalPlatform.copy()
var cycleCount = 0
private set
private var tiltDir: Direction = UP
private var repetitionPeriod: Int? = null
private val directedIndices = mapOf(
UP to (0 until platform.numRows).flatMap { y ->
(0 until platform.numCols).map { x ->
Point(x, y)
}
},
DOWN to (0 until platform.numRows).reversed().flatMap { y ->
(0 until platform.numCols).map { x ->
Point(x, y)
}
},
LEFT to (0 until platform.numCols).flatMap { x ->
(0 until platform.numRows).map { y ->
Point(x, y)
}
},
RIGHT to (0 until platform.numCols).reversed().flatMap { x ->
(0 until platform.numRows).map { y ->
Point(x, y)
}
},
)
fun tilt() {
directedIndices[tiltDir]!!.forEach { p ->
if (platform[p] == 'O') {
// to will be the point that p slides north to
var to = p
var toNext = to.go(tiltDir)
while (platform.containsPoint(toNext) && platform[toNext] == '.') {
to = toNext
toNext = to.go(tiltDir)
}
platform[to] = 'O'
if (p != to) {
platform[p] = '.'
}
}
}
tiltDir = tiltDir.ccw
}
fun cycle() {
do {
tilt()
} while (tiltDir != UP)
cycleCount++
}
// returns the period of repetition
fun findRepetition(): Int {
repetitionPeriod?.also {
return it
}
val cycles = mutableMapOf(
originalPlatform.toKey() to 0,
)
// handle rest of first cycle
cycle()
assert(cycleCount == 1)
// continue cycling until a repeated configuration is found
var key = platform.toKey()
while (key !in cycles.keys) {
cycles[key] = cycleCount
cycle()
key = platform.toKey()
}
return (cycleCount - cycles[key]!!)
.also { repetitionPeriod = it }
}
fun load(): Int =
platform.pointIndices.sumOf { p ->
if (platform[p] == 'O') {
platform.numRows - p.y
} else {
0
}
}
}
fun main() = timed {
val solution = (DATAPATH / "2023/day14.txt")
.readGrid()
.let(::Solution)
solution.tilt()
println("Part one: ${solution.load()}")
val period = solution.findRepetition()
repeat((1_000_000_000 - solution.cycleCount) % period) {
solution.cycle()
}
println("Part two: ${solution.load()}")
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 3,570 | advent-of-code | MIT License |
src/Day09.kt | maciekbartczak | 573,160,363 | false | {"Kotlin": 41932} | import kotlin.math.abs
fun main() {
fun part1(input: List<String>): Int {
return getUniquePositionsVisitedByTailCount(input, 2)
}
fun part2(input: List<String>): Int {
return getUniquePositionsVisitedByTailCount(input, 10)
}
val testInput = readInput("Day09_test")
check(part1(testInput) == 13)
check(part2(testInput) == 1)
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
val directionMap = mapOf(
'U' to (0 to 1),
'D' to (0 to -1),
'L' to (-1 to 0),
'R' to (1 to 0)
)
private fun getUniquePositionsVisitedByTailCount(moves: List<String>, knotCount: Int): Int {
val visitedPositions = mutableSetOf<Pair<Int, Int>>()
val knotPositions = mutableListOf<Pair<Int, Int>>()
repeat(knotCount) {
knotPositions.add(0 to 0)
}
moves
.map {
it.parseInput()
}
.forEach {
val offset = directionMap[it.first]!!
repeat(it.second) {
// treat the knot under index 0 as head
knotPositions[0] = knotPositions[0].offsetBy(offset)
var lastOffset = offset
for (i in 1 until knotCount) {
val head = knotPositions[i - 1]
val currentKnot = knotPositions[i]
val (newTail, tailMoveOffset) = moveTail(currentKnot, head, lastOffset)
knotPositions[i] = newTail
lastOffset = tailMoveOffset
}
visitedPositions.add(knotPositions[knotCount - 1])
}
}
return visitedPositions.size
}
private fun String.parseInput(): Pair<Char, Int> {
val input = this.split(" ")
return input[0].toCharArray()[0] to input[1].toInt()
}
private fun moveTail(
currentTailPosition: Pair<Int, Int>,
currentHeadPosition: Pair<Int, Int>,
lastHeadMove: Pair<Int, Int>
): Pair<Pair<Int, Int>, Pair<Int, Int>> {
if (currentHeadPosition.isTouching(currentTailPosition)) {
return currentTailPosition to (0 to 0)
}
if (currentHeadPosition.isAlignedVertically(currentTailPosition)) {
val offset = 0 to lastHeadMove.second
return currentTailPosition.offsetBy(offset) to offset
}
if (currentHeadPosition.isAlignedHorizontally(currentTailPosition)) {
val offset = lastHeadMove.first to 0
return currentTailPosition.offsetBy(offset) to offset
}
val xDistance = abs(currentHeadPosition.first - currentTailPosition.first)
val yDistance = abs(currentHeadPosition.second - currentTailPosition.second)
val offset = if (xDistance > 1 && yDistance > 1) {
lastHeadMove
} else if (xDistance > 1) {
lastHeadMove.first to currentHeadPosition.second - currentTailPosition.second
} else {
currentHeadPosition.first - currentTailPosition.first to lastHeadMove.second
}
return currentTailPosition.offsetBy(offset) to offset
}
private fun Pair<Int, Int>.isAlignedVertically(other: Pair<Int, Int>): Boolean {
return this.first == other.first
}
private fun Pair<Int, Int>.isAlignedHorizontally(other: Pair<Int, Int>): Boolean {
return this.second == other.second
}
private fun Pair<Int, Int>.isTouching(other: Pair<Int, Int>): Boolean {
for (x in -1..1) {
for (y in -1..1) {
val offset = x to y
if (this.offsetBy(offset) == other) {
return true
}
}
}
return false
}
| 0 | Kotlin | 0 | 0 | 53c83d9eb49d126e91f3768140476a52ba4cd4f8 | 3,524 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day12_passage_pathing/PassagePathing.kt | barneyb | 425,532,798 | false | {"Kotlin": 238776, "Shell": 3825, "Java": 567} | package day12_passage_pathing
import java.util.*
/**
* Another graph, specified solely by the edges (the nodes are implied). The
* right data structure is required, though it needn't be a fancy variant. A
* simple adjacency list is plenty, and a symbol table isn't required. With the
* right structure populated from the input, just a matter of walking w/ a visit
* map and counting the paths that don't violate the rules.
*
* Part two requires more bookkeeping, but like Treachery of Whales (#7), the
* strategy pattern is the way to go. The strategy is "can enter cave?", where
* part one is based solely on case, while part two needs to do some analysis of
* the prior path to allow reentering exactly one small cave exactly twice.
*
* A symbol table can make things somewhat faster, and will certainly scale
* better if the cave system were to have more than the 20-something caves in
* the input. Representing small/large caves is required, of course, and having
* to dereference the symbol table on every "can enter" check may mitigate any
* advantages. A single bit can be represented by the sign bit on a signed
* integer, so there is a zero-overhead way to encode that info. Sneaky!
*/
fun main() {
util.solve(5333, ::partOne)
util.solve(146553, ::partTwo)
// using String instead of Int is ~35% slower
// using Set instead of List is ~200% slower
}
//typealias Cave = String
//
//private const val START: Cave = "start"
//private const val END: Cave = "end"
//
//val Cave.isUnlimitedEntry
// get() =
// this[0].isUpperCase()
typealias Cave = Int
private const val START: Cave = 0
private const val END: Cave = 1
val Cave.isUnlimitedEntry
get() =
this > END
data class Path(val at: Cave, val visited: List<Cave>, val double: Boolean) {
constructor(at: Cave) : this(at, listOf(at), false)
fun then(cave: Cave): Path =
Path(
cave,
visited + cave,
double || (!cave.isUnlimitedEntry && visited.contains(cave))
)
}
private fun String.toGraph(): Map<Cave, Collection<Cave>> {
val nodes = mutableMapOf("start" to START, "end" to END)
val graph: Map<Cave, Collection<Cave>> =
mutableMapOf<Cave, MutableList<Cave>>()
.apply {
lines()
.map { edge ->
edge.split('-')
.map { cave ->
nodes.getOrPut(cave) {
if (cave[0].isUpperCase())
nodes.size
else
-nodes.size
}
}
}
.map { (a, b) ->
getOrPut(a, ::mutableListOf).add(b)
getOrPut(b, ::mutableListOf).add(a)
}
}
// println(nodes)
return graph
}
private fun countPaths(input: String, accept: (Path, Cave) -> Boolean): Int {
val graph = input.toGraph()
var pathCount = 0
// val paths = mutableSetOf<Path>()
val queue: Queue<Path> = ArrayDeque()
queue.add(Path(START))
while (queue.isNotEmpty()) {
val p = queue.remove()
if (p.at == END) {
pathCount += 1
// println(p)
// if (!paths.add(p)) throw IllegalStateException("Duplicate path recorded?! ${p}")
// if (paths.size > 40) throw IllegalStateException("runaway traversal...")
continue
}
queue.addAll(
graph[p.at]!!
.filter { accept(p, it) }
.map { p.then(it) }
)
}
return pathCount
// return paths.size
}
fun partOne(input: String) =
countPaths(input) { p: Path, it: Cave ->
it.isUnlimitedEntry || !p.visited.contains(it)
}
fun partTwo(input: String) =
countPaths(input) { p: Path, it: Cave ->
if (it.isUnlimitedEntry)
true
else if (it == START)
false
else
!p.double || !p.visited.contains(it)
}
| 0 | Kotlin | 0 | 0 | a8d52412772750c5e7d2e2e018f3a82354e8b1c3 | 4,167 | aoc-2021 | MIT License |
src/Day08.kt | Kanialdo | 573,165,497 | false | {"Kotlin": 15615} | import kotlin.math.max
fun main() {
fun part1(input: List<String>): Int {
val area = input.map { row -> row.toCharArray().map { it.digitToInt() } }
val visibility = Array(area.size) { BooleanArray(area.first().size) { false } }
val dimension = area.size
for (y in 1 until dimension - 1) {
var max = area[y].first()
for (x in 1 until dimension - 1) {
visibility[y][x] = visibility[y][x] || area[y][x] > max
max = max(area[y][x], max)
}
max = area[y].last()
for (x in dimension - 2 downTo 1) {
visibility[y][x] = visibility[y][x] || area[y][x] > max
max = max(area[y][x], max)
}
}
for (x in 1 until dimension - 1) {
var max = area.first()[x]
for (y in 1 until dimension - 1) {
visibility[y][x] = visibility[y][x] || area[y][x] > max
max = max(area[y][x], max)
}
max = area.last()[x]
for (y in dimension - 2 downTo 1) {
visibility[y][x] = visibility[y][x] || area[y][x] > max
max = max(area[y][x], max)
}
}
// for (y in area.first().indices) {
// for (x in area.indices) {
// print(if (visibility[y][x]) "o" else "x")
// }
// println()
// }
return visibility.sumOf { it.count { it } } + visibility.size * 4 - 4
}
fun List<List<Int>>.countRight(x: Int, y: Int): Int {
var count = 0
for (i in x + 1 until size) {
count++
if (this[y][x] <= this[y][i]) break
}
return count
}
fun List<List<Int>>.countLeft(x: Int, y: Int): Int {
var count = 0
for (i in x - 1 downTo 0) {
count++
if (this[y][x] <= this[y][i]) break
}
return count
}
fun List<List<Int>>.countTop(x: Int, y: Int): Int {
var count = 0
for (i in y + 1 until size) {
count++
if (this[y][x] <= this[i][x]) break
}
return count
}
fun List<List<Int>>.countBottom(x: Int, y: Int): Int {
var count = 0
for (i in y - 1 downTo 0) {
count++
if (this[y][x] <= this[i][x]) break
}
return count
}
fun part2(input: List<String>): Int {
val area = input.map { row -> row.toCharArray().map { it.digitToInt() } }
val score = Array(area.size) { IntArray(area.first().size) { 0 } }
val dimension = area.size
for (y in 1 until dimension - 1 ) {
for (x in 1 until dimension - 1) {
score[y][x] = area.countRight(x = x, y = y) *
area.countLeft(x = x, y = y) *
area.countBottom(x = x, y = y) *
area.countTop(x = x, y = y)
}
}
// for (y in 0 until dimension) {
// for (x in 0 until dimension) {
// print(score[y][x])
// }
// println()
// }
return score.maxOf { it.max() }
}
val testInput = readInput("Day08_test")
check(part1(testInput), 21)
check(part2(testInput), 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 10a8550a0a85bd0a928970f8c7c5aafca2321a4b | 3,423 | advent-of-code-2022 | Apache License 2.0 |
src/Day10.kt | matusekma | 572,617,724 | false | {"Kotlin": 119912, "JavaScript": 2024} | import kotlin.math.abs
data class State(
val cycle: Int,
val X: Int,
val signalStrengths: MutableMap<Int, Int>
)
class Day10 {
fun part1(instructions: List<String>): Int {
var state = State(1, 1, mutableMapOf())
for (instruction in instructions) {
val commandWithOptionalParam = instruction.split(' ')
val param = if (commandWithOptionalParam.size > 1) commandWithOptionalParam[1] else null
state = execute(commandWithOptionalParam[0], param, state)
}
return state.signalStrengths.entries
.filter { (cycle, _) -> (cycle - 20) % 40 == 0 }
.sumOf { (cycle, x) -> cycle * x }
}
fun execute(command: String, param: String?, state: State): State {
var cycle = state.cycle
var X = state.X
val signalStrengths = state.signalStrengths
when (command) {
"noop" -> {
signalStrengths[cycle] = X
val newCycle = cycle + 1
return State(newCycle, X, signalStrengths)
}
"addx" -> {
signalStrengths[cycle] = X
signalStrengths[cycle + 1] = X
val newCycle = cycle + 2
val newX = X + param!!.toInt()
return State(newCycle, newX, signalStrengths)
}
}
return State(cycle, X, signalStrengths)
}
fun part2(instructions: List<String>) {
var state = State(1, 1, mutableMapOf())
for (instruction in instructions) {
val commandWithOptionalParam = instruction.split(' ')
val param = if (commandWithOptionalParam.size > 1) commandWithOptionalParam[1] else null
state = execute(commandWithOptionalParam[0], param, state)
}
state.signalStrengths.entries
.forEach { (cycle, X) ->
val position = (cycle - 1) % 40
if (abs(position-X) <= 1) print("#") else print('.')
if (cycle % 40 == 0) {
println()
}
}
}
}
fun main() {
val day10 = Day10()
val input = readInput("input10_1")
println(day10.part1(input))
println(day10.part2(input))
} | 0 | Kotlin | 0 | 0 | 744392a4d262112fe2d7819ffb6d5bde70b6d16a | 2,247 | advent-of-code | Apache License 2.0 |
advent2022/src/main/kotlin/year2022/Day08.kt | bulldog98 | 572,838,866 | false | {"Kotlin": 132847} | package year2022
import AdventDay
typealias Forest = List<List<Int>>
fun Forest.isVisible(x: Int, y: Int): Boolean {
val ownHeight = this[x][y]
val leftVisible = (0 until x).all { this[it][y] < ownHeight }
val rightVisible = (x + 1 until this[x].size).all { this[it][y] < ownHeight }
val topVisible = (0 until y).all { this[x][it] < ownHeight }
val bottomVisible = (y + 1 until this.size).all { this[x][it] < ownHeight }
return leftVisible || rightVisible || topVisible || bottomVisible ||
x == 0 || y == 0 || x == this[y].size - 1 || y == this.size - 1
}
fun List<String>.parseForest(): Forest = map { it.toList().map { c -> c.toString().toInt() }}
fun Iterable<Int>.countUnless(pred: (Int) -> Boolean): Int {
var res = 0
for (element in this) {
res++
if (pred(element))
return res
}
return res
}
fun Forest.getVisibleCoords(): Set<Pair<Int, Int>> {
val foundInvisible = mutableSetOf<Pair<Int, Int>>()
for (x in this.indices) {
for (y in this[x].indices) {
if (isVisible(x, y)) {
foundInvisible.add(x to y)
}
}
}
return foundInvisible
}
fun Forest.sceniceMeasure(x: Int, y: Int): Int {
val ownHeight = this[x][y]
val leftVisible = (0 until x).reversed().countUnless { this[it][y] >= ownHeight }
val rightVisible = (x + 1 until this[x].size).countUnless { this[it][y] >= ownHeight }
val topVisible = (0 until y).reversed().countUnless { this[x][it] >= ownHeight }
val bottomVisible = (y + 1 until this.size).countUnless { this[x][it] >= ownHeight }
return leftVisible * rightVisible * topVisible * bottomVisible
}
class Day08 : AdventDay(2022, 8) {
override fun part1(input: List<String>): Int {
return input.parseForest().getVisibleCoords().size
}
override fun part2(input: List<String>): Int {
val forest = input.parseForest()
val visible = forest.getVisibleCoords().maxBy { (x,y) -> forest.sceniceMeasure(x, y)}
return forest.sceniceMeasure(visible.first, visible.second)
}
}
fun main() = Day08().run() | 0 | Kotlin | 0 | 0 | 02ce17f15aa78e953a480f1de7aa4821b55b8977 | 2,142 | advent-of-code | Apache License 2.0 |
src/main/kotlin/day5.kt | gautemo | 725,273,259 | false | {"Kotlin": 79259} | import shared.*
fun main() {
val input = Input.day(5)
println(day5A(input))
println(day5B(input))
}
fun day5A(input: Input): Long {
val seeds = input.chunks[0].toLongs()
val categories = input.chunks.drop(1).map(Category::from)
val mapped = seeds.map { seed ->
categories.fold(seed) { value, category ->
category.map(value)
}
}
return mapped.min()
}
fun day5B(input: Input): Long {
var min = Long.MAX_VALUE
val seeds = input.chunks[0].toLongs().chunked(2)
val categories = input.chunks.drop(1).map(Category::from)
seeds.forEach { seed ->
for (i in seed[0]..<seed[0] + seed[1]) {
val value = categories.fold(i) { value, category ->
category.map(value)
}
min = minOf(min, value)
}
}
return min
}
private class Category(val converters: List<Converter>) {
fun map(value: Long): Long {
return converters.firstOrNull { it.inRange(value) }?.mappedTo(value) ?: value
}
companion object {
fun from(chunk: String): Category {
return Category(chunk.lines().drop(1).map(Converter::from))
}
}
}
private class Converter(val destination: Long, val source: Long, val range: Long) {
fun inRange(value: Long) = value >= source && value < source + range
fun mappedTo(value: Long) = destination + value - source
companion object {
fun from(line: String): Converter {
val (destination, source, range) = line.toLongs()
return Converter(destination, source, range)
}
}
} | 0 | Kotlin | 0 | 0 | 6862b6d7429b09f2a1d29aaf3c0cd544b779ed25 | 1,614 | AdventOfCode2023 | MIT License |
src/com/aaron/helloalgorithm/algorithm/二叉树/_226_翻转二叉树.kt | aaronzzx | 431,740,908 | false | null | package com.aaron.helloalgorithm.algorithm.二叉树
import com.aaron.helloalgorithm.algorithm.LeetCode
import com.aaron.helloalgorithm.algorithm.TreeNode
import com.aaron.helloalgorithm.structure.tree.ktx.println
import com.aaron.helloalgorithm.structure.tree.printer.BinaryTrees
import java.util.*
/**
* # 226. 翻转一棵二叉树
*
* 示例:
*
* 输入:
* ```
* 4
* / \
* 2 7
* / \ / \
* 1 3 6 9
* ```
* 输出:
* ```
* 4
* / \
* 7 2
* / \ / \
* 9 6 3 1
* ```
* 备注:
* 这个问题是受到 <NAME> 的 原问题 启发的 :
*
* 谷歌:我们90%的工程师使用您编写的软件(Homebrew),但是您却无法在面试时在白板上写出翻转二叉树这道题,这太糟糕了。
*
* 来源:力扣(LeetCode)
*
* 链接:[https://leetcode-cn.com/problems/invert-binary-tree/]
*
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*
* @author <EMAIL>
* @since 2021/11/23
*/
class _226_翻转二叉树
private val NUMS = intArrayOf(50, 25, 75, 12, 40, 60, 90, 6, 20, 30, 48, 55, 70, 80, 100)
fun LeetCode.二叉树.run_226_翻转二叉树(nums: IntArray = NUMS) {
if (nums.isEmpty()) {
println("[]")
return
}
val root = TreeNode(nums[0]).also {
it.root = it
}
val list = nums.toMutableList().also {
it.removeAt(0)
}
list.forEach {
var node: TreeNode? = root
var parent = root
var compare = 0
while (node != null) {
parent = node
compare = it.compareTo(node.`val`)
when (compare) {
-1 -> {
node = node.left
}
1 -> {
node = node.right
}
else -> {
node.`val` = it
return
}
}
}
val newNode = TreeNode(it).also { treeNode ->
treeNode.root = root
}
when (compare) {
-1 -> {
parent.left = newNode
}
else -> {
parent.right = newNode
}
}
}
root.println(BinaryTrees.PrintStyle.LEVEL_ORDER)
// val inverted = _226_翻转二叉树_层序遍历(root)
// val inverted = _226_翻转二叉树_前序遍历(root)
// val inverted = _226_翻转二叉树_中序遍历(root)
val inverted = _226_翻转二叉树_后序遍历(root)
println()
inverted!!.println(BinaryTrees.PrintStyle.LEVEL_ORDER)
}
fun LeetCode.二叉树._226_翻转二叉树_前序遍历(root: TreeNode?): TreeNode? {
root ?: return root
print("${root.`val`}, ")
val temp = root.right
root.right = _226_翻转二叉树_前序遍历(root.left)
root.left = _226_翻转二叉树_前序遍历(temp)
return root
}
fun LeetCode.二叉树._226_翻转二叉树_中序遍历(root: TreeNode?): TreeNode? {
root ?: return root
val invertedLeft = _226_翻转二叉树_中序遍历(root.left)
print("${root.`val`}, ")
val temp = root.right
root.right = invertedLeft
root.left = _226_翻转二叉树_中序遍历(temp)
return root
}
fun LeetCode.二叉树._226_翻转二叉树_后序遍历(root: TreeNode?): TreeNode? {
root ?: return root
val left = _226_翻转二叉树_后序遍历(root.left)
val right = _226_翻转二叉树_后序遍历(root.right)
print("${root.`val`}, ")
root.left = right
root.right = left
return root
}
fun LeetCode.二叉树._226_翻转二叉树_层序遍历(root: TreeNode?): TreeNode? {
root ?: return root
val queue: Queue<TreeNode> = LinkedList<TreeNode>().also {
it.offer(root)
}
while (queue.isNotEmpty()) {
val poll = queue.poll()
print("${poll.`val`}, ")
val temp = poll.left
poll.left = poll.right
poll.right = temp
if (poll.left != null) {
queue.offer(poll.left)
}
if (poll.right != null) {
queue.offer(poll.right)
}
}
return root
} | 0 | Kotlin | 0 | 0 | 2d3d823b794fd0712990cbfef804ac2e138a9db3 | 4,175 | HelloAlgorithm | Apache License 2.0 |
src/main/kotlin/com/sk/topicWise/binarysearch/33. Search in Rotated Sorted Array.kt | sandeep549 | 262,513,267 | false | {"Kotlin": 530613} | package com.sk.topicWise.binarysearch
class Solution33 {
fun search(nums: IntArray, target: Int): Int {
if (nums.isEmpty()) return -1
// find smallest element, use it's index as rotation count
var l = 0
var r = nums.lastIndex
while (l < r) {
val mid = l + (r - l) / 2
if (nums[mid] > nums[r]) l = mid + 1 // Why comparing with right element and not left ?
else r = mid
}
val rot = l
l = 0
r = nums.lastIndex
while (l < r) {
val mid = l + (r - l) / 2
val realmid = (mid + rot) % nums.size
if (nums[realmid] < target) l = mid + 1
else r = mid
}
l = (l + rot) % nums.size
return if (nums[l] == target) l else -1
}
}
// from solution
// https://leetcode.com/problems/search-in-rotated-sorted-array/discuss/14435/Clever-idea-making-it-simple
private fun search2(nums: IntArray, target: Int): Int {
if (nums.isEmpty()) return -1
var l = 0
var r = nums.lastIndex
val MAX = Int.MAX_VALUE
val MIN = Int.MIN_VALUE
while (l < r) {
val mid = l + (r - l) / 2
val num = when {
nums[mid] < nums[0] == target < nums[0] -> nums[mid]
target < nums[0] -> MIN
else -> MAX
}
if (num < target) l = mid + 1
else r = mid
}
return if (nums[l] == target) l else -1
}
| 1 | Kotlin | 0 | 0 | cf357cdaaab2609de64a0e8ee9d9b5168c69ac12 | 1,449 | leetcode-kotlin | Apache License 2.0 |
kotlin/src/com/daily/algothrim/leetcode/SummaryRanges.kt | idisfkj | 291,855,545 | false | null | package com.daily.algothrim.leetcode
/**
* 228. 汇总区间
* 给定一个无重复元素的有序整数数组 nums 。
*
* 返回 恰好覆盖数组中所有数字 的 最小有序 区间范围列表。也就是说,nums 的每个元素都恰好被某个区间范围所覆盖,并且不存在属于某个范围但不属于 nums 的数字 x 。
*
* 列表中的每个区间范围 [a,b] 应该按如下格式输出:
*
* "a->b" ,如果 a != b
* "a" ,如果 a == b
*
* 示例 1:
*
* 输入:nums = [0,1,2,4,5,7]
* 输出:["0->2","4->5","7"]
* 解释:区间范围是:
* [0,2] --> "0->2"
* [4,5] --> "4->5"
* [7,7] --> "7"
*
* */
class SummaryRanges {
companion object {
@JvmStatic
fun main(args: Array<String>) {
SummaryRanges().solution(intArrayOf(0, 1, 2, 4, 5, 7)).apply {
forEach {
println(it)
}
}
println()
SummaryRanges().solution2(intArrayOf(0, 1, 2, 4, 5, 7)).apply {
forEach {
println(it)
}
}
}
}
// 0,1,2,4,5,7
fun solution(nums: IntArray): List<String> {
val list = arrayListOf<String>()
var flag = false
var start = 0
var current = 0
nums.forEach {
when {
!flag -> {
flag = true
start = it
current = start
}
current + 1 == it -> current = it
else -> {
if (start == current) {
list.add("$start")
} else {
list.add("$start->$current")
}
start = it
current = it
}
}
}
if (flag) {
if (start == current) {
list.add("$start")
} else {
list.add("$start->$current")
}
}
return list
}
fun solution2(nums: IntArray): List<String> {
val list = arrayListOf<String>()
var i = 0
var j = 0
val n = nums.size
while (i < n) {
if (i + 1 == n || nums[i + 1] != nums[i] + 1) {
if (i == j) {
list.add("${nums[i]}")
} else {
list.add("${nums[j]}->${nums[i]}")
}
j = i + 1
}
i++
}
return list
}
} | 0 | Kotlin | 9 | 59 | 9de2b21d3bcd41cd03f0f7dd19136db93824a0fa | 2,589 | daily_algorithm | Apache License 2.0 |
src/main/kotlin/eu/michalchomo/adventofcode/year2023/Day09.kt | MichalChomo | 572,214,942 | false | {"Kotlin": 56758} | package eu.michalchomo.adventofcode.year2023
import eu.michalchomo.adventofcode.Day
import eu.michalchomo.adventofcode.main
object Day09 : Day {
override val number: Int = 9
override fun part1(input: List<String>): String = solve(input) { histories ->
histories.foldRight(0) { ints, acc -> ints.last() + acc }
}
override fun part2(input: List<String>): String = solve(input) { histories ->
histories.foldRight(0) { ints, acc -> ints.first() - acc }
}
private fun solve(input: List<String>, extrapolate: (List<List<Int>>) -> Int): String = input.sumOf { line ->
line.splitToIntList().predictNext(extrapolate)
}.toString()
private fun String.splitToIntList(): List<Int> = this.split(' ').map { it.toInt() }
private fun List<Int>.predictNext(extrapolate: (List<List<Int>>) -> Int): Int {
val extrapolation = mutableListOf(this)
while (extrapolation.last().toSet().size > 1) {
extrapolation.add(
extrapolation.last().drop(1)
.mapIndexed { i, it -> it.diff(extrapolation.last()[i]) }
.toList()
)
}
return extrapolate(extrapolation)
}
private fun Int.diff(other: Int) =
(kotlin.math.max(this, other) - kotlin.math.min(this, other)) * if (this < other) -1 else 1
}
fun main() {
main(Day09)
}
| 0 | Kotlin | 0 | 0 | a95d478aee72034321fdf37930722c23b246dd6b | 1,388 | advent-of-code | Apache License 2.0 |
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[561]数组拆分 I.kt | maoqitian | 175,940,000 | false | {"Kotlin": 354268, "Java": 297740, "C++": 634} | import java.util.*
//给定长度为 2n 的整数数组 nums ,你的任务是将这些数分成 n 对, 例如 (a1, b1), (a2, b2), ..., (an, bn) ,使得
//从 1 到 n 的 min(ai, bi) 总和最大。
//
// 返回该 最大总和 。
//
//
//
// 示例 1:
//
//
//输入:nums = [1,4,3,2]
//输出:4
//解释:所有可能的分法(忽略元素顺序)为:
//1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
//2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
//3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4
//所以最大总和为 4
//
// 示例 2:
//
//
//输入:nums = [6,2,6,5,1,2]
//输出:9
//解释:最优的分法为 (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 +
//6 = 9
//
//
//
//
// 提示:
//
//
// 1 <= n <= 104
// nums.length == 2 * n
// -104 <= nums[i] <= 104
//
// Related Topics 数组
// 👍 222 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun arrayPairSum(nums: IntArray): Int {
//排序 获取 数组下标偶数位和 时间复杂度 O(n)
Arrays.sort(nums)
var sum = 0
var i = 0
while (i < nums.size) {
sum += nums[i]
i += 2
}
return sum
}
}
//leetcode submit region end(Prohibit modification and deletion)
| 0 | Kotlin | 0 | 1 | 8a85996352a88bb9a8a6a2712dce3eac2e1c3463 | 1,371 | MyLeetCode | Apache License 2.0 |
2021/src/main/kotlin/day9_imp.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.IntGrid
import utils.Solution
fun main() {
Day9Imp.run()
}
object Day9Imp : Solution<IntGrid>() {
override val name = "day9"
override val parser = IntGrid.singleDigits.map { it.borderWith(9) }
override fun part1(input: IntGrid): Int {
var sum = 0
for (y in 1 until input.height - 1) {
for (x in 1 until input.width - 1) {
if (input[x][y] < input[x][y - 1] &&
input[x][y] < input[x - 1][y] &&
input[x][y] < input[x][y + 1] &&
input[x][y] < input[x + 1][y]) {
sum += 1 + input[x][y]
}
}
}
return sum
}
override fun part2(input: IntGrid): Number? {
val visited = Array(input.height) { BooleanArray(input.width) { false } }
// recursively 4-way-fill at x + y and return the number of cells filled
fun fill(x: Int, y: Int): Int {
if (visited[x][y]) {
return 0
}
if (input[x][y] >= 9) {
return 0
}
visited[x][y] = true
return 1 + fill(y-1, x) + fill(y+1, x) + fill(y, x-1) + fill(y, x+1)
}
val sizes = mutableListOf<Int>()
for (y in 1 until input.height - 1) {
for (x in 1 until input.width - 1) {
val sz = fill(x, y)
if (sz > 0) sizes += sz
}
}
sizes.sortDescending()
var product = 1
for (i in 0 until 3) {
product *= sizes[i]
}
return product
}
}
| 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 1,406 | aoc_kotlin | MIT License |
src/Day03.kt | papichulo | 572,669,466 | false | {"Kotlin": 16864} | import kotlin.IllegalArgumentException
fun main() {
fun valueForChar(char: Char): Int {
return when (char) {
'a' -> 1
'b' -> 2
'c' -> 3
'd' -> 4
'e' -> 5
'f' -> 6
'g' -> 7
'h' -> 8
'i' -> 9
'j' -> 10
'k' -> 11
'l' -> 12
'm' -> 13
'n' -> 14
'o' -> 15
'p' -> 16
'q' -> 17
'r' -> 18
's' -> 19
't' -> 20
'u' -> 21
'v' -> 22
'w' -> 23
'x' -> 24
'y' -> 25
'z' -> 26
'A' -> 27
'B' -> 28
'C' -> 29
'D' -> 30
'E' -> 31
'F' -> 32
'G' -> 33
'H' -> 34
'I' -> 35
'J' -> 36
'K' -> 37
'L' -> 38
'M' -> 39
'N' -> 40
'O' -> 41
'P' -> 42
'Q' -> 43
'R' -> 44
'S' -> 45
'T' -> 46
'U' -> 47
'V' -> 48
'W' -> 49
'X' -> 50
'Y' -> 51
'Z' -> 52
else -> throw IllegalArgumentException()
}
}
fun findMatchingChar(s1: String, s2: String): Char {
var x = '0'
s1.forEach {
c -> if (s2.contains(c)) x = c
}
return x
}
fun findMatchingCharBetween(s1: String, s2: String, s3: String): Char {
var x = '0'
s1.forEach {
c -> if (s2.contains(c) && s3.contains(c)) x = c
}
return x
}
fun String.splitInHalf() = take(this.length / 2) to substring(this.length / 2)
fun part2(input: List<String>): Int {
return input.chunked(3).map { findMatchingCharBetween(it[0], it[1], it[2]) }.sumOf { valueForChar(it)}
}
fun part1(input: List<String>): Int {
return input.map { t -> t.splitInHalf() }
.map { findMatchingChar(it.first, it.second) }
.sumOf { valueForChar(it) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e277ee5bca823ce3693e88df0700c021e9081948 | 2,433 | aoc-2022-in-kotlin | Apache License 2.0 |
src/day03/Day03_functional.kt | seastco | 574,758,881 | false | {"Kotlin": 72220} | package day03
import readLines
/**
* Credit goes to tginsberg (https://github.com/tginsberg/advent-2022-kotlin)
* I'm experimenting with his solutions to better learn functional programming in Kotlin.
* Files without the _functional suffix are my original solutions.
*/
private fun Char.priority(): Int =
when (this) {
in 'a'..'z' -> (this - 'a') + 1
in 'A'..'Z' -> (this - 'A') + 27
else -> throw IllegalArgumentException("Letter not in range: $this")
}
private fun List<String>.sharedItem(): Char =
map { it.toSet() } // convert List<String> to List<Set<Char>>
.reduce { left, right -> left intersect right } // intersect each set from left to right
.first() // return the shared Char
private fun String.sharedItem(): Char =
listOf(
substring(0..length / 2),
substring(length / 2)
).sharedItem()
private fun part1(input: List<String>): Int {
return input.sumOf { it.sharedItem().priority() }
}
private fun part2(input: List<String>): Int {
return input.chunked(3).sumOf { it.sharedItem().priority() }
}
fun main() {
println(part1(readLines("day03/test")))
println(part1(readLines("day03/input")))
println(part2(readLines("day03/test")))
println(part2(readLines("day03/input")))
}
| 0 | Kotlin | 0 | 0 | 2d8f796089cd53afc6b575d4b4279e70d99875f5 | 1,295 | aoc2022 | Apache License 2.0 |
src/Day04/Day04.kt | SelenaChen123 | 573,253,480 | false | {"Kotlin": 14884} | import java.io.File
fun main() {
fun part1(input: List<String>): Int {
var duplicates = 0
for (line in input) {
val first = line.split(",")[0].split("-")
val second = line.split(",")[1].split("-")
if ((second[0].toInt() in first[0].toInt()..first[1].toInt() &&
second[1].toInt() in first[0].toInt()..first[1].toInt()) ||
(first[0].toInt() in second[0].toInt()..second[1].toInt() &&
first[1].toInt() in second[0].toInt()..second[1].toInt())
) {
duplicates++
}
}
return duplicates
}
fun part2(input: List<String>): Int {
var duplicates = 0
for (line in input) {
val first = line.split(",")[0].split("-")
val second = line.split(",")[1].split("-")
if (second[0].toInt() in first[0].toInt()..first[1].toInt() ||
second[1].toInt() in first[0].toInt()..first[1].toInt() ||
first[0].toInt() in second[0].toInt()..second[1].toInt() ||
first[1].toInt() in second[0].toInt()..second[1].toInt()
) {
duplicates++
}
}
return duplicates
}
val testInput = File("input", "Day04_test.txt").readLines()
val input = File("input", "Day04.txt").readLines()
val part1TestOutput = part1(testInput)
check(part1TestOutput == 2)
println(part1(input))
val part2TestOutput = part2(testInput)
check(part2TestOutput == 4)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 551af4f0efe11744f918d1ff5bb2259e34c5ecd3 | 1,667 | AdventOfCode2022 | Apache License 2.0 |
2021/03/07/jjeda/Sorting.kt | Road-of-CODEr | 323,110,862 | false | null |
// https://app.codility.com/programmers/lessons/6-sorting/distinct/
fun distinct(A: IntArray): Int {
return A.toSet().size
}
// https://app.codility.com/programmers/lessons/6-sorting/max_product_of_three/
fun maxProductOfThree(A: IntArray): Int {
val indexWithA = A.withIndex().sortedBy { it.value }
val length = A.size
val positiveMaxValue = indexWithA[length - 1].value * indexWithA[length - 2].value * indexWithA[length - 3].value
val negativeMaxValue = indexWithA[0].value * indexWithA[1].value * indexWithA[length - 1].value
return if (positiveMaxValue > negativeMaxValue) positiveMaxValue else negativeMaxValue
}
// https://app.codility.com/programmers/lessons/6-sorting/number_of_disc_intersections/
// TODO: Refactor this O(N^2) time complexity
fun numberOfDiscIntersections(A: IntArray): Int {
val sortedA = A.withIndex().sortedBy { it.index - it.value }
return sortedA.asSequence().mapIndexed { index, sortedValue ->
val rightEnd = if (sortedValue.index + sortedValue.value >= Int.MAX_VALUE) {
Int.MAX_VALUE
} else {
sortedValue.index + sortedValue.value
}
sortedA.subList(index + 1, A.size).count {
indexedValue ->
rightEnd >= indexedValue.index - indexedValue.value
}
}.reduce { acc, number ->
if (acc > 10000000) return -1
acc + number
}
}
// https://app.codility.com/programmers/lessons/6-sorting/triangle/
fun triangle(A: IntArray): Int {
val windowedA = A.sorted().reversed().windowed(3, 1)
windowedA.forEach {
if (it[0] < it[1] + it[2]) return 1
}
return 0
} | 1 | Java | 25 | 22 | cae1df83ac110519a5f5d6b940fa3e90cebb48c1 | 1,566 | stupid-week-2021 | MIT License |
2k23/aoc2k23/src/main/kotlin/06.kt | papey | 225,420,936 | false | {"Rust": 88237, "Kotlin": 63321, "Elixir": 54197, "Crystal": 47654, "Go": 44755, "Ruby": 24620, "Python": 23868, "TypeScript": 5612, "Scheme": 117} | package d06
import input.read
import kotlin.math.*
fun main() {
println("Part 1: ${part1(read("06.txt"))}")
println("Part 2: ${part2(read("06.txt"))}")
}
fun part1(input: List<String>): Long = input
.map { line -> line.split(" ").mapNotNull { it.toLongOrNull() } }
.let { (a, b) -> a.zip(b) }
.fold(1L) { acc, (time, distance) ->
acc * solve(-time.toDouble(), distance.toDouble())
}
fun part2(input: List<String>): Long = input
.map { line -> line.replace(Regex("^.*:\\s"), "").replace(" ", "").toLong() }
.let { (time, distance) -> solve(-time.toDouble(), distance.toDouble()) }
private fun solve(b: Double, c: Double): Long {
val det = b * b - 4 * c
val r1 = (-b - sqrt(det)) / 2.0
val r2 = (-b + sqrt(det)) / 2.0
val cr1 = ceil(r1)
val cr2 = ceil(r2)
val res = abs(cr1 - cr2).toLong()
return if (cr1 == r1 && cr2 == r2) return res - 1 else res
}
| 0 | Rust | 0 | 3 | cb0ea2fc043ebef75aff6795bf6ce8a350a21aa5 | 924 | aoc | The Unlicense |
day06/kotlin/corneil/src/main/kotlin/solution.kt | timgrossmann | 224,991,491 | true | {"HTML": 2739009, "Python": 169603, "Java": 157274, "Jupyter Notebook": 116902, "TypeScript": 113866, "Kotlin": 89503, "Groovy": 73664, "Dart": 47763, "C++": 43677, "CSS": 34994, "Ruby": 27091, "Haskell": 26727, "Scala": 11409, "Dockerfile": 10370, "JavaScript": 6496, "PHP": 4152, "Go": 2838, "Shell": 2493, "Rust": 2082, "Clojure": 567, "Tcl": 46} | package com.github.corneil.aoc2019.day6
import java.io.File
class OrbitData {
fun addOrbit(obj: String, orbiting: String) {
assert(orbits[orbiting] == null)
orbits[orbiting] = Orbit(
objects[obj] ?: createObj(obj),
objects[orbiting] ?: createObj(orbiting)
)
}
private fun createObj(obj: String): Orbitable {
val o = Orbitable(obj)
objects[obj] = o
return o
}
val objects: MutableMap<String, Orbitable> = mutableMapOf()
val orbits: MutableMap<String, Orbit> = mutableMapOf()
fun findOrbits(obj: String): List<Orbit> {
val orbiting = orbits[obj]
return if(orbiting == null) emptyList() else listOf(orbiting) + findOrbits(orbiting.centre.name)
}
fun findTransfers(start: String, end: String): List<Pair<Orbitable, Orbitable>> {
val startOrbits = findOrbits(start)
val endOrbits = findOrbits(end)
val shared = startOrbits.find { orbit -> endOrbits.find { it == orbit } != null }
requireNotNull(shared) { "Expected a shared orbit" }
val inward = startOrbits.subList(0, startOrbits.indexOf(shared))
val outward = endOrbits.subList(0, endOrbits.indexOf(shared))
val transfers = inward.map { it.orbits to it.centre } + outward.map { it.centre to it.orbits }
return transfers.subList(0, transfers.size - 2)
}
fun findOrbit(obj: String): Orbit {
return orbits[obj] ?: throw Exception("Expected to find $obj orbiting something")
}
}
data class Orbitable(val name: String)
data class Orbit(
val centre: Orbitable,
val orbits: Orbitable
)
fun prepareData(input: String): List<String> {
return input.split('\n').map { it.trim() }.toList()
}
fun loadOrbits(input: List<String>): OrbitData {
val data = OrbitData()
input.forEach { line ->
val items = line.split(')')
data.addOrbit(items[0], items[1])
}
return data
}
fun main(args: Array<String>) {
val fileName = if (args.size > 1) args[0] else "input.txt"
val orbits = loadOrbits(File(fileName).readLines().map { it.trim() })
val allOrbits = orbits.objects.keys.flatMap { orbits.findOrbits(it) }
println("Orbits=${allOrbits.size}")
val you2san = orbits.findTransfers("YOU", "SAN")
println("YOU->SAN=${you2san.size}")
val you = orbits.findOrbit("YOU")
val san = orbits.findOrbit("SAN")
println("YOU=$you")
println("SAN=$san")
val transfer = orbits.findTransfers(you.centre.name, san.centre.name)
println(transfer.map { it.first.name + " -> " + it.second.name }.joinToString("\n"))
println("Transfers=${transfer.size}")
}
| 0 | HTML | 0 | 1 | bb19fda33ac6e91a27dfaea27f9c77c7f1745b9b | 2,671 | aoc-2019 | MIT License |
src/main/java/challenges/leetcode/StringPermutation.kt | ShabanKamell | 342,007,920 | false | null | package challenges.leetcode
/*
Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.
In other words, return true if one of s1's permutations is the substring of s2.
Example 1:
Input: s1 = "ab", s2 = "eidbaooo"
Output: true
Explanation: s2 contains one permutation of s1 ("ba").
Example 2:
Input: s1 = "ab", s2 = "eidboaoo"
Output: false
Constraints:
1 <= s1.length, s2.length <= 104
s1 and s2 consist of lowercase English letters.
https://leetcode.com/problems/permutation-in-string/
*/
object StringPermutation {
private fun checkInclusion(s1: String, s2: String): Boolean {
if (s1.length > s2.length) return false
val s1map = IntArray(26)
val s2map = IntArray(26)
for (i in s1.indices) {
s1map[s1[i] - 'a']++
s2map[s2[i] - 'a']++
}
var count = 0
for (i in 0..25) if (s1map[i] == s2map[i]) count++
for (i in 0 until s2.length - s1.length) {
val r = s2[i + s1.length] - 'a'
val l = s2[i] - 'a'
if (count == 26) return true
s2map[r]++
if (s2map[r] == s1map[r]) count++
else if (s2map[r] == s1map[r] + 1) count--
s2map[l]--
if (s2map[l] == s1map[l]) count++
else if (s2map[l] == s1map[l] - 1) count--
}
return count == 26
}
private fun checkInclusion2(s1: String, s2: String): Boolean {
if (s1.length > s2.length) return false
val s1map = IntArray(26)
val s2map = IntArray(26)
for (i in s1.indices) {
s1map[s1[i] - 'a']++
s2map[s2[i] - 'a']++
}
for (i in 0 until s2.length - s1.length) {
if (matches(s1map, s2map)) return true
s2map[s2[i + s1.length] - 'a']++
s2map[s2[i] - 'a']--
}
return matches(s1map, s2map)
}
private fun matches(s1map: IntArray, s2map: IntArray): Boolean {
for (i in 0..25) {
if (s1map[i] != s2map[i]) return false
}
return true
}
@JvmStatic
fun main(args: Array<String>) {
var s1 = "ab"
var s2 = "eidbaooo"
println("s1 = $s1, s2 = $s2")
println(checkInclusion(s1, s2))
println(checkInclusion2(s1, s2))
s1 = "ab"
s2 = "eidboaoo"
println("s1 = $s1, s2 = $s2")
println(checkInclusion(s1, s2))
println(checkInclusion2(s1, s2))
}
} | 0 | Kotlin | 0 | 0 | ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70 | 2,493 | CodingChallenges | Apache License 2.0 |
2016/main/day_07/Main.kt | Bluesy1 | 572,214,020 | false | {"Rust": 280861, "Kotlin": 94178, "Shell": 996} | package day_07_2016
import java.io.File
fun part1(input: List<String>) {
input.filter {
val hypernets = it.split('[').drop(1).map { it1 -> it1.split(']')[0] }.any {
it1 -> it1.windowed(4).any { it2 -> it2[0] == it2[3] && it2[1] == it2[2] && it2[0] != it2[1] }
}
if (hypernets) false else {
it.split('[').map {
it1 ->
val split = it1.split(']')
if (split.size == 1) split[0] else split[1]
}.any { it1 -> it1.windowed(4).any { it2 -> it2[0] == it2[3] && it2[1] == it2[2] && it2[0] != it2[1] } }
}
}.count().let { print("The number of TLS addresses is $it") }
}
fun part2(input: List<String>) {
input.filter {
val BABs = it.split('[').map {
it1 ->
val split = it1.split(']')
if (split.size == 1) split[0] else split[1]
}.map { it1 -> it1.windowed(3)
.filter { it2 -> it2[0] == it2[2] && it2[0] != it2[1] }
}
.flatten()
.map { aba -> "${aba[1]}${aba[0]}${aba[1]}" }
.toSet()
it.split('[')
.drop(1)
.map { it1 -> it1.split(']')[0] }
.map { it1 -> it1.windowed(3) }
.flatten()
.any { it1 -> it1 in BABs }
}.count().let { print("The number of SSL addresses is $it") }
}
fun main(){
val inputFile = File("2016/inputs/Day_07.txt")
print("\n----- Part 1 -----\n")
part1(inputFile.readLines())
print("\n----- Part 2 -----\n")
part2(inputFile.readLines())
} | 0 | Rust | 0 | 0 | 537497bdb2fc0c75f7281186abe52985b600cbfb | 1,609 | AdventofCode | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaxSubarraySumCircular.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.max
import kotlin.math.min
/**
* 918. Maximum Sum Circular Subarray
* @see <a href="https://leetcode.com/problems/maximum-sum-circular-subarray/">Source</a>
*/
fun interface MaxSubarraySumCircular {
operator fun invoke(nums: IntArray): Int
}
class MaxSubarraySumCircularOnePass : MaxSubarraySumCircular {
override operator fun invoke(nums: IntArray): Int {
var total = 0
var maxSum: Int = nums[0]
var curMax = 0
var minSum: Int = nums[0]
var curMin = 0
for (a in nums) {
curMax = max(curMax + a, a)
maxSum = max(maxSum, curMax)
curMin = min(curMin + a, a)
minSum = min(minSum, curMin)
total += a
}
return if (maxSum > 0) max(maxSum, total - minSum) else maxSum
}
}
class MaxSubarraySumCircularKadane : MaxSubarraySumCircular {
override operator fun invoke(nums: IntArray): Int {
val nonCircularSum = kadaneMaxSum(nums)
var totalSum = 0
for (i in nums.indices) {
totalSum += nums[i]
nums[i] = -nums[i]
}
val circularSum = totalSum + kadaneMaxSum(nums)
return if (circularSum == 0) nonCircularSum else max(circularSum, nonCircularSum)
}
private fun kadaneMaxSum(nums: IntArray): Int {
var currentSum = nums[0]
var maxSum = nums[0]
for (i in 1 until nums.size) {
if (currentSum < 0) currentSum = 0
currentSum += nums[i]
maxSum = max(maxSum, currentSum)
}
return maxSum
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,239 | kotlab | Apache License 2.0 |
src/Day02.kt | stcastle | 573,145,217 | false | {"Kotlin": 24899} | /** Beats is the option that the current one beats. */
enum class PlayOption() {
ROCK,
PAPER,
SCISSORS,
}
fun String.toPlayOption(): PlayOption =
when (this) {
"A",
"X" -> PlayOption.ROCK
"B",
"Y" -> PlayOption.PAPER
"C",
"Z" -> PlayOption.SCISSORS
else -> throw Exception("Expecting A, B, C, X, Y, or Z. Got $this")
}
fun PlayOption.toXYZ(): String =
when (this) {
PlayOption.ROCK -> "X"
PlayOption.PAPER -> "Y"
PlayOption.SCISSORS -> "Z"
}
fun PlayOption.beats(): PlayOption =
when (this) {
PlayOption.ROCK -> PlayOption.SCISSORS
PlayOption.PAPER -> PlayOption.ROCK
PlayOption.SCISSORS -> PlayOption.PAPER
}
fun PlayOption.beats(other: PlayOption): Boolean = this.beats() == other
fun String.whatDoIPlay(theirs: PlayOption): PlayOption =
when (this) {
// Lose
"X" -> theirs.beats()
// Draw
"Y" -> theirs
// Win
"Z" -> theirs.beats().beats() // Trick of the cycle
else -> throw Exception("Expecting X, Y, or Z. Got $this.")
}
/** Score for what you played. */
fun baseScore(p: PlayOption): Int =
when (p) {
PlayOption.ROCK -> 1
PlayOption.PAPER -> 2
PlayOption.SCISSORS -> 3
}
/** Score for losing, winning, or drawing. */
fun gameScore(theirs: PlayOption, mine: PlayOption): Int {
// Draw.
if (theirs == mine) {
return 3
}
// Win.
if (mine.beats(theirs)) {
return 6
}
// Loss.
return 0
}
fun main() {
fun part1(input: List<String>): Int =
input.fold(initial = 0) { score: Int, line: String ->
val plays: List<String> = line.split(" ")
assert(plays.size == 2)
val theirs: PlayOption = plays.first().toPlayOption()
val mine = plays.last().toPlayOption()
score + baseScore(mine) + gameScore(theirs, mine)
}
fun part2(input: List<String>): Int {
val newPlays =
input.map { line ->
val plays: List<String> = line.split(" ")
assert(plays.size == 2)
val theirs = plays.first().toPlayOption()
val mine = plays.last().whatDoIPlay(theirs)
listOf<String>(theirs.toXYZ(), mine.toXYZ()).joinToString(" ")
}
return part1(newPlays)
}
val day = "02"
val testInput = readInput("Day${day}_test")
println("Part 1 test = ${part1(testInput)}")
val input = readInput("Day${day}")
println("part1 = ${part1(input)}")
println("Part 2 test = ${part2(testInput)}")
println("part2 = ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 746809a72ea9262c6347f7bc8942924f179438d5 | 2,544 | aoc2022 | Apache License 2.0 |
src/Day03.kt | RusticFlare | 574,508,778 | false | {"Kotlin": 78496} | fun main() {
val alphabet = "abcdefghijklmnopqrstuvwxyz"
val score = (" " + alphabet + alphabet.uppercase()).toList()
fun Char.priority() = score.indexOf(this)
fun part1(input: List<String>): Int {
return input.sumOf {
val mid = it.length / 2
val first = it.substring(0 until mid).asIterable()
val second = it.substring(startIndex = mid).toSet()
(first intersect second).single().priority()
}
}
fun part2(input: List<String>): Int {
return input.chunked(3).sumOf { elves ->
elves.map { it.toSet() }
.reduce(Set<Char>::intersect)
.single()
.priority()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readLines("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readLines("Day03")
check(part1(input) == 7980)
println(part1(input))
check(part2(input) == 2881)
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 10df3955c4008261737f02a041fdd357756aa37f | 1,067 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day09.kt | carloxavier | 574,841,315 | false | {"Kotlin": 14082} | import kotlin.math.absoluteValue
fun main() {
check(simulateHeadTailMovements(readInput("Day09_test")).size == 13)
// Part1
println(simulateHeadTailMovements(readInput("Day09")).size)
}
private fun simulateHeadTailMovements(inputMoves: List<String>): HashSet<Position> {
val tailPositions = hashSetOf(Position(0, 0))
var currentHeadPosition = Position(0, 0)
var currentTailPosition = Position(0, 0)
inputMoves.forEach {
val (movement, distance) = it.toMovement()
repeat(distance) {
val prevHeadPosition = currentHeadPosition
currentHeadPosition = currentHeadPosition.move(movement)
if (currentTailPosition.isFarFrom(currentHeadPosition)) {
currentTailPosition = prevHeadPosition
tailPositions.add(currentTailPosition)
}
}
}
return tailPositions
}
private fun String.toMovement(): Pair<Movement, Int> {
val (move, distance) = this.split(" ")
return when (move) {
"R" -> Pair(Movement.Right, distance.toInt())
"L" -> Pair(Movement.Left, distance.toInt())
"D" -> Pair(Movement.Down, distance.toInt())
"U" -> Pair(Movement.Up, distance.toInt())
else -> throw Exception()
}
}
private data class Position(val posX: Int, val posY: Int)
private fun Position.isFarFrom(position: Position): Boolean =
(this.posX - position.posX).absoluteValue > 1 || (this.posY - position.posY).absoluteValue > 1
private fun Position.move(move: Movement): Position = when (move) {
Movement.Right -> Position(posX + 1, posY)
Movement.Down -> Position(posX, posY - 1)
Movement.Left -> Position(posX - 1, posY)
Movement.Up -> Position(posX, posY + 1)
}
private enum class Movement {
Left, Right, Down, Up,
} | 0 | Kotlin | 0 | 0 | 4e84433fe866ce1a8c073a7a1e352595f3ea8372 | 1,803 | adventOfCode2022 | Apache License 2.0 |
app/src/main/kotlin/com/bloidonia/advent2020/Day_07.kt | timyates | 317,965,519 | false | null | package com.bloidonia.advent2020
import com.bloidonia.linesFromResource
class Day_07(input: List<String>) {
data class Bag(val quantity: Int, val color: String)
// Split the sentences into bag colours and numbers
fun tokenize(input: String) =
input.split("bag[s]?|contain|,|\\.|no other".toRegex()).map { it.trim() }.filter(String::isNotEmpty)
// Given a string generate a map entry with a colour key, and a list of bags and quantities as values
fun toEntry(input: String): Pair<String, List<Bag>> {
val tokens = tokenize(input)
return tokens[0] to tokens.drop(1).map { toBag(it) }
}
// parse a "9 wee yellow" string into a quantity and colour
private fun toBag(numberAndColor: String): Bag {
return "(\\d+) (.+)".toRegex().matchEntire(numberAndColor)!!.groupValues.let {
Bag(it[1].toInt(), it[2])
}
}
// Take the string of rules, and build a big map from it
private val bagMap = input.map { toEntry(it) }.toMap()
// look through the map, and return a list of the colours of all bags that contain bags of the required color
private fun colourOfBagsContaining(color: String) =
bagMap.filter { bagEntry -> bagEntry.value.map { it.color }.contains(color) }.map { it.key }
// starting at a color, find all bags that contain it. Then find all bags that contain them. Keep going till we've not more bags to look for
fun walkColorsBackwards(color: String): Set<String> {
val result = mutableSetOf<String>()
colourOfBagsContaining(color).let { bagNames ->
result.addAll(bagNames)
var queueToCheck = bagNames
while (queueToCheck.isNotEmpty()) {
queueToCheck = queueToCheck.map(this::colourOfBagsContaining).flatten().filter { it !in result }
result.addAll(queueToCheck)
}
return result
}
}
// given a bag color, recursively look how many bags are inside it
fun bagCount(color: String): Int =
bagMap[color]!!.map { it.quantity + (it.quantity * bagCount(it.color)) }.sum()
}
fun main() {
val day07 = Day_07(linesFromResource("/7.txt"))
val result = day07.walkColorsBackwards("shiny gold")
println(result.size)
println(day07.bagCount("shiny gold"))
} | 0 | Kotlin | 0 | 0 | cab3c65ac33ac61aab63a1081c31a16ac54e4fcd | 2,326 | advent-of-code-2020-kotlin | Apache License 2.0 |
src/day14/Day14.kt | andreas-eberle | 573,039,929 | false | {"Kotlin": 90908} | package day14
import readInput
const val day = "14"
fun main() {
fun calculatePart1Score(input: List<String>): Int {
val allLines = input.map { line ->
line.split(" -> ")
.map { it.split(",") }
.map { (x, y) -> Coordinate(x.toInt(), y.toInt()) }
.map { Coordinate(it.x, it.y) }
.windowed(2)
.map { (p1, p2) -> p1 to p2 }
}
.flatten()
val allCoordinates = allLines.flatMap { listOf(it.first, it.second) }
val minX = allCoordinates.minOf { it.x }
val maxX = allCoordinates.maxOf { it.x }
val maxY = allCoordinates.maxOf { it.y }
val offsetLines = allLines.map { (p1, p2) -> Coordinate(p1.x - minX, p1.y) to Coordinate(p2.x - minX, p2.y) }
val height = maxY + 1
val width = maxX - minX + 1
val map = List(height) { MutableList(width) { false } }
offsetLines.forEach { (p1, p2) ->
Line(p1, p2).points.forEach { map[it] = true }
}
val sandSpawn = Coordinate(500 - minX, 0)
var sandCounter = 0
try {
while (true) {
var sandLocation = sandSpawn.copy()
while (true) {
when {
!map[sandLocation.down] -> sandLocation = sandLocation.down
!map[sandLocation.leftDiagonal] -> sandLocation = sandLocation.leftDiagonal
!map[sandLocation.rightDiagonal] -> sandLocation = sandLocation.rightDiagonal
else -> {
map[sandLocation] = true
break
}
}
}
sandCounter++
}
} catch (e: IndexOutOfBoundsException) {
}
return sandCounter
}
fun calculatePart2Score(input: List<String>): Int {
val initialLines = input.map { line ->
line.split(" -> ")
.map { it.split(",") }
.map { (x, y) -> Coordinate(x.toInt(), y.toInt()) }
.map { Coordinate(it.x, it.y) }
.windowed(2)
.map { (p1, p2) -> p1 to p2 }
}
.flatten()
val allInitialPoints = initialLines.flatMap { listOf(it.first, it.second) }
val initialMaxY = allInitialPoints.maxOf { it.y }
val initialMinX = allInitialPoints.minOf { it.x }
val initialMaxX = allInitialPoints.maxOf { it.x }
val allLines = initialLines + listOf(Coordinate(initialMinX - 300, initialMaxY + 2) to Coordinate(initialMaxX + 300, initialMaxY + 2))
val allCoordinates = allLines.flatMap { listOf(it.first, it.second) }
val minX = allCoordinates.minOf { it.x }
val maxX = allCoordinates.maxOf { it.x }
val maxY = allCoordinates.maxOf { it.y }
val offsetLines = allLines.map { (p1, p2) -> Coordinate(p1.x - minX, p1.y) to Coordinate(p2.x - minX, p2.y) }
val height = maxY + 1
val width = maxX - minX + 1
val map = List(height) { MutableList(width) { false } }
offsetLines.forEach { (p1, p2) ->
Line(p1, p2).points.forEach { map[it] = true }
}
val sandSpawn = Coordinate(500 - minX, 0)
var sandCounter = 0
while (true) {
var sandLocation = sandSpawn.copy()
while (true) {
when {
!map[sandLocation.down] -> sandLocation = sandLocation.down
!map[sandLocation.leftDiagonal] -> sandLocation = sandLocation.leftDiagonal
!map[sandLocation.rightDiagonal] -> sandLocation = sandLocation.rightDiagonal
else -> {
map[sandLocation] = true
if (sandLocation == sandSpawn) {
return sandCounter + 1
}
break
}
}
}
sandCounter++
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("/day$day/Day${day}_test")
val input = readInput("/day$day/Day${day}")
val part1TestPoints = calculatePart1Score(testInput)
val part1points = calculatePart1Score(input)
println("Part1 test points: $part1TestPoints")
println("Part1 points: $part1points")
check(part1TestPoints == 24)
val part2TestPoints = calculatePart2Score(testInput)
val part2points = calculatePart2Score(input)
println("Part2 test points: \n$part2TestPoints")
println("Part2 points: \n$part2points")
check(part2TestPoints == 93)
}
operator fun <T> List<List<T>>.get(coordinate: Coordinate): T {
return this[coordinate.y][coordinate.x]
}
operator fun <T> List<MutableList<T>>.set(coordinate: Coordinate, value: T) {
this[coordinate.y][coordinate.x] = value
}
data class Line(val p1: Coordinate, val p2: Coordinate) {
val points: List<Coordinate>
get() = ((p1.y..p2.y) + (p2.y..p1.y)).distinct().flatMap { y ->
((p1.x..p2.x) + (p2.x..p1.x)).distinct().map { x ->
Coordinate(x, y)
}
}
}
data class Coordinate(val x: Int, val y: Int) {
val down: Coordinate
get() = Coordinate(x, y + 1)
val leftDiagonal: Coordinate
get() = Coordinate(x - 1, y + 1)
val rightDiagonal: Coordinate
get() = Coordinate(x + 1, y + 1)
} | 0 | Kotlin | 0 | 0 | e42802d7721ad25d60c4f73d438b5b0d0176f120 | 5,552 | advent-of-code-22-kotlin | Apache License 2.0 |
src/Day03.kt | Allagash | 572,736,443 | false | {"Kotlin": 101198} | // Day 03, Advent of Code 2022, Rucksack Reorganization
fun main() {
fun getScore(input: Char) =
when (input) {
in 'a'..'z' -> input.code - 'a'.code + 1
in 'A'..'Z' -> input.code - 'A'.code + 27
else -> {
check(false)
-100000
}
}
fun part1(input: List<String>): Int {
var total = 0
input.forEach {
val size = it.length
val first = it.substring(0, size / 2).toSet()
val second = it.substring(size / 2).toSet()
val intersect = first.intersect(second)
//println(intersect)
check(intersect.size == 1)
total += getScore(intersect.first())
}
return total
}
fun part2(input: List<String>): Int {
val chunks = input.chunked(3)
var total = 0
chunks.forEach {
val set1 = it[0].toSet()
val set2 = it[1].toSet()
val set3 = it[2].toSet()
val intersect = set1.intersect(set2).intersect(set3)
//println(intersect)
check(intersect.size == 1)
total += getScore(intersect.first())
}
return total
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8d5fc0b93f6d600878ac0d47128140e70d7fc5d9 | 1,519 | AdventOfCode2022 | Apache License 2.0 |
src/Day10.kt | wujingwe | 574,096,169 | false | null | object Day10 {
private fun ops(inputs: List<String>): List<Int> {
return inputs.flatMap { s ->
val tokens = s.split(" ")
when (tokens[0]) {
"noop" -> listOf(0)
"addx" -> listOf(0, tokens[1].toInt())
else -> emptyList()
}
}.runningFold(1) { acc, elem -> acc + elem }
}
fun part1(inputs: List<String>): Int {
val res = ops(inputs)
return (20..220 step 40).sumOf { it * res[it - 1] }
}
fun part2(inputs: List<String>): String {
return ops(inputs).filterIndexed { index, _ ->
index < 240
}.foldIndexed(StringBuilder()) { index, acc, x ->
val position = index % 40
val c = if (position in x - 1..x + 1) '#' else '.'
acc.append(c)
}.toString()
}
}
fun main() {
fun part1(inputs: List<String>): Int {
return Day10.part1(inputs)
}
fun part2(inputs: List<String>): String {
return Day10.part2(inputs)
}
val testInput = readInput("../data/Day10_test")
check(part1(testInput) == 13140)
part2(testInput).chunked(40).forEach {
println(it)
}
val image =
"##..##..##..##..##..##..##..##..##..##.." +
"###...###...###...###...###...###...###." +
"####....####....####....####....####...." +
"#####.....#####.....#####.....#####....." +
"######......######......######......####" +
"#######.......#######.......#######....."
check(part2(testInput) == image)
val input = readInput("../data/Day10")
println(part1(input))
part2(input).chunked(40).forEach {
println(it)
}
}
| 0 | Kotlin | 0 | 0 | a5777a67d234e33dde43589602dc248bc6411aee | 1,711 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/Day02/Day02.kt | brhliluk | 572,914,305 | false | {"Kotlin": 16006} | fun main() {
fun part1(input: List<String>) = input.map {
MyMove.byLetter(it[2])!!.getFightResult(OponentMove.byLetter(it[0])!!) + MyMove.byLetter(it[2])!!.value
}.reduce { acc, result -> acc + result }
fun part2(input: List<String>) = input.map {
val oponentMove = OponentMove.byLetter(it[0])!!
val myMove = FightResult.byLetter(it[2])!!.getRequiredMove(oponentMove)
myMove.getFightResult(oponentMove) + myMove.value
}.reduce { acc, result -> acc + result }
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
enum class OponentMove(val letter: Char) {
ROCK('A'), PAPER('B'), SCISSORS('C');
companion object {
fun byLetter(letter: Char) = values().firstOrNull { it.letter == letter }
}
}
enum class MyMove(val letter: Char, val value: Int) {
ROCK('X', 1), PAPER('Y', 2), SCISSORS('Z', 3);
fun getFightResult(oponentMove: OponentMove) : Int {
return when (this) {
ROCK -> when (oponentMove) {
OponentMove.ROCK -> 3
OponentMove.PAPER -> 0
OponentMove.SCISSORS -> 6
}
PAPER -> when (oponentMove) {
OponentMove.ROCK -> 6
OponentMove.PAPER -> 3
OponentMove.SCISSORS -> 0
}
SCISSORS -> when (oponentMove) {
OponentMove.ROCK -> 0
OponentMove.PAPER -> 6
OponentMove.SCISSORS -> 3
}
}
}
companion object {
fun byLetter(letter: Char) = values().firstOrNull { it.letter == letter }
}
}
enum class FightResult(val letter: Char) {
LOOSE('X'), DRAW('Y'), WIN('Z');
fun getRequiredMove(oponentMove: OponentMove) = when (this) {
WIN -> when (oponentMove) {
OponentMove.ROCK -> MyMove.PAPER
OponentMove.PAPER -> MyMove.SCISSORS
OponentMove.SCISSORS -> MyMove.ROCK
}
DRAW -> when (oponentMove) {
OponentMove.ROCK -> MyMove.ROCK
OponentMove.PAPER -> MyMove.PAPER
OponentMove.SCISSORS -> MyMove.SCISSORS
}
LOOSE -> when (oponentMove) {
OponentMove.ROCK -> MyMove.SCISSORS
OponentMove.PAPER -> MyMove.ROCK
OponentMove.SCISSORS -> MyMove.PAPER
}
}
companion object {
fun byLetter(letter: Char) = values().firstOrNull { it.letter == letter }
}
} | 0 | Kotlin | 0 | 0 | 96ac4fe0c021edaead8595336aad73ef2f1e0d06 | 2,482 | kotlin-aoc | Apache License 2.0 |
src/Day20.kt | Riari | 574,587,661 | false | {"Kotlin": 83546, "Python": 1054} | fun main() {
val magicIndices = listOf(1000, 2000, 3000)
fun solve(input: List<String>, key: Long = 1, iterations: Int = 1): Long {
val sequence = input.map { it.toInt() * key }.withIndex().toMutableList()
repeat (iterations) {
for (originalIndex in sequence.indices) {
val index = sequence.indexOfFirst { it.index == originalIndex }
val number = sequence.removeAt(index)
sequence.add((index + number.value).mod(sequence.size), number)
}
}
val zeroIndex = sequence.indexOfFirst { it.value == 0L }
return magicIndices.sumOf { sequence[(zeroIndex + it) % sequence.size].value }
}
fun part1(input: List<String>): Long {
return solve(input)
}
fun part2(input: List<String>): Long {
return solve(input, 811589153, 10)
}
val testInput = readInput("Day20_test")
check(part1(testInput) == 3L)
check(part2(testInput) == 1623178306L)
val input = readInput("Day20")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8eecfb5c0c160e26f3ef0e277e48cb7fe86c903d | 1,088 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2023/2023-25.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2023
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputLines
import kotlin.time.measureTime
fun main() {
val input = readInputLines(2023, "25-input")
val test1 = readInputLines(2023, "25-test1")
println("Part1:")
part1(test1).println()
measureTime {
part1(input).println()
}.println()
}
private fun part1(input: List<String>): Int {
val nodes = mutableMapOf<String, MutableSet<String>>()
input.forEach {
val (src, dests) = it.split(": ")
dests.split(' ').forEach { dest ->
nodes.getOrPut(src, defaultValue = { mutableSetOf() }) += dest
nodes.getOrPut(dest, defaultValue = { mutableSetOf() }) += src
}
}
val list = nodes.keys.toList()
val vector = List(list.size) { row ->
MutableList(list.size) { col -> if (list[col] in nodes[list[row]]!!) 1 else 0 }
}
val half = globalMinCut(vector)
return half * (list.size - half)
}
private fun globalMinCut(mat: List<MutableList<Int>>): Int {
val n = mat.size
val co = List(n) { mutableListOf(it) }
for (phase in 1 ..< n) {
val w = mat[0].toMutableList()
var s = 0
var t = 0
repeat(n - phase) {
w[t] = Int.MIN_VALUE
s = t
t = w.indices.maxBy { w[it] }
for (i in 0 ..< n) {
w[i] += mat[t][i]
}
}
val cut = w[t] - mat[t][t]
if (cut == 3) {
return co[t].size
}
co[s] += co[t]
for (i in 0 ..< n) mat[s][i] += mat[t][i]
for (i in 0 ..< n) mat[i][s] = mat[s][i]
mat[0][t] = Int.MIN_VALUE
}
error("not 3?")
}
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 1,770 | advent-of-code | MIT License |
src/main/kotlin/dec5/Main.kt | dladukedev | 318,188,745 | false | null | package dec5
import java.lang.Exception
import kotlin.math.ceil
import kotlin.math.floor
data class BoardingPassDirections(
val rowDirections: List<Direction>,
val seatDirections: List<Direction>
)
data class BoardingPass(
val row: Int,
val seat: Int
)
enum class Direction {
FRONT,
BACK,
LEFT,
RIGHT
}
fun getLocationIndex(directions: List<Direction>, min: Int, max: Int): Int {
val index = directions.fold(Pair(min, max)){ acc, direction ->
val accMin = acc.first
val accMax = acc.second
val accMidCeil = ceil(((accMin + accMax) / 2.0)).toInt()
val accMidFloor = floor(((accMin + accMax) / 2.0)).toInt()
when(direction) {
Direction.LEFT, Direction.FRONT -> Pair(accMin, accMidFloor)
Direction.BACK, Direction.RIGHT -> Pair(accMidCeil, accMax)
}
}
return when(directions.last()) {
Direction.LEFT, Direction.FRONT -> index.first
Direction.BACK, Direction.RIGHT -> index.second
}
}
fun getLocation(boardingPassDirections: BoardingPassDirections): BoardingPass {
val row = getLocationIndex(boardingPassDirections.rowDirections, 0, 127)
val seat = getLocationIndex(boardingPassDirections.seatDirections, 0, 7)
return BoardingPass(row, seat)
}
fun getBoardingPassFromInput(directionList: String): BoardingPassDirections {
val rowChunk = directionList.substring(0, 7)
val seatChunk = directionList.substring(7)
val rowDirections = rowChunk.map {
when(it) {
'F' -> Direction.FRONT
'B' -> Direction.BACK
else -> throw Exception("Invalid Row Direction: $it")
}
}
val seatDirections = seatChunk.map {
when(it) {
'R' -> Direction.RIGHT
'L' -> Direction.LEFT
else -> throw Exception("Invalid Seat Direction: $it")
}
}
return BoardingPassDirections(
rowDirections,
seatDirections
)
}
fun findMissingSeat(seatIds: List<Int>): Int {
val min = seatIds.min() ?: throw Exception("Set Contains no Minimum")
val max = seatIds.max() ?: throw Exception("Set Contains no Maximum")
val missingSeatIds = (min..max).filter {
!seatIds.contains(it) && seatIds.contains(it+1) && seatIds.contains(it-1)
}
return missingSeatIds.single()
}
fun main() {
val boardingPasses = input.map { getBoardingPassFromInput(it) }
val seatIds = boardingPasses.map { getLocation(it) }
.map { (it.row * 8) + it.seat }
println("------------ PART 1 ------------")
val seatId = seatIds.max()
println("result: $seatId")
println("------------ PART 1 ------------")
println(findMissingSeat(seatIds))
} | 0 | Kotlin | 0 | 0 | d4591312ddd1586dec6acecd285ac311db176f45 | 2,729 | advent-of-code-2020 | MIT License |
src/main/kotlin/com/jacobhyphenated/advent2022/day4/Day4.kt | jacobhyphenated | 573,603,184 | false | {"Kotlin": 144303} | package com.jacobhyphenated.advent2022.day4
import com.jacobhyphenated.advent2022.Day
// Use type aliases to avoid repeatedly writing a bunch of Pair<> types
typealias Section = Pair<Int,Int>
typealias SectionGroup = Pair<Section, Section>
/**
* Day 4: Camp Cleanup
*
* Each group of two elves is assigned 2 sections to clean. Sometimes those sections overlap.
*
* Each group is represented by two "sections" which are Pair<Int,Int>
* The pair's first value is the low value and the second is the high value of the range covered by the section
*/
class Day4: Day<List<SectionGroup>> {
override fun getInput(): List<SectionGroup> {
return readInputFile("day4").lines()
.map {
val (group1, group2) = it
.split(",")
.map { range ->
val (low, high) = range.split("-").map { num -> num.toInt() }
Pair(low, high)
}
Pair(group1, group2)
}
}
/**
* Find groups where one section is completely inside the other section
* Return the count of groups that have such overlap
*/
override fun part1(input: List<SectionGroup>): Number {
return input.count {
val (group1, group2) = it
// A section is contained inside another if:
// The low value is greater than or equal to the other low and
// the high value is less than or equal to the other high value
// Do this in both directions
(group1.first >= group2.first && group1.second <= group2.second) ||
(group2.first >= group1.first && group2.second <= group1.second)
}
}
/**
* Find groups where there is any overlap at all and return the count of those groups.
*/
override fun part2(input: List<SectionGroup>): Number {
return input.count {
val (group1, group2) = it
// Similar to part one, except we only need to check if the low value is between the other's low and high
(group1.first >= group2.first && group1.first <= group2.second) ||
(group2.first >= group1.first && group2.first <= group1.second)
}
}
}
| 0 | Kotlin | 0 | 0 | 9f4527ee2655fedf159d91c3d7ff1fac7e9830f7 | 2,268 | advent2022 | The Unlicense |
src/Day04.kt | rod41732 | 728,131,475 | false | {"Kotlin": 26028} | /**
* You can edit, run, and share this code.
* play.kotlinlang.org
*/
fun main() {
val testInput = readInput("Day04_test")
val input = readInput("Day04")
fun part1(input: List<String>): Int {
return input
.map {
val (winnings, owned) = it.substringAfter(":").split("|").map {
it.trim().split(" ").filter { !it.isBlank() }.map { it.toInt() }
}
val cnt = owned.count { winnings.contains(it) }
if (cnt == 0) {
0
} else {
1 shl (cnt - 1)
}
}.sum()
}
fun part2(input: List<String>): Int {
val matches = input
.map {
val (winnings, owned) = it.substringAfter(":").split("|").map {
it.trim().split(" ").filter { !it.isBlank() }.map { it.toInt() }
}
val cnt = owned.count { winnings.contains(it) }
cnt
}.toList()
val counts = MutableList(matches.size) { 1 }
matches.forEachIndexed { idx, match ->
(1..match).forEach {
counts[idx + it] += counts[idx]
}
}
return counts.sum()
}
assertEqual(part1(testInput), 13)
assertEqual(part2(testInput), 30)
println("Part1: ${part1((input))}")
println("Part2: ${part2((input))}")
}
| 0 | Kotlin | 0 | 0 | 05a308a539c8a3f2683b11a3a0d97a7a78c4ffac | 1,438 | aoc-23 | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem1235/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem1235
import kotlin.math.max
/**
* LeetCode page: [1235. Maximum Profit in Job Scheduling](https://leetcode.com/problems/maximum-profit-in-job-scheduling/);
*/
class Solution {
/* Complexity:
* Time O(NLogN) and Space O(N) where N is the size of startTime/endTime/profit;
*/
fun jobScheduling(startTime: IntArray, endTime: IntArray, profit: IntArray): Int {
val sortedJobs = MutableList(startTime.size) {
Job(startTime[it], endTime[it], profit[it])
}.apply { sortBy { it.start } }
// dp[i]::= the maximum profit by scheduling the jobs in sortedJobs[i: ]
val dp = IntArray(sortedJobs.size + 1)
for (i in profit.indices.reversed()) {
val profitIfSkip = dp[i + 1]
val profitIfPick = sortedJobs[i].profit +
dp[sortedJobs.binarySearchLeftBy(sortedJobs[i].end) { it.start }]
dp[i] = max(profitIfSkip, profitIfPick)
}
return dp.max()
}
private data class Job(val start: Int, val end: Int, val profit: Int)
private fun <T, K : Comparable<K>> List<T>.binarySearchLeftBy(
target: K,
fromIndex: Int = 0,
untilIndex: Int = size,
selector: (T) -> K,
): Int {
if (target <= selector(this[fromIndex])) {
return fromIndex
}
if (target > selector(this[untilIndex - 1])) {
return untilIndex
}
var left = fromIndex
var right = untilIndex - 1
while (left < right) {
val mid = (left + right) ushr 1
val value = selector(this[mid])
if (value < target) {
left = mid + 1
} else {
right = mid
}
}
return left
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,816 | hj-leetcode-kotlin | Apache License 2.0 |
src/Day10.kt | wmichaelshirk | 573,031,182 | false | {"Kotlin": 19037} |
fun main() {
fun part1(input: List<String>): Int {
val computation = sequence {
var x = 1
var cycle = 1
for (instruction in input) {
val splitInstruction = instruction.split(" ")
val op = splitInstruction.first()
val arg = splitInstruction.last()
if (op == "addx") {
yield(cycle to x)
cycle += 1
yield(cycle to x)
cycle += 1
x += arg.toInt()
} else {
yield(cycle to x)
cycle += 1
}
}
}
val signalSum = computation
.drop(19)
.windowed(1, 40, true)
.take(6)
.map {
val pair = it.first()
pair.first * pair.second
}
.sum()
return signalSum
}
fun part2(input: List<String>): Int {
val computation = sequence {
var x = 1
var cycle = 1
for (instruction in input) {
val splitInstruction = instruction.split(" ")
val op = splitInstruction.first()
val arg = splitInstruction.last()
if (op == "addx") {
yield(cycle to x)
cycle += 1
yield(cycle to x)
cycle += 1
x += arg.toInt()
} else {
yield(cycle to x)
cycle += 1
}
}
}
computation.forEach {
val (cycle, x) = it
val col = (cycle - 1) % 40
val sprite = x-1 .. x+1
if ((cycle - 1) % 40 == 0) {
print("\n")
}
if (col in sprite) {
print("#")
} else {
print(".")
}
}
return 1
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
check(part2(testInput) == 1)
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 2 | b748c43e9af05b9afc902d0005d3ba219be7ade2 | 2,307 | 2022-Advent-of-Code | Apache License 2.0 |
src/aoc2022/Day19_.kt | RobertMaged | 573,140,924 | false | {"Kotlin": 225650} | package aoc2022
import utils.checkEquals
import utils.sendAnswer
//
//private sealed class Goods{
// data class ORE(val oreCost: Int) : Goods()
// data class CLAY(val oreCost: Int) : Goods()
// data class OBSIDIAN(val oreCost: Int, val clayCost: Int) : Goods()
// data class GEODE(val oreCost: Int, val obsidianCost: Int) : Goods()
// companion object {
// fun values(): Array<Goods> {
// return arrayOf(ORE, CLAY, OBSIDIAN, GEODE)
// }
//
// fun valueOf(value: String): Goods {
// return when (value) {
// "ORE" -> ORE
// "CLAY" -> CLAY
// "OBSIDIAN" -> OBSIDIAN
// "GEODE" -> GEODE
// else -> throw IllegalArgumentException("No object Goods.$value")
// }
// }
// }
//}
//private fun Goods.of(oreCost: Int, clayCost: Int, obsedianOreCost: Int, obsedianClayCost: Int, geodeOreConst: Int, geode)
//private val startingRobots = Goods.values().associate { it.toString() to if(it == Goods.ORE) 1 else 0 }
//private data class Blueprint(val id: Int, val robotCosts: Map<String, Goods>, val workingRobots: MutableMap<String, Int> = startingRobots.toMutableMap(), val goods: MutableMap<String, Int>)
fun main() {
fun part1(input: List<String>): Int {
return input.withIndex().sumOf { (blueprintIndex, line) ->
val id = blueprintIndex +1
val robots = line.dropWhile { it != 'E' }.split(". ")
val oreCost = robots[0].substringAfter("costs ").first().digitToInt()
val clayCost = robots[1].substringAfter("costs ").first().digitToInt()
val obsidianCostOre = robots[2].substringAfter("costs ").first().digitToInt()
val obsidianCostClay = robots[2].substringAfter("and ").takeWhile { it.isDigit() }.toInt()
val geodeOreCost = robots[3].substringAfter("costs ").first().digitToInt()
val geodeObsidianCost = robots[3].substringAfter("and ").takeWhile { it.isDigit() }.toInt()
var (oreRobs, clayRobs, obsidianRobs, geodeRobs) = listOf(1, 0, 0, 0)
var (oreCount, clayCount, obsidianCount, geodeCount) = listOf(0, 0, 0, 0)
var minutes = 1
repeat(24){
val robFactory: () -> Unit = when{
oreCount >= geodeOreCost && obsidianCount >= geodeObsidianCost ->{
oreCount-= geodeOreCost
obsidianCount -= geodeObsidianCost
{ geodeRobs++ }
}
oreCount >= obsidianCostOre && clayCount >= obsidianCostClay ->{
oreCount-= obsidianCostOre
clayCount -= obsidianCostClay
{ clayRobs++ }
}
oreCount >= clayCost -> {
oreCount -= clayCost
{ clayRobs++ }
}
oreCount >= oreCost -> {
oreCount-= oreCost
{ oreRobs++ }
}
else -> {{}}
}
repeat(oreRobs){
oreCount++
}
repeat(clayRobs){
clayCount++
}
repeat(obsidianRobs){
obsidianCount++
}
repeat(geodeRobs){
geodeCount++
}
robFactory()
val x = 0
}
id * geodeCount
}
// return input.size
}
fun part2(input: List<String>): Int {
return input.size
}
// parts execution
val testInput = readInput("Day19_test")
val input = readInput("Day19")
part1(testInput).checkEquals(33)
part1(input)
.sendAnswer(part = 1, day = "19", year = 2022)
part2(testInput).checkEquals(TODO())
part2(input)
.sendAnswer(part = 2, day = "19", year = 2022)
}
| 0 | Kotlin | 0 | 0 | e2e012d6760a37cb90d2435e8059789941e038a5 | 3,942 | Kotlin-AOC-2023 | Apache License 2.0 |
src/main/kotlin/io/combination/CombinationSumII.kt | jffiorillo | 138,075,067 | false | {"Kotlin": 434399, "Java": 14529, "Shell": 465} | package io.combination
import io.utils.runTests
// https://leetcode.com/problems/combination-sum-ii/
class CombinationSumII {
fun execute(input: IntArray, target: Int): List<List<Int>> {
val validValues = input.filter { it <= target }
if (validValues.isEmpty()) return emptyList()
val result = mutableSetOf<List<Int>>()
var values = validValues.indices.map { listOf(it) }
while (values.isNotEmpty()) {
result.addAll(values
.map { list -> list.map { validValues[it] } }
.filter { it.sum() == target }
.map { it.sorted() })
values = values.flatMap { list ->
validValues.indices.mapNotNull { index ->
if (index !in list && list.fold(validValues[index]) { acc, i -> acc + validValues[i] } <= target) {
(list + index).sorted()
} else null
}
}.distinct()
}
return result.toList()
}
}
fun main() {
runTests(listOf(
Triple(intArrayOf(10, 1, 2, 7, 6, 1, 5), 8, setOf(listOf(1, 7), listOf(1, 2, 5), listOf(2, 6), listOf(1, 1, 6))),
Triple(intArrayOf(14, 6, 25, 9, 30, 20, 33, 34, 28, 30, 16, 12, 31, 9, 9, 12, 34, 16, 25, 32, 8, 7, 30, 12, 33, 20, 21, 29, 24, 17, 27, 34, 11, 17, 30, 6, 32, 21, 27, 17, 16, 8, 24, 12, 12, 28, 11, 33, 10, 32, 22, 13, 34, 18, 12), 27,
setOf(listOf(6, 6, 7, 8), listOf(6, 7, 14), listOf(6, 8, 13), listOf(6, 9, 12), listOf(6, 10, 11), listOf(6, 21), listOf(7, 8, 12), listOf(7, 9, 11), listOf(7, 20), listOf(8, 8, 11), listOf(8, 9, 10), listOf(9, 9, 9), listOf(9, 18), listOf(10, 17), listOf(11, 16), listOf(13, 14), listOf(27)))
)) { (input, target, value) -> value to CombinationSumII().execute(input, target).toSet() }
} | 0 | Kotlin | 0 | 0 | f093c2c19cd76c85fab87605ae4a3ea157325d43 | 1,703 | coding | MIT License |
src/day07/Day07.kt | palpfiction | 572,688,778 | false | {"Kotlin": 38770} | package day07
import readInput
import java.lang.IllegalArgumentException
sealed class File(val name: String, val parent: Directory?) {
abstract val size: Int
}
class Directory(
name: String,
parent: Directory? = null,
) : File(name, parent) {
var contents: MutableList<File> = mutableListOf()
override val size
get() = contents.sumOf { it.size }
}
class RegularFile(name: String, parent: Directory?, override val size: Int) : File(name, parent)
sealed class Command
class ChangeDirectory(
val destination: String
) : Command()
object ListDirectory : Command()
fun main() {
val commandRegex = """\$ (\w+).?(.+)?""".toRegex()
val regularFileRegex = """(\d+) (.+)""".toRegex()
val directoryRegex = """dir (.+)""".toRegex()
fun isCommand(line: String) = line.matches(commandRegex)
fun parseCommand(line: String): Command {
if (!isCommand(line)) throw IllegalArgumentException()
val (_, type, argument) = commandRegex.find(line)!!.groupValues
return when (type) {
"cd" -> ChangeDirectory(argument)
"ls" -> ListDirectory
else -> throw IllegalArgumentException()
}
}
fun changeDirectory(root: Directory, current: Directory, destination: String) = when (destination) {
"/" -> root
".." -> current.parent
else -> current.contents.filterIsInstance<Directory>().first { it.name == destination }
} ?: throw IllegalArgumentException()
fun parseRegularFile(file: String, current: Directory): RegularFile {
val (_, size, name) = regularFileRegex.find(file)!!.groupValues
return RegularFile(name, current, size.toInt())
}
fun parseDirectory(file: String, current: Directory): Directory {
val (_, name) = directoryRegex.find(file)!!.groupValues
return Directory(name, current)
}
fun parseFile(file: String, current: Directory): File = when {
file.matches(regularFileRegex) -> parseRegularFile(file, current)
file.matches(directoryRegex) -> parseDirectory(file, current)
else -> throw IllegalArgumentException()
}
fun parseFileSystem(input: List<String>): Directory {
val root = Directory("/")
var currentDirectory = root
val directories = mutableListOf(root)
var currentCommand: Command
var index = 0
while (index < input.size) {
currentCommand = parseCommand(input[index])
index++
when (currentCommand) {
is ChangeDirectory -> currentDirectory =
changeDirectory(root, currentDirectory, currentCommand.destination)
is ListDirectory ->
currentDirectory.contents.addAll(
input
.drop(index)
.takeWhile { !isCommand(it) }
.map { parseFile(it, currentDirectory) }
.also { index += it.size }
.also {
directories.addAll(it.filterIsInstance<Directory>())
}
)
}
}
return root
}
fun getDirectories(directory: Directory): List<Directory> {
val directories: List<Directory> = directory.contents.filterIsInstance<Directory>()
return directories.plus(
directories
.map { getDirectories(it) }
.flatten()
)
}
fun part1(input: List<String>): Int =
getDirectories(parseFileSystem(input))
.filter { it.size <= 100_000 }
.sumOf { it.size }
fun part2(input: List<String>): Int {
val root = parseFileSystem(input)
val directories = getDirectories(root)
val unusedSpace = 70_000_000 - root.size
val neededSpace = 30_000_000 - unusedSpace
return directories
.filter { it.size >= neededSpace }
.minByOrNull { it.size }!!
.size
}
val testInput = readInput("/day07/Day07_test")
println(part1(testInput))
println(part2(testInput))
//check(part1(testInput) == 11)
//check(part2(testInput) == 70)
val input = readInput("/day07/Day07")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5b79ec5fa4116e496cd07f0c7cea7dabc8a371e7 | 4,366 | advent-of-code | Apache License 2.0 |
src/leetcodeProblem/leetcode/editor/en/RussianDollEnvelopes.kt | faniabdullah | 382,893,751 | false | null | //You are given a 2D array of integers envelopes where envelopesintArrayOf(i) = intArrayOf(wi, hi)
//represents the width and the height of an envelope.
//
// One envelope can fit into another if and only if both the width and height
//of one envelope are greater than the other envelope's width and height.
//
// Return the maximum number of envelopes you can Russian doll (i.e., put one
//inside the other).
//
// Note: You cannot rotate an envelope.
//
//
// Example 1:
//
//
//Input: envelopes = intArrayOf(intArrayOf(5,4),intArrayOf(6,4),intArrayOf(6,7),intArrayOf(2,3))
//Output: 3
//Explanation: The maximum number of envelopes you can Russian doll is 3 (intArrayOf(2,3)
//=> intArrayOf(5,4) => intArrayOf(6,7)).
//
//
// Example 2:
//
//
//Input: envelopes = intArrayOf(intArrayOf(1,1),intArrayOf(1,1),intArrayOf(1,1))
//Output: 1
//
//
//
// Constraints:
//
//
// 1 <= envelopes.length <= 5000
// envelopesintArrayOf(i).length == 2
// 1 <= wi, hi <= 10⁴
//
// Related Topics Array Binary Search Dynamic Programming Sorting 👍 2606 👎 66
package leetcodeProblem.leetcode.editor.en
import java.util.*
class RussianDollEnvelopes {
fun solution() {
}
//below code will be used for submission to leetcode (using plugin of course)
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun maxEnvelopes(envelopes: Array<IntArray>): Int {
var maxEnvelopes = 1
val dp = IntArray(envelopes.size) { 1 }
Arrays.sort(
envelopes
) { arr1, arr2 -> if (arr1[0] == arr2[0]) arr2[1] - arr1[1] else arr1[0] - arr2[0] }
for (i in 1 until envelopes.size) {
for (j in 0..i) {
if (envelopes[j][0] > envelopes[i][0] && envelopes[j][1] > envelopes[i][1]
&& dp[j] + 1 > dp[i]
) {
dp[i] = dp[j] + 1
} else if (envelopes[j][0] < envelopes[i][0] && envelopes[j][1] < envelopes[i][1] && dp[j] + 1 > dp[i]) {
dp[i] = dp[j] + 1
}
}
maxEnvelopes = maxOf(maxEnvelopes, dp[i])
}
return maxEnvelopes
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
fun main() {
RussianDollEnvelopes.Solution().maxEnvelopes(
arrayOf(
intArrayOf(1, 15),
intArrayOf(7, 18),
intArrayOf(7, 6),
intArrayOf(7, 100),
// 3 , 5 ?
intArrayOf(2, 200), //
intArrayOf(17, 30), // 4
intArrayOf(17, 45), // 5
intArrayOf(3, 5),
intArrayOf(7, 8),
intArrayOf(3, 6),
intArrayOf(3, 10),
intArrayOf(7, 20),
intArrayOf(17, 3),
intArrayOf(17, 45)
)
)
}
| 0 | Kotlin | 0 | 6 | ecf14fe132824e944818fda1123f1c7796c30532 | 2,923 | dsa-kotlin | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem983/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem983
/**
* LeetCode page: [983. Minimum Cost For Tickets](https://leetcode.com/problems/minimum-cost-for-tickets/);
*/
class Solution {
/* Complexity:
* Time O(N) and Space O(N) where N is the size of days;
*/
fun mincostTickets(days: IntArray, costs: IntArray): Int {
// suffixMinCost[i] ::= the min cost of the suffix array of days start from index i
val suffixMinCost = IntArray(days.size + 1)
for (i in days.indices.reversed()) {
// Case 1: We buy a day pass on day[i]
val firstDay = days[i]
val dayPassMinCost =
costs[0] + suffixMinCost[days.firstIndex(fromIndex = i) { day -> day > firstDay }]
// Case 2: We buy a week pass on day[i]
val weekPassExpiryDay = firstDay + 6
val weekPassMinCost =
costs[1] + suffixMinCost[days.firstIndex(fromIndex = i) { day -> day > weekPassExpiryDay }]
// Case 3: We buy a month pass on day[i]
val monthPassExpiryDay = firstDay + 29
val monthPassMinCost =
costs[2] + suffixMinCost[days.firstIndex(fromIndex = i) { day -> day > monthPassExpiryDay }]
// The min cost is the min among possible cases
suffixMinCost[i] = minOf(dayPassMinCost, weekPassMinCost, monthPassMinCost)
}
return suffixMinCost[0]
}
private fun IntArray.firstIndex(
fromIndex: Int = 0,
fallBackValue: Int = size,
predicate: (element: Int) -> Boolean = { true }
): Int {
var index = fromIndex
while (index < size) {
val element = this[index]
val isMatched = predicate(element)
if (isMatched) return index
index++
}
return fallBackValue
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,843 | hj-leetcode-kotlin | Apache License 2.0 |
src/Day02.kt | AleksanderBrzozowski | 574,061,559 | false | null | import java.lang.IllegalArgumentException
class Part1 {
fun run() {
val testGame = game("Day02_test")
println(testGame.sumOf { it.score() })
}
private fun String.toShape() = when (this) {
"A", "X" -> Shape.ROCK
"B", "Y" -> Shape.PAPER
"C", "Z" -> Shape.SCISSORS
else -> throw IllegalArgumentException("Unknown shape: $this")
}
private fun game(name: String): List<Round> {
return readInput(name)
.map {
val (opponent, player) = it.split(" ")
Round(player = player.toShape(), opponent = opponent.toShape())
}
}
private data class Round(val opponent: Shape, val player: Shape) {
fun score(): Int = player.score + result().score
private fun result(): RoundResult = when {
player == opponent -> RoundResult.DRAW
player == Shape.ROCK && opponent == Shape.SCISSORS -> RoundResult.WIN
player == Shape.PAPER && opponent == Shape.ROCK -> RoundResult.WIN
player == Shape.SCISSORS && opponent == Shape.PAPER -> RoundResult.WIN
else -> RoundResult.LOSS
}
}
private enum class Shape(val score: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3),
}
private enum class RoundResult(val score: Int) {
LOSS(0),
DRAW(3),
WIN(6),
}
}
class Part2 {
fun run() {
val testGame = game("Day02_test")
println(testGame.sumOf { it.score() })
}
private fun String.toShape() = when (this) {
"A" -> Shape.ROCK
"B" -> Shape.PAPER
"C" -> Shape.SCISSORS
else -> throw IllegalArgumentException("Unknown shape: $this")
}
private fun String.toResult() = when (this) {
"X" -> RoundResult.LOSS
"Y" -> RoundResult.DRAW
"Z" -> RoundResult.WIN
else -> throw IllegalArgumentException("Unknown result: $this")
}
private fun game(name: String): List<Round> {
return readInput(name)
.map {
val (opponent, result) = it.split(" ")
val player = result.toResult().playerShape(opponent.toShape())
Round(player = player, opponent = opponent.toShape())
}
}
private data class Round(val opponent: Shape, val player: Shape) {
fun score(): Int = player.score + result().score
private fun result(): RoundResult = when {
player == opponent -> RoundResult.DRAW
player == Shape.ROCK && opponent == Shape.SCISSORS -> RoundResult.WIN
player == Shape.PAPER && opponent == Shape.ROCK -> RoundResult.WIN
player == Shape.SCISSORS && opponent == Shape.PAPER -> RoundResult.WIN
else -> RoundResult.LOSS
}
}
private enum class Shape(val score: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3),
}
private enum class RoundResult(val score: Int) {
LOSS(0),
DRAW(3),
WIN(6);
fun playerShape(opponent: Shape): Shape = when (this) {
RoundResult.DRAW -> opponent
RoundResult.WIN -> when (opponent) {
Shape.ROCK -> Shape.PAPER
Shape.PAPER -> Shape.SCISSORS
Shape.SCISSORS -> Shape.ROCK
}
RoundResult.LOSS -> when (opponent) {
Shape.ROCK -> Shape.SCISSORS
Shape.PAPER -> Shape.ROCK
Shape.SCISSORS -> Shape.PAPER
}
}
}
}
fun main() {
Part1().run()
Part2().run()
}
| 0 | Kotlin | 0 | 0 | 161c36e3bccdcbee6291c8d8bacf860cd9a96bee | 3,598 | kotlin-advent-of-code-2022 | Apache License 2.0 |
src/Day21.kt | Excape | 572,551,865 | false | {"Kotlin": 36421} | fun main() {
data class Expression(var left: Any, var right: Any, val operand: Char) {
fun evaluate(): ULong {
assert(left is ULong)
assert(right is ULong)
val l = left as ULong
val r = right as ULong
val result = when (operand) {
'+' -> l + r
'-' -> l - r
'*' -> l * r
'/' -> l / r
else -> throw IllegalStateException("Invalid operand $operand")
}
return result
}
fun printRecursively(allExpressions: Map<String, Any>): String {
val leftString = getExpressionString(allExpressions, left)
val rightString = getExpressionString(allExpressions, right)
return "($leftString $operand $rightString)"
}
private fun getExpressionString(allExpressions: Map<String, Any>, expr: Any) = when (expr) {
is String -> {
val job = allExpressions[expr]!!
if (job is Expression) job.printRecursively(allExpressions) else job.toString()
}
else -> expr.toString()
}
}
fun parseExpression(expr: String): Any {
val numberOrExpressions = expr.split(" ")
if (numberOrExpressions.size == 1) {
return numberOrExpressions.first().toULong()
}
return Expression(numberOrExpressions[0], numberOrExpressions[2], numberOrExpressions[1].first())
}
fun parseInput(input: List<String>) =
input.map { it.split(":") }.associate { it[0] to parseExpression(it[1].trim()) }
fun updateExpression(newExpression: Expression, allExpressions: Map<String, Any>) {
if (newExpression.left is String && allExpressions[newExpression.left] is ULong) {
newExpression.left = allExpressions[newExpression.left]!!
}
if (newExpression.right is String && allExpressions[newExpression.right] is ULong) {
newExpression.right = allExpressions[newExpression.right]!!
}
}
fun part1(input: List<String>): ULong {
val expressions = parseInput(input)
val iterations = generateSequence(expressions) { allExpressions ->
allExpressions.mapValues { (_, expr) ->
if (expr is ULong) {
return@mapValues expr
}
val newExpression = expr as Expression
updateExpression(newExpression, allExpressions)
return@mapValues when {
newExpression.left is ULong && newExpression.right is ULong -> newExpression.evaluate()
else -> newExpression
}
}
}.takeWhile { it["root"] is Expression }.toList()
val rootExpression: Expression = iterations.last()["root"] as Expression
return rootExpression.evaluate()
}
fun buildEquation(expressions: Map<String, Any>): String {
val root = expressions["root"]!! as Expression
val rootWithEquals = root.copy(operand = '=')
return rootWithEquals.printRecursively(expressions)
}
fun part2(input: List<String>): String {
val inputExpr = parseInput(input).toMutableMap()
inputExpr["humn"] = "X"
var changed = true
var currentExpr = inputExpr.toMap()
while (changed) {
changed = false
currentExpr = currentExpr.mapValues { (_, expr) ->
if (expr is ULong) {
return@mapValues expr
}
if (expr == "X") {
return@mapValues expr
}
val newExpression = (expr as Expression).copy()
updateExpression(newExpression, currentExpr)
if (newExpression != expr) {
changed = true
}
return@mapValues when {
newExpression.left is ULong && newExpression.right is ULong -> newExpression.evaluate()
else -> newExpression
}
}
}
return buildEquation(currentExpr.toMap())
}
val testInput = readInput("Day21_test")
check(part1(testInput) == 152UL)
val input = readInput("Day21")
val part1Answer = part1(input)
val part2Answer = part2(input)
println("part 1: $part1Answer")
println("part 2: Plug this into a solver :) : $part2Answer")
}
| 0 | Kotlin | 0 | 0 | a9d7fa1e463306ad9ea211f9c037c6637c168e2f | 4,470 | advent-of-code-2022 | Apache License 2.0 |
src/Day20.kt | syncd010 | 324,790,559 | false | null | import kotlin.math.min
class Day20: Day {
// This represents a leg of a path
data class Leg(val to: String, val steps: Int, val level: Int)
private val dirs = listOf(Position(0, -1), Position(1, 0), Position(0, 1), Position(-1, 0))
fun convert(input: List<String>) : Map<String, List<Leg>> {
fun findPortals(input: List<String>): List<Pair<String, Position>> {
val portals = mutableListOf<Pair<String, Position>>()
for (y in input.indices) {
for (x in input[y].indices) {
if (!input[y][x].isUpperCase() ||
(x > 0 && input[y][x-1].isUpperCase()) ||
(y > 0 && x < input[y-1].length && input[y-1][x].isUpperCase()))
continue
val posX =
if (x + 1 < input[y].length && input[y][x + 1].isUpperCase()) {
if (x > 0 && input[y][x - 1] == '.') x - 1
else x + 2
} else x
val posY =
if (y + 1 < input.size && x < input[y+1].length && input[y+1][x].isUpperCase()) {
if (y > 0 && x < input[y-1].length && input[y - 1][x] == '.') y - 1
else y + 2
} else y
val id = when {
y == posY -> String(charArrayOf(input[y][x], input[y][x+1]))
x == posX -> String(charArrayOf(input[y][x], input[y+1][x]))
else -> "ERROR"
}
portals.add(Pair(id, Position(posX, posY)))
}
}
return portals
}
fun findLegs(maze: List<String>, from: String, fromPos: Position, portals: List<Pair<String, Position>>) : MutableList<Leg> {
val legs = mutableListOf<Leg>()
val frontier = mutableListOf(Pair(fromPos, 0)) // List of <position, distance>
val visited = mutableListOf(fromPos)
while (frontier.isNotEmpty()) {
val (pos, dist) = frontier.removeAt(0)
for (newPos in dirs.map { pos + it }) {
if (newPos.y < 0 || newPos.y >= maze.size || newPos.x < 0 || newPos.x >= maze[newPos.y].length ) continue
val type = maze[newPos.y][newPos.x]
if (newPos in visited || type == '#' || type == ' ') continue
visited.add(newPos)
if (type.isUpperCase()) {
val portal = portals.find { (_, portalPos) -> portalPos == pos }!!.first
val level = if (pos.y == 2 || pos.y == maze.size - 3 || pos.x == 2 || pos.x == maze[pos.y].length - 3) -1 else 1
val suffix = if (level == -1) 'o' else 'i'
if (portal != from) legs.add(Leg(portal + suffix, dist + 1, level))
} else {
frontier.add(Pair(newPos, dist + 1))
}
}
}
return legs
}
val mazeMap = mutableMapOf<String, MutableList<Leg>>()
with(findPortals(input)) {
forEach { (id, pos) ->
val legs = findLegs(input, id, pos, this)
val suffix = if (pos.y == 2 || pos.y == input.size - 3 || pos.x == 2 || pos.x == input[pos.y].length - 3) 'o' else 'i'
mazeMap[id + suffix] = legs
}
}
return mazeMap
}
override fun solvePartOne(input: List<String>): Int {
val mazeMap = convert(input)
val frontier = mutableListOf(listOf(Leg("AAi", 0, 0)))
var bestDist = Int.MAX_VALUE
while (frontier.size > 0) {
val path = frontier.minBy { it.sumBy { it.steps } }!!
frontier.remove(path)
if (path.last().to == "ZZo") {
if (path.sumBy { it.steps } < bestDist) {
bestDist = path.sumBy { it.steps }
}
continue
}
val entry = path.last().to.substring(0..1) + (if (path.last().to[2] == 'i') 'o' else 'i')
mazeMap[entry]?.forEach { leg ->
if (path.all { it.to != leg.to } && (path.sumBy { it.steps } + leg.steps < bestDist))
frontier.add(path + leg)
}
}
return bestDist - 1
}
override fun solvePartTwo(input: List<String>): Int {
val mazeMap = convert(input)
val frontier = mutableListOf(listOf(Leg("AAi", 0, 0)))
var bestDist = Int.MAX_VALUE
while (frontier.size > 0) {
val path = frontier.minBy { it.last().steps }!!
frontier.remove(path)
if (path.last().to == "ZZo") {
bestDist = min(bestDist, path.last().steps)
continue
}
val entry = path.last().to.substring(0..1) + (if (path.last().to[2] == 'i') 'o' else 'i')
mazeMap[entry]?.forEach { leg ->
if ((leg.to == "ZZo" || leg.to == "AAo") && path.last().level != 0) return@forEach
val level = path.last().level + leg.level
val steps = path.last().steps + leg.steps
if ((leg.to != "ZZo" && leg.to != "AAo" && level < 0) ||
(path.any { it.to == leg.to && it.level == level }) ||
(steps > bestDist))
return@forEach
frontier.add(path + Leg(leg.to, steps, level))
}
}
return bestDist - 1
}
} | 0 | Kotlin | 0 | 0 | 11c7c7d6ccd2488186dfc7841078d9db66beb01a | 5,782 | AoC2019 | Apache License 2.0 |
src/main/kotlin/com/psmay/exp/advent/y2021/Day06.kt | psmay | 434,705,473 | false | {"Kotlin": 242220} | package com.psmay.exp.advent.y2021
object Day06 {
data class LanternfishClock(val timeToNextRespawn: Int) {
// Note that this model is equivalent to, but not the same as, the problem description, which
// always puts the new fish at the end.
fun ageOneDay(): List<LanternfishClock> {
val newAge = timeToNextRespawn - 1
return if (newAge < 0)
listOf(LanternfishClock(6), LanternfishClock(8))
else
listOf(LanternfishClock(newAge))
}
}
private fun ageAllOneDay(clocks: List<LanternfishClock>) = clocks.flatMap { it.ageOneDay() }
// This looks like a job for tail recursion!
private tailrec fun ageAll(clocks: List<LanternfishClock>, days: Int): List<LanternfishClock> =
if (days <= 0) clocks
else ageAll(ageAllOneDay(clocks), days - 1)
// Part 2 needs an approach that, ahem, *scales* better. Fortunately, I have an idea.
private fun age(ageTableInput: Map<Int, Long>, days: Int): Map<Int, Long> {
data class Counted(val timeLeft: Int, val numberAffected: Long)
fun ageOneDay(counts: List<Counted>): List<Counted> {
// For each existing row, produces rows to add to the result.
val nextPartialRows = counts.map { (currentTimeLeft, numberAffected) ->
val newTimeLeft = currentTimeLeft - 1
if (newTimeLeft == -1) {
listOf(
Counted(6, numberAffected),
Counted(8, numberAffected),
)
} else {
listOf(Counted(newTimeLeft, numberAffected))
}
}.flatten()
return nextPartialRows
.groupBy({ (timeLeft, _) -> timeLeft }, { (_, numberAffected) -> numberAffected })
.map { (timeLeft, numbersAffected) -> Counted(timeLeft, numbersAffected.sum()) }
}
tailrec fun age(counts: List<Counted>, days: Int): List<Counted> {
return if (days <= 0)
counts
else
age(ageOneDay(counts), days - 1)
}
if (ageTableInput.keys.any { it < 0 }) {
throw IllegalArgumentException("Input contains negative timers.")
}
val counts = ageTableInput.entries.map { (k, v) -> Counted(k, v) }
val aged = age(counts, days)
return aged.associateBy({ it.timeLeft }, { it.numberAffected })
}
fun part1(input: List<Int>): Int {
val clocks = input.map { LanternfishClock(it) }
val aged = ageAll(clocks, 80)
return aged.size
}
fun part2(input: List<Int>): Long {
val timerTable = input
.groupBy { it }
.map { (k, v) -> k to v.size.toLong() }
.toMap()
return age(timerTable, 256).values.sum()
}
} | 0 | Kotlin | 0 | 0 | c7ca54612ec117d42ba6cf733c4c8fe60689d3a8 | 2,895 | advent-2021-kotlin | Creative Commons Zero v1.0 Universal |
advent-of-code-2021/src/main/kotlin/Day5.kt | jomartigcal | 433,713,130 | false | {"Kotlin": 72459} | //Day 5: Hydrothermal Venture
//https://adventofcode.com/2021/day/5
import java.io.File
val regex = Regex("""(\d+),(\d+) -> (\d+),(\d+)""")
fun main() {
val lines = File("src/main/resources/Day5.txt").readLines()
val vents = lines.map {
regex.matchEntire(it)!!
.destructured
.let { (x1, y1, x2, y2) ->
(x1.toInt() to y1.toInt()) to (x2.toInt() to y2.toInt())
}
}
val horizontalVents = vents.filter { it.first.first == it.second.first }
val verticalVents = vents.filter { it.first.second == it.second.second }
val diagonalVents = vents.toMutableList() - horizontalVents - verticalVents
countOverlap(horizontalVents, verticalVents, diagonalVents, false)
countOverlap(horizontalVents, verticalVents, diagonalVents, true)
}
fun countOverlap(
horizontalVents: List<Pair<Pair<Int, Int>, Pair<Int, Int>>>,
verticalVents: List<Pair<Pair<Int, Int>, Pair<Int, Int>>>,
diagonalVents: List<Pair<Pair<Int, Int>, Pair<Int, Int>>>,
includeDiagonals: Boolean
) {
val ventMap = mutableMapOf<Pair<Int, Int>, Int>()
horizontalVents.forEach {
val x = it.first.first
val y1 = it.first.second
val y2 = it.second.second
val (min, max) = if (y1 > y2) y2 to y1 else y1 to y2
(min..max).forEach { y ->
ventMap[x to y] = ventMap.getOrDefault(x to y, 0) + 1
}
}
verticalVents.forEach {
val y = it.first.second
val x1 = it.first.first
val x2 = it.second.first
val (min, max) = if (x1 > x2) x2 to x1 else x1 to x2
(min..max).forEach { x ->
ventMap[x to y] = ventMap.getOrDefault(x to y, 0) + 1
}
}
if (includeDiagonals) {
diagonalVents.forEach {
val x1 = it.first.first
val y1 = it.first.second
val x2 = it.second.first
val y2 = it.second.second
if (x1 > x2) {
(x2..x1).forEachIndexed { index, _ ->
val y = if (y1 > y2) y2 + index else y2 - index
ventMap[x2 + index to y] = ventMap.getOrDefault(x2 + index to y, 0) + 1
}
} else {
(x1..x2).forEachIndexed { index, _ ->
val y = if (y1 > y2) y1 - index else y1 + index
ventMap[x1 + index to y] = ventMap.getOrDefault(x1 + index to y, 0) + 1
}
}
}
}
println(ventMap.count { it.value >= 2 })
}
| 0 | Kotlin | 0 | 0 | 6b0c4e61dc9df388383a894f5942c0b1fe41813f | 2,526 | advent-of-code | Apache License 2.0 |
src/Day08.kt | schoi80 | 726,076,340 | false | {"Kotlin": 83778} | fun main() {
val input = readInput("Day08")
val nodes = (2..<input.size).associate { i ->
val line = input[i].split("=")
val node = line[0].trim()
val steps = line[1].split(",").map { it.trim() }.let {
it[0].substring(1) to it[1].dropLast(1)
}
node to steps
}
fun String.nextNode(i:Char): String {
return if (i == 'L')
nodes[this]!!.first
else nodes[this]!!.second
}
fun part1(input: List<String>): Long {
val instruction = input[0]
var stepCount = 0
var currNode = "AAA"
while (currNode != "ZZZ") {
val index = stepCount % instruction.length
currNode = currNode.nextNode(instruction[index])
stepCount++
}
return stepCount.toLong()
}
fun part2(input: List<String>): Long {
val start = nodes.keys.filter { it.last() == 'A' }
val instruction = input[0]
fun String.countStepsToZ(): Long {
var currNode = this
var stepCount = 0L
while (currNode.last() != 'Z') {
val index = stepCount % instruction.length
currNode = currNode.nextNode(instruction[index.toInt()])
stepCount++
}
return stepCount
}
return start.map { it.countStepsToZ() }.reduce { acc, i -> lcm(acc, i) }
}
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | ee9fb20d0ed2471496185b6f5f2ee665803b7393 | 1,532 | aoc-2023 | Apache License 2.0 |
src/Day03.kt | JCofman | 576,062,635 | false | {"Kotlin": 6297} | fun parseInput(rawInput: String) = rawInput
val alphabetScore = mapOf(
'a' to 1,
'b' to 2,
'c' to 3,
'd' to 4,
'e' to 5,
'f' to 6,
'g' to 7,
'h' to 8,
'i' to 9,
'j' to 10,
'k' to 11,
'l' to 12,
'm' to 13,
'n' to 14,
'o' to 15,
'p' to 16,
'q' to 17,
'r' to 18,
's' to 19,
't' to 20,
'u' to 21,
'v' to 22,
'w' to 23,
'x' to 24,
'y' to 25,
'z' to 26,
'A' to 27,
'B' to 28,
'C' to 29,
'D' to 30,
'E' to 31,
'F' to 32,
'G' to 33,
'H' to 34,
'I' to 35,
'J' to 36,
'K' to 37,
'L' to 38,
'M' to 39,
'N' to 40,
'O' to 41,
'P' to 42,
'Q' to 43,
'R' to 44,
'S' to 45,
'T' to 46,
'U' to 47,
'V' to 48,
'W' to 49,
'X' to 50,
'Y' to 51,
'Z' to 52
)
fun main() {
fun solvePart1(input: List<String>): Int {
val twoPartsSplitted = input.map { str ->
val half = str.length / 2
listOf(str.slice(0 until half), str.slice(half until str.length))
}
var score = 0
// 2. find the char in both strings
twoPartsSplitted.forEachIndexed { idx, item ->
val alreadySeen: MutableMap<Char, Char> = mutableMapOf()
item[0].forEach { char ->
alreadySeen[char] = char
}
// 3. calculate score
var escape = false;
item[1].forEachIndexed { i, char ->
if (alreadySeen[char] != null && escape == false) {
score += alphabetScore[char] ?: 0
escape = true;
return@forEachIndexed
}
}
}
return score
}
fun solvePart2(input: List<String>): Int {
fun parseAndSplitString(rawInput: String): List<List<String>> {
val input = parseInput(rawInput)
val lines = input.split("\n")
val substrings = mutableListOf<List<String>>()
while (lines.isNotEmpty()) {
substrings.add(lines.splice(0, 3).map { it })
}
return substrings
}
fun calculateScore(substrings: List<List<String>>, alphabetScore: Map<String, Int>): Int {
val commonChars = mutableListOf<String>()
for (i in 0 until substrings.size) {
val commonChar = setOf(
substrings[i].reduce { acc, cur ->
acc.split("").filter { cur.contains(it) }.joinToString("")
}
).first()
commonChars.add(commonChar)
}
var score = 0
commonChars.forEach {
score += alphabetScore[it] ?: 0
}
return score
}
}
fun part1(input: List<String>): Int {
return solvePart1(input)
}
fun part2(input: List<String>): Int {
return solvePart2(input)
}
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | c25a54b03df77c1be46827642b6adc7644825c8c | 3,076 | aoc-2022-in-kotlin | Apache License 2.0 |
solutions/aockt/y2021/Y2021D13.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2021
import aockt.util.OcrDecoder
import io.github.jadarma.aockt.core.Solution
object Y2021D13 : Solution {
/** Represents a discrete point in 2D space. */
private data class Point(val x: UInt, val y: UInt)
/** Represents a possible origami fold. */
private sealed interface Fold {
val amount: UInt
/** Fold the paper upwards from the horizontal line [amount] of units down. */
data class Up(override val amount: UInt) : Fold
/** Fold the paper to the left from the vertical line [amount] of units to the right. */
data class Left(override val amount: UInt) : Fold
}
/** Given a point, determines where it will land after the [fold], or `null` if it's on the line or under-flows. */
private fun Point.origamiFold(fold: Fold): Point? {
val axisValue = when (fold) {
is Fold.Left -> x
is Fold.Up -> y
}
return when (axisValue) {
in 0u until fold.amount -> this
fold.amount -> null
else -> if (axisValue > fold.amount * 2u) null else Point(
x = if (fold is Fold.Left) fold.amount * 2u - x else x,
y = if (fold is Fold.Up) fold.amount * 2u - y else y,
)
}
}
/** Performs the origami [fold] on all points and returns the new set of unique points. */
private fun Set<Point>.origamiFold(fold: Fold): Set<Point> = buildSet {
for (point in this@origamiFold) point.origamiFold(fold)?.let { add(it) }
}
/** Builds a string containing all the dots marked on the origami paper. */
private fun Set<Point>.visualize(): String {
if (isEmpty()) return ""
val width = maxOf { it.x }.toInt() + 1
val height = maxOf { it.y }.toInt() + 1
val dotMap = BooleanArray(width * height) { false }
forEach { dot -> dotMap[(dot.y.toInt() * width + dot.x.toInt())] = true }
return buildString {
dotMap.forEachIndexed { i, dot ->
append(if (dot) '#' else '.')
if ((i + 1) % width == 0 && i != dotMap.lastIndex) appendLine('.')
}
appendLine('.')
}
}
/** Parse the [input] and return the position of the dots on the paper and the list of folding instructions. */
private fun parseInput(input: String): Pair<Set<Point>, List<Fold>> {
val (rawFolds, rawPoints) = input
.lineSequence()
.filterNot { it.isBlank() }
.partition { it.startsWith("fold along") }
val points = rawPoints
.map { it.split(',') }
.map { (a, b) -> Point(a.toUInt(), b.toUInt()) }
.toSet()
val folds = rawFolds
.map { it.removePrefix("fold along ") }
.map { it.split('=') }
.map { (axis, amount) ->
when (axis) {
"x" -> Fold::Left
"y" -> Fold::Up
else -> throw IllegalArgumentException()
}(amount.toUIntOrNull() ?: throw IllegalArgumentException())
}
return points to folds
}
override fun partOne(input: String) =
parseInput(input).let { (points, folds) ->
points.origamiFold(folds.first()).count()
}
override fun partTwo(input: String) =
parseInput(input).let { (points, folds) ->
folds
.fold(points) { dots, fold -> dots.origamiFold(fold) }
.visualize()
.let(OcrDecoder::decode)
}
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 3,578 | advent-of-code-kotlin-solutions | The Unlicense |
kotlin/src/com/s13g/aoc/aoc2015/Day9.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2015
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import com.s13g.aoc.resultFrom
import kotlin.math.max
import kotlin.math.min
/**
* --- Day 9: All in a Single Night ---
* https://adventofcode.com/2015/day/9
*/
class Day9 : Solver {
override fun solve(lines: List<String>): Result {
val re = """(\w+) to (\w+) = (\d+)$""".toRegex()
val distances = lines
.map { re.find(it)!!.destructured }
.map { (from, to, distance) ->
Distance(
setOf(from, to),
distance.toInt()
)
}
.toSet()
val destinations = distances.map { it.cities }.flatten().toSet()
val m1 = shortestLongestTravel("", destinations, distances, false)
val m2 = shortestLongestTravel("", destinations, distances, true)
return resultFrom(m1, m2)
}
private fun shortestLongestTravel(
from: String,
destinations: Set<String>,
distances: Set<Distance>,
longest: Boolean
): Int {
if (destinations.isEmpty()) return 0
var best = if (longest) Int.MIN_VALUE else Int.MAX_VALUE
for (nextStop in destinations) {
val trip = setOf(from, nextStop)
val distCost = distances.find { it.cities == trip }?.cost ?: 0
val cost = distCost + shortestLongestTravel(
nextStop,
destinations.minus(nextStop),
distances,
longest
)
best = if (longest) max(best, cost) else min(best, cost)
}
return best
}
data class Distance(val cities: Set<String>, val cost: Int)
} | 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 1,532 | euler | Apache License 2.0 |
2023/src/main/kotlin/Day03.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | object Day03 {
data class Pos(val x: Int, val y: Int)
data class PartWithSymbol(val number: Int, val symbol: Char, val symbolPos: Pos)
fun part1(input: String): Int {
return getPartsWithSymbols(input).sumOf { it.number }
}
fun part2(input: String): Int {
return getPartsWithSymbols(input)
.filter { it.symbol == '*' }
.groupBy { it.symbolPos }
.values
.filter { it.size == 2 }
.sumOf { it[0].number * it[1].number }
}
private fun getPartsWithSymbols(input: String): List<PartWithSymbol> {
val grid = input.splitNewlines().map { it.toCharArray() }
val partsWithSymbols = mutableListOf<PartWithSymbol>()
fun addPart(number: Int, symbolPos: Pos) {
partsWithSymbols.add(PartWithSymbol(number, grid[symbolPos.y][symbolPos.x], symbolPos))
}
for (row in grid.indices) {
var currNumber = 0
var symbolPos: Pos? = null
for (col in grid[row].indices) {
val curr = grid[row][col]
if (curr.isDigit()) {
currNumber = currNumber * 10 + curr.digitToInt()
if (symbolPos == null) {
symbolPos = findSymbol(grid, row, col)
}
} else if (currNumber != 0) {
if (symbolPos != null) {
addPart(currNumber, symbolPos)
symbolPos = null
}
currNumber = 0
}
}
if (currNumber != 0 && symbolPos != null) {
addPart(currNumber, symbolPos)
}
}
return partsWithSymbols
}
private fun findSymbol(grid: List<CharArray>, row: Int, col: Int): Pos? {
((row - 1).coerceAtLeast(0)..(row + 1).coerceAtMost(grid.size - 1)).forEach { y ->
((col - 1).coerceAtLeast(0)..(col + 1).coerceAtMost(grid[0].size - 1)).forEach { x ->
val curr = grid[y][x]
if (curr != '.' && !curr.isDigit()) {
return Pos(x, y)
}
}
}
return null
}
} | 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 1,911 | advent-of-code | MIT License |
src/Day04.kt | karlwalsh | 573,854,263 | false | {"Kotlin": 32685} | fun main() {
fun part1(input: List<String>): Int = input.asInputForPart1AndPart2().count { it.assignmentsFullyContained() }
fun part2(input: List<String>): Int = input.asInputForPart1AndPart2().count { it.assignmentsOverlap() }
val input = readInput("Day04")
with(::part1) {
val exampleResult = this(example())
check(exampleResult == 2) { "Part 1 result was $exampleResult" }
println("Part 1: ${this(input)}")
}
with(::part2) {
val exampleResult = this(example())
check(exampleResult == 4) { "Part 2 result was $exampleResult" }
println("Part 2: ${this(input)}")
}
}
private data class Pair(val first: Assignment, val second: Assignment) {
fun assignmentsFullyContained(): Boolean = first.fullyContains(second) || second.fullyContains(first)
fun assignmentsOverlap(): Boolean = first.overlaps(second) || second.overlaps(first)
}
private data class Assignment(val start: Int, val end: Int) {
fun fullyContains(other: Assignment): Boolean = this.start <= other.start && this.end >= other.end
fun overlaps(other: Assignment): Boolean = other.start in start..end || start in other.start..other.end
}
private fun List<String>.asInputForPart1AndPart2(): List<Pair> = this.map { it.toPair() }
private fun String.toPair() = Pair(this.split(",")[0].toAssignment(), this.split(",")[1].toAssignment())
private fun String.toAssignment() = Assignment(this.split("-")[0].toInt(), this.split("-")[1].toInt())
private fun example() = """
2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8
""".trimIndent().lines() | 0 | Kotlin | 0 | 0 | f5ff9432f1908575cd23df192a7cb1afdd507cee | 1,647 | advent-of-code-2022 | Apache License 2.0 |
src/Day11.kt | askeron | 572,955,924 | false | {"Kotlin": 24616} | class Day11 : Day<Long>(10605, 2713310158L, 58056, 15048718170L) {
private class Monkey(
private val items: MutableList<Long>,
private val operation: (Long) -> Long,
private val divisibleForTest: Int,
private val monkeyIndexForTrue: Int,
private val monkeyIndexForFalse: Int,
) {
var itemsInspectedCount = 0
fun inspect(monkeys: List<Monkey>, reliefFactor: Int) {
items.forEach { value ->
itemsInspectedCount++
val newValue = (operation.invoke(value) / reliefFactor) % monkeys.map { it.divisibleForTest }.fold(1) { a, b -> a * b }
val newMonkeyIndex = if (newValue % divisibleForTest == 0L) monkeyIndexForTrue else monkeyIndexForFalse
monkeys[newMonkeyIndex].items += newValue
}
items.clear()
}
}
private fun parseInput(input: List<String>): List<Monkey> {
return input.split("")
.map { lines ->
Monkey(
items = lines[1].substringAfter(':').split(',').map { it.trim().toLong() }.toMutableList(),
operation = lines[2].split(' ').takeLast(2).toPair().let { (a, b) ->
when (a) {
"+" -> { x -> x + (b.toLongOrNull() ?: x) }
"*" -> { x -> x * (b.toLongOrNull() ?: x) }
else -> error("not implemented")
}
},
divisibleForTest = lines[3].split(' ').last().toInt(),
monkeyIndexForTrue = lines[4].split(' ').last().toInt(),
monkeyIndexForFalse = lines[5].split(' ').last().toInt(),
)
}
}
private fun partCommon(input: List<String>, reliefFactor: Int, roundCount: Int): Long {
val monkeys = parseInput(input)
repeat(roundCount) { _ -> monkeys.forEach { it.inspect(monkeys, reliefFactor) } }
return monkeys.map { it.itemsInspectedCount }.sortedDescending().let { it[0].toLong() * it[1] }
}
override fun part1(input: List<String>): Long {
return partCommon(input, 3, 20)
}
override fun part2(input: List<String>): Long {
return partCommon(input, 1, 10_000)
}
}
| 0 | Kotlin | 0 | 1 | 6c7cf9cf12404b8451745c1e5b2f1827264dc3b8 | 2,318 | advent-of-code-kotlin-2022 | Apache License 2.0 |
Collections/Max min/src/TaskExtensionMaxMin.kt | Rosietesting | 373,564,502 | false | {"HTML": 178715, "JavaScript": 147056, "Kotlin": 113135, "CSS": 105840} | fun main () {
val numbers = listOf(45,7,1,0,45,65,2,3)
println("Count value ${numbers.count()}")
println("Max value ${numbers.max()}")
println("Min value ${numbers.min()}")
println("Average value ${numbers.average()}")
println("Sum value ${numbers.sum()}")
println("Min value ${numbers.minBy { it % 3 }}")
val strings = listOf("one", "two", "three", "four")
val longestString = strings.maxWith(compareBy { it.length })
println("logetString word id " + longestString)
val numbersSum = listOf(5, 42, 10, 4)
println("List sum is " + numbersSum.sumBy { it * 1 })
println(numbersSum.sumByDouble { it.toDouble()})
val vals = listOf(5, 2, 10, 4)
val sum = vals.reduce { sum, element -> sum + element }
println("Sum is " + sum)
//Shop
// checkAllCustomersAreFromCity returns true if all customers are from a given city
val city1 = City ("Bogota")
val city2 = City ("London")
val product1 = Product("Bread", 10.50)
val product2 = Product("Rice", 4.23)
val product3 = Product("potatoes", 1.23)
val product4 = Product("brocoli", 12.60)
val order1 = Order(listOf(product1,product3, product4), true)
val order2 = Order(listOf(product2), true)
val order3 = Order(listOf(product1, product2), true)
val order4 = Order(listOf(product3, product4), true)
val customer1 = Customer("<NAME>", city1, listOf(order1, order2, order3))
val customer2 = Customer("<NAME>", city2, listOf(order1))
val customer3 = Customer("Santi", city2, listOf(order1, order4))
val shop = Shop("Roxipan", listOf(customer2,customer3, customer1))
//return the customer who has placed the most amount of orders in this shop
val order = shop.customers.maxBy { it.orders.size }
//return the most expensive product that has been ordered by the given customer
//val expensiveProduct = shop.customers.filter { it.orders }
val prodiuct = customer1.orders
.flatMap(Order::products)
.maxBy(Product::price)
val f1 = customer1.orders
val fr = customer1.orders
.flatMap(Order::products)
val f3= customer1.orders
.flatMap(Order::products)
.maxBy(Product::price)
//callable reference
println("Callable reference")
ExampleDataClass::class.java.methods.forEach(::println)
}
data class ExampleDataClass(
val name: String, var enabled: Boolean)
| 0 | HTML | 0 | 0 | b0aa518d220bb43c9398dacc8a6d9b6c602912d5 | 2,438 | KotlinKoans | MIT License |
src/aoc2022/Day04.kt | miknatr | 576,275,740 | false | {"Kotlin": 413403} | package aoc2022
fun main() {
fun IntRange.isFullyContain(range: IntRange) =
(this.contains(range.first) && this.contains(range.last)) || (range.contains(this.first) && range.contains(this.last))
fun parseRange(strRange: String): IntRange {
val numbers = strRange.split("-")
return numbers[0].toInt()..numbers[1].toInt()
}
fun part1(input: List<String>) = input
.filter { it != "" }
.map { line -> line.split(",") }
.map { sections -> Pair(parseRange(sections[0]), parseRange(sections[1])) }
.filter { it.first.isFullyContain(it.second) }
.size
fun part2(input: List<String>) = input
.filter { it != "" }
.map { line -> line.split(",") }
.map { sections -> Pair(parseRange(sections[0]), parseRange(sections[1])) }
.filter { it.first.intersect(it.second).isNotEmpty() }
.size
val testInput = readInput("Day04_test")
part1(testInput).println()
part2(testInput).println()
val input = readInput("Day04")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 400038ce53ff46dc1ff72c92765ed4afdf860e52 | 1,101 | aoc-in-kotlin | Apache License 2.0 |
src/main/kotlin/com/kishor/kotlin/algo/dp/RoboticDelivery.kt | kishorsutar | 276,212,164 | false | null | package com.kishor.kotlin.algo.dp
import java.util.ArrayList
fun main() {
val markings = listOf(listOf(0, 3),listOf(0,5),listOf(0,7),listOf(1,6),listOf(1,8),listOf(1,9),listOf(2,3),listOf(2,5),listOf(2,6))
println(chooseAFlask(markings, 3, listOf(4,6,6,7)))
}
fun chooseAFlask(markings: List<List<Int>>, flaskTypes: Int, requirements: List<Int>): Int {
val flaskMap = mutableMapOf<Int, MutableList<Int>>()
for (mark in markings) {
if (mark[0] in flaskMap) {
flaskMap[mark[0]]!!.add(mark[1])
} else {
flaskMap[mark[0]] = mutableListOf(mark[1])
}
}
var minSum =Int.MAX_VALUE
var flaskId = -1
for (flsk in 0 until flaskTypes) {
for (req in requirements) {
var currentSum = 0
val flaskMarkings = flaskMap[flsk]!!
for (mark in flaskMarkings) {
if (mark >= req) {
currentSum += mark - req
}
}
if (currentSum < minSum) {
minSum = currentSum
flaskId = flsk
}
}
}
return flaskId
}
fun chooseAFlask(numOrders: Int, requirements: IntArray, flaskTypes: Int, markings: List<List<Int>>): Int {
val map =
arrayOf(mutableListOf(flaskTypes)) //building a map for each flask type for fast retrieval
for (mark in markings) {
map[mark[0]].add(mark[1])
}
var min_cost = 1e11.toLong()
var cost: Long
var index = -1
for (i in 0 until flaskTypes) {
cost = 0
for (j in requirements.indices) {
cost += upperBound(map[i], requirements[j]) - requirements[j]
}
if (cost < min_cost) {
min_cost = cost
index = i
}
}
return index
}
fun isContainsDuplicate(string: String): Boolean {
var asciiArray = IntArray(26) { 0 }
for (ch in string) {
val value = 96 - ch.toInt()
asciiArray[value]++
}
for (i in 0 until asciiArray.size) {
if (asciiArray[i] > 1) return false
}
return true
}
private fun upperBound(arr: List<Int>?, x: Int): Long {
var l = 0
var r = arr!!.size - 1
var mid: Int
if (arr[0] >= x) return arr[0].toLong()
if (arr[r] < x) return Long.MAX_VALUE
while (l < r) {
mid = (l + r) / 2
if (arr[mid] >= x && arr[mid] <= x) return arr[mid].toLong()
if (arr[mid] > x) r = mid - 1 else l = mid + 1
}
return Long.MAX_VALUE
} | 0 | Kotlin | 0 | 0 | 6672d7738b035202ece6f148fde05867f6d4d94c | 2,564 | DS_Algo_Kotlin | MIT License |
src/main/kotlin/days/Solution22.kt | Verulean | 725,878,707 | false | {"Kotlin": 62395} | package days
import adventOfCode.InputHandler
import adventOfCode.Solution
import adventOfCode.util.PairOf
import adventOfCode.util.Point2D
import adventOfCode.util.ints
import kotlin.math.max
object Solution22 : Solution<Pair<Int, List<Set<Int>>>>(AOC_YEAR, 22) {
private operator fun List<Int>.component6() = this[5]
override fun getInput(handler: InputHandler): Pair<Int, List<Set<Int>>> {
val coordinates = handler.getInput("\n").map(String::ints).sortedBy { it[2] }
val tallest = mutableMapOf<Point2D, PairOf<Int>>().withDefault { -1 to 0 }
val dependencyGraph = mutableListOf<Set<Int>>()
coordinates.forEachIndexed { i, (x0, y0, z0, x1, y1, z1) ->
var maxHeight = 0
val dependencies = mutableSetOf<Int>()
(x0..x1).forEach { x ->
(y0..y1).forEach { y ->
val (j, z) = tallest.getValue(x to y)
if (z > maxHeight) {
maxHeight = z
dependencies.clear()
dependencies.add(j)
} else if (z == maxHeight) {
dependencies.add(j)
}
}
}
dependencyGraph.add(dependencies)
val z = z1 - max(z0 - maxHeight - 1, 0)
(x0..x1).forEach { x ->
(y0..y1).forEach { y ->
tallest[x to y] = i to z
}
}
}
return coordinates.size to dependencyGraph
}
override fun solve(input: Pair<Int, List<Set<Int>>>): PairOf<Int> {
val (n, dependencyGraph) = input
val ans1 = n - dependencyGraph.filter { it.size == 1 }
.flatten()
.filter { it >= 0 }
.toSet()
.size
val ans2 = (0 until n).sumOf { i ->
val affected = mutableSetOf(i)
dependencyGraph.withIndex()
.drop(i + 1)
.forEach { (j, dependencies) ->
if ((dependencies - affected).isEmpty()) affected.add(j)
}
affected.size - 1
}
return ans1 to ans2
}
}
| 0 | Kotlin | 0 | 1 | 99d95ec6810f5a8574afd4df64eee8d6bfe7c78b | 2,191 | Advent-of-Code-2023 | MIT License |
src/day03/day03.kt | LostMekka | 574,697,945 | false | {"Kotlin": 92218} | package day03
import util.readInput
import util.shouldBe
fun main() {
val day = 3
val testInput = readInput(day, testInput = true).parseInput()
part1(testInput) shouldBe 157
part2(testInput) shouldBe 70
val input = readInput(day).parseInput()
println("output for part1: ${part1(input)}")
println("output for part2: ${part2(input)}")
}
private class Input(
val lines: List<String>,
)
private fun List<String>.parseInput(): Input {
return Input(this)
}
private val Char.priority
get() = when {
isLowerCase() -> code - 96
else -> code - 38
}
private fun part1(input: Input): Int {
return input.lines.sumOf { line ->
val (a, b) = line.toList()
.chunked(line.length / 2)
.map { it.toSet() }
val type = a.intersect(b).single()
type.priority
}
}
private fun part2(input: Input): Int {
return input.lines
.chunked(3)
.sumOf { group ->
val type = group
.map { it.toSet() }
.reduce { a, b -> a intersect b }
.single()
type.priority
}
}
| 0 | Kotlin | 0 | 0 | 58d92387825cf6b3d6b7567a9e6578684963b578 | 1,150 | advent-of-code-2022 | Apache License 2.0 |
y2021/src/main/kotlin/adventofcode/y2021/Day16.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2021
import adventofcode.io.AdventSolution
object Day16 : AdventSolution(2021, 16, "Packet Decoder") {
override fun solvePartOne(input: String) = PacketDecoder(input).parsePacket().let(::sumOfVersions)
override fun solvePartTwo(input: String) = PacketDecoder(input).parsePacket().let(::eval)
}
private sealed class Packet(val version: Int, val type: Int)
private class Literal(version: Int, type: Int, val data: Long) : Packet(version, type)
private class Operator(version: Int, type: Int, val data: List<Packet>) : Packet(version, type)
private class PacketDecoder(input: String) {
private val binary = "F$input".toBigInteger(16).toString(2).drop(4)
private var index = 0
private fun readBits(n: Int): Int = binary.substring(index, index + n).toInt(2).also { index += n }
fun parsePacket(): Packet {
val version = readBits(3)
val type = readBits(3)
return if (type == 4) Literal(version, type, parseLiteral())
else Operator(version, type, parseSubpackets())
}
private fun parseLiteral(): Long {
var result = 0L
do {
val next = readBits(1) == 1
result *= 16
result += readBits(4)
} while (next)
return result
}
private fun parseSubpackets(): List<Packet> {
return if (readBits(1) == 0) {
val lastBit = readBits(15) + index
buildList {
while (index < lastBit) {
add(parsePacket())
}
}
} else {
val packetCount = readBits(11)
List(packetCount) { parsePacket() }
}
}
}
private fun sumOfVersions(p: Packet): Int = when (p) {
is Literal -> p.version
is Operator -> p.version + p.data.sumOf(::sumOfVersions)
}
private fun eval(p: Packet): Long = when (p) {
is Literal -> p.data
is Operator -> when (p.type) {
0 -> p.data.sumOf(::eval)
1 -> p.data.map(::eval).reduce(Long::times)
2 -> p.data.minOf(::eval)
3 -> p.data.maxOf(::eval)
5 -> p.data.map(::eval).let { if (it[0] > it[1]) 1L else 0L }
6 -> p.data.map(::eval).let { if (it[0] < it[1]) 1L else 0L }
7 -> p.data.map(::eval).let { if (it[0] == it[1]) 1L else 0L }
else -> throw IllegalStateException()
}
} | 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 2,371 | advent-of-code | MIT License |
src/Day04.kt | DeltaSonic62 | 572,718,847 | false | {"Kotlin": 8676} | fun main() {
fun part1(input: List<String>): Int {
var count = 0
for (pair in input) {
val first = pair.split(',')[0].split('-');
val second = pair.split(',')[1].split('-');
if ((first[0].toInt() <= second[0].toInt() && first[1].toInt() >= second[1].toInt()) || (second[0].toInt() <= first[0].toInt() && second[1].toInt() >= first[1].toInt())) {
count++
}
}
return count
}
fun part2(input: List<String>): Int {
var count = 0
for (pair in input) {
val first = pair.split(',')[0].split('-');
val second = pair.split(',')[1].split('-');
for (i in first[0].toInt()..first[1].toInt()) {
if (i >= second[0].toInt() && i <= second[1].toInt()) {
count++;
break;
}
}
}
return count
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 7cdf94ad807933ab4769ce4995a43ed562edac83 | 1,218 | aoc-2022-kt | Apache License 2.0 |
src/main/kotlin/days/Day17.kt | andilau | 399,220,768 | false | {"Kotlin": 85768} | package days
@AdventOfCodePuzzle(
name = "<NAME>",
url = "https://adventofcode.com/2020/day/17",
date = Date(day = 17, year = 2020)
)
class Day17(val input: List<String>) : Puzzle {
override fun partOne(): Int {
return generateSequence(
readInput { x, y -> Point3D(x, y, 0) }) { space -> space.next() }
.drop(6)
.first().size
}
override fun partTwo(): Int {
var hyper = readInput { x, y -> Hypercube(x, y, 0, 0) }
repeat(6) {
hyper = hyper.next()
}
return hyper.size
}
private fun readInput(pointFunction: (Int, Int) -> Point): Set<Point> {
val space = mutableSetOf<Point>()
for (y in input.indices) {
for (x in input[y].indices) {
if (input[y][x] == '#')
space.add(pointFunction(x, y))
}
}
return space
}
private fun Set<Point>.next(): Set<Point> {
val next = mutableSetOf<Point>()
val active = this
val all = active
.flatMap { point -> point.neighbors() }
.toSet()
all.forEach { point ->
val activeNeighbors = point.neighbors().count { neighbor -> neighbor in active }
when {
point in active && activeNeighbors in setOf(2, 3) -> next.add(point)
point !in active && activeNeighbors in setOf(3) -> next.add(point)
}
}
return next
}
interface Point {
fun neighbors(): List<Point>
}
data class Point3D(val x: Int, val y: Int, val z: Int) : Point {
override fun neighbors(): List<Point3D> =
(x - 1..x + 1).map { x ->
(y - 1..y + 1).map { y ->
(z - 1..z + 1).mapNotNull { z ->
Point3D(x, y, z).takeIf { it != this }
}
}.flatten()
}.flatten()
}
data class Hypercube(val x: Int, val y: Int, val z: Int, val h: Int) : Point {
override fun neighbors(): List<Hypercube> =
(x - 1..x + 1).map { x ->
(y - 1..y + 1).map { y ->
(z - 1..z + 1).map { z ->
(h - 1..h + 1).mapNotNull { h ->
Hypercube(x, y, z, h).takeIf { it != this }
}
}.flatten()
}.flatten()
}.flatten()
}
} | 7 | Kotlin | 0 | 0 | 2809e686cac895482c03e9bbce8aa25821eab100 | 2,477 | advent-of-code-2020 | Creative Commons Zero v1.0 Universal |
src/day5.kt | miiila | 725,271,087 | false | {"Kotlin": 77215} | import java.io.File
import java.math.BigInteger
import kotlin.system.exitProcess
import kotlin.time.measureTime
private const val DAY = 5
fun main() {
if (!File("./day${DAY}_input").exists()) {
downloadInput(DAY)
println("Input downloaded")
exitProcess(0)
}
val transformer = { x: String -> x }
val input = loadInput(DAY, false, transformer)
// println(input)
val (seeds, maps) = parseInput(input)
println(measureTime {
print("Part1: ")
print(solvePart1(seeds, maps))
print(" ")
})
println(measureTime {
print("Part2: ")
print(solvePart2(seeds, maps))
print(" ")
})
println(measureTime {
print("Part2 brute force: ")
print(solvePart2Brute(seeds, maps))
print(" ")
})
}
data class Range(
val fromStart: BigInteger,
val fromEnd: BigInteger,
val offset: BigInteger = 0.toBigInteger()
)
fun parseInput(input: List<String>): Pair<List<BigInteger>, Map<String, List<Range>>> {
var seeds: List<BigInteger> = listOf()
val maps: MutableMap<String, MutableList<Range>> = mutableMapOf()
var currentMap: String = ""
for ((i, line) in input.withIndex()) {
if (i == 0) {
seeds = line.trim().split(":").last().trim().split(" ").map(String::toBigInteger)
continue
}
if (line.isEmpty()) {
continue
}
if (line.endsWith(":")) {
currentMap = line.split(" ").first()
maps[currentMap] = mutableListOf()
continue
}
val ranges = line.trim().split(" ").map(String::toBigInteger)
maps[currentMap]!!.add(Range(ranges[1], ranges[1] + ranges[2], ranges[1] - ranges[0]))
}
return Pair(seeds, maps)
}
// Part 1
private fun solvePart1(seeds: List<BigInteger>, maps: Map<String, List<Range>>): BigInteger {
val res = seeds.map { lookupSeedInMaps(it, maps) }
return res.min()
}
private fun lookupSeedInMaps(seed: BigInteger, maps: Map<String, List<Range>>): BigInteger {
var current = seed
for ((_, ranges) in maps) {
for (range in ranges) {
if (current >= range.fromStart && current < range.fromEnd) {
current -= range.offset
break
}
}
}
return current
}
private fun lookupSeedInMaps(seed: Range, maps: Map<String, List<Range>>): BigInteger {
var current = listOf(seed)
for ((_, ranges) in maps) {
for (range in ranges) {
current = current.map { splitRanges(it, range) }.flatten()
}
current = current.map { Range(it.fromStart - it.offset, it.fromEnd - it.offset) }
}
return (current.minOf { it.fromStart })
}
// Part 2
private fun solvePart2(seeds: List<BigInteger>, maps: Map<String, List<Range>>): BigInteger {
var i = 0
val seedsRanges = mutableListOf<Range>()
while (i < seeds.count()) {
seedsRanges.add(Range(seeds[i], seeds[i] + seeds[++i]))
i++
}
val res = seedsRanges.map { lookupSeedInMaps(it, maps) }
return res.min()
}
private fun solvePart2Brute(seeds: List<BigInteger>, maps: Map<String, List<Range>>): BigInteger {
var i = 0
val seedsRanges = mutableListOf<Range>()
while (i < seeds.count()) {
seedsRanges.add(Range(seeds[i], seeds[i] + seeds[++i]))
i++
}
var res = 28809304000000.toBigInteger()
for (pair in seedsRanges) {
var k = pair.fromStart
while (k < pair.fromEnd) {
val t = lookupSeedInMaps(k, maps)
res = (BigInteger::min)(t, res)
k++
}
}
return res
}
fun splitRanges(first: Range, second: Range): List<Range> {
val res = mutableListOf<Range>()
// Overlap
if (first.fromStart < second.fromEnd && second.fromStart < first.fromEnd) {
var overlapStart = first.fromStart
var overlapEnd = first.fromEnd
if (first.fromStart < second.fromStart) {
res.add(Range(first.fromStart, second.fromStart))
overlapStart = second.fromStart
}
if (first.fromEnd > second.fromEnd) {
res.add(Range(second.fromEnd, first.fromEnd))
overlapEnd = second.fromEnd
}
res.add(Range(overlapStart, overlapEnd, second.offset))
} else {
res.add(first)
}
return res
} | 0 | Kotlin | 0 | 1 | 1cd45c2ce0822e60982c2c71cb4d8c75e37364a1 | 4,386 | aoc2023 | MIT License |
src/Day08.kt | jordanfarrer | 573,120,618 | false | {"Kotlin": 20954} | @file:Suppress("DuplicatedCode")
fun main() {
val day = "Day08"
fun parseMap(input: List<String>): List<Tree> {
val trees = mutableListOf<Tree>()
input.forEachIndexed { row, line ->
line.toCharArray().forEachIndexed { col, treeHeight ->
trees.add(Tree(row, col, treeHeight.digitToInt()))
}
}
return trees
}
fun findVisibleTrees(sortedTrees: Iterable<Tree>, startingHeight: Int = -1): List<Tree> {
var currentMaxHeight = startingHeight
val visibleTrees = mutableListOf<Tree>()
sortedTrees.forEach {
if (it.height > currentMaxHeight) {
visibleTrees.add(it)
currentMaxHeight = it.height
}
}
return visibleTrees.toList()
}
fun findViewingDistance(sortedTrees: Iterable<Tree>, originHeight: Int): Int {
var visible = 0
for (tree in sortedTrees) {
visible++
if (tree.height >= originHeight) break
}
return visible
}
fun findScenicScore(trees: Iterable<Tree>, row: Int, col: Int): Int {
val scores = mutableListOf<Int>()
val tree = trees.find { it.row == row && it.col == col } ?: error("Can't find tree")
val treesUp = trees.filter { it.col == col && it.row < row }.sortedByDescending { it.row }
val treesLeft = trees.filter { it.row == row && it.col < col }.sortedByDescending { it.col }
val treesRight = trees.filter { it.row == row && it.col > col }.sortedBy { it.col }
val treesDown = trees.filter { it.col == col && it.row > row }.sortedBy { it.row }
scores.add(findViewingDistance(treesUp, tree.height))
scores.add(findViewingDistance(treesLeft, tree.height))
scores.add(findViewingDistance(treesRight, tree.height))
scores.add(findViewingDistance(treesDown, tree.height))
return scores.reduce { acc, i -> acc * i }
}
@Suppress("unused")
fun display(trees: Iterable<Tree>, visible: Iterable<Tree>) {
val rows = trees.maxOf { it.row }
val cols = trees.maxOf { it.col }
for (row in 0..rows) {
var line = ""
for (col in 0..cols) {
val tree = trees.find { it.row == row && it.col == col } ?: error("Can't find tree")
val isVisible = visible.any { it.row == row && it.col == col }
if (isVisible) {
line += tree.height
} else {
line += " "
}
}
println(line)
}
}
fun part1(input: List<String>): Int {
val trees = parseMap(input)
val rows = trees.maxOf { it.row }
val cols = trees.maxOf { it.col }
val visibleTrees = mutableSetOf<Tree>()
// add perimeter
visibleTrees.addAll(visibleTrees.filter { it.row == 0 || it.row == rows || it.col == 0 || it.col == cols })
// columns (up and down)
for (col in 0..cols) {
val treesInColFromTop = trees.filter { it.col == col }.sortedBy { it.row }
visibleTrees.addAll(findVisibleTrees(treesInColFromTop))
val treesInColFromBottom = trees.filter { it.col == col }.sortedByDescending { it.row }
visibleTrees.addAll(findVisibleTrees((treesInColFromBottom)))
}
for (row in 0..rows) {
val treesInRowFromLeft = trees.filter { it.row == row }.sortedBy { it.col }
visibleTrees.addAll(findVisibleTrees(treesInRowFromLeft))
val treesInRowFromRight = trees.filter { it.row == row }.sortedByDescending { it.col }
visibleTrees.addAll(findVisibleTrees(treesInRowFromRight))
}
// display(trees, visibleTrees)
return visibleTrees.size
}
fun part2(input: List<String>): Int {
val trees = parseMap(input)
return trees.maxOf { findScenicScore(trees, it.row, it.col) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("${day}_test")
val part1Result = part1(testInput)
println("Part 1 (test): $part1Result")
check(part1Result == 21)
val part2Result = part2(testInput)
println("Part 2 (test): $part2Result")
check(part2Result == 8)
val input = readInput(day)
println(part1(input))
println(part2(input))
}
data class Tree(val row: Int, val col: Int, val height: Int) | 0 | Kotlin | 0 | 1 | aea4bb23029f3b48c94aa742958727d71c3532ac | 4,475 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/Day04.kt | elliaoster | 573,666,162 | false | {"Kotlin": 14556} | fun main() {
fun part1(input: List<String>): Int {
var counter = 0
for (line in input) {
//find the first range
val beforeComma = line.split(",").first()
val firstP1 = beforeComma.split("-").first().toInt()
val firstP2 = beforeComma.split("-").last().toInt()
//find the second range
val afterComma = line.split(",").last()
val secondP1 = afterComma.split("-").first().toInt()
val secondP2 = afterComma.split("-").last().toInt()
//see if the one fully contains the second
if ((firstP1 <= secondP1 && firstP2 >= secondP2) || (secondP1 <= firstP1 && secondP2 >= firstP2)) {
//add one to counter
counter++
}
}
return counter
}
fun part2(input: List<String>): Int {
var counter = 0
for (line in input) {
//find the first range
val beforeComma = line.split(",").first()
val firstP1 = beforeComma.split("-").first().toInt()
val firstP2 = beforeComma.split("-").last().toInt()
//find the second range
val afterComma = line.split(",").last()
val secondP1 = afterComma.split("-").first().toInt()
val secondP2 = afterComma.split("-").last().toInt()
//see if the one partially contains the second
if (secondP1 in firstP1..firstP2 || firstP1 in secondP1..secondP2) {
//add one to counter
counter++
}
}
return counter
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 27e774b133f9d5013be9a951d15cefa8cb01a984 | 1,890 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/tr/emreone/adventofcode/days/Day6.kt | EmRe-One | 434,793,519 | false | {"Kotlin": 44202} | package tr.emreone.adventofcode.days
import kotlin.math.max
object Day6 {
enum class Command {
ON,
OFF,
TOGGLE
}
fun part1(input: List<String>): Int {
val regex = """^(turn on|turn off|toggle) (\d+),(\d+) through (\d+),(\d+)$""".toRegex()
val lightsGrid = Array(1000) { IntArray(1000) { 0 } }
input.forEach {
val (command, x1, y1, x2, y2) = regex.matchEntire(it)!!.destructured
val commandValue = when (command) {
"turn on" -> Command.ON
"turn off" -> Command.OFF
"toggle" -> Command.TOGGLE
else -> throw IllegalArgumentException("Unknown command: $command")
}
for (x in x1.toInt()..x2.toInt()) {
for (y in y1.toInt()..y2.toInt()) {
when(commandValue) {
Command.ON -> lightsGrid[x][y] = 1
Command.OFF -> lightsGrid[x][y] = 0
Command.TOGGLE -> lightsGrid[x][y] = (lightsGrid[x][y] + 1) % 2
}
}
}
}
return lightsGrid.sumOf { line ->
line.sum()
}
}
fun part2(input: List<String>): Int {
val regex = """^(turn on|turn off|toggle) (\d+),(\d+) through (\d+),(\d+)$""".toRegex()
val lightsGrid = Array(1000) { IntArray(1000) { 0 } }
input.forEach {
val (command, x1, y1, x2, y2) = regex.matchEntire(it)!!.destructured
val commandValue = when (command) {
"turn on" -> +1
"turn off" -> -1
"toggle" -> +2
else -> throw IllegalArgumentException("Unknown command: $command")
}
for (x in x1.toInt()..x2.toInt()) {
for (y in y1.toInt()..y2.toInt()) {
lightsGrid[x][y] = max(0, lightsGrid[x][y] + commandValue)
}
}
}
return lightsGrid.sumOf { line ->
line.sum()
}
}
}
| 0 | Kotlin | 0 | 0 | 57f6dea222f4f3e97b697b3b0c7af58f01fc4f53 | 2,090 | advent-of-code-2015 | Apache License 2.0 |
kotlin/graphs/lca/Lca.kt | polydisc | 281,633,906 | true | {"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571} | package graphs.lca
import java.util.stream.Stream
// Answering LCA queries in O(log(n)) with O(n) preprocessing
class Lca(tree: Array<List<Integer>>, root: Int) {
var depth: IntArray
var dfs_order: IntArray
var cnt: Int
var first: IntArray
var minPos: IntArray
var n: Int
fun dfs(tree: Array<List<Integer>>, u: Int, d: Int) {
depth[u] = d
dfs_order[cnt++] = u
for (v in tree[u]) if (depth[v] == -1) {
dfs(tree, v, d + 1)
dfs_order[cnt++] = u
}
}
fun buildTree(node: Int, left: Int, right: Int) {
if (left == right) {
minPos[node] = dfs_order[left]
return
}
val mid = left + right shr 1
buildTree(2 * node + 1, left, mid)
buildTree(2 * node + 2, mid + 1, right)
minPos[node] =
if (depth[minPos[2 * node + 1]] < depth[minPos[2 * node + 2]]) minPos[2 * node + 1] else minPos[2 * node + 2]
}
fun lca(a: Int, b: Int): Int {
return minPos(Math.min(first[a], first[b]), Math.max(first[a], first[b]), 0, 0, n - 1)
}
fun minPos(a: Int, b: Int, node: Int, left: Int, right: Int): Int {
if (a == left && right == b) return minPos[node]
val mid = left + right shr 1
return if (a <= mid && b > mid) {
val p1 = minPos(a, Math.min(b, mid), 2 * node + 1, left, mid)
val p2 = minPos(Math.max(a, mid + 1), b, 2 * node + 2, mid + 1, right)
if (depth[p1] < depth[p2]) p1 else p2
} else if (a <= mid) {
minPos(a, Math.min(b, mid), 2 * node + 1, left, mid)
} else if (b > mid) {
minPos(Math.max(a, mid + 1), b, 2 * node + 2, mid + 1, right)
} else {
throw RuntimeException()
}
}
companion object {
// Usage example
fun main(args: Array<String?>?) {
val tree: Array<List<Integer>> = Stream.generate { ArrayList() }.limit(5).toArray { _Dummy_.__Array__() }
tree[0].add(1)
tree[0].add(2)
tree[1].add(3)
tree[1].add(4)
val lca = Lca(tree, 0)
System.out.println(0 == lca.lca(1, 2))
System.out.println(1 == lca.lca(3, 4))
System.out.println(0 == lca.lca(4, 2))
}
}
init {
val nodes = tree.size
depth = IntArray(nodes)
Arrays.fill(depth, -1)
n = 2 * nodes - 1
dfs_order = IntArray(n)
cnt = 0
dfs(tree, root, 0)
minPos = IntArray(4 * n)
buildTree(0, 0, n - 1)
first = IntArray(nodes)
Arrays.fill(first, -1)
for (i in dfs_order.indices) if (first[dfs_order[i]] == -1) first[dfs_order[i]] = i
}
}
| 1 | Java | 0 | 0 | 4566f3145be72827d72cb93abca8bfd93f1c58df | 2,748 | codelibrary | The Unlicense |
src/Day25.kt | AlaricLightin | 572,897,551 | false | {"Kotlin": 87366} | fun main() {
check(snafuToDecimal("1=0") == 15L)
check(snafuToDecimal("1-0") == 20L)
check(snafuToDecimal("1=11-2") == 2022L)
check(snafuToDecimal("1-0---0") == 12345L)
check(snafuToDecimal("1121-1110-1=0") == 314159265L)
check(decimalToSnafu(15) == "1=0")
check(decimalToSnafu(20) == "1-0")
check(decimalToSnafu(2022) == "1=11-2")
check(decimalToSnafu(12345) == "1-0---0")
check(decimalToSnafu(314159265) == "1121-1110-1=0")
fun solution(input: List<String>): String {
return decimalToSnafu(
input.sumOf { snafuToDecimal(it) }
)
}
check(solution(readInput("Day25_test")) == "2=-1=0")
println(solution(readInput("Day25")))
}
private val snafuDigits: Map<Char, Int> = mapOf(
'2' to 2,
'1' to 1,
'0' to 0,
'-' to -1,
'=' to -2
)
private fun snafuToDecimal(s: String): Long {
var result = 0L
var multiplier = 1L
for (i in (0..s.lastIndex).reversed()) {
result += snafuDigits[s[i]]!! * multiplier
multiplier *= 5L
}
return result
}
private fun decimalToSnafu(a: Long): String {
val resultList: MutableList<Int> = mutableListOf()
var current: Long = a
var addToNext = 0
while (current > 0) {
val normalDigit: Int = (current % 5 + addToNext).toInt()
addToNext = if (normalDigit <= 2) {
resultList.add(normalDigit)
0
} else {
resultList.add(normalDigit - 5)
1
}
current /= 5
}
if (addToNext > 0)
resultList.add(1)
return resultList.reversed().joinToString(separator = "") {
when (it) {
-2 -> "="
-1 -> "-"
in 0..2 -> it.toString()
else -> throw IllegalArgumentException()
}
}
} | 0 | Kotlin | 0 | 0 | ee991f6932b038ce5e96739855df7807c6e06258 | 1,812 | AdventOfCode2022 | Apache License 2.0 |
src/Day07.kt | adrianforsius | 573,044,406 | false | {"Kotlin": 68131} |
import org.assertj.core.api.Assertions.assertThat
//fun part1(path: Path): Int = path.useLines{ lines ->
// lines
// .count()
data class Node(var children:List<Node>, val name: String, var size: Int = 0, val marked: Boolean=false) {
var parent: Node? = null
}
fun cd(curr: Node, root: Node, cmd: String): Node =
when (cmd) {
"/" -> root
".." -> curr.parent!!
else -> curr.children.first{ it.name == cmd }
}
fun addFolder(curr: Node, name: String) {
if (name in curr.children.filter{ it.size == 0}.map{ it.name }.toList()) return
val folder = Node(children=emptyList(), name=name)
folder.parent = curr
curr.children = curr.children + folder
return
}
fun addFile(curr: Node, size: Int, name: String) {
val file = Node(emptyList(), name, size)
file.parent = curr
curr.children = curr.children + file
curr.children.toSet().toList()
return
}
fun ls(curr: Node, files: List<String>) {
for (f in files) {
if (f == "") continue
if (f.startsWith("dir")) {
addFolder(curr, f.split(" ").last())
} else {
val (size, name) = f.split(" ")
addFile(curr, size.toInt(), name )
}
}
}
data class PairV2(var current: Int, var fit: Int)
fun traverse(n: Node, pair: Pair<Int, Int>): Pair<Int, Int> {
if (n.children.size == 0) {
return Pair(n.size, pair.second)
}
var current = 0
var p = pair
for (n in n.children) {
p = traverse(n, p)
current += p.first
}
var total = p.second
if (current < 100_000) {
total += current
}
return Pair(current, total)
}
fun traverseTotal(n: Node, total: Int): Int {
if (n.children.size == 0) {
return n.size
}
var current = 0
for (n in n.children) {
current += traverseTotal(n, total)
}
return current
}
fun traverse_v2(n: Node, pair: PairV2, missing: Int): PairV2 {
if (n.children.size == 0) {
return PairV2(n.size, pair.fit)
}
var current = 0
var p = pair
for (n in n.children) {
p = traverse_v2(n, p, missing)
current += p.current
}
var fit = p.fit
if (current >= missing && current < fit) {
fit = current
}
return PairV2(current, fit)
}
fun main() {
fun part1(input: String): Int {
val root = Node(emptyList(), "/", 0)
var curr = root
val cmd = input.split("$ ").drop(1)
for (i in cmd.drop(1)) {
val start = i.slice(0..1)
when (start) {
"ls" -> ls(curr, i.split("\n").drop(1))
"cd" -> curr = cd(curr, root, i.trimEnd('\n').split(" ").last())
else -> error("invalid command")
}
}
return traverse(root, Pair(0,0)).second
}
fun part2(input: String): Int {
val root = Node(emptyList(), "/", 0)
var curr = root
val cmd = input.split("$ ").drop(1)
for (i in cmd.drop(1)) {
val start = i.slice(0..1)
when (start) {
"ls" -> ls(curr, i.split("\n").drop(1))
"cd" -> curr = cd(curr, root, i.trimEnd('\n').split(" ").last())
else -> error("invalid command")
}
}
val total = traverseTotal(root, 0)
val used = 70_000_000 - total
val missing = 30_000_000 - used
return traverse_v2(root, PairV2(0, Int.MAX_VALUE), missing).fit
}
// test if implementation meets criteria from the description, like:
// Tes
val testInput = readText("Day07_test")
val output1 = part1(testInput)
assertThat(output1).isEqualTo(95437)
// Answer
val input = readText("Day07")
val outputAnswer1 = part1(input)
assertThat(outputAnswer1).isEqualTo(2104783)
// Test
// val output2 = part2(testInput)
// assertThat(output2).isEqualTo(24933642)
// Answer
val outputAnswer2 = part2(input)
assertThat(outputAnswer2).isEqualTo(5883165)
}
| 0 | Kotlin | 0 | 0 | f65a0e4371cf77c2558d37bf2ac42e44eeb4bdbb | 4,039 | kotlin-2022 | Apache License 2.0 |
archive/src/main/kotlin/com/grappenmaker/aoc/year17/Day07.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year17
import com.grappenmaker.aoc.PuzzleSet
import com.grappenmaker.aoc.diff
import kotlin.math.absoluteValue
fun PuzzleSet.day7() = puzzle(day = 7) {
val tree = inputLines.map { l ->
val parts = l.split(" -> ")
val (name, weightPart) = parts.first().split(" ")
val weight = weightPart.drop(1).dropLast(1).toInt()
val children = parts.getOrNull(1)?.split(", ")?.toSet() ?: emptySet()
DiscEntry(name, weight, children)
}
fun DiscEntry.parent() = (tree - this).singleOrNull { name in it.children }
val head = tree.single { it.parent() == null }
partOne = head.name
val byName = tree.associateBy { it.name }
val weights = mutableMapOf<String, Int>()
fun DiscEntry.weight(): Int = weights.getOrPut(name) { weight + children.sumOf { byName.getValue(it).weight() } }
fun DiscEntry.foundChildren() = children.map { byName.getValue(it) }
fun DiscEntry.balanced() = foundChildren().map { it.weight() }.distinct().singleOrNull() != null
fun DiscEntry.find(offset: Int? = null): Int = when {
offset != null && balanced() -> weight - offset
else -> {
val toSearch = foundChildren()
val wrong = toSearch.single { e ->
val other = toSearch - e
val target = (other.firstOrNull() ?: e).weight()
other.all { it.weight() == target } && e.weight != target
}
wrong.find(
offset ?: toSearch.map { it.weight() }.toSet()
.also { assert(it.size == 2) }.diff().absoluteValue
)
}
}
partTwo = head.find().s()
}
private data class DiscEntry(val name: String, val weight: Int, val children: Set<String>) | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 1,772 | advent-of-code | The Unlicense |
2k23/aoc2k23/src/main/kotlin/01.kt | papey | 225,420,936 | false | {"Rust": 88237, "Kotlin": 63321, "Elixir": 54197, "Crystal": 47654, "Go": 44755, "Ruby": 24620, "Python": 23868, "TypeScript": 5612, "Scheme": 117} | package d01
import input.read
fun main() {
println("Part 1: ${part1(read("01.txt"))}")
println("Part 2: ${part2(read("01.txt"))}")
}
fun part1(lines: List<String>): Int {
return lines.map { line -> line.filter { it.isDigit() } }
.map(::firstLastDigits)
.sumOf { it.toInt() }
}
fun part2(lines: List<String>): Int {
return lines.map(::replaceCharsWithDigits)
.map { line -> line.filter { it.isDigit() } }
.map(::firstLastDigits)
.sumOf { it.toInt() }
}
fun firstLastDigits(line: String): String {
val digits = line.toCharArray()
return "${digits.first()}${digits.last()}"
}
fun replaceCharsWithDigits(line: String): String {
val digitsMap = mapOf(
"one" to 1,
"two" to 2,
"three" to 3,
"four" to 4,
"five" to 5,
"six" to 6,
"seven" to 7,
"eight" to 8,
"nine" to 9,
"zero" to 0,
)
return digitsMap.entries.fold(line) { acc, entry ->
val replace = "%s%s%s".format(entry.key, entry.value.toString(), entry.key)
acc.replace(entry.key, replace)
}
}
| 0 | Rust | 0 | 3 | cb0ea2fc043ebef75aff6795bf6ce8a350a21aa5 | 1,126 | aoc | The Unlicense |
src/main/kotlin/com/hj/leetcode/kotlin/problem1319/Solution2.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem1319
/**
* LeetCode page: [1319. Number of Operations to Make Network Connected](https://leetcode.com/problems/number-of-operations-to-make-network-connected/);
*/
class Solution2 {
/* Complexity:
* Time O(E) and Space O(n) where E is the size of connections;
*/
fun makeConnected(n: Int, connections: Array<IntArray>): Int {
val numCables = connections.size
if (numCables < n - 1) return -1
val computerUnionFind = UnionFind(n, connections)
val numConnectedComponents = numConnectedComponents(computerUnionFind)
return numConnectedComponents - 1
}
private class UnionFind(numComputers: Int, connections: Array<IntArray>) {
private val parent = IntArray(numComputers) { it }
private val rank = IntArray(numComputers)
init {
for ((aComputer, bComputer) in connections) {
union(aComputer, bComputer)
}
}
private fun union(aComputer: Int, bComputer: Int) {
val aParent = find(aComputer)
val bParent = find(bComputer)
if (aParent == bParent) return
val aRank = rank[aComputer]
val bRank = rank[bComputer]
when {
aRank < bRank -> parent[aParent] = bParent
aRank > bRank -> parent[bParent] = aParent
else -> {
parent[aParent] = bParent
rank[bParent]++
}
}
}
private tailrec fun find(computer: Int): Int {
val isRoot = parent[computer] == computer
return if (isRoot) computer else find(parent[computer])
}
fun numUnions(): Int {
val computers = parent.indices
return computers.count { it == parent[it] }
}
}
private fun numConnectedComponents(computerUnionFind: UnionFind): Int {
return computerUnionFind.numUnions()
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,005 | hj-leetcode-kotlin | Apache License 2.0 |
leetcode-75-kotlin/src/main/kotlin/DetermineIfTwoStringsAreClose.kt | Codextor | 751,507,040 | false | {"Kotlin": 49566} | /**
* Two strings are considered close if you can attain one from the other using the following operations:
*
* Operation 1: Swap any two existing characters.
* For example, abcde -> aecdb
* Operation 2: Transform every occurrence of one existing character into another existing character,
* and do the same with the other character.
* For example, aacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's)
* You can use the operations on either string as many times as necessary.
*
* Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise.
*
*
*
* Example 1:
*
* Input: word1 = "abc", word2 = "bca"
* Output: true
* Explanation: You can attain word2 from word1 in 2 operations.
* Apply Operation 1: "abc" -> "acb"
* Apply Operation 1: "acb" -> "bca"
* Example 2:
*
* Input: word1 = "a", word2 = "aa"
* Output: false
* Explanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations.
* Example 3:
*
* Input: word1 = "cabbba", word2 = "abbccc"
* Output: true
* Explanation: You can attain word2 from word1 in 3 operations.
* Apply Operation 1: "cabbba" -> "caabbb"
* Apply Operation 2: "caabbb" -> "baaccc"
* Apply Operation 2: "baaccc" -> "abbccc"
*
*
* Constraints:
*
* 1 <= word1.length, word2.length <= 10^5
* word1 and word2 contain only lowercase English letters.
* @see <a href="https://leetcode.com/problems/determine-if-two-strings-are-close/">LeetCode</a>
*/
fun closeStrings(word1: String, word2: String): Boolean {
if (word1.length != word2.length) return false
val frequencyArray1 = IntArray(26)
val frequencyArray2 = IntArray(26)
word1.forEach { char ->
frequencyArray1[char - 'a'] = 1 + frequencyArray1[char - 'a']
}
word2.forEach { char ->
frequencyArray2[char - 'a'] = 1 + frequencyArray2[char - 'a']
}
val frequencyOfFrequencyMap1 = mutableMapOf<Int, Int>()
val frequencyOfFrequencyMap2 = mutableMapOf<Int, Int>()
for ((index, frequency1) in frequencyArray1.withIndex()) {
if (frequency1 != 0 && frequencyArray2[index] == 0) {
return false
} else {
val frequency2 = frequencyArray2[index]
frequencyOfFrequencyMap1[frequency1] = 1 + frequencyOfFrequencyMap1.getOrDefault(frequency1, 0)
frequencyOfFrequencyMap2[frequency2] = 1 + frequencyOfFrequencyMap2.getOrDefault(frequency2, 0)
}
}
if (frequencyOfFrequencyMap1.size != frequencyOfFrequencyMap2.size) {
return false
}
frequencyOfFrequencyMap1.entries.forEach { entry ->
if (!frequencyOfFrequencyMap2.contains(entry.key) || entry.value != frequencyOfFrequencyMap2[entry.key]) {
return false
}
}
return true
}
| 0 | Kotlin | 0 | 0 | 0511a831aeee96e1bed3b18550be87a9110c36cb | 2,801 | leetcode-75 | Apache License 2.0 |
year2021/day09/part1/src/main/kotlin/com/curtislb/adventofcode/year2021/day09/part1/Year2021Day09Part1.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | /*
--- Day 9: Smoke Basin ---
These caves seem to be lava tubes. Parts are even still volcanically active; small hydrothermal
vents release smoke into the caves that slowly settles like rain.
If you can model how the smoke flows through the caves, you might be able to avoid it and be that
much safer. The submarine generates a heightmap of the floor of the nearby caves for you (your
puzzle input).
Smoke flows to the lowest point of the area it's in. For example, consider the following heightmap:
```
2199943210
3987894921
9856789892
8767896789
9899965678
```
Each number corresponds to the height of a particular location, where 9 is the highest and 0 is the
lowest a location can be.
Your first goal is to find the low points - the locations that are lower than any of its adjacent
locations. Most locations have four adjacent locations (up, down, left, and right); locations on the
edge or corner of the map have three or two adjacent locations, respectively. (Diagonal locations do
not count as adjacent.)
In the above example, there are four low points, all highlighted: two are in the first row (a 1 and
a 0), one is in the third row (a 5), and one is in the bottom row (also a 5). All other locations on
the heightmap have some lower adjacent location, and so are not low points.
The risk level of a low point is 1 plus its height. In the above example, the risk levels of the low
points are 2, 1, 6, and 6. The sum of the risk levels of all low points in the heightmap is
therefore 15.
Find all of the low points on your heightmap. What is the sum of the risk levels of all low points
on your heightmap?
*/
package com.curtislb.adventofcode.year2021.day09.part1
import com.curtislb.adventofcode.year2021.day09.basin.HeightMap
import java.nio.file.Path
import java.nio.file.Paths
/**
* Returns the solution to the puzzle for 2021, day 9, part 1.
*
* @param inputPath The path to the input file for this puzzle.
*/
fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Int {
val heightMap = HeightMap(inputPath.toFile().readText())
return heightMap.findLowPoints().sumOf { heightMap.riskLevel(it) }
}
fun main() {
println(solve())
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 2,185 | AdventOfCode | MIT License |
src/Day04.kt | brigittb | 572,958,287 | false | {"Kotlin": 46744} | fun main() {
fun parse(input: List<String>): List<List<IntRange>> =
input
.flatMap { it.split(",") }
.map { it.split("-") }
.map { (start, end) -> IntRange(start.toInt(), end.toInt()) }
.chunked(2)
fun part1(input: List<List<IntRange>>): Int =
input
.count { (first, second) ->
first.contains(second.first) && first.contains(second.last) ||
second.contains(first.first) && second.contains(first.last)
}
fun part2(input: List<List<IntRange>>): Int =
input
.map { (first, second) -> first.intersect(second) }
.count { it.isNotEmpty() }
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(parse(testInput)) == 2)
check(part2(parse(testInput)) == 4)
val input = readInput("Day04")
println(part1(parse(input)))
println(part2(parse(input)))
}
| 0 | Kotlin | 0 | 0 | 470f026f2632d1a5147919c25dbd4eb4c08091d6 | 1,012 | aoc-2022 | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.