path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/com/leetcode/P447.kt | antop-dev | 229,558,170 | false | {"Kotlin": 695315, "Java": 213000} | package com.leetcode
// https://github.com/antop-dev/algorithm/issues/332
class P447 {
fun numberOfBoomerangs(points: Array<IntArray>): Int {
var answer = 0
for (i in points.indices) {
val map = mutableMapOf<Int, Int>()
for (j in points.indices) {
if (i == j) continue
val distance = distance(points[i], points[j])
map[distance] = (map[distance] ?: 0) + 1
}
// combinations of boomerang tuple
for (count in map.values) {
answer += count * (count - 1)
}
}
return answer
}
private fun distance(p1: IntArray, p2: IntArray): Int {
// 두 포인트간에 거리 구하기
// 원래는 제곱과 루트(sqrt)를 계산해야 하지만
// 모든 결과가 동일한 연산을 하므로 생략 가능하다
val dx = p1[0] - p2[0]
val dy = p1[1] - p2[1]
return (dx * dx) + (dy * dy)
}
}
| 1 | Kotlin | 0 | 0 | 9a3e762af93b078a2abd0d97543123a06e327164 | 1,013 | algorithm | MIT License |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions29.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.special
import com.qiaoyuang.algorithm.round1.SingleDirectionNode
fun test29() {
val node1 = SingleDirectionNode(element = 1)
node1.next = node1
printlnResult(node1, 2)
val node2 = SingleDirectionNode(element = 2)
node2.next = node2
printlnResult(node2, 1)
printlnResult(linkedList(), 8)
}
/**
* Questions 29: Insert a node to a sorted circle linked list
*/
private infix fun <T : Comparable<T>> SingleDirectionNode<T>.insert(value: T): SingleDirectionNode<T> {
var pointer = this
do {
if (pointer.element <= value && pointer.next!!.element > value)
break
else
pointer = pointer.next!!
} while (pointer.next !== this)
val newNode = SingleDirectionNode(value, pointer.next)
pointer.next = newNode
return if (value <= element) newNode else this
}
private fun printlnResult(node: SingleDirectionNode<Int>, num: Int) {
print("Insert the $num to linked list: ")
printlnCircleLinkedList(node)
print("We got: ")
printlnCircleLinkedList(node insert num)
}
private fun <T> printlnCircleLinkedList(node: SingleDirectionNode<T>?) {
if (node == null) {
println("empty")
return
}
var _node = node
do {
print(_node!!.element)
_node = _node.next
if (_node !== node)
print(", ")
} while (_node !== node)
println(';')
}
private fun linkedList(): SingleDirectionNode<Int> {
val head = SingleDirectionNode(element = 1)
head.next =
SingleDirectionNode(element = 2, next =
SingleDirectionNode(element = 3, next =
SingleDirectionNode(element = 4, next =
SingleDirectionNode(element = 5, next =
SingleDirectionNode(element = 6, next =
SingleDirectionNode(element = 7, next =
SingleDirectionNode(element = 9, next =
SingleDirectionNode(element = 10, next =
SingleDirectionNode(element = 11, next =
SingleDirectionNode(element = 12, head))))))))))
return head
}
| 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 2,053 | Algorithm | Apache License 2.0 |
src/main/kotlin/g1201_1300/s1297_maximum_number_of_occurrences_of_a_substring/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1201_1300.s1297_maximum_number_of_occurrences_of_a_substring
// #Medium #String #Hash_Table #Sliding_Window
// #2023_06_08_Time_253_ms_(75.00%)_Space_38_MB_(100.00%)
@Suppress("UNUSED_PARAMETER")
class Solution {
fun maxFreq(s: String, max: Int, minSize: Int, maxSize: Int): Int {
// the map of occurrences
val sub2Count: MutableMap<String, Int> = HashMap()
// sliding window indices
var lo = 0
var hi = minSize - 1
var maxCount = 0
// unique letters counter
val uniq = CharArray(26)
var uniqCount = 0
// initial window calculation - `hi` is excluded here!
for (ch in s.substring(lo, hi).toCharArray()) {
uniq[ch.code - 'a'.code] = uniq[ch.code - 'a'.code] + 1.toChar().code
if (uniq[ch.code - 'a'.code].code == 1) {
uniqCount++
}
}
while (hi < s.length) {
// handle increment of hi
val hiCh = s[hi]
uniq[hiCh.code - 'a'.code] = uniq[hiCh.code - 'a'.code] + 1.toChar().code
if (uniq[hiCh.code - 'a'.code].code == 1) {
uniqCount++
}
++hi
// add the substring to the map of occurences
val sub = s.substring(lo, hi)
if (uniqCount <= max) {
var count = 1
if (sub2Count.containsKey(sub)) {
count += sub2Count[sub]!!
}
sub2Count[sub] = count
maxCount = Math.max(maxCount, count)
}
// handle increment of lo
val loCh = s[lo]
uniq[loCh.code - 'a'.code] = uniq[loCh.code - 'a'.code] - 1.toChar().code
if (uniq[loCh.code - 'a'.code].code == 0) {
uniqCount--
}
++lo
}
return maxCount
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,892 | LeetCode-in-Kotlin | MIT License |
src/Misc.kt | Flame239 | 570,094,570 | false | {"Kotlin": 60685} | import java.io.File
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import kotlin.system.measureNanoTime
fun readInput(name: String) = File("input", "$name.txt").readLines()
fun gcd(a: Int, b: Int): Int {
if (b == 0) return a
return gcd(b, a % b)
}
fun lcm(a: Int, b: Int): Int {
return a / gcd(a, b) * b
}
fun lcmList(input: List<Int>): Int {
return input.reduce { a, b -> lcm(a, b) }
}
fun parseC(s: String): C = s.split(", ").map { it.substring(2) }.map { it.toInt() }.let { (x, y) -> C(x, y) }
private val red = "\u001b[0;31m"
private val green = "\u001b[32m"
private val reset = "\u001b[0m"
fun measure(block: () -> Any) {
var min: Long = Long.MAX_VALUE
var result: Any = ""
repeat(1) {
measureNanoTime {
result = block()
}.also { min = min(min, it) }
}
println(red + result + reset)
println(green + "⏳ " + min / 1000000 + " ms" + reset)
}
| 0 | Kotlin | 0 | 0 | 27f3133e4cd24b33767e18777187f09e1ed3c214 | 944 | advent-of-code-2022 | Apache License 2.0 |
leetcode/src/offer/middle/Offer45.kt | zhangweizhe | 387,808,774 | false | null | package offer.middle
import java.lang.StringBuilder
fun main() {
// 剑指 Offer 45. 把数组排成最小的数
// https://leetcode.cn/problems/ba-shu-zu-pai-cheng-zui-xiao-de-shu-lcof/
println(minNumber(intArrayOf(3,30,34,5,9)))
}
fun minNumber(nums: IntArray): String {
mergeSort(nums, 0, nums.size - 1)
val sb = StringBuilder()
for (i in nums) {
sb.append(i)
}
return sb.toString()
}
private fun mergeSort(nums: IntArray, start: Int, end: Int) {
if (start >= end) {
return
}
val mid = (start + end) / 2
mergeSort(nums, start, mid)
mergeSort(nums, mid+1, end)
var leftIndex = start
var rightIndex = mid + 1
var k = 0
val tmpArray = IntArray(end - start + 1)
while (leftIndex <= mid && rightIndex <= end) {
val leftNum = nums[leftIndex] //6
val rightNum = nums[rightIndex] //35
val m = leftNum.toString() + rightNum.toString() //635
val n = rightNum.toString() + leftNum.toString() //356
if (m > n) {
tmpArray[k++] = rightNum
rightIndex++
}else {
tmpArray[k++] = leftNum
leftIndex++
}
}
while (leftIndex <= mid) {
tmpArray[k++] = nums[leftIndex++]
}
while (rightIndex <= end) {
tmpArray[k++] = nums[rightIndex++]
}
// 放回原数组
for (i in tmpArray.indices) {
nums[start + i] = tmpArray[i]
}
} | 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 1,451 | kotlin-study | MIT License |
Kotlin/Corrections/chapitre 3/ProceduresFonctions/src/demo.kt | P-Giraffe | 80,914,727 | false | {"C#": 69509, "Java": 27950, "Swift": 17118, "Kotlin": 9670} | import NePasToucher.readInt
fun main(args: Array<String>) {
ex4()
}
fun ex1() {
pythagore(2.2,5.0)
}
fun pythagore(coteA:Double, coteB:Double) {
val carrehyp = coteA*coteA + coteB*coteB
val hyp = Math.sqrt(carrehyp)
println("L'hypothénuse mesure ${hyp}")
}
fun ex2() {
demandeValeurs(7)
demandeValeurs(4)
demandeValeurs(2)
}
fun demandeValeurs(diviseur:Int) {
var nbValeurs = 0
var nbDivisibles = 0
do {
print("Entrez une valeur (ou 0 pour arrêter) : ")
val valeurSaisie = readInt()
if (valeurSaisie != 0) {
if (valeurSaisie % diviseur == 0) {
nbDivisibles += 1
}
nbValeurs += 1
}
} while (valeurSaisie != 0)
println("Vous avez saisi ${nbValeurs} valeur${if (nbValeurs > 1) "s" else ""} dont ${nbDivisibles} divisible(s) par " + diviseur)
}
fun ex3() {
multiplication(40)
}
fun multiplication(dimension: Int) {
val nbChiffresMax = Math.ceil(Math.log10((dimension * dimension).toDouble() + 1.0)).toInt()
for (ligne in 1..dimension) {
for (colonne in 1..dimension) {
print("${ligne*colonne}".padStart(nbChiffresMax + 1))
}
println()
}
}
fun ex4() {
println("0 == ${sommeProcheV2(0)}")
println("10 == ${sommeProcheV2(10)}")
println("10 == ${sommeProcheV2(11)}")
println("15 == ${sommeProcheV2(14)}")
println("15 == ${sommeProcheV2(18)}")
}
fun sommeProche(cible: Int): Int {
var borneSup = 0
var borneInf:Int
var passage = 0
do {
passage += 1
borneInf = borneSup
borneSup += passage
} while(borneSup<cible)
if (borneSup==cible || cible-borneInf>borneSup-cible) {
return borneSup
}else {
return borneInf
}
}
fun sommeProcheV2(cible:Int) : Int{
var sumNb = 0
var compteur = 0
do {
compteur++
sumNb += compteur
} while (sumNb < cible)
if (Math.abs(sumNb - compteur - cible) <= sumNb - cible) {
sumNb -= compteur
}
println("La somme la plus proche est ${sumNb}")
return sumNb
}
| 0 | C# | 0 | 2 | 2df53ce5ec4673e6d3bcc202376d40d3d3a6bdd9 | 2,124 | BasesProgrammation | Apache License 2.0 |
kotlin/day02/deep.kt | aesdeef | 433,698,136 | false | {"Python": 118972, "Elm": 30537, "JavaScript": 6228, "Kotlin": 2090, "HTML": 244} | package day02
import java.io.File
data class Instruction(val command: String, val value: Int)
fun main() {
val instructions = parseInput()
val part1 = solvePart1(instructions)
val part2 = solvePart2(instructions)
println(part1)
println(part2)
}
fun parseInput(): List<Instruction> {
return File("../../input/02.txt")
.readLines()
.map { it.split(" ") }
.map { Instruction(it[0], it[1].toInt()) }
}
fun solvePart1(instructions: List<Instruction>): Int {
var horizontal = 0
var depth = 0
instructions.forEach {
val (command, value) = it
when (command) {
"forward" -> horizontal += value
"down" -> depth += value
"up" -> depth -= value
}
}
return horizontal * depth
}
fun solvePart2(instructions: List<Instruction>): Int {
var aim = 0
var horizontal = 0
var depth = 0
instructions.forEach {
val (command, value) = it
when (command) {
"forward" -> {
horizontal += value
depth += aim * value
}
"down" -> aim += value
"up" -> aim -= value
}
}
return horizontal * depth
}
| 0 | Python | 0 | 2 | 4561bcf12ac03d360f5b28c48ef80134f97613b9 | 1,231 | advent-of-code-2021 | MIT License |
app/src/main/java/com/github/shannonbay/studybuddy/TextToSSMLConverter.kt | shannonbay | 686,516,365 | false | {"Kotlin": 37122} | package com.github.shannonbay.studybuddy
class TextToSSMLIterator(inputText: String) : Iterator<String> {
private val sentences: List<String> = inputText.split(Regex("[.!?]"))
private var sentenceIndex = 0
private var phraseIndex = 0
private var wordIndex = 0
private var emphasisLevel = 1
override fun hasNext(): Boolean {
return sentenceIndex < sentences.size
}
fun isSimpleWord(word: String): Boolean {
val simpleWords = setOf("the", "to", "it", "that") // Define your list of simple words
return word.toLowerCase() in simpleWords
}
override fun next(): String {
val sentence = sentences[sentenceIndex]
val phrases = sentence.split(Regex("[,;]|\\b(And|Or|But)\\b"))
if (phraseIndex < phrases.size) {
val phrase = phrases[phraseIndex]
val words = phrase.trim().split(" ")
// Generate SSML for the current word with emphasis
var closed: Boolean = false
val emphasizedWord = words.mapIndexed { index, w ->
if (index == wordIndex*3) {
/*if (isSimpleWord(w)) {
// Skip simple words and move to the next wordIndex
wordIndex = (wordIndex + 1) % words.size
w // Return the original word without emphasis
} else {*/
"<prosody rate=\"slow\" pitch=\"+10%\"><emphasis level='x-strong'>$w"
} else if (index == wordIndex*3+2) {
closed = true
"$w</emphasis></prosody>"
} else w
}.joinToString(" ")
// Increment indices for the next iteration
wordIndex = (wordIndex + 1) % (words.size/3)
if (wordIndex == 0) {
phraseIndex++
}
// Emphasize a different word in each repetition
emphasisLevel = (emphasisLevel % words.size) + 1
if(!closed) return "<speak>$emphasizedWord</emphasis></prosody></speak>"
// Return the generated SSML
return "<speak>$emphasizedWord</speak>"
} else {
// Move to the next phrase
phraseIndex = 0
sentenceIndex++
return "<speak><break time=\"500ms\"/></speak>"
}
}
}
fun main() {
val inputText = "Hello, World! This is a test sentence and another example."
val ssmlIterator = TextToSSMLIterator(inputText)
while (ssmlIterator.hasNext()) {
val ssmlPhrase = ssmlIterator.next()
println(ssmlPhrase)
}
}
| 0 | Kotlin | 0 | 0 | 633eb6441cfe5cb602248322cb5fd2f014898194 | 2,628 | study-buddy | MIT License |
src/main/kotlin/g2301_2400/s2318_number_of_distinct_roll_sequences/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2301_2400.s2318_number_of_distinct_roll_sequences
// #Hard #Dynamic_Programming #Memoization #2023_06_30_Time_441_ms_(100.00%)_Space_49.6_MB_(100.00%)
class Solution {
private val memo = Array(10001) { Array(7) { IntArray(7) } }
private val mod = 1000000007
private val m = arrayOf(
intArrayOf(1, 2, 3, 4, 5, 6),
intArrayOf(2, 3, 4, 5, 6),
intArrayOf(1, 3, 5),
intArrayOf(1, 2, 4, 5),
intArrayOf(1, 3, 5),
intArrayOf(1, 2, 3, 4, 6),
intArrayOf(1, 5)
)
fun distinctSequences(n: Int): Int {
return dp(n, 0, 0)
}
private fun dp(n: Int, prev: Int, pprev: Int): Int {
if (n == 0) {
return 1
}
if (memo[n][prev][pprev] != 0) {
return memo[n][prev][pprev]
}
var ans = 0
for (x in m[prev]) {
if (x != pprev) {
ans = (ans + dp(n - 1, x, prev)) % mod
}
}
memo[n][prev][pprev] = ans
return ans
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,032 | LeetCode-in-Kotlin | MIT License |
year2022/src/main/kotlin/net/olegg/aoc/year2022/day19/Day19.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2022.day19
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.Vector4D
import net.olegg.aoc.year2022.DayOf2022
import java.util.PriorityQueue
/**
* See [Year 2022, Day 19](https://adventofcode.com/2022/day/19)
*/
object Day19 : DayOf2022(19) {
private val PATTERN = (
"Blueprint (\\d+): Each ore robot costs (\\d+) ore\\. " +
"Each clay robot costs (\\d+) ore\\. " +
"Each obsidian robot costs (\\d+) ore and (\\d+) clay\\. " +
"Each geode robot costs (\\d+) ore and (\\d+) obsidian\\."
).toRegex()
private val BLUEPRINTS = lines
.mapNotNull { PATTERN.find(it) }
.map {
val (number, oreOre, clayOre, obsidianOre, obsidianClay, geodeOre, geodeObsidian) = it.destructured
Blueprint(
number = number.toInt(),
configs = listOf(
Robot(
cost = Rocks(
ore = oreOre.toInt(),
).vector,
produce = Rocks(
ore = 1,
).vector,
),
Robot(
cost = Rocks(
ore = clayOre.toInt(),
).vector,
produce = Rocks(
clay = 1,
).vector,
),
Robot(
cost = Rocks(
ore = obsidianOre.toInt(),
clay = obsidianClay.toInt(),
).vector,
produce = Rocks(
obsidian = 1,
).vector,
),
Robot(
cost = Rocks(
ore = geodeOre.toInt(),
obsidian = geodeObsidian.toInt(),
).vector,
produce = Rocks(
geode = 1,
).vector,
),
),
)
}
override fun first(): Any? {
return BLUEPRINTS.take(1).sumOf { blueprint ->
maxGeodes(blueprint, 24) * blueprint.number
}
}
override fun second(): Any? {
return BLUEPRINTS.take(3)
.map { maxGeodes(it, 32) }
.reduce(Int::times)
}
private fun maxGeodes(
blueprint: Blueprint,
time: Int
): Int {
val initialState = State(
robots = Vector4D(1, 0, 0, 0),
resources = Vector4D(0, 0, 0, 0),
time = time,
)
val queue = PriorityQueue<State>(
compareBy(
{ -it.robots.manhattan() },
{ -it.resources.w },
{ it.time },
),
).apply {
this += initialState
}
val seen = mutableSetOf<State>()
var best = 0
while (queue.isNotEmpty()) {
val curr = queue.remove()
if (curr in seen) {
continue
}
seen += curr
val newResources = curr.resources + curr.robots
if (curr.time == 1) {
best = maxOf(best, newResources.w)
} else {
val newState = State(
robots = curr.robots,
resources = newResources,
time = curr.time - 1,
)
if (newState !in seen) {
val possibleBest = newState.resources.w +
newState.robots.w * newState.time +
newState.time * (newState.time - 1) / 2
if (possibleBest > best) {
queue.add(newState)
}
}
}
blueprint.configs.forEach { config ->
val buildCost = config.cost
val afterBuild = curr.resources - buildCost
if (afterBuild.toList().all { it >= 0 }) {
if (curr.time == 1) {
best = maxOf(best, afterBuild.w)
} else {
val newState = State(
robots = curr.robots + config.produce,
resources = afterBuild + curr.robots,
time = curr.time - 1,
)
if (newState !in seen) {
val possibleBest = newState.resources.w +
newState.robots.w * newState.time +
newState.time * (newState.time - 1) / 2
if (possibleBest > best) {
queue.add(newState)
}
}
}
}
}
}
return best
}
data class Rocks(
val ore: Int = 0,
val clay: Int = 0,
val obsidian: Int = 0,
val geode: Int = 0,
) {
val list = listOf(ore, clay, obsidian, geode)
val vector = Vector4D(ore, clay, obsidian, geode)
}
data class Robot(
val cost: Vector4D,
val produce: Vector4D,
)
data class Blueprint(
val number: Int,
val configs: List<Robot>,
)
data class State(
val robots: Vector4D,
val resources: Vector4D,
val time: Int,
)
}
fun main() = SomeDay.mainify(Day19)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 4,510 | adventofcode | MIT License |
src/test/kotlin/ch/ranil/aoc/aoc2022/Day07.kt | stravag | 572,872,641 | false | {"Kotlin": 234222} | package ch.ranil.aoc.aoc2022
import ch.ranil.aoc.AbstractDay
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
object Day07 : AbstractDay() {
@Test
fun tests() {
assertEquals(95437, compute1(testInput))
assertEquals(1084134, compute1(puzzleInput))
assertEquals(24933642, compute2(testInput))
assertEquals(6183184, compute2(puzzleInput))
}
private fun compute1(input: List<String>): Int {
val folders = parse(input)
return folders
.map { it.value }
.filter { it <= 100000 }
.sum()
}
private fun compute2(input: List<String>): Int {
val folders = parse(input)
val unusedSpace = 70000000 - folders.entries.first().value
val requiredSpace = 30000000 - unusedSpace
return folders
.map { it.value }
.filter { it >= requiredSpace }
.min()
}
private fun parse(input: List<String>): Map<String, Int> {
val folders = linkedMapOf<String, Int>()
val currentPath = mutableListOf<String>()
input.forEach { line ->
when {
line.isChangeDir() -> {
when (val dirName = line.split(" ")[2]) {
".." -> currentPath.removeLast()
else -> {
currentPath.add(dirName)
folders[currentPath.joinToString()] = 0
}
}
}
line.isFile() -> {
val fileSize = line.split(" ").first().toInt()
currentPath
.runningFold(emptyList<String>()) { acc, s -> acc + s }
.forEach { path ->
folders.computeIfPresent(path.joinToString()) { _, folderSize -> folderSize + fileSize }
}
}
}
}
return folders
}
fun String.isChangeDir() = startsWith("$ cd")
fun String.isFile() = matches("^[0-9]+ .*".toRegex())
}
| 0 | Kotlin | 1 | 0 | dbd25877071cbb015f8da161afb30cf1968249a8 | 2,115 | aoc | Apache License 2.0 |
src/Day02.kt | realpacific | 573,561,400 | false | {"Kotlin": 59236} | fun main() {
fun part1(input: List<String>): Int {
var totalScores = 0
input.forEach { line ->
val (opponentMove, myMove) = line.split(" ")
when (myMove) {
"X" -> totalScores += 1
"Y" -> totalScores += 2
"Z" -> totalScores += 3
}
if ((opponentMove == "A" && myMove == "X") || (opponentMove == "B" && myMove == "Y") || (opponentMove == "C" && myMove == "Z")) {
totalScores += 3
} else if ((opponentMove == "A" && myMove == "Y") || (opponentMove == "B" && myMove == "Z") || (opponentMove == "C" && myMove == "X")) {
totalScores += 6
}
}
return totalScores
}
fun part2(input: List<String>): Int {
var totalScores = 0
input.forEach { line ->
val (opponentMove, result) = line.split(" ")
// X means you need to lose, Y means you need to end the round in a draw, and Z means you need to win.
when (result) {
"X" -> totalScores += 0 // lose
"Y" -> totalScores += 3 // draw
"Z" -> totalScores += 6 // win
}
// A for Rock, B for Paper, and C for Scissors.
// 1 for Rock, 2 for Paper, and 3 for Scissors
if (opponentMove == "A") { // rock
if (result == "X") totalScores += 3 // lose so choose scissors
if (result == "Y") totalScores += 1 // draw so choose rock
if (result == "Z") totalScores += 2 // win so choose paper
} else if (opponentMove == "C") { // scissors
if (result == "X") totalScores += 2 // lose
if (result == "Y") totalScores += 3 // draw
if (result == "Z") totalScores += 1 // win
} else if (opponentMove == "B") { // paper
if (result == "X") totalScores += 1 // lose
if (result == "Y") totalScores += 2 // draw
if (result == "Z") totalScores += 3 // win
}
}
return totalScores
}
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f365d78d381ac3d864cc402c6eb9c0017ce76b8d | 2,222 | advent-of-code-2022 | Apache License 2.0 |
Kotlin/min_number_of_1.kt | manan025 | 412,155,744 | false | null | import java.lang.Integer.min
import java.util.*
/*
KOTLIN PROGRAM TO FIND THE ROWS WITH MINIMUM NUMBER OF 1s
INPUT FORMAT :
number of rows and number of column
||THE ARRAY ||
OUTPUT FORMAT:
ith row which has the least number of 1s
the elements of row which has the least number of 1s
INPUT:
5 4
1 1 1 2
1 1 5 2
0 0 1 1
1 1 2 2
1 0 1 1
OUTPUT:
2 row:
1 1 5 2
3 row:
0 0 1 1
4 row:
1 1 2 2
Time complexity : O(N^2);
Space complexity : O(N^2);
*/
fun main() {
val scanner = Scanner(System.`in`)
val noOfRows: Int = scanner.nextInt()
val noOfColumns: Int = scanner.nextInt()
val array = Array(noOfRows) { IntArray(noOfColumns) }
val noOf1sPerRow = IntArray(noOfRows) { 0 }
readInputArray(array, noOfRows, noOfColumns)
val minNoOf1s = findMin1s(array, noOfRows, noOf1sPerRow)
printRowsWithMin1s(array, minNoOf1s, noOf1sPerRow)
}
fun readInputArray(array: Array<IntArray>, noOfRows: Int, noOfColumns: Int) {
val scanner = Scanner(System.`in`)
for (rowIndex in 0 until noOfRows) {
for (columnIndex in 0 until noOfColumns) {
array[rowIndex][columnIndex] = scanner.nextInt()
}
}
}
fun findMin1s(array: Array<IntArray>, noOfRows: Int, noOf1sPerRow: IntArray): Int {
var minNoOf1s = Int.MAX_VALUE;
for (i in 0 until noOfRows) {
noOf1sPerRow[i] = array[i].fold(0) { prev, curr -> prev + (if (curr == 1) 1 else 0) }
minNoOf1s = min(minNoOf1s, noOf1sPerRow[i])
}
return minNoOf1s;
}
fun printRowsWithMin1s(array: Array<IntArray>, minNoOf1s: Int, noOf1sPerRow: IntArray) {
for (i in array.indices) {
if (minNoOf1s == noOf1sPerRow[i]) {
println("${i + 1} row:")
println(array[i].joinToString(" "))
}
}
} | 115 | Java | 89 | 26 | c185dcedc449c7e4f6aa5e0d8989589ef60b9565 | 1,743 | DS-Algo-Zone | MIT License |
archive/src/main/kotlin/com/grappenmaker/aoc/year15/Day11.kt | 770grappenmaker | 434,645,245 | false | {"Kotlin": 409647, "Python": 647} | package com.grappenmaker.aoc.year15
import com.grappenmaker.aoc.PuzzleSet
import kotlin.math.abs
fun PuzzleSet.day11() = puzzle {
val password = input.trim().map { it.digitCode }
val (first, second) = generateSequence(password) { it.nextPassword() }
.filter { it.isValid() }.map { pwd -> pwd.joinToString("") { it.digitChar.toString() } }
.take(2).toList()
partOne = first
partTwo = second
}
// Unlike incrementPassword, this one also skips if one of the illegal values is found
fun List<Int>.nextPassword(max: Int = 26) = when (val pivot = indexOfFirst { it in passwordDisallowed }) {
-1 -> incrementPassword(max)
else -> {
// 1. Cut off until the pivot
// 2. Add pivot + 1
// 3. Add zeroes
take(pivot) + (this[pivot] + 1) + (1..<size - pivot).map { 0 }
}
}
val passwordDisallowed = listOf('i', 'o', 'l').map { it.digitCode }
fun List<Int>.incrementPassword(max: Int = 26) = if (isEmpty()) emptyList() else buildList {
fun increment(index: Int) {
// Calculate incremented value
val newValue = (this@incrementPassword[index] + 1) % max
// Add to top of list
add(0, newValue)
// If value wrapped, increment next index as well
if (newValue == 0) increment(index - 1)
// Else, finish and add the rest
else addAll(0, this@incrementPassword.take(index))
}
increment(this@incrementPassword.indices.last)
}
val Char.digitCode get() = code - 97
val Int.digitChar get() = (this + 97).toChar()
fun List<Int>.isValid() =
asSequence().windowed(3).any { (a, b, c) -> b - a == 1 && c - b == 1 } &&
windowed(2).withIndex().filter { (_, p) -> p[0] == p[1] }.let { pairs ->
pairs.any { (idxA) -> pairs.any { (idxB) -> abs(idxA - idxB) >= 2 } }
} | 0 | Kotlin | 0 | 7 | 92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585 | 1,835 | advent-of-code | The Unlicense |
src/main/kotlin/com/jacobhyphenated/advent2023/day22/Day22.kt | jacobhyphenated | 725,928,124 | false | {"Kotlin": 121644} | package com.jacobhyphenated.advent2023.day22
import com.jacobhyphenated.advent2023.Day
import kotlin.math.max
import kotlin.math.min
/**
* Day 22: Sand Slabs
*
* Blocks of sand are falling and represented by the puzzle input.
* Each line has two 3d coordinates that describe n number of 1 cube sections of sand that make up the block.
*
* The floor is at z = 0, so the lowest z value possible is 1, where a block comes to rest on the floor.
* If a part of a block touches a part of another block, that block then comes to rest in that location.
*/
class Day22: Day<List<Block>> {
override fun getInput(): List<Block> {
return parseInput(readInputFile("22"))
}
// Runs in about 12 seconds
/**
* Part 1: A Block can be safely disintegrated if it is not the only block supporting some other block.
* How many blocks can be safely disintegrated?
*
* This takes around 12 seconds to run with almost the entire time spent finding the settled brick locations.
* Optimizing that part of the problem (which is re-used for part 2) will have a big performance impact
*/
override fun part1(input: List<Block>): Int {
val (settled, supportMap) = buildSupportMap(input)
// supportMap describes what bricks are being held up by the key block.
// now determine which blocks are holding up the key block
// supportedBy can only be calculated once all blocks are settled
val supportedBy = settled.associateWith { block ->
val result = mutableSetOf<Block>()
for ((k,v) in supportMap) {
if (block in v) {
result.add(k)
}
}
result
}
var canBeRemoved = 0
// a block can be removed if all blocks it supports are supported by at least one other block
settled.forEach { block ->
val blocksItSupports = supportMap[block] ?: emptySet()
if(blocksItSupports.all { supportedBy.getValue(it).size > 1 }) {
canBeRemoved++
}
}
return canBeRemoved
}
/**
* Part 2: If we disintegrate a block that is the only block holding another block up,
* that block will fall, along with any blocks it's solely supporting, etc.
*
* Determine how many other blocks will fall when each block is disintegrated
*/
override fun part2(input: List<Block>): Any {
val (settled, supportMap) = buildSupportMap(input)
val supportedBy = settled.associateWith { block ->
val result = mutableSetOf<Block>()
for ((k,v) in supportMap) {
if (block in v) {
result.add(k)
}
}
result
}
var totalCollapse = 0
settled.forEach { block ->
// look only at blocks that don't have other supporting blocks
val blocksItSupports = (supportMap[block] ?: emptySet())
.filter { supportedBy.getValue(it).size == 1 }
// count is a unique set of blocks that will fall if [block] is disintegrated
val count = blocksItSupports.toMutableSet()
var chain = blocksItSupports.toList()
while (chain.isNotEmpty()) {
chain = chain.mapNotNull { supportMap[it] }.flatten()
// if a block has a supporting block that is not in our count set, then it won't fall
.filter { supportedBy.getValue(it).all { b -> b in count } }
count.addAll(chain)
}
totalCollapse += count.size
}
return totalCollapse
}
/**
* Given the starting location of each block.
* Return the final resting location of each block.
* And return a map of a block to the other blocks it supports,
* that is, blocks that it is underneath and touching.
*/
private fun buildSupportMap(input: List<Block>): Pair<List<Block>, Map<Block, Set<Block>>> {
val orderedBlocks = input.sortedBy { it.minZ }
val settled = mutableListOf<Block>()
val supportMap = mutableMapOf<Block, MutableSet<Block>>()
for (block in orderedBlocks) {
var current = block
while(current.minZ > 1) {
val next = current.oneZDown()
val supports = settled.filter { it.cubes.intersect(next.cubes).isNotEmpty() }
if (supports.isNotEmpty()) {
supports.forEach { support ->
supportMap.getOrPut(support) { mutableSetOf() }.add(current)
}
break
}
current = next
}
settled.add(current)
}
return Pair(settled, supportMap)
}
fun parseInput(input: String): List<Block> {
return input.lines().map { line->
val coords = line.split("~")
val (x1,y1,z1) = coords[0].split(",").map { it.toInt() }
val (x2,y2,z2) = coords[1].split(",").map { it.toInt() }
Block.fromCoordinates(x1, y1, z1, x2, y2, z2)
}
}
}
data class Block(val cubes: Set<Triple<Int,Int,Int>>) {
val minZ: Int = cubes.minOf { (_,_,z) -> z }
fun oneZDown(): Block {
return Block(cubes.map { (x,y,z) -> Triple(x,y,z-1) }.toSet())
}
companion object {
fun fromCoordinates(x1: Int, y1: Int, z1: Int, x2: Int, y2: Int, z2: Int): Block {
if (x1 == x2 && y1 == y2){
return Block((min(z1,z2) .. max(z1,z2)).map { Triple(x1,y1,it) }.toSet())
}
else if (x1 == x2 && z1 == z2) {
return Block((min(y1,y2) .. max(y1,y2)).map { Triple(x1, it, z1) }.toSet())
}
else if (y1 == y2 && z1 == z2) {
return Block((min(x1, x2) .. max(x1, x2)).map { Triple(it, y1, z1) }.toSet())
}
throw IllegalStateException("Failed to parse Block from coordinates")
}
}
}
fun main(@Suppress("UNUSED_PARAMETER") args: Array<String>) {
Day22().run()
} | 0 | Kotlin | 0 | 0 | 90d8a95bf35cae5a88e8daf2cfc062a104fe08c1 | 5,536 | advent2023 | The Unlicense |
kotlin/10.kt | NeonMika | 433,743,141 | false | {"Kotlin": 68645} | class Day10 : Day<List<List<Char>>>("10") {
val pairs = mapOf(
')' to '(',
']' to '[',
'}' to '{',
'>' to '<'
)
val corruptedCost = mapOf(
')' to 3L,
']' to 57L,
'}' to 1197L,
'>' to 25137L
)
val invalidCost = mapOf(
'(' to 1,
'[' to 2,
'{' to 3,
'<' to 4
)
override fun dataStar1(lines: List<String>) = lines.map { line -> line.toCharArray().toList() }
override fun dataStar2(lines: List<String>) = dataStar1(lines)
override fun star1(data: List<List<Char>>): Number {
val corruptedEnds = mutableListOf<Char>()
for (line in data) {
line.fold(mutableListOf()) { acc: MutableList<Char>?, e ->
when {
acc == null -> null
e in pairs.values -> acc.apply { add(e) }
acc.last() == pairs[e] -> acc.apply { removeLast() }
else -> {
corruptedEnds += e
null
}
}
}
}
return corruptedEnds.sumOf { corruptedCost[it]!! }
}
override fun star2(data: List<List<Char>>): Number {
val scores = mutableListOf<Long>()
lineLoop@ for (line in data) {
val stack = mutableListOf<Char>()
for (ch in line) {
when (ch) {
in pairs.values -> stack.add(ch)
else -> if (stack.last() == pairs[ch]) stack.removeLast() else continue@lineLoop
}
}
if (stack.isNotEmpty()) {
scores += stack.reversed().fold(0L) { acc, e -> acc * 5 + invalidCost[e]!! }
}
}
return scores.sorted()[scores.size / 2]
}
}
fun main() {
Day10()()
} | 0 | Kotlin | 0 | 0 | c625d684147395fc2b347f5bc82476668da98b31 | 1,858 | advent-of-code-2021 | MIT License |
src/main/kotlin/com/ginsberg/advent2020/Day04.kt | tginsberg | 315,060,137 | false | null | /*
* Copyright (c) 2020 by <NAME>
*/
/**
* Advent of Code 2020, Day 4 - Passport Processing
* Problem Description: http://adventofcode.com/2020/day/4
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2020/day4/
*/
package com.ginsberg.advent2020
class Day04(input: String) {
private val passports: List<String> = input.split("\n\n")
fun solvePart1(): Int =
passports
.count { passport -> expectedFields.all { passport.contains(it)} }
fun solvePart2(): Int =
passports
.count { passport -> fieldPatterns.all { it.containsMatchIn(passport) } }
companion object {
private val expectedFields = listOf("byr:", "iyr:", "eyr:", "hgt:", "hcl:", "ecl:", "pid:")
private val fieldPatterns = listOf(
"""\bbyr:(19[2-9][0-9]|200[0-2])\b""",
"""\biyr:(201[0-9]|2020)\b""",
"""\beyr:(202[0-9]|2030)\b""",
"""\bhgt:((1([5-8][0-9]|9[0-3])cm)|((59|6[0-9]|7[0-6])in))\b""",
"""\bhcl:#[0-9a-f]{6}\b""",
"""\becl:(amb|blu|brn|gry|grn|hzl|oth)\b""",
"""\bpid:[0-9]{9}\b"""
).map { it.toRegex() }
}
}
| 0 | Kotlin | 2 | 38 | 75766e961f3c18c5e392b4c32bc9a935c3e6862b | 1,189 | advent-2020-kotlin | Apache License 2.0 |
aoc2022/aoc2022-kotlin/src/main/kotlin/de/havox_design/aoc2022/day15/BeaconExclusionZone.kt | Gentleman1983 | 737,309,232 | false | {"Kotlin": 342004, "Scala": 9632} | package de.havox_design.aoc2022.day15
class BeaconExclusionZone(private var filename: String) {
private val data = readFile()
fun processPart1(desiredRow: Int): Int =
data.mapNotNull { it.findRange(desiredRow) }
.reduce()
.sumOf { it.last - it.first }
fun processPart2(caveSize: Int): Long {
val cave = (0..caveSize)
return data.firstNotNullOf { sensor ->
val up = Point2D(sensor.location.x, sensor.location.y - sensor.distance - 1)
val right = Point2D(sensor.location.x + sensor.distance + 1, sensor.location.y)
val down = Point2D(sensor.location.x, sensor.location.y + sensor.distance + 1)
val left = Point2D(sensor.location.x - sensor.distance - 1, sensor.location.y)
(up.lineTo(right) + right.lineTo(down) + down.lineTo(left) + left.lineTo(up))
.filter { location -> location.x in cave && location.y in cave }
.firstOrNull { possibleLocation -> data.none { sensor -> sensor.isInRange(possibleLocation) } }
}.calculateTuningFrequency()
}
private fun readFile(): Set<Sensor> {
val fileData = getResourceAsText(filename)
return fileData.map { row ->
Sensor(
Point2D(
row
.substringAfter("x=")
.substringBefore(",")
.toInt(),
row
.substringAfter("y=")
.substringBefore(":")
.toInt()
),
Point2D(
row
.substringAfterLast("x=")
.substringBefore(",")
.toInt(),
row
.substringAfterLast("y=")
.toInt()
)
)
}.toSet()
}
private fun getResourceAsText(path: String): List<String> =
this.javaClass.classLoader.getResourceAsStream(path)!!.bufferedReader().readLines()
private fun List<IntRange>.reduce(): List<IntRange> =
if (this.size <= 1) this
else {
val sorted = this.sortedBy { it.first }
sorted
.drop(1)
.fold(mutableListOf(sorted.first())) { reduced, range ->
val lastRange = reduced.last()
if (range.first <= lastRange.last)
reduced[reduced.lastIndex] = (lastRange.first..maxOf(lastRange.last, range.last))
else
reduced.add(range)
reduced
}
}
}
| 4 | Kotlin | 0 | 1 | b94716fbc95f18e68774eb99069c0b703875615c | 2,718 | aoc2022 | Apache License 2.0 |
src/main/kotlin/day1/RocketEquation.kt | jabrena | 226,094,749 | false | null | package day1
import kotlin.math.floor
/**
*
* --- Day 1: The Tyranny of the Rocket Equation ---
* Santa has become stranded at the edge of the Solar System while delivering presents to other planets! To accurately calculate his position in space, safely align his warp drive, and return to Earth in time to save Christmas, he needs you to bring him measurements from fifty stars.
*
* Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!
* The Elves quickly load you into a spacecraft and prepare to launch.
* At the first Go / No Go poll, every Elf is Go until the Fuel Counter-Upper. They haven't determined the amount of fuel required yet.
* Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2.
*
* For example:
*
* For a mass of 12, divide by 3 and round down to get 4, then subtract 2 to get 2.
* For a mass of 14, dividing by 3 and rounding down still yields 4, so the fuel required is also 2.
* For a mass of 1969, the fuel required is 654.
* For a mass of 100756, the fuel required is 33583.
*
* The Fuel Counter-Upper needs to know the total fuel requirement. To find it, individually calculate the fuel needed for the mass of each module (your puzzle input), then add together all the fuel values.
* What is the sum of the fuel requirements for all of the modules on your spacecraft?
*
*/
class RocketEquation {
private val FUEL_INPUT_FILE = "/day1/input.txt"
private val readInputFile = this::class.java.getResourceAsStream(FUEL_INPUT_FILE).bufferedReader().readLines()
/**
* Fuel required to launch a given module is based on its mass.
* Specifically, to find the fuel required for a module,
* take its mass, divide by three, round down, and subtract 2.
*/
val calculateFuel = { mass : Int -> (floor(mass / 3.0).toInt()) - 2 }
/**
* The Fuel Counter-Upper needs to know the total fuel requirement. To find it, individually calculate
* the fuel needed for the mass of each module (your puzzle input), then add together all the fuel values.
* What is the sum of the fuel requirements for all of the modules on your spacecraft?
*/
fun getTotalFuelRequeriment() : Int {
return readInputFile
.map { it.toInt() }
.map { calculateFuel(it) }
.sum()
}
}
| 1 | Kotlin | 0 | 0 | 60f2e4143a0a69097235ccb623079a0f19150681 | 2,581 | advent-of-code-2019 | Apache License 2.0 |
src/main/kotlin/days/Day04.kt | TheMrMilchmann | 433,608,462 | false | {"Kotlin": 94737} | /*
* Copyright (c) 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package days
import utils.*
fun main() {
data class CardEntry(val number: Int, var marked: Boolean)
class BingoCard(val rows: List<List<CardEntry>>) {
init {
val rowsCount = rows.size
require(rows.all { it.size == rowsCount })
}
val isComplete get() =
rows.any { it.all { (_, marked) -> marked } } || rows.indices.any { x -> rows.all { column -> column[x].marked } }
val entries get() = rows.flatten()
fun mark(number: Int): Boolean {
var changed = false
rows.forEach {
it.forEach { entry ->
if (number == entry.number && !entry.marked) {
changed = true
entry.marked = true
}
}
}
return changed
}
override fun toString(): String = rows.joinToString(separator = "\n") { column ->
column.joinToString(separator = "\t") { (number, marked) -> "${number.toString().padStart(2)}-${if (marked) "T" else "F"}"}
}
}
fun parseInput(): Pair<List<Int>, List<BingoCard>> {
val input = readInput()
val drawnNumbers = input.first().split(",").map(String::toInt)
val cards = input.drop(2)
.windowed(size = 5, step = 6)
.map { row -> BingoCard(row.map { it.trim().split("""\s+""".toRegex()).map { CardEntry(it.toInt(), false) } }) }
return (drawnNumbers to cards)
}
fun part1(): Int {
val (drawnNumbers, cards) = parseInput()
val cardsByNumber = buildMap<Int, MutableList<BingoCard>> {
cards.forEach { card -> card.rows.forEach { column -> column.forEach { (number, _) -> computeIfAbsent(number) { mutableListOf() }.add(card) } } }
}
val (drawnNumber, winningCard) = Unit.let {
for (drawnNumber in drawnNumbers) {
for (card in cardsByNumber[drawnNumber] ?: emptyList()) {
if (card.mark(drawnNumber)) {
if (card.isComplete) {
return@let drawnNumber to card
}
}
}
}
error("No card won?")
}
val unmarkedSum = winningCard.entries.filter { (_, marked) -> !marked }.sumOf(CardEntry::number)
return unmarkedSum * drawnNumber
}
fun part2(): Int {
val (drawnNumbers, cards) = parseInput()
val cardsByNumber = buildMap<Int, MutableList<BingoCard>> {
cards.forEach { card -> card.rows.forEach { column -> column.forEach { (number, _) -> computeIfAbsent(number) { mutableListOf() }.add(card) } } }
}
val incompleteCards = ArrayList<BingoCard>(cards)
val drawnNumber = Unit.let {
for (drawnNumber in drawnNumbers) {
for (card in (cardsByNumber[drawnNumber] ?: emptyList()).filter { it in incompleteCards }) {
if (card.mark(drawnNumber)) {
if (card.isComplete) {
if (incompleteCards.size == 1) {
return@let drawnNumber
} else {
incompleteCards.remove(card)
}
}
}
}
}
error("No card 'won' last")
}
val losingCard = incompleteCards.single()
val unmarkedSum = losingCard.entries.filter { (_, marked) -> !marked }.sumOf(CardEntry::number)
return unmarkedSum * drawnNumber
}
println("Part 1: ${part1()}")
println("Part 2: ${part2()}")
} | 0 | Kotlin | 0 | 1 | dfc91afab12d6dad01de552a77fc22a83237c21d | 4,862 | AdventOfCode2021 | MIT License |
src/Day16.kt | anilkishore | 573,688,256 | false | {"Kotlin": 27023} | class Valve(val id: String, val flowRate: Int = 0, val edges: List<String> = listOf())
fun main() {
val input = readInput("Day16")
val valves = input.map { inp ->
val ss = inp.split(";")
val s1 = ss[0].split(" ")
val rate = ss[0].split("=")[1].toInt()
val edges = ss[1].split(", ").map { it.takeLast(2) }
Valve(s1[1], rate, edges)
}.associateBy { it.id }
fun dfs(u: Valve, tLeft: Int, used: Set<String>): Int {
if (tLeft <= 1)
return 0
// println("At uid = ${u.id}")
var best = 0
if (u.flowRate > 0 && !used.contains(u.id)) {
best = maxOf(best, (u.flowRate * tLeft - 1) + dfs(u, tLeft - 1, used.union(listOf("u.id"))))
}
for (vid in u.edges) {
best = maxOf(best, dfs(valves[vid]!!, tLeft - 1, used))
}
return best
}
fun part1(): Int {
val src = valves["AA"] ?: return 0
return dfs(src, 30, mutableSetOf<String>())
}
println(part1())
} | 0 | Kotlin | 0 | 0 | f8f989fa400c2fac42a5eb3b0aa99d0c01bc08a9 | 1,027 | AOC-2022 | Apache License 2.0 |
kotlin/src/katas/kotlin/leetcode/adjust_salaries/AdjustSalaries.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.leetcode.adjust_salaries
import datsok.shouldEqual
import org.junit.Test
/**
* Give an array of salaries. The total salary has a budget.
* At the beginning, the total salary of employees is larger than the budget.
* It is required to find the number k, and reduce all the salaries larger than k to k,
* such that the total salary is exactly equal to the budget.
*
* https://leetcode.com/discuss/interview-question/351313/Google-or-Phone-Screen-or-Salary-Adjustment
*/
class AdjustSalariesTests {
@Test fun `it works`() {
adjustSalaries(arrayOf(10, 30, 20, 40), budget = 80) shouldEqual arrayOf(10, 20, 25, 25)
}
}
private fun adjustSalaries(salaries: Array<Int>, budget: Int): Array<Int> {
salaries.sort()
var deficit = salaries.sum() - budget
var maxIndex = salaries.size - 1
while (deficit > 0) {
maxIndex = findMaxIndex(salaries, maxIndex)
val max = salaries[maxIndex]
val maxCount = salaries.size - maxIndex
val nextMax = salaries[maxIndex - 1]
var space = (max - nextMax) * maxCount
if (space < deficit) {
deficit -= space
} else {
space = deficit
deficit -= deficit
}
(maxIndex until salaries.size).forEach { i ->
salaries[i] -= space / maxCount
}
}
return salaries
}
private fun findMaxIndex(a: Array<Int>, from: Int): Int {
var i = from
var max = Int.MIN_VALUE
var maxIndex = i
while (i >= 0) {
if (a[i] >= max) {
max = a[i]
maxIndex = i
}
i--
}
return maxIndex
} | 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 1,645 | katas | The Unlicense |
aoc-2020/src/commonMain/kotlin/fr/outadoc/aoc/twentytwenty/Day17.kt | outadoc | 317,517,472 | false | {"Kotlin": 183714} | package fr.outadoc.aoc.twentytwenty
import fr.outadoc.aoc.scaffold.Day
import fr.outadoc.aoc.scaffold.readDayInput
class Day17 : Day<Int> {
companion object {
private const val PRINT_DEBUG = false
}
private data class Point4D(val x: Int, val y: Int, val z: Int, val w: Int)
private data class Dimension(val iteration: Int = 0, val activeCubes: List<Point4D>) {
// Add some extra room around existing cubes so that we can add new ones
private val rangePadding = 1
private fun getRangeForAxis(axis: (Point4D) -> Int): IntRange =
(activeCubes.minOf(axis) - rangePadding)..(activeCubes.maxOf(axis) + rangePadding)
val xRange: IntRange by lazy { getRangeForAxis { it.x } }
val yRange: IntRange by lazy { getRangeForAxis { it.y } }
val zRange: IntRange by lazy { getRangeForAxis { it.z } }
val wRange: IntRange by lazy { getRangeForAxis { it.w } }
private val activeCubeLookup = activeCubes.associateBy { it.hashCode() }
val Point4D.isActive: Boolean
get() = activeCubeLookup.containsKey(hashCode())
}
private fun pointsInRange(xRange: IntRange, yRange: IntRange, zRange: IntRange, wRange: IntRange): List<Point4D> {
return wRange.flatMap { w: Int ->
zRange.flatMap { z: Int ->
yRange.flatMap { y: Int ->
xRange.map { x: Int ->
Point4D(x, y, z, w)
}
}
}
}
}
private fun Point4D.getNeighbors(dimensionCount: Int): List<Point4D> {
val reach = 1
return pointsInRange(
xRange = (x - reach)..(x + reach),
yRange = (y - reach)..(y + reach),
zRange = (z - reach)..(z + reach),
wRange = if (dimensionCount > 3) (w - reach)..(w + reach) else 0..0
) - this // Remove current point from consideration
}
private fun Dimension.next(dimensionCount: Int): Dimension = Dimension(
iteration = iteration + 1,
activeCubes = pointsInRange(
xRange,
yRange,
zRange,
wRange = if (dimensionCount > 3) wRange else 0..0
).mapNotNull { cube ->
val isActive = cube.isActive
val activeNeighborCount = cube
.getNeighbors(dimensionCount)
.count { neighbor ->
neighbor.isActive
}
when {
isActive && activeNeighborCount in 2..3 -> {
// If a cube is active and exactly 2 or 3 of its neighbors are also active, the cube remains active.
cube
}
isActive -> {
// Otherwise, the cube becomes inactive.
null
}
activeNeighborCount == 3 -> {
// If a cube is inactive but exactly 3 of its neighbors are active, the cube becomes active.
cube
}
else -> {
// Otherwise, the cube remains inactive.
null
}
}
}
)
private fun Dimension.nthIteration(dimensionCount: Int, n: Int): Dimension {
return (0 until n).fold(this) { dimension, _ ->
dimension.next(dimensionCount).also {
if (PRINT_DEBUG) it.print()
}
}
}
private fun Dimension.print() {
println("=== iteration #$iteration ===")
wRange.forEach { w ->
zRange.forEach { z ->
println("z = $z, w = $w")
println("┌─${"──".repeat(xRange.count())}┐")
yRange.forEach { y ->
print("│ ")
xRange.map { x ->
if (Point4D(x, y, z, w).isActive) '■' else '.'
}.forEach { c ->
print("$c ")
}
println("│")
}
println("└─${"──".repeat(xRange.count())}┘")
}
}
}
private val initialLayer: List<Point4D> =
readDayInput()
.lines()
.flatMapIndexed { y, line ->
line.mapIndexedNotNull { x, c ->
when (c) {
'#' -> Point4D(x = x, y = y, z = 0, w = 0)
else -> null
}
}
}
private val initialState: Dimension =
Dimension(activeCubes = initialLayer)
override fun step1(): Int {
return initialState
.nthIteration(dimensionCount = 3, n = 6)
.activeCubes.size
}
override fun step2(): Int {
return initialState
.nthIteration(dimensionCount = 4, n = 6)
.activeCubes.size
}
override val expectedStep1: Int = 237
override val expectedStep2: Int = 2448
} | 0 | Kotlin | 0 | 0 | 54410a19b36056a976d48dc3392a4f099def5544 | 5,021 | adventofcode | Apache License 2.0 |
src/algorithms/sorter/merge/Main.kt | bdatdo0601 | 130,766,362 | false | null | package algorithms.sorter.merge
import algorithms.sorter.utils.Element
import algorithms.sorter.utils.SortAlgorithmEnum
import algorithms.sorter.insertion.insertionSorter
object MergeSortTester {
private class ExampleElement(override val value: Number) : Element {
override fun toString(): String {
return "Object { value: ${this.value} }"
}
}
private fun generateRandomElements(size: Int, limit: Int): ArrayList<Element> {
val list = ArrayList<Element>(size)
for (i in 0 until size) {
list.add(ExampleElement(Math.round(Math.random()*limit)))
}
return list
}
@JvmStatic
fun main(args: Array<String>){
println("Test Merge Sort")
val list = generateRandomElements(10, 100)
println("Unsorted: $list, size: ${list.size}")
mergeSorter(list, true)
println("Ascending sort: $list, size: ${list.size}")
mergeSorter(list, false)
println("Descending sort: $list, size: ${list.size}")
}
}
private fun merge(list: MutableList<Element>, startIndex: Int, middleIndex: Int, endIndex: Int, isAscending: Boolean): MutableList<Element> {
// iterate through every element of second list backward
for (i in endIndex - 1 downTo middleIndex) {
// store the last object of the first list
val lastFirstArrayElem = list[middleIndex - 1] //Can't store only index since the index value will be change
// keep track of exact index first list has moved up to
var newElemPositionIndex = middleIndex - 1
for (j in middleIndex - 2 downTo startIndex) {
//checking whether or not should the current elem be moved
val shouldMove = if (isAscending) {
list[j].value.toFloat() > list[i].value.toFloat()
} else {
list[j].value.toFloat() < list[i].value.toFloat()
}
if (shouldMove) {
// if it does, store the current elem in the position ahead of it and the index of the current elem
// will be where the current elem of second list be place
newElemPositionIndex = j
list[j + 1] = list[j]
} else {
break
}
}
// check to see if need to be swap with the last element of first list
// (edge case when only last elem of first list is the only value greater than current elem of second list)
val shouldSwapWithLastFirstArrayElem = if (isAscending) {
lastFirstArrayElem.value.toFloat() > list[i].value.toFloat()
} else {
lastFirstArrayElem.value.toFloat() < list[i].value.toFloat()
}
// if position has been changed or should swap with last first list, swap the current elem of second list with
// that position and put the last value of first list to current elem of second list
if (newElemPositionIndex != middleIndex - 1 || shouldSwapWithLastFirstArrayElem) {
list[newElemPositionIndex] = list[i]
list[i] = lastFirstArrayElem
}
}
return list.subList(startIndex, endIndex)
}
private fun mergeSort(list: MutableList<Element>, startIndex: Int, endIndex: Int, isAscending: Boolean, sortAlgorithm: SortAlgorithmEnum, sortSize: Int): MutableList<Element> {
return if (endIndex - startIndex > sortSize) {
val middleIndex = startIndex + ((endIndex - startIndex) / 2)
mergeSort(list, startIndex, middleIndex, isAscending, sortAlgorithm, sortSize)
mergeSort(list, middleIndex, endIndex, isAscending, sortAlgorithm, sortSize)
merge(list, startIndex, middleIndex, endIndex, isAscending)
} else {
val subList = list.subList(startIndex, endIndex)
if (subList.size != 1) {
when (sortAlgorithm) {
SortAlgorithmEnum.MERGE_SORT, SortAlgorithmEnum.INSERTION_SORT -> insertionSorter(subList, isAscending)
}
}
subList
}
}
fun mergeSorter(list: MutableList<Element>, isAscending: Boolean = true, sortAlgorithm: SortAlgorithmEnum = SortAlgorithmEnum.MERGE_SORT, sortSize: Int = 10): MutableList<Element> {
return mergeSort(list, 0, list.size, isAscending, sortAlgorithm, sortSize)
}
/**
* ATTEMPT FOR IN-PLACE MERGING
*/
//private fun swapElem(list: MutableList<Element>, firstIndex: Int, secondIndex: Int) {
// val tempElement = list[firstIndex]
// list[firstIndex] = list[secondIndex]
// list[secondIndex] = tempElement
//}
// for (i in startIndex until endIndex) {
// if (i == secondPointer) {
// if (secondPointer != endIndex - 1) secondPointer++
// else break
// }
// if (i == tempValueHolderIndex && tempValueHolderIndex < secondPointer) {
// tempValueHolderIndex++
// }
// val shouldSwap = if (isAscending) {
// list[i].value.toFloat() > list[secondPointer].value.toFloat() ||
// list[i].value.toFloat() > list[tempValueHolderIndex].value.toFloat()
// } else {
// list[i].value.toFloat() < list[secondPointer].value.toFloat() ||
// list[i].value.toFloat() < list[tempValueHolderIndex].value.toFloat()
// }
// val shouldTempValueSwapWithSecondPointerValue = when {
// tempValueHolderIndex == secondPointer -> false
// isAscending -> list[tempValueHolderIndex].value.toFloat() > list[secondPointer].value.toFloat()
// else -> list[tempValueHolderIndex].value.toFloat() < list[secondPointer].value.toFloat()
// }
// if (shouldTempValueSwapWithSecondPointerValue) {
// swapElem(list, tempValueHolderIndex, secondPointer)
//
// if (secondPointer != endIndex - 1) secondPointer++
// }
// if (shouldSwap && i != tempValueHolderIndex) {
// swapElem(list, i, tempValueHolderIndex)
// if (i > middleIndex && tempValueHolderIndex < secondPointer) {
// tempValueHolderIndex++
// }
// if (secondPointer == tempValueHolderIndex && secondPointer != endIndex - 1) secondPointer++
// }
// if (i > secondPointer && i + 1 < endIndex) {
// secondPointer = i + 1
// tempValueHolderIndex = secondPointer
// }
// } | 0 | Kotlin | 0 | 0 | 0d320f800a2fa6fb96a193d0bbf9eb2beb42a1c3 | 6,335 | project-bunny | MIT License |
src/main/kotlin/g2001_2100/s2056_number_of_valid_move_combinations_on_chessboard/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2001_2100.s2056_number_of_valid_move_combinations_on_chessboard
// #Hard #Array #String #Simulation #Backtracking
// #2023_06_25_Time_600_ms_(100.00%)_Space_44.1_MB_(100.00%)
class Solution {
// 0: rook, queen, bishop
private val dirs = arrayOf(
arrayOf(intArrayOf(-1, 0), intArrayOf(1, 0), intArrayOf(0, -1), intArrayOf(0, 1)),
arrayOf(
intArrayOf(-1, 0),
intArrayOf(1, 0),
intArrayOf(0, -1),
intArrayOf(0, 1),
intArrayOf(1, 1),
intArrayOf(-1, -1),
intArrayOf(-1, 1),
intArrayOf(1, -1)
),
arrayOf(intArrayOf(1, 1), intArrayOf(-1, -1), intArrayOf(-1, 1), intArrayOf(1, -1))
)
fun countCombinations(pieces: Array<String?>, positions: Array<IntArray>): Int {
val endPosition: Array<ArrayList<IntArray>?> = arrayOfNulls(pieces.size)
for (i in pieces.indices) {
endPosition[i] = ArrayList()
}
for (i in pieces.indices) {
positions[i][0]--
positions[i][1]--
endPosition[i]!!.add(positions[i])
var dirIndex = 0
when (pieces[i]) {
"rook" -> dirIndex = 0
"queen" -> dirIndex = 1
"bishop" -> dirIndex = 2
}
for (d in dirs[dirIndex]) {
var r = positions[i][0]
var c = positions[i][1]
while (true) {
r += d[0]
c += d[1]
if (r < 0 || r >= 8 || c < 0 || c >= 8) {
break
}
endPosition[i]!!.add(intArrayOf(r, c))
}
}
}
return dfs(positions, endPosition, IntArray(pieces.size), 0)
}
private fun dfs(positions: Array<IntArray>, stop: Array<ArrayList<IntArray>?>, stopIndex: IntArray, cur: Int): Int {
if (cur == stopIndex.size) {
val p = Array(positions.size) { IntArray(2) }
for (i in p.indices) {
p[i] = intArrayOf(positions[i][0], positions[i][1])
}
return check(p, stop, stopIndex)
}
var res = 0
for (i in stop[cur]!!.indices) {
stopIndex[cur] = i
res += dfs(positions, stop, stopIndex, cur + 1)
}
return res
}
private fun check(positions: Array<IntArray>, stop: Array<ArrayList<IntArray>?>, stopIndex: IntArray): Int {
var keepGoing = true
while (keepGoing) {
keepGoing = false
for (i in positions.indices) {
var diff = stop[i]!![stopIndex[i]][0] - positions[i][0]
if (diff > 0) {
keepGoing = true
positions[i][0]++
} else if (diff < 0) {
keepGoing = true
positions[i][0]--
}
diff = stop[i]!![stopIndex[i]][1] - positions[i][1]
if (diff > 0) {
keepGoing = true
positions[i][1]++
} else if (diff < 0) {
keepGoing = true
positions[i][1]--
}
}
val seen: MutableSet<Int> = HashSet()
for (position in positions) {
val key = position[0] * 100 + position[1]
if (seen.contains(key)) {
return 0
}
seen.add(key)
}
}
return 1
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 3,589 | LeetCode-in-Kotlin | MIT License |
leetcode-75-kotlin/src/main/kotlin/RemovingStarsFromAString.kt | Codextor | 751,507,040 | false | {"Kotlin": 49566} | /**
* You are given a string s, which contains stars *.
*
* In one operation, you can:
*
* Choose a star in s.
* Remove the closest non-star character to its left, as well as remove the star itself.
* Return the string after all stars have been removed.
*
* Note:
*
* The input will be generated such that the operation is always possible.
* It can be shown that the resulting string will always be unique.
*
*
* Example 1:
*
* Input: s = "leet**cod*e"
* Output: "lecoe"
* Explanation: Performing the removals from left to right:
* - The closest character to the 1st star is 't' in "leet**cod*e". s becomes "lee*cod*e".
* - The closest character to the 2nd star is 'e' in "lee*cod*e". s becomes "lecod*e".
* - The closest character to the 3rd star is 'd' in "lecod*e". s becomes "lecoe".
* There are no more stars, so we return "lecoe".
* Example 2:
*
* Input: s = "erase*****"
* Output: ""
* Explanation: The entire string is removed, so we return an empty string.
*
*
* Constraints:
*
* 1 <= s.length <= 10^5
* s consists of lowercase English letters and stars *.
* The operation above can be performed on s.
* @see <a href="https://leetcode.com/problems/removing-stars-from-a-string/">LeetCode</a>
*/
fun removeStars(s: String): String {
val resultList = mutableListOf<Char>()
s.forEach { char ->
if (char == '*') {
resultList.removeLast()
} else {
resultList.add(char)
}
}
return resultList.joinToString("")
}
| 0 | Kotlin | 0 | 0 | 0511a831aeee96e1bed3b18550be87a9110c36cb | 1,515 | leetcode-75 | Apache License 2.0 |
src/Day01.kt | maquirag | 576,698,073 | false | {"Kotlin": 3883} | fun main() {
val day = "01"
fun countBags(input: List<String>): List<Int> = sequence {
var total = 0
input.forEach {
if (it.isBlank()) {
yield(total)
total = 0
} else {
total += it.toInt()
}
}
yield(total)
}.toList()
fun part1(input: List<String>): Int {
val bags = countBags(input)
return bags.max()
}
fun part2(input: List<String>): Int {
val bags = countBags(input)
return bags.sortedDescending().take(3).sum()
}
val testInput = readInput("Day${day}_Test")
val input = readInput("Day${day}")
val test1 = part1(testInput)
check(test1 == 24000)
println("Part 1 => ${part1(input)}")
val test2 = part2(testInput)
check(test2 == 45000)
println("Part 2 => ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 23403172e909f8fb0c87e953d06fc0921c75fc32 | 885 | aoc2022-kotlin | Apache License 2.0 |
src/test/kotlin/leetcode/mock/MockInterviews.kt | Magdi | 390,731,717 | false | null | package leetcode
import org.junit.Test
import org.junit.Assert.*
import java.util.*
import kotlin.collections.HashMap
import kotlin.collections.HashSet
class MockInterviews1Test {
@Test
fun `test case 1`() {
assertEquals("", MockSolution1().removeDuplicates("aa"))
assertEquals("a", MockSolution1().removeDuplicates("aaa"))
assertEquals("ba", MockSolution1().removeDuplicates("aaba"))
assertEquals("ay", MockSolution1().removeDuplicates("azxxzy"))
}
@Test
fun `test case 2`() {
assertArrayEquals(
arrayOf("acdf", "acef", "bcdf", "bcef"),
MockSolution2().expand("{a,b}c{d,e}f")
)
}
@Test
fun `test case 3`() {
val checker = StreamChecker(arrayOf("ab", "ba", "aaab", "abab", "baa"))
assertFalse(checker.query('b'))
assertTrue(checker.query('a'))
assertTrue(checker.query('b'))
}
}
/**
* Stream of Characters
*/
private class StreamChecker(words: Array<String>) {
private val trie = Trie()
private var maxLength = 0
init {
words.forEach {
trie.add(it.reversed())
maxLength = Math.max(maxLength, it.length)
}
}
var currentString = StringBuilder()
fun query(letter: Char): Boolean {
currentString.append(letter)
return trie.find(currentString, maxLength)
}
private class Trie(private val root: TrieNode = TrieNode()) {
fun add(s: String) {
var cur = root
s.forEachIndexed { index, c ->
cur = cur.add(c, index == s.lastIndex)
}
}
fun find(sb: StringBuilder, maxLength: Int): Boolean {
var cur = root
for (i in 0 until Math.min(maxLength, sb.length)) {
val next = cur.find(sb[sb.lastIndex - i])
if (next == null) {
return false
} else if (next.isEnd) {
return true
} else {
cur = next
}
}
return false
}
}
private class TrieNode(private val charMap: HashMap<Char, TrieNode> = HashMap(), var isEnd: Boolean = false) {
fun add(c: Char, isEnd: Boolean): TrieNode {
val node = charMap.getOrDefault(c, TrieNode())
node.isEnd = isEnd or node.isEnd
charMap[c] = node
return node
}
fun find(c: Char): TrieNode? {
return charMap[c]
}
}
}
// Brace Expansion
private class MockSolution2 {
fun expand(s: String): Array<String> {
val options = mutableListOf<List<Char>>()
convertToGraph(s, options)
val ans = HashSet<String>()
dfs(0, StringBuilder(), options, ans)
return ans.sorted().toTypedArray()
}
private fun dfs(i: Int, sb: StringBuilder, options: MutableList<List<Char>>, ans: HashSet<String>) {
if (i == options.size) {
ans.add(sb.toString())
return
}
options[i].forEach {
sb.append(it)
dfs(i + 1, sb, options, ans)
sb.deleteCharAt(sb.lastIndex)
}
}
fun convertToGraph(s: String, options: MutableList<List<Char>>) {
val stack = Stack<Char>()
var isOption = false
s.forEach {
if (it == '{') {
isOption = true
} else if (it == '}') {
isOption = false
val optionList = mutableListOf<Char>()
while (stack.isNotEmpty()) {
optionList.add(stack.pop())
}
options.add(optionList)
} else if (it in 'a'..'z') {
if (isOption) {
stack.add(it)
} else {
options.add(listOf(it))
}
}
}
}
}
/**
* Remove All Adjacent Duplicates In String
*/
private class MockSolution1 {
fun removeDuplicates(s: String): String {
val stack: Stack<Char> = Stack<Char>()
s.forEach {
if (stack.isNotEmpty() && stack.peek() == it) {
stack.pop()
} else {
stack.add(it)
}
}
val res = StringBuilder()
while (stack.isNotEmpty()) {
res.append(stack.pop())
}
return res.reverse().toString()
}
} | 0 | Kotlin | 0 | 0 | 63bc711dc8756735f210a71454144dd033e8927d | 4,448 | ProblemSolving | Apache License 2.0 |
kotlin/src/main/kotlin/adventofcode/day8/Day8_2.kt | thelastnode | 160,586,229 | false | null | package adventofcode.day8
import java.io.File
import java.util.*
object Day8_2 {
fun parse(line: String): List<Int> {
return Scanner(line).asSequence().map { it.toInt(10) }.toList()
}
private fun <T> MutableList<T>.pop(n: Int): List<T> {
val res = this.take(n)
(0 until n).forEach { this.removeAt(0) }
return res
}
data class Node(val metadata: List<Int>, val children: List<Node>) {
fun value(): Int {
if (children.isEmpty()) {
return metadata.sum()
}
return metadata.filter { it in (1..children.size) }
.map { it - 1 } // convert to index
.map { children[it].value() }
.sum()
}
}
fun readNode(inputs: MutableList<Int>): Node {
val (childCount, metadataCount) = inputs.pop(2)
val children = (0 until childCount).map { readNode(inputs) }
val metadata = inputs.pop(metadataCount)
return Node(metadata = metadata, children = children)
}
fun process(inputs: MutableList<Int>): Int {
val tree = readNode(inputs)
return tree.value()
}
}
fun main(args: Array<String>) {
val lines = File("./day8-input").readText()
val inputs = Day8_2.parse(lines)
println(Day8_2.process(inputs.toMutableList()))
}
| 0 | Kotlin | 0 | 0 | 8c9a3e5a9c8b9dd49eedf274075c28d1ebe9f6fa | 1,359 | adventofcode | MIT License |
advent2022/src/main/kotlin/year2022/Day13.kt | bulldog98 | 572,838,866 | false | {"Kotlin": 132847} | package year2022
import AdventDay
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonPrimitive
sealed class Elem : Comparable<Elem>
data class ListElem(val elem: List<Elem>) : Elem() {
override fun compareTo(other: Elem): Int = when (other) {
is ListElem -> when {
elem.isEmpty() && other.elem.isNotEmpty() -> -1
elem.isNotEmpty() && other.elem.isEmpty() -> 1
elem.isEmpty() -> 0
else -> {
val a = this.elem[0]
val b = other.elem[0]
val result = a.compareTo(b)
if (result == 0) {
ListElem(this.elem.drop(1)).compareTo(ListElem(other.elem.drop(1)))
} else {
result
}
}
}
is IntElem -> this.compareTo(ListElem(listOf(other)))
}
}
data class IntElem(val elem: Int): Elem() {
override fun compareTo(other: Elem): Int = when (other) {
is IntElem -> elem.compareTo(other.elem)
is ListElem -> ListElem(listOf(this)).compareTo(other)
}
}
fun JsonElement.convert(): Elem = when (this) {
is JsonArray -> ListElem(map { it.convert() })
is JsonPrimitive -> IntElem(content.toInt())
else -> error("not parse")
}
fun String.parse(): Elem {
val json = Json.decodeFromString<JsonArray>(this)
return json.convert()
}
class Day13 : AdventDay(2022, 13) {
override fun part1(input: List<String>): Int {
val pairWise = input.chunked(3)
val stuff = pairWise.mapIndexed { i, (a, b) ->
a.parse().compareTo(b.parse()) to i + 1
}.filter { (c) -> c <= 0 }
return stuff.sumOf { (_, i) -> i }
}
override fun part2(input: List<String>): Int {
val marker1 = ListElem(listOf(ListElem(listOf(IntElem(2)))))
val marker2 = ListElem(listOf(ListElem(listOf(IntElem(6)))))
val lines = input
.asSequence()
.filter { it.isNotEmpty() }
.map{
it.parse()
}
.plus(marker1)
.plus(marker2)
.sortedWith(Elem::compareTo)
.toList()
return (1 + lines.indexOfFirst { it.compareTo(marker1) == 0 }) *
(1 + lines.indexOfFirst { it.compareTo(marker2) == 0 })
}
}
fun main() = Day13().run() | 0 | Kotlin | 0 | 0 | 02ce17f15aa78e953a480f1de7aa4821b55b8977 | 2,451 | advent-of-code | Apache License 2.0 |
src/Day10.kt | acunap | 573,116,784 | false | {"Kotlin": 23918} | import kotlin.math.max
import kotlin.time.ExperimentalTime
import kotlin.time.measureTime
@OptIn(ExperimentalTime::class)
fun main() {
fun part1(input: List<String>) : Int {
val markedCycleIndexes = listOf(20, 60, 100, 140, 180, 220)
var cyclesIndex = 1
var signalStrength = 1
var accumulateMarkedCycleIndexesSignalStrength = 0
fun increaseCyclesIndex(steps: Int) {
for (i in 0 until steps) {
if (markedCycleIndexes.contains(cyclesIndex)) {
accumulateMarkedCycleIndexesSignalStrength += cyclesIndex * signalStrength
}
cyclesIndex++
}
}
input.forEach { line ->
when {
line == "noop" -> {
increaseCyclesIndex(1)
}
line.startsWith("addx") -> {
increaseCyclesIndex(2)
val value = line.split(" ").last().toInt()
signalStrength += value
}
}
}
return accumulateMarkedCycleIndexesSignalStrength
}
fun part2(input: List<String>) : Boolean {
val ctr = MutableList(6 * 40) { "." }
var cyclesIndex = 1
var signalStrength = 1
fun drawCtr() {
ctr.chunked(40).forEach { row ->
row.forEach { element ->
print("$element")
}
println()
}
println()
println()
}
fun increaseCyclesIndex(steps: Int) {
for (i in 0 until steps) {
val signalIndex = max((cyclesIndex % 40) - 1, 0)
if (listOf(signalStrength - 1, signalStrength, signalStrength + 1).contains(signalIndex)) {
ctr[cyclesIndex - 1] = "#"
}
cyclesIndex++
}
}
input.forEach { line ->
when {
line == "noop" -> {
increaseCyclesIndex(1)
}
line.startsWith("addx") -> {
increaseCyclesIndex(2)
val value = line.split(" ").last().toInt()
signalStrength += value
}
}
}
drawCtr()
return true
}
val time = measureTime {
val input = readLines("Day10")
println(part1(input))
println(part2(input))
}
println("Real data time $time")
val timeTest = measureTime {
val inputTest = readLines("Day10_test")
check(part1(inputTest) == 13140)
check(part2(inputTest))
}
println("Test data time $timeTest.")
}
| 0 | Kotlin | 0 | 0 | f06f9b409885dd0df78f16dcc1e9a3e90151abe1 | 2,739 | advent-of-code-2022 | Apache License 2.0 |
src/Day01.kt | mr-cell | 575,589,839 | false | {"Kotlin": 17585} | fun main() {
fun parseInput(input: List<String>): List<Int> =
input.fold(mutableListOf(mutableListOf<Int>())) { acc, i ->
if (i == "") acc.add(mutableListOf())
else acc.last().add(i.toInt())
acc
}
.map { it.sum() }
.sortedDescending()
fun part1(input: List<String>): Int {
val calories = parseInput(input)
return calories.first()
}
fun part2(input: List<String>): Int {
val calories = parseInput(input)
return calories.take(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2528bf0f72bcdbe7c13b6a1a71e3d7fe1e81e7c9 | 847 | advent-of-code-2022 | Apache License 2.0 |
app/src/main/java/com/cristianovecchi/mikrokanon/dataAnalysis/Kmeans.kt | CristianoVecchi | 358,026,092 | false | null | package com.cristianovecchi.mikrokanon.dataAnalysis
// version 1.2.21
import java.util.Random
import kotlin.math.*
data class Point(var x: Double, var y: Double, var group: Int, val partIndex: Int, val noteIndex: Int)
typealias LPoint = List<Point>
typealias MLPoint = MutableList<Point>
val origin get() = Point(0.0, 0.0, 0, 0, 0)
val r = Random()
val hugeVal = Double.POSITIVE_INFINITY
const val RAND_MAX = Int.MAX_VALUE
const val PTS = 40
const val K = 10 // number of groups
const val W = 400
const val H = 400
fun main() {
val points = genXY(PTS, 10.0)
val centroids = lloyd(points, PTS, K)
// println("POINTS(${points.size}): $points")
// println("CENTROIDS(${centroids.size}): $centroids")
points.forEach{
println("$it -> ${centroids[it.group]}")
}
val sums = points.groupingBy { it.group }.eachCount().toSortedMap()
println(sums)
//printEps(points, PTS, centroids, K)
}
fun rand() = r.nextInt(RAND_MAX)
fun randf(m: Double) = m * rand() / (RAND_MAX - 1)
fun genXY(count: Int, radius: Double): LPoint {
val pts = List(count) { origin }
/* note: this is not a uniform 2-d distribution */
for (i in 0 until count) {
val ang = randf(2.0 * PI)
val r = randf(radius)
pts[i].x = r * cos(ang)
pts[i].y = r * sin(ang)
}
return pts
}
fun dist2(a: Point, b: Point): Double {
val x = a.x - b.x
val y = a.y - b.y
return x * x + y * y
}
fun nearest(pt: Point, cent: LPoint, nCluster: Int): Pair<Int, Double> {
var minD = hugeVal
var minI = pt.group
for (i in 0 until nCluster) {
val d = dist2(cent[i], pt)
if (minD > d) {
minD = d
minI = i
}
}
return minI to minD
}
fun kpp(pts: LPoint, len: Int, cent: MLPoint) {
if (pts.isEmpty() || len == 0) return
val nCent = cent.size
val d = DoubleArray(len)
//println("points size:${pts.size} length:$len")
cent[0] = pts[rand() % len].copy()
for (nCluster in 1 until nCent) {
var sum = 0.0
for (j in 0 until len) {
d[j] = nearest(pts[j], cent, nCluster).second
sum += d[j]
}
sum = randf(sum)
for (j in 0 until len) {
sum -= d[j]
if (sum > 0.0) continue
cent[nCluster] = pts[j].copy()
break
}
}
for (j in 0 until len) pts[j].group = nearest(pts[j], cent, nCent).first
}
fun lloyd(pts: LPoint, len: Int, nCluster: Int): LPoint {
val cent = MutableList(nCluster) { origin }
kpp(pts, len, cent)
do {
/* group element for centroids are used as counters */
for (i in 0 until nCluster) {
with (cent[i]) { x = 0.0; y = 0.0; group = 0 }
}
for (j in 0 until len) {
val p = pts[j]
val c = cent[p.group]
with (c) { group++; x += p.x; y += p.y }
}
for (i in 0 until nCluster) {
val c = cent[i]
c.x /= c.group
c.y /= c.group
}
var changed = 0
/* find closest centroid of each point */
for (j in 0 until len) {
val p = pts[j]
val minI = nearest(p, cent, nCluster).first
if (minI != p.group) {
changed++
p.group = minI
}
}
}
while (changed > (len shr 10)) /* stop when 99.9% of points are good */
for (i in 0 until nCluster) cent[i].group = i
return cent
}
fun printEps(pts: LPoint, len: Int, cent: LPoint, nCluster: Int) {
val colors = DoubleArray(nCluster * 3)
for (i in 0 until nCluster) {
colors[3 * i + 0] = (3 * (i + 1) % 11) / 11.0
colors[3 * i + 1] = (7 * i % 11) / 11.0
colors[3 * i + 2] = (9 * i % 11) / 11.0
}
var minX = hugeVal
var minY = hugeVal
var maxX = -hugeVal
var maxY = -hugeVal
for (j in 0 until len) {
val p = pts[j]
if (maxX < p.x) maxX = p.x
if (minX > p.x) minX = p.x
if (maxY < p.y) maxY = p.y
if (minY > p.y) minY = p.y
}
val scale = minOf(W / (maxX - minX), H / (maxY - minY))
val cx = (maxX + minX) / 2.0
val cy = (maxY + minY) / 2.0
print("%%!PS-Adobe-3.0\n%%%%BoundingBox: -5 -5 %${W + 10} ${H + 10}\n")
print("/l {rlineto} def /m {rmoveto} def\n")
print("/c { .25 sub exch .25 sub exch .5 0 360 arc fill } def\n")
print("/s { moveto -2 0 m 2 2 l 2 -2 l -2 -2 l closepath ")
print(" gsave 1 setgray fill grestore gsave 3 setlinewidth")
print(" 1 setgray stroke grestore 0 setgray stroke }def\n")
val f1 = "%g %g %g setrgbcolor"
val f2 = "%.3f %.3f c"
val f3 = "\n0 setgray %g %g s"
for (i in 0 until nCluster) {
val c = cent[i]
println(f1.format(colors[3 * i], colors[3 * i + 1], colors[3 * i + 2]))
for (j in 0 until len) {
val p = pts[j]
if (p.group != i) continue
println(f2.format((p.x - cx) * scale + W / 2, (p.y - cy) * scale + H / 2))
}
println(f3.format((c.x - cx) * scale + W / 2, (c.y - cy) * scale + H / 2))
}
print("\n%%%%EOF")
}
| 0 | Kotlin | 0 | 4 | 291915e53e98603f2fe14154dbdd445187649b67 | 5,158 | MikroKanon | MIT License |
séance 1 et 2 _ classe et objet/correction/Complexe.kt | strouilhet | 683,668,398 | false | {"Kotlin": 11285} | import kotlin.math.PI
import kotlin.math.atan
import kotlin.math.round
import kotlin.math.sqrt
class Complexe(val reel: Double = 0.0, val im: Double = 0.0) {
constructor(c: Complexe) : this(c.reel, c.im)
fun module(): Double = sqrt(reel * reel + im * im)
fun argument(): Double =
if (reel == 0.0)
if (im >= 0) PI / 2 else -PI / 2
else atan(im / reel)
fun add(z:Complexe): Complexe =Complexe(reel+z.reel, im+ z.im)
fun mul(z:Complexe): Complexe = Complexe(reel*z.reel - im*z.im,reel*z.im + im*z.reel)
/**
* puissance
* précondition n >=1
* @param n, puissance
* @return puissance (Complexe)
*/
fun puissance(n:Int):Complexe {
var r:Complexe=this
for (i in 2..n) r=mul(r)
return Complexe(round(r.reel), round(r.im))
}
fun puissanceBis(n: Int): Complexe {
var r = Complexe(1.0, 0.0)
for (i in 0 until n) // n-1 compris
r = r.mul(this)
return r
}
/**
* inverse du nombre complexe
* précondition : this est non nul
* @return inverse (Complexe)
*/
fun inverse(): Complexe
=Complexe(reel / (reel * reel + im * im), -im / (reel * reel + im * im))
/**
* division du nombre complexe par z
* précondition : z non nul
* @param z, diviseur
* @return quotiont (Complexe)
*/
fun div(z: Complexe): Complexe = this.mul(z.inverse())
override fun toString(): String = "$reel + i $im"
companion object {
val I = Complexe(0.0, 1.0)
val J = Complexe(-1 / 2.0, Math.sqrt(3.0) / 2)
}
}
// question 1 --> avant l'ajout des getters
/*
class Complexe constructor(_reel:Double = 0.0, _im:Double= 0.0) {
private val reel:Double=_reel
private val im: Double=_im
constructor(c:Complexe): this(c.reel, c.im) {
}
}*/
| 0 | Kotlin | 0 | 0 | f779bf1e69f9666da225866aca777252438953a1 | 1,869 | KeepCalmAndCode3 | MIT License |
2021/src/day06/Solution.kt | vadimsemenov | 437,677,116 | false | {"Kotlin": 56211, "Rust": 37295} | package day06
import java.nio.file.Files
import java.nio.file.Paths
fun main() {
val mem = Array(2) {
Array(9) {
LongArray(257) { -1 }
}
}
fun model(daysLeft: Int, day: Int, part: Int): Long {
require(daysLeft in 0..8)
require(part in 0..1)
val lastDay = if (part == 0) 80 else 256
require(day in 0..lastDay)
mem[part][daysLeft][day].let {
if (it != -1L) return it
}
val res = if (day >= lastDay) 1 else if (daysLeft == 0) {
model(6, day + 1, part) + model(8, day + 1, part)
} else {
model(daysLeft - 1, day + 1, part)
}
return res.also {
mem[part][daysLeft][day] = res
}
}
fun part1(input: Input): Long {
return input.sumOf { model(it, 0, 0) }
}
fun part2(input: Input): Long {
return input.sumOf { model(it, 0, 1) }
}
check(part1(readInput("test-input.txt")) == 5934L)
println(part1(readInput("input.txt")))
part2(readInput("test-input.txt")).let {
check(it == 26984457539L) { it }
}
println(part2(readInput("input.txt")))
}
private fun readInput(s: String): Input {
return Files.newBufferedReader(Paths.get("src/day06/$s")).readLines().first().split(",").map { it.toInt() }
}
private typealias Input = List<Int> | 0 | Kotlin | 0 | 0 | 8f31d39d1a94c862f88278f22430e620b424bd68 | 1,248 | advent-of-code | Apache License 2.0 |
src/kotlin/kt_101/Lambdas_111.kt | iJKENNEDY | 343,256,517 | false | null | package kt_101
class Lambdas_111 {
fun iterando_lambdas(){
// val values = listOf(1,3,4,6,7,8,9,13,23,59,50)
// values.forEach{
// println("$it: ${it*it}")
// }
println()
var prices = listOf(1.3,4.94,99.95,55.49)
val largePrices = prices.filter {
it > 45.0
}
println(largePrices)
println()
val salesPrices = prices.map {
it*0.5
}
println(salesPrices)
println()
val userInput = listOf("0","123","enigma","945")
val numbers = userInput.map {
it.toIntOrNull()
}
println("numbers: ${numbers}")
println()
var sum123 = prices.fold(0.0){ a,b ->
a+b
}
println("sum = ${sum123}")
println()
val stock = mapOf(1.0 to 43, 1.4 to 49, 2.4 to 44.4
,59.9 to 490, 6.0 to 684)
var stockSum = 0.0
}
fun lambda_basico(){
val multiplyLambda: (Int,Int)-> Int
multiplyLambda = {a: Int, b: Int -> Int
a*b
}
val lambdaResult = multiplyLambda(123,99)
println("lambda result = $lambdaResult")
println()
val lambdaResultSum2:(Int, Int)-> Int= { a, b ->
a+b
}
val ss3 = lambdaResultSum2(45,85)
val lambdaResta:(Int, Int)->Int={a, b -> a-b}
val rest = lambdaResta(544,111)
println("sum2 = $ss3")
println("resta = $rest")
var doubleLambda = {a: Double -> a*4}
doubleLambda = {2.3 * it}
val resDouble = doubleLambda(33.33)
println("rdl = $resDouble")
val square:(Int)->Int = {it* it}
val cubeNum:(Int)->Int = {it*it*it}
println("square = ${square(12)}")
println("cubeNum = ${cubeNum(4)}")
}
fun operateOnNumbers(a:Int, b:Int, operation:(Int,Int)->Int):Int{
val result = operation(a,b)
println("result: $result")
return result
}
}
| 0 | Kotlin | 0 | 0 | 08f08f782264b0f173eea4dc235aebe4492e4536 | 2,046 | kotlin_code_101 | MIT License |
src/main/kotlin/day17.kt | Arch-vile | 572,557,390 | false | {"Kotlin": 132454} | package day17
import aoc.utils.*
import kotlin.text.toList
data class Shape(val blocks: List<Cursor>) {
fun isFalling(stationary: List<Shape>): Boolean {
val intersect = stationary.flatMap { it.blocks }.intersect(this.blocks.toSet())
return intersect.isEmpty()
}
fun move(move: Cursor, stationary: MutableList<Shape>): Shape {
val updated = this.copy(blocks = blocks.map { it.plus(move) })
return if (!updated.isFalling(stationary) || updated.isOutOfBounds()) {
this
} else {
updated
}
}
fun blow(direction: Char, stationary: MutableList<Shape>): Shape {
// Let's not move if not free
if (!isFalling(stationary))
return this
val move = when (direction) {
'>' -> Cursor(1, 0)
'<' -> Cursor(-1, 0)
else -> throw Error("unknown direction")
}
return this.move(move, stationary)
}
private fun isOutOfBounds(): Boolean {
val maxX = blocks.maxOf { it.x }
val minX = blocks.minOf { it.x }
return minX < 0 || maxX > 6
}
}
fun part1(): Long {
return runSimulation(2022)
}
fun part2(): Long {
return runSimulation(2022)
}
fun main() {
val matrix = Matrix(10,10){a,b -> "d"}
val timer = Timer(1000000000000)
var i = 0L
while(i < 1000000000000) {
timer.processed = i+1
val v = matrix.get(Cursor((i % matrix.width()).toInt(),0))
val t = matrix.get(Cursor((i % matrix.width()).toInt(),(i%matrix.height()).toInt()))
val p = t.cursor.plus(Cursor(1,2))
matrix.rows()[(i%matrix.height()).toInt()].map { it.cursor.plus(Cursor(1,1)) }
i+=1
}
runSimulation(100)
}
fun runSimulation(rocksToDrop: Long): Long {
val gasDirection = readInput("day17-input.txt").take(1).flatMap { it.toList() }
val stationary = mutableListOf(floor)
var nextGasIndex = 0;
var nextRockIndex = 0
var rockCount: Long = 0
val timer = Timer(rocksToDrop)
while (rockCount < rocksToDrop) {
rockCount += 1
timer.processed = rockCount
val highestPoint = highestPoint(stationary)
val nextShape = rocks.getLooping(nextRockIndex)
var current = nextShape.move(Cursor(0, highestPoint.y + 4), stationary)
while (true) {
val direction = gasDirection.getLooping(nextGasIndex)
current = current.blow(direction, stationary)
nextGasIndex += 1
val previous = current
current = current.move(DOWN, stationary)
if (previous == current)
break
}
stationary.add(current)
if (stationary.size > 150)
stationary.removeAt(0)
nextRockIndex++
}
println(visualize(stationary))
val highestPoint = highestPoint(stationary)
return highestPoint.y.toLong()
}
private fun tryFindPattern(
stationary: MutableList<Shape>,
patternToMatch: Set<Cursor>?
) {
var patternToMatch1 = patternToMatch
if (stationary.size > 20) {
if (patternToMatch1 == null) {
patternToMatch1 = stationary.takeLast(20).flatMap { it.blocks }.toSet()
patternToMatch1 = normalize(patternToMatch1)
} else {
var test = stationary.takeLast(20).flatMap { it.blocks }.toSet()
test = normalize(test)
if (test.containsAll(patternToMatch1) && test.size == patternToMatch1.size) {
throw Error("found")
}
}
}
}
fun normalize(cursors: Set<Cursor>): Set<Cursor> {
val lowest = cursors.minByOrNull { it.y }!!.y
return cursors.map { it.minus(Cursor(0, lowest)) }.toSet()
}
private fun visualize(stationary: List<Shape>, rock: Shape? = null) {
val symbols = ('a'..'z').toList()
val lowest = lowestPoint(stationary).y
val offsettedShapes = stationary.map { it.copy(blocks = it.blocks.map { it.minus(Cursor(0, lowest)) }) }
val height = highestPoint(offsettedShapes).y
val matrix = Matrix(7, height + 10L) { a, b -> "." }
offsettedShapes.forEach { shape ->
val symbol = symbols.random().toString()
shape.blocks.forEach {
matrix.replace(it) { symbol }
}
}
rock?.let {
it.blocks.forEach { matrix.replace(it) { "@" } }
}
println(matrix.flipHorizontal().visualize(""))
println("------------------------------")
}
fun highestPoint(stationary: List<Shape>): Cursor {
return stationary.flatMap { it.blocks }
.maxByOrNull { it.y }!!
}
fun lowestPoint(stationary: List<Shape>): Cursor {
return stationary.flatMap { it.blocks }
.minByOrNull { it.y }!!
}
val hLine = Shape(
listOf(
Cursor(2, 0),
Cursor(3, 0),
Cursor(4, 0),
Cursor(5, 0),
)
)
val vLine = Shape(
listOf(
Cursor(2, 0),
Cursor(2, 1),
Cursor(2, 2),
Cursor(2, 3),
)
)
val cross = Shape(
listOf(
Cursor(2, 1),
Cursor(3, 1),
Cursor(4, 1),
Cursor(3, 0),
Cursor(3, 2),
)
)
val lBlock = Shape(
listOf(
Cursor(2, 0),
Cursor(3, 0),
Cursor(4, 0),
Cursor(4, 1),
Cursor(4, 2),
)
)
val square = Shape(
listOf(
Cursor(2, 0),
Cursor(3, 0),
Cursor(2, 1),
Cursor(3, 1),
)
)
val floor = Shape(
listOf(
Cursor(0, 0),
Cursor(1, 0),
Cursor(2, 0),
Cursor(3, 0),
Cursor(4, 0),
Cursor(5, 0),
Cursor(6, 0),
)
)
val rocks = listOf(hLine, cross, lBlock, vLine, square)
val DOWN = Cursor(0, -1)
| 0 | Kotlin | 0 | 0 | e737bf3112e97b2221403fef6f77e994f331b7e9 | 5,681 | adventOfCode2022 | Apache License 2.0 |
src/Day01.kt | cypressious | 572,916,585 | false | {"Kotlin": 40281} | fun main() {
fun part1(input: List<String>): Int {
return input.map { it.toInt() }.windowed(2, 1).count { (a, b) -> b > a }
}
fun part2(input: List<String>): Int {
return input
.asSequence()
.map { it.toInt() }
.windowed(3, 1)
.map { it.sum() }
.windowed(2, 1)
.count { (a, b) -> b > a }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 7)
check(part2(testInput) == 5)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 169fb9307a34b56c39578e3ee2cca038802bc046 | 669 | AdventOfCode2021 | Apache License 2.0 |
src/2021/Day17_1.kts | Ozsie | 318,802,874 | false | {"Kotlin": 99344, "Python": 1723, "Shell": 975} | import java.io.File
import kotlin.math.absoluteValue
import kotlin.math.max
File("input/2021/day17").forEachLine { line ->
val (xTarget, yTarget) = line.substring(13).split(", ")
val (xMin, xMax) = xTarget.substring(2).split("..").map { it.toInt() }.sortedBy { it }
val (yMin, yMax) = yTarget.substring(2).split("..").map { it.toInt() }.sortedBy { it }
val xRange = xMin.toInt()..xMax.toInt()
val yRange = yMin.toInt()..yMax.toInt()
var initVel = Pair(0,0)
var maxYPos = Int.MIN_VALUE
for (x in 0..500) {
for (y in -200..200) {
var localYMax = Int.MIN_VALUE
var position = Pair(0,0)
var velocity = Pair(x,y)
var steps = 0
var over = false
while (true) {
steps++
val nX = position.first + velocity.first
val nY = position.second + velocity.second
position = Pair(nX, nY)
if (nY > localYMax) localYMax = nY
val inX = position.first >= xRange.first && position.first <= xRange.last
val inY = position.second >= yRange.first && position.second <= yRange.last
if (inX && inY) break
val short = (nX < xRange.first && nY < yRange.first)
val long = (nX > xRange.last && nY < yRange.first)
val toMuchY = (nY < yRange.last)
if (short || long || toMuchY) {
over = true
break
}
val nVX = if (velocity.first > 0) velocity.first - 1 else if (velocity.first < 0) velocity.first + 1 else velocity.first
val nVY = velocity.second - 1
velocity = Pair(nVX, nVY)
}
if (!over){
maxYPos = max(localYMax, maxYPos)
initVel = Pair(x,y)
}
}
}
println(maxYPos)
} | 0 | Kotlin | 0 | 0 | d938da57785d35fdaba62269cffc7487de67ac0a | 1,932 | adventofcode | MIT License |
src/main/kotlin/day1.kt | tianyu | 574,561,581 | false | {"Kotlin": 49942} | private fun main() {
part1("The elf carrying the most calories has:") {
calories().max()
}
part2("The three elves carrying the most calories has:") {
calories().top(3).sum()
}
}
private fun calories() = sequence {
withInputLines("day1.txt") {
var calories = 0
val inventory = iterator()
while (inventory.hasNext()) {
when (val item = inventory.next()) {
"" -> {
yield(calories)
calories = 0
}
else -> calories += item.toInt()
}
}
if (calories > 0) {
yield(calories)
}
}
}
private fun Sequence<Int>.top(n: Int) = IntArray(n) { 0 }.also { top ->
forEach { value ->
if (value > top[0]) {
top[0] = value
top.sort()
}
}
}
| 0 | Kotlin | 0 | 0 | 6144cc0ccf1a51ba2e28c9f38ae4e6dd4c0dc1ea | 750 | AdventOfCode2022 | MIT License |
advent-of-code-2023/src/test/kotlin/Day9Test.kt | yuriykulikov | 159,951,728 | false | {"Kotlin": 1666784, "Rust": 33275} | import io.kotest.matchers.collections.shouldContainAll
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
class Day9Test {
private val testInput =
"""
0 3 6 9 12 15
1 3 6 10 15 21
10 13 16 21 30 45
"""
.trimIndent()
@Test
fun `silver test (example)`() {
parseSequences(testInput)
.map { initialSequence -> foldSequence(initialSequence) }
.apply { shouldContainAll(18, 28, 68) }
.sum()
.shouldBe(114)
}
@Test
fun `silver test`() {
parseSequences(loadResource("Day9"))
.sumOf { initialSequence -> foldSequence(initialSequence) }
.shouldBe(1479011877)
}
@Test
fun `gold test (example)`() {
parseSequences(testInput)
.sumOf { initialSequence -> foldSequenceGold(initialSequence) }
.shouldBe(2)
}
@Test
fun `gold test`() {
parseSequences(loadResource("Day9"))
.sumOf { initialSequence -> foldSequenceGold(initialSequence) }
.shouldBe(973)
}
private fun foldSequence(initialSequence: List<Int>): Int {
return generateSequence(initialSequence) { it.zipWithNext { l, r -> r - l } }
.takeWhile { seq -> !seq.all { it == 0 } }
.sumOf { it.last() }
}
private fun foldSequenceGold(initialSequence: List<Int>): Int {
return generateSequence(initialSequence) { it.zipWithNext { l, r -> r - l } }
.takeWhile { seq -> !seq.all { it == 0 } }
.map { it.first() }
.toList()
.reversed()
.fold(0) { acc, next -> next - acc }
}
private fun parseSequences(input: String) =
input
.lines()
.filterNot { it.isEmpty() }
.map { line -> line.trim().split(" ").map { it.toInt() } }
}
| 0 | Kotlin | 0 | 1 | f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3 | 1,776 | advent-of-code | MIT License |
src/main/kotlin/utils/AlgorithmAStar.kt | joakimgy | 347,076,060 | false | null | package utils
interface Graph {
interface Vertex
interface Edge<T : Vertex> {
val a: T
val b: T
}
}
abstract class AlgorithmAStar<V : Graph.Vertex, E : Graph.Edge<V>>(
private val edges: List<E>
) : Graph {
private val V.neighbors: List<V>
get() = edges
.asSequence()
.filter { it.a == this || it.b == this }
.map { listOf(it.a, it.b) }
.flatten()
.filterNot { it == this }
.distinct()
.toList()
private val E.cost: Double
get() = costToMoveThrough(this)
private fun findRoute(from: V, to: V): E? {
return edges.find {
(it.a == from && it.b == to) || (it.a == to && it.b == from)
}
}
private fun findRouteOrElseCreateIt(from: V, to: V): E {
return findRoute(from, to) ?: createEdge(from, to)
}
private fun generatePath(currentPos: V, cameFrom: Map<V, V>): List<V> {
val path = mutableListOf(currentPos)
var current = currentPos
while (cameFrom.containsKey(current)) {
current = cameFrom.getValue(current)
path.add(0, current)
}
return path.toList()
}
abstract fun costToMoveThrough(edge: E): Double
abstract fun createEdge(from: V, to: V): E
fun findPath(begin: V, end: V): Pair<List<V>, Double> {
val cameFrom = mutableMapOf<V, V>()
val openVertices = mutableSetOf(begin)
val closedVertices = mutableSetOf<V>()
val costFromStart = mutableMapOf(begin to 0.0)
val estimatedRoute = findRouteOrElseCreateIt(from = begin, to = end)
val estimatedTotalCost = mutableMapOf(begin to estimatedRoute.cost)
while (openVertices.isNotEmpty()) {
val currentPos = openVertices.minByOrNull { estimatedTotalCost.getValue(it) }!!
// Check if we have reached the finish
if (currentPos == end) {
// Backtrack to generate the most efficient path
val path = generatePath(currentPos, cameFrom)
// First Route to finish will be optimum route
return Pair(path, estimatedTotalCost.getValue(end))
}
// Mark the current vertex as closed
openVertices.remove(currentPos)
closedVertices.add(currentPos)
(currentPos.neighbors - closedVertices).forEach { neighbour ->
val routeCost = findRouteOrElseCreateIt(from = currentPos, to = neighbour).cost
val cost: Double = costFromStart.getValue(currentPos) + routeCost
if (cost < costFromStart.getOrDefault(neighbour, Double.MAX_VALUE)) {
if (!openVertices.contains(neighbour)) {
openVertices.add(neighbour)
}
cameFrom[neighbour] = currentPos
costFromStart[neighbour] = cost
val estimatedRemainingRouteCost = findRouteOrElseCreateIt(from = neighbour, to = end).cost
estimatedTotalCost[neighbour] = cost + estimatedRemainingRouteCost
}
}
}
throw IllegalArgumentException("No Path from Start $begin to Finish $end")
}
}
| 0 | Kotlin | 0 | 0 | 0d6915b4c7ffde4ba2024584fab4b9b16b719d9a | 3,283 | tower-defence | MIT License |
src/main/kotlin/de/pgebert/aoc/days/Day08.kt | pgebert | 724,032,034 | false | {"Kotlin": 65831} | package de.pgebert.aoc.days
import de.pgebert.aoc.Day
import de.pgebert.aoc.utils.lcm
class Day08(input: String? = null) : Day(8, "Haunted Wasteland", input) {
private val nodeRegex = "(\\S+) = \\((\\S+), (\\S+)\\)".toRegex()
override fun partOne(): Int {
val (instructions, nodes) = parseInput()
var currentNode = "AAA"
var steps = 0
while (currentNode != "ZZZ") {
currentNode = nodes[currentNode]!!.let {
when (instructions[steps % instructions.length]) {
'L' -> it.first
else -> it.second
}
}
steps++
}
return steps
}
override fun partTwo(): Long {
val (instructions, nodes) = parseInput()
var startNodes = nodes.keys.filter { it.endsWith("A") }
return startNodes.map {
var currentNode = it
var steps = 0
while (!currentNode.endsWith("Z")) {
currentNode = nodes[currentNode]!!.let {
when (instructions[steps % instructions.length]) {
'L' -> it.first
else -> it.second
}
}
steps++
}
steps.toLong()
}.reduce(::lcm)
}
private fun parseInput(): Pair<String, Map<String, Pair<String, String>>> {
val instructions = inputList.first()
val nodes = inputList.filter { it.isNotEmpty() }.drop(1).map { line ->
val (start, left, right) = nodeRegex.find(line)!!.destructured
start to Pair(left, right)
}.toMap()
return Pair(instructions, nodes)
}
}
| 0 | Kotlin | 1 | 0 | a30d3987f1976889b8d143f0843bbf95ff51bad2 | 1,726 | advent-of-code-2023 | MIT License |
src/main/aoc2015/Day12.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2015
import java.util.*
class Day12(val input: String) {
fun solvePart1(): Int {
return input.split(',', ':', '[', ']', '{', '}').mapNotNull { it.toIntOrNull() }.sum()
}
private data class Node(var sum: Int = 0, var red: Boolean = false, val children: MutableList<Node> = mutableListOf())
private fun ignoreRed(): Int {
// Split the string with same delimiters in part 1, except colon and keep the delimiters:
// https://stackoverflow.com/questions/37131283/how-to-split-a-string-and-plant-the-delimiters-between-the-splitted-parts-in-kot
val reg = Regex("(?<=[,{}\\[\\]])|(?=[,{}\\[\\]])")
val list = input.split(reg).filterNot { listOf("", ",", "[", "]").contains(it) }
// Create a tree where each new object is a child to the current node
val root = Node()
var curr = root
val stack = Stack<Node>()
for (token in list) {
when {
token == "{" -> {
// Start of a new object create a child node and continue processing it
val child = Node()
curr.children.add(child)
// push the current node to the stack and continue with this when the
// new object has been processed.
stack.push(curr)
curr = child
}
token == "}" -> {
// Object ends, continue processing the parent
curr = stack.pop()
}
token.contains(":\"red\"") -> {
// :"red" are red in objects that should cause ignores. Mark this node as red
// ("red" without leading colon is in arrays and does not affect the sum)
curr.red = true
}
else -> {
// Either an object (has : followed by the value), or an array where
// : does not exist and substringAfter will return the original string.
// If it's an integer add it to the sum, for the rest (colors) add 0
curr.sum += token.substringAfter(":").toIntOrNull() ?: 0
}
}
}
return sum(root)
}
// Sum the value of all non-red nodes in the tree
private fun sum(node: Node): Int {
return if (node.red) {
0
} else {
node.sum + node.children.sumOf { sum(it) }
}
}
fun solvePart2(): Int {
return ignoreRed()
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 2,589 | aoc | MIT License |
src/main/kotlin/adventofcode2023/day20/day20.kt | dzkoirn | 725,682,258 | false | {"Kotlin": 133478} | package adventofcode2023.day20
import adventofcode2023.day8.findLCM
import adventofcode2023.readInput
import java.util.LinkedList
import java.util.Queue
import kotlin.time.measureTime
data class Signal(
val level: SignalLevel,
val source: String,
val destination: String
) {
enum class SignalLevel {
LOW, HIGH;
}
}
abstract class Module(
val name: String,
val destinations: Array<String>
) {
open fun addSource(name: String) {}
abstract fun sendSignal(signal: Signal): Collection<Signal>
}
class Broadcaster(
name: String,
destinations: Array<String>
) : Module(name, destinations) {
override fun sendSignal(signal: Signal): Collection<Signal> {
return destinations.map { Signal(signal.level, name, it) }
}
}
class FlipFlop(
name: String,
destinations: Array<String>
) : Module(name, destinations) {
private var isOn: Boolean = false
override fun sendSignal(signal: Signal): Collection<Signal> {
return when (signal.level) {
Signal.SignalLevel.HIGH -> emptyList()
Signal.SignalLevel.LOW -> {
isOn = !isOn
val outLevel = if (isOn) {
Signal.SignalLevel.HIGH
} else {
Signal.SignalLevel.LOW
}
destinations.map { Signal(outLevel, name, it) }
}
}
}
}
class Conjunction(
name: String,
destinations: Array<String>,
) : Module(name, destinations) {
private val sources = mutableMapOf<String, Signal.SignalLevel>()
override fun addSource(name: String) {
sources[name] = Signal.SignalLevel.LOW
}
override fun sendSignal(signal: Signal): Collection<Signal> {
sources[signal.source] = signal.level
val outLevel = if (sources.values.all { it == Signal.SignalLevel.HIGH }) {
Signal.SignalLevel.LOW
} else {
Signal.SignalLevel.HIGH
}
return destinations.map { Signal(outLevel, name, it) }
}
}
fun parseInput(input: List<String>): Map<String, Module> {
return input.associate { line ->
line.split("->").map { s -> s.trim() }.let { (module, destinationsStr) ->
val destinations = destinationsStr.split(",").map { s -> s.trim() }.toTypedArray()
if (module == "broadcaster") {
"broadcaster" to Broadcaster("broadcaster", destinations)
} else if (module.startsWith("%")) {
val key = module.substring(1)
key to FlipFlop(key, destinations)
} else {
val key = module.substring(1)
key to Conjunction(key, destinations)
}
}
}.also { map ->
map.values.forEach { m -> m.destinations.forEach { d -> map[d]?.addSource(m.name) } }
}
}
fun pushButton(times: Int, schema: Map<String, Module>): Pair<Int, Int> {
val queue: Queue<Signal> = LinkedList()
var lowCounter: Int = 0
var highCounter: Int = 0
repeat(times) {
queue.add(Signal(Signal.SignalLevel.LOW, "button", "broadcaster"))
while (queue.isNotEmpty()) {
val signal = queue.poll().also {
if (it.level == Signal.SignalLevel.LOW) {
lowCounter++
} else {
highCounter++
}
}
val module = schema[signal.destination]
if (module != null) {
val out = module.sendSignal(signal)
queue.addAll(out)
}
}
}
return Pair(lowCounter, highCounter)
}
fun puzzle1(input: List<String>): Int {
val scheme = parseInput(input)
return pushButton(1000, scheme).let { (low, high) -> low * high }
}
fun main() {
println("Day 20")
val input = readInput("day20")
val time1 = measureTime {
println("Puzzle 1 ${puzzle1(input)}")
}
println("Puzzle 1 took $time1")
val time2 = measureTime {
println("Puzzle 2 ${puzzle2(input)}")
}
println("Puzzle 2 took $time2")
}
fun puzzle2(input: List<String>): Long {
val schema = parseInput(input)
val queue: Queue<Signal> = LinkedList()
val modulesToListen = schema.values.filter { it.destinations.contains("ll") }.map { it.name }.toMutableSet()
val counters = mutableListOf<Long>()
var counter: Long = 1
while(true) {
queue.add(Signal(Signal.SignalLevel.LOW, "button", "broadcaster"))
while (queue.isNotEmpty()) {
val signal = queue.poll()
if (signal.destination == "rx" && signal.level == Signal.SignalLevel.LOW) {
return counter
}
if (signal.source in modulesToListen && signal.level == Signal.SignalLevel.HIGH) {
counters.add(counter)
modulesToListen.remove(signal.source)
}
val module = schema[signal.destination]
if (module != null) {
val out = module.sendSignal(signal)
queue.addAll(out)
}
}
counter++
if (modulesToListen.isEmpty()) {
return counters.reduce(::findLCM)
}
}
} | 0 | Kotlin | 0 | 0 | 8f248fcdcd84176ab0875969822b3f2b02d8dea6 | 5,220 | adventofcode2023 | MIT License |
src/week4/FindWords.kt | anesabml | 268,056,512 | false | null | package week4
class FindWords {
fun findWords(board: Array<CharArray>, words: Array<String>): List<String> {
val result = mutableListOf<String>()
val root = buildTrie(words)
for (i in board.indices) {
for (j in board[0].indices) {
dfs(board, root, result, i, j)
}
}
return result
}
private fun dfs(board: Array<CharArray>, p: TrieNode, result: MutableList<String>, i: Int, j: Int) {
if (i < 0 || i >= board.size || j < 0 || j >= board[0].size || board[i][j] == '#' || p.next[board[i][j] - 'a'] == null) {
return
}
val currentChar = board[i][j]
val _p = p.next[currentChar - 'a']!!
if (_p.word != "") {
result.add(_p.word)
_p.word = ""
}
board[i][j] = '#'
dfs(board, _p, result, i - 1, j)
dfs(board, _p, result, i + 1, j)
dfs(board, _p, result, i, j - 1)
dfs(board, _p, result, i, j + 1)
board[i][j] = currentChar
}
private fun buildTrie(words: Array<String>): TrieNode {
val root = TrieNode()
for (word in words) {
var p = root
for (c in word) {
val i = c - 'a'
if (p.next[i] == null) {
p.next[i] = TrieNode()
}
p = p.next[i]!!
}
p.word = word
}
return root
}
class TrieNode {
val next = Array<TrieNode?>(26) { null }
var word: String = ""
}
} | 0 | Kotlin | 0 | 1 | a7734672f5fcbdb3321e2993e64227fb49ec73e8 | 1,574 | leetCode | Apache License 2.0 |
src/main/kotlin/graph/core/TopoSort.kt | yx-z | 106,589,674 | false | null | package graph.core
import graph.core.Status.*
import util.OneArray
import util.toOneArray
// topological sort of a directed acyclic graph (dag)
fun <V> Graph<V>.topoSort(checkIdentity: Boolean = true): OneArray<Vertex<V>> {
val sorted = ArrayList<Vertex<V>>()
val status = HashMap<Vertex<V>, Status>()
vertices.forEach { status[it] = NEW }
var clock = vertices.size
vertices.forEach {
if (status[it] == NEW) {
clock = topoSort(it, status, clock, sorted, checkIdentity)
}
}
return sorted.toOneArray()
}
private fun <V> Graph<V>.topoSort(vertex: Vertex<V>,
status: HashMap<Vertex<V>, Status>,
clock: Int,
list: ArrayList<Vertex<V>>,
checkIdentity: Boolean): Int {
var counter = clock
status[vertex] = ACTIVE
getEdgesFrom(vertex, checkIdentity).forEach { (_, u) ->
when (status[u]) {
NEW -> counter = topoSort(u, status, counter, list, checkIdentity)
ACTIVE -> throw CycleDetectedException()
else -> {
}
}
}
status[vertex] = FINISHED
list.add(0, vertex)
return counter - 1
}
class CycleDetectedException
: Exception("graph contains cycles, cannot be sorted")
enum class Status {
NEW, ACTIVE, FINISHED;
}
fun main(args: Array<String>) {
val vertices = (1..5).map { Vertex(it) }
val edges = setOf(
Edge(vertices[0], vertices[1], true),
Edge(vertices[0], vertices[2], true),
Edge(vertices[0], vertices[3], true),
Edge(vertices[0], vertices[4], true),
Edge(vertices[1], vertices[4], true),
Edge(vertices[2], vertices[1], true),
Edge(vertices[2], vertices[3], true),
Edge(vertices[3], vertices[4], true))
val graph = Graph(vertices, edges)
println(graph.topoSort())
}
| 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 1,774 | AlgoKt | MIT License |
src/main/kotlin/space/d_lowl/kglsm/problem/MAXSAT.kt | d-lowl | 300,622,439 | false | null | package space.d_lowl.kglsm.problem
import kotlin.random.Random
data class SATLiteral(val index: Int, val negated: Boolean) {
override fun toString(): String = "${if (negated) "¬" else ""}x$index"
}
class SATClause(private val literals: Array<SATLiteral>) {
private val maxIndex = literals.map { it.index }.max() ?: 0
fun evaluate(assignment: Array<Boolean>): Boolean {
assert(assignment.size - 1 >= maxIndex)
return literals.any {
val b = assignment[it.index]
if (!it.negated) b else !b
}
}
override fun toString(): String = "(${literals.joinToString("∨")})"
}
class MAXSAT(private val maxIndex: Int, private val clauses: List<SATClause>): Problem<Boolean> {
override fun getSolutionCost(solution: Array<Boolean>): Double {
assert(solution.size - 1 == maxIndex)
return 1.0 - clauses.count { it.evaluate(solution) }.toDouble() / clauses.size
}
override fun toString(): String = clauses.joinToString("∧")
companion object {
fun getRandomInstance(noVariables: Int, noClauses: Int, maxPerClause: Int): MAXSAT =
MAXSAT(noVariables, List(noClauses) {
SATClause(Array(maxPerClause) {
SATLiteral(Random.nextInt(noVariables), Random.nextBoolean())
})
})
}
}
| 17 | Kotlin | 0 | 1 | 0886e814be75a77fa8f33faa867329aef19085a5 | 1,351 | kGLSM | MIT License |
src/main/kotlin/de/nosswald/aoc/days/Day06.kt | 7rebux | 722,943,964 | false | {"Kotlin": 34890} | package de.nosswald.aoc.days
import de.nosswald.aoc.Day
// https://adventofcode.com/2023/day/6
object Day06 : Day<Int>(6, "Wait For It") {
override fun partOne(input: List<String>): Int {
val (times, records) = input.map { line ->
line
.split(":")
.last()
.split(" ")
.filter(String::isNotBlank)
.map(String::toLong)
}
return times.zip(records).map { (time, record) -> countPossibleRecords(time, record) }.reduce(Int::times)
}
override fun partTwo(input: List<String>): Int {
val (time, record) = input.map { line ->
line
.split(":")
.last()
.filterNot(Char::isWhitespace)
.toLong()
}
return countPossibleRecords(time, record)
}
private fun countPossibleRecords(time: Long, record: Long): Int {
return (1..time).count { (time - it) * it > record }
}
override val partOneTestExamples: Map<List<String>, Int> = mapOf(
listOf(
"Time: 7 15 30",
"Distance: 9 40 200",
) to 288
)
override val partTwoTestExamples: Map<List<String>, Int> = mapOf(
listOf(
"Time: 7 15 30",
"Distance: 9 40 200",
) to 71503
)
}
| 0 | Kotlin | 0 | 1 | 398fb9873cceecb2496c79c7adf792bb41ea85d7 | 1,376 | advent-of-code-2023 | MIT License |
src/main/kotlin/Problem32.kt | jimmymorales | 496,703,114 | false | {"Kotlin": 67323} | @file:Suppress("MagicNumber")
/**
* Pandigital products
*
* We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example,
* the 5-digit number, 15234, is 1 through 5 pandigital.
*
* The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1
* through 9 pandigital.
*
* Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9
* pandigital.
*
* HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.
*
* https://projecteuler.net/problem=32
*/
fun main() {
println(isMultiplicationPandigital(multiplicand = 39, multiplier = 186, product = 7254))
println(checkPandigitalsMultiplications())
}
private fun checkPandigitalsMultiplications(): Int = buildSet {
for (i in 2 until 100) {
for (j in (i + 1) until 2_000) {
val p = i * j
if (isMultiplicationPandigital(multiplicand = i, multiplier = j, product = p)) {
add(p)
}
}
}
}.sum()
private fun isMultiplicationPandigital(multiplicand: Int, multiplier: Int, product: Int): Boolean {
check(multiplicand * multiplier == product)
var digitsFlags = 0
val digits = multiplicand.digits() + multiplier.digits() + product.digits()
if (digits.size != 9) {
return false
}
digits.forEach {
digitsFlags = digitsFlags or (1 shl (it - 1))
}
return digitsFlags == 511
}
fun Int.digits(): List<Int> = buildList {
var num = this@digits
while (num != 0) {
add(num % 10)
num /= 10
}
reverse()
}
| 0 | Kotlin | 0 | 0 | e881cadf85377374e544af0a75cb073c6b496998 | 1,600 | project-euler | MIT License |
src/Day12.kt | hijst | 572,885,261 | false | {"Kotlin": 26466} | import java.util.Queue
import java.util.LinkedList
fun main() {
data class Cell(val row: Int, val col: Int, var depth: Int = 0)
fun IntGrid.findFirstIndex(value: Int): Cell =
rows.indexOfFirst { it.contains(value) }.let {
Cell(
it ,
it.let { row -> rows[row].indexOfFirst { v -> v == value } }
)
}
fun IntGrid.getUnvisitedNeighbours(cur: Cell, visited: List<Cell>): List<Cell> = listOfNotNull(
if (!visited.contains(Cell(cur.row,cur.col - 1,0))
&& cur.col > 0
&& rows[cur.row][cur.col] - rows[cur.row][cur.col - 1] >= -1)
Cell(cur.row,cur.col - 1,0) else null,
if (!visited.contains(Cell(cur.row - 1, cur.col,0))
&& cur.row > 0
&& rows[cur.row][cur.col] - rows[cur.row - 1][cur.col] >= -1)
Cell(cur.row - 1, cur.col,0) else null,
if (!visited.contains(Cell(cur.row,cur.col + 1,0))
&& cur.col < cols.size - 1
&& rows[cur.row][cur.col] - rows[cur.row][cur.col + 1] >= -1)
Cell(cur.row,cur.col + 1,0) else null,
if (!visited.contains(Cell(cur.row + 1, cur.col,0))
&& cur.row < rows.size - 1
&& rows[cur.row][cur.col] - rows[cur.row + 1][cur.col] >= -1)
Cell(cur.row + 1, cur.col,0) else null
)
fun IntGrid.getUnvisitedNeighboursReversed(cur: Cell, visited: List<Cell>): List<Cell> = listOfNotNull(
if (!visited.contains(Cell(cur.row,cur.col - 1,0))
&& cur.col > 0
&& rows[cur.row][cur.col - 1] - rows[cur.row][cur.col] >= -1)
Cell(cur.row,cur.col - 1,0) else null,
if (!visited.contains(Cell(cur.row - 1, cur.col,0))
&& cur.row > 0
&& rows[cur.row - 1][cur.col] - rows[cur.row][cur.col] >= -1)
Cell(cur.row - 1, cur.col,0) else null,
if (!visited.contains(Cell(cur.row,cur.col + 1,0))
&& cur.col < cols.size - 1
&& rows[cur.row][cur.col + 1] - rows[cur.row][cur.col] >= -1)
Cell(cur.row,cur.col + 1,0) else null,
if (!visited.contains(Cell(cur.row + 1, cur.col,0))
&& cur.row < rows.size - 1
&& rows[cur.row + 1][cur.col] - rows[cur.row][cur.col] >= -1)
Cell(cur.row + 1, cur.col,0) else null
)
fun bfsDistanceToGoal(grid: IntGrid, start: Cell, goal: Cell): Int? {
val queue: Queue<Cell> = LinkedList()
val visited = mutableListOf(start)
var depth = 0
queue.add(start)
while (queue.size !=0) {
val cur = queue.remove()
if (cur.depth == depth) depth += 1
if (cur.row == goal.row && cur.col == goal.col) return depth - 1
for (n in grid.getUnvisitedNeighbours(cur, visited)) {
visited.add(n)
queue.add(Cell(n.row, n.col, depth))
}
}
return null
}
fun bfsDistancesToGoal(grid: IntGrid, goal: Cell): List<Int> {
val queue: Queue<Cell> = LinkedList()
val visited = mutableListOf(goal)
val distances = mutableListOf(1000)
var depth = 0
queue.add(goal)
while (queue.size !=0) {
val cur = queue.remove()
if (cur.depth == depth) depth += 1
if (grid.rows[cur.row][cur.col] == 0) distances.add(depth - 1)
for (n in grid.getUnvisitedNeighboursReversed(cur, visited)) {
visited.add(n)
queue.add(Cell(n.row, n.col, depth))
}
}
return distances
}
fun part1(input: List<String>): Int {
val grid = readGridFromChars(input)
val start = grid.findFirstIndex(-14)
val goal = grid.findFirstIndex(-28)
grid.rows[start.row][start.col] = 1
grid.rows[goal.row][goal.col] = 25
return bfsDistanceToGoal(grid, start, goal) ?: -1
}
fun part2(input: List<String>): Int {
val grid = readGridFromChars(input)
val goal = grid.findFirstIndex(-28)
grid.rows[goal.row][goal.col] = 25
val distances: List<Int> = bfsDistancesToGoal(grid, goal)
return distances.min()
}
val testInput = readInputLines("Day12_test")
check(part1(testInput) == 31)
check(part2(testInput) == 29)
val input = readInputLines("Day12_input")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 2258fd315b8933642964c3ca4848c0658174a0a5 | 4,426 | AoC-2022 | Apache License 2.0 |
ceria/02/src/main/kotlin/Solution.kt | VisionistInc | 317,503,410 | false | null | import java.io.File;
fun main(args : Array<String>) {
val input = File(args.first()).readLines()
println("Solution 1: ${solution1(input)}")
println("Solution 2: ${solution2(input)}")
}
private fun solution1(input: List<String>) :Int {
var validPasswordIndexes = mutableListOf<Int>()
input.forEachIndexed { index, line ->
val parts = line.split(" ")
val minmax = parts.get(0).split("-").map{ it.toInt() }
val range = IntRange(minmax.get(0), minmax.get(1))
val countInPasswd = parts.get(2).count{ parts.get(1).dropLast(1).contains(it) }
if (range.contains(countInPasswd)) {
validPasswordIndexes.add(index)
}
}
return validPasswordIndexes.size
}
private fun solution2(input: List<String>) :Int {
var validPasswordIndexes = mutableListOf<Int>()
input.forEachIndexed { index, line ->
val parts = line.split(" ")
val minmax = parts.get(0).split("-").map{ it.toInt() }
val range = IntRange(minmax.get(0), minmax.get(1))
if ((parts.get(2).get(range.start - 1) == parts.get(1).dropLast(1).single()).xor(
(parts.get(2).get(range.endInclusive - 1) == parts.get(1).dropLast(1).single())) ) {
validPasswordIndexes.add(index)
}
}
return validPasswordIndexes.size
} | 0 | Rust | 0 | 0 | 002734670384aa02ca122086035f45dfb2ea9949 | 1,343 | advent-of-code-2020 | MIT License |
src/Day13.kt | lsimeonov | 572,929,910 | false | {"Kotlin": 66434} | import readInput
import java.lang.Integer.max
interface JsonValue : Comparable<JsonValue> {
fun equals(other: JsonValue): Boolean
override operator fun compareTo(other: JsonValue): Int
companion object {
fun parse(input: String): JsonValue {
val trimmed = input.trim()
return if (trimmed.startsWith("[")) {
var list = mutableListOf<JsonValue>()
if (trimmed.length > 2) {
var tokenBeginning = 1
var depth = 0
for (i in 1 until trimmed.length - 1) {
when (trimmed[i]) {
'[' -> depth++
']' -> depth--
',' -> if (depth == 0) {
list.add(parse(trimmed.substring(tokenBeginning, i)))
tokenBeginning = i + 1
}
}
}
if (tokenBeginning < trimmed.length - 1) {
list.add(parse(trimmed.substring(tokenBeginning, trimmed.length - 1)))
}
}
JsonList(list)
} else {
JsonInteger.parse(trimmed)
}
}
}
}
class JsonInteger(val value: Int) : JsonValue {
override fun equals(other: JsonValue): Boolean {
if (other is JsonInteger) {
return value == other.value
}
return false
}
override fun hashCode(): Int {
return value
}
override fun compareTo(other: JsonValue): Int {
if (other is JsonInteger) {
return value.compareTo(other.value)
} else if (other is JsonList) {
val newValue = JsonList(listOf(this))
return newValue.compareTo(other)
}
throw IllegalArgumentException("Cannot compare JsonInteger to $other")
}
override fun toString(): String = value.toString()
companion object {
fun parse(input: String): JsonInteger {
return JsonInteger(input.toInt())
}
}
}
class JsonList(val list: List<JsonValue>): JsonValue {
override fun equals(other: JsonValue): Boolean {
if (other is JsonList) {
return list == other.list
}
return false
}
override fun hashCode(): Int {
return list.hashCode()
}
override fun compareTo(other: JsonValue): Int {
if (other is JsonList) {
for (i in 0 until max(list.size, other.list.size)) {
if (i == list.size) {
return -1
} else if (i == other.list.size) {
return 1
}
val cmp = list[i].compareTo(other.list[i])
if (cmp != 0) {
return cmp
}
}
return 0
} else if (other is JsonInteger) {
val newOther = JsonList(listOf(other))
return compareTo(newOther)
}
throw IllegalArgumentException("Cannot compare JsonList to $other")
}
override fun toString(): String {
return list.joinToString(", ", "[", "]")
}
}
fun solvePart1(inputPath: String): Int {
val jsonPairs = readInput(inputPath).filter { it.isNotBlank() }.chunked(2)
var indicesWithRightOrder = mutableListOf<Int>()
for (i in jsonPairs.indices) {
val jsonPair = jsonPairs[i]
val json1 = JsonValue.parse(jsonPair[0])
val json2 = JsonValue.parse(jsonPair[1])
if (json1 < json2) {
indicesWithRightOrder.add(i + 1)
}
}
println("Right ordered indices: $indicesWithRightOrder")
return indicesWithRightOrder.sum()
}
fun part1() {
println("Part 1")
solvePart1("Day13").let { result ->
println("Sample: $result")
// assert(result == 13)
}
solvePart1("Day13").let { result ->
println("Result: $result")
// assert(result == 6656)
}
}
fun solvePart2(inputPath: String): Int {
val jsonValues = readInput(inputPath).filter { it.isNotBlank() }.map { JsonValue.parse(it) }
val distressSignalOne = JsonValue.parse("[[2]]")
val distressSignalTwo = JsonValue.parse("[[6]]")
val distressSignals = listOf<JsonValue>(distressSignalOne, distressSignalTwo)
val jsonValuesAndDistressSignals = jsonValues + distressSignals
val jsonValuesAndDistressSignalsSorted = jsonValuesAndDistressSignals.sorted()
return (jsonValuesAndDistressSignalsSorted.indexOf(distressSignalOne) + 1) * (jsonValuesAndDistressSignalsSorted.indexOf(distressSignalTwo) + 1)
}
fun part2() {
println("Part 2")
solvePart2("Day13").let { result ->
println("Sample: $result")
assert(result == 140)
}
solvePart2("Day13").let { result ->
println("Result: $result")
assert(result == 19716)
}
}
fun main () {
println("Day 13")
part1()
part2()
}
| 0 | Kotlin | 0 | 0 | 9d41342f355b8ed05c56c3d7faf20f54adaa92f1 | 5,010 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day05/Day05.kt | dustinconrad | 572,737,903 | false | {"Kotlin": 100547} | package day05
import byEmptyLines
import readResourceAsBufferedReader
fun main() {
println("part 1: ${part1(readResourceAsBufferedReader("5_1.txt").readLines())}")
println("part 2: ${part2(readResourceAsBufferedReader("5_1.txt").readLines())}")
}
fun part1(input: List<String>): String {
return solve(input) { stack, instr -> stack.execute1(instr) }
}
fun part2(input: List<String>): String {
return solve(input) { stack, instr -> stack.execute2(instr) }
}
private fun solve(input: List<String>, stackFn: (SupplyStacks, CraneInstruction) -> Unit): String {
val (stack, instructions) = parseInput(input)
instructions.forEach { stackFn.invoke(stack, it) }
return stack.tops()
}
fun parseInput(input: List<String>): Pair<SupplyStacks, List<CraneInstruction>> {
val (stacks, instructions) = input.byEmptyLines()
val stack = parseSupplyStack(stacks.lines())
val instrs = parseInstructions(instructions.lines())
return stack to instrs
}
fun parseSupplyStack(input: List<String>): SupplyStacks {
val base = input.last()
.chunked(4)
val stacks = List(base.size) { StringBuilder() }
for (i in (input.size - 2) downTo 0) {
val row = input[i]
val blocks = row.chunked(4)
blocks.forEachIndexed { idx, block ->
if (block.isNotBlank()) {
stacks[idx].append(block[1])
}
}
}
return SupplyStacks(stacks)
}
fun parseInstructions(input: List<String>): List<CraneInstruction> {
return input.map { parseInstruction(it) }
}
fun parseInstruction(line: String): CraneInstruction {
val parts = line.split(" ")
return CraneInstruction(
parts[1].toInt(),
parts[3].toInt(),
parts[5].toInt()
)
}
class SupplyStacks(private val stacks: List<StringBuilder>) {
fun execute1(instr: CraneInstruction) {
execute(instr) { it.reversed() }
}
fun execute2(instr: CraneInstruction) {
execute(instr) { it }
}
private fun execute(instr: CraneInstruction, moveFn: (String) -> String) {
val src = stacks[instr.src - 1]
val move = src.substring(src.length - instr.amt)
src.setLength(src.length - instr.amt)
val dst = stacks[instr.dst - 1]
dst.append(moveFn.invoke(move))
}
fun tops(): String {
return stacks.joinToString("") { it.last().toString() }
}
}
data class CraneInstruction(val amt: Int, val src: Int, val dst: Int) | 0 | Kotlin | 0 | 0 | 1dae6d2790d7605ac3643356b207b36a34ad38be | 2,483 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/graph/dijkstra/Dijkstra.kt | Mw-majo | 499,332,924 | false | {"Kotlin": 10226} | package graph.dijkstra
class Dijkstra() {
private val ansList: List<List<List<Int>>>
private val shortestPathCosts = mutableListOf<Map<Int, Int>>()
private val edges: List<List<Int>>
private val nodeNumber: Int
private val id: IntRange
private val graphData: Array<Array<Int>>
private val nodeEdges: Map<Int, Array<Int>>
init {
val (nodeNumber, edgeNumber) = readLine()!!
.split(" ")
.slice(0..1)
.map { it.toInt() }
this.nodeNumber = nodeNumber
val edges = List(edgeNumber) {
readLine()!!
.split(" ")
.slice(0..2)
.map{ it.toInt() }
}
this.edges = edges
this.id = 0 until this.nodeNumber
this.graphData = Graph(this.nodeNumber, edges).costList
this.nodeEdges = id.associateWith { graphData[it] }
ansList = solveAllCondition()
}
// スタートとゴールのノードを受け取り、最短経路を返す関数
fun getShortestPath(startNode: Int, goalNode: Int): List<Int> {
return ansList[startNode][goalNode]
}
// スタートノードを受け取り、そこから各ノードへの最短経路を返す関数
fun getShortestPath(startNode: Int): List<List<Int>> {
return ansList[startNode]
}
// 最短経路のコストを返す
fun getShortestPathCost(startNode: Int, goalNode: Int): Int {
return shortestPathCosts[startNode][goalNode] ?: throw IllegalArgumentException("don't exist node. startNode: $startNode goalNode: $goalNode")
}
private fun solveAllCondition(): List<List<List<Int>>> {
val result = mutableListOf<List<List<Int>>>()
for (i in id) {
val tempNode = solve(i)
result.add(tempNode)
}
return result.toList()
}
private fun solve(startNodeId: Int): List<List<Int>> {
val nodeCostList = id.associateWith { if (it == startNodeId) 0 else Int.MAX_VALUE }.toMutableMap()
val nodeIsVisited = id.associateWith { false }.toMutableMap()
val nodeParent: MutableMap<Int, Int?> = id.associateWith { null }.toMutableMap()
while (nodeIsVisited.any { !it.value }) {
val closestNode = getMinCostNode(nodeCostList, nodeIsVisited)
val closestNodeCost =
nodeCostList[closestNode] ?: throw java.lang.NullPointerException("closest nodeCost Nullpo desuwa")
val checkingEdges =
nodeEdges[closestNode] ?: throw java.lang.NullPointerException("nodeEdge Nullpo desuwa")
checkingEdges.forEachIndexed { idx, cost ->
//println("$cost $idx")
if (cost > 0) {
val targetCost = nodeCostList[idx] ?: throw java.lang.NullPointerException("nodeCost Nullpo desuwa")
if (targetCost > cost + closestNodeCost) {
nodeCostList[idx] = cost + closestNodeCost
nodeParent[idx] = closestNode
}
}
}
nodeIsVisited[closestNode] = true
}
val parentsList = mutableListOf<List<Int>>()
for (i in id) {
var parent: Int? = i
val list = mutableListOf<Int>(parent!!)
while (true) {
parent = nodeParent[parent]
if (parent == null) break
list.add(parent)
}
parentsList.add(list.toList().reversed())
}
shortestPathCosts.add(nodeCostList)
return parentsList.toList()
}
private fun getMinCostNode(nodeCostList: MutableMap<Int, Int>, nodeIsVisited: MutableMap<Int, Boolean>): Int { // 最小コストノードのID
val unvisitedNode = nodeIsVisited.filter { !it.value }
val minCostNode = unvisitedNode
.map { it.key }
.associateWith { nodeCostList[it] }
.minByOrNull { it.value ?: Int.MAX_VALUE }
?.key
return minCostNode ?: throw java.lang.NullPointerException("min cost is null-pointer desuwa")
}
} | 0 | Kotlin | 0 | 0 | 879af69c9e7d03517ee5b81f3d0ae1bd188ec467 | 4,139 | dijkstara | Apache License 2.0 |
src/main/kotlin/days/Day07.kt | julia-kim | 435,257,054 | false | {"Kotlin": 15771} | package days
import readInput
import kotlin.math.absoluteValue
fun main() {
fun part1(input: List<String>): Int {
val horizontalPositions = input[0].split(",").map { it.toInt() }
val outcomes: MutableList<Int> = mutableListOf()
horizontalPositions.forEach { pos ->
var totalFuel = 0
horizontalPositions.forEach {
val diff = (it - pos).absoluteValue
totalFuel += diff
}
outcomes.add(totalFuel)
}
return outcomes.minOf { it }
}
fun part2(input: List<String>): Int {
val horizontalPositions = input[0].split(",").map { it.toInt() }
val outcomes: MutableList<Int> = mutableListOf()
(0..horizontalPositions.maxOf { it }).forEach { pos ->
var totalFuel = 0
horizontalPositions.forEach {
var fuelCost = 0
var diff = (it - pos).absoluteValue
while (diff > 0) {
fuelCost += diff
diff--
}
totalFuel += fuelCost
}
outcomes.add(totalFuel)
}
return outcomes.minOf { it }
}
val testInput = readInput("Day07_test")
check(part1(testInput) == 37)
check(part2(testInput) == 168)
val input = readInput("Day07")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 5febe0d5b9464738f9a7523c0e1d21bd992b9302 | 1,410 | advent-of-code-2021 | Apache License 2.0 |
2020/src/year2020/day03/Day03.kt | eburke56 | 436,742,568 | false | {"Kotlin": 61133} | package year2020.day03
import util.readAllLines
private fun findTrees(dx: Int, dy: Int): Int {
val input = readAllLines("input.txt")
val height = input.size
val width = input[0].length
val matrix: Array<MutableList<Char>> = Array(height) { mutableListOf<Char>() }
for (i in 0 until height) {
input[i].forEach { char ->
matrix[i].add(char)
}
}
matrix.forEach {
it.forEach { char ->
print(char)
}
println()
}
var trees = 0
var x = 0
var y = 0
while (y < height) {
if (matrix[y][x] == '#') {
trees++
}
x = (x + dx) % width
y += dy
}
return trees
}
fun main() {
val trees = findTrees(3, 1)
println(trees)
val mult = findTrees(1, 1) *
findTrees(3, 1) *
findTrees(5, 1) *
findTrees(7, 1) *
findTrees(1, 2)
println(mult)
}
| 0 | Kotlin | 0 | 0 | 24ae0848d3ede32c9c4d8a4bf643bf67325a718e | 936 | adventofcode | MIT License |
advent-of-code2015/src/main/kotlin/utils.kt | REDNBLACK | 128,669,137 | false | null | import java.math.BigInteger
import java.security.MessageDigest
fun parseInput(file: String): String {
return Thread.currentThread()
.contextClassLoader
.getResourceAsStream(file)
.bufferedReader()
.use { it.readText() }
.trim()
}
fun Iterable<Int>.mul() = reduce { a, b -> a * b }
fun Iterable<Long>.mul() = reduce { a, b -> a * b }
fun <T : Any> List<T>.permutations() : Sequence<List<T>> = if (size == 1) sequenceOf(this) else {
val iterator = iterator()
var head = iterator.next()
var permutations = (this - head).permutations().iterator()
fun nextPermutation(): List<T>? = if (permutations.hasNext()) permutations.next() + head else {
if (iterator.hasNext()) {
head = iterator.next()
permutations = (this - head).permutations().iterator()
nextPermutation()
} else null
}
generateSequence { nextPermutation() }
}
fun <T : Any> List<T>.combinations(n: Int) : Sequence<List<T>> = if (n == 0) sequenceOf(emptyList()) else {
flatMapTails { subList -> subList.tail().combinations(n - 1).map { it + subList.first() } }
}
private fun <T> List<T>.flatMapTails(f: (List<T>) -> (Sequence<List<T>>)): Sequence<List<T>> = if (isEmpty()) emptySequence() else {
f(this) + this.tail().flatMapTails(f)
}
fun <T> List<T>.tail(): List<T> = drop(1)
fun <T> List<T>.split(size: Int) = (0..this.size - size)
.fold(mutableListOf<List<T>>(), { result, i ->
result.add(subList(i, i + size))
result
})
inline fun <reified INNER> array2d(sizeOuter: Int, sizeInner: Int, noinline innerInit: (Int) -> INNER): Array<Array<INNER>>
= Array(sizeOuter) { Array(sizeInner, innerInit) }
fun String.chunk(size: Int) = (0..length - size).map { i -> substring(i, i + size) }
fun String.splitToLines() = trim().split("\n").map(String::trim).filter(String::isNotEmpty)
fun String.toMD5() = MessageDigest.getInstance("MD5").digest(toByteArray())
fun String.indexOfAll(needle: String): List<Int> {
val result = mutableListOf<Int>()
var index = indexOf(needle)
while (index >= 0) {
if (index >= 0) result.add(index)
index = indexOf(needle, index + 1)
}
return result
}
fun ByteArray.toHex() = String.format("%0" + (size shl 1) + "X", BigInteger(1, this))
| 0 | Kotlin | 0 | 0 | e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7 | 2,354 | courses | MIT License |
src/main/kotlin/day20.kt | gautemo | 725,273,259 | false | {"Kotlin": 79259} | import shared.*
fun main() {
val input = Input.day(20)
println(day20A(input))
println(day20B(input))
}
fun day20A(input: Input): Int {
val modules = createModules(input)
val broadcaster = modules.first { it is Broadcaster }
repeat(1000) {
broadcaster.pulse(false, "aptly")
while (modules.any { it.buffer.isNotEmpty() }) {
modules.forEach { it.triggerPulse() }
}
}
return countHigh * countLow
}
fun day20B(input: Input): Long {
val modules = createModules(input)
val broadcaster = modules.first { it is Broadcaster }
val conjuctionTalkingToOutput = modules.first {
module -> module.connected.any { it is Output }
} as Conjunction
val requiredRemembers = conjuctionTalkingToOutput.remembers
.map { it.key }
.associateWith { null as Long? }
.toMutableMap()
var count = 0L
while (true) {
broadcaster.pulse(false, "aptly")
count++
while (modules.any { it.buffer.isNotEmpty() }) {
modules.forEach { it.triggerPulse() }
conjuctionTalkingToOutput.remembers.forEach {
if(it.value && requiredRemembers[it.key] == null) requiredRemembers[it.key] = count
}
}
if(requiredRemembers.all { it.value != null }) {
return requiredRemembers.toList().fold(1) { acc, pair ->
lcm(acc, pair.second!!)
}
}
}
}
var countHigh = 0
var countLow = 0
private sealed class Module(val name: String) {
val buffer = mutableListOf<Pair<Boolean, String>>()
var connected = emptyList<Module>()
set(value) {
field = value
value.forEach {
if(it is Conjunction) {
it.register(name)
}
}
}
fun pulse(high: Boolean, from: String) {
if(high) countHigh++ else countLow++
buffer.add(high to from)
}
fun triggerPulse() {
val pulse = buffer.removeFirstOrNull()
if(pulse != null) {
when (this) {
is FlipFlop -> {
if(!pulse.first){
on = !on
connected.forEach { it.pulse(on, name) }
}
}
is Conjunction -> {
remembers[pulse.second] = pulse.first
connected.forEach { c -> c.pulse(remembers.any { !it.value }, name) }
}
is Broadcaster -> {
connected.forEach { it.pulse(pulse.first, name) }
}
is Output -> {}
}
}
}
}
private class FlipFlop(name: String) : Module(name) {
var on = false
}
private class Conjunction(name: String) : Module(name) {
var remembers = mutableMapOf<String, Boolean>()
fun register(connectedFrom: String) {
remembers[connectedFrom] = false
}
}
private class Broadcaster(name: String) : Module(name)
private class Output(name: String): Module(name)
private fun createModules(input: Input): List<Module> {
val output = Output("output")
val modules = input.lines.map {
val name = it.split(' ')[0].drop(1)
when(it[0]) {
'b' -> Broadcaster(name)
'%' -> FlipFlop(name)
'&' -> Conjunction(name)
else -> throw Exception()
}
}
input.lines.forEach { line ->
val name = line.split(' ')[0].drop(1)
val connected = line.split("->")[1].split(',').map(String::trim)
modules.first { it.name == name }.connected = connected.map { c -> modules.find { it.name == c } ?: output }
}
return modules
} | 0 | Kotlin | 0 | 0 | 6862b6d7429b09f2a1d29aaf3c0cd544b779ed25 | 3,729 | AdventOfCode2023 | MIT License |
src/Day01.kt | orirabi | 574,124,632 | false | {"Kotlin": 14153} | fun main() {
fun getMaxCalories(input: List<String>): Int {
var highest = 1 to 0
var current = 1
var currentSum = 0
input.forEach {
if (it.isBlank()) {
if (currentSum > highest.second) {
highest = current to currentSum
}
current++
currentSum = 0
} else {
currentSum += it.toInt()
}
}
return highest.second
}
fun getMaxCaloriesByThree(input: List<String>): Int {
val calorieCounts = mutableListOf<Int>()
var currentSum = 0
input.forEach {
if (it.isBlank()) {
calorieCounts.add(currentSum)
currentSum = 0
} else {
currentSum += it.toInt()
}
}
return calorieCounts.asSequence().sortedDescending().take(3).sum()
}
val calorieList = readInput("Day01")
println(getMaxCalories(calorieList))
println(getMaxCaloriesByThree(calorieList))
}
| 0 | Kotlin | 0 | 0 | 41cb10eac3234ae77ed7f3c7a1f39c2f9d8c777a | 1,068 | AoC-2022 | Apache License 2.0 |
src/main/kotlin/se/saidaspen/aoc/aoc2015/Day24.kt | saidaspen | 354,930,478 | false | {"Kotlin": 301372, "CSS": 530} | package se.saidaspen.aoc.aoc2015
import se.saidaspen.aoc.util.Day
import se.saidaspen.aoc.util.ints
import se.saidaspen.aoc.util.words
import java.util.*
fun main() {
Day24.run()
}
object Day24 : Day(2015, 24) {
inline fun <reified T> combinations(arr: Array<T>, m: Int) = sequence {
val n = arr.size
val result = Array(m) { arr[0] }
val stack = LinkedList<Int>()
stack.push(0)
while (stack.isNotEmpty()) {
var resIndex = stack.size - 1;
var arrIndex = stack.pop()
while (arrIndex < n) {
result[resIndex++] = arr[arrIndex++]
stack.push(arrIndex)
if (resIndex == m) {
yield(result.toList())
break
}
}
}
}
override fun part1(): Any {
val inputs = ints(input).toTypedArray()
val target = inputs.sum() / 3
for (length in 2..inputs.size) {
val qe = combinations(inputs, length).filter { it.sum() == target}.map { it.map{ v -> v.toLong()}.reduce { acc, i -> acc*i } }.minOrNull()
if (qe != null) return qe
}
return ""
}
override fun part2(): Any {
val inputs = ints(input).toTypedArray()
val target = inputs.sum() / 4
for (length in 2..inputs.size) {
val qe = combinations(inputs, length).filter { it.sum() == target}.map { it.map{ v -> v.toLong()}.reduce { acc, i -> acc*i } }.minOrNull()
if (qe != null) return qe
}
return ""
}
}
| 0 | Kotlin | 0 | 1 | be120257fbce5eda9b51d3d7b63b121824c6e877 | 1,593 | adventofkotlin | MIT License |
src/main/kotlin/com/sk/topicWise/tree/124. Binary Tree Maximum Path Sum.kt | sandeep549 | 262,513,267 | false | {"Kotlin": 530613} | package com.sk.topicWise.tree
class Solution124 {
/**
* Traverse the tree and while backtrack, maintain mas_so_far at every node, return max passing through
* current node. We need to return values for first 3 cases from below, 4th case will be considered
* in max_so_far
*
* For each node there can be four ways that the max path goes through the node:
* 1. Node only
* 2. Max path through Left Child + Node
* 3. Max path through Right Child + Node
* 4. Max path through Left Child + Node + Max path through Right Child
*/
fun maxPathSum(root: TreeNode?): Int {
return dfs(root).max()
}
private fun dfs(root: TreeNode?): IntArray {
if (root == null) return intArrayOf(-1001, -1001)
val larr = dfs(root.left)
val rarr = dfs(root.right)
// max path till now
val max_so_far = larr[1] // max so far from left side
.coerceAtLeast(larr[0] + root.`val`) // max going through curr + left
.coerceAtLeast(rarr[1]) // max so far from right side
.coerceAtLeast(rarr[0] + root.`val`) // max going through curr + right
.coerceAtLeast(root.`val`) // only this node
.coerceAtLeast(larr[0] + root.`val` + rarr[0]) // left + node + right
val max_passing_through = root.`val`
.coerceAtLeast(larr[0] + root.`val`)
.coerceAtLeast(rarr[0] + root.`val`)
return intArrayOf(max_passing_through, max_so_far)
}
}
| 1 | Kotlin | 0 | 0 | cf357cdaaab2609de64a0e8ee9d9b5168c69ac12 | 1,511 | leetcode-kotlin | Apache License 2.0 |
Fermat_numbers/Kotlin/src/FermatNumbers.kt | ncoe | 108,064,933 | false | {"D": 425100, "Java": 399306, "Visual Basic .NET": 343987, "C++": 328611, "C#": 289790, "C": 216950, "Kotlin": 162468, "Modula-2": 148295, "Groovy": 146721, "Lua": 139015, "Ruby": 84703, "LLVM": 58530, "Python": 46744, "Scala": 43213, "F#": 21133, "Perl": 13407, "JavaScript": 6729, "CSS": 453, "HTML": 409} | import java.math.BigInteger
import kotlin.math.pow
fun main() {
println("First 10 Fermat numbers:")
for (i in 0..9) {
println("F[$i] = ${fermat(i)}")
}
println()
println("First 12 Fermat numbers factored:")
for (i in 0..12) {
println("F[$i] = ${getString(getFactors(i, fermat(i)))}")
}
}
private fun getString(factors: List<BigInteger>): String {
return if (factors.size == 1) {
"${factors[0]} (PRIME)"
} else factors.map { it.toString() }
.joinToString(" * ") {
if (it.startsWith("-"))
"(C" + it.replace("-", "") + ")"
else it
}
}
private val COMPOSITE = mutableMapOf(
9 to "5529",
10 to "6078",
11 to "1037",
12 to "5488",
13 to "2884"
)
private fun getFactors(fermatIndex: Int, n: BigInteger): List<BigInteger> {
var n2 = n
val factors: MutableList<BigInteger> = ArrayList()
var factor: BigInteger
while (true) {
if (n2.isProbablePrime(100)) {
factors.add(n2)
break
} else {
if (COMPOSITE.containsKey(fermatIndex)) {
val stop = COMPOSITE[fermatIndex]
if (n2.toString().startsWith(stop!!)) {
factors.add(BigInteger("-" + n2.toString().length))
break
}
}
//factor = pollardRho(n)
factor = pollardRhoFast(n)
n2 = if (factor.compareTo(BigInteger.ZERO) == 0) {
factors.add(n2)
break
} else {
factors.add(factor)
n2.divide(factor)
}
}
}
return factors
}
private val TWO = BigInteger.valueOf(2)
private fun fermat(n: Int): BigInteger {
return TWO.pow(2.0.pow(n.toDouble()).toInt()).add(BigInteger.ONE)
}
// See: https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm
@Suppress("unused")
private fun pollardRho(n: BigInteger): BigInteger {
var x = BigInteger.valueOf(2)
var y = BigInteger.valueOf(2)
var d = BigInteger.ONE
while (d.compareTo(BigInteger.ONE) == 0) {
x = pollardRhoG(x, n)
y = pollardRhoG(pollardRhoG(y, n), n)
d = (x - y).abs().gcd(n)
}
return if (d.compareTo(n) == 0) {
BigInteger.ZERO
} else d
}
// Includes Speed Up of 100 multiples and 1 GCD, instead of 100 multiples and 100 GCDs.
// See Variants section of Wikipedia article.
// Testing F[8] = 1238926361552897 * Prime
// This variant = 32 sec.
// Standard algorithm = 107 sec.
private fun pollardRhoFast(n: BigInteger): BigInteger {
val start = System.currentTimeMillis()
var x = BigInteger.valueOf(2)
var y = BigInteger.valueOf(2)
var d: BigInteger
var count = 0
var z = BigInteger.ONE
while (true) {
x = pollardRhoG(x, n)
y = pollardRhoG(pollardRhoG(y, n), n)
d = (x - y).abs()
z = (z * d).mod(n)
count++
if (count == 100) {
d = z.gcd(n)
if (d.compareTo(BigInteger.ONE) != 0) {
break
}
z = BigInteger.ONE
count = 0
}
}
val end = System.currentTimeMillis()
println(" Pollard rho try factor $n elapsed time = ${end - start} ms (factor = $d).")
return if (d.compareTo(n) == 0) {
BigInteger.ZERO
} else d
}
private fun pollardRhoG(x: BigInteger, n: BigInteger): BigInteger {
return (x * x + BigInteger.ONE).mod(n)
}
| 0 | D | 0 | 4 | c2a9f154a5ae77eea2b34bbe5e0cc2248333e421 | 3,505 | rosetta | MIT License |
generator/api/src/commonMain/kotlin/com/github/jcornaz/kwik/generator/api/GeneratorCombination.kt | mmiikkkkaa | 391,233,716 | true | {"Kotlin": 137409} | package com.github.jcornaz.kwik.generator.api
import kotlin.random.Random
/**
* Returns a generator of values built from the elements of `this` generator and the [other] generator
* using the provided [transform] function applied to each pair of elements.
*/
fun <A, B, R> Generator<A>.combineWith(
other: Generator<B>,
transform: (A, B) -> R
): Generator<R> =
Generator.combine(this, other, transform)
/**
* Returns a generator of values built from the elements of `this` generator and the [other] generator
*/
fun <A, B> Generator<A>.combineWith(
other: Generator<B>
): Generator<Pair<A, B>> =
Generator.combine(this, other, ::Pair)
/**
* Returns a generator of combining the elements of [generator1] and [generator2]
* using the provided [transform] function applied to each pair of elements.
*/
fun <A, B, R> Generator.Companion.combine(
generator1: Generator<A>,
generator2: Generator<B>,
transform: (A, B) -> R
): Generator<R> =
CombinedGenerators(generator1, generator2, transform)
/**
* Returns a generator of combining the elements of [generator1] and [generator2]
*/
fun <A, B> Generator.Companion.combine(
generator1: Generator<A>,
generator2: Generator<B>
): Generator<Pair<A, B>> =
combine(generator1, generator2, ::Pair)
private class CombinedGenerators<A, B, R>(
private val generator1: Generator<A>,
private val generator2: Generator<B>,
private val transform: (A, B) -> R
) : Generator<R> {
override fun generate(random: Random): R =
transform(generator1.generate(random), generator2.generate(random))
}
/**
* Returns a generator merging values of with the [other] generator
*/
operator fun <T> Generator<T>.plus(other: Generator<T>): Generator<T> =
MergedGenerators(this, other)
private class MergedGenerators<T>(
private val generator1: Generator<T>,
private val generator2: Generator<T>
) : Generator<T> {
override fun generate(random: Random): T =
if (random.nextBoolean()) generator1.generate(random) else generator2.generate(random)
}
/**
* Returns a generator that randomly pick a value from the given list of the generator according to their respective weights.
*
* Example:
* ```
* // This generator has 3/4 chances to generate a positive value and 1/4 chance to generate a negative value
* val num = Generator.frequency(listOf(
* 3.0 to Generator.positiveInts(),
* 1.0 to Generator.negativeInts()
* ))
* ```
*
* @throws IllegalArgumentException if [weightedGenerators] is empty, contains negative weights or the sum of the weight is zero
*/
fun <T> Generator.Companion.frequency(
weightedGenerators: Iterable<Pair<Double, Generator<T>>>
): Generator<T> {
val list = weightedGenerators.asSequence()
.onEach { (weight, _) -> require(weight >= 0.0) { "Negative weight(s) found in frequency input" } }
.filter { (weight, _) -> weight > 0.0 }
.sortedByDescending { (weight, _) -> weight }
.toList()
return when (list.size) {
0 -> throw IllegalArgumentException("No generator (with weight > 0) to use for frequency-based generation")
1 -> list.single().second
2 -> list.let { (source1, source2) ->
DualGenerator(source1.second, source2.second, source1.first / (source1.first + source2.first))
}
else -> FrequencyGenerator(list)
}
}
/**
* Returns a generator that randomly pick a value from the given list of the generator according to their respective weights.
*
* Example:
* ```
* // This generator has 3/4 chances to generate a positive value and 1/4 chance to generate a negative value
* val num = Generator.frequency(
* 3.0 to Generator.positiveInts(),
* 1.0 to Generator.negativeInts()
* )
* ```
*
* @throws IllegalArgumentException if [weightedGenerators] is empty, contains negative weights or the sum of the weight is zero
*/
fun <T> Generator.Companion.frequency(
vararg weightedGenerators: Pair<Double, Generator<T>>
): Generator<T> = frequency(weightedGenerators.asList())
private class DualGenerator<T>(
private val source1: Generator<T>,
private val source2: Generator<T>,
private val source1Probability: Double
) : Generator<T> {
override fun generate(random: Random): T =
if (random.nextDouble() < source1Probability) source1.generate(random) else source2.generate(random)
}
private class FrequencyGenerator<T>(private val weightedGenerators: List<Pair<Double, Generator<T>>>) : Generator<T> {
val max = weightedGenerators.sumByDouble { (weight, _) -> weight }
init {
require(max > 0.0) { "The sum of the weights is zero" }
}
override fun generate(random: Random): T {
var value = random.nextDouble(max)
weightedGenerators.forEach { (weight, generator) ->
if (value < weight) return generator.generate(random)
value -= weight
}
return weightedGenerators.random(random).second.generate(random)
}
}
| 0 | Kotlin | 0 | 0 | b25753bac300e410cff143bf079b55bd79d193dd | 5,013 | kwik | Apache License 2.0 |
kotlin/0778-swim-in-rising-water.kt | neetcode-gh | 331,360,188 | false | {"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750} | class Solution {
fun swimInWater(grid: Array<IntArray>): Int {
val visited = Array<BooleanArray>(grid.size){ BooleanArray(grid[0].size) }
val minHeap = PriorityQueue<IntArray>{ a: IntArray, b: IntArray -> a[0] - b[0] } //[height, r, c]
val directions = arrayOf(intArrayOf(1,-1,0,0),intArrayOf(0,0,1,-1))
minHeap.add(intArrayOf(grid[0][0],0,0)) //startpos
while(!minHeap.isEmpty()){
val (h,r,c) = minHeap.poll()
visited[r][c] = true
if(r == grid.size-1 && c == grid[0].size-1)
return h
for(i in 0..3){
val nextR = r + directions[0][i]
val nextC = c + directions[1][i]
if(isValid(grid,visited,nextR, nextC))
minHeap.add(intArrayOf(maxOf(h,grid[nextR][nextC]),nextR,nextC))
}
}
return -1
}
private fun isValid(
grid: Array<IntArray>,
visited: Array<BooleanArray>,
r: Int,
c: Int
) = r >= 0 && c >= 0 && r < grid.size && c < grid[0].size && visited[r][c] == false
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 1,110 | leetcode | MIT License |
src/main/aoc2016/Day3.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2016
class Day3(private val input: List<String>) {
private data class Shape(val x: Int, val y: Int, val z: Int)
private fun process(input: List<String>): List<Shape> {
val shapes = mutableListOf<Shape>()
input.forEach { line ->
val entry = line.trim().split(" ").filter { it != "" }.sortedWith(compareBy { it.toInt() })
shapes.add(Shape(entry[0].trim().toInt(),
entry[1].trim().toInt(),
entry[2].trim().toInt())
)
}
return shapes
}
private fun process2(input: List<String>): List<Shape> {
val shapes = mutableListOf<Shape>()
var i = 0
while (i < input.size) {
val row1 = input[i++].trim().split(" ").filter { it != "" }
val row2 = input[i++].trim().split(" ").filter { it != "" }
val row3 = input[i++].trim().split(" ").filter { it != "" }
for (j in 0..2) {
val shape = listOf(row1[j], row2[j], row3[j]).sortedWith(compareBy { it.toInt() })
shapes.add(Shape(shape[0].toInt(), shape[1].toInt(), shape[2].toInt()))
}
}
return shapes
}
private fun solve(input: List<Shape>): Int {
return input.count { it.x + it.y > it.z }
}
fun solvePart1(): Int {
return solve(process(input))
}
fun solvePart2(): Int {
return solve(process2(input))
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 1,461 | aoc | MIT License |
src/Day08.kt | k3vonk | 573,555,443 | false | {"Kotlin": 17347} | fun main() {
fun <E: Any> printPrettyGrid(grid: MutableList<MutableList<E>>) {
println()
grid.forEach {
println(it)
}
}
fun parseInputIntoGrid(input: List<String>, grid: MutableList<MutableList<Char>>) {
input.forEach {
grid.add(it.toMutableList())
}
}
fun generateVisibilityGrid(grid: MutableList<MutableList<Char>>): MutableList<MutableList<Int>> {
val rows = grid.size
val columns = grid[0].size
return MutableList(rows) { MutableList(columns) { 0 } } // 0 = invisible
}
fun cleanUpViewScoreGrid(treeGrid: MutableList<MutableList<Char>>, grid: MutableList<MutableList<Int>>) {
for (i in grid.indices) {
// rows
grid[0][i] = 0
grid[grid.lastIndex][i] = 0 // last row
// columns
grid[i][0] = 0 // first column
grid[i][grid[0].lastIndex] = 0 // last column
}
val max = grid.maxBy { it.max() }.max()
for (i in grid.indices) {
for (j in grid[0].indices) {
if (grid[i][j] < max) grid[i][j] = 0
else grid[i][j] = treeGrid[i][j].digitToInt()
}
}
}
fun countVisibleTrees(visibilityGrid: MutableList<MutableList<Int>>): Int {
return visibilityGrid.sumOf { li ->
li.count { it == 1 }
}
}
fun part1(treeGrid: MutableList<MutableList<Char>>, pointGrid: MutableList<MutableList<Int>>): Int {
val visibilityGrid = generateVisibilityGrid(treeGrid)
for (rowIndex in 0 until treeGrid.size) {
var leftSide = 0
var rightSide = 0
for (columnIndex in 0 until treeGrid[0].size) {
if (treeGrid[rowIndex][columnIndex].code > leftSide) {
visibilityGrid[rowIndex][columnIndex] = 1
leftSide = treeGrid[rowIndex][columnIndex].code
pointGrid[rowIndex][columnIndex] += 1
}
val reverseColumnIndex = treeGrid[0].size - 1 - columnIndex
if (treeGrid[rowIndex][reverseColumnIndex].code > rightSide) {
visibilityGrid[rowIndex][reverseColumnIndex] = 1
rightSide = treeGrid[rowIndex][reverseColumnIndex].code
pointGrid[rowIndex][reverseColumnIndex] += 1
}
}
}
for (columnIndex in 0 until treeGrid[0].size) {
var topSide = 0
var bottomSide = 0
for (rowIndex in 0 until treeGrid.size) {
// view from top
if (treeGrid[rowIndex][columnIndex].code > topSide) {
visibilityGrid[rowIndex][columnIndex] = 1
topSide = treeGrid[rowIndex][columnIndex].code
pointGrid[rowIndex][columnIndex] += 1
}
// view from bottom
val reverseRow = treeGrid.size - 1 - rowIndex
if(treeGrid[reverseRow][columnIndex].code > bottomSide) {
visibilityGrid[reverseRow][columnIndex] = 1
bottomSide = treeGrid[reverseRow][columnIndex].code
pointGrid[reverseRow][columnIndex] += 1
}
}
}
return countVisibleTrees(visibilityGrid)
}
fun part2(treeGrid: MutableList<MutableList<Char>>, pointGrid: MutableList<MutableList<Int>>): Int {
cleanUpViewScoreGrid(treeGrid, pointGrid)
// val visibilityGrid = generateVisibilityGrid(treeGrid)
for (rowIndex in 0 until pointGrid.size) {
for (columnIndex in 0 until pointGrid[0].size) {
// if (treeGrid[rowIndex][columnIndex].code > leftSide) {
// pointGrid[rowIndex][columnIndex] = 1
// leftSide = treeGrid[rowIndex][columnIndex].code
// }
// val reverseColumnIndex = treeGrid[0].size - 1 - columnIndex
// if (treeGrid[rowIndex][reverseColumnIndex].code > rightSide) {
// pointGrid[rowIndex][reverseColumnIndex] = 1
// rightSide = treeGrid[rowIndex][reverseColumnIndex].code
// }
}
}
//
// for (columnIndex in 0 until treeGrid[0].size) {
// var topSide = 0
// var bottomSide = 0
// for (rowIndex in 0 until treeGrid.size) {
// // view from top
// if (treeGrid[rowIndex][columnIndex].code > topSide) {
// pointGrid[rowIndex][columnIndex] = 1
// topSide = treeGrid[rowIndex][columnIndex].code
// }
//
// // view from bottom
// val reverseRow = treeGrid.size - 1 - rowIndex
// if(treeGrid[reverseRow][columnIndex].code > bottomSide) {
// pointGrid[reverseRow][columnIndex] = 1
// bottomSide = treeGrid[reverseRow][columnIndex].code
// }
// }
// }
printPrettyGrid(pointGrid)
return countVisibleTrees(pointGrid)
}
val input = readInput("Day08_mock")
val treeGrid = mutableListOf<MutableList<Char>>()
parseInputIntoGrid(input, treeGrid)
printPrettyGrid(treeGrid)
val viewPoint = generateVisibilityGrid(treeGrid)
println(part1(treeGrid, viewPoint))
println(part2(treeGrid, viewPoint))
} | 0 | Kotlin | 0 | 1 | 68a42c5b8d67442524b40c0ce2e132898683da61 | 5,473 | AOC-2022-in-Kotlin | Apache License 2.0 |
src/main/kotlin/days/Day12.kt | andilau | 433,504,283 | false | {"Kotlin": 137815} | package days
@AdventOfCodePuzzle(
name = "Passage Pathing",
url = "https://adventofcode.com/2021/day/12",
date = Date(day = 12, year = 2021)
)
class Day12(val input: List<String>) : Puzzle {
private val links = input.parseInput()
override fun partOne() =
links.generatePaths { path, next -> next.isBigCave() || next !in path }.size
override fun partTwo() =
links.generatePaths { path, next ->
next.isBigCave() || next !in path ||
path.filter { it.isSmallCave() }.groupBy { it }
.filterValues { it.size == 2 }
.isEmpty()
}
.size
private inline fun Map<String, List<String>>.generatePaths(
visitPredicate: (List<String>, String) -> Boolean
): Set<List<String>> {
var paths: Set<List<String>> = this.getValue(START).map { listOf(START, it) }.toSet()
while (paths
.map { path -> path.last() }
.any { it != END }
) {
paths =
paths.filter { path -> path.last() == END }.toSet() +
paths
.filter { path -> path.last() != END }
.flatMap { path ->
val last = path.last()
this.getValue(last).mapNotNull { next ->
if (visitPredicate.invoke(path, next))
path + next
else
null
}
}
}
return paths.toSet()
}
private fun List<String>.parseInput(): Map<String, List<String>> =
flatMap { line ->
val (from, to) = line.split('-')
buildList {
if (from != END && to != START) add(from to to)
if (from != START && to != END) add(to to from)
}
}.groupBy(keySelector = { it.first }, valueTransform = { it.second })
companion object {
const val START = "start"
const val END = "end"
}
private fun String.isSmallCave() = first().isLowerCase()
private fun String.isBigCave() = first().isUpperCase()
} | 0 | Kotlin | 0 | 0 | b3f06a73e7d9d207ee3051879b83e92b049a0304 | 2,316 | advent-of-code-2021 | Creative Commons Zero v1.0 Universal |
openrndr-math/src/commonMain/kotlin/org/openrndr/math/Bezier.kt | openrndr | 122,222,767 | false | {"Kotlin": 2343473, "ANTLR": 9333, "GLSL": 2677, "CSS": 87} | package org.openrndr.math
import kotlin.math.sqrt
/* quadratic bezier */
fun bezier(x0: Double, c0: Double, x1: Double, t: Double): Double {
val it = 1.0 - t
val it2 = it * it
val t2 = t * t
return it2 * x0 + 2.0 * it * t * c0 + t2 * x1
}
fun derivative(x0: Double, c0: Double, x1: Double, t: Double): Double {
val it = 1.0 - t
return 2.0 * it * (c0 - x0) + 2.0 * t * (x1 - c0)
}
fun derivative(x0: Vector2, c0: Vector2, x1: Vector2, t: Double): Vector2 {
val it = 1.0 - t
return Vector2(2 * it * (c0.x - x0.x) + 2 * t * (x1.x - c0.x), 2 * it * (c0.y - x0.y) + 2 * t * (x1.y - c0.y))
}
/**
* Similar to [derivative] but handles cases in which [p0] and [p1] coincide.
*/
fun safeDerivative(p0: Vector2, c0: Vector2, p1: Vector2, t: Double): Vector2 {
val epsilon = 10E-6
var u = t
val d10 = c0 - p0
val d21 = c0 - p1
if (u < epsilon && d10.squaredLength < epsilon) {
u = epsilon
}
if (u > (1.0 - epsilon) && d21.squaredLength < epsilon) {
u = 1.0 - epsilon
}
val iu = 1.0 - u
return Vector2(2 * iu * (c0.x - p0.x) + 2 * u * (p1.x - c0.x), 2 * iu * (c0.y - p0.y) + 2 * u * (p1.y - c0.y))
}
fun derivative(x0: Vector3, c0: Vector3, x1: Vector3, t: Double): Vector3 {
val it = 1.0 - t
return Vector3(2 * it * (c0.x - x0.x) + 2 * t * (x1.x - c0.x),
2 * it * (c0.y - x0.y) + 2 * t * (x1.y - c0.y),
2 * it * (c0.z - x0.z) + 2 * t * (x1.z - c0.z)
)
}
fun roots(p: List<Double>): List<Double> {
//https://github.com/Pomax/bezierjs/blob/gh-pages/lib/utils.js
if (p.size == 3) {
val a = p[0]
val b = p[1]
val c = p[2]
val d = a - 2 * b + c
if (d != 0.0) {
val m1 = -sqrt(b * b - a * c)
val m2 = -a + b
val v1 = -(m1 + m2) / d
val v2 = -(-m1 + m2) / d
return listOf(v1, v2)
} else if (b != c && d == 0.0) {
return listOf((2 * b * c) / (2 * (b - c)))
}
return emptyList()
} else if (p.size == 2) {
val a = p[0]
val b = p[1]
return if (a != b) {
listOf(a / (a - b))
} else {
emptyList()
}
}
return emptyList()
}
fun derivative(p0: Vector3, p1: Vector3, p2: Vector3, p3: Vector3, t: Double): Vector3 {
val it = 1.0 - t
return p1.minus(p0).times(3.0 * it * it).plus(p2.minus(p1).times(6.0 * it * t)).plus(p3.minus(p2).times(3.0 * t * t))
}
fun derivative(p0: Vector2, p1: Vector2, p2: Vector2, p3: Vector2, t: Double): Vector2 {
val it = 1.0 - t
return p1.minus(p0).times(3.0 * it * it).plus(p2.minus(p1).times(6.0 * it * t)).plus(p3.minus(p2).times(3.0 * t * t))
}
/**
* Similar to [derivative] but handles cases in which [p0] and [p1] or [p2] and [p3] coincide.
*/
fun safeDerivative(p0: Vector2, p1: Vector2, p2: Vector2, p3: Vector2, t: Double): Vector2 {
val epsilon = 10E-6
var u = t
val d10 = p1 - p0
val d32 = p3 - p2
if (u < epsilon && d10.squaredLength < epsilon) {
u = epsilon
}
if (u > (1.0 - epsilon) && d32.squaredLength < epsilon) {
u = 1.0 - epsilon
}
val iu = 1.0 - u
return ((d10 * (3.0 * iu * iu)) + (p2 - p1) * (6.0 * iu * u)) + d32 * (3.0 * u * u)
}
fun normal(x0: Vector2, c0: Vector2, x1: Vector2, t: Double): Vector2 {
val (x, y) = derivative(x0, c0, x1, t)
return Vector2(-y, x).normalized
}
fun bezier(x0: Vector2, c0: Vector2, x1: Vector2, t: Double): Vector2 {
val it = 1.0 - t
val it2 = it * it
val t2 = t * t
return Vector2(
it2 * x0.x + 2 * it * t * c0.x + t2 * x1.x,
it2 * x0.y + 2 * it * t * c0.y + t2 * x1.y
)
}
fun bezier(x0: Vector3, c0: Vector3, x1: Vector3, t: Double): Vector3 {
val it = 1.0 - t
val it2 = it * it
val t2 = t * t
return Vector3(
it2 * x0.x + 2 * it * t * c0.x + t2 * x1.x,
it2 * x0.y + 2 * it * t * c0.y + t2 * x1.y,
it2 * x0.z + 2 * it * t * c0.z + t2 * x1.z)
}
/* cubic bezier */
fun bezier(x0: Double, c0: Double, c1: Double, x1: Double, t: Double): Double {
val it = 1.0 - t
val it2 = it * it
val it3 = it2 * it
val t2 = t * t
val t3 = t2 * t
return it3 * x0 + 3.0 * it2 * t * c0 + 3.0 * it * t2 * c1 + t3 * x1
}
fun bezier(x0: Vector2, c0: Vector2, c1: Vector2, x1: Vector2, t: Double): Vector2 {
val it = 1.0 - t
val it2 = it * it
val it3 = it2 * it
val t2 = t * t
val t3 = t2 * t
return Vector2(
it3 * x0.x + 3 * it2 * t * c0.x + 3 * it * t2 * c1.x + t3 * x1.x,
it3 * x0.y + 3 * it2 * t * c0.y + 3 * it * t2 * c1.y + t3 * x1.y)
}
/**
* Samples a single point based on the provided
* [t](https://pomax.github.io/bezierinfo/#explanation) value
* from given 3D cubic Bézier curve.
*
* @param x0 The starting anchor point of the curve.
* @param c0 The first control point.
* @param c1 The second control point.
* @param x1 The ending anchor point of the curve.
* @param t The value of *t* in the range of `0.0` to `1.0`.
* @return A sample on the curve.
*/
fun bezier(x0: Vector3, c0: Vector3, c1: Vector3, x1: Vector3, t: Double): Vector3 {
val it = 1.0 - t
val it2 = it * it
val it3 = it2 * it
val t2 = t * t
val t3 = t2 * t
return Vector3(
it3 * x0.x + 3 * it2 * t * c0.x + 3 * it * t2 * c1.x + t3 * x1.x,
it3 * x0.y + 3 * it2 * t * c0.y + 3 * it * t2 * c1.y + t3 * x1.y,
it3 * x0.z + 3 * it2 * t * c0.z + 3 * it * t2 * c1.z + t3 * x1.z)
}
// linear type bezier
/* quadratic bezier */
fun <T: LinearType<T>> bezier(x0: T, c0: T, x1: T, t: Double): T {
val it = 1.0 - t
val it2 = it * it
val t2 = t * t
return x0 * it2 + c0 * (2.0 * it * t) + x1 * t2
}
fun <T : LinearType<T>> bezier(x0: T, c0: T, c1: T, x1: T, t: Double): T {
val it = 1.0 - t
val it2 = it * it
val it3 = it2 * it
val t2 = t * t
val t3 = t2 * t
return x0 * (it3) + c0 * (3 * it2 * t) + c1 * (3 * it * t2) + x1 * (t3)
}
| 34 | Kotlin | 71 | 808 | 7707b957f1c32d45f2fbff6b6a95a1a2da028493 | 6,075 | openrndr | BSD 2-Clause FreeBSD License |
src/main/kotlin/aoc2017/KnotHash.kt | komu | 113,825,414 | false | {"Kotlin": 395919} | package komu.adventofcode.aoc2017
import komu.adventofcode.utils.octetsToHex
import komu.adventofcode.utils.swap
fun knotHash(input: String): String {
val lengths = lengthsFromAscii(input)
val sparseHash = knotHashArray(lengths, rounds = 64)
return denseHash(sparseHash)
}
fun knotHashChecksum(lengths: List<Int>, size: Int = 256, rounds: Int = 1): Int {
val array = knotHashArray(lengths, size, rounds)
return array[0] * array[1]
}
private fun knotHashArray(lengths: List<Int>, size: Int = 256, rounds: Int): IntArray {
val array = IntArray(size) { it }
var position = 0
var skip = 0
repeat(rounds) {
for (length in lengths) {
reverse(array, position, length)
position = (position + length + skip) % array.size
skip++
}
}
return array
}
private fun reverse(array: IntArray, position: Int, length: Int) {
for (i in 0 until length / 2)
array.swap((position + i) % array.size, (position + length - i - 1) % array.size)
}
private fun lengthsFromAscii(str: String): List<Int> =
str.map { it.toInt() } + listOf(17, 31, 73, 47, 23)
private fun denseHash(sparseHash: IntArray): String =
sparseHash.toList()
.chunked(16)
.map { it.reduce { a, b -> a xor b } }
.octetsToHex()
| 0 | Kotlin | 0 | 0 | 8e135f80d65d15dbbee5d2749cccbe098a1bc5d8 | 1,349 | advent-of-code | MIT License |
src/advent/of/code/SeventhPuzzle.kt | 1nco | 725,911,911 | false | {"Kotlin": 112713, "Shell": 103} | package advent.of.code
import java.util.*
class SeventhPuzzle {
companion object {
private val day = "7";
private var input: MutableList<String> = arrayListOf();
private var result = 0L;
private var resultSecond = 0L;
var hands = mutableListOf<Hand>();
var chars = arrayOf("A", "K", "Q", "T", "9", "8", "7", "6", "5", "4", "3", "2", "J");
var types = arrayOf("five of a kind","four of a kind", "full house", "three of a kind", "two pair", "one pair", "high card")
val comparator = object : Comparator<Hand> {
override fun compare(o1: Hand?, o2: Hand?): Int {
if (o1 != null && o2 != null) {
if (types.indexOf(o1.type) < types.indexOf(o2.type)) {
return -1;
}
if (types.indexOf(o1.type) > types.indexOf(o2.type)) {
return 1;
}
if (types.indexOf(o1.type) == types.indexOf(o2.type)) {
for (i in 0..5) {
if (o1.value[i] != o2.value[i]) {
if (chars.indexOf(o1.value[i].toString()) < chars.indexOf(o2.value[i].toString())) {
return -1;
}
if (chars.indexOf(o1.value[i].toString()) > chars.indexOf(o2.value[i].toString())) {
return 1;
}
}
}
return 0;
}
return 0;
} else {
return 0;
}
}
}
fun solve() {
System.out.println(Date());
input.addAll(Reader.readInput(day));
var lineNum = 0;
input.forEach { line ->
var hand = line.split(" ")[0];
hands.add(Hand(line.split(" ")[0], "", line.split(" ")[1].trim().toLong()));
lineNum++;
}
hands.forEach{ hand ->
setHandType(hand, 5, "five of a kind");
setHandType(hand, 4, "four of a kind");
setFullHouseType(hand);
setHandType(hand, 3, "three of a kind");
setTwoOrOnePairType(hand);
if (hand.type == "") {
hand.type = "high card";
}
}
var sortedHands = hands.sortedWith(comparator);
var i = sortedHands.size.toLong();
sortedHands.forEach{hand ->
result += hand.bid * i;
i--;
}
System.out.println(result)
}
private fun setHandType(hand: Hand, count: Int, type: String) {
chars.forEach { char ->
var handValue = hand.value.replace("J", char);
if (handValue.count { it.toString() == char } == count && hand.type == "") {
hand.type = type;
}
}
}
private fun setTwoOrOnePairType(hand: Hand) {
var hasOnePair = false
chars.forEach { char ->
var handValue = if (!hasOnePair) hand.value.replace("J", char) else hand.value;
if (handValue.count { it.toString() == char } == 2 && hand.type == "") {
if (hasOnePair) {
hand.type = "two pair";
} else {
hasOnePair = true;
}
}
}
if (hasOnePair && hand.type == "") {
hand.type = "one pair";
}
}
private fun setFullHouseType(hand: Hand) {
var hasThreePair = false;
var threePairChar = "";
chars.forEach { char ->
var handValue = hand.value.replace("J", char);
if (handValue.count { it.toString() == char } == 3 && hand.type == "") {
hasThreePair = true;
threePairChar = char;
}
}
chars.forEach { char ->
if (hand.value.count { it.toString() == char } == 2 && hand.type == "" && char != threePairChar && char != "J") {
if (hasThreePair) {
hand.type = "full house";
}
}
}
}
}
}
class Hand(value: String, type: String, bid: Long) {
var value: String;
var type: String;
var bid: Long;
init {
this.value = value;
this.type = type;
this.bid = bid;
}
} | 0 | Kotlin | 0 | 0 | 0dffdeba1ebe0b44d24f94895f16f0f21ac8b7a3 | 4,768 | advent-of-code | Apache License 2.0 |
src/array/LeetCode295.kt | Alex-Linrk | 180,918,573 | false | null | package array
import kotlin.math.min
/**
* 数据流的中位数
* 中位数是有序列表中间的数。如果列表长度是偶数,中位数则是中间两个数的平均值。
*
*例如,
*
*[2,3,4] 的中位数是 3
*
*[2,3] 的中位数是 (2 + 3) / 2 = 2.5
*
*设计一个支持以下两种操作的数据结构:
*
*void addNum(int num) - 从数据流中添加一个整数到数据结构中。
*double findMedian() - 返回目前所有元素的中位数。
*示例:
*
*addNum(1)
*addNum(2)
*findMedian() -> 1.5
*addNum(3)
*findMedian() -> 2
*进阶:
*
*如果数据流中所有整数都在 0 到 100 范围内,你将如何优化你的算法?
*如果数据流中 99% 的整数都在 0 到 100 范围内,你将如何优化你的算法?
*/
class MedianFinder() {
val list = mutableListOf<Int>()
/** initialize your data structure here. */
fun addNum(num: Int) {
if (list.isEmpty() || list.last() < num) {
list.add(num)
return
}
if (list.first() > num) {
list.add(0, num)
return
}
list.add(midFind(list.toIntArray(), num), num)
}
fun findMedian(): Double {
val size = list.size
return when {
size == 0 -> 0.0
size % 2 == 0 -> (list[size / 2] + list[list.size / 2 - 1]) / 2.0
else -> list[list.size / 2].toDouble()
}
}
fun midFind(nums: IntArray, target: Int): Int {
var left = 0
var right = nums.lastIndex
while (left <= right) {
val mid = (left + right) / 2
when {
nums[mid] == target -> return mid
nums[mid] < target -> left = mid + 1
else -> right = mid - 1
}
}
return left
}
}
fun main() {
val mid = MedianFinder()
mid.addNum(0)
mid.addNum(2)
mid.addNum(1)
mid.addNum(3)
mid.addNum(2)
mid.addNum(0)
mid.addNum(4)
mid.addNum(3)
mid.addNum(2)
mid.addNum(1)
println(mid.list)
}
| 0 | Kotlin | 0 | 0 | 59f4ab02819b7782a6af19bc73307b93fdc5bf37 | 2,081 | LeetCode | Apache License 2.0 |
src/main/kotlin/de/lostmekka/raymarcher/Point.kt | LostMekka | 166,667,888 | false | null | package de.lostmekka.raymarcher
import kotlin.math.abs
import kotlin.math.cos
import kotlin.math.sin
import kotlin.math.sqrt
data class Point(val x: Double, val y: Double, val z: Double) {
constructor(x: Number, y: Number, z: Number) : this(x.toDouble(), y.toDouble(), z.toDouble())
val length by lazy { sqrt(squaredLength) }
val squaredLength by lazy { x * x + y * y + z * z }
val isNormalized by lazy { squaredLength == 1.0 }
val absoluteValue: Point by lazy { Point(abs(x), abs(y), abs(z)) }
val normalized: Point by lazy { length.takeIf { it != 0.0 }?.let { Point(x / it, y / it, z / it) } ?: Point.zero }
companion object {
val zero = Point(.0, .0, .0)
val right = Point(1.0, .0, .0)
val left = Point(-1.0, .0, .0)
val up = Point(.0, 1.0, .0)
val down = Point(.0, -1.0, .0)
val forward = Point(.0, .0, 1.0)
val backward = Point(.0, .0, -1.0)
}
}
operator fun Point.plus(other: Point) = Point(x + other.x, y + other.y, z + other.z)
operator fun Point.minus(other: Point) = Point(x - other.x, y - other.y, z - other.z)
operator fun Point.unaryMinus() = Point(-x, -y, -z)
operator fun Point.times(scalar: Double) = Point(x * scalar, y * scalar, z * scalar)
operator fun Point.div(scalar: Double) = Point(x / scalar, y / scalar, z / scalar)
infix fun Point.dot(other: Point) = x * other.x + y * other.y + z * other.z
infix fun Point.cross(other: Point) = Point(
x * other.z - z * other.y,
z * other.x - x * other.z,
x * other.y - y * other.x
)
private fun square(scalar: Double) = scalar * scalar
infix fun Point.distanceTo(other: Point) = sqrt(squaredDistanceTo(other))
infix fun Point.squaredDistanceTo(other: Point) = square(x - other.x) + square(y - other.y) + square(z - other.z)
infix fun Point.floorMod(other: Point) = Point(
(x % other.x + other.x) % other.x,
(y % other.y + other.y) % other.y,
(z % other.z + other.z) % other.z
)
data class Matrix(
val a00: Double, val a10: Double, val a20: Double,
val a01: Double, val a11: Double, val a21: Double,
val a02: Double, val a12: Double, val a22: Double
)
operator fun Matrix.times(p: Point) = Point(
a00 * p.x + a10 * p.y + a20 * p.z,
a01 * p.x + a11 * p.y + a21 * p.z,
a02 * p.x + a12 * p.y + a22 * p.z
)
fun xRotationMatrix(angle: Double): Matrix {
val sin = sin(angle)
val cos = cos(angle)
return Matrix(
1.0, 0.0, 0.0,
0.0, cos, -sin,
0.0, sin, cos
)
}
fun yRotationMatrix(angle: Double): Matrix {
val sin = sin(angle)
val cos = cos(angle)
return Matrix(
cos, 0.0, sin,
0.0, 1.0, 0.0,
-sin, 0.0, cos
)
}
fun zRotationMatrix(angle: Double): Matrix {
val sin = sin(angle)
val cos = cos(angle)
return Matrix(
cos, -sin, 0.0,
sin, cos, 0.0,
0.0, 0.0, 1.0
)
}
| 0 | Kotlin | 0 | 0 | ee4232112b2341901a32fa8378687cae3aab0c8d | 2,886 | ray-marcher-kt | MIT License |
src/test/kotlin/days/y2022/Day02Test.kt | jewell-lgtm | 569,792,185 | false | {"Kotlin": 161272, "Jupyter Notebook": 103410, "TypeScript": 78635, "JavaScript": 123} | package days.y2022
import days.Day
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.core.Is.`is`
import org.junit.jupiter.api.Test
class Day02Test {
@Test
fun testExampleOne() {
assertThat(
Day02().partOne(
"""
A Y
B X
C Z
""".trimIndent()
), `is`(15)
)
}
@Test
fun testPartOne() {
assertThat(Day02().partOne(), `is`(14264))
}
@Test
fun testExampleTwo() {
assertThat(
Day02().partTwo(
"""
A Y
B X
C Z
""".trimIndent()
), `is`(12)
)
}
@Test
fun testPartTwo() {
assertThat(Day02().partTwo(), `is`(12382))
}
}
class Day02 : Day(2022, 2) {
override fun partOne(input: String): Any {
val throws = parseInput(input)
return throws.sumOf { it.partOneScore() }
}
override fun partTwo(input: String): Any {
val throws = parseInput(input)
return throws.sumOf { it.partTwoScore() }
}
private fun parseInput(input: String): List<Pair<Char, Char>> = input.lines().map { line ->
val (a, b) = line.split(" ")
Pair(a[0], b[0])
}
private fun Pair<Char, Char>.partOneScore(): Int =
when (first) {
'A' -> when (second) {
'X' -> 1 + 3
'Y' -> 2 + 6
'Z' -> 3 + 0
else -> error("Unknown second: $second")
}
'B' -> when (second) {
'X' -> 1 + 0
'Y' -> 2 + 3
'Z' -> 3 + 6
else -> error("Unknown second: $second")
}
'C' -> when (second) {
'X' -> 1 + 6
'Y' -> 2 + 0
'Z' -> 3 + 3
else -> error("Unknown second: $second")
}
else -> error("Unknown first: $first")
}
private fun Pair<Char, Char>.partTwoScore(): Int =
when (first) {
'A' -> when (second) {
'X' -> Pair('A', 'Z').partOneScore()
'Y' -> Pair('A', 'X').partOneScore()
'Z' -> Pair('A', 'Y').partOneScore()
else -> error("Unknown second: $second")
}
'B' -> when (second) {
'X' -> Pair('B', 'X').partOneScore()
'Y' -> Pair('B', 'Y').partOneScore()
'Z' -> Pair('B', 'Z').partOneScore()
else -> error("Unknown second: $second")
}
'C' -> when (second) {
'X' -> Pair('C', 'Y').partOneScore()
'Y' -> Pair('C', 'Z').partOneScore()
'Z' -> Pair('C', 'X').partOneScore()
else -> error("Unknown second: $second")
}
else -> error("Unknown first: $first")
}
}
| 0 | Kotlin | 0 | 0 | b274e43441b4ddb163c509ed14944902c2b011ab | 2,941 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/main/kotlin/dev/shtanko/algorithms/leetcode/RangeAddition.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.extensions.second
/**
* 370. Range Addition
* @see <a href="https://leetcode.com/problems/range-addition/">Source</a>
*/
fun interface RangeAddition {
operator fun invoke(length: Int, updates: Array<IntArray>): IntArray
}
/**
* Approach 1: Naive Approach
* Time complexity : O(n * k)
* Space complexity : O(1)
*/
class RangeAdditionBruteForce : RangeAddition {
override operator fun invoke(length: Int, updates: Array<IntArray>): IntArray {
val ans = IntArray(length) { 0 }
for (triplet in updates) {
val startIndex = triplet.first()
val endIndex = triplet.second()
val inc = triplet.last()
for (i in startIndex..endIndex) {
ans[i] += inc
}
}
return ans
}
}
/**
* Approach 2: Range Caching
* Time complexity : O(n + k)
* Space complexity : O(1)
*/
class RangeAdditionCaching : RangeAddition {
override operator fun invoke(length: Int, updates: Array<IntArray>): IntArray {
val ans = IntArray(length) { 0 }
for (triplet in updates) {
val startIndex = triplet.first()
val endIndex = triplet.second()
val inc = triplet.last()
ans[startIndex] += inc
if (endIndex < length - 1) {
ans[endIndex + 1] -= inc
}
}
var sum = 0
for (i in 0 until length) {
sum += ans[i]
ans[i] = sum
}
return ans
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,170 | kotlab | Apache License 2.0 |
src/main/kotlin/d13/d13.kt | LaurentJeanpierre1 | 573,454,829 | false | {"Kotlin": 118105} | package d13
import readInput
import java.lang.IllegalStateException
sealed class Item : Comparable<Item>
class ItemList(val list: List<Item>) : Item() {
/**
* Compares this object with the specified object for order. Returns zero if this object is equal
* to the specified [other] object, a negative number if it's less than [other], or a positive number
* if it's greater than [other].
*/
override fun compareTo(other: Item): Int {
val right = if (other is ItemList)
other.list.listIterator()
else
listOf(other).listIterator()
val left = list.listIterator()
do {
if (left.hasNext()) {
if (right.hasNext()) {
val res = left.next().compareTo(right.next())
if (res != 0) return res
} else return 1
} else {
return if (right.hasNext()) -1 else 0
}
} while (true)
}
override fun toString(): String {
return list.toString()
}
}
class ItemInt(val int : Int) : Item() {
/**
* Compares this object with the specified object for order. Returns zero if this object is equal
* to the specified [other] object, a negative number if it's less than [other], or a positive number
* if it's greater than [other].
*/
override fun compareTo(other: Item): Int {
if (other is ItemList)
return ItemList(listOf(this)).compareTo(other)
if (other is ItemInt)
return int.compareTo(other.int)
throw IllegalStateException()
}
override fun toString(): String {
return int.toString()
}
}
fun parse(line : String) : Item {
return parse(line.toCharArray().toList().listIterator())!!
}
fun parse(line: ListIterator<Char>) : Item? {
when (val first = line.next()) {
'[' -> {
val res = mutableListOf<Item>()
while (line.next() != ']') {
line.previous() // unconsume char
val item = parse(line)
if (item != null)
res.add(item)
if (line.next() != ',')
line.previous() // unconsume char
}
return ItemList(res)
}
in '0'..'9' -> {
var int = first - '0'
var next = line.next()
while (next in '0'..'9') {
int = 10 * int + (next - '0')
next = line.next()
}
line.previous()
return ItemInt(int)
}
else -> return null
}
}
fun part1(input: List<String>): Int {
val ite = input.listIterator()
var idx = 1
var score = 0
while (ite.hasNext()) {
val left = parse(ite.next())
val right = parse(ite.next())
println("Comparing $left with $right")
assert(!ite.hasNext() || ite.next().isBlank())
if (left < right)
score += idx
++idx
}
return score
}
fun part2(input: List<String>): Int {
val packets = mutableListOf<Item>()
val ite = input.listIterator()
while (ite.hasNext()) {
val left = parse(ite.next())
val right = parse(ite.next())
assert(!ite.hasNext() || ite.next().isBlank())
packets.add(left)
packets.add(right)
}
val divider1 = parse("[[2]]")
val divider2 = parse("[[6]]")
packets.add(divider1)
packets.add(divider2)
packets.sort()
val idx1 = packets.indexOf(divider1) + 1
val idx2 = packets.indexOf(divider2) + 1
val res = idx1*idx2
println("idx = $idx1 * $idx2 = $res")
return res
}
fun main() {
//val input = readInput("d13/test")
val input = readInput("d13/input1")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5cf6b2142df6082ddd7d94f2dbde037f1fe0508f | 3,829 | aoc2022 | Creative Commons Zero v1.0 Universal |
baparker/04/main.kt | VisionistInc | 433,099,870 | false | {"Kotlin": 91599, "Go": 87605, "Ruby": 65600, "Python": 21104} | import java.io.File
import kotlin.collections.mutableListOf
var numberList: List<String> = mutableListOf()
var boardList: MutableList<MutableList<String>> = mutableListOf()
val BOARD_SIZE = 5
fun getNumbersAndBoards() {
var lineIndex = 0
var boardIndex = -1
File("input.txt").forEachLine {
if (lineIndex == 0) {
numberList = it.split(",")
} else {
if (it.isEmpty()) {
boardList.add(mutableListOf())
boardIndex++
} else {
boardList.get(boardIndex).addAll(it.trim().split("\\s+".toRegex()))
}
}
lineIndex++
}
}
fun checkForLineWin(
board: List<String>,
start: Int,
end: Int,
stepSize: Int,
indexValue: Int,
): Int {
var numHits = 0
for (i in start..end step stepSize) {
if (board.get(i).startsWith("*")) {
numHits++
} else break
}
// a win returns the sum
if (numHits == BOARD_SIZE) {
var sum = 0
board.forEach({ value: String ->
if (!value.startsWith("*")) {
sum += value.toInt()
}
})
return sum * indexValue.toInt()
}
return -1
}
fun traverseBoard(currentNum: String, board: MutableList<String>): MutableList<String>? {
for (index in board.indices) {
if (board[index].equals(currentNum)) {
// Mark the match with an *
board[index] = "*" + board[index]
val rowStart = index / BOARD_SIZE * BOARD_SIZE
val xSum =
checkForLineWin(
board,
rowStart,
(rowStart + BOARD_SIZE) - 1,
1,
currentNum.toInt(),
)
if (xSum > -1) {
println(xSum)
return board
}
val colStart = index % BOARD_SIZE
val ySum =
checkForLineWin(
board,
colStart,
(BOARD_SIZE * BOARD_SIZE) - 1,
BOARD_SIZE,
currentNum.toInt(),
)
if (ySum > -1) {
println(ySum)
return board
}
}
}
return null
}
fun traverseAllBoards(currentNum: String) {
var removeBoards: MutableList<MutableList<String>> = mutableListOf()
for (board in boardList) {
val boardToRemove = traverseBoard(currentNum, board)
if (boardToRemove != null) {
removeBoards.add(boardToRemove)
}
}
boardList.removeAll(removeBoards)
}
fun getBingo() {
for (num in numberList) {
traverseAllBoards(num)
}
}
fun main() {
getNumbersAndBoards()
getBingo()
}
| 0 | Kotlin | 4 | 1 | e22a1d45c38417868f05e0501bacd1cad717a016 | 2,934 | advent-of-code-2021 | MIT License |
kotlin/2251-number-of-flowers-in-full-bloom.kt | neetcode-gh | 331,360,188 | false | {"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750} | // two heaps
class Solution {
fun fullBloomFlowers(flowers: Array<IntArray>, _people: IntArray): IntArray {
val people = _people.mapIndexed { i, p -> p to i }.sortedBy { it.first }
val res = IntArray (_people.size)
var count = 0
val start = PriorityQueue<Int>()
val end = PriorityQueue<Int>()
for ((s, e) in flowers) {
start.add(s)
end.add(e)
}
for ((p, i) in people) {
while (start.isNotEmpty() && start.peek() <= p) {
start.poll()
count++
}
while (end.isNotEmpty() && end.peek() < p) {
end.poll()
count--
}
res[i] = count
}
return res
}
}
// one heap
class Solution {
fun fullBloomFlowers(flowers: Array<IntArray>, _people: IntArray): IntArray {
val people = _people.mapIndexed { i, p -> p to i }.sortedBy { it.first }
val res = IntArray (_people.size)
flowers.sortBy { it[0] }
val end = PriorityQueue<Int>()
var j = 0
for ((p, i) in people) {
while (j < flowers.size && flowers[j][0] <= p) {
end.add(flowers[j][1])
j++
}
while (end.isNotEmpty() && end.peek() < p)
end.poll()
res[i] = end.size
}
return res
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 1,435 | leetcode | MIT License |
src/main/kotlin/com/nibado/projects/advent/y2018/Day11.kt | nielsutrecht | 47,550,570 | false | null | package com.nibado.projects.advent.y2018
import com.nibado.projects.advent.Day
import com.nibado.projects.advent.Point
import com.nibado.projects.advent.collect.SummedAreaTable
import kotlin.math.min
object Day11 : Day {
private val grid = Grid(6392)
class Grid(serial: Int) {
private val grid = IntArray(300 * 300)
private val summed: SummedAreaTable
init {
for (x in 1..300) {
for (y in 1..300) {
val rackId = x + 10
grid[toIndex(x, y)] = hundred((rackId * y + serial) * rackId) - 5
}
}
summed = SummedAreaTable.from(grid.toList().chunked(300).map { it.toIntArray() })
}
fun get(x: Int, y: Int, size: Int = 3): Int {
val a = Point(x - 1, y - 1)
val b = a + Point(size - 1, size - 1)
return summed.get(a, b)
}
private fun hundred(v: Int) = ((v % 1000) - (v % 100)) / 100
private fun toIndex(x: Int, y: Int) = x - 1 + (y - 1) * 300
}
private fun maxSize(p: Point) = min(300 - p.x, 300 - p.y)
override fun part1() = (1..298).flatMap { y -> (1..298).map { x -> Point(x, y) } }
.maxByOrNull { grid.get(it.x, it.y) }
?.let { "${it.x},${it.y}" }!!
override fun part2() = (1..300).flatMap { y -> (1..300).map { x -> Point(x, y) } }.asSequence()
.flatMap { p -> (1..maxSize(p)).asSequence().map { p to it } }
.maxByOrNull { grid.get(it.first.x, it.first.y, it.second) }
?.let { "${it.first.x},${it.first.y},${it.second}" }!!
} | 1 | Kotlin | 0 | 15 | b4221cdd75e07b2860abf6cdc27c165b979aa1c7 | 1,634 | adventofcode | MIT License |
src/main/kotlin/com/jacobhyphenated/advent2022/day5/Day5.kt | jacobhyphenated | 573,603,184 | false | {"Kotlin": 144303} | package com.jacobhyphenated.advent2022.day5
import com.jacobhyphenated.advent2022.Day
// Distinguish between Crates as the data structure holding the initial state of the stacks
// and CratesMut which is a mutable data structure used when executing the crane instructions
typealias CratesMut = List<MutableList<Char>>
typealias Crates = List<List<Char>>
/**
* Day 5: Supply Stacks
*
* A number of crates of supplies are placed in several stacks.
* The initial positioning of the crates, and the instructions for the crane
* are the puzzle input.
*/
class Day5: Day<Pair<Crates, List<Instruction>>> {
override fun getInput(): Pair<Crates, List<Instruction>> {
return parseInputString(readInputFile("day5"))
}
/**
* The crane lifts one crate at a time.
* An instruction of "move 3 from 1 to 2"
* moves three crates from stack 1 to stack 2 moving one crate at a time.
* The crane always removes from the top of the stack and places on the top of the stack
*
* Moving from left to right (lowest stack to highest stack) pull the character from the top
* crate on the stack and return the string as a message.
*/
override fun part1(input: Pair<Crates, List<Instruction>>): String {
val (cratesInput, instructions) = input
// don't mutate the input I want to re-use for part2 (I miss rust)
val crates = cratesInput.map { it.toMutableList() }
instructions.forEach { instruction ->
repeat(instruction.number){
moveCrate(crates, instruction.start, instruction.destination)
}
}
return crates.map { it.last() }.joinToString(separator = "")
}
/**
* The crane actually picks up all crates it needs to move in a single instruction at once.
* So instead of moving crates in reverse order (part 1), it moves them in the same order.
*
* Return the message spelled by the top crate in each stack.
*/
override fun part2(input: Pair<Crates, List<Instruction>>): String {
val (cratesInput, instructions) = input
val crates = cratesInput.map { it.toMutableList() }
instructions.forEach { instruction ->
val stack = crates[instruction.start].removeLastN(instruction.number)
crates[instruction.destination].addAll(stack)
}
return crates.map { it.last() }.joinToString(separator = "")
}
private fun moveCrate(crates: CratesMut, from: Int, to: Int) {
val crate = crates[from].removeLast()
crates[to].add(crate)
}
/**
* Parsing the input by splitting into two sections: crates and instructions
*
* For crates, use a bottom up approach
* - find index of the character for each line that corresponds to a stack
* - add crates to the stack in reverse order (bottom of stack first)
*
* Instructions are parsed out of the string
* - subtract one from the "to" and "from" stacks to convert stack number to array index
*/
fun parseInputString(input: String): Pair<Crates, List<Instruction>> {
val (crateString, instructionString) = input.split("\n\n")
val crateIndexMap: MutableMap<Int, MutableList<Char>> = mutableMapOf()
val crateInputLines = crateString.lines().reversed()
crateInputLines[0].forEachIndexed{ index, c ->
if (!c.isWhitespace()){
crateIndexMap[index] = mutableListOf()
}
}
crateInputLines.slice(1 until crateInputLines.size).forEach { crateLine ->
crateIndexMap.keys.forEach { index ->
if (crateLine.length > index && !crateLine[index].isWhitespace()) {
// !! is safe because index must be a key for crateIndexMap. Wish the compiler could know that
crateIndexMap[index]!!.add(crateLine[index])
}
}
}
val crates = crateIndexMap.keys.sorted().map { crateIndexMap.getValue(it) }
val instructions = instructionString.lines().map {
val (move, toFrom) = it.split(" from ")
val number = move.trim().split(" ").last().toInt()
val (start, destination) = toFrom.split("to").map { c-> c.trim().toInt() }
Instruction(start - 1, destination - 1, number)
}
return Pair(crates, instructions)
}
}
data class Instruction(
val start: Int,
val destination: Int,
val number: Int
)
/**
* Remove the last N elements from a mutable list and return them.
*
* @param n the number of elements to be removed from the end of the list
* @return A list containing the removed elements with order preserved
*/
fun <T> MutableList<T>.removeLastN(n: Int): List<T> {
val removedPart = this.slice(this.size - n until this.size)
repeat(n) { this.removeLast() }
return removedPart
} | 0 | Kotlin | 0 | 0 | 9f4527ee2655fedf159d91c3d7ff1fac7e9830f7 | 4,881 | advent2022 | The Unlicense |
aoc-2021/src/commonMain/kotlin/fr/outadoc/aoc/twentytwentyone/Day03.kt | outadoc | 317,517,472 | false | {"Kotlin": 183714} | package fr.outadoc.aoc.twentytwentyone
import fr.outadoc.aoc.scaffold.Day
import fr.outadoc.aoc.scaffold.readDayInput
@Suppress("NonAsciiCharacters", "LocalVariableName")
class Day03 : Day<Int> {
private val input: List<IntArray> = readDayInput()
.lineSequence()
.map { line -> line.map { it.digitToInt() }.toIntArray() }
.toList()
private fun IntArray.flip() = map { if (it == 1) 0 else if (it == 0) 1 else it }.toIntArray()
private fun IntArray.toInt() = joinToString("").toInt(radix = 2)
private fun List<IntArray>.mostCommonBitMap(): IntArray {
return reduce { sum, line -> sum.zip(line) { a, b -> a + b }.toIntArray() }
.map { oneCount ->
val zeroCount = size - oneCount
when {
oneCount > zeroCount -> 1
oneCount < zeroCount -> 0
else -> -1
}
}
.toIntArray()
}
override fun step1(): Int {
val mostCommonBitMap = input.mostCommonBitMap()
val γ = mostCommonBitMap.toInt()
val ε = mostCommonBitMap.flip().toInt()
return γ * ε
}
override fun step2(): Int {
val oxygenGeneratorRating = filterWithBitCriteria(candidates = input, wantedBit = 1).toInt()
val co2ScrubberRating = filterWithBitCriteria(candidates = input, wantedBit = 0).toInt()
return oxygenGeneratorRating * co2ScrubberRating
}
private fun filterWithBitCriteria(candidates: List<IntArray>, wantedBit: Int, index: Int = 0): IntArray {
return if (candidates.size == 1) candidates.first()
else {
val mostCommonBitMap = candidates.mostCommonBitMap().let { if (wantedBit == 0) it.flip() else it }
filterWithBitCriteria(
candidates = candidates.filter { candidate ->
candidate[index] == mostCommonBitMap[index]
|| (mostCommonBitMap[index] == -1 && candidate[index] == wantedBit)
},
wantedBit = wantedBit,
index = index + 1
)
}
}
override val expectedStep1 = 3882564
override val expectedStep2 = 3385170
}
| 0 | Kotlin | 0 | 0 | 54410a19b36056a976d48dc3392a4f099def5544 | 2,227 | adventofcode | Apache License 2.0 |
day03/part2.kts | bmatcuk | 726,103,418 | false | {"Kotlin": 214659} | // --- Part Two ---
// The engineer finds the missing part and installs it in the engine! As the
// engine springs to life, you jump in the closest gondola, finally ready to
// ascend to the water source.
//
// You don't seem to be going very fast, though. Maybe something is still
// wrong? Fortunately, the gondola has a phone labeled "help", so you pick it
// up and the engineer answers.
//
// Before you can explain the situation, she suggests that you look out the
// window. There stands the engineer, holding a phone in one hand and waving
// with the other. You're going so slowly that you haven't even left the
// station. You exit the gondola.
//
// The missing part wasn't the only issue - one of the gears in the engine is
// wrong. A gear is any * symbol that is adjacent to exactly two part numbers.
// Its gear ratio is the result of multiplying those two numbers together.
//
// This time, you need to find the gear ratio of every gear and add them all up
// so that the engineer can figure out which gear needs to be replaced.
//
// Consider the same engine schematic again:
//
// 467..114..
// ...*......
// ..35..633.
// ......#...
// 617*......
// .....+.58.
// ..592.....
// ......755.
// ...$.*....
// .664.598..
//
// In this schematic, there are two gears. The first is in the top left; it has
// part numbers 467 and 35, so its gear ratio is 16345. The second gear is in
// the lower right; its gear ratio is 451490. (The * adjacent to 617 is not a
// gear because it is only adjacent to one part number.) Adding up all of the
// gear ratios produces 467835.
//
// What is the sum of all of the gear ratios in your engine schematic?
import java.io.*
import kotlin.io.*
import kotlin.math.*
val RGX = Regex("(\\d+)")
val lines = File("input.txt").readLines()
val lineLength = lines[0].length
val result = lines.withIndex().flatMap { (lineIdx, line) ->
RGX.findAll(line).flatMap {
val num = it.groupValues[1].toInt()
val range = it.range
val expandedRange = max(range.start - 1, 0)..min(range.endInclusive + 1, line.length - 1)
sequence {
if (lineIdx > 0) {
val prevLine = lines[lineIdx - 1]
yieldAll(expandedRange.filter { prevLine[it] == '*' }.map { lineLength * (lineIdx - 1) + it })
}
if (lineIdx + 1 < lines.size) {
val nextLine = lines[lineIdx + 1]
yieldAll(expandedRange.filter { nextLine[it] == '*' }.map { lineLength * (lineIdx + 1) + it })
}
if (line[expandedRange.start] == '*') {
yield(lineLength * lineIdx + expandedRange.start)
}
if (line[expandedRange.endInclusive] == '*') {
yield(lineLength * lineIdx + expandedRange.endInclusive)
}
}.map { it to num }
}
}.groupBy({ it.first }, { it.second }).values.filter { it.size == 2 }.sumOf { it.reduce(Int::times) }
println(result)
| 0 | Kotlin | 0 | 0 | a01c9000fb4da1a0cd2ea1a225be28ab11849ee7 | 2,836 | adventofcode2023 | MIT License |
kotlinP/src/main/java/com/jadyn/kotlinp/dynamic/dynamic-0.kt | JadynAi | 136,196,478 | false | null | package com.jadyn.kotlinp.dynamic
import kotlin.math.max
/**
*JadynAi since 4/20/21
*/
fun main() {
// println("fib result ${maxSubArray(intArrayOf(-2, 1, -3, 4, -1, 2, 1, -5, 4))}")
// println("counts ${climbStairs(4)}")
// println("max profit ${maxProfit1(intArrayOf(3, 3, 6, 7, 1, 6, 5, 4, 10))}")
println("机器人路径 ${Test.judgeWordIsInMatrix("SEARCH")}")
}
/**
* 斐波那契数列
* */
fun fib(n: Int): Int {
if (n < 2) return n
var pre = 0
var cur = 1
for (i in 2..n) {
val sum = pre + cur
pre = cur
cur = sum
}
return cur
}
/**
* 最大子序和
* */
fun maxSubArray(nums: IntArray): Int {
var sum = 0
var maxAnswer = nums[0]
for (num in nums) {
sum = max(sum + num, num)
maxAnswer = max(sum, maxAnswer)
}
return maxAnswer
}
fun coinChange(coins: IntArray, amount: Int): Int {
if (amount == 0) return 0
if (amount < 0) return -1
coins.forEach {
val subProblem = coinChange(coins, amount - it)
if (subProblem == -1) {
return@forEach
}
}
return -1
}
/**
* 爬n楼梯,每次只能爬1或者2,共有多少种解法
* */
fun climbStairs(n: Int): Int {
if (n <= 0) {
return 0
}
val countsArray = arrayOfNulls<Int>(n)
countsArray[0] = 1
countsArray[1] = 2
for (i in 2 until n) {
countsArray[i] = countsArray[i - 1]!! + countsArray[i - 2]!!
}
return countsArray[n - 1]!!
}
/**
* 给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
* 你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。
* 设计一个算法来计算你所能获取的最大利润。
* 返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0
* */
fun maxProfit(prices: IntArray): Int {
if (prices.size == 0) return 0
var max = 0
var min = prices[0]
for (i in 0..prices.lastIndex) {
if (prices[i] <= min) {
min = prices[i]
} else if (prices[i] - min > max) {
max = prices[i] - min
}
}
return if (max < 0) 0 else max
}
fun maxProfit1(prices: IntArray): Int {
if (prices.size == 0) return 0
var max = 0
// 4/26/21-10:05 PM 前一天的利润
var pre = 0
for (i in 1..prices.lastIndex) {
val diff = prices[i] - prices[i - 1]
// 4/26/21-10:04 PM 状态转移方程,i天的利润就是前一天的利润,加上i天的i-1的利润差
pre = Math.max(0, pre + diff)
max = Math.max(max, pre)
}
return max
}
/**
* 一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为 “Start” )。
* 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为 “Finish” )。
* 问总共有多少条不同的路径?
* */
fun uniquePaths(m: Int, n: Int): Int {
val dp = Array<IntArray>(m) {
if (it == 0) {
IntArray(n) { 1 }
} else {
IntArray(n) { na -> if (na == 0) 1 else 0 }
}
}
// dp.forEachIndexed { index, ints ->
// ints.forEachIndexed { j, na ->
// // 4/28/21-10:13 PM 这么写的判断条件,为什么不直接从1开始遍历呢?
// // 固化、固化!
// if (index != 0 && j != 0) {
// dp[index][j] = dp[index - 1][j] + dp[index][j - 1]
// }
// }
// }
for (i in 1 until m) {
for (j in 1 until n) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
}
}
return dp[m - 1][n - 1]
}
/**
* 优化机器人的控件复杂度为O(n)
* 相当于把短数组按照max次数过了一遍
* d[j] 就相当于是cur dp[j-1]相当于是pre
* */
fun uniquePaths1(m: Int, n: Int): Int {
val min = Math.min(m, n)
val max = Math.max(m, n)
val dp = IntArray(min) { 1 }
for (i in 1 until max) {
for (j in 1 until min) {
println("i $i j $j dp ${dp[j]}")
dp[j] += dp[j - 1]
}
}
return dp[min - 1]
} | 0 | Kotlin | 6 | 17 | 9c5efa0da4346d9f3712333ca02356fa4616a904 | 4,202 | Kotlin-D | Apache License 2.0 |
src/Lesson2Arrays/CyclicRotation.kt | slobodanantonijevic | 557,942,075 | false | {"Kotlin": 50634} | /**
* 100/100
* @param A
* @param K
* @return
*/
fun solution(A: IntArray, K: Int): IntArray? {
val N = A.size
val result = IntArray(N)
for (i in 0 until N) {
val key: Int = (i + K) % N
result[key] = A[i]
}
return result
}
/**
* An array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is moved to the first place. For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7] (elements are shifted right by one index and 6 is moved to the first place).
*
* The goal is to rotate array A K times; that is, each element of A will be shifted to the right K times.
*
* Write a function:
*
* class Solution { public int[] solution(int[] A, int K); }
*
* that, given an array A consisting of N integers and an integer K, returns the array A rotated K times.
*
* For example, given
*
* A = [3, 8, 9, 7, 6]
* K = 3
* the function should return [9, 7, 6, 3, 8]. Three rotations were made:
*
* [3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7]
* [6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9]
* [7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8]
* For another example, given
*
* A = [0, 0, 0]
* K = 1
* the function should return [0, 0, 0]
*
* Given
*
* A = [1, 2, 3, 4]
* K = 4
* the function should return [1, 2, 3, 4]
*
* Assume that:
*
* N and K are integers within the range [0..100];
* each element of array A is an integer within the range [−1,000..1,000].
* In your solution, focus on correctness. The performance of your solution will not be the focus of the assessment.
*/ | 0 | Kotlin | 0 | 0 | 155cf983b1f06550e99c8e13c5e6015a7e7ffb0f | 1,659 | Codility-Kotlin | Apache License 2.0 |
src/main/kotlin/g0101_0200/s0110_balanced_binary_tree/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0101_0200.s0110_balanced_binary_tree
// #Easy #Depth_First_Search #Tree #Binary_Tree #Programming_Skills_II_Day_2 #Level_2_Day_6_Tree
// #Udemy_Tree_Stack_Queue #2023_07_11_Time_182_ms_(71.30%)_Space_36.5_MB_(78.48%)
import com_github_leetcode.TreeNode
/*
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun isBalanced(root: TreeNode?): Boolean {
// Empty Tree is balanced
if (root == null) {
return true
}
// Get max height of subtree child
// Get max height of subtree child
// compare height difference (cannot be more than 1)
var leftHeight = 0
var rightHeight = 0
if (root.left != null) {
leftHeight = getMaxHeight(root.left)
}
if (root.right != null) {
rightHeight = getMaxHeight(root.right)
}
val heightDiff = Math.abs(leftHeight - rightHeight)
// if passes height check
// - Check if left subtree is balanced and if the right subtree is balanced
// - If one of both are imbalanced, then the tree is imbalanced
return heightDiff <= 1 && isBalanced(root.left) && isBalanced(root.right)
}
private fun getMaxHeight(root: TreeNode?): Int {
if (root == null) {
return 0
}
var leftHeight = 0
var rightHeight = 0
// Left
if (root.left != null) {
leftHeight = getMaxHeight(root.left)
}
// Right
if (root.right != null) {
rightHeight = getMaxHeight(root.right)
}
return if (leftHeight > rightHeight) {
1 + leftHeight
} else {
1 + rightHeight
}
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,890 | LeetCode-in-Kotlin | MIT License |
2021/src/main/kotlin/com/trikzon/aoc2021/Day12.kt | Trikzon | 317,622,840 | false | {"Kotlin": 43720, "Rust": 21648, "C#": 12576, "C++": 4114, "CMake": 397} | package com.trikzon.aoc2021
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
fun main() {
val input = getInputStringFromFile("/day12.txt")
benchmark(Part.One, ::day12Part1, input, 5252, 5000)
benchmark(Part.One, ::day12Part2, input, 147784, 50)
}
fun day12Part1(input: String): Int {
val caveConnections = HashMap<String, ArrayList<String>>()
input.lines().forEach { line ->
val caves = line.split('-')
if (caves[1] == "start") {
if (caveConnections["start"] == null) {
caveConnections["start"] = ArrayList<String>().apply { add(caves[0]) }
} else {
caveConnections["start"]?.add(caves[0])
}
} else if (caves[0] == "end") {
if (caveConnections[caves[1]] == null) {
caveConnections[caves[1]] = ArrayList<String>().apply { add("end") }
} else {
caveConnections[caves[1]]?.add("end")
}
} else {
if (caveConnections[caves[0]] == null) {
if (caves[0] != "end") caveConnections[caves[0]] = ArrayList<String>().apply { add(caves[1]) }
} else {
if (caves[0] != "end") caveConnections[caves[0]]?.add(caves[1])
}
if (caveConnections[caves[1]] == null) {
if (caves[0] != "start") caveConnections[caves[1]] = ArrayList<String>().apply { add(caves[0]) }
} else {
if (caves[0] != "start") caveConnections[caves[1]]?.add(caves[0])
}
}
}
return visitCave("start", LinkedList(), caveConnections)
}
fun visitCave(cave: String, path: LinkedList<String>, caveConnections: HashMap<String, ArrayList<String>>): Int {
val newPath = LinkedList(path).apply { add(cave) }
var paths = 0
if (caveConnections[cave] != null) {
for (connection in caveConnections[cave]!!) {
if (connection == "end") {
paths += 1
continue
}
if (!hasBeenVisited(connection, newPath)) {
paths += visitCave(connection, newPath, caveConnections)
}
}
}
return paths
}
fun hasBeenVisited(cave: String, path: LinkedList<String>): Boolean {
if (cave[0].isUpperCase()) return false
for (visited in path) {
if (visited == cave) {
return true
}
}
return false
}
fun day12Part2(input: String): Int {
val caveConnections = HashMap<String, ArrayList<String>>()
input.lines().forEach { line ->
val caves = line.split('-')
if (caves[1] == "start") {
if (caveConnections["start"] == null) {
caveConnections["start"] = ArrayList<String>().apply { add(caves[0]) }
} else {
caveConnections["start"]?.add(caves[0])
}
} else if (caves[0] == "end") {
if (caveConnections[caves[1]] == null) {
caveConnections[caves[1]] = ArrayList<String>().apply { add("end") }
} else {
caveConnections[caves[1]]?.add("end")
}
} else {
if (caveConnections[caves[0]] == null) {
if (caves[0] != "end") caveConnections[caves[0]] = ArrayList<String>().apply { add(caves[1]) }
} else {
if (caves[0] != "end") caveConnections[caves[0]]?.add(caves[1])
}
if (caveConnections[caves[1]] == null) {
if (caves[0] != "start") caveConnections[caves[1]] = ArrayList<String>().apply { add(caves[0]) }
} else {
if (caves[0] != "start") caveConnections[caves[1]]?.add(caves[0])
}
}
}
return visitCavePart2("start", LinkedList(), caveConnections)
}
fun visitCavePart2(cave: String, path: LinkedList<String>, caveConnections: HashMap<String, ArrayList<String>>): Int {
val newPath = LinkedList(path).apply { add(cave) }
var paths = 0
if (caveConnections[cave] != null) {
for (connection in caveConnections[cave]!!) {
if (connection == "end") {
paths += 1
continue
}
if (!hasBeenVisitedPart2(connection, newPath)) {
paths += visitCavePart2(connection, newPath, caveConnections)
}
}
}
return paths
}
fun hasBeenVisitedPart2(cave: String, path: LinkedList<String>): Boolean {
if (cave[0].isUpperCase()) return false
var alreadyDoubled = false
for (visited in path) {
if (visited[0].isLowerCase()) {
if (path.count { i -> i == visited } >= 2) alreadyDoubled = true
}
}
var timesVisited = 0
for (visited in path) {
if (visited == cave) {
timesVisited++
if (alreadyDoubled) {
return true
}
}
if (timesVisited == 2) return true
}
return false
}
| 0 | Kotlin | 1 | 0 | d4dea9f0c1b56dc698b716bb03fc2ad62619ca08 | 4,989 | advent-of-code | MIT License |
src/Day10.kt | oleksandrbalan | 572,863,834 | false | {"Kotlin": 27338} | import kotlin.math.abs
fun main() {
val input = readInput("Day10")
.filterNot { it.isEmpty() }
.map {
when {
it.startsWith(COMMAND_ADDX) -> listOf(0, it.split(" ")[1].toInt())
it.startsWith(COMMAND_NOOP) -> listOf(0)
else -> error("Command not supported")
}
}
.flatten()
.scan(1) { acc, i -> acc + i }
val part1 = CYCLES.sumOf { it * input[it - 1] }
println("Part1: $part1")
println("Part2:")
val width = 40
val height = 6
repeat(height) { row ->
repeat(width) { column ->
val index = row * width + column
val position = input[index]
val pixel = if (abs(position - column) <= 1) PIXEL_WHITE else PIXEL_DARK
print(pixel)
}
println()
}
}
private const val COMMAND_ADDX = "addx"
private const val COMMAND_NOOP = "noop"
private const val PIXEL_WHITE = "#"
private const val PIXEL_DARK = "."
private val CYCLES = listOf(20, 60, 100, 140, 180, 220)
| 0 | Kotlin | 0 | 2 | 1493b9752ea4e3db8164edc2dc899f73146eeb50 | 1,064 | advent-of-code-2022 | Apache License 2.0 |
src/Day09.kt | SeanDijk | 575,314,390 | false | {"Kotlin": 29164} | import java.util.*
import kotlin.math.abs
import kotlin.math.sign
fun main() {
data class Coordinate(val x: Int, val y: Int) {
fun moveX(int: Int) = copy(x = x + int)
fun moveY(int: Int) = copy(y = y + int)
fun left() = moveX(-1)
fun right() = moveX(1)
fun up() = moveY(1)
fun down() = moveY(-1)
fun distanceX(other: Coordinate) = abs(x - other.x)
fun distanceY(other: Coordinate) = abs(y - other.y)
fun delta(other: Coordinate) = Coordinate(x - other.x, y - other.y)
}
data class Command(val direction: String, val times: Int)
val commandBindings = mapOf(
"R" to Coordinate::right,
"U" to Coordinate::up,
"L" to Coordinate::left,
"D" to Coordinate::down
)
fun parseCommands(input: List<String>): Sequence<Command> {
return input.asSequence().map {
val (direction, times) = it.split(' ')
Command(direction, times.toInt())
}
}
fun part1(input: List<String>): Int {
class GameState {
var head = Coordinate(0, 0)
var tail = Coordinate(0, 0)
set(value) {
tailSpots.add(value)
field = value
}
val tailSpots = mutableSetOf(tail)
}
val gameState = GameState()
fun move(command: Command) {
val moveFunction = commandBindings[command.direction]!!
with(gameState) {
for (i in 0 until command.times) {
head = moveFunction(head)
val delta = head.delta(tail)
val distanceX = head.distanceX(tail)
val distanceY = head.distanceY(tail)
if (distanceX + distanceY == 3) {
tail = tail.moveX(delta.x.sign).moveY(delta.y.sign)
} else if (distanceX == 2) {
tail = tail.moveX(delta.x.sign)
} else if (distanceY == 2) {
tail = tail.moveY(delta.y.sign)
}
}
}
}
parseCommands(input).forEach { move(it) }
return gameState.tailSpots.size
}
fun part2(input: List<String>): Int {
class GameState(val debug: Boolean = false) {
var head: Coordinate = Coordinate(0, 0)
val tails: LinkedList<Coordinate> = LinkedList(generateSequence { Coordinate(0, 0) }.take(9).toList())
val tracker = mutableSetOf(Coordinate(0, 0))
val headTracker = mutableSetOf(Coordinate(0, 0))
fun stateToString(size: Int): String {
val yStart = size / 2
var yCount = yStart
val xStart = 1 - yCount
var xCount = xStart
var currentCoord = Coordinate(xCount, yCount)
fun generateField(): String {
if (currentCoord == head) {
return "[H]"
}
val tailNumber = tails.indexOfFirst { it == currentCoord }
if (tailNumber != -1) {
return "[${tailNumber + 1}]"
}
// if (tracker.contains(currentCoord)) {
// if (headTracker.contains(currentCoord)) {
// return "[#]"
// }
if (currentCoord == Coordinate(0, 0)) {
return "[s]"
}
return "[ ]"
}
fun advanceField() {
currentCoord = if (currentCoord.x == yStart) {
currentCoord.copy(x = 1 - yStart, y = currentCoord.y - 1)
} else {
currentCoord.right()
}
}
return generateSequence {
generateSequence { generateField() }
.onEach { advanceField() }
.take(size)
.reduce() { acc, s -> "$acc $s" } + " ${yCount--}\n"
}
.take(size)
.reduce { acc, sequence -> acc + sequence } +
generateSequence { "${xCount++}".padEnd(4) }
.take(size)
.reduce { acc, sequence -> acc + sequence }
}
}
val gameState = GameState()
fun move(command: Command) {
val moveFunction = commandBindings[command.direction]!!
with(gameState) {
for (i in 0 until command.times) {
head = moveFunction(head)
headTracker.add(head)
val iterator: MutableListIterator<Coordinate> = tails.listIterator()
var last = head
while (iterator.hasNext()) {
val current = iterator.next()
val delta = last.delta(current)
val distanceX = last.distanceX(current)
val distanceY = last.distanceY(current)
/*
Welp this whole if statement was a roller coaster to fix...
It used to be `if (distanceX + distanceY == 3)`. Leftover from part 1
But the distance can be more than 3 now as well with the extra tails!
This is because the tails are able to move diagonal, so if it moves away diagonally,
the distance becomes 4.
At least I got to write a nifty way of printing the board state and add a debug mode :')
*/
val newLocation = if (distanceX + distanceY >= 3) {
current.moveX(delta.x.sign).moveY(delta.y.sign)
} else if (distanceX == 2) {
current.moveX(delta.x.sign)
} else if (distanceY == 2) {
current.moveY(delta.y.sign)
} else {
current
}
last = newLocation
iterator.set(newLocation)
}
tracker.add(tails.last)
if (debug) {
println("\n\n\n")
println(gameState.stateToString(10))
println("Waiting for user input...")
Scanner(System.`in`).nextLine()
}
}
}
}
parseCommands(input).forEach {
move(it)
}
// println(gameState.stateToString(150))
return gameState.tracker.size
}
val test = """
R 4
U 4
L 3
D 1
R 4
D 1
L 5
R 2
""".trimIndent().lines()
val test2 = """
R 5
U 8
L 8
D 3
R 17
D 10
L 25
U 20
""".trimIndent().lines()
println(part1(test))
println(part1(readInput("Day09")))
println(part2(test))
println(part2(test2))
println(part2(readInput("Day09")))
}
| 0 | Kotlin | 0 | 0 | 363747c25efb002fe118e362fb0c7fecb02e3708 | 7,431 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/day15.kt | tianyu | 574,561,581 | false | {"Kotlin": 49942} | import assertk.assertThat
import assertk.assertions.*
import kotlin.math.absoluteValue
private fun main() {
tests {
val sensors = sensors("day15-example.txt")
"Read sensors" {
assertThat(sensors).containsAll(
Sensor(2, 18, -2, 15),
Sensor(10, 20, 10, 16),
Sensor(0, 11, 2, 10),
Sensor(20, 1, 15, 3),
)
}
"Sensor range" {
assertThat(Sensor(9, 16, 10, 16).range).isEqualTo(1)
assertThat(Sensor(8, 7, 2, 10).range).isEqualTo(9)
}
"Sensor coverage" {
val sensor = Sensor(8, 7, 2, 10)
assertThat(sensor.coverage(10)).isEqualTo(2..14)
assertThat(sensor.coverage(7)).isEqualTo(-1..17)
assertThat(sensor.coverage(16)).isEqualTo(8..8)
assertThat(sensor.coverage(-2)).isEqualTo(8..8)
assertThat(sensor.coverage(-3)).isEmpty()
assertThat(sensor.coverage(17)).isEmpty()
}
"Part 1 Example" {
assertThat(sensors.totalCoverage(10)).isEqualTo(26)
}
"Inverting a range" {
assertThat((0..100) - listOf()).containsExactly(0..100)
assertThat((0..100) - listOf(-3..-1)).containsExactly(0..100)
assertThat((0..100) - listOf(101..105)).containsExactly(0..100)
assertThat((0..100) - listOf(0..50)).containsExactly(51..100)
assertThat((0..100) - listOf(80..100)).containsExactly(0..79)
assertThat((0..100) - listOf(0..100)).isEmpty()
assertThat((0..100) - listOf(-5..20, 70..110)).containsExactly(21..69)
assertThat((0..100) - listOf(25..49, 76..99)).containsExactly(0..24, 50..75, 100..100)
assertThat((0..100) - listOf(0..15, 18..30, 96..105)).containsExactly(16..17, 31..95)
}
"Part 2 Example" {
assertThat(sensors.findBeaconOptions(0..20, 0..20)).containsOnly(14 to 11)
}
}
val sensors = sensors()
part1("The number of positions that cannot contain a beacon at y=2000000 is:") {
sensors.totalCoverage(2_000_000)
}
part2("The tuning frequency of the distress beacon is:") {
val size = 4_000_000
val (x, y) = sensors.findBeaconOptions(0..size, 0..size).first()
x.toLong() * size + y.toLong()
}
}
private data class Sensor(val x: Int, val y: Int, val beaconX: Int, val beaconY: Int) {
val range = (x - beaconX).absoluteValue + (y - beaconY).absoluteValue
fun coverage(lineY: Int): IntRange {
// find lineX where:
// |x - lineX| + |y - lineY| <= range
// |x - lineX| <= range - |y - lineY|
val k = range - (y - lineY).absoluteValue
// lineX - x <= k and x - lineX <= k
// lineX <= x + k and lineX >= x - k
// x - k <= lineX <= x + k
return x - k .. x + k
}
}
private fun List<Sensor>.totalCoverage(lineY: Int): Int {
val beacons = mapNotNullTo(mutableSetOf()) { if (it.beaconY == lineY) it.beaconX else null }
return asSequence()
.map { it.coverage(lineY) }
.coalesce()
.sumOf { it.size - beacons.count(it::contains) }
}
private fun List<Sensor>.findBeaconOptions(xrange: IntRange, yrange: IntRange): Set<Pair<Int, Int>> {
val beacons = mapTo(mutableSetOf()) { it.beaconX to it.beaconY }
val options = yrange.asSequence().flatMapTo(mutableSetOf()) { y ->
val coverage = asSequence().map { it.coverage(y) }.sortedBy { it.first }.coalesce()
val options = xrange - coverage
options.flatMap { xs ->
xs.map { x -> x to y }
}
}
return options - beacons
}
private fun Sequence<IntRange>.coalesce() = buildList<IntRange> {
val ranges = this@coalesce.iterator()
if (!ranges.hasNext()) return@buildList
add(ranges.next())
for (range in ranges) {
when {
range.isEmpty() -> continue
range.first in last() -> set(lastIndex, last().first..maxOf(last().last, range.last))
else -> add(range)
}
}
}
private operator fun IntRange.minus(ranges: List<IntRange>) = buildList {
addInversions(this@minus, ranges.iterator())
}
private tailrec fun MutableList<IntRange>.addInversions(outer: IntRange, inner: Iterator<IntRange>) {
if (outer.isEmpty()) return
if (!inner.hasNext()) add(outer).also { return }
val next = inner.next()
if (outer.first < next.first) {
add(outer.first..minOf(outer.last, next.first - 1))
}
addInversions(next.last + 1..outer.last, inner)
}
private fun sensors(resource: String = "day15.txt") = buildList {
withInputLines(resource) {
this@withInputLines.forEach { line ->
val (sensorX, sensorY, beaconX, beaconY) = Regex("-?\\d+").findAll(line)
.map { it.value.toInt() }.toList()
add(Sensor(sensorX, sensorY, beaconX, beaconY))
}
}
sortBy { sensor: Sensor -> sensor.x - sensor.range }
} | 0 | Kotlin | 0 | 0 | 6144cc0ccf1a51ba2e28c9f38ae4e6dd4c0dc1ea | 4,597 | AdventOfCode2022 | MIT License |
src/com/zypus/SLIP/algorithms/SpringEvolution.kt | zypus | 213,665,750 | false | null | package com.zypus.SLIP.algorithms
import com.zypus.SLIP.algorithms.genetic.Selection
import com.zypus.SLIP.algorithms.genetic.Selections
import com.zypus.SLIP.algorithms.genetic.builder.evolution
import com.zypus.SLIP.algorithms.genetic.crossover
import com.zypus.SLIP.algorithms.genetic.mutate
import com.zypus.SLIP.controllers.SimulationController
import com.zypus.SLIP.models.*
import java.util.*
/**
* TODO Add description
*
* @author fabian <<EMAIL>>
*
* @created 03/03/16
*/
class SpringEvolution(val initial: Initial, val environment: Environment, val setting: SimulationSetting) {
val evolutionRule = evolution<Long, SpringController, Double, HashMap<Any,Double>, Environment, Environment, Double, HashMap<Any, Double>> {
solution = {
initialize = { (2 * (Math.random() - 0.5) * Long.MAX_VALUE).toLong() }
mapping = { gen ->
val f = (gen.toDouble() / 0x3fffffffffffffffL)
SpringController ({ slip -> f * slip.velocity.x + 0.1 }) }
select = { population ->
val picked = Selections.elitist(population, 10) {
(it.behaviour as HashMap<*, *>).values.sumByDouble { it as Double }
}
val toBeReplaced = population.filter { e -> !picked.contains(e) }
Selection(toBeReplaced.size, (0..4).map { picked[2 * it] to picked[2 * it + 1] }, toBeReplaced)
}
reproduce = { mother, father ->
mother.crossover(father, 1.0).mutate(1.0)
}
behaviour = {
initialize = { hashMapOf() }
store = { e,o,b -> e[o.genotype] = b; e }
remove = {e,o -> e.remove(o.genotype); e}
}
}
singularProblem = environment
test = {
match = {
evolutionState ->
evolutionState.solutions.flatMap { s -> evolutionState.problems.map { p -> s to p } }
}
evaluate = {
controller, environment ->
var state = SimulationState(SLIP(initial).copy(controller = controller), environment)
for (i in 1..10000) {
state = SimulationController.step(state, setting)
if (state.slip.position.y - state.slip.radius <= state.environment.terrain(state.slip.position.x)) break
}
val x = state.slip.position.x
x to x
}
}
}
fun evolve(): SpringController {
var state = evolutionRule.initialize(300, 1)
for (i in 1..100) {
evolutionRule.matchAndEvaluate(state)
state = evolutionRule.selectAndReproduce(state)
}
evolutionRule.matchAndEvaluate(state)
val first = state.solutions.sortedByDescending { (it.behaviour as HashMap<*, *>).values.sumByDouble { it as Double } }.first()
println(state.solutions.first().genotype)
return first.phenotype
}
}
| 0 | Kotlin | 0 | 0 | 418ee8837752143194fd769e86fac85e15136929 | 2,589 | SLIP | MIT License |
leetcode/src/main/kotlin/com/artemkaxboy/leetcode/p10/Leet1034.kt | artemkaxboy | 513,636,701 | false | {"Kotlin": 547181, "Java": 13948} | package com.artemkaxboy.leetcode.p10
import com.artemkaxboy.leetcode.LeetUtils
import java.util.*
/**
* Medium
* Runtime 256ms Beats 100.0%
* Memory 37.7MB Beats 50.00%
*/
class Leet1034 {
class Solution {
private lateinit var grid: Array<IntArray>
private val queue: Queue<Pair<Int, Int>> = LinkedList()
private lateinit var explored: HashSet<Pair<Int, Int>>
private var wantedColor = 0
private val border = LinkedList<Pair<Int, Int>>()
fun colorBorder(grid: Array<IntArray>, row: Int, col: Int, color: Int): Array<IntArray> {
val rows = grid.size
val cols = grid[0].size
val lastRow = rows - 1
val lastCol = cols - 1
wantedColor = grid[row][col]
val item = row to col
explored = HashSet(rows * cols)
explored.add(item)
queue.offer(item)
this.grid = grid
while (queue.isNotEmpty()) {
val (iRow, iCol) = queue.poll()
if (iRow > 0) addToQueueIfNeeded(iRow - 1, iCol)
if (iRow < lastRow) addToQueueIfNeeded(iRow + 1, iCol)
if (iCol > 0) addToQueueIfNeeded(iRow, iCol - 1)
if (iCol < lastCol) addToQueueIfNeeded(iRow, iCol + 1)
if (iRow == 0 || iRow == lastRow || iCol == 0 || iCol == lastCol) border.add(iRow to iCol)
else if (
grid[iRow - 1][iCol] != wantedColor || grid[iRow + 1][iCol] != wantedColor
|| grid[iRow][iCol - 1] != wantedColor || grid[iRow][iCol + 1] != wantedColor
)
border.add(iRow to iCol)
}
while (border.isNotEmpty()) {
val (r, c) = border.poll()
grid[r][c] = color
}
return grid
}
private fun addToQueueIfNeeded(row: Int, col: Int) {
val item = row to col
if (!explored.contains(item)) {
explored.add(item)
if (grid[row][col] == wantedColor) {
queue.offer(item)
}
}
}
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
val testCase1 = Data(
"[[1,1],[1,2]]".split("],[").map { LeetUtils.stringToIntArray(it) }.toTypedArray(),
0, 0, 3,
"[[3,3],[3,2]]",
)
// doWork(testCase1)
val testCase2 = Data(
"[[1,1,1],[1,1,1],[1,1,1]]".split("],[").map { LeetUtils.stringToIntArray(it) }.toTypedArray(),
1, 1, 2,
"[[2,2,2],[2,1,2],[2,2,2]]",
)
// doWork(testCase2)
val testCase3 = Data(
"[[1,1,1],[0,1,1],[1,1,1]]".split("],[").map { LeetUtils.stringToIntArray(it) }.toTypedArray(),
1, 1, 2,
"[[2,2,2],[0,2,2],[2,2,2]]",
)
// doWork(testCase3)
val testCase4 = Data(
"[[1,2,1,2,1,2],[2,2,2,2,1,2],[1,2,2,2,1,2]]".split("],[").map { LeetUtils.stringToIntArray(it) }
.toTypedArray(),
1, 3, 1,
"[[1,1,1,1,1,2],[1,2,1,1,1,2],[1,1,1,1,1,2]]",
)
doWork(testCase4)
}
private fun doWork(data: Data) {
val solution = Solution()
val result = solution.colorBorder(data.grid, data.row, data.col, data.color)
val stringResult = result.joinToString(",", "[", "]") { it.joinToString(",", "[", "]") }
println("Data: $data")
println("Result: $stringResult\n")
// assert(stringResult == data.expected)
if (stringResult != data.expected) throw RuntimeException("Unexpected result\nwanted: ${data.expected}\n got: $stringResult")
}
}
data class Data(
val grid: Array<IntArray>,
val row: Int,
val col: Int,
val color: Int,
val expected: String,
)
}
| 0 | Kotlin | 0 | 0 | 516a8a05112e57eb922b9a272f8fd5209b7d0727 | 4,106 | playground | MIT License |
openrndr-math/src/main/kotlin/org/openrndr/math/Equations.kt | ericyd | 308,041,887 | true | {"Kotlin": 1389413, "Java": 759791, "ANTLR": 9333, "CSS": 4706, "GLSL": 1846, "Shell": 548} | package org.openrndr.math
private const val DISCRIMINANT_EPSILON = 1e-10
private const val SOLUTION_EPSILON = 1e-8
private val MACHINE_EPSILON = Math.ulp(1.0)
private const val EPSILON = 1e-14
// adapted from https://github.com/paperjs/paper.js/blob/develop/src/util/Numerical.js
// converted from Artifex Equations.java
private fun trim(acc: DoubleArray, len: Int): DoubleArray {
return if (len == acc.size) {
acc
} else if (len == 0) {
DoubleArray(0)
} else {
val result = DoubleArray(len)
System.arraycopy(acc, 0, result, 0, len)
result
}
}
private fun split(n: Double): DoubleArray {
val x = n * 134217729
val y = n - x
val hi = y + x
val lo = n - hi
return doubleArrayOf(hi, lo)
}
private fun discriminant(a: Double, b: Double, c: Double): Double {
var D = b * b - a * c
val E = b * b + a * c
if (StrictMath.abs(D) * 3 < E) {
val ad: DoubleArray = split(a)
val bd: DoubleArray = split(b)
val cd: DoubleArray = split(c)
val p = b * b
val dp = bd[0] * bd[0] - p + 2 * bd[0] * bd[1] + bd[1] * bd[1]
val q = a * c
val dq = ad[0] * cd[0] - q + ad[0] * cd[1] + ad[1] * cd[0] + ad[1] * cd[1]
D = p - q + (dp - dq)
}
return D
}
fun solveLinear(a: Double, b: Double, acc: DoubleArray): Int {
return if (StrictMath.abs(a) < EPSILON) {
0
} else {
acc[0] = -b / a
1
}
}
fun solveLinear(a: Double, b: Double): DoubleArray {
val acc = DoubleArray(1)
return trim(acc, solveLinear(a, b, acc))
}
fun solveQuadratic(a: Double, b: Double, c: Double, acc: DoubleArray): Int {
var a = a
var b = b
var c = c
if (StrictMath.abs(a) < EPSILON) {
return solveLinear(b, c, acc)
}
b *= -0.5
val k: Double = normalizationFactor(a, b, c)
a *= k
b *= k
c *= k
val D = discriminant(a, b, c)
return if (D >= -DISCRIMINANT_EPSILON) {
val Q: Double = if (D < 0) 0.0 else StrictMath.sqrt(D)
val R = b + if (b < 0) -Q else Q
if (R == 0.0) {
acc[0] = c / a
acc[1] = -c / a
} else {
acc[0] = R / a
acc[1] = c / R
}
var writeIdx = 0
for (readIdx in 0..1) {
val x = acc[readIdx]
// since the tolerance for the discriminant is fairly large, we check our work
val y = a * x * x + -2 * b * x + c
if (StrictMath.abs(y) < SOLUTION_EPSILON) {
acc[writeIdx++] = x
}
}
writeIdx
} else {
0
}
}
fun solveQuadratic(a: Double, b: Double, c: Double): DoubleArray {
val acc = DoubleArray(2)
return trim(acc, solveQuadratic(a, b, c, acc))
}
fun solveCubic(a: Double, b: Double, c: Double, d: Double, acc: DoubleArray): Int {
var a = a
var b = b
var c = c
var d = d
val k: Double = normalizationFactor(a, b, c, d)
a *= k
b *= k
c *= k
d *= k
var x: Double
var b1: Double
var c2: Double
var qd: Double
var q: Double
if (StrictMath.abs(a) < EPSILON) {
return solveQuadratic(b, c, d, acc)
} else if (StrictMath.abs(d) < EPSILON) {
b1 = b
c2 = c
x = 0.0
} else {
x = -(b / a) / 3
b1 = a * x + b
c2 = b1 * x + c
qd = (a * x + b1) * x + c2
q = c2 * x + d
val t = q / a
val r = StrictMath.pow(StrictMath.abs(t), 1 / 3.0)
val s = if (t < 0) (-1).toDouble() else 1.toDouble()
val td = -qd / a
val rd = if (td > 0) 1.324717957244746 * StrictMath.max(r, StrictMath.sqrt(td)) else r
var x0 = x - s * rd
if (x0 != x) {
do {
x = x0
b1 = a * x + b
c2 = b1 * x + c
qd = (a * x + b1) * x + c2
q = c2 * x + d
x0 = if (qd == 0.0) x else x - q / (qd / (1 + MACHINE_EPSILON))
} while (s * x0 > s * x)
if (StrictMath.abs(a) * x * x > StrictMath.abs(d / x)) {
c2 = -d / x
b1 = (c2 - c) / x
}
}
}
var solutions: Int = solveQuadratic(a, b1, c2, acc)
for (i in 0 until solutions) {
if (acc[i] == x) {
return solutions
}
}
val y = a * x * x * x + b * x * x + c * x + d
if (StrictMath.abs(y) < SOLUTION_EPSILON) {
acc[solutions++] = x
}
return solutions
}
fun solveCubic(a: Double, b: Double, c: Double, d: Double): DoubleArray {
val acc = DoubleArray(3)
return trim(acc, solveCubic(a, b, c, d, acc))
} | 0 | Kotlin | 0 | 0 | 504c91db41658c3c6d464e4b60f9f017096c0f6d | 4,669 | openrndr | BSD 2-Clause FreeBSD License |
Cyclotomic_Polynomial/Kotlin/src/CyclotomicPolynomial.kt | ncoe | 108,064,933 | false | {"D": 425100, "Java": 399306, "Visual Basic .NET": 343987, "C++": 328611, "C#": 289790, "C": 216950, "Kotlin": 162468, "Modula-2": 148295, "Groovy": 146721, "Lua": 139015, "Ruby": 84703, "LLVM": 58530, "Python": 46744, "Scala": 43213, "F#": 21133, "Perl": 13407, "JavaScript": 6729, "CSS": 453, "HTML": 409} | import java.util.TreeMap
import kotlin.math.abs
import kotlin.math.pow
import kotlin.math.sqrt
private const val algorithm = 2
fun main() {
println("Task 1: cyclotomic polynomials for n <= 30:")
for (i in 1..30) {
val p = cyclotomicPolynomial(i)
println("CP[$i] = $p")
}
println()
println("Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:")
var n = 0
for (i in 1..10) {
while (true) {
n++
val cyclo = cyclotomicPolynomial(n)
if (cyclo!!.hasCoefficientAbs(i)) {
println("CP[$n] has coefficient with magnitude = $i")
n--
break
}
}
}
}
private val COMPUTED: MutableMap<Int, Polynomial> = HashMap()
private fun cyclotomicPolynomial(n: Int): Polynomial? {
if (COMPUTED.containsKey(n)) {
return COMPUTED[n]
}
if (n == 1) {
// Polynomial: x - 1
val p = Polynomial(1, 1, -1, 0)
COMPUTED[1] = p
return p
}
val factors = getFactors(n)
if (factors.containsKey(n)) {
// n prime
val termList: MutableList<Term> = ArrayList()
for (index in 0 until n) {
termList.add(Term(1, index.toLong()))
}
val cyclo = Polynomial(termList)
COMPUTED[n] = cyclo
return cyclo
} else if (factors.size == 2 && factors.containsKey(2) && factors[2] == 1 && factors.containsKey(n / 2) && factors[n / 2] == 1) {
// n = 2p
val prime = n / 2
val termList: MutableList<Term> = ArrayList()
var coeff = -1
for (index in 0 until prime) {
coeff *= -1
termList.add(Term(coeff.toLong(), index.toLong()))
}
val cyclo = Polynomial(termList)
COMPUTED[n] = cyclo
return cyclo
} else if (factors.size == 1 && factors.containsKey(2)) {
// n = 2^h
val h = factors[2]!!
val termList: MutableList<Term> = ArrayList()
termList.add(Term(1, 2.0.pow((h - 1).toDouble()).toLong()))
termList.add(Term(1, 0))
val cyclo = Polynomial(termList)
COMPUTED[n] = cyclo
return cyclo
} else if (factors.size == 1 && !factors.containsKey(n)) {
// n = p^k
var p = 0
for (prime in factors.keys) {
p = prime
}
val k = factors[p]!!
val termList: MutableList<Term> = ArrayList()
for (index in 0 until p) {
termList.add(Term(1, (index * p.toDouble().pow(k - 1.toDouble()).toInt()).toLong()))
}
val cyclo = Polynomial(termList)
COMPUTED[n] = cyclo
return cyclo
} else if (factors.size == 2 && factors.containsKey(2)) {
// n = 2^h * p^k
var p = 0
for (prime in factors.keys) {
if (prime != 2) {
p = prime
}
}
val termList: MutableList<Term> = ArrayList()
var coeff = -1
val twoExp = 2.0.pow((factors[2]!!) - 1.toDouble()).toInt()
val k = factors[p]!!
for (index in 0 until p) {
coeff *= -1
termList.add(Term(coeff.toLong(), (index * twoExp * p.toDouble().pow(k - 1.toDouble()).toInt()).toLong()))
}
val cyclo = Polynomial(termList)
COMPUTED[n] = cyclo
return cyclo
} else if (factors.containsKey(2) && n / 2 % 2 == 1 && n / 2 > 1) {
// CP(2m)[x] = CP(-m)[x], n odd integer > 1
val cycloDiv2 = cyclotomicPolynomial(n / 2)
val termList: MutableList<Term> = ArrayList()
for (term in cycloDiv2!!.polynomialTerms) {
termList.add(if (term.exponent % 2 == 0L) term else term.negate())
}
val cyclo = Polynomial(termList)
COMPUTED[n] = cyclo
return cyclo
}
// General Case
return when (algorithm) {
0 -> {
// Slow - uses basic definition.
val divisors = getDivisors(n)
// Polynomial: ( x^n - 1 )
var cyclo = Polynomial(1, n, -1, 0)
for (i in divisors) {
val p = cyclotomicPolynomial(i)
cyclo = cyclo.divide(p)
}
COMPUTED[n] = cyclo
cyclo
}
1 -> {
// Faster. Remove Max divisor (and all divisors of max divisor) - only one divide for all divisors of Max Divisor
val divisors = getDivisors(n)
var maxDivisor = Int.MIN_VALUE
for (div in divisors) {
maxDivisor = maxDivisor.coerceAtLeast(div)
}
val divisorsExceptMax: MutableList<Int> = ArrayList()
for (div in divisors) {
if (maxDivisor % div != 0) {
divisorsExceptMax.add(div)
}
}
// Polynomial: ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor
var cyclo = Polynomial(1, n, -1, 0).divide(Polynomial(1, maxDivisor, -1, 0))
for (i in divisorsExceptMax) {
val p = cyclotomicPolynomial(i)
cyclo = cyclo.divide(p)
}
COMPUTED[n] = cyclo
cyclo
}
2 -> {
// Fastest
// Let p ; q be primes such that p does not divide n, and q q divides n.
// Then CP(np)[x] = CP(n)[x^p] / CP(n)[x]
var m = 1
var cyclo = cyclotomicPolynomial(m)
val primes = factors.keys.toMutableList()
primes.sort()
for (prime in primes) {
// CP(m)[x]
val cycloM = cyclo
// Compute CP(m)[x^p].
val termList: MutableList<Term> = ArrayList()
for (t in cycloM!!.polynomialTerms) {
termList.add(Term(t.coefficient, t.exponent * prime))
}
cyclo = Polynomial(termList).divide(cycloM)
m *= prime
}
// Now, m is the largest square free divisor of n
val s = n / m
// Compute CP(n)[x] = CP(m)[x^s]
val termList: MutableList<Term> = ArrayList()
for (t in cyclo!!.polynomialTerms) {
termList.add(Term(t.coefficient, t.exponent * s))
}
cyclo = Polynomial(termList)
COMPUTED[n] = cyclo
cyclo
}
else -> {
throw RuntimeException("ERROR 103: Invalid algorithm.")
}
}
}
private fun getDivisors(number: Int): List<Int> {
val divisors: MutableList<Int> = ArrayList()
val sqrt = sqrt(number.toDouble()).toLong()
for (i in 1..sqrt) {
if (number % i == 0L) {
divisors.add(i.toInt())
val div = (number / i).toInt()
if (div.toLong() != i && div != number) {
divisors.add(div)
}
}
}
return divisors
}
private fun crutch(): MutableMap<Int, Map<Int, Int>> {
val allFactors: MutableMap<Int, Map<Int, Int>> = TreeMap()
val factors: MutableMap<Int, Int> = TreeMap()
factors[2] = 1
allFactors[2] = factors
return allFactors
}
private val allFactors = crutch()
var MAX_ALL_FACTORS = 100000
fun getFactors(number: Int): Map<Int, Int> {
if (allFactors.containsKey(number)) {
return allFactors[number]!!
}
val factors: MutableMap<Int, Int> = TreeMap()
if (number % 2 == 0) {
val factorsDivTwo = getFactors(number / 2)
factors.putAll(factorsDivTwo)
factors.merge(2, 1) { a: Int?, b: Int? -> Integer.sum(a!!, b!!) }
if (number < MAX_ALL_FACTORS) allFactors[number] = factors
return factors
}
val sqrt = sqrt(number.toDouble()).toLong()
var i = 3
while (i <= sqrt) {
if (number % i == 0) {
factors.putAll(getFactors(number / i))
factors.merge(i, 1) { a: Int?, b: Int? -> Integer.sum(a!!, b!!) }
if (number < MAX_ALL_FACTORS) {
allFactors[number] = factors
}
return factors
}
i += 2
}
factors[number] = 1
if (number < MAX_ALL_FACTORS) {
allFactors[number] = factors
}
return factors
}
private class Polynomial {
val polynomialTerms: MutableList<Term>
// Format - coeff, exp, coeff, exp, (repeating in pairs) . . .
constructor(vararg values: Int) {
require(values.size % 2 == 0) { "ERROR 102: Polynomial constructor. Length must be even. Length = " + values.size }
polynomialTerms = mutableListOf()
var i = 0
while (i < values.size) {
val t = Term(values[i].toLong(), values[i + 1].toLong())
polynomialTerms.add(t)
i += 2
}
polynomialTerms.sortWith(TermSorter())
}
constructor() {
// zero
polynomialTerms = ArrayList()
polynomialTerms.add(Term(0, 0))
}
fun hasCoefficientAbs(coeff: Int): Boolean {
for (term in polynomialTerms) {
if (abs(term.coefficient) == coeff.toLong()) {
return true
}
}
return false
}
constructor(termList: MutableList<Term>) {
if (termList.isEmpty()) {
// zero
termList.add(Term(0, 0))
} else {
// Remove zero terms if needed
termList.removeIf { t -> t.coefficient == 0L }
}
if (termList.size == 0) {
// zero
termList.add(Term(0, 0))
}
polynomialTerms = termList
polynomialTerms.sortWith(TermSorter())
}
fun divide(v: Polynomial?): Polynomial {
var q = Polynomial()
var r = this
val lcv = v!!.leadingCoefficient()
val dv = v.degree()
while (r.degree() >= v.degree()) {
val lcr = r.leadingCoefficient()
val s = lcr / lcv // Integer division
val term = Term(s, r.degree() - dv)
q = q.add(term)
r = r.add(v.multiply(term.negate()))
}
return q
}
fun add(polynomial: Polynomial): Polynomial {
val termList: MutableList<Term> = ArrayList()
var thisCount = polynomialTerms.size
var polyCount = polynomial.polynomialTerms.size
while (thisCount > 0 || polyCount > 0) {
val thisTerm = if (thisCount == 0) null else polynomialTerms[thisCount - 1]
val polyTerm = if (polyCount == 0) null else polynomial.polynomialTerms[polyCount - 1]
when {
thisTerm == null -> {
termList.add(polyTerm!!.clone())
polyCount--
}
polyTerm == null -> {
termList.add(thisTerm.clone())
thisCount--
}
thisTerm.degree() == polyTerm.degree() -> {
val t = thisTerm.add(polyTerm)
if (t.coefficient != 0L) {
termList.add(t)
}
thisCount--
polyCount--
}
thisTerm.degree() < polyTerm.degree() -> {
termList.add(thisTerm.clone())
thisCount--
}
else -> {
termList.add(polyTerm.clone())
polyCount--
}
}
}
return Polynomial(termList)
}
fun add(term: Term): Polynomial {
val termList: MutableList<Term> = ArrayList()
var added = false
for (currentTerm in polynomialTerms) {
if (currentTerm.exponent == term.exponent) {
added = true
if (currentTerm.coefficient + term.coefficient != 0L) {
termList.add(currentTerm.add(term))
}
} else {
termList.add(currentTerm.clone())
}
}
if (!added) {
termList.add(term.clone())
}
return Polynomial(termList)
}
fun multiply(term: Term): Polynomial {
val termList: MutableList<Term> = ArrayList()
for (currentTerm in polynomialTerms) {
termList.add(currentTerm.clone().multiply(term))
}
return Polynomial(termList)
}
fun leadingCoefficient(): Long {
return polynomialTerms[0].coefficient
}
fun degree(): Long {
return polynomialTerms[0].exponent
}
override fun toString(): String {
val sb = StringBuilder()
var first = true
for (term in polynomialTerms) {
if (first) {
sb.append(term)
first = false
} else {
sb.append(" ")
if (term.coefficient > 0) {
sb.append("+ ")
sb.append(term)
} else {
sb.append("- ")
sb.append(term.negate())
}
}
}
return sb.toString()
}
}
private class TermSorter : Comparator<Term> {
override fun compare(o1: Term, o2: Term): Int {
return (o2.exponent - o1.exponent).toInt()
}
}
// Note: Cyclotomic Polynomials have small coefficients. Not appropriate for general polynomial usage.
private class Term(var coefficient: Long, var exponent: Long) {
fun clone(): Term {
return Term(coefficient, exponent)
}
fun multiply(term: Term): Term {
return Term(coefficient * term.coefficient, exponent + term.exponent)
}
fun add(term: Term): Term {
if (exponent != term.exponent) {
throw RuntimeException("ERROR 102: Exponents not equal.")
}
return Term(coefficient + term.coefficient, exponent)
}
fun negate(): Term {
return Term(-coefficient, exponent)
}
fun degree(): Long {
return exponent
}
override fun toString(): String {
if (coefficient == 0L) {
return "0"
}
if (exponent == 0L) {
return "" + coefficient
}
if (coefficient == 1L) {
return if (exponent == 1L) {
"x"
} else {
"x^$exponent"
}
}
return if (exponent == 1L) {
coefficient.toString() + "x"
} else coefficient.toString() + "x^" + exponent
}
}
| 0 | D | 0 | 4 | c2a9f154a5ae77eea2b34bbe5e0cc2248333e421 | 14,482 | rosetta | MIT License |
src/main/kotlin/ru/glukhov/aoc/Day10.kt | cobaku | 576,736,856 | false | {"Kotlin": 25268} | package ru.glukhov.aoc
import java.io.BufferedReader
fun main() {
val microcode = Problem.forDay("day10").use { parseMicrocode(it) }
println("Result of the first problem: ${first(microcode)}")
println("Result of the first problem:\n ${second(microcode)}")
}
private fun first(microcode: List<Pair<Operation, Int>>): Int {
val powers = mutableListOf<Int>()
execute(microcode) { register, cycle ->
if (cycle % 20 == 0) {
powers.add(cycle * register)
}
}
return powers[0] + powers[2] + powers[4] + powers[6] + powers[8] + powers[10]
}
private fun second(microcode: List<Pair<Operation, Int>>): String {
val builder = StringBuilder()
execute(microcode) { register, cycle ->
if (cycle % 40 == 0) {
builder.append("\n")
}
if (isPixelInSprite(cycle - 1, register)) {
builder.append("#")
} else {
builder.append(".")
}
}
return builder.toString()
}
private fun execute(microcode: List<Pair<Operation, Int>>, state: (register: Int, cycle: Int) -> Unit) {
var cycle = 1
var operationCycle = 1
var register = 1
var index = 0
var operation = microcode[index]
while (microcode.size - 1 > index) {
state(register, cycle)
if (operation.first == Operation.NOOP) {
operation = microcode[++index]
operationCycle = 1
} else {
if (operationCycle == 2) {
register += operation.second
operation = microcode[++index]
operationCycle = 1
} else {
operationCycle++
}
}
cycle++
}
}
private fun isPixelInSprite(pixel: Int, spriteMiddle: Int): Boolean {
val normalizedPixel = pixel % 40
return normalizedPixel >= spriteMiddle - 1 && normalizedPixel <= spriteMiddle + 1
}
private fun parseMicrocode(reader: BufferedReader): List<Pair<Operation, Int>> = reader.lines()
.map {
if (it == "noop") {
return@map Pair(Operation.NOOP, 0)
} else {
return@map Pair(Operation.ADDX, it.split(" ").let { s -> Integer.valueOf(s[1]) })
}
}
.toList()
private enum class Operation {
NOOP,
ADDX
} | 0 | Kotlin | 0 | 0 | a40975c1852db83a193c173067aba36b6fe11e7b | 2,304 | aoc2022 | MIT License |
capitulo5/src/main/kotlin/5.8TaxadeEstacionamento.kt | Cursos-Livros | 667,537,024 | false | {"Kotlin": 104564} | //5.8 (Taxa de estacionamento) Um estacionamento cobra uma taxa mínima de $ 2,00 para estacionar até três
//horas. A garagem cobra um adicional de US$ 0,50 por hora para cada hora ou parte dela além de três
//horas. A cobrança máxima para qualquer período de 24 horas é de US$ 10,00. Suponha que não haja estacionamento para
//mais de 24 horas seguidas. Escreva um aplicativo que calcule e exiba as taxas de estacionamento
//para cada cliente que estacionou na garagem ontem. Você deve inserir as horas estacionadas para cada
//cliente. O programa deve exibir a cobrança do cliente atual e deve calcular e
//exibir o total acumulado dos recebimentos de ontem. Ele deve usar o método calculateCharges para determinar a cobrança de cada cliente.
fun main(args: Array<String>) {
println("Quantidade de carros estacionada ontem:")
val input = readLine() ?: "0"
val quantidadeCarros = input.toInt()
var totalRecebidoOntem = 0.0
for (i in 1..quantidadeCarros) {
val horas = calculaHoras()
println("O cliente $i ficou $horas hora")
val totalRecebido = totalRecebido(horas)
println("Valor total: $totalRecebido")
totalRecebidoOntem += totalRecebido
}
println("O tal recebido ontem foi de: $totalRecebidoOntem")
}
fun calculaHoras(): Int {
println("Digite a quantidade horas cliente ficou")
var input = readLine() ?: "0"
val horas = input.toInt()
return horas
}
fun totalRecebido(horas: Int): Double {
var valorTotal = 0.0
if (horas <= 3) {
valorTotal += 2.00
} else {
valorTotal = totalRecebidoMais3horas(horas) + 2.00
}
return valorTotal
}
fun totalRecebidoMais3horas(horas: Int): Double {
var valorTotalMais3 = 0.0
if (horas >= 24) {
valorTotalMais3 = 8.00
return valorTotalMais3
}
for (i in 3..horas) {
valorTotalMais3 += 0.5
}
return valorTotalMais3
}
| 0 | Kotlin | 0 | 0 | f2e005135a62b15360c2a26fb6bc2cbad18812dd | 1,939 | Kotlin-Como-Programar | MIT License |
src/Day01.kt | jwalter | 573,111,342 | false | {"Kotlin": 19975} | fun main() {
fun sumOfEachElf(input: List<String>): MutableList<Int> {
val res = input.fold(mutableListOf<Int>()) { acc, value ->
if (value.isBlank() || acc.isEmpty()) {
acc.add(0)
} else {
acc.add(acc.removeLast() + value.toInt())
}
acc
}
return res
}
fun part1(input: List<String>): Int {
val res = sumOfEachElf(input)
return res.max()
}
fun part2(input: List<String>): Int {
val sums = sumOfEachElf(input)
sums.sortDescending()
return sums.take(3).sum()
}
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 576aeabd297a7d7ee77eca9bb405ec5d2641b441 | 801 | adventofcode2022 | Apache License 2.0 |
src/Day03.kt | felldo | 572,233,925 | false | {"Kotlin": 76496} | fun main() {
val map: Map<String, Int> = 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)
val testInput = readInput("Day03")
val part1 = testInput
.map { Pair(it.substring(0, it.length / 2), it.substring(it.length / 2, it.length)) }
.map {
for (c in it.second.toCharArray()) {
if (it.first.contains(c)) {
return@map map[c.toString()]!!
}
}
return@map 0
}
.filter { it != 0 }
.sum()
println("Part 1: $part1")
val part2 = testInput
.chunked(3)
.map {
for (c in it[0].toCharArray()) {
if (it[1].contains(c) && it[2].contains(c)) {
return@map map[c.toString()]!!
}
}
return@map 0
}
.filter { it != 0 }
.sum()
println("Part 2: $part2")
}
| 0 | Kotlin | 0 | 0 | 0ef7ac4f160f484106b19632cd87ee7594cf3d38 | 1,857 | advent-of-code-kotlin-2022 | Apache License 2.0 |
2021/src/Day06.kt | Bajena | 433,856,664 | false | {"Kotlin": 65121, "Ruby": 14942, "Rust": 1698, "Makefile": 454} | // https://adventofcode.com/2021/day/6
fun main() {
fun part1() {
var fishDays = mutableMapOf<Int, Long>().withDefault { 0 }
val days = 256
val newFishDayCount = 8
val resetFishDayCount = 6
for (line in readInput("Day06")) {
for (fish in line.split(",")) {
fishDays[fish.toInt()] = fishDays.getValue(fish.toInt()) + 1
}
}
for (i in 1..days) {
var newFishDays = mutableMapOf<Int, Long>().withDefault { 0 }
for (days in fishDays.keys) {
if (days == 0) {
newFishDays[resetFishDayCount] = fishDays.getValue(days)
newFishDays[newFishDayCount] = fishDays.getValue(days)
} else {
newFishDays[days - 1] = fishDays.getValue(days) + newFishDays.getValue(days - 1)
}
}
fishDays = newFishDays.toSortedMap()
val total = fishDays.values.sum()
println("After $i days: $total - $fishDays")
}
println(fishDays.values.sum())
}
fun part2() {
}
part1()
part2()
}
| 0 | Kotlin | 0 | 0 | a5ca56b7ac8d9d48f82dc079c8ea0cf06d17109a | 1,010 | advent-of-code | Apache License 2.0 |
app/src/main/kotlin/me/mataha/misaki/util/text/Levenshtein.kt | mataha | 302,513,601 | false | {"Kotlin": 92734, "Gosu": 702, "Batchfile": 104, "Shell": 90} | package me.mataha.misaki.util.text
import me.mataha.misaki.util.functional.assign
import me.mataha.misaki.util.math.min
/**
* Calculates [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance)
* between two character sequences. A higher score indicates a greater distance.
*
* Only deletions, insertions and substitutions are included among its allowable
* operations.
*
* Implementation based on [`unlimitedCompare`](https://github.com/apache/commons-text/blob/master/src/main/java/org/apache/commons/text/similarity/LevenshteinDistance.java#L341-L399)
* from Apache Commons Text (licensed under ASL 2.0).
*/
fun levenshteinDistance(a: CharSequence, b: CharSequence): Int {
var first = a
var second = b
if (first == second) return 0
if (first.isEmpty()) return second.length
if (second.isEmpty()) return first.length
if (first.length > second.length) {
first = assign(second) { second = first }
}
val distances = IntArray(first.length + 1) { index -> index }
for (j in 1..second.length) {
var corner = distances[0]
distances[0] = j
for (i in 1..first.length) {
val upper = distances[i]
val deletion = distances[i - 1] + 1
val insertion = distances[i] + 1
val substitution = corner + if (first[i - 1] == second[j - 1]) 0 else 1
distances[i] = min(deletion, insertion, substitution)
corner = upper
}
}
return distances[first.length]
}
| 0 | Kotlin | 0 | 0 | 748a5b25a39d01b2ffdcc94f1a99a6fbc8a02685 | 1,528 | misaki | MIT License |
src/main/kotlin/advent/Advent7.kt | v3rm0n | 225,866,365 | false | null | package advent
import intcode.Calculator
import java.util.concurrent.LinkedBlockingQueue
class Advent7 : Advent {
override fun firstTask(input: List<String>) = phases(input)
override fun secondTask(input: List<String>): Long {
val intcodes = input.flatMap { it.split(',').map(String::toLong) }
return forUniqueValues(5..9L) { a, b, c, d, e ->
val firstChannel = LinkedBlockingQueue<Long>(1)
firstChannel.put(0L)
val firstCalculator = Calculator(intcodes, a)
val first = firstCalculator.calculate(firstChannel)
val second = Calculator(intcodes, b).calculate(first)
val third = Calculator(intcodes, c).calculate(second)
val fourth = Calculator(intcodes, d).calculate(third)
val fifth = Calculator(intcodes, e).calculate(fourth)
var lastValue = 0L
while (!firstCalculator.halted) {
lastValue = fifth.take()
firstChannel.put(lastValue)
}
lastValue
}
}
private fun phases(input: List<String>): Long {
val intcodes = input.flatMap { it.split(',').map(String::toLong) }
return forUniqueValues(0..4L) { a, b, c, d, e ->
val first = Calculator(intcodes).calculate(listOf(a, 0)).first()
val second = Calculator(intcodes).calculate(listOf(b, first)).first()
val third = Calculator(intcodes).calculate(listOf(c, second)).first()
val fourth = Calculator(intcodes).calculate(listOf(d, third)).first()
Calculator(intcodes).calculate(listOf(e, fourth)).first()
}
}
private fun forUniqueValues(range: LongRange, func: (Long, Long, Long, Long, Long) -> Long): Long {
var largestValue = 0L
for (a in range) {
for (b in range) {
if (a != b) {
for (c in range) {
if (c != b && c != a) {
for (d in range) {
if (d != c && d != b && d != a) {
for (e in range) {
if (e != d && e != b && e != c && e != a) {
val newValue = func(a, b, c, d, e)
if (newValue > largestValue) {
largestValue = newValue
}
}
}
}
}
}
}
}
}
}
return largestValue
}
}
| 0 | Kotlin | 0 | 1 | 5c36cb254100f80a6e9c16adff5e7aadc8c9e98f | 2,761 | aoc2019 | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.