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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
algorithms/src/main/kotlin/com/kotlinground/algorithms/numssameconsecdiff/numssameconsecdiff.kt | BrianLusina | 113,182,832 | false | {"Kotlin": 483489, "Shell": 7283, "Python": 1725} | package com.kotlinground.algorithms.numssameconsecdiff
/**
* Each level contains the numbers that are of the same amount of digits. Also, each level corresponds to the solutions
with a specific number of digits.
level 1: [1, 2, 3, 4, 5, 6, 7, 8, 9]
level 2: [18, 29, 70, 81, 92]
level 3: [181, 292, 707, 818, 929]
For example, given N=3 and K=7, at the first level, we would have potentially 9 candidates
(i.e. [1, 2, 3, 4, 5, 7, 8, 9]). When we move on to the second level, the candidates are reduced down to
[18, 29, 70, 81, 92]. Finally, at the last level, we would have the solutions as [181, 292, 707, 818, 929].
Algorithm
Here are a few steps to implement the BFS algorithm for this problem.
- We could implement the algorithm with nested two-levels loops, where the outer loop iterates through levels and
the inner loop handles the elements within each level.
- We could use a list data structure to keep the numbers for a single level, i.e. here we name the variable as queue
- For each number in the queue, we could apply the same logics as in the DFS approach, except the last step,
rather than making a recursive call for the next number we simply append the number to the queue for the next level.
Complexity Analysis
Let N be the number of digits for a valid combination, and K be the difference between digits.
- Time Complexity: O(2^N)
Essentially with the BFS approach, all the intermeidate candidates form a binary tree, same as the execution
tree as in the DFS approach. Only this time, we traverse in a breadth-first manner, rather than the depth-first.
Therefore, the overall time complexity of the algorithm would be O(2^{N})
- Space Complexity: O(2^{N})
We use two queues to maintain the intermediate solutions, which contain no more than two levels of elements.
The number of elements at the level of i is up to 9 * 2^{i-1}
To sum up, the space complexity of the algorithm would be {O}(9 * 2^{N-1} + 9 * 2^{N-2}) = O(2^N).
*/
@Suppress("NestedBlockDepth", "MagicNumber")
fun numsSameConsecDiff(n: Int, k: Int): IntArray {
if (n == 1) {
return IntRange(0, 9).toList().toIntArray()
}
var queue = IntRange(1, 9).toList().toIntArray()
for (level in 0 until n - 1) {
val nextQueue = mutableListOf<Int>()
for (num in queue) {
val tailDigit = num % 10
// # using set() to avoid duplicates when K == 0
val nextDigits = setOf<Int>(tailDigit + k, tailDigit - k)
for (nextDigit in nextDigits) {
if (nextDigit in 0..9) {
val newNum = num * 10 + nextDigit
nextQueue.add(newNum)
}
}
}
queue = nextQueue.toIntArray()
}
return queue
}
| 1 | Kotlin | 1 | 0 | 5e3e45b84176ea2d9eb36f4f625de89d8685e000 | 2,761 | KotlinGround | MIT License |
codeforces/kotlinheroes8/f.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.kotlinheroes8
fun main() {
val (n, m) = readInts()
val groups = List(2) { mutableListOf<IndexedValue<Int>>() }
repeat(n) {
val (k, t) = readInts()
groups[t - 1].add(IndexedValue(it, k))
}
val groupSum = groups.map { group -> group.sumOf { it.value } }
val can = BooleanArray(m + 1)
val how = Array<IndexedValue<Int>?>(m + 1) { null }
can[0] = true
for (series in groups[1]) for (i in m - series.value downTo 0) {
if (!can[i] || can[i + series.value]) continue
can[i + series.value] = true
how[i + series.value] = series
}
val x = can.indices.firstOrNull { can[it] && maxOf(2 * it - 1, 2 * (groupSum[1] - it)) + groupSum[0] <= m }
?: return println(-1)
val odd = mutableListOf<IndexedValue<Int>>()
var z = x
while (z > 0) z -= how[z]!!.also { odd.add(it) }.value
val ans = IntArray(n)
fun place(list: List<IndexedValue<Int>>, start: Int, gap: Int) {
list.fold(start) { time, series -> (time + series.value * gap).also { ans[series.index] = time } }
}
place(odd, 1, 2)
place(groups[1] - odd, 2, 2)
place(groups[0], m - groupSum[0] + 1, 1)
println(ans.joinToString(" "))
}
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,268 | competitions | The Unlicense |
src/jvmMain/kotlin/day06/initial/Day06.kt | liusbl | 726,218,737 | false | {"Kotlin": 109684} | package day06.initial
import java.io.File
import kotlin.math.*
/**
Time: 7 15 30
Record: 9 40 200
0 -> 0
1 -> (7-1)*1=6
2 -> (7-2)*2=10
3 -> (7-3)*3=12
4 -> (7-4)*4=12
5 -> (7-5)*5=10
6 -> (7-6)*6=6
7 -> 0
formula:
h = hold
f = result time
t = time
d = distance
f = (t - h) * h
f = h*t - h*h
-h^2 + ht - f = 0
h^2 - ht + f = 0
h - ?
x^2 - xt + f = 0
(-b +- sqrt(b^2 - 4ac)) / 2
h = (t + sqrt(t^2 - 4f))/2
h = (t - sqrt(t^2 - 4f))/2
/. Maybe use something like binary search to find the nearest record?
// Otherwise maybe something with calculus?
*/
fun main() {
solvePart1() // Solution: 131376, finished 14:08
// solvePart2() // Solution: 34123437, finished 14:10
}
fun solve(time: Long, record: Long): Long {
val t = time
val f = record
val h1 = (t - sqrt(t.toDouble().pow(2) - 4 * f)) / 2
val h2 = (t + sqrt(t.toDouble().pow(2) - 4 * f)) / 2
val dubiousLength = h2 - h1
val startThing = if (h1.toLong().toDouble() == h1) {
h1.toLong() + 1
} else {
ceil(h1).toLong()
}
val endThing = if (h2.toLong().toDouble() == h2) {
h2.toLong() - 1
} else {
floor(h2).toLong()
}
// (0..t).forEach {
// println("$it -> (${t}-$it)*$it=${(t - it) * it}")
// }
val result = endThing - startThing + 1
println("time: $time, record: $record, h1: $h1, h2: $h2, length: $dubiousLength, startThing: $startThing, endThing: $endThing")
println("result: $result")
println()
return result
}
// 143451 IS NOT RIGHT ANSWER
// 131376 is correct
fun solvePart1() {
// val input = File("src/jvmMain/kotlin/day06/input/input_part1_test.txt")
// val input = File("src/jvmMain/kotlin/day06/input/input.txt")
val input = File("src/jvmMain/kotlin/day06/input/input_part2.txt")
val (timeText, recordText) = input.readLines()
val times = timeText.split(" ").filter { it.isNotBlank() }.map { it.toLong() }
val records = recordText.split(" ").filter { it.isNotBlank() }.map { it.toLong() }
val raceList = times.zip(records) { time, record -> Race(time, record) }
val res = raceList.fold(1L) { acc, race ->
acc * solve(race.time, race.record)
}
println(res)
// val t = 7
// val f = 9
// val h1 = (t - sqrt(t.toDouble().pow(2) - 4 * f)) / 2
// val h2 = (t + sqrt(t.toDouble().pow(2) - 4 * f)) / 2
//
// println("$h1, $h2")
//
// (0..7).forEach {
// println("$it -> (${7}-$it)*$it=${(7 - it) * it}")
// }
// println()
// println()
//
//
// (0..15).forEach {
// println("$it -> (${15}-$it)*$it=${(15 - it) * it}")
// }
// println()
//
// (0..20).forEach {
// println("$it -> (${20}-$it)*$it=${(20 - it) * it}")
// }
val result = "result"
println(raceList)
}
data class Race(
val time: Long,
val record: Long
) | 0 | Kotlin | 0 | 0 | 1a89bcc77ddf9bc503cf2f25fbf9da59494a61e1 | 2,849 | advent-of-code | MIT License |
kotlin/templates-and-commons/src/main/kotlin/NumberTheory.kt | ShreckYe | 345,946,821 | false | null | import kotlin.math.ln
import kotlin.math.sqrt
fun simplePrimesTo(n: Int): List<Int> =
(2..n).filter { i -> (2 until i).all { i % it != 0 } }
val xLnXConst = 30 * ln(113.toDouble()) / 113
fun piXUpperBound(x: Int): Int = run {
require(x >= 2)
// see: https://en.wikipedia.org/wiki/Prime-counting_function#Inequalities
(xLnXConst * x / ln(x.toDouble())).toInt()
}
// check with already computed primes
fun primesToWithCheckWithAlreadyComputedPrimes(n: Int): List<Int> =
ArrayList<Int>(piXUpperBound(n)).apply {
for (i in 2..n) {
val sqrtN = sqrt(i.toDouble()).toInt()
if (asSequence().takeWhile { it <= sqrtN }.none { i % it == 0 })
add(i)
}
trimToSize()
}
fun lazyPrimes(): List<Int> =
TODO()
// see: https://en.wikipedia.org/wiki/Generation_of_primes#Complexity and https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
// see: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Pseudocode
// O(n log(log(n)))
fun primesToWithSOE(n: Int): List<Int> {
// BooleanArray is slightly faster than BitSet
val a = BooleanArray(n + 1) { true }
for (i in 2..sqrt(n.toDouble()).toInt())
if (a[i]) {
var j = i.squared()
while (j <= n) {
a[j] = false
j += i
}
}
return (2..n).filter { a[it] }
}
data class FactorAndNum(val factor: Int, val num: Int)
data class FactorResult<R, N>(val result: R, val remaining: N)
// O(log(factor, n)) = O(log(n))
fun countFactors(n: Long, factor: Int): FactorResult<Int, Long> {
require(n > 0 && factor > 1)
return if (n % factor != 0L) FactorResult(0, n)
else {
val (nNum, remaining) = countFactors(n / factor, factor)
FactorResult(nNum + 1, remaining)
}
}
/*inline class PrimeAndNum(val factorAndNum: FactorAndNum) {
constructor(prime: Int, num: Int) : this(FactorAndNum(prime, num))
val prime inline get() = factorAndNum.factor
val num inline get() = factorAndNum.num
}*/
//typealias PrimeAndNum = FactorAndNum
// O(max(primes.size, log(n)))
fun factorizeWithFactors(n: Long, factors: List<Int>): FactorResult<List<FactorAndNum>, Long> {
@Suppress("NAME_SHADOWING")
var n = n
val pns = ArrayList<FactorAndNum>(factors.size)
for (p in factors) {
val (num, remainingN) = countFactors(n, p)
if (num > 0) {
pns.add(FactorAndNum(p, num))
n = remainingN
if (n == 1L) break
}
}
pns.trimToSize()
return FactorResult(pns, n)
}
// O(sqrt(n) log(log(n)))
fun factorizePrimes(n: Long): List<FactorAndNum> {
require(n <= Int.MAX_VALUE.toLong().squared())
// TODO: maybe use lazy primes here when implemented
val (pns, remaining) = factorizeWithFactors(n, primesToWithSOE(sqrt(n.toDouble()).toInt()))
return if (remaining == 1L) pns
else pns + FactorAndNum(remaining.toInt(), 1)
}
fun recomposeFactors(factorAndNums: List<FactorAndNum>): Long =
factorAndNums.asSequence()
.map { it.factor.toLong() powInt it.num }
.reduceOrNull { a, b -> a * b } ?: 1L
fun recomposeFactors(factorizationResult: FactorResult<List<FactorAndNum>, Long>): Long =
recomposeFactors(factorizationResult.result) * factorizationResult.remaining | 0 | Kotlin | 1 | 1 | 743540a46ec157a6f2ddb4de806a69e5126f10ad | 3,308 | google-code-jam | MIT License |
src/main/kotlin/com/groundsfam/advent/y2023/d15/Day15.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2023.d15
import com.groundsfam.advent.DATAPATH
import com.groundsfam.advent.timed
import kotlin.io.path.div
import kotlin.io.path.readLines
private data class Lens(val label: String, val focalLength: Int)
private fun hash(s: String): Int =
s.fold(0) { curr, c ->
(curr + c.code) * 17 % 256
}
private fun executeHashmap(instructions: List<Instruction>): Long {
val boxes = Array(256) { linkedMapOf<String, Lens>() }
instructions.forEach { ins ->
val box = boxes[hash(ins.label)]
when (ins) {
is Remove -> {
box.remove(ins.label)
}
is Insert -> {
box[ins.label] = Lens(ins.label, ins.focalLength)
}
}
}
return boxes.withIndex().sumOf { (i, box) ->
box.values.foldIndexed(0L) { j, sum, lens ->
sum + (i + 1) * (j + 1) * lens.focalLength
}
}
}
fun main() = timed {
val steps = (DATAPATH / "2023/day15.txt").readLines().first()
.split(",")
steps
.sumOf(::hash)
.also { println("Part one: $it") }
steps
.map(String::parse)
.let(::executeHashmap)
.also { println("Part two: $it") }
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 1,246 | advent-of-code | MIT License |
src/day08/Day08Answer2.kt | IThinkIGottaGo | 572,833,474 | false | {"Kotlin": 72162} | package day08
import readInput
/**
* Answers from [Advent of Code with <NAME> | Day 8](https://youtu.be/6d6FXFh-UdA)
*/
val input = readInput("day08")
fun main() {
val myGameField = GameField.fromLines(input)
println(myGameField.countVisible()) // 1803
println(myGameField.maxScenicScore()) // 268912
}
class GameField(private val field: List<List<Int>>) {
operator fun get(x: Int, y: Int) = field[y][x]
private val fieldWidth = field[0].size
private val fieldHeight = field.size
fun countVisible(): Int {
val visible = sequence {
for (y in 0 until fieldHeight) {
for (x in 0 until fieldWidth) {
yield(isVisible(x, y))
}
}
}
return visible.count { it }
}
private fun isVisible(x: Int, y: Int): Boolean {
val treeHeight = get(x, y)
val left = (0 until x)
val right = (x + 1 until fieldWidth)
val top = (0 until y)
val bottom = (y + 1 until fieldHeight)
return x == 0 ||
y == 0 ||
x == fieldWidth - 1 ||
y == fieldHeight - 1 ||
!left.isEmpty() && left.all { get(it, y) < treeHeight } ||
!right.isEmpty() && right.all { get(it, y) < treeHeight } ||
!top.isEmpty() && top.all { get(x, it) < treeHeight } ||
!bottom.isEmpty() && bottom.all { get(x, it) < treeHeight }
}
fun maxScenicScore(): Int {
val scores = sequence {
for (y in 0 until fieldHeight) {
for (x in 0 until fieldWidth) {
yield(scenicScore(x, y))
}
}
}
return scores.max()
}
private fun scenicScore(x: Int, y: Int): Int {
val treeHeight = get(x, y)
if (x == 0 || y == 0 || x == fieldWidth - 1 || y == fieldHeight - 1) return 0
val left = (x - 1 downTo 0)
val leftTrees = left.takeWhile { get(it, y) < treeHeight }.count()
val leftOffset = if (leftTrees < left.count()) 1 else 0
val right = (x + 1 until fieldWidth)
val rightTrees = right.takeWhile { get(it, y) < treeHeight }.count()
val rightOffset = if (rightTrees < right.count()) 1 else 0
val top = (y - 1 downTo 0)
val topTrees = top.takeWhile { get(x, it) < treeHeight }.count()
val topOffset = if (topTrees < top.count()) 1 else 0
val bottom = (y + 1 until fieldHeight)
val bottomTrees = bottom.takeWhile { get(x, it) < treeHeight }.count()
val bottomOffset = if (bottomTrees < bottom.count()) 1 else 0
return (leftTrees + leftOffset) * (rightTrees + rightOffset) * (topTrees + topOffset) * (bottomTrees + bottomOffset)
}
companion object {
fun fromLines(lines: List<String>): GameField {
val filed = List(lines.size) { MutableList(lines[0].length) { 0 } }
for ((y, line) in input.withIndex()) {
for ((x, char) in line.withIndex()) {
filed[y][x] = char.digitToInt()
}
}
return GameField(filed)
}
}
} | 0 | Kotlin | 0 | 0 | 967812138a7ee110a63e1950cae9a799166a6ba8 | 3,207 | advent-of-code-2022 | Apache License 2.0 |
src/algorithmsinanutshell/DijkstraAlgorithm.kt | realpacific | 234,499,820 | false | null | package algorithmsinanutshell
import algorithmdesignmanualbook.padLeft
import java.util.*
import kotlin.test.assertEquals
class DijkstraAlgorithm(val graph: Graph, private val startVertex: Vertex, private val endVertex: Vertex) {
/**
* List containing path:length
*/
private val connections = mutableListOf<Pair<String, Int>>()
private val distance = mutableMapOf<Graph.Vertex, Int>()
init {
graph.getAllNodes().forEach {
if (startVertex != it) {
distance[it] = Integer.MAX_VALUE
} else {
distance[startVertex] = 0
}
}
}
private fun relaxVertex(queue: LinkedList<Vertex>, vertex: Vertex) {
val currentWeight = distance[vertex]!!
vertex.edges.forEach {
val end = it.endVertex
val costOfPath = it.weight!!
if (distance[end]!! > currentWeight + costOfPath) {
distance[end] = currentWeight + costOfPath
queue.addLast(it.endVertex)
}
}
}
fun execute(): Pair<String, Int> {
val queue = LinkedList<Graph.Vertex>()
queue.addLast(startVertex)
while (queue.isNotEmpty()) {
val first = queue.removeFirst()
relaxVertex(queue, first)
println(first.value.toString() + ": " + distance[first])
}
println("Min distance from start to end vertex is ${distance[endVertex]}")
// Above LOC finds best distance from start vertex
// To find the path that has best distance, we have to do Depth first traversal
depthFirstTraversal(startVertex, Stack<Vertex>().also { it.add(startVertex) }, 0)
println("All paths from start to end vertex are:")
connections.forEach {
println(it.first.padLeft() + " : " + it.second)
}
val bestPath = connections.minByOrNull { it.second }!!
println("Shortest path is $bestPath")
return bestPath
}
/**
* Recursively traverse a list
*/
private fun depthFirstTraversal(vertex: Vertex, stack: Stack<Vertex>, totalDistance: Int) {
if (vertex == endVertex) {
// If endVertex then store the path
connections.add(Pair(stack.getVertexNames(), totalDistance))
} else {
for (edge in vertex.edges) {
// On every branch out, clone the stack
val newStack = stack.clone() as Stack<Vertex>
newStack.add(edge.endVertex)
depthFirstTraversal(edge.endVertex, newStack, totalDistance + edge.weight!!)
}
}
}
}
fun main() {
test1()
test2()
}
private fun test1() {
val graph = Graph(Relation.WEIGHTED_DIRECTED)
val v1 = graph.add(1)
val v6 = graph.add(6)
val v2 = graph.add(2)
val v3 = graph.add(3)
val v4 = graph.add(4)
val v5 = graph.add(5)
v1.connectWith(v2, 5)
v1.connectWith(v3, 4)
v3.connectWith(v2, 6)
v2.connectWith(v4, 2)
v3.connectWith(v6, 6)
v6.connectWith(v5, 1)
v4.connectWith(v5, 4)
val (path, distance) = DijkstraAlgorithm(graph, v1, v5).execute()
assertEquals(11, distance)
assertEquals("1,2,4,5", path)
}
private fun test2() {
val graph = Graph(Relation.WEIGHTED_DIRECTED)
val v1 = graph.add(1)
val v2 = graph.add(2)
val v3 = graph.add(3)
val v4 = graph.add(4)
val v5 = graph.add(5)
val v6 = graph.add(6)
v1.connectWith(v2, 5)
v1.connectWith(v3, 20)
v1.connectWith(v4, 11)
v1.connectWith(v5, 25)
v2.connectWith(v3, 10)
v3.connectWith(v4, 4)
v3.connectWith(v6, 20)
v4.connectWith(v5, 10)
v5.connectWith(v6, 1)
val (path, distance) = DijkstraAlgorithm(graph, v1, v6).execute()
assertEquals(22, distance)
assertEquals("1,4,5,6", path)
}
| 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 3,865 | algorithms | MIT License |
src/main/kotlin/prefixSum/MinSubArrayLen.kt | ghonix | 88,671,637 | false | null | package prefixSum
import kotlin.math.min
/*
https://leetcode.com/problems/minimum-size-subarray-sum/
*/
class MinSubArrayLen {
fun minSubArrayLen(target: Int, nums: IntArray): Int {
if (nums.isEmpty()) {
return 0
}
var minSize = Int.MAX_VALUE
val prefixSums = IntArray(nums.size)
prefixSums[0] = nums[0]
for (i in 1 until nums.size) {
prefixSums[i] = prefixSums[i - 1] + nums[i]
}
for (i in prefixSums.indices) {
val remainder = prefixSums[i] - target
if (remainder < 0) {
continue
}
val lowerBound = search(prefixSums, 0, i - 1, prefixSums[i], target)
if (lowerBound != -1) {
minSize = min(minSize, i - lowerBound + 1)
}
}
return if (minSize == Int.MAX_VALUE) {
0
} else {
minSize
}
}
private fun search(array: IntArray, low: Int, hi: Int, prefixSum: Int, target: Int): Int {
var start = low
var end = hi
var mid = (start + end) / 2
while (start <= end) {
mid = (start + end) / 2
if (prefixSum - array[mid] == target) {
return mid + 1
} else if (prefixSum - array[mid] > target) {
start = mid + 1
} else {
end = mid - 1
}
}
return mid
}
}
fun main() {
val m = MinSubArrayLen()
println(
m.minSubArrayLen(20, intArrayOf(1, 2, 0, 6, 14, 15))
) // 2
// println(
// m.minSubArrayLen(20, intArrayOf(2, 16, 14, 15))
// ) // 2
//
// println(
// m.minSubArrayLen(7, intArrayOf(2, 3, 1, 2, 4, 3))
// ) // 2
//
// println(
// m.minSubArrayLen(4, intArrayOf(1, 4, 4))
// ) // 1
//
// println(
// m.minSubArrayLen(15, intArrayOf(1, 2, 3, 4, 5))
// ) // 5
//
// println(
// m.minSubArrayLen(11, intArrayOf(1, 1, 1, 1, 1, 1, 1, 1))
// ) // 0
} | 0 | Kotlin | 0 | 2 | 25d4ba029e4223ad88a2c353a56c966316dd577e | 2,120 | Problems | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/FrogPosition.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import java.util.LinkedList
import java.util.Queue
/**
* 1377. Frog Position After T Seconds
* @see <a href="https://leetcode.com/problems/frog-position-after-t-seconds/">Source</a>
*/
fun interface FrogPosition {
fun proceed(n: Int, edges: Array<IntArray>, t: Int, target: Int): Double
}
class FrogPositionBFS : FrogPosition {
override fun proceed(n: Int, edges: Array<IntArray>, t: Int, target: Int): Double {
var t0 = t
val graph: Map<Int, List<Int>> = initialize(edges)
val visited: BooleanArray = BooleanArray(n).apply {
this[0] = true
}
val prob: DoubleArray = DoubleArray(n).apply {
this[0] = 1.0
}
val q: Queue<Int> = LinkedList<Int>().apply {
offer(0)
}
while (q.isNotEmpty() && t0-- > 0) {
for (size in q.size downTo 1) {
val u = q.poll()
val nextVerticesCount = adjacentVerticesCount(graph, visited, u)
val ints = graph[u] ?: emptyList()
for (v in ints) {
if (visited[v]) continue
visited[v] = true
q.offer(v)
prob[v] = prob[u] / nextVerticesCount
}
if (nextVerticesCount > 0) prob[u] = 0.0 // frog don't stay vertex u, he keeps going to the next vertex
}
}
return prob[target - 1]
}
private fun initialize(edges: Array<IntArray>): Map<Int, MutableList<Int>> {
val graph: MutableMap<Int, MutableList<Int>> = HashMap()
for (edge in edges) {
val p1 = edge[0] - 1
val p2 = edge[1] - 1
graph.computeIfAbsent(p1) { LinkedList() }.add(p2)
graph.computeIfAbsent(p2) { LinkedList() }.add(p1)
}
return graph
}
private fun adjacentVerticesCount(graph: Map<Int, List<Int>>, visited: BooleanArray, u: Int): Int {
var nextVerticesCount = 0
val ints = graph[u] ?: emptyList()
for (v in ints) {
if (!visited[v]) nextVerticesCount++
}
return nextVerticesCount
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,793 | kotlab | Apache License 2.0 |
src/com/mrxyx/algorithm/Coin.kt | Mrxyx | 366,778,189 | false | null | package com.mrxyx.algorithm
import kotlin.math.min
/**
* 零钱兑换
* https://leetcode-cn.com/problems/coin-change/
*/
class Coin {
private var res: Int = Int.MAX_VALUE
/**
* 暴力递归 自顶向下
*/
fun coinChangeV1(coins: Array<Int>, amount: Int): Int {
if (coins.isEmpty()) return 0
coinChangeHelperV1(coins, amount, 0)
return if (res == Int.MAX_VALUE) -1 else res
}
/**
# 初始化 base case
dp[0][0][...] = base
# 进行状态转移
for 状态1 in 状态1的所有取值:
for 状态2 in 状态2的所有取值:
for ...
dp[状态1][状态2][...] = 求最值(选择1,选择2...)
**/
private fun coinChangeHelperV1(coins: Array<Int>, amount: Int, count: Int) {
if (amount < 0) return
if (amount == 0) res = min(res, count)
for (coin in coins)
coinChangeHelperV1(coins, amount - coin, count + 1)
}
/**
* 备忘录递归 自顶向下
*/
lateinit var cache: Array<Int>
fun coinChangeV2(coins: Array<Int>, amount: Int): Int {
if (coins.isEmpty()) return 0
cache = Array(amount) { 0 }
return coinChangeHelperV2(coins, amount)
}
private fun coinChangeHelperV2(coins: Array<Int>, amount: Int): Int {
when {
amount < 0 -> return -1
amount == 0 -> return 0
}
if (cache[amount-1] != 0) return cache[amount-1]
var res: Int
var min: Int = Int.MAX_VALUE
for (coin in coins) {
res = coinChangeHelperV2(coins, amount - coin)
if (res in 0..min) min = res + 1
}
cache[amount - 1] = if (min == Integer.MAX_VALUE) -1 else min
return cache[amount - 1]
}
/**
* 动态规划
*/
fun coinChangeV3(coins: Array<Int>, amount: Int): Int {
if (coins.isEmpty()) return -1
val cache: Array<Int> = Array(amount + 1) { 0 }
cache[0] = 0
var min: Int
for (i in 1..amount) {
min = Int.MAX_VALUE
for (coin in coins)
if (i - coin >= 0 && cache[i - coin] < min)
min = cache[i - coin] + 1
cache[i] = min
}
return if (cache[amount] == Int.MAX_VALUE) -1 else cache[amount]
}
} | 0 | Kotlin | 0 | 0 | b81b357440e3458bd065017d17d6f69320b025bf | 2,318 | algorithm-test | The Unlicense |
2023/src/main/kotlin/Day24.kt | dlew | 498,498,097 | false | {"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262} | import kotlin.math.abs
object Day24 {
fun part1(input: String, testRange: LongRange): Int {
val hailstones = parse(input)
return hailstones
.mapIndexed { a, h1 ->
hailstones.subList(a + 1, hailstones.size).count { h2 ->
willCollideXy(h1, h2, testRange)
}
}
.sum()
}
// I'm absolute shit at thinking in more than 2 dimensions, so I just implemented a solution someone came up with
// here: https://www.reddit.com/r/adventofcode/comments/18pnycy/2023_day_24_solutions/keqf8uq/
fun part2(input: String): Long {
val hailstones = parse(input)
// Find the velocity of the hailstone
fun findVelocity(hailstones: List<Hailstone>, position: (Hailstone) -> Long, velocity: (Hailstone) -> Long): Long {
val possibilities = (-300L..300L).toMutableList()
hailstones.forEachIndexed { index, h1 ->
hailstones.drop(index + 1).forEach { h2 ->
if (velocity(h1) == velocity(h2)) {
val distance = abs(position(h1) - position(h2))
possibilities.removeIf {
val testVelocity = velocity(h1) - it
testVelocity == 0L || distance % testVelocity != 0L
}
if (possibilities.size == 1) {
return possibilities[0]
}
}
}
}
throw IllegalStateException("Didn't work!")
}
val velocity = XYZ(
x = findVelocity(hailstones, { it.position.x }, { it.velocity.x }),
y = findVelocity(hailstones, { it.position.y }, { it.velocity.y }),
z = findVelocity(hailstones, { it.position.z }, { it.velocity.z })
)
// Find the intersection between two hailstones minus the velocity
val h1 = hailstones[0].copy(
velocity = XYZ(
x = hailstones[0].velocity.x - velocity.x,
y = hailstones[0].velocity.y - velocity.y,
z = hailstones[0].velocity.z - velocity.z
)
)
val h2 = hailstones[1].copy(
velocity = XYZ(
x = hailstones[1].velocity.x - velocity.x,
y = hailstones[1].velocity.y - velocity.y,
z = hailstones[1].velocity.z - velocity.z
)
)
val (x, y) = intercept(h1, h2, { it.y }, { it.x })!!
val (z) = intercept(h1, h2, { it.y }, { it.z })!!
return x + y + z
}
private fun intercept(h1: Hailstone, h2: Hailstone, d1: (XYZ) -> Long, d2: (XYZ) -> Long): Pair<Long, Long>? {
val m1 = d1(h1.velocity).toDouble() / d2(h1.velocity)
val m2 = d1(h2.velocity).toDouble() / d2(h2.velocity)
if (m1 == m2) {
return null
}
val b1 = d1(h1.position) - ((d1(h1.velocity) * d2(h1.position)) / d2(h1.velocity))
val b2 = d1(h2.position) - ((d1(h2.velocity) * d2(h2.position)) / d2(h2.velocity))
val top = d1(h1.velocity) * d2(h2.velocity) - d1(h2.velocity) * d2(h1.velocity)
val bottom = d2(h1.velocity) * d2(h2.velocity)
val a = (bottom * (b2 - b1)) / top
val b = (d1(h1.velocity) * a) / d2(h1.velocity) + b1
return a to b
}
private fun willCollideXy(h1: Hailstone, h2: Hailstone, testRange: LongRange): Boolean {
val intercept = interceptXy(h1, h2)
return intercept != null
&& intercept.x >= testRange.first
&& intercept.x <= testRange.last
&& intercept.y >= testRange.first
&& intercept.y <= testRange.last
&& h1.velocity.x < 0 != intercept.x > h1.position.x
&& h2.velocity.x < 0 != intercept.x > h2.position.x
}
private fun interceptXy(hailstone1: Hailstone, hailstone2: Hailstone): Intercept? {
val m1 = hailstone1.velocity.y.toDouble() / hailstone1.velocity.x
val m2 = hailstone2.velocity.y.toDouble() / hailstone2.velocity.x
if (m1 == m2) {
return null
}
val b1 = hailstone1.position.y - (m1 * hailstone1.position.x)
val b2 = hailstone2.position.y - (m2 * hailstone2.position.x)
val x = (b2 - b1) / (m1 - m2)
val y = (m1 * x) + b1
return Intercept(x, y, 0.0)
}
private data class XYZ(val x: Long, val y: Long, val z: Long)
private data class Intercept(val x: Double, val y: Double, val z: Double)
private data class Hailstone(val position: XYZ, val velocity: XYZ)
private fun parse(input: String): List<Hailstone> {
val regex = Regex("(\\d+),\\s+(\\d+),\\s+(\\d+)\\s+@\\s+(-?\\d+),\\s+(-?\\d+),\\s+(-?\\d+)")
return input.splitNewlines().map {
val match = regex.matchEntire(it)!!
return@map Hailstone(
position = XYZ(
x = match.groupValues[1].toLong(),
y = match.groupValues[2].toLong(),
z = match.groupValues[3].toLong(),
),
velocity = XYZ(
x = match.groupValues[4].toLong(),
y = match.groupValues[5].toLong(),
z = match.groupValues[6].toLong(),
)
)
}
}
} | 0 | Kotlin | 0 | 0 | 6972f6e3addae03ec1090b64fa1dcecac3bc275c | 4,774 | advent-of-code | MIT License |
src/main/kotlin/day7/day7KtTest.kt | Jessevanbekkum | 112,612,571 | false | null | package day7
fun day7_1(filename: String):String {
val lines = util.readLines(filename);
val regex = Regex("([a-z]*) \\((\\d*)\\) -> ([a-z, ]*)").toPattern()
val first = ArrayList<String>()
val rest = ArrayList<String>()
lines.forEach {
val result = regex.matcher(it)
if (result.matches()) {
first.add(result.group(1))
rest.addAll(result.group(3).split(',').map { l -> l.trim() })
}
}
first.removeAll(rest);
return first.get(0);
}
val weightMap = HashMap<String, Int>()
val childrenMap = HashMap<String, List<String>>()
fun day7_2(filename: String):String {
val lines = util.readLines(filename);
val regex = Regex("([a-z]*) \\((\\d*)\\) -> ([a-z, ]*)").toPattern()
val regex2 = Regex("([a-z]*) \\((\\d*)\\)").toPattern()
lines.forEach {
if (it.contains("->")) {
val result = regex.matcher(it)
result.matches()
val name = result.group(1)
val weight = result.group(2)
val children = result.group(3).split(',').map { l -> l.trim() }
weightMap.put(name, Integer.parseInt(weight))
childrenMap.put(name, children)
}
else {
val result = regex2.matcher(it)
result.matches()
val name = result.group(1)
val weight = result.group(2)
weightMap.put(name, Integer.parseInt(weight))
}
}
return weightOfTree("uownj").toString()
}
fun weightOfTree(name: String): Int {
var weight = weightMap.get(name)!!
val children = childrenMap.get(name);
if (children != null) {
val map = children.map { i -> weightOfTree(i) }
if (map.max() != map.min()) {
println(name)
println(map)
println(weight)
}
return weight + map.sum()
}
else {
return weight
}
} | 0 | Kotlin | 0 | 0 | 1340efd354c61cd070c621cdf1eadecfc23a7cc5 | 1,891 | aoc-2017 | Apache License 2.0 |
src/Day02.kt | wujingwe | 574,096,169 | false | null | fun main() {
fun String.toShape(): Shape = when(this) {
"A", "X" -> Shape.Rock
"B", "Y" -> Shape.Paper
else -> Shape.Scissor
}
fun shapeScore(shape: Shape): Int {
return shape.score
}
fun outcomeScore(opponent: Shape, me: Shape): Int {
return if (me > opponent) {
6 // win
} else if (me == opponent) {
3 // draw
} else {
0 // lose
}
}
fun part1(inputs: List<String>): Int {
var total = 0
inputs.forEach {
val (a, b) = it.split(" ")
val opponent = a.toShape()
val me = b.toShape()
total += shapeScore(me)
total += outcomeScore(opponent, me)
}
return total
}
fun part2(inputs: List<String>): Int {
var total = 0
inputs.forEach {
val (a, b) = it.split(" ")
val opponent = a.toShape()
val me = when (b) {
"X" -> { // lose
when (opponent) {
Shape.Rock -> Shape.Scissor
Shape.Paper -> Shape.Rock
else -> Shape.Paper
}
}
"Y" -> opponent
else -> { // win
when (opponent) {
Shape.Rock -> Shape.Paper
Shape.Paper -> Shape.Scissor
else -> Shape.Rock
}
}
}
total += shapeScore(me)
total += outcomeScore(opponent, me)
}
return total
}
val testInput = readInput("../data/Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("../data/Day02")
println(part1(input))
println(part2(input))
}
sealed class Shape(val score: Int) {
object Rock: Shape(1)
object Paper : Shape(2)
object Scissor : Shape(3)
operator fun compareTo(opponent: Shape): Int {
if (this == opponent) {
return 0 // draw
}
if ((opponent is Rock && this is Paper) ||
(opponent is Paper && this is Scissor) ||
(opponent is Scissor && this is Rock)
) {
return 1 // win
}
return -1 // lose
}
}
| 0 | Kotlin | 0 | 0 | a5777a67d234e33dde43589602dc248bc6411aee | 2,368 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/Day06.kt | bent-lorentzen | 727,619,283 | false | {"Kotlin": 68153} | import java.time.LocalDateTime
import java.time.ZoneOffset
import kotlin.math.floor
import kotlin.math.sqrt
fun main() {
fun getValues(input: List<String>, label: String) =
input.first { it.startsWith(label) }.substringAfter(label).split(Regex(" +")).filterNot { it.isEmpty() }.map { it.toInt() }
fun solveEquation(distance: Long, time: Long): Pair<Int, Int> {
val b = time
val a = -1
val c = -distance
val lowLimit = (-b + sqrt(((b * b) + (-4 * a * c)).toDouble())) / (2 * a)
val highLimit = (-b + -sqrt(((b * b) + (-4 * a * c)).toDouble())) / (2 * a)
return floor(lowLimit).toInt() to floor(highLimit).toInt()
}
fun part1(input: List<String>): Int {
val times = getValues(input, "Time:")
val distances = getValues(input, "Distance:")
return times.mapIndexed { index, time ->
val lowHigh = solveEquation(distances[index].toLong(), time.toLong())
lowHigh.second - lowHigh.first
}.fold(1) { acc, i ->
acc * i
}
}
fun part2(input: List<String>): Int {
val time = getValues(input, "Time:").joinToString("").toLong()
val distance = getValues(input, "Distance:").joinToString("").toLong()
val lowHigh = solveEquation(distance, time)
return lowHigh.second - lowHigh.first
}
val timer = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli()
val input = readLines("day06-input.txt")
val result1 = part1(input)
"Result1: $result1".println()
val result2 = part2(input)
"Result2: $result2".println()
println("${LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli() - timer} ms")
}
| 0 | Kotlin | 0 | 0 | 41f376bd71a8449e05bbd5b9dd03b3019bde040b | 1,711 | aoc-2023-in-kotlin | Apache License 2.0 |
src/Day03.kt | mddanishansari | 576,622,315 | false | {"Kotlin": 11861} | fun main() {
val lowerCaseRange = 'a'..'z'
fun Char.priority(): Int {
if (this in lowerCaseRange)
return code - 96
return code - 38
}
fun part1(input: List<String>): Int {
var priorities = 0
input.forEach {
val (firstHalf, secondHalf) = it.chunked(it.count() / 2)
val common = firstHalf.toSet().intersect(secondHalf.toSet()).first()
priorities += common.priority()
}
return priorities
}
fun part2(input: List<String>): Int {
var priorities = 0
input.chunked(3).forEach {
val first = it[0]
val second = it[1]
val third = it[2]
val common = first.toSet().intersect(second.toSet()).intersect(third.toSet()).first()
priorities += common.priority()
}
return priorities
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | e032e14b57f5e6c2321e2b02b2e09d256a27b2e2 | 1,163 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/groundsfam/advent/y2022/d11/Day11.kt | agrounds | 573,140,808 | false | {"Kotlin": 281620, "Shell": 742} | package com.groundsfam.advent.y2022.d11
import com.groundsfam.advent.DATAPATH
import com.groundsfam.advent.timed
import kotlin.io.path.div
import kotlin.io.path.useLines
class Monkey(startingItems: List<Long>, val operation: (Long) -> Long, val test: (Long) -> Int) {
private val items = ArrayDeque(startingItems)
var inspections = 0L
private set
fun handleItem(): Pair<Long, Int> =
operation(items.removeFirst())
.let { it to test(it) }
.also { inspections++ }
fun receiveItem(item: Long) {
items.addLast(item)
}
fun isEmpty() = items.isEmpty()
}
fun doRound(monkeys: List<Monkey>) {
monkeys.forEach { monkey ->
while (!monkey.isEmpty()) {
monkey.handleItem()
.also { (item, nextMonkey) ->
monkeys[nextMonkey].receiveItem(item)
}
}
}
}
fun main() = timed {
val (monkeysOne, monkeysTwo) = (DATAPATH / "2022/day11.txt").useLines {
it.toList()
}.let { lines ->
val mod = (lines.indices step 7).map { i ->
lines[i + 3].split(" ").last().toLong()
}.reduce { a, b -> a * b }
(lines.indices step 7).map { i ->
val items = lines[i + 1].trim().split(" ")
.let { it.subList(2, it.size) }
.map { it.filterNot { c -> c == ',' }.toLong() }
val operation = lines[i + 2].trim().split(" ").let {
val (op, arg) = it.subList(4, it.size)
val partial = when (op) {
"+" -> { a: Long, b: Long -> a + b }
"*" -> { a: Long, b: Long -> a * b }
else -> throw RuntimeException("Illegal operation: ${lines[i + 2]}")
}
when (arg) {
"old" -> { old: Long -> partial(old, old) }
else -> { old: Long -> partial(old, arg.toLong()) }
}
}
val divBy = lines[i + 3].split(" ").last().toLong()
val ifTrue = lines[i + 4].split(" ").last().toInt()
val ifFalse = lines[i + 5].split(" ").last().toInt()
val test = { x: Long -> if (x % divBy == 0L) ifTrue else ifFalse }
Monkey(items, { old: Long -> operation(old) / 3 }, test) to
Monkey(items, { old: Long -> operation(old) % mod }, test)
}
}.let { list ->
list.map { it.first } to list.map { it.second }
}
repeat(20) {
doRound(monkeysOne)
}
monkeysOne.map{ it.inspections }
.sorted()
.takeLast(2)
.let { (a, b) -> a * b }
.also { println("Part one: $it") }
repeat(10_000) {
doRound(monkeysTwo)
}
monkeysTwo.map { it.inspections }
.sorted()
.takeLast(2)
.let { (a, b) -> a * b }
.also { println("Part two: $it") }
}
| 0 | Kotlin | 0 | 1 | c20e339e887b20ae6c209ab8360f24fb8d38bd2c | 2,899 | advent-of-code | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem990/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem990
/**
* LeetCode page: [990. Satisfiability of Equality Equations](https://leetcode.com/problems/satisfiability-of-equality-equations/);
*/
class Solution {
/* Complexity:
* Time O(N) and Space O(1) where N is the size of equations;
*/
fun equationsPossible(equations: Array<String>): Boolean {
val idPerLowercase = UnionFind()
unifyIdByEqual(equations, idPerLowercase)
idPerLowercase.optimizeInternalState()
return validateNotEqual(equations, idPerLowercase)
}
private class UnionFind {
private val numLowercase = 26
private val parentIdPerLowercase = IntArray(numLowercase) { indexAsInitialId -> indexAsInitialId }
fun unifyId(lowercase1: Char, lowercase2: Char) {
val id1 = findId(lowercase1)
val id2 = findId(lowercase2)
if (id1 == id2) return
val (smallId, largeId) = if (id1 < id2) id1 to id2 else id2 to id1
updateParentId(lowercase1, smallId)
updateParentId(lowercase2, smallId)
val index = largeId
updateParentId(index, smallId)
}
fun findId(lowercase: Char): Int {
val index = getIndex(lowercase)
return findId(index)
}
private fun getIndex(lowercase: Char): Int {
require(lowercase.isLowerCase())
return lowercase - 'a'
}
private tailrec fun findId(index: Int): Int {
val parentId = parentIdPerLowercase[index]
val isRootId = parentId == index
return if (isRootId) parentId else findId(parentId)
}
private fun updateParentId(lowercase: Char, newId: Int) {
val index = getIndex(lowercase)
updateParentId(index, newId)
}
private fun updateParentId(index: Int, newId: Int) {
parentIdPerLowercase[index] = newId
}
fun optimizeInternalState() {
for (index in parentIdPerLowercase.indices) {
parentIdPerLowercase[index] = findId(index)
}
}
}
private fun unifyIdByEqual(equations: Array<String>, idPerLowercase: UnionFind) {
for (equation in equations) {
if (equation[1] == '!') continue
val (variable1, variable2) = getVariables(equation)
idPerLowercase.unifyId(variable1, variable2)
}
}
private fun getVariables(equation: String) = Pair(equation[0], equation[3])
private fun validateNotEqual(equations: Array<String>, idPerLowercase: UnionFind): Boolean {
for (equation in equations) {
if (equation[1] == '=') continue
val (variable1, variable2) = getVariables(equation)
val id1 = idPerLowercase.findId(variable1)
val id2 = idPerLowercase.findId(variable2)
if (id1 == id2) return false
}
return true
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,967 | hj-leetcode-kotlin | Apache License 2.0 |
aoc-day9/src/Day9.kt | rnicoll | 438,043,402 | false | {"Kotlin": 90620, "Rust": 1313} | import java.nio.file.Files
import java.nio.file.Path
import java.util.*
fun main() {
val map: Array<IntArray> = Files.readAllLines(Path.of("input")).mapNotNull { line ->
if (line.isBlank()) {
null
} else {
line.toCharArray().map { it.toString().toInt() }.toIntArray()
}
}.toTypedArray()
part1(map)
part2(SeaMap(map))
}
fun part1(map: Array<IntArray>) {
val lowest = mutableListOf<Int>()
for (row in map.indices) {
for (col in map[row].indices) {
val value = map[row][col]
if (getValue(map, row, col - 1) > value
&& getValue(map, row, col + 1) > value
&& getValue(map, row - 1, col) > value
&& getValue(map, row + 1, col) > value) {
lowest.add(value)
}
}
}
println(lowest.sum() + lowest.count())
}
fun part2(map: SeaMap) {
val basins = mutableListOf<Set<Coord>>()
val seen = mutableSetOf<Coord>()
for (row in 0 until map.rows) {
for (col in 0 until map.cols) {
val coord = Coord(row, col)
val value = map.get(coord)
if (value < 9) {
if (coord !in seen) {
val basin = getBasin(map, coord, seen)
basins.add(basin)
seen.addAll(basin)
}
}
}
}
val sizes: List<Int> = basins.map { it.size }.sorted().reversed()
println(sizes)
var total = 1
for (i in 0 until 3) {
total *= (sizes[i])
}
println(total)
}
fun getBasin(map: SeaMap, start: Coord, seen: Set<Coord>): Set<Coord> {
val coords = mutableSetOf<Coord>()
val toProcess = Stack<Coord>()
toProcess.add(start)
while (toProcess.isNotEmpty()) {
val centre = toProcess.pop()
coords.add(centre)
val around = listOfNotNull(centre.west(), centre.east(map), centre.north(), centre.south(map))
.filter { map.get(it) < 9 }
.filter { it !in seen }
.filter { it !in coords }
toProcess.addAll(around)
}
return coords
}
fun getValue(map: Array<IntArray>, row: Int, col: Int): Int {
if (row < 0 || row >= map.size) {
return Int.MAX_VALUE
}
if (col < 0 || col >= map[row].size) {
return Int.MAX_VALUE
}
return map[row][col]
} | 0 | Kotlin | 0 | 0 | 8c3aa2a97cb7b71d76542f5aa7f81eedd4015661 | 2,388 | adventofcode2021 | MIT License |
project/src/problems/PrimeAndCompositeNumbers.kt | informramiz | 173,284,942 | false | null | package problems
object PrimeAndCompositeNumbers {
/**
* https://codility.com/media/train/8-PrimeNumbers.pdf
* if number a is a divisor of n, then n/a is also a divisor.
* One of these two divisors is less than or equal to √n.
* (If that were not the case, n would be
* a product of two numbers greater than √n, which is impossible.)
*
* For example, for n = 36, following are symmetric divisors
*
* 1 | 2 3 4 | 6 | 9 12 18 36
* (1, 2, 3, 4) has symmetric divisors (9, 12, 18, 36),
* 6 has symmetric divisor 6 (both are same) so we count it only 1 time
*
* Thus, iterating through all the numbers from 1 to √n allows us to find all the divisors.
* If number n is of the form k^2
* , then the symmetric divisor of k is also k. This divisor should be
* counted just once.
*/
fun countDivisors(n: Int): Int {
val longN = n.toLong()
var i = 1L
var count = 0
while (i * i < n) {
//check if i divides n
if (longN % i == 0L) {
//we count both i and it's symmetric divisor n/i
//because i can only divide n if
// i x (n/i) = n
// i has to be multiplied by some number x to get n value and that some number
// is also a divisor
count += 2
}
i++
}
//consider the symmetric divisor case: 6 x 6 = 36 so in this we only count one number (6)
//and not both numbers because both numbers are same
if (i * i == longN) {
count++
}
return count
}
/**
* Prime is a number that is divisible by only two numbers: (1, itself)
*/
fun checkIfPrime(n: Int): Boolean {
var i = 2
while (i * i <= n) {
if (n % i == 0) {
return false
}
i++
}
return true
}
/**
* Coin Reversing Problem:
*
* Consider n coins aligned in a row. Each coin is showing heads at the beginning.
* 1 2 3 4 5 6 7 8 9 10
* Then, n people turn over corresponding coins as follows. Person i reverses coins with numbers
* that are multiples of i. That is, person i flips coins i, 2 · i, 3 · i, . . . until no more appropriate
* coins remain. The goal is to count the number of coins showing tails. In the above example,
* the final configuration is:
* T H H T H H H H T H
*
* Solution:
* A person i can only flip coins whose numbers are multiple if 'i' so that means person number has
* to be a divisor of the coin number. Coin will result in tail only if its number of divisors is an odd number.
* So total coins with odd number of divisors (each) is what we are interested in. A number can have odd number of
* divisors iff it is a perfect square and perfect squares in range (1...n) are <= sqrt(n) or more precisely
* = floor(sqrt(n))
*
* More details on link: https://informramiz.blogspot.com/2019/05/coin-reversing-codility-problem.html
*/
fun countTailCoins(n: Int): Int {
return Math.floor(Math.sqrt(n.toDouble())).toInt()
}
/**
* https://app.codility.com/programmers/lessons/10-prime_and_composite_numbers/count_factors/
* A positive integer D is a factor of a positive integer N if there exists an integer M such that N = D * M.
* For example, 6 is a factor of 24, because M = 4 satisfies the above condition (24 = 6 * 4).
* Write a function:
* class Solution { public int solution(int N); }
* that, given a positive integer N, returns the number of its factors.
* For example, given N = 24, the function should return 8, because 24 has 8 factors, namely 1, 2, 3, 4, 6, 8, 12, 24. There are no other factors of 24.
*/
fun countFactors(n: Int): Int {
//factors are just divisors so count divisors
return countDivisors(n)
}
/**
* https://app.codility.com/programmers/lessons/10-prime_and_composite_numbers/min_perimeter_rectangle/
* An integer N is given, representing the area of some rectangle.
* The area of a rectangle whose sides are of length A and B is A * B, and the perimeter is 2 * (A + B).
* The goal is to find the minimal perimeter of any rectangle whose area equals N. The sides of this rectangle should be only integers.
* For example, given integer N = 30, rectangles of area 30 are:
* (1, 30), with a perimeter of 62,
* (2, 15), with a perimeter of 34,
* (3, 10), with a perimeter of 26,
* (5, 6), with a perimeter of 22.
* Write a function:
* class Solution { public int solution(int N); }
* that, given an integer N, returns the minimal perimeter of any rectangle whose area is exactly equal to N.
*
* For example, given an integer N = 30, the function should return 22, as explained above.
* Write an efficient algorithm for the following assumptions:
* N is an integer within the range [1..1,000,000,000].
*/
fun findMinimumPerimeter(n: Int): Int {
//we will use long to avoid integer overflow which can easily happen if given
//n = Int.MAX_VALUE
val longN = n.toLong()
var i = 1L
var minPerimeter = (2 + (longN + longN))
while (i * i < longN) {
//rectangles with area N will have sides A, B as divisors so
//we need to find divisors and then calculate perimeter and
//keep track of minimum perimeter
if (n % i == 0L) {
val A = i
val B = n / i
val perimeter = 2 * (A + B)
minPerimeter = Math.min(minPerimeter, perimeter)
}
i++
}
//handle the boundary case of perfect squares (6 x 6 = 36)
if (i * i == longN) {
//in this case both sides are i (A = i, B = i)
val perimeter = 2 * (i + i)
minPerimeter = Math.min(minPerimeter, perimeter)
}
return minPerimeter.toInt()
}
/**
* https://app.codility.com/programmers/lessons/10-prime_and_composite_numbers/peaks/
* Peaks
* Divide an array into the maximum number of same-sized blocks, each of which should contain
* an index P such that A[P - 1] < A[P] > A[P + 1].
*/
fun peaks(A: IntArray): Int {
//array size must be >= 3 for any peak to exist
if (A.size < 3) return 0
//calculate prefixSums for peaks (peaks encountered till any index from left to right)
//this will help us in easily finding peaks count in a given range.
val prefixSums = peaksPrefixSum(A)
//if there is no peak at all, then just return
if (prefixSums[A.size] == 0) return 0
//the smaller the size of k the max blocks we will have and because k will be increasing
//so the first ever k for which all blocks will contain peaks
//will result in max blocks
var k = 2
//Because all blocks should be equal size so max possible K will be <= n/2
//because the only other possible K is when K = N (1 block)
val halfN = A.size / 2
while (k <= halfN ) {
//K can only divide array A of size N in equal blocks if it is a divisor of the N
if (A.size % k == 0) {
if (doAllBlocksContainPeaks(prefixSums, k)) {
//return blocks count
return A.size / k
}
}
k++
}
//Remember, we have already checked at top of function for at least 1 peak in full array
//so this code flow is only reached when no possible blocks were found with each having a peak
//that means the whole array is just 1 block
//so just return 1
return 1
}
private fun peaksPrefixSum(A: IntArray): Array<Int> {
val prefixSums = Array(A.size + 1) {0}
for (i in 1 until A.size) {
prefixSums[i+1] = prefixSums[i] + if (i+1 < A.size && A[i] > A[i-1] && A[i] > A[i+1]) 1 else 0
}
return prefixSums
}
private fun doAllBlocksContainPeaks(prefixSums: Array<Int>, blockSize: Int): Boolean {
for (i in 0..prefixSums.size-blockSize step blockSize) {
if (!isPeakPresent(prefixSums, i, i+blockSize-1)) {
return false
}
}
return true
}
private fun isPeakPresent(prefixSums: Array<Int>, x: Int, y: Int): Boolean {
return peaksCountInRange(prefixSums, x, y) > 0
}
private fun peaksCountInRange(prefixSums: Array<Int>, x: Int, y: Int): Int {
//Py = Py+1 - Px
return prefixSums[y+1] - prefixSums[x]
}
/**
* https://app.codility.com/programmers/lessons/10-prime_and_composite_numbers/flags/
* Flags
* Find the maximum number of flags that can be set on mountain peaks.
*/
fun findMaxSettableFlags(A: IntArray): Int {
//find peak indexes in array A
val peakIndexes = findPeakIndexes(A)
//if there are no peaks then we can't set any flags at all
if (peakIndexes.isEmpty()) {
return 0
}
//variable to keep track of max flags set
var maxFlagsSet = 0
//the max flags we can set are equal to total peaks
//in case each peak is exactly peaks.size distance (index distance) apart
//and min flags is 1 because we can always set flag on the first peak so
//the range for possible flag count values is [1, peaks.size]
var start = 1
var end = peakIndexes.size
//we will use binary search. We know that if we can set X flags then that
//means that we also set x-1, x-2 ... flags so the range we should check is
//(mid, end] and if we can't set x flags then we know that we can't set
//x+1, x+2 flags count as well so the range to check is [start, mid)
while (start <= end) {
//get the middle of flag counts range [start, end]
val midFlagsCount = Math.ceil((start + end) / 2.0).toInt()
//try setting the flags K = midFlagsCount
val newSetFlagsCount = setFlags(peakIndexes, midFlagsCount)
//check if all flags were set
if (newSetFlagsCount >= midFlagsCount) {
//that means all flags before mid can be set (range: [start, mid])
//so let's check how many more flags we can set
//in the range (mid, end]
start = midFlagsCount + 1
} else if (newSetFlagsCount < midFlagsCount) {
//not all flags were set so it means
//we should check the range [start, mid]
end = midFlagsCount - 1
}
//keep track of max flags set so far.
maxFlagsSet = Math.max(newSetFlagsCount, maxFlagsSet)
}
return maxFlagsSet
}
/**
* Returns peaks indexes in array A
*/
private fun findPeakIndexes(A: IntArray): List<Int> {
if (A.size < 3) return emptyList()
val peakIndexes = mutableListOf<Int>()
for (i in 1 until A.size) {
//check if it is a peak
if (i+1 < A.size && A[i] > A[i-1] && A[i] > A[i+1]) {
peakIndexes.add(i)
}
}
return peakIndexes
}
/**
* Try to set given number of flags (flagsCount)
* and return the number of flags that were successfully set on peaks
*/
private fun setFlags(peakIndexes: List<Int>, flagsCount: Int): Int {
//we need at least 1 peak to set any flag
if (peakIndexes.isEmpty()) {
return 0
}
//first peak will definitely have a flag set so flagsCount-1
var remainingFlags = flagsCount - 1
//first peak flag already set
var previousFlagIndex = peakIndexes[0]
for (pIndex in peakIndexes) {
//check if current peakIndex is at K = flagsCount distance apart from the previous peak
//as this is the condition for setting flags.
if (pIndex - previousFlagIndex >= flagsCount) {
//Make current peakIndex as previous flag index (as flag is set) for use in next iteration
previousFlagIndex = pIndex
//as 1 flag was set so decrease flag count
remainingFlags--
}
//if we have already set all flags so no need to check more
if (remainingFlags <= 0) break
}
//return the max flags set
return flagsCount - remainingFlags
}
} | 0 | Kotlin | 0 | 0 | a38862f3c36c17b8cb62ccbdb2e1b0973ae75da4 | 12,737 | codility-challenges-practice | Apache License 2.0 |
src/y2016/Day17.kt | gaetjen | 572,857,330 | false | {"Kotlin": 325874, "Mermaid": 571} | package y2016
import util.Direction
import util.Pos
import util.md5
object Day17 {
val viablePositions = List(4) { x -> List(4) { y -> x to y } }.flatten().toSet()
fun part1(input: String): String {
var states = listOf((0 to 3) to "")
while (true) {
states = states.flatMap {
nextStates(input, it.first, it.second)
}
states.firstOrNull { it.first == 3 to 0 }?.let {
return it.second
}
}
}
private val directions = mapOf(
Direction.UP to (0 to 'U'),
Direction.DOWN to (1 to 'D'),
Direction.LEFT to (2 to 'L'),
Direction.RIGHT to (3 to 'R')
)
private fun nextStates(
input: String,
pos: Pos,
hist: String
): Iterable<Pair<Pos, String>> {
val hash = (input + hist).md5().take(4)
return directions.filter { (_, v) ->
hash[v.first].code >= 'b'.code
}.map { (k, v) ->
k.move(pos) to hist + v.second
}.filter {
it.first in viablePositions
}
}
fun part2(input: String): Int {
var states = listOf((0 to 3) to "")
val solutions = mutableListOf<String>()
var steps = 0
while (states.isNotEmpty()) {
states = states.flatMap {
nextStates(input, it.first, it.second)
}
val ends = states.filter { it.first == 3 to 0 }
solutions.addAll(
ends.map { it.second }
)
states = states - ends.toSet()
steps++
}
return solutions.last().length
}
}
fun main() {
val testInput1 = "ihgpwlah"
val testInput2 = "kglvqrro"
val testInput3 = "ulqzkmiv"
println("------Tests------")
println(Day17.part1(testInput1))
println(Day17.part1(testInput2))
println(Day17.part1(testInput3))
println(Day17.part2(testInput1))
println(Day17.part2(testInput2))
println(Day17.part2(testInput3))
println("------Real------")
val input = "mmsxrhfx"
println(Day17.part1(input))
println(Day17.part2(input))
} | 0 | Kotlin | 0 | 0 | d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a | 2,158 | advent-of-code | Apache License 2.0 |
src/main/kotlin/Day15.kt | i-redbyte | 433,743,675 | false | {"Kotlin": 49932} | import java.util.*
fun main() {
val data = readInputFile("day15").map { it.toCharArray().map { it.digitToInt() } }
fun part1(): Int {
val n = data.size
val m = data.first().size
val matrix = Array(n) { IntArray(m) { Int.MAX_VALUE } }
val v = Array(n) { BooleanArray(m) }
fun relax(i: Int, j: Int, x: Int) {
if (i !in 0 until n || j !in 0 until m) return
matrix[i][j] = minOf(matrix[i][j], x + data[i][j])
}
matrix[0][0] = 0
while (!v[n - 1][m - 1]) {
var mx = Int.MAX_VALUE
var mi = -1
var mj = -1
for (i in 0 until n) for (j in 0 until m) {
if (!v[i][j] && matrix[i][j] < mx) {
mx = matrix[i][j]
mi = i
mj = j
}
}
v[mi][mj] = true
relax(mi - 1, mj, mx)
relax(mi + 1, mj, mx)
relax(mi, mj - 1, mx)
relax(mi, mj + 1, mx)
}
return matrix[n - 1][m - 1]
}
fun part2(): Int {
val n0 = data.size
val m0 = data[0].size
val n = 5 * n0
val m = 5 * m0
val a = Array(n) { i ->
IntArray(m) { j ->
val k = i / n0 + j / m0
(data[i % n0][j % m0] + k - 1) % 9 + 1
}
}
val d = Array(n) { IntArray(m) { Int.MAX_VALUE } }
data class Pos(val i: Int, val j: Int, val x: Int)
val v = Array(n) { BooleanArray(m) }
val q = PriorityQueue(compareBy(Pos::x))
fun relax(i: Int, j: Int, x: Int) {
if (i !in 0 until n || j !in 0 until m || v[i][j]) return
val xx = x + a[i][j]
if (xx < d[i][j]) {
d[i][j] = xx
q += Pos(i, j, xx)
}
}
d[0][0] = 0
q.add(Pos(0, 0, 0))
while (!v[n - 1][m - 1]) {
val (i, j, x) = q.remove()
if (v[i][j]) continue
v[i][j] = true
relax(i - 1, j, x)
relax(i + 1, j, x)
relax(i, j - 1, x)
relax(i, j + 1, x)
}
return d[n - 1][m - 1]
}
println("Result part1: ${part1()}")
println("Result part2: ${part2()}")
} | 0 | Kotlin | 0 | 0 | 6d4f19df3b7cb1906052b80a4058fa394a12740f | 2,307 | AOC2021 | Apache License 2.0 |
src/Day01/Day01.kt | ctlevi | 578,257,705 | false | {"Kotlin": 10889} | fun main() {
fun part1(input: List<String>): Int {
var currentElfCalorieCount: Int = 0
var highestCalorieCount: Int = 0
for (row in input) {
if (row == "") {
if (currentElfCalorieCount > highestCalorieCount) {
highestCalorieCount = currentElfCalorieCount
}
currentElfCalorieCount = 0
} else {
currentElfCalorieCount += row.toInt()
}
}
return highestCalorieCount;
}
fun tryReplaceLowestCount(toCheck: Int, counts: MutableList<Int>) {
if (toCheck > counts.last()) {
counts.set(counts.size - 1, toCheck)
counts.sort()
counts.reverse()
}
}
fun part2(input: List<String>): Int {
var currentElfCalorieCount: Int = 0
var threeHighestCalorieCounts: MutableList<Int> = mutableListOf(0, 0, 0)
for (row in input) {
if (row == "") {
tryReplaceLowestCount(currentElfCalorieCount, threeHighestCalorieCounts)
currentElfCalorieCount = 0
} else {
currentElfCalorieCount += row.toInt()
}
}
return threeHighestCalorieCounts.sum();
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01/test")
val testResult = part1(testInput)
"Test Result: ${testResult}".println()
val input = readInput("Day01/input")
"Part 1 Result: ${part1(input)}".println()
"Part 2 Result: ${part2(input)}".println()
}
| 0 | Kotlin | 0 | 0 | 0fad8816e22ec0df9b2928983713cd5c1ac2d813 | 1,613 | advent_of_code_2022 | Apache License 2.0 |
src/Day12.kt | acrab | 573,191,416 | false | {"Kotlin": 52968} | import com.google.common.truth.Truth.assertThat
import kotlin.math.min
data class HillPoint(val elevation: Char, val x: Int, val y: Int, val isEnd: Boolean = false) {
var steps: Int = Int.MAX_VALUE
var visited: Boolean = false
}
fun main() {
fun parseMap(
input: List<String>
): Pair<List<List<HillPoint>>, Pair<HillPoint, HillPoint>> {
lateinit var startPoint: HillPoint
lateinit var endPoint: HillPoint
val map =
input.mapIndexed { x, it ->
it.toCharArray().mapIndexed { y, char ->
when (char) {
'S' -> {
startPoint = HillPoint('a', x, y)
startPoint
}
'E' -> {
endPoint = HillPoint('z', x, y, isEnd = true)
endPoint
}
else -> HillPoint(char, x, y)
}
}
}
return Pair(map, startPoint to endPoint)
}
fun part1(input: List<String>): Int {
val (map, keyPoints) = parseMap(input)
val startPoint = keyPoints.first
val pointsToCheck = mutableListOf(startPoint)
startPoint.visited = true
startPoint.steps = 0
while (pointsToCheck.size > 0) {
val nextPoint = pointsToCheck.minBy { it.steps }
// remove ourselves
pointsToCheck.remove(nextPoint)
// Find all valid neighbours
map.orthogonalNeighbours(nextPoint.x, nextPoint.y, null).filterNotNull()
.forEach {
if (it.elevation <= nextPoint.elevation + 1) {
// Update their step counts
it.steps = min(it.steps, nextPoint.steps + 1)
// add them to the list if necessary
if (!it.visited) {
pointsToCheck.add(it)
it.visited = true
if (it.isEnd) {
return it.steps
}
}
}
}
}
throw IllegalStateException("Didn't find end!")
}
fun part2(input: List<String>): Int {
val (map, keyPoints) = parseMap(input)
val endPoint = keyPoints.second
val pointsToCheck = mutableListOf(endPoint)
endPoint.visited = true
endPoint.steps = 0
while (pointsToCheck.size > 0) {
val nextPoint = pointsToCheck.minBy { it.steps }
// remove ourselves
pointsToCheck.remove(nextPoint)
// Find all valid neighbours
map.orthogonalNeighbours(nextPoint.x, nextPoint.y, null).filterNotNull()
.forEach {
if (it.elevation >= nextPoint.elevation - 1) {
// Update their step counts
it.steps = min(it.steps, nextPoint.steps + 1)
// add them to the list if necessary
if (!it.visited) {
pointsToCheck.add(it)
it.visited = true
}
}
}
}
return map.minOf { row -> row.filter { it.elevation == 'a' }.minOf { it.steps } }
}
val testInput = readInput("Day12_test")
assertThat(part1(testInput)).isEqualTo(31)
val input = readInput("Day12")
println(part1(input))
assertThat(part2(testInput)).isEqualTo(29)
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 0be1409ceea72963f596e702327c5a875aca305c | 3,689 | aoc-2022 | Apache License 2.0 |
src/Day04.kt | vitind | 578,020,578 | false | {"Kotlin": 60987} |
fun main() {
fun getSectionCount(sectionStart: Int, sectionEnd: Int) : Int {
val range = sectionEnd - sectionStart
return if (range == 1) { range } else { range + 1 }
}
fun getSectionBounds(sectionString: String) : List<Int> = sectionString.split("-").map { it.toInt() }
fun part1(input: List<String>): Int {
var pairSectionOverlapCount = 0
input.forEach {
val elfSections = it.split(",")
val firstElfSections = getSectionBounds(elfSections[0])
val secondElfSections = getSectionBounds(elfSections[1])
if (getSectionCount(firstElfSections[0], firstElfSections[1]) <= getSectionCount(secondElfSections[0], secondElfSections[1])) {
if ((firstElfSections[0] >= secondElfSections[0]) && (firstElfSections[1] <= secondElfSections[1])) {
pairSectionOverlapCount += 1
}
} else { // firstElfSections >= secondElfSections
if ((firstElfSections[0] <= secondElfSections[0]) && (firstElfSections[1] >= secondElfSections[1])) {
pairSectionOverlapCount += 1
}
}
}
return pairSectionOverlapCount
}
fun part2(input: List<String>): Int {
var pairSectionOverlapCount = 0
input.forEach {
val elfSections = it.split(",")
val firstElfSections = getSectionBounds(elfSections[0])
val secondElfSections = getSectionBounds(elfSections[1])
val firstElfSectionRangeSet = (firstElfSections[0]..firstElfSections[1]).toSet()
val secondElfSectionRangeSet = (secondElfSections[0]..secondElfSections[1]).toSet()
if (firstElfSectionRangeSet.intersect(secondElfSectionRangeSet).size > 0) { // If there is any overlapping section IDs
pairSectionOverlapCount += 1
}
}
return pairSectionOverlapCount
}
val input = readInput("Day04")
part1(input).println()
part2(input).println()
} | 0 | Kotlin | 0 | 0 | 2698c65af0acd1fce51525737ab50f225d6502d1 | 2,054 | aoc2022 | Apache License 2.0 |
dataStructuresAndAlgorithms/src/main/java/dev/funkymuse/datastructuresandalgorithms/sort/MergeInsertionSort.kt | FunkyMuse | 168,687,007 | false | {"Kotlin": 1728251} | package dev.funkymuse.datastructuresandalgorithms.sort
/**
* Merge-Insertion sort is a sorting algorithm using the principle that for
* smaller sets of data, insertion sort is more efficient than merge sort.
* It uses a threshold. If the list's size is below the threshold, insertion sort will be used.
*
* Principle:
* Use insertion sort for smaller lists below the threshold size, otherwise
* use merge sort.
*
* Time complexity: O(n log n) on average.
*
* Space complexity: O(n) auxiliary for merging.
*/
fun mergeInsertionSort(list: MutableList<Int>, insertionThreshold: Int = 8) {
mergeInsertionSort(list, 0, list.size - 1, insertionThreshold)
}
private fun mergeInsertionSort(list: MutableList<Int>, start: Int, end: Int, insertionThreshold: Int = 8) {
if (end > start) {
if ((end - start) > insertionThreshold) {
val mid = (end + start) / 2
mergeInsertionSort(list, start, mid)
mergeInsertionSort(list, mid + 1, end)
merge(list, start, mid, end)
} else {
insertionSort(list, start, end)
}
}
}
private fun <T : Comparable<T>> insertionSort(list: MutableList<T>, start: Int = 0, end: Int = list.size) {
for (j in (start + 1)..end) {
val key = list[j]
var i = j - 1
while (i >= start && list[i] > key) {
list[i + 1] = list[i]
i -= 1
}
list[i + 1] = key
}
}
private fun merge(list: MutableList<Int>, start: Int, mid: Int, end: Int) {
val numLeft = mid - start + 1
val numRight = end - mid
val leftArray = IntArray(numLeft + 1)
val rightArray = IntArray(numRight + 1)
for (i in 1..numLeft) {
leftArray[i - 1] = list[start + i - 1]
}
for (i in 1..numRight) {
rightArray[i - 1] = list[mid + i]
}
leftArray[numLeft] = Int.MAX_VALUE
rightArray[numRight] = Int.MAX_VALUE
var i = 0
var j = 0
for (k in start..end) {
list[k] = if (leftArray[i] < rightArray[j]) leftArray[i++] else rightArray[j++]
}
} | 0 | Kotlin | 92 | 771 | e2afb0cc98c92c80ddf2ec1c073d7ae4ecfcb6e1 | 2,073 | KAHelpers | MIT License |
src/Coordinate.kt | andreas-eberle | 573,039,929 | false | {"Kotlin": 90908} | import java.lang.Integer.max
import java.lang.Integer.min
import kotlin.math.absoluteValue
import kotlin.math.sign
data class Coordinate(val x: Int, val y: Int) {
constructor(x: String, y: String) : this(x.toInt(), y.toInt())
fun manhattanDistanceTo(coordinate: Coordinate): Int = manhattanDistanceTo(coordinate.x, coordinate.y)
fun manhattanDistanceTo(x: Int, y: Int): Int = (this.x - x).absoluteValue + (this.y - y).absoluteValue
operator fun minus(other: Coordinate) = Coordinate(x - other.x, y - other.y)
operator fun plus(value: Int) = Coordinate(x + value, y + value)
operator fun plus(other: Coordinate) = Coordinate(x + other.x, y + other.y)
fun wrap(width: Int, height: Int): Coordinate = Coordinate(x.mod(width), y.mod(height))
operator fun rangeTo(o: Coordinate): List<Coordinate> = (this.y..o.y).flatMap { newY -> (this.x..o.x).map { newX -> Coordinate(newX, newY) } }
infix fun lineTo(o: Coordinate): List<Coordinate> {
val xSign = (o.x - x).sign
val ySign = (o.y - y).sign
val xSequence = if (xSign >= 0) x..o.x else x downTo o.x
val ySequence = if (ySign >= 0) y..o.y else y downTo o.y
return when {
xSign == 0 && ySign == 0 -> listOf(this)
xSign != 0 && ySign != 0 -> xSequence.zip(ySequence).map { (x, y) -> Coordinate(x, y) }
ySign == 0 -> xSequence.map { Coordinate(it, y) }
else -> ySequence.map { Coordinate(x, it) }
}
}
fun isIn(width: Int, height: Int) = x in 0 until width && y in 0 until height
}
fun Collection<Coordinate>.maxEach(): Coordinate = reduce { acc, coordinate -> Coordinate(max(acc.x, coordinate.x), max(acc.y, coordinate.y)) }
fun Collection<Coordinate>.minEach(): Coordinate = reduce { acc, coordinate -> Coordinate(min(acc.x, coordinate.x), min(acc.y, coordinate.y)) }
fun List<Pair<Coordinate, Coordinate>>.flatten(): List<Coordinate> = flatMap { listOf(it.first, it.second) }
| 0 | Kotlin | 0 | 0 | e42802d7721ad25d60c4f73d438b5b0d0176f120 | 1,972 | advent-of-code-22-kotlin | Apache License 2.0 |
contest1907/src/main/kotlin/D.kt | austin226 | 729,634,548 | false | {"Kotlin": 23837} | import kotlin.math.max
import kotlin.math.min
// https://codeforces.com/contest/1907/problem/D
private fun String.splitWhitespace() = split("\\s+".toRegex())
private fun readInt(): Int = readln().toInt()
private fun readInts(): List<Int> = readln().splitWhitespace().map { it.toInt() }
private fun testK(segments: List<IntRange>, k: Int): Boolean {
var location = 0..0
for (segment in segments) {
// Our location becomes the intersection of this segment, with the locations we can be after
// jumping up to k.
val locMin = max(0, location.first - k)
val locMax = min(1_000_000_000, location.last + k)
location = max(locMin, segment.first)..min(locMax, segment.last)
// If the intersection is empty, return false.
if (location.isEmpty()) {
return false
}
}
return true
}
private fun solve(segments: List<IntRange>): Int {
// Find smallest k where testK is true
var kL = 0
var kR = 1_000_000_000
var minPassed = kR
while (kL < kR) {
val kM = (kL + kR) / 2
if (testK(segments, kM)) {
minPassed = min(minPassed, kM)
// try smaller
kR = kM - 1
} else {
// Try bigger
kL = kM + 1
}
}
if (kL == kR) {
if (testK(segments, kL)) {
minPassed = min(minPassed, kL)
}
}
return minPassed
}
private fun testcase() {
val n = readInt()
val segments = MutableList(n) { 0..0 }
for (i in 0..<n) {
val lr = readInts()
val l = lr[0]
val r = lr[1]
segments[i] = l..r
}
println(solve(segments))
}
fun main() {
val t = readInt()
for (i in 0..<t) {
testcase()
}
} | 0 | Kotlin | 0 | 0 | 4377021827ffcf8e920343adf61a93c88c56d8aa | 1,765 | codeforces-kt | MIT License |
aoc-2021/src/commonMain/kotlin/fr/outadoc/aoc/twentytwentyone/Day12.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
class Day12 : Day<Int> {
private enum class NodeType {
Start,
End,
SmallCave,
BigCave
}
private data class Node(
val id: String,
val connectedTo: MutableSet<Node> = mutableSetOf()
) {
val type: NodeType = when (id) {
"start" -> NodeType.Start
"end" -> NodeType.End
id.lowercase() -> NodeType.SmallCave
else -> NodeType.BigCave
}
override fun toString() = "$id -> " + connectedTo.joinToString { node -> node.id }
override fun hashCode() = id.hashCode()
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as Node
if (id != other.id) return false
return true
}
}
private val nodes =
readDayInput()
.lineSequence()
.map { line -> line.split('-') }
.fold(emptySet<Node>()) { acc, (startId, endId) ->
val startNode = acc.firstOrNull { node -> node.id == startId } ?: Node(id = startId)
val endNode = acc.firstOrNull { node -> node.id == endId } ?: Node(id = endId)
startNode.connectedTo += endNode
endNode.connectedTo += startNode
acc + startNode + endNode
}
private val startNode = nodes.first { node -> node.type == NodeType.Start }
private val endNode = nodes.first { node -> node.type == NodeType.End }
private tailrec fun findAllPaths(
visitedNodes: Set<List<Node>>,
allowDoubleSmallCaveVisit: Boolean
): Set<List<Node>> {
if (visitedNodes.all { node -> node.last() == endNode })
return visitedNodes
val nodes: Set<List<Node>> = visitedNodes
.flatMap { chain: List<Node> ->
val wasSmallCaveVisitedTwiceAlready =
chain.asSequence()
.filter { node -> node.type == NodeType.SmallCave }
.groupingBy { node -> node.id }
.eachCount()
.any { (_, count) -> count > 1 }
when (val current: Node = chain.last()) {
endNode -> listOf(chain)
else -> current
.connectedTo
.filterNot { node -> node == startNode }
.filter { node ->
when (node.type) {
NodeType.SmallCave ->
when (chain.count { it == node }) {
0 -> true
1 -> allowDoubleSmallCaveVisit && !wasSmallCaveVisitedTwiceAlready
else -> false
}
else -> true
}
}
.map { node -> chain + node }
}
}
.toSet()
return findAllPaths(
visitedNodes = nodes,
allowDoubleSmallCaveVisit = allowDoubleSmallCaveVisit
)
}
override fun step1() =
findAllPaths(
visitedNodes = setOf(listOf(startNode)),
allowDoubleSmallCaveVisit = false
).size
override fun step2() =
findAllPaths(
visitedNodes = setOf(listOf(startNode)),
allowDoubleSmallCaveVisit = true
).size
override val expectedStep1 = 3292
override val expectedStep2 = 89592
}
| 0 | Kotlin | 0 | 0 | 54410a19b36056a976d48dc3392a4f099def5544 | 3,823 | adventofcode | Apache License 2.0 |
day02/part2.kts | bmatcuk | 726,103,418 | false | {"Kotlin": 214659} | // --- Part Two ---
// The Elf says they've stopped producing snow because they aren't getting any
// water! He isn't sure why the water stopped; however, he can show you how to
// get to the water source to check it out for yourself. It's just up ahead!
//
// As you continue your walk, the Elf poses a second question: in each game you
// played, what is the fewest number of cubes of each color that could have
// been in the bag to make the game possible?
//
// Again consider the example games from earlier:
//
// Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
// Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue
// Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red
// Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red
// Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green
//
// - In game 1, the game could have been played with as few as 4 red, 2 green,
// and 6 blue cubes. If any color had even one fewer cube, the game would
// have been impossible.
// - Game 2 could have been played with a minimum of 1 red, 3 green, and 4 blue
// cubes.
// - Game 3 must have been played with at least 20 red, 13 green, and 6 blue
// cubes.
// - Game 4 required at least 14 red, 3 green, and 15 blue cubes.
// - Game 5 needed no fewer than 6 red, 3 green, and 2 blue cubes in the bag.
//
// The power of a set of cubes is equal to the numbers of red, green, and blue
// cubes multiplied together. The power of the minimum set of cubes in game 1
// is 48. In games 2-5 it was 12, 1560, 630, and 36, respectively. Adding up
// these five powers produces the sum 2286.
//
// For each game, find the minimum set of cubes that must have been present.
// What is the sum of the power of these sets?
import java.io.*
import kotlin.io.*
import kotlin.math.*
val GAME_RGX = Regex("^Game \\d+: ")
val CNT_RGX = Regex("(\\d+) (red|green|blue)")
val result = File("input.txt").readLines().sumBy {
val gameMatch = GAME_RGX.find(it)
val minCubes = hashMapOf(
"red" to 0,
"green" to 0,
"blue" to 0
)
it.drop(gameMatch!!.range.endExclusive).splitToSequence("; ").forEach {
it.splitToSequence(", ").forEach {
val cntMatch = CNT_RGX.matchEntire(it)!!.groupValues
minCubes[cntMatch[2]] = max(minCubes[cntMatch[2]]!!, cntMatch[1].toInt())
}
}
minCubes.values.reduce(Int::times)
}
println(result)
| 0 | Kotlin | 0 | 0 | a01c9000fb4da1a0cd2ea1a225be28ab11849ee7 | 2,399 | adventofcode2023 | MIT License |
src/main/kotlin/net/wrony/aoc2023/a7/Main.kt | kopernic-pl | 727,133,267 | false | {"Kotlin": 52043} | package net.wrony.aoc2023.a7
import net.wrony.aoc2023.a7.Hand.Companion.fromTextLine
import kotlin.io.path.Path
import kotlin.io.path.readLines
//Five of a kind, where all five cards have the same label: AAAAA
//Four of a kind, where four cards have the same label and one card has a different label: AA8AA
//Full house, where three cards have the same label, and the remaining two cards share a different label: 23332
//Three of a kind, where three cards have the same label, and the remaining two cards are each different from any other card in the hand: TTT98
//Two pair, where two cards share one label, two other cards share a second label, and the remaining card has a third label: 23432
//One pair, where two cards share one label, and the other three cards have a different label from the pair and each other: A23A4
//High card, where all cards' labels are distinct: 23456
enum class HandType {
HighCard,
OnePair,
TwoPair,
ThreeOfAKind,
FullHouse,
FourOfAKind,
FiveOfAKind
}
data class Hand(val cards: String, val bid: Int, val cardValMapper: (Char)->Int) : Comparable<Hand> {
private val handMap by lazy { cards.groupingBy { it }.eachCount() }
private val cardsAsNumbers by lazy {
cards.map(cardValMapper)
}
companion object {
fun fromTextLine(line: String, cardValMapper: (Char) -> Int): Hand {
val (cards, bid) = line.split(" ")
return Hand(cards, bid.toInt(), cardValMapper)
}
}
val handType: HandType by lazy {
val vals = handMap.values.sortedDescending()
when {
handMap.size == 1 -> HandType.FiveOfAKind
vals.max() == 4 -> HandType.FourOfAKind
vals.containsAll(listOf(3, 2)) -> HandType.FullHouse
vals == listOf(3, 1, 1) -> HandType.ThreeOfAKind
vals == listOf(2, 2, 1) -> HandType.TwoPair
vals == listOf(2, 1, 1, 1) -> HandType.OnePair
handMap.size == 5 -> HandType.HighCard
else -> throw Exception("Unknown hand type should not happen $this, map: $handMap")
}
}
val handTypeJokerized: HandType by lazy {
when {
!cards.contains('J') -> return@lazy handType
else -> {
return@lazy listOf('2', '3', '4', '5', '6', '7', '8', '9', 'T', 'Q', 'K', 'A').map { r ->
Hand(cards.replace('J', r), bid, cardValMapper).handType
}.maxOf { it }
}
}
}
override fun compareTo(other: Hand): Int {
return when (this.handType.ordinal - other.handType.ordinal) {
0 -> compareByOrder(other)
else -> this.handType.ordinal - other.handType.ordinal
}
}
fun compareJokerized(otherHand: Hand): Int {
return when (this.handTypeJokerized.ordinal - otherHand.handTypeJokerized.ordinal) {
0 -> compareByOrder(otherHand)
else -> this.handTypeJokerized.ordinal - otherHand.handTypeJokerized.ordinal
}
}
private fun compareByOrder(other: Hand): Int {
this.cardsAsNumbers.forEachIndexed { index, i ->
when {
i > other.cardsAsNumbers[index] -> return 1
i < other.cardsAsNumbers[index] -> return -1
}
}
return 0
}
}
val valMapper = { c: Char ->
when (c) {
'A' -> 14
'K' -> 13
'Q' -> 12
'J' -> 11
'T' -> 10
else -> c.toString().toInt()
}
}
val jokerizedValMapper = { c: Char ->
when (c) {
'A' -> 14
'K' -> 13
'Q' -> 12
'J' -> 1
'T' -> 10
else -> c.toString().toInt()
}
}
fun main() {
Path("src/main/resources/7.txt").readLines()
.map { fromTextLine(it, valMapper) }
.sorted()
.mapIndexed { idx, hand -> idx to ((idx+1) * hand.bid).toLong() }
.sumOf { it.second }
.let { println(it) }
//255103572 -
//254024898 OK
val c: Comparator<Hand> = Comparator { o1, o2 ->
o1.compareJokerized(o2)
}
Path("src/main/resources/7.txt").readLines()
.map { fromTextLine(it, jokerizedValMapper) }
.sortedWith(c)
.mapIndexed { idx, hand -> idx to ((idx+1) * hand.bid).toLong() }
.sumOf { it.second }
.let { println(it)}
} | 0 | Kotlin | 0 | 0 | 1719de979ac3e8862264ac105eb038a51aa0ddfb | 4,343 | aoc-2023-kotlin | MIT License |
src/test/kotlin/be/brammeerten/y2022/Day19Test.kt | BramMeerten | 572,879,653 | false | {"Kotlin": 170522} | package be.brammeerten.y2022
import be.brammeerten.extractRegexGroups
import be.brammeerten.extractRegexGroupsI
import be.brammeerten.readFile
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import kotlin.math.max
val POTENTIAL_EXTRA_GEODES_PER_MINUTE_LEFT = createSequence(listOf(0), 0, 32)
fun createSequence(total: List<Int>, robots: Int, timeLeft: Int): List<Int> {
if (timeLeft == 0) return total
val newTotal = (total.lastOrNull() ?: 0) + robots
return createSequence(total + newTotal, robots+1, timeLeft-1)
}
class Day19Test {
@Test
fun `part 1a`() {
val bluePrints = readBlueprints("2022/day19/exampleInput.txt")
assertThat(getTotalQualityLevel(bluePrints)).isEqualTo(33)
}
@Test
fun `part 1b`() {
val bluePrints = readBlueprints("2022/day19/input.txt")
assertThat(getTotalQualityLevel(bluePrints)).isEqualTo(600)
}
@Test
fun `part 2`() {
val bluePrints = readBlueprints("2022/day19/exampleInput.txt")
assertThat(getGeodesMultiplied(bluePrints, minutes = 32)).isEqualTo(56 * 62)
}
@Test
fun `part 2b`() {
val bluePrints = readBlueprints("2022/day19/input.txt")
assertThat(getGeodesMultiplied(bluePrints.subList(0, 3), minutes = 32)).isEqualTo(0)
}
fun getTotalQualityLevel(blueprints: List<Blueprint>): Int {
return blueprints
.sumOf {
val bestState = it.getMaxGeodes()
println("Blueprint ${it.id}: ${bestState.geode} geodes")
bestState.geode * it.id
}
}
fun getGeodesMultiplied(blueprints: List<Blueprint>, minutes: Int): Int {
return blueprints
.map {
val bestState = it.getMaxGeodes(minutes)
println("Blueprint ${it.id}: ${bestState.geode} geodes")
bestState.geode
}.reduce { acc, g -> acc * g }
}
fun readBlueprints(file: String): List<Blueprint> {
return readFile(file)
.map { blueprint ->
Blueprint(
extractRegexGroupsI("Blueprint (\\d+):.*", blueprint)[0],
readRobotCost("ore", blueprint),
readRobotCost("clay", blueprint),
readRobotCost("obsidian", blueprint),
readRobotCost("geode", blueprint)
)
}
}
fun readRobotCost(type: String, line: String): RobotCost {
val regex = "Each $type robot costs ([^.]+)."
return RobotCost(
extractRegexGroups(regex, line)[0].split(" and ")
.map { cost -> extractRegexGroups("(\\d+) (.+)", cost) }
.map { it[1] to it[0].toInt() }.toMap())
}
data class Blueprint(
val id: Int,
val oreRobotCost: RobotCost,
val clayRobotCost: RobotCost,
val obsidianRobotCost: RobotCost,
val geodeRobotCost: RobotCost
) {
val robotCosts = mapOf("ore" to oreRobotCost, "clay" to clayRobotCost, "obsidian" to obsidianRobotCost, "geode" to geodeRobotCost)
fun getMaxGeodes(minutes: Int = 24): State {
val start = State(minute = 0, 0, 0, 0, 0, oreRobots = 1, 0, 0, 0, null, /*emptyList()*/)
return sim(start, minutes, 0)
}
fun sim(state: State, minutes: Int, curMax: Int): State {
if (state.minute >= minutes)
return state
var result = state
var currentMax = curMax
for (option in getOptions(state)) {
if (getPotential(option, minutes) < currentMax) continue
val simulation = sim(option, minutes, currentMax)
result = if (simulation.geode > result.geode) simulation else result
currentMax = max(result.geode, currentMax)
}
return result
}
fun getPotential(state: State, minutes: Int): Int {
val potential = state.geode + (state.geodeRobots * (minutes - state.minute))
return potential + POTENTIAL_EXTRA_GEODES_PER_MINUTE_LEFT[minutes - state.minute]
}
fun getOptions(state: State): List<State> {
val canAfford: Map<String, RobotCost> = this.robotCosts
.filter { it.value.canAfford(state) }
// Koop of spaar als nog iets beschikbaar kan komen
// Koop niet wat al vorige ronde gekocht had kunnen worden (tenzij er iets anders gekocht is vorige ronde)
if (canAfford.isEmpty()) {
return listOf(state.advance())
} else {
val options = canAfford
.filter { !it.value.couldAffordInPrevRound(state) || state.hasNewBots() }
.map { state.advance().buyRobot(it.key, it.value)}
if (canAfford.size < this.robotCosts.size)
return options + state.advance()
else if (options.isEmpty())
throw IllegalStateException("Zou nooit mogen")
else
return options
}
}
}
data class RobotCost(val costs: Map<String, Int>) {
fun canAfford(state: State): Boolean {
return costs.all { cost -> cost.value <= state.get(cost.key) }
}
fun couldAffordInPrevRound(state: State): Boolean {
return if (state.oldState == null) false else canAfford(state.oldState)
}
}
data class State(val minute: Int,
val ores: Int, val clay: Int, val obsidian: Int, val geode: Int,
val oreRobots: Int, val clayRobots: Int, val obsidianRobots: Int, val geodeRobots: Int,
val oldState: State? = null) {
fun get(resource: String): Int {
return when (resource) {
"ore" -> ores
"clay" -> clay
"obsidian" -> obsidian
"geode" -> geode
else -> throw IllegalStateException("Unknown resource $resource")
}
}
fun advance(): State {
return State(
minute+1,
ores+oreRobots, clay+clayRobots, obsidian+obsidianRobots, geode+geodeRobots,
oreRobots, clayRobots, obsidianRobots, geodeRobots,
this
)
}
override fun toString(): String {
return "Minute ${minute}: ore($oreRobots, $ores), clay($clayRobots, $clay), obsid(${obsidianRobots}, $obsidian), geode($geodeRobots, $geode), "
}
fun hasNewBots(): Boolean {
if (oldState == null)
return clayRobots > 0 || oreRobots > 0 || obsidianRobots > 0 || geodeRobots > 0
return oldState.oreRobots != oreRobots
|| oldState.clayRobots != clayRobots
|| oldState.obsidianRobots != obsidianRobots
|| oldState.geodeRobots != geodeRobots
}
fun buyRobot(robot: String, cost: RobotCost): State {
return State(
minute,
ores - (cost.costs["ore"] ?: 0),
clay - (cost.costs["clay"] ?: 0),
obsidian - (cost.costs["obsidian"] ?: 0),
geode - (cost.costs["geode"] ?: 0),
oreRobots + (if (robot == "ore") 1 else 0),
clayRobots + (if (robot == "clay") 1 else 0),
obsidianRobots + (if (robot == "obsidian") 1 else 0),
geodeRobots + (if (robot == "geode") 1 else 0),
oldState,
)
}
}
}
| 0 | Kotlin | 0 | 0 | 1defe58b8cbaaca17e41b87979c3107c3cb76de0 | 7,647 | Advent-of-Code | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem399/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem399
/**
* LeetCode page: [399. Evaluate Division](https://leetcode.com/problems/evaluate-division/);
*/
class Solution {
/* Complexity:
* Time O(NE) and Space O(E) where E is the size of equations and N is the size of queries;
*/
fun calcEquation(equations: List<List<String>>, values: DoubleArray, queries: List<List<String>>): DoubleArray {
val knownQuotients = adjacencyList(equations, values)
return DoubleArray(queries.size) { index ->
val (u, v) = queries[index]
computeQuotient(u, v, knownQuotients) ?: -1.0
}
}
private fun adjacencyList(
equations: List<List<String>>,
values: DoubleArray,
): Map<String, List<Quotient>> {
val result = hashMapOf<String, MutableList<Quotient>>()
for ((index, equation) in equations.withIndex()) {
val (u, v) = equation
val value = values[index]
result.computeIfAbsent(u) { mutableListOf() }.add(Quotient(v, value))
result.computeIfAbsent(v) { mutableListOf() }.add(Quotient(u, 1.0 / value))
}
return result
}
private data class Quotient(val divisor: String, val value: Double)
private fun computeQuotient(
dividend: String,
divisor: String,
knownQuotients: Map<String, List<Quotient>>,
visited: MutableSet<String> = hashSetOf(),
): Double? {
if (dividend !in knownQuotients || divisor !in knownQuotients) {
return null
}
if (dividend == divisor) {
return 1.0
}
visited.add(dividend)
for (quotient in knownQuotients[dividend] ?: emptyList()) {
if (quotient.divisor in visited) {
continue
}
val subQuotient =
computeQuotient(quotient.divisor, divisor, knownQuotients, visited)
if (subQuotient != null) {
return quotient.value * subQuotient
}
}
return null
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,066 | hj-leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/io/binarysearch/AllElementsInTwoBinarySearchTree.kt | jffiorillo | 138,075,067 | false | {"Kotlin": 434399, "Java": 14529, "Shell": 465} | package io.binarysearch
import io.models.TreeNode
// https://leetcode.com/problems/all-elements-in-two-binary-search-trees/
class AllElementsInTwoBinarySearchTree {
fun getAllElements(root1: TreeNode?, root2: TreeNode?): List<Int> = execute(root1, root2)
fun execute(root0: TreeNode?, root1: TreeNode?): List<Int> = when {
root0 == null -> inOrderTraversal(root1)
root1 == null -> inOrderTraversal(root0)
else -> mutableListOf<Int>().apply {
val elements0 = inOrderTraversal(root0)
val elements1 = inOrderTraversal(root1)
var index0 = 0
var index1 = 0
while (index0 < elements0.size && index1 < elements1.size) {
if (elements0[index0] < elements1[index1]) {
add(elements0[index0])
index0++
} else {
add(elements1[index1])
index1++
}
}
(index0 until elements0.size).forEach { add(elements0[it]) }
(index1 until elements1.size).forEach { add(elements1[it]) }
}
}
private fun inOrderTraversal(root: TreeNode?, acc: List<Int> = emptyList()): List<Int> = when (root) {
null -> acc
else -> inOrderTraversal(root.right, inOrderTraversal(root.left, acc) + root.`val`)
}
}
fun main() {
val allElementsInTwoBinarySearchTree = AllElementsInTwoBinarySearchTree()
listOf(
Triple(TreeNode(2, TreeNode(1), TreeNode(4)), TreeNode(1, TreeNode(0), TreeNode(3)), listOf(0, 1, 1, 2, 3, 4))
).forEachIndexed { index, (root0, root1, value) ->
val output = allElementsInTwoBinarySearchTree.execute(root0, root1)
val isValid = output == value
if (isValid)
println("index $index $output is valid")
else
println("index $index Except $value but instead got $output")
}
}
| 0 | Kotlin | 0 | 0 | f093c2c19cd76c85fab87605ae4a3ea157325d43 | 1,741 | coding | MIT License |
src/day07/Day07.kt | andreas-eberle | 573,039,929 | false | {"Kotlin": 90908} | package day07
import readInput
import java.util.*
const val day = "07"
fun main() {
fun calculateDirectories(input: List<String>): MutableMap<String, Int> {
val currentDirectory = Stack<String>()
val directories = mutableMapOf<String, Int>()
input.forEach {
when {
it.startsWith("$ cd ..") -> currentDirectory.pop()
it.startsWith("$ cd") -> {
val currentDirectoryName = it.substringAfterLast("$ cd ")
currentDirectory.push(currentDirectoryName)
}
it.startsWith("$ ls") -> {}
it.startsWith("dir ") -> {}
else -> {
val splitLine = it.split(" ")
val size = splitLine[0].toInt()
repeat(currentDirectory.size) { depth ->
val directory = currentDirectory.subList(0, depth + 1).toDirectoryPath()
directories[directory] = directories.getOrDefault(directory, 0) + size
}
}
}
}
return directories
}
fun calculatePart1Score(input: List<String>): Int {
val directories = calculateDirectories(input)
return directories.filterValues { it <= 100000 }.values.sum()
}
fun calculatePart2Score(input: List<String>): Int {
val directories = calculateDirectories(input)
val totalSpace = 70000000
val requiredForUpdate = 30000000
val totalUsed = directories.getValue("/")
val required = requiredForUpdate - (totalSpace - totalUsed)
val smallestFitting = directories.entries.filter { it.value >= required}.minBy { it.value }
return smallestFitting.value
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("/day$day/Day${day}_test")
val input = readInput("/day$day/Day${day}")
val part1TestPoints = calculatePart1Score(testInput)
val part1Points = calculatePart1Score(input)
println("Part1 test points: $part1TestPoints")
println("Part1 points: $part1Points")
check(part1TestPoints == 95437)
val part2TestPoints = calculatePart2Score(testInput)
val part2Points = calculatePart2Score(input)
println("Part2 test points: $part2TestPoints")
println("Part2 points: $part2Points")
check(part2TestPoints == 24933642)
}
fun Collection<String>.toDirectoryPath() = joinToString("/") | 0 | Kotlin | 0 | 0 | e42802d7721ad25d60c4f73d438b5b0d0176f120 | 2,509 | advent-of-code-22-kotlin | Apache License 2.0 |
src/day04/Day04.kt | Xlebo | 572,928,568 | false | {"Kotlin": 10125} | package day04
import getOrFetchInputData
import readInput
fun main() {
fun List<String>.asSections(): List<Pair<Pair<Int, Int>, Pair<Int, Int>>> =
this.map { row ->
row.split(",")
.map { section -> section.split("-").map { it.toInt() } }
.map { Pair(it[0], it[1]) }
}
.map { Pair(it[0], it[1]) }
fun part1(input: List<String>): Int {
return input.asSections()
.count {
(it.first.first >= it.second.first && it.first.second <= it.second.second) ||
(it.first.first <= it.second.first && it.first.second >= it.second.second)
}
}
fun part2(input: List<String>): Int {
return input.asSections()
.count {
(it.first.first <= it.second.first && it.first.second >= it.second.first) ||
(it.first.first >= it.second.first && it.first.first <= it.second.second)
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test", "day04")
val result1 = part1(testInput)
val result2 = part2(testInput)
check(result1 == 2) { "Got: $result1" }
check(result2 == 4) { "Got: $result2" }
val input = getOrFetchInputData(4)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | cd718c2c7cb59528080d2aef599bd93e0919d2d9 | 1,376 | aoc2022 | Apache License 2.0 |
src/Day07.kt | buongarzoni | 572,991,996 | false | {"Kotlin": 26251} | private const val TOTAL_MEMORY = 70_000_000L
private const val NEEDED_MEMORY = 30_000_000L
fun solveDay07() {
val input = readInput("Day07_test")
execute(input)
}
private val currentPath = ArrayDeque<String>()
private val sizesByPath = mutableMapOf<String, Long>()
private var usedMemory = 0L
private fun execute(input: List<String>) {
input.forEach { line ->
if (line.contains("$ cd")) {
changeDirectory(command = line)
} else if (line.isFile()){
val size = line.getSize()
addFileSizeToDirectoryAndParents(size)
usedMemory += size
}
}
val availableMemory = TOTAL_MEMORY - usedMemory
val neededMemoryToFree = NEEDED_MEMORY - availableMemory
val solution1 = sizesByPath.values.filter { it <= 100000 }.sum()
println("Part 1 solution : $solution1")
val solution2 = sizesByPath.values.filter { it >= neededMemoryToFree }.min()
println("Part 2 solution : $solution2")
}
private fun changeDirectory(command: String) {
val moveTo = command.split(" ")[2]
if (moveTo == "..") {
currentPath.removeLast()
} else {
currentPath.add(moveTo)
}
}
private fun addFileSizeToDirectoryAndParents(size: Int) {
var dir = "/"
for (e in currentPath) {
if (!dir.endsWith("/")) dir += "/"
dir += e
sizesByPath.compute(dir) { _, prev -> (prev ?: 0L) + size }
}
}
private fun String.isFile() = split(" ").first().toIntOrNull() != null
private fun String.getSize() = split(" ").first().toInt()
| 0 | Kotlin | 0 | 0 | 96aadef37d79bcd9880dbc540e36984fb0f83ce0 | 1,553 | AoC-2022 | Apache License 2.0 |
src/day05/Day05.kt | daniilsjb | 726,047,752 | false | {"Kotlin": 66638, "Python": 1161} | package day05
import java.io.File
import kotlin.math.max
import kotlin.math.min
fun main() {
val data = parse("src/day05/Day05.txt")
println("🎄 Day 05 🎄")
println()
println("[Part 1]")
println("Answer: ${part1(data)}")
println()
println("[Part 2]")
println("Answer: ${part2(data)}")
}
private data class Range(
val start: Long,
val end: Long,
)
private data class Mapping(
val src: Range,
val dst: Range,
)
private data class Almanac(
val seeds: List<Long>,
val transforms: List<List<Mapping>>,
)
private fun String.toMapping(): Mapping =
this.split(" ")
.map(String::toLong)
.let { (dst, src, length) ->
Mapping(
Range(src, src + length - 1),
Range(dst, dst + length - 1),
)
}
private fun parse(path: String): Almanac {
val sections = File(path)
.readText()
.split("\n\n", "\r\n\r\n")
val seeds = sections.first()
.split(": ", " ")
.mapNotNull(String::toLongOrNull)
val maps = sections.asSequence()
.drop(1)
.map { it.split("\n", "\r\n") }
.map { it.drop(1) }
.map { it.map(String::toMapping) }
.toList()
return Almanac(seeds, maps)
}
private fun intersection(a: Range, b: Range): Range? =
if (a.end < b.start || b.end < a.start) {
null
} else {
Range(max(a.start, b.start), min(a.end, b.end))
}
private fun part1(data: Almanac): Long {
val (seeds, transforms) = data
val values = seeds.toMutableList()
for (mapping in transforms) {
transforming@ for ((i, value) in values.withIndex()) {
for ((src, dst) in mapping) {
if (value in src.start..src.end) {
values[i] = dst.start + (value - src.start)
continue@transforming
}
}
}
}
return values.min()
}
private fun part2(data: Almanac): Long {
val (seeds, transforms) = data
val ranges = seeds
.chunked(2)
.map { (start, length) -> Range(start, start + length - 1) }
.toMutableList()
for (mappings in transforms) {
// List of ranges that already had a mapping applied to them. These are
// stored separately because we don't want to transform the same range
// multiple times within the same transformation "round".
val transformed = mutableListOf<Range>()
for ((src, dst) in mappings) {
// We may need to break each range into multiple sub-ranges in case
// the mapping only applies to its portion. This is the "unmapped"
// parts of the split ranges to be re-used later.
val remainders = mutableListOf<Range>()
for (range in ranges) {
val intersection = intersection(range, src)
if (intersection == null) {
remainders.add(range)
continue
}
val offset = intersection.start - src.start
val length = intersection.end - intersection.start
transformed.add(Range(
dst.start + offset,
dst.start + offset + length,
))
if (range.start < src.start) {
remainders.add(Range(range.start, src.start - 1))
}
if (range.end > src.end) {
remainders.add(Range(src.end + 1, range.end))
}
}
ranges.clear()
ranges.addAll(remainders)
}
ranges.addAll(transformed)
}
return ranges.minOf(Range::start)
}
| 0 | Kotlin | 0 | 0 | 46a837603e739b8646a1f2e7966543e552eb0e20 | 3,882 | advent-of-code-2023 | MIT License |
year2020/src/main/kotlin/net/olegg/aoc/year2020/day16/Day16.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2020.day16
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.utils.parseInts
import net.olegg.aoc.utils.parseLongs
import net.olegg.aoc.utils.toPair
import net.olegg.aoc.year2020.DayOf2020
/**
* See [Year 2020, Day 16](https://adventofcode.com/2020/day/16)
*/
object Day16 : DayOf2020(16) {
private val RANGE_PATTERN = ".*: (\\d+)-(\\d+) or (\\d+)-(\\d+)".toRegex()
override fun first(): Any? {
val (ranges, yours, nearby) = data.split("\n\n")
val valid = mutableSetOf<Int>()
ranges
.lines()
.flatMap { line -> RANGE_PATTERN.find(line)?.groupValues?.drop(1).orEmpty() }
.map { it.toInt() }
.zipWithNext()
.forEach { (from, to) -> (from..to).forEach { valid += it } }
val invalid = mutableListOf<Int>()
invalid += yours
.lines()
.drop(1)
.flatMap { it.parseInts(",") }
.filter { it !in valid }
invalid += nearby
.lines()
.drop(1)
.flatMap { it.parseInts(",") }
.filter { it !in valid }
return invalid.sum()
}
override fun second(): Any? {
val (ranges, yours, nearby) = data.split("\n\n")
val validValues = mutableSetOf<Int>()
val rangeValues = ranges
.lines()
.map { line ->
RANGE_PATTERN.find(line)
?.groupValues
?.drop(1)
.orEmpty()
.map { it.toInt() }
.zipWithNext { a, b -> a..b }
.toPair()
}
rangeValues.forEach {
validValues += it.first
validValues += it.second
}
val yourTicket = yours
.lines()
.last()
.parseLongs(",")
val validTickets = nearby
.lines()
.drop(1)
.map { it.parseInts(",") }
.filter { line -> line.all { it in validValues } }
val possiblePositions = rangeValues
.withIndex()
.associateTo(mutableMapOf()) { (column, range) ->
column to yourTicket.indices
.asSequence()
.map { col ->
col to validTickets.map { it[col] }
}
.filter { (_, col) -> col.all { it in range.first || it in range.second } }
.mapTo(mutableSetOf()) { it.first }
}
val fixedPositions = mutableMapOf<Int, Int>()
while (possiblePositions.isNotEmpty() && possiblePositions.any { it.value.size == 1 }) {
val fixed = possiblePositions.entries.first { it.value.size == 1 }
val fixedValue = fixed.value.first()
fixedPositions[fixed.key] = fixedValue
possiblePositions.remove(fixed.key)
possiblePositions.forEach {
it.value -= fixedValue
}
}
val permutation = yourTicket.indices.map { yourTicket[fixedPositions[it] ?: 0] }
return ranges.lines()
.zip(permutation)
.filter { it.first.startsWith("departure") }
.map { it.second }
.reduce(Long::times)
}
}
fun main() = SomeDay.mainify(Day16)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 2,890 | adventofcode | MIT License |
src/Day24.kt | EdoFanuel | 575,561,680 | false | {"Kotlin": 80963} | import utils.BBox2D
import utils.Coord2DInt
import utils.Orientation
import utils.aStar
import kotlin.math.abs
import kotlin.math.max
class Day24 {
data class Wind(val location: Coord2DInt, val orientation: Orientation) {
fun move(boundary: BBox2D): Coord2DInt {
val newLoc = location + orientation.direction
if (newLoc.x < boundary.x.first) newLoc.x = boundary.x.last.toInt()
if (newLoc.x > boundary.x.last) newLoc.x = boundary.x.first.toInt()
if (newLoc.y < boundary.y.first) newLoc.y = boundary.y.last.toInt()
if (newLoc.y > boundary.y.last) newLoc.y = boundary.y.first.toInt()
return newLoc
}
}
data class Valley(val start: Coord2DInt,
val end: Coord2DInt,
val winds: MutableList<Wind> = mutableListOf(),
val boundary: BBox2D)
fun parseInput(input: List<String>): Valley {
val start = Coord2DInt(0, input.first().indexOf('.'))
val end = Coord2DInt(input.lastIndex, input.last().indexOf('.'))
val winds = mutableListOf<Wind>()
val directions = mapOf(
'<' to Orientation.WEST,
'>' to Orientation.EAST,
'^' to Orientation.NORTH,
'v' to Orientation.SOUTH
)
for (i in input.indices) {
for (j in input[i].indices) {
if (input[i][j] in directions.keys) {
winds += Wind(
Coord2DInt(i, j),
directions[input[i][j]]!!
)
}
}
}
val boundary = BBox2D(
1L until input.lastIndex,
1L until input[0].lastIndex
)
return Valley(start, end, winds, boundary)
}
fun getObstaclesAtTime(cache: MutableMap<Int, List<Wind>>, boundary: BBox2D, time: Int): Set<Coord2DInt> {
if (time < 0) return emptySet()
if (time !in cache.keys) {
getObstaclesAtTime(cache, boundary, time - 1)
cache[time] = cache[time - 1]!!.map { Wind(it.move(boundary), it.orientation) }
}
return cache[time]!!.map { it.location }.toSet()
}
}
fun main() {
val day = Day24()
fun part1(input: List<String>): Int {
val valley = day.parseInput(input)
println("${valley.start} --> ${valley.end}")
println(valley.boundary)
val possibleMoves = listOf(
Orientation.NORTH.direction,
Orientation.SOUTH.direction,
Orientation.WEST.direction,
Orientation.EAST.direction,
Coord2DInt(0, 0) // stay still
)
val obstacleCache = mutableMapOf<Int, List<Day24.Wind>>()
obstacleCache[0] = valley.winds.toList()
val path = aStar(
valley.start to 0,
{ (coord, _) -> coord == valley.end },
{ (coord, time) -> possibleMoves
.map { it + coord to time + 1 }
.filter { it.first in valley.boundary || it.first == valley.end || it.first == valley.start }
.filter { it.first !in day.getObstaclesAtTime(obstacleCache, valley.boundary, it.second) }},
{ (coord, time) -> max(abs(coord.x - valley.end.x), abs(coord.y - valley.end.y)) * 1.0 }
)
return path.size
}
fun part2(input: List<String>): Int {
val valley = day.parseInput(input)
println("${valley.start} --> ${valley.end} --> ${valley.start} --> ${valley.end}")
println(valley.boundary)
val possibleMoves = listOf(
Orientation.NORTH.direction,
Orientation.SOUTH.direction,
Orientation.WEST.direction,
Orientation.EAST.direction,
Coord2DInt(0, 0) // stay still
)
val obstacleCache = mutableMapOf<Int, List<Day24.Wind>>()
obstacleCache[0] = valley.winds.toList()
val path1 = aStar(
valley.start to 0,
{ (coord, _) -> coord == valley.end },
{ (coord, time) -> possibleMoves
.map { it + coord to time + 1 }
.filter { it.first in valley.boundary || it.first == valley.end || it.first == valley.start }
.filter { it.first !in day.getObstaclesAtTime(obstacleCache, valley.boundary, it.second) }},
{ (coord, time) -> max(abs(coord.x - valley.end.x), abs(coord.y - valley.end.y)) * 1.0 }
)
val path2 = aStar(
valley.end to path1.maxOf { it.second },
{ (coord, _) -> coord == valley.start },
{ (coord, time) -> possibleMoves
.map { it + coord to time + 1 }
.filter { it.first in valley.boundary || it.first == valley.end || it.first == valley.start }
.filter { it.first !in day.getObstaclesAtTime(obstacleCache, valley.boundary, it.second) }},
{ (coord, time) -> max(abs(coord.x - valley.start.x), abs(coord.y - valley.start.y)) * 1.0 }
)
val path3 = aStar(
valley.start to path2.maxOf { it.second },
{ (coord, _) -> coord == valley.end },
{ (coord, time) -> possibleMoves
.map { it + coord to time + 1 }
.filter { it.first in valley.boundary || it.first == valley.end || it.first == valley.start }
.filter { it.first !in day.getObstaclesAtTime(obstacleCache, valley.boundary, it.second) }},
{ (coord, time) -> max(abs(coord.x - valley.end.x), abs(coord.y - valley.end.y)) * 1.0 }
)
return path3.maxOf { it.second }
}
val test = readInput("Day24_test")
println("=== Part 1 (test) ===")
println(part1(test))
println("=== Part 2 (test) ===")
println(part2(test))
val input = readInput("Day24")
println("=== Part 1 (puzzle) ===")
println(part1(input))
println("=== Part 2 (puzzle) ===")
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 46a776181e5c9ade0b5e88aa3c918f29b1659b4c | 5,978 | Advent-Of-Code-2022 | Apache License 2.0 |
src/main/kotlin/day4/Day4.kt | mortenberg80 | 574,042,993 | false | {"Kotlin": 50107} | package day4
class Day4 {
fun getOrganizer(filename: String): SupplyOrganizer {
val readLines = this::class.java.getResourceAsStream(filename).bufferedReader().readLines()
return SupplyOrganizer(readLines)
}
}
class SupplyOrganizer(input: List<String>) {
val elfPairs = input.map { ElfPair(it) }
val fullyContained = elfPairs.count { it.fullyContains }
val overlapped = elfPairs.count { it.overlaps }
}
data class ElfPair(val input: String) {
private val firstSection = AssignedSection(input.split(",").first())
private val secondSection = AssignedSection(input.split(",").last())
val fullyContains = firstSection.sections.intersect(secondSection.sections) == firstSection.sections
|| secondSection.sections.intersect(firstSection.sections) == secondSection.sections
val overlaps = firstSection.sections.intersect(secondSection.sections).isNotEmpty()
override fun toString(): String {
return "ElfPair[${firstSection.range}][${secondSection.range}][fullyContains=$fullyContains][overlaps=$overlaps]"
}
}
data class AssignedSection(val input: String) {
val from = input.split("-")[0].toInt()
val to = input.split("-")[1].toInt()
val range = (from..to)
val sections = range.toSet()
override fun toString(): String {
return "AssignedSection[$range]"
}
}
fun main() {
val organizerTest = Day4().getOrganizer("/day4_test.txt")
val organizerInput = Day4().getOrganizer("/day4_input.txt")
//println("elfpairs: ${organizerTest.elfPairs}")
organizerInput.elfPairs.filter { !it.fullyContains }.forEach { println(it)}
println("Part 1 test: ${organizerTest.fullyContained}")
println("Part 1 input: ${organizerInput.fullyContained}")
println("Part 1 test: ${organizerTest.overlapped}")
println("Part 1 input: ${organizerInput.overlapped}")
}
| 0 | Kotlin | 0 | 0 | b21978e145dae120621e54403b14b81663f93cd8 | 1,886 | adventofcode2022 | Apache License 2.0 |
kotlin/src/katas/kotlin/sort/mergesort/MergeSort5.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.sort.mergesort
import nonstdlib.listOfInts
import nonstdlib.permutations
import nonstdlib.printed
import datsok.shouldEqual
import org.junit.Test
import java.util.*
import kotlin.random.Random
class MergeSort5Tests {
@Test fun `trivial examples`() {
emptyList<Int>().mergeSort() shouldEqual emptyList()
listOf(1).mergeSort() shouldEqual listOf(1)
}
@Test fun `sort list of 2 elements`() {
listOf(1, 2).mergeSort() shouldEqual listOf(1, 2)
listOf(2, 1).mergeSort() shouldEqual listOf(1, 2)
}
@Test fun `sort list of 3 elements`() {
listOf(1, 2, 3).mergeSort() shouldEqual listOf(1, 2, 3)
listOf(1, 3, 2).mergeSort() shouldEqual listOf(1, 2, 3)
listOf(2, 1, 3).mergeSort() shouldEqual listOf(1, 2, 3)
listOf(2, 3, 1).mergeSort() shouldEqual listOf(1, 2, 3)
listOf(3, 1, 2).mergeSort() shouldEqual listOf(1, 2, 3)
listOf(3, 2, 1).mergeSort() shouldEqual listOf(1, 2, 3)
}
@Test fun `sort list of 4 elements`() {
listOf(1, 2, 3, 4).permutations().forEach {
it.mergeSort() shouldEqual listOf(1, 2, 3, 4)
}
}
@Test fun `sort random list`() {
fun List<Int>.isSorted() = windowed(2).all { it[0] <= it[1] }
val list = Random.listOfInts(sizeRange = 0..100, valuesRange = 0..100).printed()
list.mergeSort().isSorted() shouldEqual true
}
}
private fun <E: Comparable<E>> List<E>.mergeSort(): List<E> {
fun merge(left: List<E>, right: List<E>): List<E> {
var i = 0
var j = 0
val result = ArrayList<E>()
while (i < left.size && j < right.size) {
if (left[i] < right[j]) result.add(left[i++])
else result.add(right[j++])
}
result.addAll(left.drop(i))
result.addAll(right.drop(j))
return result
}
val queue = LinkedList<List<E>>()
queue.addAll(map { listOf(it) })
while (queue.size > 1) {
val list1 = queue.removeFirst()
val list2 = queue.removeFirst()
queue.add(merge(list1, list2))
}
return queue.firstOrNull() ?: emptyList()
}
private fun <E: Comparable<E>> List<E>.mergeSort_recursive(): List<E> {
fun merge(left: List<E>, right: List<E>): List<E> {
return when {
left.isEmpty() -> right
right.isEmpty() -> left
left[0] < right[0] -> listOf(left[0]) + merge(left.drop(1), right)
else -> listOf(right[0]) + merge(left, right.drop(1))
}
}
if (size <= 1) return this
return merge(
subList(0, size / 2).mergeSort(),
subList(size / 2, size).mergeSort()
)
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 2,705 | katas | The Unlicense |
src/main/kotlin/g1201_1300/s1202_smallest_string_with_swaps/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1201_1300.s1202_smallest_string_with_swaps
// #Medium #String #Hash_Table #Depth_First_Search #Breadth_First_Search #Union_Find
// #2023_06_09_Time_562_ms_(100.00%)_Space_84.3_MB_(100.00%)
class Solution {
fun smallestStringWithSwaps(s: String, pairs: List<List<Int>>): String {
val uf = UF(s.length)
for (p in pairs) {
uf.union(p[0], p[1])
}
val freqMapPerRoot: MutableMap<Int, IntArray> = HashMap()
for (i in s.indices) {
freqMapPerRoot.computeIfAbsent(uf.find(i)) { IntArray(26) }[s[i].code - 'a'.code]++
}
val ans = CharArray(s.length)
for (i in ans.indices) {
val css = freqMapPerRoot[uf.find(i)]
for (j in css!!.indices) {
if (css[j] > 0) {
ans[i] = (j + 'a'.code).toChar()
css[j]--
break
}
}
}
return String(ans)
}
internal class UF(n: Int) {
var root: IntArray
var rank: IntArray
init {
root = IntArray(n)
rank = IntArray(n)
for (i in 0 until n) {
root[i] = i
rank[i] = 1
}
}
fun find(u: Int): Int {
if (u == root[u]) {
return u
}
root[u] = find(root[u])
return root[u]
}
fun union(u: Int, v: Int) {
val ru = find(root[u])
val rv = find(root[v])
if (ru != rv) {
if (rank[ru] < rank[rv]) {
root[ru] = root[rv]
} else if (rank[ru] > rank[rv]) {
root[rv] = root[ru]
} else {
root[rv] = root[ru]
rank[ru]++
}
}
}
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,884 | LeetCode-in-Kotlin | MIT License |
project/src/problems/Sorting.kt | informramiz | 173,284,942 | false | null | package problems
import extensions.swap
//https://codility.com/media/train/4-Sorting.pdf
object Sorting {
fun selectionSort(A: Array<Int>): Array<Int> {
for (i in 0 until A.size-1) {
val minimumElementIndex = findIndexOfMinimum(A, i+1)
A.swap(i, minimumElementIndex)
}
return A
}
private fun findIndexOfMinimum(A: Array<Int>, startIndex: Int): Int {
var min = A[startIndex]
var minIndex = startIndex
for (i in startIndex+1 until A.size) {
if (min > A[i]) {
min = A[i]
minIndex = i
}
}
return minIndex
}
/**
* Counting sort (time = O(n + k)) is only used when we know the
* the numbers range [0...k]
* NOTE: This program does not support negative numbers, we can add
* negative numbers support by either shifting all elements some number so that
* the minimum negative number becomes 0 or we can count negative numbers in a separate array
*/
fun countingSort(A: Array<Int>, maximumPossibleNumberInArray: Int): Array<Int> {
//make an array for the possible number range
val counter = Array(maximumPossibleNumberInArray + 1) {0}
//count all the numbers in array
A.forEach { value ->
counter[value]++
}
//for all the possible numbers in range [0...k]
//go through each if its count is greater than 0 then add to array A
//that many times
var indexA = 0
counter.forEachIndexed { number, count ->
for (i in 0 until count) {
A[indexA] = number
indexA++
}
}
return A
}
fun mergeSort(A: Array<Int>) {
_mergeSort(A,0, A.size)
}
private fun _mergeSort(A: Array<Int>, start: Int, end: Int) {
if ((end - start) < 2) { //size = 1, so already sorted
return
}
val middle = (start + end) / 2
_mergeSort(A, start, middle)
_mergeSort(A, middle, end)
mergeArray(A, start, middle, end)
}
private fun mergeArray(destination: Array<Int>, start: Int, middle: Int, end: Int) {
var start1 = start
var start2 = middle
val copy = destination.copyOf()
for (i in start until end) {
if (start1 < middle && (start2 >= end || copy[start1] <= copy[start2])) {
destination[i] = copy[start1]
start1++
} else {
destination[i] = copy[start2]
start2++
}
}
}
/**
* You are given a zero-indexed array A consisting of n > 0 integers; you must return
* the number of unique values in array A.
*/
fun countDistinctNumbers(A: Array<Int>): Int {
/**
* First, sort array A; similar values will then be next to each other.
* Finally, just count the number of distinct pairs in adjacent cells.
*/
if (A.isEmpty()) {
return 0
}
A.sort()
var distinctCount = 1
for (i in 0 until A.size-1) {
if (A[i] != A[i + 1]) {
distinctCount++
}
}
return distinctCount
}
/**
* https://app.codility.com/programmers/lessons/6-sorting/max_product_of_three/
*
* MaxProductOfThree
* Maximize A[P] * A[Q] * A[R] for any triplet (P, Q, R).
* Note: Array size n is in range [3..100_000] and
* A[i] is in range [−1,000..1,000].
*/
fun maxProductOfThree(A: Array<Int>): Int {
A.sort()
//the biggest product can be achieved by following 2 ways
//1. 3 biggest positive numbers
//2. 1 biggest positive number, 2 biggest (in terms of absolute value) negative numbers because
// multiplying 2 negative numbers will result in positive number
//first check the the case-1 (biggest positive numbers)
val maxProduct = A[A.lastIndex] * A[A.lastIndex-1] * A[A.lastIndex-2]
//as array is sorted so biggest (in terms of absolute value) will be on start of array (A[0], A[1])
val maxProductWith2NegativeNumbers = A[A.lastIndex] * A[0] * A[1]
return Math.max(maxProduct, maxProductWith2NegativeNumbers)
}
/**
* https://app.codility.com/programmers/lessons/6-sorting/triangle/
* Triangle
* Determine whether a triangle can be built from a given set of edges.
*/
fun isTriangularTripletPresent(A: Array<Int>): Int {
if (A.size < 3) return 0
A.sort()
for (i in 0 until A.size - 2) {
//after sorting numbers have to be adjacent to fulfill triplet condition
//otherwise there value distance will be greater enough to violate at least 1 condition
val p = A[i]
val q = A[i + 1]
val r = A[i + 2]
if (isTriangularTriplet(p, q, r)) {
return 1
}
}
return 0
}
private fun isTriangularTriplet(p: Int, q: Int, r: Int): Boolean {
val condition1 = p.toLong() + q > r
val condition2 = q.toLong() + r > p
val condition3 = r.toLong() + p > q
return condition1 && condition2 && condition3
}
/**
* Disc Intersections
*/
fun calculateDiscIntersections(A: Array<Int>): Int {
val MAX_PAIRS_ALLOWED = 10_000_000L
//calculate startX and endX for each disc
//as y is always 0 so we don't care about it. We only need X
val ranges = Array(A.size) { i ->
calculateXRange(i, A[i])
}
//sort Xranges by the startX
ranges.sortBy { range ->
range.start
}
val starts = Array(ranges.size) {index ->
ranges[index].start
}
var count = 0
for (i in 0 until ranges.size) {
val checkRange = ranges[i]
//find the right most disc whose start is less than or equal to end of current disc
val index = bisectRight(starts, checkRange.endInclusive, i)
//the number of discs covered by this disc are:
//count(the next disc/range ... to the last disc/range covered by given disc/range)
//example: given disc index = 3, last covered (by given disc) disc index = 5
//count = 5 - 3 = 2
//because there are only 2 discs covered by given disc
// (immediate next disc with index 4 and last covered disc at index 5)
val intersections = (index - i)
//because we are only considering discs intersecting/covered by a given disc to the right side
//and ignore any discs that are intersecting on left (because previous discs have already counted those
// when checking for their right intersects) so this calculation avoids any duplications
count += intersections
if (count > MAX_PAIRS_ALLOWED) {
return -1
}
}
return if (count > MAX_PAIRS_ALLOWED) {
-1
} else {
count
}
}
private fun calculateXRange(x: Int, r: Int): LongRange {
val minX = x - r.toLong()
val maxX = x + r.toLong()
return LongRange(minX, maxX)
}
private fun doesIntersect(srcRange: LongRange, chkRange: LongRange): Boolean {
return srcRange.start in chkRange || srcRange.endInclusive in chkRange
}
fun binarySearch(array: Array<Int>, key: Int): Int {
var start = 0
var end = array.size - 1
while (start <= end) {
val mid = Math.ceil((start + end) / 2.0).toInt()
val midValue = array[mid]
when {
midValue == key ->
return mid
midValue < key -> // key is in right half part
start = mid + 1
else -> //key is in first half of the array
end = mid - 1
}
}
return -1
}
fun bisectRight(array: Array<Long>, key: Long, arrayStart: Int = 0): Int {
var start = arrayStart
var end = array.size - 1
var bisect = start
while (start <= end) {
val mid = Math.ceil((start + end) / 2.0).toInt()
val midValue = array[mid]
val indexAfterMid = mid + 1
if (key >= midValue) {
bisect = mid
}
if (key >= midValue && (indexAfterMid > end || key < array[indexAfterMid])) {
break
} else if (key < midValue) {
end = mid - 1
} else {
start = mid + 1
}
}
return bisect
}
} | 0 | Kotlin | 0 | 0 | a38862f3c36c17b8cb62ccbdb2e1b0973ae75da4 | 8,805 | codility-challenges-practice | Apache License 2.0 |
src/Day11.kt | LauwiMeara | 572,498,129 | false | {"Kotlin": 109923} | const val RELIEF = 3
const val ROUNDS_PART_1 = 20
const val ROUNDS_PART_2 = 10000
data class Monkey (val items: MutableList<Long>, val operation: List<String>, val testDivisibleBy: Int, val indexIfTestTrue: Int, val indexIfTestFalse: Int, var totalNumOfInspectedItems: Int)
fun main() {
fun getMonkeys(input: List<String>): List<Monkey> {
val monkeys = mutableListOf<Monkey>()
for (line in input) {
val monkey = line.split(System.lineSeparator())
val items = monkey[1].split(": ",", ").drop(1).map{it.toLong()}.toMutableList()
val operation = monkey[2].substringAfter("new = old ").split(" ")
val testDivisibleBy = monkey[3].substringAfter("divisible by ").toInt()
val indexIfTestTrue = monkey[4].substringAfter("monkey ").toInt()
val indexIfTestFalse = monkey[5].substringAfter("monkey ").toInt()
monkeys.add(Monkey(items, operation, testDivisibleBy, indexIfTestTrue, indexIfTestFalse, 0))
}
return monkeys
}
fun part1(input: List<String>): Int {
val monkeys = getMonkeys(input)
for (round in 1..ROUNDS_PART_1) {
for (monkey in monkeys) {
for (i in monkey.items.indices) {
var item = monkey.items[i]
// Monkey plays with the item. Worry intensifies.
val worry = if (monkey.operation.last() == "old") item else monkey.operation.last().toLong()
when (monkey.operation.first()) {
"*" -> item *= worry
else -> item += worry
}
// Monkey gets bored with the item. Worry calms down.
item /= RELIEF
// Monkey throws the item to a different monkey.
if (item.toInt() % monkey.testDivisibleBy == 0) {
monkeys[monkey.indexIfTestTrue].items.add(item)
} else {
monkeys[monkey.indexIfTestFalse].items.add(item)
}
monkey.totalNumOfInspectedItems++
}
monkey.items.clear()
}
}
return monkeys.map{it.totalNumOfInspectedItems}.sortedDescending().subList(0, 2).reduce{acc, it -> acc * it}
}
fun part2(input: List<String>): Long {
val monkeys = getMonkeys(input)
val totalTestDivisibleBy = monkeys.map{it.testDivisibleBy}.reduce{acc, it -> acc * it}
for (round in 1..ROUNDS_PART_2) {
for (monkey in monkeys) {
for (i in monkey.items.indices) {
var item = monkey.items[i]
// Monkey plays with the item. Worry intensifies.
val worry = if (monkey.operation.last() == "old") item else monkey.operation.last().toLong()
when (monkey.operation.first()) {
"*" -> item *= worry
else -> item += worry
}
// Keep worry level manageable by dividing by the totalTestDivisibleBy.
item %= totalTestDivisibleBy
// Monkey throws the item to a different monkey.
if (item % monkey.testDivisibleBy == 0L) {
monkeys[monkey.indexIfTestTrue].items.add(item)
} else {
monkeys[monkey.indexIfTestFalse].items.add(item)
}
monkey.totalNumOfInspectedItems++
}
monkey.items.clear()
}
}
return monkeys.map{it.totalNumOfInspectedItems.toLong()}.sortedDescending().subList(0, 2).reduce{acc, it -> acc * it}
}
val input = readInputSplitByDelimiter("Day11", "${System.lineSeparator()}${System.lineSeparator()}")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 1 | 34b4d4fa7e562551cb892c272fe7ad406a28fb69 | 3,952 | AoC2022 | Apache License 2.0 |
src/leetcodeProblem/leetcode/editor/en/NumberOfValidWordsForEachPuzzle.kt | faniabdullah | 382,893,751 | false | null | //With respect to a given puzzle string, a word is valid if both the following
//conditions are satisfied:
//
// word contains the first letter of puzzle.
// For each letter in word, that letter is in puzzle.
//
// For example, if the puzzle is "abcdefg", then valid words are "faced",
//"cabbage", and "baggage", while
// invalid words are "beefed" (does not include 'a') and "based" (includes 's'
//which is not in the puzzle).
//
//
//
//Return an array answer, where answer[i] is the number of words in the given
//word list words that is valid with respect to the puzzle puzzles[i].
//
// Example 1:
//
//
//Input: words = ["aaaa","asas","able","ability","actt","actor","access"],
//puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"]
//Output: [1,1,3,2,4,0]
//Explanation:
//1 valid word for "aboveyz" : "aaaa"
//1 valid word for "abrodyz" : "aaaa"
//3 valid words for "abslute" : "aaaa", "asas", "able"
//2 valid words for "absoryz" : "aaaa", "asas"
//4 valid words for "actresz" : "aaaa", "asas", "actt", "access"
//There are no valid words for "gaswxyz" cause none of the words in the list
//contains letter 'g'.
//
//
// Example 2:
//
//
//Input: words = ["apple","pleas","please"], puzzles = ["aelwxyz","aelpxyz",
//"aelpsxy","saelpxy","xaelpsy"]
//Output: [0,1,3,2,0]
//
//
//
// Constraints:
//
//
// 1 <= words.length <= 10⁵
// 4 <= words[i].length <= 50
// 1 <= puzzles.length <= 10⁴
// puzzles[i].length == 7
// words[i] and puzzles[i] consist of lowercase English letters.
// Each puzzles[i] does not contain repeated characters.
//
// Related Topics Array Hash Table String Bit Manipulation Trie 👍 676 👎 57
package leetcodeProblem.leetcode.editor.en
class NumberOfValidWordsForEachPuzzle {
fun solution() {
}
//below code will be used for submission to leetcode (using plugin of course)
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun findNumOfValidWords(words: Array<String>, puzzles: Array<String>): List<Int> {
// still find solution
return listOf()
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
fun main() {}
| 0 | Kotlin | 0 | 6 | ecf14fe132824e944818fda1123f1c7796c30532 | 2,232 | dsa-kotlin | MIT License |
src/Day24.kt | illarionov | 572,508,428 | false | {"Kotlin": 108577} | import Day24.Blizzard
import Day24.Direction.*
import Day24.Valley
import Day24.XY
fun main() {
val testInput = readInput("Day24_test")
.parseValley()
val input = readInput("Day24")
.parseValley()
part1(testInput).also {
println("Part 1, test input: $it")
check(it == 18)
}
part1(input).also {
println("Part 1, real input: $it")
check(it == 334)
}
part2(testInput).also {
println("Part 2, test input: $it")
check(it == 54)
}
part2(input).also {
println("Part 2, real input: $it")
check(it == 934)
}
}
private object Day24 {
data class XY(val x: Int, val y: Int)
enum class Direction { UP, DOWN, LEFT, RIGHT }
private val Direction.printChar: Char
get() = when (this) {
UP -> '^'
DOWN -> 'v'
LEFT -> '<'
RIGHT -> '>'
}
data class Blizzard(
val xy: XY,
val direction: Direction
)
class Valley(
val width: Int,
val height: Int,
val blizzards: List<Blizzard>,
val initialPosition: XY,
val endPosition: XY
) {
private val blizzardsMapCache: MutableMap<Int, Set<XY>> = mutableMapOf()
fun getBlizzardsMap(pMinute: Int): Set<XY> {
val minute = pMinute % (width * height)
return blizzardsMapCache.getOrPut(minute) {
blizzards.mapTo(mutableSetOf()) { b ->
val xy = when (b.direction) {
UP -> b.xy.copy(y = (b.xy.y - minute).mod(height))
DOWN -> b.xy.copy(y = (b.xy.y + minute).mod(height))
LEFT -> b.xy.copy(x = (b.xy.x - minute).mod(width))
RIGHT -> b.xy.copy(x = (b.xy.x + minute).mod(width))
}
xy
}
}
}
fun print() {
val blizzardsGroup = blizzards.groupBy { it.xy }
val enter = " ".repeat(initialPosition.x) + "E"
println(enter)
(0 until height).forEach { y ->
val s = (0 until width).map { x ->
blizzardsGroup[XY(x, y)]?.let {
if (it.size == 1) {
it[0].direction.printChar
} else {
it.size.digitToChar(64)
}
} ?: '.'
}.joinToString("")
println(s)
}
val exit = " ".repeat(endPosition.x) + "L"
println(exit)
}
}
}
private fun part1(valley: Valley): Int {
return getMinimalTimePath(valley, 0)
}
private fun part2(input: Valley): Int {
val timeFirstTrip = getMinimalTimePath(input, 0)
println("Time first trip: $timeFirstTrip")
val valleyBack = Valley(
width = input.width,
height = input.height,
blizzards = input.blizzards,
initialPosition = input.endPosition,
endPosition = input.initialPosition
)
val timeBack = getMinimalTimePath(valleyBack, timeFirstTrip)
println("Time back: $timeBack")
val timeSecondTrip = getMinimalTimePath(input, timeBack)
println("Time second trip: $timeSecondTrip")
return timeSecondTrip
}
private fun getMinimalTimePath(valley: Valley, startMinute: Int): Int {
data class State(
val minute: Int,
val xy: XY,
)
data class CacheKey(
val xy: XY,
val blizzardOffset: Int
)
var bestTime = Int.MAX_VALUE
val cache: MutableMap<CacheKey, Int> = mutableMapOf()
val q: ArrayDeque<State> = ArrayDeque()
q.addLast(
State(
minute = startMinute,
xy = valley.initialPosition,
)
)
fun enqueueIfApplicable(newMinute: Int, newXY: XY) {
if (newMinute >= bestTime
) {
return
}
if (newXY == valley.endPosition) {
//println("Found path in ${newMinute} minutes")
bestTime = newMinute
return
}
if ((newXY.x !in 0 until valley.width
|| newXY.y !in 0 until valley.height)
&& (newXY != valley.initialPosition)
) {
return
}
val blizzardSet = valley.getBlizzardsMap(newMinute)
if (newXY in blizzardSet) {
return
}
val cacheKey = CacheKey(
xy = newXY,
blizzardOffset = newMinute % (valley.width * valley.height)
)
cache[cacheKey]?.let { k ->
if (k <= newMinute) {
return
}
}
cache[cacheKey] = newMinute
q.addLast(
State(
minute = newMinute,
xy = newXY,
)
)
}
while (!q.isEmpty()) {
val s = q.removeFirst()
// DOWN
enqueueIfApplicable(
newMinute = s.minute + 1,
newXY = s.xy.copy(y = s.xy.y + 1)
)
// RIGHT
enqueueIfApplicable(
newMinute = s.minute + 1,
newXY = s.xy.copy(x = s.xy.x + 1)
)
// UP
enqueueIfApplicable(
newMinute = s.minute + 1,
newXY = s.xy.copy(y = s.xy.y - 1)
)
// LEFT
enqueueIfApplicable(
newMinute = s.minute + 1,
newXY = s.xy.copy(x = s.xy.x - 1)
)
// WAIT
enqueueIfApplicable(
newMinute = s.minute + 1,
newXY = s.xy
)
}
return bestTime
}
private fun List<String>.parseValley(): Valley {
val initialX = this[0].indexOf('.') - 1
val endX = this.last().indexOf('.') - 1
val width = this[0].length - 2
val height = this.size - 2
val blizzards: List<Blizzard> = this.flatMapIndexed { y: Int, s: String ->
s.mapIndexedNotNull { x, c ->
val xy = XY(x - 1, y - 1)
when (c) {
'<' -> Blizzard(xy, LEFT)
'>' -> Blizzard(xy, RIGHT)
'^' -> Blizzard(xy, UP)
'v' -> Blizzard(xy, DOWN)
else -> null
}
}
}
return Valley(
width = width,
height = height,
blizzards = blizzards,
initialPosition = XY(initialX, -1),
endPosition = XY(endX, height)
)
} | 0 | Kotlin | 0 | 0 | 3c6bffd9ac60729f7e26c50f504fb4e08a395a97 | 6,436 | aoc22-kotlin | Apache License 2.0 |
src/Day04.kt | erikthered | 572,804,470 | false | {"Kotlin": 36722} | fun main() {
fun part1(input: List<String>): Int {
var contained = 0
for(line in input) {
val (a, b) = line.split(",").map { getSections(it) }
if(a.containsAll(b) || b.containsAll(a))
contained += 1
}
return contained
}
fun part2(input: List<String>): Int {
var overlap = 0
for(line in input) {
val (a, b) = line.split(",").map { getSections(it) }
if(a.intersect(b).isNotEmpty())
overlap += 1
}
return overlap
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
fun getSections(range: String): Set<Int> {
val (lower, upper) = range.split("-").map { it.toInt() }
return lower.rangeTo(upper).toSet()
}
| 0 | Kotlin | 0 | 0 | 3946827754a449cbe2a9e3e249a0db06fdc3995d | 996 | aoc-2022-kotlin | Apache License 2.0 |
src/main/aoc2021/Day12.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2021
class Day12(input: List<String>) {
private val graph = parseInput(input)
private fun String.isEnd() = equals("end")
private fun String.isStart() = equals("start")
private fun String.isSmall() = first().isLowerCase() // It's all lowercase or all uppercase
private fun parseInput(input: List<String>): Map<String, Set<String>> {
return mutableMapOf<String, Set<String>>()
.withDefault { setOf() }
.apply {
input.map { it.split("-") }
.forEach { (first, second) ->
this[first] = getValue(first) + second
this[second] = getValue(second) + first
}
}
}
private fun canVisit(node: String, visited: List<String>, revisitsLeft: Int): Boolean {
return when {
!node.isSmall() -> true // can always go to large caves
node.isStart() -> false // can't go back to the start
revisitsLeft > 0 -> true // it's still possible to revisit small caves
node in visited -> false // no further revisits are allowed
else -> true
}
}
/**
* Recursive function to count the number of paths leading to the end.
*/
private fun countPaths(currentNode: String, visited: List<String>, revisitsRemaining: Int): Int {
if (currentNode.isEnd()) {
return 1
}
val possibilities = graph.getValue(currentNode).filter { canVisit(it, visited, revisitsRemaining) }
val nextVisited = visited.toMutableList().also { it.add(currentNode) }
return possibilities.sumOf { next ->
val remaining = if (next.isSmall() && next in visited) revisitsRemaining - 1 else revisitsRemaining
countPaths(next, nextVisited, remaining)
}
}
fun solvePart1(): Int {
return countPaths("start", listOf(), 0)
}
fun solvePart2(): Int {
return countPaths("start", listOf(), 1)
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 2,025 | aoc | MIT License |
src/main/kotlin/day7/Day7.kt | alxgarcia | 435,549,527 | false | {"Kotlin": 91398} | package day7
import java.io.File
import kotlin.math.abs
fun parseInput(input: String) = input.split(",").groupingBy(String::toInt).eachCount()
private fun minFuelSpentToAlignedPosition(data: Map<Int, Int>, costFn: (Int, Int) -> Int): Int {
val min = data.keys.minOf { it }
val max = data.keys.maxOf { it }
return (min..max)
.map { destination -> data.map { (currentPosition, crabs) -> costFn(destination, currentPosition) * crabs } }
.minOf { it.sum() }
}
fun minFuelSpentToAlignedPosition(data: Map<Int, Int>): Int =
minFuelSpentToAlignedPosition(data){ destination, currentPosition -> abs(destination - currentPosition)}
fun minFuelSpentToAlignedPositionPart2(data: Map<Int, Int>): Int =
minFuelSpentToAlignedPosition(data){ destination: Int, currentPosition: Int ->
val steps = abs(currentPosition - destination)
((steps * (steps + 1)) / 2)
}
fun main() {
File("./input/day7.txt").useLines { lines ->
val crabsMap = parseInput(lines.first())
println("First part: ${minFuelSpentToAlignedPosition(crabsMap)}")
println("Second part: ${minFuelSpentToAlignedPositionPart2(crabsMap)}")
}
}
| 0 | Kotlin | 0 | 0 | d6b10093dc6f4a5fc21254f42146af04709f6e30 | 1,139 | advent-of-code-2021 | MIT License |
src/Day03.kt | zhiqiyu | 573,221,845 | false | {"Kotlin": 20644} | import kotlin.math.max
import kotlin.math.abs
fun main() {
fun getPriority(item: Char): Int {
if (item.isLowerCase()) {
return item.minus('a') + 1
} else {
return item.minus('A') + 27
}
}
fun part1(input: List<String>): Int {
var result = 0
for (line in input) {
var seen = hashSetOf<Char>()
var duplicates = hashSetOf<Char>()
for (i in line.indices) {
if (i < line.length / 2) {
seen.add(line.get(i))
} else {
if (seen.contains(line.get(i))) {
duplicates.add(line.get(i))
}
}
}
for (item in duplicates) {
result += getPriority(item)
}
}
return result
}
fun part2(input: List<String>): Int {
var result = 0
for (i in 0..input.lastIndex step 3) {
var dup = input.get(i).toMutableList() intersect (input.get(i+1).toMutableList() intersect input.get(i+2).toMutableList())
var badge = dup.iterator().next()
result += getPriority(badge)
}
return result
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println("----------")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d3aa03b2ba2a8def927b94c2b7731663041ffd1d | 1,608 | aoc-2022 | Apache License 2.0 |
src/Day07.kt | cisimon7 | 573,872,773 | false | {"Kotlin": 41406} | fun main() {
fun getNestedDirectories(folder: FileSystem.Storage): List<FileSystem.Storage> {
val directories = mutableListOf<FileSystem.Storage>()
val stack = mutableListOf(folder to false)
while (stack.isNotEmpty()) {
val (storage, checked) = stack.last()
if (checked) stack.removeLast() else {
val fs = storage.fileSystem.filterIsInstance<FileSystem.Storage>()
when (fs.isEmpty()) {
true -> stack.removeLast()
false -> {
directories.addAll(fs)
stack.removeLast()
stack += fs.map { it to false }
}
}
}
}
return directories + folder
}
fun part1(root: FileSystem.Storage): Int {
val directories = getNestedDirectories(root)
return directories.map { it.size }.filter { it <= 100_000 }.sum()
}
fun part2(root: FileSystem.Storage): Int {
val directories = getNestedDirectories(root)
return directories.filter { 30_000_000 <= (70_000_000 - root.size + it.size) }.minOf { it.size }
}
fun parse(stringList: List<String>): FileSystem.Storage {
val inputOutput = stringList.joinToString("\n").split("$").drop(1).map { it.trim() }
var stack: FileSystem.Storage = FileSystem.Storage.Root()
val root = stack
for (io in inputOutput.drop(1)) {
when (io.substring(0, 2)) {
"ls" -> {
val fs = io.lines().drop(1).asFileSystem(stack)
stack.fileSystem += fs
}
"cd" -> {
val path = io.removePrefix("cd ").trim()
stack = if (path.contains("..")) {
stack.parentDir ?: error("illegal move")
} else if (path.contains("/")) {
root
} else {
stack.fileSystem.filterIsInstance<FileSystem.Storage>().firstOrNull { it.name == path }
?: error("tried to cd into a file or none existent directory")
}
}
}
}
return root
}
val testInput = readInput("Day07_test")
check(part1(parse(testInput)) == 95_437)
check(part2(parse(testInput)) == 24_933_642)
val input = readInput("Day07_input")
println(part1(parse(input)))
println(part2(parse(input)))
}
/* Code copied from Jetbrains <NAME> */
private fun List<String>.asFileSystem(parent: FileSystem.Storage): List<FileSystem> {
return map { elem ->
when {
elem.startsWith("dir") -> {
FileSystem.Storage.Directory(name = elem.removePrefix("dir "), parent)
}
elem.first().isDigit() -> {
val (size, name) = elem.split(" ")
FileSystem.File(name.trim(), size.toInt(), parent)
}
else -> error("Malformed input")
}
}
}
sealed interface FileSystem {
var name: String
var size: Int
val parentDir: Storage?
class File(override var name: String, val fSize: Int, override val parentDir: Storage?) : FileSystem {
override var size = fSize
}
sealed interface Storage : FileSystem {
val fileSystem: MutableList<FileSystem>
override var size: Int
get() = fileSystem.sumOf { it.size }
set(value) {}
class Directory(
override var name: String,
override val parentDir: Storage?,
override val fileSystem: MutableList<FileSystem> = mutableListOf()
) : Storage
class Root(
override var name: String = "/",
override val parentDir: Storage? = null,
override val fileSystem: MutableList<FileSystem> = mutableListOf()
) : Storage
}
}
| 0 | Kotlin | 0 | 0 | 29f9cb46955c0f371908996cc729742dc0387017 | 3,974 | aoc-2022 | Apache License 2.0 |
src/Day09.kt | spaikmos | 573,196,976 | false | {"Kotlin": 83036} | fun main() {
val DIM = 1000
val START = DIM/2
fun part1(input: List<String>): Int {
val head = intArrayOf(START, START)
var tail = intArrayOf(START, START)
val seen = mutableSetOf(Pair(START, START))
for (i in input) {
val parts = i.split(" ")
val dir = parts[0][0]
val dist = parts[1].toInt()
for (j in 1..dist) {
val prev = head.clone()
// Move the head
when (dir) {
'U' -> head[1]++
'D' -> head[1]--
'L' -> head[0]--
'R' -> head[0]++
}
// Tail only moves if head is more than 2 spaces away in any direction
if ((kotlin.math.abs(head[0] - tail[0]) > 1) ||
(kotlin.math.abs(head[1] - tail[1]) > 1)) {
// If the tail moves, it occupies the previous space that head was at
tail = prev
// Add the position to the set of visited positions
seen.add(Pair(tail[0], tail[1]))
}
}
}
return seen.size
}
fun part2(input: List<String>): Int {
val knot = Array(10){Array(2){START}}
val seen = mutableSetOf(Pair(START, START))
for (i in input) {
val parts = i.split(" ")
val dir = parts[0][0]
val dist = parts[1].toInt()
for (j in 1..dist) {
// Move the head
when (dir) {
'U' -> knot[0][1]++
'D' -> knot[0][1]--
'L' -> knot[0][0]--
'R' -> knot[0][0]++
}
for (k in 1..9) {
if ((kotlin.math.abs(knot[k-1][0] - knot[k][0]) > 1) &&
(kotlin.math.abs(knot[k-1][1] - knot[k][1]) > 1)) {
// Previous knot moved diagonally. This needs to move in same direction
knot[k][0] = (knot[k-1][0] + knot[k][0]) / 2
knot[k][1] = (knot[k-1][1] + knot[k][1]) / 2
} else if (kotlin.math.abs(knot[k-1][0] - knot[k][0]) > 1) {
knot[k][0] = (knot[k-1][0] + knot[k][0]) / 2
knot[k][1] = knot[k-1][1]
} else if (kotlin.math.abs(knot[k-1][1] - knot[k][1]) > 1) {
knot[k][1] = (knot[k-1][1] + knot[k][1]) / 2
knot[k][0] = knot[k-1][0]
} else {
// Chain has stopped moving, no need to process the rest of the knots
break
}
}
// Add the position to the set of visited positions
seen.add(Pair(knot[9][0], knot[9][1]))
}
}
return seen.size
}
val input = readInput("../input/Day09")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 6fee01bbab667f004c86024164c2acbb11566460 | 3,059 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/dev/paulshields/aoc/Day5.kt | Pkshields | 433,609,825 | false | {"Kotlin": 133840} | /**
* Day 5: Hydrothermal Venture
*/
package dev.paulshields.aoc
import dev.paulshields.aoc.common.Point
import dev.paulshields.aoc.common.readFileAsStringList
fun main() {
println(" ** Day 5: Hydrothermal Venture ** \n")
val rawHydrothermalVents = readFileAsStringList("/Day5HydrothermalVentsLineSegments.txt")
val hydrothermalVents = rawHydrothermalVents.map {
it.split(" -> ").map {
it.split(",")
.mapNotNull { it.toIntOrNull() }
.let(Point::fromList)
}.let(LineSegment::fromList)
}
val ventsExcludingDiagonals = hydrothermalVents.filter { it.start.x == it.end.x || it.start.y == it.end.y }
val numberOfOverlapPointExcludingDiagonals = countPointsWhereLinesOverlap(ventsExcludingDiagonals)
println("There are $numberOfOverlapPointExcludingDiagonals points where the hydrothermal vents overlap excluding diagonals")
val numberOfOverlapPoints = countPointsWhereLinesOverlap(hydrothermalVents)
println("There are $numberOfOverlapPoints points where the hydrothermal vents overlap including diagonals")
}
fun countPointsWhereLinesOverlap(lineSegments: List<LineSegment>) =
lineSegments.flatMap { it.pointsOnLine }
.groupingBy { it }
.eachCount()
.filter { it.value > 1 }
.count()
data class LineSegment(val start: Point, val end: Point) {
companion object {
fun fromList(xy: List<Point>) = LineSegment(xy.component1(), xy.component2())
}
val pointsOnLine = if (start.x == end.x) {
directionlessRange(start.y, end.y).map { Point(start.x, it) }
} else if (start.y == end.y) {
directionlessRange(start.x, end.x).map { Point(it, start.y) }
} else {
directionlessRange(start.x, end.x).zip(directionlessRange(start.y, end.y)).map { Point(it.first, it.second) }
}
}
private fun directionlessRange(start: Int, end: Int) = if (start < end) (start..end) else (start downTo end)
| 0 | Kotlin | 0 | 0 | e3533f62e164ad72ec18248487fe9e44ab3cbfc2 | 1,969 | AdventOfCode2021 | MIT License |
src/main/kotlin/aoc2020/day05_binary_boarding/BinaryBoarding.kt | barneyb | 425,532,798 | false | {"Kotlin": 238776, "Shell": 3825, "Java": 567} | package aoc2020.day05_binary_boarding
fun main() {
util.solve(842, ::partOne)
util.solve(617, ::partTwo)
}
private val IntRange.size
get() = last - start + 1
private fun IntRange.partition(c: Char) = when (c) {
'F', 'L' -> start..(last - size / 2)
'B', 'R' -> (start + size / 2)..last
else -> throw IllegalArgumentException("Unknown '$c' partition")
}
fun seatId(pass: String): Int {
val r = pass.subSequence(0, 7).fold(0..127, IntRange::partition)
assert(r.size == 1)
val s = pass.substring(7).fold(0..7, IntRange::partition)
assert(s.size == 1)
return r.first * 8 + s.first
}
fun partOne(input: String) =
input
.lines()
.maxOf(::seatId)
fun partTwo(input: String): Int {
val ids = input
.lines()
.asSequence()
.map(::seatId)
.toSet()
for (id in 842 downTo 0) {
if (!ids.contains(id) && ids.contains(id + 1) && ids.contains(id - 1)) {
return id
}
}
throw IllegalStateException("No empty seat found?!")
}
| 0 | Kotlin | 0 | 0 | a8d52412772750c5e7d2e2e018f3a82354e8b1c3 | 1,051 | aoc-2021 | MIT License |
src/main/kotlin/day8.kt | gautemo | 725,273,259 | false | {"Kotlin": 79259} | import shared.*
fun main() {
val input = Input.day(8)
println(day8A(input))
println(day8B(input))
}
fun day8A(input: Input): Long {
val (instructions, network) = input.chunks
val nodes = network.lines().toNetwork()
val ghost = Ghost(nodes.first { it.name == "AAA" })
while (ghost.on.name != "ZZZ") {
ghost.move(instructions[(ghost.step % instructions.length).toInt()])
}
return ghost.step
}
/* Luckily the input is rigged so that the distance to the first end, is the length of the repeating cycle */
fun day8B(input: Input): Long {
val (instructions, network) = input.chunks
val nodes = network.lines().toNetwork()
val ghosts = nodes.filter { it.name.endsWith('A') }.map { Ghost(it) }
ghosts.forEach { ghost ->
while (!ghost.on.name.endsWith('Z')) {
ghost.move(instructions[(ghost.step % instructions.length).toInt()])
}
}
return ghosts.fold(1){ acc, g -> lcm(acc, g.step) }
}
private fun List<String>.toNetwork(): List<Node> {
val nodes = map { Node(it.split(' ')[0]) }
forEach { line ->
val node = nodes.first { it.name == line.split(' ')[0]}
val leftName = Regex("""\((\w+),""").find(line)!!.groupValues[1]
val rightName = Regex(""",\s(\w+)\)""").find(line)!!.groupValues[1]
node.left = nodes.first { it.name == leftName }
node.right = nodes.first { it.name == rightName }
}
return nodes
}
private class Node(val name: String){
lateinit var left: Node
lateinit var right: Node
}
private class Ghost(var on: Node) {
var step = 0L
fun move(to: Char) {
when(to) {
'L' -> on = on.left
'R' -> on = on.right
}
step++
}
} | 0 | Kotlin | 0 | 0 | 6862b6d7429b09f2a1d29aaf3c0cd544b779ed25 | 1,745 | AdventOfCode2023 | MIT License |
src/main/kotlin/year2022/day-16.kt | ppichler94 | 653,105,004 | false | {"Kotlin": 182859} | package year2022
import lib.TraversalBreadthFirstSearch
import lib.aoc.Day
import lib.aoc.Part
fun main() {
Day(16, 2022, PartA16(), PartB16()).run()
}
open class PartA16 : Part() {
internal data class State(val current: String, val minutes: Int, val opened: Set<Valve>)
internal data class Valve(val name: String, val flowRate: Int, val links: List<String>)
private lateinit var valves: Map<String, Valve>
private lateinit var distances: Map<String, Map<String, Int>>
private lateinit var remainingValves: Set<Valve>
private var maxFlowRate: Int = 0
override fun parse(text: String) {
val regex = """Valve (.*) has flow rate=(\d+); tunnels? leads? to valves? (.*)""".toRegex()
valves = text.split("\n")
.map {
val (name, flowRate, links) = regex.find(it)!!.destructured
Valve(name, flowRate.toInt(), links.split(", "))
}.associateBy { it.name }
maxFlowRate = valves.values.sumOf(Valve::flowRate)
val significantValves = valves.values.filter { it.name == "AA" || it.flowRate > 0 }
distances = significantValves.associate { from ->
val traversal = TraversalBreadthFirstSearch { n, _ -> valveNeighbours(n) }
.startFrom(from.name)
.traverseAll()
from.name to significantValves.filter { it != from && it.name != "AA" }
.associate { to -> to.name to traversal.getPath(to.name).size }
}
remainingValves = significantValves.filter { it.name != "AA" }.toSet()
}
private fun valveNeighbours(node: String) = valves[node]!!.links
override fun compute(): String {
return traverse(timeLeft = 30).toString()
}
internal fun traverse(
timeLeft: Int,
current: Valve = valves.getValue("AA"),
remaining: Set<Valve> = remainingValves,
cache: MutableMap<State, Int> = mutableMapOf(),
withElephant: Boolean = false
): Int {
val currentScore = timeLeft * current.flowRate
val currentState = State(current.name, timeLeft, remaining)
return currentScore + cache.getOrPut(currentState) {
val maxCurrent = remaining
.filter { distances[current.name]!![it.name]!! < timeLeft }
.takeIf { it.isNotEmpty() }
?.maxOf {
val remainingMinutes = timeLeft - 1 - distances[current.name]!![it.name]!!
traverse(remainingMinutes, it, remaining - it, cache, withElephant)
} ?: 0
maxOf(maxCurrent, if (withElephant) traverse(timeLeft = 26, remaining = remaining) else 0)
}
}
override val exampleAnswer: String
get() = "1651"
}
class PartB16 : PartA16() {
override fun compute(): String {
return traverse(timeLeft = 26, withElephant = true).toString()
}
override val exampleAnswer: String
get() = "1707"
} | 0 | Kotlin | 0 | 0 | 49dc6eb7aa2a68c45c716587427353567d7ea313 | 3,048 | Advent-Of-Code-Kotlin | MIT License |
src/main/kotlin/com/jacobhyphenated/advent2022/day3/Day3.kt | jacobhyphenated | 573,603,184 | false | {"Kotlin": 144303} | package com.jacobhyphenated.advent2022.day3
import com.jacobhyphenated.advent2022.Day
/**
* Day 3: Rucksack Reorganization
*
* There are a bunch of rucksacks with different items (characters a-z and A-Z)
* Each item has a priority: a-z is 1-26 and A-Z is 27-52
*/
class Day3: Day<List<String>> {
// create a map that ties each item character to its priority score
private val priorityMap = (
('a'..'z').zip(1..26) +
('A'..'Z').zip(27..52)
).toMap()
override fun getInput(): List<String> {
return readInputFile("day3").lines()
}
/**
* Each rucksack is evenly split into two sections.
* For each rucksack, the two sections will have 1 item in common.
* Find that item's priority and sum the priority score for all rucksacks.
*/
override fun part1(input: List<String>): Number {
return input.sumOf {
val half = it.length / 2
val firstHalf = it.substring(0, half).toCharArray().toSet()
val secondHalf = it.substring(half, it.length).toCharArray().toSet()
firstHalf.intersect(secondHalf)
.sumOf { c -> priorityMap.getValue(c) }
}
}
/**
* The elves have groups of three (in order based on the puzzle input).
* Each group has exactly one item in all 3 rucksacks.
*
* Find the priority of the unique item for each group, and add them all up.
*/
override fun part2(input: List<String>): Number {
// use windowed to get groups of 3 with a step of 3 between each group so no rucksack appears in multiple groups
return input.windowed(3, 3).sumOf { rucksack ->
rucksack.map { it.toCharArray().toSet() }
.reduce { a, b -> a.intersect(b) }// set intersection to find the common item in rucksack group
.sumOf { priorityMap.getValue(it) }
}
}
} | 0 | Kotlin | 0 | 0 | 9f4527ee2655fedf159d91c3d7ff1fac7e9830f7 | 1,912 | advent2022 | The Unlicense |
2023/src/main/kotlin/de/skyrising/aoc2023/day7/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2023.day7
import de.skyrising.aoc.*
import it.unimi.dsi.fastutil.bytes.Byte2IntMap
import java.nio.ByteBuffer
enum class HandType {
HIGH_CARD,
ONE_PAIR,
TWO_PAIR,
THREE_OF_A_KIND,
FULL_HOUSE,
FOUR_OF_A_KIND,
FIVE_OF_A_KIND,
}
const val MIRROR_CHAR_CODE = 'Z'.code + 'A'.code
private inline fun packCodes(code: (Int)->Long) = (code(0) shl 32) or (code(1) shl 24) or (code(2) shl 16) or (code(3) shl 8) or code(4)
private fun type(histogram: Byte2IntMap) = when(histogram.size) {
1 -> HandType.FIVE_OF_A_KIND
2 -> if (3 in histogram.values) HandType.FULL_HOUSE else HandType.FOUR_OF_A_KIND
3 -> if (3 in histogram.values) HandType.THREE_OF_A_KIND else HandType.TWO_PAIR
4 -> HandType.ONE_PAIR
else -> HandType.HIGH_CARD
}
private fun type2(histogram: Byte2IntMap): HandType {
val jokers = histogram.remove('J'.code.toByte())
if (jokers == 5) return HandType.FIVE_OF_A_KIND
val e = histogram.byte2IntEntrySet().maxBy { it.intValue }
e.setValue(e.intValue + jokers)
return type(histogram)
}
private class Hand(val type: HandType, val cardValues: Long, val bid: Int) : Comparable<Hand> {
override fun compareTo(other: Hand): Int {
val bestKindCmp = type.compareTo(other.type)
if (bestKindCmp != 0) return bestKindCmp
return cardValues.compareTo(other.cardValues)
}
companion object {
private fun order(c: Byte, jCode: Byte) = when (c.toInt()) {
'J'.code -> jCode
in '0'.code..'9'.code -> c
else -> (MIRROR_CHAR_CODE - c).toByte()
}
fun part1(cards: ByteBuffer, bid: Int) = Hand(
type(cards.histogram()),
packCodes { order(cards[it], (MIRROR_CHAR_CODE - 'R'.code).toByte()).toLong() },
bid
)
fun part2(cards: ByteBuffer, bid: Int) = Hand(
type2(cards.histogram()),
packCodes { order(cards[it], '1'.code.toByte()).toLong() },
bid
)
}
}
private inline fun run(input: PuzzleInput, ctor: (ByteBuffer,Int)-> Hand) = input.byteLines.map {
ctor(it.slice(0, 5), it.slice(6, it.remaining() - 6).toInt())
}.sorted().sumOfWithIndex { i, it -> it.bid * (i + 1) }
val test = TestInput("""
32T3K 765
T55J5 684
KK677 28
KTJJT 220
QQQJA 483
""")
@PuzzleName("Camel Cards")
fun PuzzleInput.part1() = run(this, Hand.Companion::part1)
fun PuzzleInput.part2() = run(this, Hand.Companion::part2)
| 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 2,495 | aoc | MIT License |
src/Day04.kt | peterphmikkelsen | 573,069,935 | false | {"Kotlin": 7834} | fun main() {
fun part1(input: List<String>): Int {
var sum = 0
for (intervals in input) {
val (first, second) = intervals.splitToIntervals()
val intersection = first.intersect(second)
if (intersection == first.toSet() || intersection == second.toSet()) sum++
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
for (intervals in input) {
val (first, second) = intervals.splitToIntervals()
if (first.intersect(second).isNotEmpty()) sum++
}
return sum
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
private fun String.splitToIntervals(): Pair<IntRange, IntRange> {
val (first, second) = this.split(",")
.map { IntRange(it.substringBefore("-").toInt(), it.substringAfter("-").toInt()) }
return Pair(first, second)
} | 0 | Kotlin | 0 | 0 | 374c421ff8d867a0bdb7e8da2980217c3455ecfd | 1,112 | aoc-2022 | Apache License 2.0 |
src/Day13.kt | HylkeB | 573,815,567 | false | {"Kotlin": 83982} | private sealed class Value {
class List : Value() {
var values = emptyList<Value>()
}
class Primitive(val value: Int) : Value()
}
private sealed class ValidationResult
private object Valid : ValidationResult()
private object Invalid : ValidationResult()
private object Unknown : ValidationResult()
fun main() {
fun parseValue(string: String): Value {
return if (string.startsWith("[")) {
val content = string
.substringAfter("[")
.substringBeforeLast("]")
.fold(mutableListOf("")) { acc, char ->
if (char == ',' && acc.last().count { it == '[' } == acc.last().count { it == ']' }) {
acc.add("")
} else {
acc.add(acc.removeLast() + char)
}
acc
}
.mapNotNull {
if (it.isEmpty()) {
null
} else {
parseValue(it)
}
}
Value.List().apply {
this.values = content
}
} else {
Value.Primitive(string.toInt())
}
}
fun parsePairs(input: List<String>): List<Pair<Value, Value>> {
val pairs = mutableListOf<Pair<Value, Value>>()
repeat(input.size) { index ->
if ((index - 1) % 3 == 0) {
val left = input[index - 1]
val right = input[index]
pairs.add(parseValue(left) to parseValue(right))
}
}
return pairs
}
fun parseSignals(input: List<String>): List<Value> {
return input.filter { it.isNotEmpty() }
.map {
parseValue(it)
}
}
fun compare(left: Value, right: Value): ValidationResult {
if (left is Value.Primitive && right is Value.Primitive) {
return if (left.value < right.value) {
Valid
} else if (left.value > right.value) {
Invalid
} else {
Unknown
}
}
// make sure both are lists
val leftAsList = when (left) {
is Value.List -> left
is Value.Primitive -> Value.List().apply { values = listOf(left) }
}
val rightAsList = when (right) {
is Value.List -> right
is Value.Primitive -> Value.List().apply { values = listOf(right) }
}
var currentIndex = 0
while (true) {
val leftItem = leftAsList.values.getOrNull(currentIndex)
val rightItem = rightAsList.values.getOrNull(currentIndex)
if (leftItem == null && rightItem == null) {
return Unknown
} else if (leftItem == null) (
return Valid
) else if (rightItem == null) {
return Invalid
} else {
val value = compare(leftItem, rightItem)
if (value != Unknown) {
return value
} else {
currentIndex++
}
}
}
}
fun part1(input: List<String>): Int {
val pairs = parsePairs(input)
val validatedPairs = pairs.map {
compare(it.first, it.second)
}
.mapIndexed { index, value ->
when (value) {
Invalid -> false to index + 1
Valid -> true to index + 1
Unknown -> throw IllegalStateException("Unknown validation")
}
}
return validatedPairs.filter { it.first }.sumOf { it.second }
}
fun part2(input: List<String>): Int {
val signals = parseSignals(input)
val dividerSignals = listOf(parseValue("[[2]]"), parseValue("[[6]]"))
val allSignals = signals + dividerSignals
val sorted = allSignals.sortedWith { left, right ->
when (compare(left, right)) {
Valid -> -1
Invalid -> 1
Unknown -> throw IllegalStateException("Unknown validation result")
}
}
return (sorted.indexOfFirst { it in dividerSignals } + 1) * (sorted.indexOfLast { it in dividerSignals } + 1)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test")
check(part1(testInput) == 13)
check(part2(testInput) == 140)
val input = readInput("Day13")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8649209f4b1264f51b07212ef08fa8ca5c7d465b | 4,768 | advent-of-code-2022-kotlin | Apache License 2.0 |
src/Day03.kt | Narmo | 573,031,777 | false | {"Kotlin": 34749} | fun main() {
fun Char.getPriority(): Int = when {
isUpperCase() -> this - 'A' + 27
else -> this - 'a' + 1
}
fun part1(input: List<String>): Int = input.sumOf { line ->
val compartmentSize = line.length / 2
val firstCompartment = line.substring(0, compartmentSize).toSet()
val secondCompartment = line.substring(compartmentSize).toSet()
secondCompartment.intersect(firstCompartment).sumOf { it.getPriority() }
}
fun part2(input: List<String>): Int = input.windowed(size = 3, step = 3, partialWindows = false).sumOf { (first, second, third) ->
first.toSet().intersect(second.toSet()).intersect(third.toSet()).sumOf { it.getPriority() }
}
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 335641aa0a964692c31b15a0bedeb1cc5b2318e0 | 844 | advent-of-code-2022 | Apache License 2.0 |
src/aoc2023/Day11.kt | anitakar | 576,901,981 | false | {"Kotlin": 124382} | package aoc2023
import readInput
import kotlin.math.abs
fun main() {
fun convertToMaze(lines: List<String>): Array<Array<Char>> {
val maze = Array(lines.size) { Array(lines[0].length) { '.' } }
for (i in lines.indices) {
maze[i] = lines[i].toCharArray().toTypedArray()
}
return maze
}
fun expand(maze: Array<Array<Char>>): Array<Array<Char>> {
val emptyRowIndices = maze.withIndex().filter { (_, row) -> row.all { it == '.' } }.map { it.index }
val emptyColumnIndices = mutableListOf<Int>()
for (j in maze[0].indices) {
var allEmpty = true
for (i in maze.indices) {
if (maze[i][j] != '.') allEmpty = false
}
if (allEmpty) emptyColumnIndices.add(j)
}
val expanded = Array(maze.size + emptyRowIndices.size) {
Array(maze[0].size + emptyColumnIndices.size) { '.' }
}
var shiftRows = 0
for (i in maze.indices) {
if (emptyRowIndices.contains(i)) shiftRows += 1
var shiftCols = 0
for (j in maze[0].indices) {
if (emptyColumnIndices.contains(j)) shiftCols += 1
expanded[i + shiftRows][j + shiftCols] = maze[i][j]
}
}
return expanded
}
fun findGalaxies(maze: Array<Array<Char>>): List<Pair<Int, Int>> {
val galaxies = mutableListOf<Pair<Int, Int>>()
for (i in maze.indices) {
for (j in maze[0].indices) {
if (maze[i][j] == '#') galaxies.add(Pair(i, j))
}
}
return galaxies
}
fun expandGalaxies(maze: Array<Array<Char>>, galaxies: List<Pair<Int, Int>>, expansion: Int): List<Pair<Long, Long>> {
val emptyRowIndices = maze.withIndex().filter { (_, row) -> row.all { it == '.' } }.map { it.index }
val emptyColumnIndices = mutableListOf<Int>()
for (j in maze[0].indices) {
var allEmpty = true
for (i in maze.indices) {
if (maze[i][j] != '.') allEmpty = false
}
if (allEmpty) emptyColumnIndices.add(j)
}
val expandedGalaxies = mutableListOf<Pair<Long, Long>>()
var shiftRows = 0L
for (i in maze.indices) {
if (emptyRowIndices.contains(i)) shiftRows += (expansion - 1)
var shiftCols = 0L
for (j in maze[0].indices) {
if (emptyColumnIndices.contains(j)) shiftCols += (expansion - 1)
if (galaxies.contains(Pair(i, j))) {
expandedGalaxies.add(Pair(i + shiftRows, j + shiftCols))
}
}
}
return expandedGalaxies
}
fun Pair<Int, Int>.manhattanDistance(other: Pair<Int, Int>): Int {
return abs(this.first - other.first) + abs(this.second - other.second)
}
fun Pair<Long, Long>.manhattanDistance(other: Pair<Long, Long>): Long {
return abs(this.first - other.first) + abs(this.second - other.second)
}
fun part1(lines: List<String>): Int {
val maze = convertToMaze(lines)
val expanded = expand(maze)
val galaxies = findGalaxies(expanded)
var sumDistances = 0
for (i in 0 until galaxies.size - 1) {
for (j in i + 1 until galaxies.size) {
sumDistances += galaxies[i].manhattanDistance(galaxies[j])
}
}
return sumDistances
}
fun part2(lines: List<String>, expansion: Int): Long {
val maze = convertToMaze(lines)
val galaxies = findGalaxies(maze)
val expandedGalaxies = expandGalaxies(maze, galaxies, expansion)
var sumDistances = 0L
for (i in 0 until expandedGalaxies.size - 1) {
for (j in i + 1 until expandedGalaxies.size) {
sumDistances += expandedGalaxies[i].manhattanDistance(expandedGalaxies[j])
}
}
return sumDistances
}
println(part1(readInput("aoc2023/Day11_test")))
println(part1(readInput("aoc2023/Day11")))
println(part2(readInput("aoc2023/Day11_test"), 10))
println(part2(readInput("aoc2023/Day11"), 1_000_000))
} | 0 | Kotlin | 0 | 1 | 50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf | 4,207 | advent-of-code-kotlin | Apache License 2.0 |
src/main/kotlin/io/github/pshegger/aoc/y2022/Y2022D7.kt | PsHegger | 325,498,299 | false | null | package io.github.pshegger.aoc.y2022
import io.github.pshegger.aoc.common.BaseSolver
class Y2022D7 : BaseSolver() {
override val year = 2022
override val day = 7
private val fileSystem by lazy { parseInput() }
private val minimumToDelete by lazy { REQUIRED_DISK_SPACE - (DISK_SPACE - fileSystem.size) }
override fun part1(): Int = fileSystem
.findDirectories(MAX_SIZE)
.sumOf { it.size }
override fun part2(): Int = fileSystem
.findDirectories(null)
.filter { it.size > minimumToDelete }
.minBy { it.size }
.size
private fun parseInput() = readInput {
val lines = readLines()
val commands = lines.indices
.filter { lines[it][0] == '$' }
.map { startIndex ->
lines.drop(startIndex).take(1) +
lines.drop(startIndex + 1).takeWhile { it[0] != '$' }
}
val root = Node.Directory("/")
var current = root
commands.forEach { commandAndOutput ->
val command = commandAndOutput[0].drop(2).split(" ").map { it.trim() }
when (command[0]) {
"cd" -> {
when (command[1]) {
"/" -> current = root
".." -> current.parent?.let { current = it }
else -> current.content
.filterIsInstance<Node.Directory>()
.find { it.name == command[1] }
?.let { current = it }
}
}
"ls" -> {
commandAndOutput.drop(1).forEach { outputLine ->
val (part1, part2) = outputLine.split(" ", limit = 2)
if (part1 == "dir") {
current.content.add(Node.Directory(part2, parent = current))
} else {
current.content.add(Node.File(part2, part1.toInt()))
}
}
}
}
}
root
}
private sealed class Node(open val name: String) {
abstract val size: Int
data class Directory(
override val name: String,
val content: MutableList<Node> = mutableListOf(),
val parent: Directory? = null
) : Node(name) {
override val size: Int
get() = content.sumOf { it.size }
fun findDirectories(maxSize: Int?): List<Directory> {
val self = when {
maxSize == null -> listOf(this)
size <= maxSize -> listOf(this)
else -> emptyList()
}
return self + content.filterIsInstance<Directory>().flatMap { it.findDirectories(maxSize) }
}
override fun toString(): String = buildString {
append("Directory(")
append("name=$name,")
append("content=$content,")
append("parent=${parent?.name}")
append(")")
}
}
data class File(override val name: String, override val size: Int) : Node(name)
}
companion object {
private const val MAX_SIZE = 100000
private const val DISK_SPACE = 70000000
private const val REQUIRED_DISK_SPACE = 30000000
}
}
| 0 | Kotlin | 0 | 0 | 346a8994246775023686c10f3bde90642d681474 | 3,434 | advent-of-code | MIT License |
src/Day07.kt | nordberg | 573,769,081 | false | {"Kotlin": 47470} | enum class FileTypes {
DIRECTORY,
FILE
}
fun main() {
data class AocFile(val name: String, val filePath: String, val size: Int?, val fileType: FileTypes)
fun part1(input: List<String>): Set<AocFile> {
val fileConts = mutableMapOf<String, MutableSet<AocFile>>()
val dirsWithoutSize = mutableSetOf(
AocFile("/", "/", null, FileTypes.DIRECTORY)
)
var currentFilePath = "/"
for (i in input.indices) {
val currLine = input[i]
if (currLine.startsWith("$ cd")) {
val targetDir = currLine.split(" ")[2]
currentFilePath = when (targetDir) {
"/" -> {
"/"
}
".." -> {
currentFilePath.dropLast(1).dropLastWhile { it != '/' }
}
else -> {
val newDir = "$currentFilePath$targetDir/"
val dirFile = AocFile(targetDir, newDir, null, FileTypes.DIRECTORY)
fileConts.putIfAbsent(currentFilePath, mutableSetOf())
fileConts[currentFilePath]!!.add(dirFile)
dirsWithoutSize.add(dirFile)
newDir
}
}
}
if (currLine.startsWith("dir ")) {
val (_, dirName) = currLine.split(" ")
val myFile = AocFile(dirName, "$currentFilePath$dirName/", null, FileTypes.DIRECTORY)
fileConts.putIfAbsent(currentFilePath, mutableSetOf())
fileConts[currentFilePath]!!.add(myFile)
dirsWithoutSize.add(myFile)
}
if (currLine[0].isDigit()) {
val (fileSize, fileName) = currLine.split(" ")
val myFile = AocFile(fileName, "$currentFilePath$fileName/", fileSize.toInt(), FileTypes.FILE)
fileConts.putIfAbsent(currentFilePath, mutableSetOf())
fileConts[currentFilePath]!!.add(myFile)
}
}
val dirsWithSize = mutableSetOf<AocFile>()
while (dirsWithoutSize.isNotEmpty()) {
val dirsPathsWithSize = dirsWithSize.map { it.filePath }.toSet()
val dirsToRemove = mutableSetOf<AocFile>()
for (d in dirsWithoutSize) {
val filesInDir = fileConts[d.filePath]!!.map {
if (it.filePath in dirsPathsWithSize) {
dirsWithSize.first { d -> d.filePath == it.filePath }
} else {
it
}
}
if (filesInDir.none { it.size == null }) {
dirsToRemove.add(d)
dirsWithSize.add(
d.copy(size = filesInDir.sumOf { it.size!! })
)
}
}
dirsWithoutSize.removeAll(dirsToRemove)
}
return dirsWithSize
}
fun part2(input: List<String>): Int {
val fileSystemSize = 70000000
val neededSpace = 30000000
val usedSpace = 50216456
val dirsWithSize = part1(input).sortedBy { it.size!! }
return dirsWithSize.first { (fileSystemSize - (usedSpace - it.size!!) >= neededSpace) }.size!!
}
// test if implementation meets criteria from the description, like:
// val testInput = readInput("Day01_test")
//check(part1(testInput) == 1)
val input = readInput("Day07")
//println(part1(input).filter { it.size!! < 100000 }.sumOf { it.size!! })
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 3de1e2b0d54dcf34a35279ba47d848319e99ab6b | 3,655 | aoc-2022 | Apache License 2.0 |
src/day02/Day02.kt | ritesh-singh | 572,210,598 | false | {"Kotlin": 99540} | package day02
import readInput
fun main() {
// Y defeats A
// Z defeats B
// X defeats C
val defeatMap = mapOf(
"A" to "Y",
"B" to "Z",
"C" to "X"
)
// X loses to B
// Y loses to C
// Z loses to A
val loseMap = mapOf(
"B" to "X",
"C" to "Y",
"A" to "Z"
)
val drawMap = mapOf(
"A" to "X",
"B" to "Y",
"C" to "Z"
)
val rockPaperScissorScore = mapOf(
"X" to 1,
"Y" to 2,
"Z" to 3
)
val LOST = 0
val DRAW = 3
val WIN = 6
fun getTotalScorePart1(opponent: String, you: String): Int {
return when (you) {
defeatMap[opponent] -> { // win
WIN + rockPaperScissorScore[you]!!
}
drawMap[opponent] -> { // draw
DRAW + rockPaperScissorScore[you]!!
}
else -> { // lost
LOST + rockPaperScissorScore[you]!!
}
}
}
fun getTotalScorePart2(opponent: String, you: String): Int {
return when (you) {
"X" -> { // need to lose
LOST + rockPaperScissorScore[loseMap[opponent]]!!
}
"Y" -> { // need to draw
DRAW + rockPaperScissorScore[drawMap[opponent]]!!
}
else -> {
// need to win
WIN + rockPaperScissorScore[defeatMap[opponent]]!!
}
}
}
fun part1(input: List<String>): Int {
var sum = 0
input.forEach {
val (first, second) = it.split(" ").map { it.trim() }
sum += getTotalScorePart1(opponent = first, you = second)
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
input.forEach {
val (first, second) = it.split(" ").map { it.trim() }
sum += getTotalScorePart2(first, second)
}
return sum
}
val input = readInput("/day02/Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 17fd65a8fac7fa0c6f4718d218a91a7b7d535eab | 2,091 | aoc-2022-kotlin | Apache License 2.0 |
solutions/aockt/y2021/Y2021D14.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2021
import io.github.jadarma.aockt.core.Solution
object Y2021D14 : Solution {
/**
* Holds metadata about a polymer after repeated polymerization via some rules.
* The submarine does not have enough memory to store exponentially growing polymers, unfortunately.
*/
private class PolymerizationStatistics(template: String, rules: Iterable<Pair<String, Char>>) {
init {
require(template.all { it in 'A'..'Z' }) { "Invalid polymer template." }
}
/** After polymerization, the last element is always the same, and is needed to compute occurrences. */
private val lastElement: Char = template.last()
/** The polymerization rules, mapping from a valid pair of elements to the new element inserted between. */
private val replace: Map<String, Char> = rules
.onEach { (pair, element) ->
require(pair.length == 2) { "Invalid rule." }
require("$pair$element".all { it in 'A'..'Z' }) { "Invalid rule." }
}
.toMap()
/** Counts how many times an element pair occurs in the currently simulated polymer. */
private val twoGram: MutableMap<String, Long> = mutableMapOf<String, Long>().apply {
template.windowed(2).forEach { pair -> updateCount(pair) { it + 1L } }
}
/**
* Applies the polymerisation operation a number of [times].
* This operation **mutates** the internal statistics state and returns a reference to itself.
*/
fun polymerize(times: Int = 1): PolymerizationStatistics = apply {
repeat(times) {
val replacementDeltas = buildMap {
for (rule in replace) {
val (pair, element) = rule
val occurrences = twoGram[pair] ?: continue
updateCount("${pair.first()}$element", true) { it + occurrences }
updateCount("$element${pair.last()}", true) { it + occurrences }
updateCount(pair, true) { it - occurrences }
}
}
replacementDeltas.forEach { (pair, delta) -> twoGram.updateCount(pair) { it + delta } }
}
}
/** Computes how many times each distinct element occurs in the simulated polymer. */
fun occurrences(): Map<Char, Long> = buildMap {
twoGram.forEach { (pair, occurrences) -> updateCount(pair.first()) { it + occurrences } }
updateCount(lastElement) { it + 1L }
}
/**
* Helper to handle counting map operations. Modifies the count of the [key], by supplying its current value
* (or `zero` if it is not tracked) to the [mapper] function. If [allowNonPositive] flag is set, negative counts
* are allowed; otherwise the [key] will be removed.
*/
private inline fun <T> MutableMap<T, Long>.updateCount(
key: T,
allowNonPositive: Boolean = false,
mapper: (Long) -> Long,
) = apply {
val nextCount = mapper(getOrDefault(key, 0L))
when {
nextCount in Long.MIN_VALUE..0L && !allowNonPositive -> remove(key)
else -> put(key, nextCount)
}
}
}
/** Parse the [input] and return the [PolymerizationStatistics] for the given polymer template. */
private fun parseInput(input: String): PolymerizationStatistics = runCatching {
val template = input.substringBefore('\n')
val rules = input
.lineSequence()
.drop(2)
.map { it.split(" -> ") }
.map { (pair, element) -> pair to element.first() }
.asIterable()
PolymerizationStatistics(template, rules)
}.getOrElse { throw IllegalArgumentException("Invalid input", it) }
override fun partOne(input: String) =
parseInput(input)
.polymerize(times = 10)
.occurrences()
.run { maxOf { it.value } - minOf { it.value } }
override fun partTwo(input: String) =
parseInput(input)
.polymerize(times = 40)
.occurrences()
.run { maxOf { it.value } - minOf { it.value } }
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 4,299 | advent-of-code-kotlin-solutions | The Unlicense |
src/Day11/Day11.kt | AllePilli | 572,859,920 | false | {"Kotlin": 47397} | package Day11
import checkAndPrint
import divides
import measureAndPrintTimeMillis
import readInput
import java.math.BigDecimal
import java.math.BigInteger
import java.math.RoundingMode
import java.util.*
fun main() {
val itemsRgx = """\s+Starting items:\s+(.*)""".toRegex()
val operationRgx = """\s+Operation:\s+new = (.*)""".toRegex()
val testRgx = """\s+Test: divisible by (\d+)""".toRegex()
val trueRgx = """\s+If true: throw to monkey (\d+)""".toRegex()
val falseRgx = """\s+If false: throw to monkey (\d+)""".toRegex()
fun List<String>.prepareInput() = joinToString(separator = "\n")
.split("\n\n")
.map { monkeyString ->
val monkeyLines = monkeyString.split("\n").drop(1)
val items = itemsRgx.matchEntire(monkeyLines.first())!!.groupValues.last()
.split(", ")
.map(String::toBigInteger)
.let { LinkedList(it) }
val operation = operationRgx.matchEntire(monkeyLines[1])!!.groupValues.last().let(::Operation)
val testDivisor = testRgx.matchEntire(monkeyLines[2])!!.groupValues.last().toBigInteger()
val trueId = trueRgx.matchEntire(monkeyLines[3])!!.groupValues.last().toInt()
val falseId = falseRgx.matchEntire(monkeyLines[4])!!.groupValues.last().toInt()
Monkey(
items as Queue<BigInteger>,
operation,
Test(testDivisor, trueId, falseId)
)
}
fun gatherResult(input: List<Monkey>) = input.map(Monkey::inspectCnt)
.sortedDescending()
.take(2)
.let { (first, second) -> first.toBigInteger() * second.toBigInteger() }
fun part1(input: List<Monkey>): BigInteger {
val three = BigDecimal(3.0)
repeat(20) { _ ->
input.forEach { monkey ->
while (monkey.items.peek() != null) {
val item = monkey.items.poll()!!.let {
monkey.operation.perform(it)
.toBigDecimal()
.divide(three, 0, RoundingMode.DOWN)
.toBigInteger()
}
monkey.inspectCnt++
val nextMonkeyId = with(monkey.test) {
if (divisor.divides(item)) trueId else falseId
}
input[nextMonkeyId].items.offer(item)
}
}
}
return gatherResult(input)
}
fun part2(input: List<Monkey>): BigInteger {
val modulo = input.fold(BigInteger.ONE) { acc, monkey ->
acc * monkey.test.divisor
}
repeat(10000) { _ ->
input.forEach { monkey ->
while (monkey.items.peek() != null) {
val (item, id) = monkey.operation
.performAndTest(monkey.items.poll()!!, monkey.test)
monkey.inspectCnt++
input[id].items.offer(item.mod(modulo))
}
}
}
return gatherResult(input)
}
check(part1(readInput("Day11_test").prepareInput()) == BigInteger("10605"))
check(part2(readInput("Day11_test").prepareInput()) == BigInteger("2713310158"))
measureAndPrintTimeMillis {
checkAndPrint(part1(readInput("Day11").prepareInput()), BigInteger("108240"))
}
measureAndPrintTimeMillis {
checkAndPrint(part2(readInput("Day11").prepareInput()), BigInteger("25712998901"))
}
}
private data class Monkey(val items: Queue<BigInteger>, val operation: Operation, val test: Test) {
var inspectCnt = 0L
}
private class Test(val divisor: BigInteger, val trueId: Int, val falseId: Int)
private class Operation(operationString: String) {
private val operationList = operationString.split(" ")
.let { (left, op, right) ->
val leftNew = if (left != "old") left.toBigInteger() else left
val rightNew = if (right != "old") right.toBigInteger() else right
Triple(leftNew, op, rightNew)
}
fun performAndTest(item: BigInteger, test: Test) = operationList.let { (left, op, right) ->
val leftNum = if (left is BigInteger) left else item
val rightNum = if (right is BigInteger) right else item
val div = test.divisor
when (op) {
"+" -> {
val sum = leftNum + rightNum
sum to if (div.divides(sum)) test.trueId else test.falseId
}
"*" -> {
val product = leftNum * rightNum
product to if (div.divides(product)) test.trueId else test.falseId
}
else -> error("Unknown op $op")
}
}
fun perform(item: BigInteger): BigInteger = operationList.let { (left, op, right) ->
val leftNum = if (left is BigInteger) left else item
val rightNum = if (right is BigInteger) right else item
when (op) {
"+" -> leftNum + rightNum
"*" -> leftNum * rightNum
else -> error("Unknown op $op")
}
}
} | 0 | Kotlin | 0 | 0 | 614d0ca9cc925cf1f6cfba21bf7dc80ba24e6643 | 5,133 | AdventOfCode2022 | Apache License 2.0 |
src/Day01.kt | stcastle | 573,145,217 | false | {"Kotlin": 24899} | import kotlin.math.max
fun main() {
fun part1(input: List<String>): Int {
var sum = 0
var max = 0
input.forEach {
if (it == "") {
max = max(sum, max)
sum = 0
} else {
sum += it.toInt()
}
}
// one more time on the end
return max(sum, max)
}
fun part2(input: List<String>): Int {
var top3 = mutableListOf(0, 0, 0) // keep sorted with smallest item first.
var sum = 0
input.forEach {
if (it == "") {
if (sum > top3[0]) {
top3[0] = sum
top3 = top3.sorted().toMutableList()
}
sum = 0
} else {
sum += it.toInt()
}
}
// one more time on the end.
if (sum > top3[0]) {
top3[0] = sum
top3 = top3.sorted().toMutableList()
}
return top3.sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
// println(part1(testInput))
check(part1(testInput) == 24000)
println(part2(testInput))
val input = readInput("Day01")
println("part1 = ${part1(input)}")
println("part2 = ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | 746809a72ea9262c6347f7bc8942924f179438d5 | 1,142 | aoc2022 | Apache License 2.0 |
Algorithms/Array/twoSum.kt | ahampriyanshu | 278,614,006 | false | {"C++": 583777, "Java": 277289, "Python": 254940, "C": 223686, "C#": 127046, "JavaScript": 96050, "Ruby": 37909, "PHP": 37167, "Go": 34857, "TypeScript": 34282, "Swift": 16690, "Jupyter Notebook": 13334, "Kotlin": 9718, "Rust": 9569, "Shell": 7923, "Scala": 6275, "Haskell": 5456, "HTML": 2270, "Clojure": 348, "Makefile": 261} | import java.util.*
/*Naive Approach: Check for all pairs if they adds up to the target or not
TC: O(n*n) SC: O(1)
*/
fun findTwoSumNaive(nums: List<Int>, target: Int): IntArray{
val n = nums.size
for(i in 0 until n){
for(j in (i+1) until n){
if(nums[i] + nums[j] == target)
return intArrayOf(nums[i], nums[j])
}
}
return intArrayOf(-1, -1)
}
/*Better Approach: Sort the given array
->create two pointers one of which points to the first element and another one to the last element.
->check if both the values pointed to by these pointers adds up to the target or not.
->if yes, return the result.
->otherwise, if the sum is lesser than the target increment left pointer
-> otherwise decrement the right pointer.
->The above intuition works because the array is sorted.
TC: O(nlogn) SC: O(n)
*/
fun findTwoSumBetter(nums: List<Int>, target: Int): IntArray{
Collections.sort(nums)
var (lo, hi) = Pair(0, nums.size - 1)
while(lo < hi){
val sum = nums[lo] + nums[hi]
if(sum == target){
return intArrayOf(nums[lo], nums[hi]);
}
if(sum < target) lo++ else hi--
}
return intArrayOf(-1, -1)
}
/*Optimal Approach:
->Use a hashmap to store the numbers as you traverse.
->At any point if you had added a value equal to the target - current_number in the hashmap.
->Then we have our ans as {current_number, target - current_number} which adds up to the target value.
->otherwise return {-1, -1} as the result.
TC: O(n) SC: O(n)
considering the hashmap works in O(1) on an average.
*/
fun findTwoSumOptimal(nums: List<Int>, target: Int): IntArray{
val map = mutableMapOf<Int, Boolean>()
for(num in nums){
if(map.containsKey(target - num))
return intArrayOf(target - num, num)
map[num] = true
}
return intArrayOf(-1, -1)
}
//main function
fun main(){
//get the input array
val nums = readLine()!!.split(' ').map{it.toInt()}
//get the target value
val target = readLine()!!.toInt()
//a pair of values to store the result
val values = findTwoSumOptimal(nums, target)
//if both the values of the result are -1
//it means no such pair exists that adds up to the target value
//otherwise, print a valid pair of values
if(values[0] == -1 && values[1] == -1)
println("No such pair exists")
else
println("${values[0]} and ${values[1]} adds up to $target")
} | 0 | C++ | 760 | 156 | ea880b13c09df58922065ab408d23fa4d264fb7c | 2,482 | algo-ds-101 | MIT License |
src/main/kotlin/g1201_1300/s1268_search_suggestions_system/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1201_1300.s1268_search_suggestions_system
// #Medium #Array #String #2023_06_08_Time_331_ms_(100.00%)_Space_50.2_MB_(88.89%)
class Solution {
private var result: MutableList<List<String>> = ArrayList()
fun suggestedProducts(products: Array<String>, searchWord: String): List<List<String>> {
// Sort products array first in lexicographically order
products.sort()
// Iterate through each "type" of searchWord by using substring
for (endIndex in 1..searchWord.length) {
val subSearchWord = searchWord.substring(0, endIndex)
// Find result for each "type" and add to result list
val curResult = findResult(products, subSearchWord)
result.add(curResult)
}
return result
}
private fun findResult(sortedProducts: Array<String>, searchWord: String): List<String> {
val curResult: MutableList<String> = ArrayList()
// Binary search returns the first index possible search result
val startIndex = binarySearch(sortedProducts, searchWord)
// Iterate the following 3 string in products or exit if reach end first
var i = startIndex
while (i < startIndex + 3 && i < sortedProducts.size) {
val cur = sortedProducts[i]
// Only add to curResult if prefix match, otherwise break and return
if (isPrefix(searchWord, cur)) {
curResult.add(cur)
} else {
return curResult
}
i++
}
return curResult
}
// Compare char by char to check if searchWord is a prefix of product
private fun isPrefix(searchWord: String, product: String): Boolean {
for (i in searchWord.indices) {
val sw = searchWord[i]
val pr = product[i]
return if (sw == pr) {
continue
} else {
false
}
}
return true
}
// Binary search to find the first index of possible search result
// The word at the found index should be the least word that's greater or equal to
// the target search word lexicographically.
private fun binarySearch(sortedProducts: Array<String>, searchWord: String): Int {
var start = 0
var end = sortedProducts.size - 1
while (start < end) {
val mid = (start + end) / 2
val midString = sortedProducts[mid]
// If mid word is lexicographically less than target word,
// continue search on right side
if (searchWord.compareTo(midString) > 0) {
start = mid + 1
continue
}
// If found the exact match
if (midString == searchWord) {
return mid
}
// If mid word is lexicographically greater than target word (possible solution)
if (searchWord.compareTo(midString) < 0) {
// If mid is at 0,
// or word at (mid - 1) is If mid word is lexicographically less than target word less than target word, this means we found the least word that's greater than target
return if (mid == 0 || searchWord.compareTo(sortedProducts[mid - 1]) > 0) {
mid
} else {
end = mid - 1
continue
}
}
}
return start
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 3,468 | LeetCode-in-Kotlin | MIT License |
src/net/sheltem/common/GraphUtils.kt | jtheegarten | 572,901,679 | false | {"Kotlin": 178521} | package net.sheltem.common
import net.sheltem.common.SearchGraph.Edge
import net.sheltem.common.SearchGraph.Route
import kotlin.random.Random
class SearchGraph<N>(val nodes: Set<Node<N>>, edges: Set<Edge<N>>, val bidirectional: Boolean, val circular: Boolean = false) {
val edges: Set<Edge<N>> = if (bidirectional) edges + edges.map { Edge(it.to, it.from, it.weight) } else edges
override fun toString() = "nodes: $nodes\nEdges: $edges"
fun bfs(startNode: Node<N>): List<List<Edge<N>>> {
val routes = startingRoutes(startNode)
while (!routes.all { it.visited(circular).containsAll(nodes) }) {
bfsStep(
routes.minBy { it.weight() },
routes,
startNode
)
}
return routes
}
fun floydWarshall(negativeEdges: Boolean = false) {
val nodeList = nodes.toList()
val distanceMatrix = Array(nodeList.size) { LongArray(nodeList.size) { 0L } }
for (k in nodeList.indices) {
for (i in nodeList.indices) {
distanceMatrix[k][i] = edges.singleOrNull { it.from == nodeList[k] && it.to == nodeList[i] }?.weight ?: Long.MAX_VALUE
}
}
for (k in distanceMatrix.indices) {
for (i in distanceMatrix.indices) {
for (j in distanceMatrix.indices) {
if (distanceMatrix[i][j] > distanceMatrix[i][k] + distanceMatrix[k][j]) {
distanceMatrix[i][j] = distanceMatrix[i][k] + distanceMatrix[k][j]
}
}
}
}
printMatrix(distanceMatrix)
}
fun printMatrix(matrix: Array<LongArray>) {
for (i in nodes.indices) {
for (j in nodes.indices) {
if (matrix[i][j] == Long.MAX_VALUE) print("INF ")
else print("${matrix[i][j]} ")
}
println()
}
}
fun bfs(startNode: Node<N>, goalNode: Node<N>): Route<N> {
val queue = ArrayDeque<Node<N>>()
val visited = mutableListOf(startNode)
queue.add(startNode)
while (queue.isNotEmpty()) {
val currentNode = queue.first()
if (currentNode == goalNode) {
break
}
edges.filter { it.from == currentNode }
.forEach { edge ->
if (visited.contains(edge.to)) {
visited.add(edge.to)
queue.add(edge.to)
}
}
}
return visited.zipWithNext()
.map { fromTo -> edges.single { it.from == fromTo.first && it.to == fromTo.second } }
.let(::routeOf)
}
fun dijkstra(startNode: Node<N>, goalNode: Node<N>): Route<N> {
val queue = nodes.toMutableSet()
val distances = queue.associateWith { Long.MAX_VALUE }.toMutableMap()
val previous = queue.associateWith { null }.toMutableMap<Node<N>, Node<N>?>()
distances[startNode] = 0
while (queue.isNotEmpty()) {
val currentNode = queue.minByOrNull { distances[it] ?: 0 }
queue.remove(currentNode)
if (currentNode == goalNode) {
break
}
edges
.filter { it.from == currentNode }
.forEach { edge ->
val toNode = edge.to
val routeDistance = (distances[currentNode] ?: 0) + edge.weight
if (routeDistance < (distances[toNode] ?: 0)) {
distances[toNode] = routeDistance
previous[toNode] = currentNode
}
}
}
return generateSequence(goalNode) { previous[it] }
.takeWhile { previous[it] != null }
.toList()
.reversed()
.zipWithNext()
.map { fromTo -> edges.single { it.from == fromTo.first && it.to == fromTo.second } }.let(::routeOf)
}
fun maxBfs(startNode: Node<N>): List<Edge<N>> = bfs(startNode).maxBy { it.weight() }
fun minBfs(startNode: Node<N>): List<Edge<N>> = bfs(startNode).minBy { it.weight() }
private fun startingRoutes(startNode: Node<N>): MutableList<List<Edge<N>>> =
edges
.filter { it.from == startNode }
.map { listOf(it) }
.toMutableList()
private fun bfsStep(currentRoute: List<Edge<N>>, routes: MutableList<List<Edge<N>>>, startNode: Node<N>) {
val potentialEdges = currentRoute
.last()
.to
.let { lastVisited ->
edges.filter { it.from == lastVisited }
}.filterNot { currentRoute.visited(circular).contains(it.to) }
.filterNot { circular && currentRoute.visited(circular).contains(startNode) }
for (potentialEdge in potentialEdges) {
if (!currentRoute.visited(circular).contains(potentialEdge.to)) {
routes.add(currentRoute + potentialEdge)
}
}
routes.remove(currentRoute)
}
@Deprecated("Doesn't work, fix later")
fun minCut(cuts: Int): Long {
val nodeSubsets = mutableListOf<MutableList<Node<N>>>()
do {
for (node in nodes) {
nodeSubsets.add(mutableListOf(node))
}
while (nodeSubsets.size > 2) {
val index = Random.nextInt(0, edges.size)
val s1 = nodeSubsets.firstOrNull { sub -> sub.contains(edges.toList()[index].from) }
val s2 = nodeSubsets.firstOrNull { sub -> sub.contains(edges.toList()[index].to) }
if (s1 == s2) {
continue
}
nodeSubsets.remove(s2)
s1!! += s2!!
}
(print("."))
} while (countCuts(nodeSubsets) != cuts)
return nodeSubsets.map {it.size.toLong() }.multiply()
}
private fun countCuts(subgraphs: List<List<Node<N>>>) =
edges.count { edge ->
subgraphs.firstOrNull { sub -> sub.contains(edge.from) } != subgraphs.firstOrNull { sub -> sub.contains(edge.to) }
}
data class Node<N>(val id: N) {
override fun toString() = "$id"
}
data class Edge<N>(val from: Node<N>, val to: Node<N>, val weight: Long) {
override fun toString() = "$from -($weight)-> $to"
fun reversed(): Edge<N> = Edge(to, from, weight)
}
data class Route<N>(val edges: List<Edge<N>> = listOf()) : List<Edge<N>> by edges, Comparable<Route<N>> {
override fun compareTo(other: Route<N>) = edges.weight() compareTo other.edges.weight()
}
}
fun Collection<Edge<*>>.weight() = sumOf { it.weight }
fun Collection<Edge<*>>.visited(circular: Boolean = false) = flatMap { if (circular) setOf(it.to) else setOf(it.from, it.to) }
fun <N> routeOf(list: Collection<Edge<N>>): Route<N> = Route(list.toList())
fun <N> routeOf(vararg elements: Edge<N>): Route<N> = if (elements.isNotEmpty()) Route(elements.asList()) else Route()
| 0 | Kotlin | 0 | 0 | ac280f156c284c23565fba5810483dd1cd8a931f | 7,078 | aoc | Apache License 2.0 |
src/main/kotlin/ru/amai/study/hackerrank/practice/interviewPreparationKit/dynamic/candies/Candies.kt | slobanov | 200,526,003 | false | null | package ru.amai.study.hackerrank.practice.interviewPreparationKit.dynamic.candies
import java.util.*
import kotlin.math.max
import kotlin.math.min
fun candies(grades: Array<Int>): Long {
val size = grades.size
val gradeByIndex = saveGrading(grades)
val startIndicesWithDirections = buildStartIndicesWithDirections(gradeByIndex, size)
val stopIndicesSet = buildStopIndicesSet(gradeByIndex, size)
fun canMove(index: Int, direction: Direction): Boolean = when (direction) {
Direction.LEFT -> index > 0
Direction.RIGHT -> index < size - 1
}
val candiesDistribution = Array(size) { 1 }
fun expandFrom(startIndex: Int, direction: Direction) {
var currentIndx = startIndex
while (currentIndx !in stopIndicesSet && canMove(currentIndx, direction)) {
val currentCandies = candiesDistribution[currentIndx]
currentIndx = direction.next(currentIndx)
candiesDistribution[currentIndx] = max(currentCandies + 1, candiesDistribution[currentIndx])
}
}
startIndicesWithDirections.forEach { (startIndex, directions) ->
directions.forEach { direction -> expandFrom(startIndex, direction) }
}
return candiesDistribution.fold(0L) { acc, i -> acc + i }
}
private fun saveGrading(grades: Array<Int>): (Int) -> Int = { index -> when {
index < 0 -> Int.MAX_VALUE
index >= grades.size -> Int.MAX_VALUE
else -> grades[index]
} }
private fun buildStartIndicesWithDirections(gradeByIndex: (Int) -> Int, size: Int): List<Pair<Int, List<Direction>>> =
(0 until size).filter { index ->
gradeByIndex(index) <= min(gradeByIndex(index - 1), gradeByIndex(index + 1))
}.map { index -> when {
gradeByIndex(index) == gradeByIndex(index + 1) -> index to listOf(Direction.LEFT)
gradeByIndex(index) == gradeByIndex(index - 1) -> index to listOf(Direction.RIGHT)
else -> index to listOf(Direction.LEFT, Direction.RIGHT)
} }
private fun buildStopIndicesSet(gradeByIndex: (Int) -> Int, size: Int): Set<Int> =
(0 until size).filter { index ->
gradeByIndex(index) >= max(gradeByIndex(index - 1), gradeByIndex(index + 1))
}.toSet()
enum class Direction {
LEFT,
RIGHT
}
fun Direction.next(index: Int): Int = when (this) {
Direction.LEFT -> index - 1
Direction.RIGHT -> index + 1
}
fun main() {
val scan = Scanner(System.`in`)
val n = scan.nextLine().trim().toInt()
val arr = Array(n) { 0 }
for (i in 0 until n) {
val arrItem = scan.nextLine().trim().toInt()
arr[i] = arrItem
}
val result = candies(arr)
println(result)
}
| 0 | Kotlin | 0 | 0 | 2cfdf851e1a635b811af82d599681b316b5bde7c | 2,653 | kotlin-hackerrank | MIT License |
src/main/kotlin/solutions/Day11.kt | chutchinson | 573,586,343 | false | {"Kotlin": 21958} | class Day11 : Solver {
data class Monkey(
val startingItems: ArrayDeque<Long>,
val worry: (Long) -> Long,
val divisor: Long,
val throwTrue: Int,
val throwFalse: Int)
override fun solve (input: Sequence<String>) {
val monkies = input
.split { it.isEmpty() }
.map(::toMonkey)
.toList()
println(first(monkies))
println(second(monkies))
}
fun first (input: List<Monkey>) = monkeyBusiness(input, 20) { it / 3 }
fun second (input: List<Monkey>): Long {
// this took me a while; we cannot trivially parallelize nor can we use arbitrary precision because the scale of the
// numbers grows too rapidly, so it was pretty clear right away we need modular artihmetic, but the problem is determining
// the modulus; the least common multiple (LCM), aka least common divisor is perfect here and it's easy to compute because
// all of the divisors happen to be distinct prime factors (at least in my input)
val modulus = input.fold(1L) { lcm, monkey -> lcm * monkey.divisor }
return monkeyBusiness(input, 10000) { it % modulus }
}
private fun toMonkey (input: List<String>): Monkey {
val startingItems = ArrayDeque(input[1].substring(18).split(",").map { it.trim().toLong() })
val op = input[2].substring(23, 24)
val value = input[2].substring(25)
val divisor = input[3].substring(21).toLong()
val ifTrue = input[4].substring(29).toInt()
val ifFalse = input[5].substring(30).toInt()
val func: (Long) -> Long = when {
op == "+" && value != "old" -> { x -> x + value.toLong() }
op == "*" && value != "old" -> { x -> x * value.toLong() }
else -> { x -> x * x }
}
return Monkey(startingItems, func, divisor, ifTrue, ifFalse)
}
private fun monkeyBusiness (monkies: List<Monkey>, n: Int, strategy: (Long) -> Long): Long {
val items = monkies.map { ArrayDeque(it.startingItems) }
val inspections = monkies.map { 0L }.toMutableList()
fun round (index: Int) {
val queue = items[index]
val monkey = monkies[index]
while (queue.isNotEmpty()) {
val item = queue.removeFirst()
val worry = strategy(monkey.worry(item))
val target = if (worry % monkey.divisor == 0L) monkey.throwTrue else monkey.throwFalse
items[target].addLast(worry)
inspections[index] = inspections[index] + 1
}
}
for (round in 0 until n) {
for (index in monkies.indices) {
round(index)
}
}
return inspections
.sortedByDescending { it }
.take(2)
.reduce { acc, count -> acc * count }
}
} | 0 | Kotlin | 0 | 0 | 5076dcb5aab4adced40adbc64ab26b9b5fdd2a67 | 2,922 | advent-of-code-2022 | MIT License |
src/Day02.kt | adrianforsius | 573,044,406 | false | {"Kotlin": 68131} | import org.assertj.core.api.Assertions.assertThat
val opponent = mapOf(
"A" to 1,
"B" to 2,
"C" to 3,
)
val player = mapOf(
"X" to 1,
"Y" to 2,
"Z" to 3,
)
fun getWinner(opp: Int): Int = when(opp) {
1 -> 2
2 -> 3
3 -> 1
else -> error("nope")
}
fun getLoser(opp: Int): Int = when(opp) {
1 -> 3
2 -> 1
3 -> 2
else -> error("nope")
}
fun main() {
fun part1(input: List<String>): Int {
val points = input.map {
it.split(" ").toTypedArray()
}.sumOf {
val played = player.getValue(it[1])
val faced = opponent.getValue(it[0])
when {
played == faced -> 3 + played
played - faced == 1 -> 6 + played
played - faced == -2 -> 6 + played
played - faced == 2 -> played
played - faced == -1 -> played
else -> error("should not happen")
}
}
return points
}
fun part2(input: List<String>): Int {
val points = input.map {
it.split(" ").toTypedArray()
}.sumOf {
val strategy = player.getValue(it[1])
val faced = opponent.getValue(it[0])
when {
strategy == 1 -> getLoser(faced)
strategy == 2 -> 3 + faced
strategy == 3 -> 6 + getWinner(faced)
else -> error("should not happen")
}
}
return points
}
// test if implementation meets criteria from the description, like:
// Test
val testInput = readInput("Day02_test")
val output1 = part1(testInput)
assertThat(output1).isEqualTo(15)
val testInput1 = readInput("Day02_test_1")
val outputTest1 = part1(testInput1)
assertThat(outputTest1).isEqualTo(15)
// Answer
val input = readInput("Day02")
val outputAnswer1 = part1(input)
assertThat(outputAnswer1).isEqualTo(13268)
// Test
val output2 = part2(testInput)
assertThat(output2).isEqualTo(12)
// Answer
val outputAnswer2 = part2(input)
assertThat(outputAnswer2).isEqualTo(15508)
}
| 0 | Kotlin | 0 | 0 | f65a0e4371cf77c2558d37bf2ac42e44eeb4bdbb | 2,154 | kotlin-2022 | Apache License 2.0 |
kotlin/2022/round-1b/2/src/main/kotlin/alllongs/AllLongsSolution.kt | ShreckYe | 345,946,821 | false | null | import kotlin.math.abs
import kotlin.math.min
fun main() {
val t = readLine()!!.toInt()
repeat(t, ::testCase)
}
fun testCase(ti: Int) {
val (nn, pp) = readLine()!!.splitToSequence(' ').map { it.toInt() }.toList()
val xx = List(nn) { readLine()!!.splitToSequence(' ').map { it.toInt() }.toList() }
val n = nn + 1
val minMaxXs = listOf(intArrayOf(0, 0)) + xx.map { intArrayOf(it.minOrNull()!!, it.maxOrNull()!!) }
//println(minMaxXs.map { it.contentToString() })
val dp = Array(n) { Array(2) { LongArray(2) } }
dp[0] = Array(2) { LongArray(2) { 0L } }
for (i in 0 until n - 1)
for (start in 0 until 2)
for (end in 0 until 2)
// swap ends
dp[i + 1][start][end] = min(
dp[i][start][1] + abs(minMaxXs[i + 1][end] - minMaxXs[i][0])/*.also { println("$i -> ${i + 1}, start $start, end 0 -> $end: + $it") }*/,
dp[i][start][0] + abs(minMaxXs[i + 1][end] - minMaxXs[i][1])/*.also { println("$i -> ${i + 1}, start $start, end 1 -> $end: + $it") }*/
)
val y = dp[n - 1].minOf { it.minOrNull()!! } + minMaxXs.map { (it[1] - it[0]).toLong() }.sum()
println("Case #${ti + 1}: $y")
}
| 0 | Kotlin | 1 | 1 | 743540a46ec157a6f2ddb4de806a69e5126f10ad | 1,230 | google-code-jam | MIT License |
src/Day10.kt | szymon-kaczorowski | 572,839,642 | false | {"Kotlin": 45324} | import kotlin.math.abs
fun main() {
fun part1(input: List<String>): Int {
val signal = mutableListOf<Int>()
signal.add(1)
input.forEach {
signal.add(signal.last())
if (it != "noop") {
val toInt = it.split(" ")[1].toInt()
signal.add(signal.last() + toInt);
}
}
val signaltimesIndex = signal.mapIndexed { index, i ->
i * (index+1)
}
val indexes = listOf(20, 60, 100, 140, 180, 220)
return indexes.map { signaltimesIndex[it-1] }.map {
it
}.sum()
}
fun part2(input: List<String>): Int {
val signal = mutableListOf<Int>()
signal.add(1)
input.forEach {
signal.add(signal.last())
if (it != "noop") {
val toInt = it.split(" ")[1].toInt()
signal.add(signal.last() + toInt);
}
}
val mutableList = (0..5).mapIndexed {
index, value ->
(1..40).mapIndexed {
lineIndex, innerValue ->
val spriteMid = signal[index * 40 + lineIndex]
if (abs(lineIndex-spriteMid)<=1) print("#") else print(".")
}.toMutableList()
println()
}.toMutableList()
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
check(part2(testInput) == 0)
val input = readInput("Day10")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 1d7ab334f38a9e260c72725d3f583228acb6aa0e | 1,619 | advent-2022 | Apache License 2.0 |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2022/2022-23.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2022
import com.github.ferinagy.adventOfCode.Coord2D
import com.github.ferinagy.adventOfCode.println
import com.github.ferinagy.adventOfCode.readInputLines
fun main() {
val input = readInputLines(2022, "23-input")
val testInput1 = readInputLines(2022, "23-test1")
println("Part1:")
part1(testInput1).println()
part1(input).println()
println()
println("Part2:")
part2(testInput1).println()
part2(input).println()
}
private fun part1(input: List<String>): Int {
val elves = solve(input, 10).first
val minX = elves.minOf { it.x }
val minY = elves.minOf { it.y }
val maxX = elves.maxOf { it.x }
val maxY = elves.maxOf { it.y }
return (maxX - minX + 1) * (maxY - minY + 1) - elves.size
}
private fun part2(input: List<String>): Int {
return solve(input, null).second
}
private fun solve(input: List<String>, max: Int?): Pair<MutableSet<Coord2D>, Int> {
val elves = mutableSetOf<Coord2D>()
input.forEachIndexed { y, line ->
line.forEachIndexed { x, c ->
if (c == '#') elves += Coord2D(x, y)
}
}
val dirs = listOf(Coord2D(0, -1), Coord2D(0, 1), Coord2D(-1, 0), Coord2D(1, 0)).map {
listOf(it, Coord2D(it.x + it.y, it.y + it.x), Coord2D(it.x - it.y, it.y - it.x))
}
var iteration = 0
while (true) {
val map = mutableMapOf<Coord2D, MutableList<Coord2D>>()
elves.forEach { e ->
if (e.adjacent(includeDiagonals = true).any { it in elves }) {
for (d in 0..3) {
val dir = dirs[(d + iteration) % 4]
if (dir.none { e + it in elves }) {
val next = e + dir.first()
map.getOrPut(next) { mutableListOf() }.add(e)
break
}
}
}
}
var moved = false
map.forEach { (dest, src) ->
if (src.size == 1) {
elves -= src.single()
elves += dest
moved = true
}
}
iteration++
if (iteration == max) break
if (!moved) break
}
return elves to iteration
}
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 2,241 | advent-of-code | MIT License |
kotlin/src/katas/kotlin/adventofcode/day9/Part1.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.adventofcode.day9
import katas.kotlin.adventofcode.day9.ParamMode.*
import java.io.*
import java.util.*
fun main() {
val text = File("src/katas/kotlin/adventofcode/day9/input.txt").readText()
val program = text.split(",").map(String::toLong)
execute(program, read = { 1 }).forEach { println(it) }
}
fun execute(program: List<Long>, read: () -> Long): List<Long> {
val programAsMap = program
.mapIndexed { index, value -> index.toLong() to value }
.toMap(TreeMap())
return sequence { execute(programAsMap, read, { yield(it) }) }.toList()
}
private inline fun execute(program: TreeMap<Long, Long>, read: () -> Long, write: (Long) -> Unit) {
var instructionPointer = 0L
var relativeBaseOffset = 0L
while (instructionPointer < program.size) {
val opCode = program[instructionPointer].toString().takeLast(2).toInt()
val paramModes = program[instructionPointer].toString().dropLast(2)
.map { it.toString().toInt() }
.let { List(3 - it.size) { 0 } + it }
.map {
when (it) {
0 -> PositionMode
1 -> ImmediateMode
2 -> RelativeMode
else -> error("")
}
}
.reversed()
val param = { index: Int -> paramModes[index - 1].read(instructionPointer + index, program, relativeBaseOffset) }
val paramValue = { index: Int -> ImmediateMode.read(instructionPointer + index, program, relativeBaseOffset) }
when (opCode) {
1 -> {
program[paramValue(3)] = param(1) + param(2)
instructionPointer += 4
}
2 -> {
program[paramValue(3)] = param(1) * param(2)
instructionPointer += 4
}
3 -> {
program[paramValue(1)] = read()
instructionPointer += 2
}
4 -> {
write(param(1))
instructionPointer += 2
}
5 -> instructionPointer = if (param(1) != 0L) param(2) else instructionPointer + 3
6 -> instructionPointer = if (param(1) == 0L) param(2) else instructionPointer + 3
7 -> {
program[paramValue(3)] = if (param(1) < param(2)) 1L else 0L
instructionPointer += 4
}
8 -> {
program[paramValue(3)] = if (param(1) == param(2)) 1L else 0L
instructionPointer += 4
}
9 -> {
relativeBaseOffset += paramValue(1)
instructionPointer += 2
}
99 -> return
else -> error("Unexpected opCode ${program[instructionPointer]} at index $instructionPointer")
}
}
}
enum class ParamMode {
PositionMode, ImmediateMode, RelativeMode;
fun read(index: Long, program: TreeMap<Long, Long>, relativeBaseOffset: Long): Long {
require(index >= 0)
val absoluteIndex = when (this) {
PositionMode -> program.getOrDefault(index, 0)
ImmediateMode -> index
RelativeMode -> relativeBaseOffset + program.getOrDefault(index, 0)
}
require(absoluteIndex >= 0)
return program.getOrDefault(absoluteIndex, 0)
}
}
| 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 3,399 | katas | The Unlicense |
src/Day04.kt | SebastianHelzer | 573,026,636 | false | {"Kotlin": 27111} |
fun main() {
fun getRangePairsFromInput(input: List<String>): List<Pair<IntRange, IntRange>> {
return input.map {
val (first, second) = it.split(',').map {
val (start, end) = it.split('-').map { it.toInt() }
start..end
}
first to second
}
}
fun part1(input: List<String>): Int {
val rangePairs: List<Pair<IntRange, IntRange>> = getRangePairsFromInput(input)
return rangePairs.count { (first, second) ->
val combined = first union second
combined == first.toSet() || combined == second.toSet()
}
}
fun part2(input: List<String>): Int {
val rangePairs: List<Pair<IntRange, IntRange>> = getRangePairsFromInput(input)
return rangePairs.count { (first, second) ->
(first intersect second).isNotEmpty()
}
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
checkEquals(2, part1(testInput))
checkEquals(4, part2(testInput))
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e48757626eb2fb5286fa1c59960acd4582432700 | 1,182 | advent-of-code-2022 | Apache License 2.0 |
src/Day04.kt | timj11dude | 572,900,585 | false | {"Kotlin": 15953} | fun main() {
val extractionRegex = "^(\\d+)-(\\d+),(\\d+)-(\\d+)$".toRegex()
fun IntRange.fullyContains(other: IntRange): Boolean = this.first <= other.first && this.last >= other.last
fun IntRange.partiallycontains(other: IntRange): Boolean = this.first in other || this.last in other || other.first in this || other.last in this
fun shared(input: Collection<String>) = input.flatMap { row ->
extractionRegex.matchEntire(row)!!.groupValues
.drop(1)
.map(String::toInt).let {
listOf(
it[0]..it[1],
it[2]..it[3]
)
}
}.windowed(2, 2)
fun part1(input: Collection<String>): Int {
return shared(input)
.count { it.first().fullyContains(it.last()) || it.last().fullyContains(it.first()) }
}
fun part2(input: Collection<String>): Int {
return shared(input)
.count { it.first().partiallycontains(it.last()) }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 28aa4518ea861bd1b60463b23def22e70b1ed481 | 1,274 | advent-of-code-2022 | Apache License 2.0 |
src/main/aoc2023/Day13.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2023
class Day13(input: List<String>) {
private val patterns2 = input.map { rawPattern ->
val rows = rawPattern.split("\n")
val cols = rows.first().indices.map { i ->
rows.map { it[i] }.joinToString("")
}
Pattern(rows, cols)
}
// Keeps rows and cols as strings for easy comparing
private data class Pattern(val rows: List<String>, val cols: List<String>)
private fun findBoth2(pattern: Pattern, fixSmudge: Boolean): Int {
val v = findReflectionLine(pattern.cols, fixSmudge)
if (v != -1) {
return v
}
val h = findReflectionLine(pattern.rows, fixSmudge)
return 100 * h
}
// Global state to keep track if the smudge has been fixed or not during comparison
private var hasFixedSmudge = false
private fun findReflectionLine(lines: List<String>, fixSmudge: Boolean): Int {
val range = lines.indices
var offset = 0
while (offset in range) {
hasFixedSmudge = false
val candidate = findCandidate(lines, offset, fixSmudge) ?: return -1
// Check all lines outward from the candidate position until we reach the edge
// or two lines no longer match
for (i in range) {
val a = candidate - i - 1
val b = candidate + i + 2
if (a !in range || b !in range) {
if (!fixSmudge || hasFixedSmudge) {
return candidate + 1
}
break
}
if (!linesMatch(lines[a], lines[b], fixSmudge)) {
break
}
}
offset = candidate + 1
}
return -1
}
// Find two identical lines next to each other. A possible candidate for the reflection line
private fun findCandidate(lines: List<String>, offset: Int, fixSmudge: Boolean): Int? {
lines.indices.drop(offset).zipWithNext().forEach { (a, b) ->
if (linesMatch(lines[a], lines[b], fixSmudge)) {
return a
}
}
return null
}
private fun linesMatch(a: String, b: String, fixSmudge: Boolean): Boolean {
var differences = 0
for (i in a.indices) {
if (a[i] != b[i]) {
differences++
}
}
if (fixSmudge && !hasFixedSmudge && differences == 1) {
// Allow the diff and fix the smudge
hasFixedSmudge = true
return true
}
return differences == 0
}
fun solvePart1(): Int {
return patterns2.sumOf { findBoth2(it, false) }
}
fun solvePart2(): Int {
return patterns2.sumOf { findBoth2(it, true) }
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 2,804 | aoc | MIT License |
src/main/kotlin/day2/day2.kt | lavong | 317,978,236 | false | null | /*
--- Day 2: Password Philosophy ---
Your flight departs in a few days from the coastal airport; the easiest way down to the coast from here is via toboggan.
The shopkeeper at the North Pole Toboggan Rental Shop is having a bad day. "Something's wrong with our computers; we can't log in!" You ask if you can take a look.
Their password database seems to be a little corrupted: some of the passwords wouldn't have been allowed by the Official Toboggan Corporate Policy that was in effect when they were chosen.
To try to debug the problem, they have created a list (your puzzle input) of passwords (according to the corrupted database) and the corporate policy when that password was set.
For example, suppose you have the following list:
1-3 a: abcde
1-3 b: cdefg
2-9 c: ccccccccc
Each line gives the password policy and then the password. The password policy indicates the lowest and highest number of times a given letter must appear for the password to be valid. For example, 1-3 a means that the password must contain a at least 1 time and at most 3 times.
In the above example, 2 passwords are valid. The middle password, <PASSWORD>g, is not; it contains no instances of b, but needs at least 1. The first and third passwords are valid: they contain one a or nine c, both within the limits of their respective policies.
How many passwords are valid according to their policies?
--- Part Two ---
While it appears you validated the passwords correctly, they don't seem to be what the Official Toboggan Corporate Authentication System is expecting.
The shopkeeper suddenly realizes that he just accidentally explained the password policy rules from his old job at the sled rental place down the street! The Official Toboggan Corporate Policy actually works a little differently.
Each policy actually describes two positions in the password, where 1 means the first character, 2 means the second character, and so on. (Be careful; Toboggan Corporate Policies have no concept of "index zero"!) Exactly one of these positions must contain the given letter. Other occurrences of the letter are irrelevant for the purposes of policy enforcement.
Given the same example list from above:
1-3 a: abcde is valid: position 1 contains a and position 3 does not.
1-3 b: cdefg is invalid: neither position 1 nor position 3 contains b.
2-9 c: ccccccccc is invalid: both position 2 and position 9 contain c.
How many passwords are valid according to the new interpretation of the policies?
*/
package day2
data class PasswordEntry(val min: Int, val max: Int, val char: Char, val password: String) {
fun isValidPart1() = password.count { it == char } in min..max
fun isValidPart2() = listOf(password[min - 1], password[max - 1]).count { it == char } == 1
}
fun main() {
val input = AdventOfCode.file("day2/input")
.lines()
.filter { it.isNotBlank() }
val passwordEntries = input
.map { it.split("-", " ", ":") }
.map { splits ->
PasswordEntry(
min = splits[0].toInt(),
max = splits[1].toInt(),
char = splits[2].toCharArray()[0],
password = splits.last()
)
}
.also { println("password entries: ${it.size}") }
passwordEntries.map { it.isValidPart1() }.filter { it }.count()
.also { println("valid passwords part1: $it") }
passwordEntries.map { it.isValidPart2() }.filter { it }.count()
.also { println("valid passwords part2: $it") }
} | 0 | Kotlin | 0 | 1 | a4ccec64a614d73edb4b9c4d4a72c55f04a4b77f | 3,526 | adventofcode-2020 | MIT License |
src/main/kotlin/com/dvdmunckhof/aoc/event2020/Day17.kt | dvdmunckhof | 318,829,531 | false | {"Kotlin": 195848, "PowerShell": 1266} | package com.dvdmunckhof.aoc.event2020
class Day17(private val input: List<String>) {
fun solvePart1(): Int {
return runCycles(3)
}
fun solvePart2(): Int {
return runCycles(4)
}
private fun runCycles(dimensions: Int): Int {
val neighbours = (0..80).map { i -> Coordinate(i % 3 - 1, i % 9 / 3 - 1, i % 27 / 9 - 1, i / 27 - 1) }
.minus(Coordinate(0, 0, 0, 0))
.filter { dimensions == 4 || it.w == 0 }
val grid = input.flatMapIndexed { x, line -> line.mapIndexed { y, c -> Coordinate(x, y, 0, 0) to (c == '#') } }
.toMap(mutableMapOf())
val sizeX = input.size
val sizeY = input[0].length
val sizeZ = 1
val sizeW = 1
for (i in 1..6) {
val offsetW = if (dimensions == 4) i else 0
val currentGrid = grid.toMap()
for (x in -i until sizeX + i) {
for (y in -i until sizeY + i) {
for (z in -i until sizeZ + i) {
for (w in -offsetW until sizeW + offsetW) {
val coordinate = Coordinate(x, y, z, w)
val count = neighbours.count { currentGrid.getOrDefault(coordinate + it, false) }
grid[coordinate] = if (currentGrid.getOrDefault(coordinate, false)) {
count == 2 || count == 3
} else {
count == 3
}
}
}
}
}
}
return grid.values.count { it }
}
private data class Coordinate(val x: Int, val y: Int, val z: Int, val w: Int) {
operator fun plus(other: Coordinate): Coordinate {
return Coordinate(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w)
}
}
}
| 0 | Kotlin | 0 | 0 | 025090211886c8520faa44b33460015b96578159 | 1,920 | advent-of-code | Apache License 2.0 |
src/main/kotlin/days/Day5.kt | VictorWinberg | 433,748,855 | false | {"Kotlin": 26228} | package days
import kotlin.math.abs
import kotlin.math.max
class Day5 : Day(5) {
private fun parseInput() = inputList.map { it.split(" -> ").map { it.split(",").map { it.toInt() } } }
override fun partOne(): Any {
val input = parseInput()
val xyInput = input.filter { (a, b) -> a[0] == b[0] || a[1] == b[1] }
return matrixCount(input, xyInput)
}
override fun partTwo(): Any {
val input = parseInput()
val xyInput = input.filter { (a, b) -> a[0] == b[0] || a[1] == b[1] || abs(a[0] - b[0]) == abs(a[1] - b[1]) }
return matrixCount(input, xyInput)
}
private fun matrixCount(
input: List<List<List<Int>>>,
xyInput: List<List<List<Int>>>
): Int {
val size = input.flatten().flatten().maxOrNull() ?: -1
val matrix = Array(size + 1) { IntArray(size + 1) { 0 } }
xyInput.forEach { (a, b) ->
val dx = b[0] - a[0]
val dy = b[1] - a[1]
val ix = if (dx > 0) 1 else if (dx < 0) -1 else 0
val iy = if (dy > 0) 1 else if (dy < 0) -1 else 0
(0..max(abs(dx), abs(dy))).forEach {
matrix[a[1] + it * iy][a[0] + it * ix] += 1
}
}
return matrix.map { it.toList() }.flatten().count { it >= 2 }
}
}
| 0 | Kotlin | 0 | 0 | d61c76eb431fa7b7b66be5b8549d4685a8dd86da | 1,308 | advent-of-code-kotlin | Creative Commons Zero v1.0 Universal |
src/Day04.kt | Ajimi | 572,961,710 | false | {"Kotlin": 11228} | fun main() {
fun part1(ranges: List<List<IntRange>>): Int = ranges.count { (first, second) ->
first.all { it in second } || second.all { it in first }
}
fun part2(ranges: List<List<IntRange>>): Int = ranges.count { (first, second) ->
first.any { it in second }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test").toSectionsRange()
check(part1(testInput) == 2)
check(part2(testInput) == 4)
val input = readInput("Day04").toSectionsRange()
println(part1(input))
println(part2(input))
}
private fun List<String>.toSectionsRange(): List<List<IntRange>> = map { sections ->
sections.split(",").map { section ->
val (start, end) = section.split("-").map { it.toInt() }
start..end
}
}
| 0 | Kotlin | 0 | 0 | 8c2211694111ee622ebb48f52f36547fe247be42 | 829 | adventofcode-2022 | Apache License 2.0 |
solutions/aockt/y2015/Y2015D18.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2015
import io.github.jadarma.aockt.core.Solution
object Y2015D18 : Solution {
private class GameOfLife(val width: Int, val height: Int, val santaVariation: Boolean = false) {
private val state = Array(width + 2) { BooleanArray(height + 2) { false } }
init {
stuckLights()
}
private fun validateCoordinates(x: Int, y: Int) {
if (x !in 0 until width || y !in 0 until height)
throw IndexOutOfBoundsException("Invalid coordinate: $x - $y")
}
operator fun get(x: Int, y: Int): Boolean {
validateCoordinates(x, y)
return state[x + 1][y + 1]
}
operator fun set(x: Int, y: Int, isAlive: Boolean) {
validateCoordinates(x, y)
state[x + 1][y + 1] = isAlive
}
/** Returns how many cells are alive in the current state of the game. */
fun aliveCells() = state.sumOf { row -> row.count { it } }
/** Passes a generation and updates the internal state. */
fun playGeneration() {
val currentGen = Array(state.size) { state[it].copyOf() }
for (x in 1..width) {
for (y in 1..height) {
val v = currentGen[x][y]
val n = currentGen.neighbourCount(x, y)
state[x][y] = when {
v && n in 2..3 -> true
!v && n == 3 -> true
else -> false
}
}
}
stuckLights()
}
/** Returns how many neighbouring cells around this point are alive. */
private fun Array<BooleanArray>.neighbourCount(x: Int, y: Int): Int {
var sum = 0
for (i in x - 1..x + 1) {
for (j in y - 1..y + 1) {
sum += this[i][j].toInt()
}
}
return sum - this[x][y].toInt()
}
private fun Boolean.toInt() = if (this) 1 else 0
/** If this is the [santaVariation], override the four corner cells to be alive. */
private fun stuckLights() {
if (!santaVariation) return
state[1][1] = true
state[width][1] = true
state[1][height] = true
state[width][height] = true
}
}
/** Parses the [input] lines and builds a new [GameOfLife] with the given initial state. */
private fun parseInput(input: List<String>, santaVariation: Boolean = false) =
GameOfLife(input.first().length, input.size, santaVariation).apply {
input.forEachIndexed { y, string ->
string.forEachIndexed { x, c ->
this[x, y] = when (c) {
'#' -> true
'.' -> false
else -> throw IllegalArgumentException("Invalid input.")
}
}
}
}
override fun partOne(input: String) = parseInput(input.lines()).run {
repeat(100) { playGeneration() }
aliveCells()
}
override fun partTwo(input: String) = parseInput(input.lines(), santaVariation = true).run {
repeat(100) { playGeneration() }
aliveCells()
}
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 3,300 | advent-of-code-kotlin-solutions | The Unlicense |
kotlin/src/com/s13g/aoc/aoc2021/Day14.kt | shaeberling | 50,704,971 | false | {"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245} | package com.s13g.aoc.aoc2021
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
/**
* --- Day 14: Extended Polymerization ---
* https://adventofcode.com/2021/day/14
*/
private typealias PairCounts = MutableMap<String, Long>
class Day14 : Solver {
override fun solve(lines: List<String>): Result {
val polymer = lines[0]
val rules = lines.filter { it.contains("->") }.map { it.split(" -> ") }.associate { it[0] to it[1][0] }
return Result("${calcRounds(polymer, rules, 10)}", "${calcRounds(polymer, rules, 40)}")
}
private fun calcRounds(polymer: String, rules: Map<String, Char>, numRounds: Int): Long {
var pairCounts: PairCounts =
polymer.windowed(2)
.map { "${it[0]}${it[1]}" }
.groupingBy { it }
.eachCount()
.map { it.key to it.value.toLong() }
.toMap()
.toMutableMap()
for (r in 1..numRounds) {
val pc2 = pairCounts.toMutableMap()
for (p in pairCounts.keys) {
if (rules.containsKey(p)) {
pc2.increment("${p[0]}${rules[p]}", pairCounts[p]!!)
pc2.increment("${rules[p]}${p[1]}", pairCounts[p]!!)
pc2[p] = pc2[p]!! - pairCounts[p]!!
}
}
pairCounts = pc2
}
// Count all individual characters.
val counts = mutableMapOf<Char, Long>()
for (pc in pairCounts) {
for (ch in pc.key) {
if (!counts.containsKey(ch)) counts[ch] = 0
counts[ch] = counts[ch]!! + pc.value
}
}
// First and last never get doubled, so add one of each for divide by two to work.
counts[polymer.first()] = counts[polymer.first()]!! + 1
counts[polymer.last()] = counts[polymer.last()]!! + 1
val max = counts.map { it.value / 2 }.max()!!
val min = counts.map { it.value / 2 }.min()!!
return max - min
}
private fun PairCounts.increment(v: String, l: Long) {
this.compute(v) { _, ll -> if (ll == null) l else ll + l }
}
} | 0 | Kotlin | 1 | 2 | 7e5806f288e87d26cd22eca44e5c695faf62a0d7 | 1,934 | euler | Apache License 2.0 |
src/main/kotlin/de/nilsdruyen/aoc/Day03.kt | nilsjr | 571,758,796 | false | {"Kotlin": 15971} | package de.nilsdruyen.aoc
fun main() {
fun part1(input: List<String>): Int = input.sumUpPrio()
fun part2(input: List<String>): Int {
return input.windowed(3, 3)
.map { group ->
group.first().first { group[1].contains(it) && group[2].contains(it) }
}
.sumOf(Char::prio)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
private fun Char.prio(): Int = if (code > 96) code - 96 else code - 38
private fun List<String>.sumUpPrio(): Int = map {
val center = it.length / 2
it.slice(0 until center) to it.slice(center until it.length)
}.map { parts ->
parts.first.first { parts.second.contains(it) }
}.sumOf(Char::prio)
| 0 | Kotlin | 0 | 0 | 1b71664d18076210e54b60bab1afda92e975d9ff | 896 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2017/Day08.kt | tginsberg | 112,672,087 | false | null | /*
* Copyright (c) 2017 by <NAME>
*/
package com.ginsberg.advent2017
/**
* AoC 2017, Day 8
*
* Problem Description: http://adventofcode.com/2017/day/8
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2017/day8/
*/
class Day08(input: List<String>) {
private val instructionRegex = """(\S+)""".toRegex()
private val registers: MutableMap<String, Int> = mutableMapOf()
private val instructions: List<Instruction> = parseInput(input)
fun solvePart1(): Int {
instructions.forEach { it.execute(registers) }
return registers.values.max() ?: 0
}
fun solvePart2(): Int =
instructions.map { it.execute(registers) }.max() ?: 0
private fun parseInput(input: List<String>): List<Instruction> =
// Row looks like: reg inc 123 if other > 3
// group numbers: ^ ^ ^ ^ ^ ^ ^
// 0 1 2 3 4 5 6
input
.map {
val groups = instructionRegex.findAll(it).toList().map { it.value }
val condition = createCondition(groups[5], groups[6].toInt())
if (groups[1] == "inc")
Instruction(condition, groups[4], groups[0]) { it + groups[2].toInt() }
else
Instruction(condition, groups[4], groups[0]) { it - groups[2].toInt() }
}
private fun createCondition(symbol: String, amount: Int): (Int) -> Boolean =
when (symbol) {
"==" -> { n -> n == amount }
"!=" -> { n -> n != amount }
"<" -> { n -> n < amount }
">" -> { n -> n > amount }
"<=" -> { n -> n <= amount }
">=" -> { n -> n >= amount }
else -> throw IllegalArgumentException("Unknown symbol: $symbol")
}
class Instruction(private val condition: (Int) -> Boolean,
private val conditionRegister: String,
private val instructionRegister: String,
private val changer: (Int) -> Int) {
fun execute(registers: MutableMap<String, Int>): Int {
if (condition(registers.getOrDefault(conditionRegister, 0))) {
registers[instructionRegister] = changer(registers.getOrDefault(instructionRegister, 0))
}
return registers.getOrDefault(instructionRegister, 0)
}
}
}
| 0 | Kotlin | 0 | 15 | a57219e75ff9412292319b71827b35023f709036 | 2,411 | advent-2017-kotlin | MIT License |
src/Day12.kt | max-zhilin | 573,066,300 | false | {"Kotlin": 114003} | fun main() {
fun part1(input: List<String>): Int {
fun map(col: Int, row: Int): Char = input[row][col]
fun height(col: Int, row: Int): Char {
val c = input[row][col]
if (c == 'S') return 'a'
if (c == 'E') return 'z'
return c
}
val (rows, cols) = listOf(input.size, input[0].length)
val steps = Array(cols) { IntArray(rows) { -1 } }
steps[138][20] = -2
var exitFound = false
var step = 0
while (!exitFound) {
for (y in 0 until rows) {
for (x in 0 until cols) {
if (step == 0 && map(x, y) == 'S') steps[x][y] = 0
if (steps[x][y] != step) continue
exitFound = exitFound || map(x, y) == 'E'
fun go(toX: Int, toY: Int) {
if (toX < 0 || toX == cols || toY < 0 || toY == rows) return
if (height(toX, toY) <= height(x, y) + 1 && steps[toX][toY] < 0) steps[toX][toY] = step + 1
}
go(x, y + 1)
go(x, y - 1)
go(x + 1, y)
go(x - 1, y)
}
}
if (!exitFound) step++
}
// println(monkeys)
return step
}
fun part2(input: List<String>): Int {
fun map(col: Int, row: Int): Char = input[row][col]
fun height(col: Int, row: Int): Char {
val c = input[row][col]
if (c == 'S') return 'a'
if (c == 'E') return 'z'
return c
}
val (rows, cols) = listOf(input.size, input[0].length)
var min = Int.MAX_VALUE
for (j in 0 until rows) {
for (i in 0 until cols) {
if (height(i, j) == 'a') {
val steps = Array(cols) { IntArray(rows) { -1 } }
steps[i][j] = 0
var exitFound = false
var step = 0
while (!exitFound) {
for (y in 0 until rows) {
for (x in 0 until cols) {
if (step == 0 && map(x, y) == 'S') steps[x][y] = 0
if (steps[x][y] != step) continue
exitFound = exitFound || map(x, y) == 'E'
fun go(toX: Int, toY: Int) {
if (toX < 0 || toX == cols || toY < 0 || toY == rows) return
if (height(toX, toY) <= height(x, y) + 1 && steps[toX][toY] < 0) steps[toX][toY] =
step + 1
}
go(x, y + 1)
go(x, y - 1)
go(x + 1, y)
go(x - 1, y)
}
}
if (!exitFound) step++
}
min = minOf(step, min)
}
}
}
return min
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day12_test")
// println(part1(testInput))
// check(part1(testInput) == 31)
// println(part2(testInput))
// check(part2(testInput) == 29)
val input = readInput("Day12")
// println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | d9dd7a33b404dc0d43576dfddbc9d066036f7326 | 3,515 | AoC-2022 | Apache License 2.0 |
app/src/main/java/com/achawki/sequencetrainer/math/Operator.kt | achawki | 382,692,328 | false | null | package com.achawki.sequencetrainer.math
import kotlin.math.min
import kotlin.random.Random
interface Operator<T> {
fun apply(t: T): Int
}
enum class BinaryOperator : Operator<Pair<Int, Int>> {
PLUS {
override fun apply(t: Pair<Int, Int>): Int {
return t.first + t.second
}
},
MINUS {
override fun apply(t: Pair<Int, Int>): Int {
return t.first - t.second
}
},
TIMES {
override fun apply(t: Pair<Int, Int>): Int {
return t.first * t.second
}
},
REMAINDER {
override fun apply(t: Pair<Int, Int>): Int {
return t.first % t.second
}
}
}
enum class UnaryOperator : Operator<Int> {
SQUARE {
override fun apply(t: Int): Int {
return t * t
}
},
DIGIT_SUM {
override fun apply(t: Int): Int {
if (t == 0) return 0
val sign = if (t < 0) -1 else 1
var digitSum = 0
var n = t * sign
while (n > 0) {
digitSum += n % 10
n /= 10
}
return digitSum * sign
}
}
}
enum class ListOperator : Operator<List<Int>> {
SUM {
override fun apply(t: List<Int>): Int {
return t.sum()
}
}
}
class WeightedOperator<T>(val operator: Operator<T>, val weight: Int)
fun getRandomOperatorsFromWeightedOperators(
availableOperators: List<WeightedOperator<*>>,
operatorsToSelect: Int
): List<Operator<*>> {
val operators = mutableListOf<Operator<*>>()
val overallWeight = availableOperators.sumOf { it.weight }
val filteredOperators = availableOperators.filter { weightedOperator -> weightedOperator.weight > 0 }
while (operators.size < min(operatorsToSelect, filteredOperators.size)) {
var currentWeight = 0
val targetWeight = Random.nextDouble() * overallWeight
for (operator in filteredOperators) {
currentWeight += operator.weight
if (currentWeight >= targetWeight) {
if (!operators.contains(operator.operator)) {
operators.add(operator.operator)
}
break
}
}
}
return operators
}
| 0 | Kotlin | 0 | 0 | fa47830638c8cbe40ba78a4cfaf61d45e12502c6 | 2,281 | number-sequence-trainer-android | Apache License 2.0 |
src/main/kotlin/days/day14/Day14.kt | Stenz123 | 725,707,248 | false | {"Kotlin": 123279, "Shell": 862} | package days.day14
import days.Day
import java.util.*
class Day14 : Day() {
override fun partOne(): Any {
val input = readInput()
val maxSize = input.size
var inputMap = mutableMapOf<Coordinate, Char>()
input.forEachIndexed { i, l ->
l.forEachIndexed { j, c ->
if (c != '.') {
inputMap[Coordinate(j, maxSize - i)] = c
}
}
}
var direction = 0
val cache = mutableListOf<MutableMap<Coordinate, Char>>()
var complete = false
val cycles = 1000000000L
var count = 0L
while (count < 4 * cycles) {
val queue: Queue<Coordinate> = when (direction) {
0 -> LinkedList(inputMap.filter { it.value == 'O' }.map { it.key }.sortedByDescending { it.y })
1 -> LinkedList(inputMap.filter { it.value == 'O' }.map { it.key }.sortedBy { it.x })
2 -> LinkedList(inputMap.filter { it.value == 'O' }.map { it.key }.sortedBy { it.y })
3 -> LinkedList(inputMap.filter { it.value == 'O' }.map { it.key }.sortedByDescending { it.x })
else -> {
throw Exception()
}
}
for (i in 0 until queue.size) {
val rock = queue.remove()
val freeSpace = when (direction) {
0 -> findNextNorthFreeSpace(rock, inputMap)
1 -> findNextWestFreeSpace(rock, inputMap)
2 -> findextSouthFreeSpace(rock, inputMap)
3 -> findNextEastFreeSpace(rock, inputMap)
else -> {
throw Exception()
}
}
inputMap.remove(rock)
inputMap[freeSpace] = 'O'
}
direction++
direction %= 4
if (direction == 0 && !complete) {
if (cache.contains(inputMap)) {
val loopStart = cache.indexOf(inputMap)
val sizeOfLoop = count / 4 - loopStart
val iterationsLeft = ((1000000000L - loopStart) % sizeOfLoop)
count = (1000000000L - iterationsLeft)*4+4
println(iterationsLeft)
complete=true
} else {
println(count)
cache.add(inputMap.toMutableMap())
}
}
count++
}
printMap(inputMap)
return inputMap.filter { it.value == 'O' }.map { it.key }.sumOf { it.y }
}
override fun partTwo(): Any {
return "day 14 part 2 not Implemented"
}
fun printMap(map: Map<Coordinate, Char>) {
for (y in map.keys.map { it.y }.max() downTo 1) {
for (x in 0..map.keys.map { it.x }.max()) {
if (map.containsKey(Coordinate(x, y))) {
print(map[Coordinate(x, y)])
} else {
print('.')
}
}
println()
}
}
}
fun findNextNorthFreeSpace(coordinate: Coordinate, map: Map<Coordinate, Char>): Coordinate {
return map.map { it.key }
.filter { it.x == coordinate.x }
.filter { it.y > coordinate.y }
.map { Coordinate(it.x, it.y - 1) }
.minByOrNull { it.y } ?: Coordinate(coordinate.x, map.map { it.key.y }.max())
}
fun findNextWestFreeSpace(coordinate: Coordinate, map: Map<Coordinate, Char>): Coordinate {
return map.map { it.key }
.filter { it.y == coordinate.y }
.filter { it.x < coordinate.x }
.map { Coordinate(it.x + 1, it.y) }
.maxByOrNull { it.x } ?: Coordinate(0, coordinate.y)
}
fun findextSouthFreeSpace(coordinate: Coordinate, map: Map<Coordinate, Char>): Coordinate {
return map.map { it.key }
.filter { it.x == coordinate.x }
.filter { it.y < coordinate.y }
.map { Coordinate(it.x, it.y + 1) }
.maxByOrNull { it.y } ?: Coordinate(coordinate.x, 1)
}
fun findNextEastFreeSpace(coordinate: Coordinate, map: Map<Coordinate, Char>): Coordinate {
//println("---")
return map.map { it.key }
.filter {
it.y == coordinate.y
}.filter {
it.x > coordinate.x
}.map {
//println("(${it.x}|${it.y})")
Coordinate(it.x - 1, it.y)
}.minByOrNull { it.x } ?: Coordinate(map.map { it.key.x }.max(), coordinate.y)
}
class Coordinate(val x: Int, val y: Int) : Comparable<Coordinate> {
override fun compareTo(other: Coordinate): Int {
if (this.y == other.y) {
return this.x.compareTo(other.x)
}
return this.y.compareTo(other.y)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Coordinate
if (x != other.x) return false
if (y != other.y) return false
return true
}
override fun hashCode(): Int {
var result = x
result = 31 * result + y
return result
}
override fun toString(): String {
return "Coordinate(x=$x, y=$y)"
}
}
| 0 | Kotlin | 1 | 0 | 3de47ec31c5241947d38400d0a4d40c681c197be | 5,251 | advent-of-code_2023 | The Unlicense |
src/day14/day14.kt | bienenjakob | 573,125,960 | false | {"Kotlin": 53763} | package day14
import inputTextOfDay
import testTextOfDay
import kotlin.math.max
import kotlin.math.min
const val day = 14
val test = testTextOfDay(day)
val input = inputTextOfDay(day)
typealias Pos = Pair<Int, Int>
val Pos.x get() = first
val Pos.y get() = second
typealias Cave = MutableMap<Pos, Char>
fun scanCave(input: String): Cave {
val cave = mutableMapOf<Pos, Char>()
val scans = input.lines()
val paths = scans.map { scan ->
scan.split(" -> ").map { node ->
node.split(",").let { (x, y) -> x.toInt() to y.toInt() }
}
}
paths.forEach { path ->
path.windowed(2).forEach { (from: Pos, to: Pos) ->
for (x in min(from.x, to.x)..max(from.x, to.x)) {
for (y in min(from.y, to.y)..max(from.y, to.y))
cave[x to y] = '#'
}
}
}
return cave
}
fun printCave(cave: MutableMap<Pos, Char>, dim: Int) {
for (y in 0..dim) {
for (x in 400..600) {
if (cave.containsKey(x to y))
print(cave[x to y])
else
print('.')
}
println("")
}
}
fun Cave.pourSand(x: Int, y: Int, abyss: Int, floor: Int): Pair<Int, Int> {
var next = x to y
do {
val current = next
// possible drop positions
val down: Pos = current.x to current.y + 1
val left: Pos = current.x-1 to current.y + 1
val right: Pos = current.x+1 to current.y + 1
// drop if possible
if (down.y != floor) {
if (!this.containsKey(down)) next = down
else if (!this.containsKey(left)) next = left
else if (!this.containsKey(right)) next = right
}
} while (next.y != current.y && next.y != abyss)
this[next] = 'o'
return next
}
fun main() {
// part1
val cave1 = scanCave(input)
val abyss = cave1.keys.map { pos -> pos.y }.max() + 1
var drops1 = -1
do {
drops1++
val y = cave1.pourSand(500,0, abyss, abyss+1).y
} while (y != abyss)
println(drops1)
check(drops1 == 644)
// part2
val cave2 = scanCave(input)
val floor = cave2.keys.map { pos -> pos.y }.max() + 2
var drops2 = 0
do {
drops2++
val y = cave2.pourSand(500,0, floor+2, floor).y
} while (y != 0)
println(drops2)
check(drops2 == 27324)
printCave(cave2, floor)
// check(part1(testInput) == 0)
// println(part1(input))
// println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 6ff34edab6f7b4b0630fb2760120725bed725daa | 2,502 | aoc-2022-in-kotlin | Apache License 2.0 |
plugins/evaluation-plugin/core/src/com/intellij/cce/metric/CodeGolfMetrics.kt | dunno99 | 221,283,848 | true | null | package com.intellij.cce.metric
import com.intellij.cce.core.Session
import com.intellij.cce.metric.util.Sample
abstract class CodeGolfMetric<T : Number> : Metric {
protected var sample = Sample()
private fun T.alsoAddToSample(): T = also { sample.add(it.toDouble()) }
protected fun computeMoves(session: Session): Int = session.lookups.sumBy { if (it.selectedPosition >= 0) it.selectedPosition else 0 }
protected fun computeCompletionCalls(sessions: List<Session>): Int = sessions.sumBy { it.lookups.count { lookup -> lookup.isNew } }
override fun evaluate(sessions: List<Session>, comparator: SuggestionsComparator): T = compute(sessions, comparator).alsoAddToSample()
abstract fun compute(sessions: List<Session>, comparator: SuggestionsComparator): T
}
class CodeGolfMovesSumMetric : CodeGolfMetric<Int>() {
override val name: String = "Code Golf Moves Count"
override val valueType = MetricValueType.INT
override val value: Double
get() = sample.sum()
override fun compute(sessions: List<Session>, comparator: SuggestionsComparator): Int {
// Add x2 amount of lookups, assuming that before each action we call code completion
// We summarize 3 types of actions:
// call code completion (1 point)
// choice suggestion from completion or symbol (if there is no offer in completion) (1 point)
// navigation to the suggestion (if it fits) (N points, based on suggestion index, assuming first index is 0)
return sessions.map { computeMoves(it) + it.lookups.count() }
.sum()
.plus(computeCompletionCalls(sessions))
}
}
class CodeGolfMovesCountNormalised : CodeGolfMetric<Double>() {
override val name: String = "Code Golf Moves Count Normalised"
override val valueType = MetricValueType.DOUBLE
override val value: Double
get() = sample.mean()
override fun compute(sessions: List<Session>, comparator: SuggestionsComparator): Double {
val linesLength = sessions.sumBy { it.expectedText.length } * 2.0
val amountOfMoves = sessions.sumBy { computeMoves(it) + it.lookups.count() } + computeCompletionCalls(sessions)
val subtrahend = sessions.count() * 2.0
// Since code completion's call and the choice of option (symbol) contains in each lookup,
// It is enough to calculate the difference for the number of lookups and extra moves (for completion case)
// To reach 0%, you also need to subtract the minimum number of lookups (eq. number of sessions plus minimum amount of completion calls)
// 0% - best scenario, every line was completed from start to end with first suggestion in list
// >100% is possible, when navigation in completion takes too many moves
return ((amountOfMoves - subtrahend) / (linesLength - subtrahend))
}
}
class CodeGolfPerfectLine : CodeGolfMetric<Int>() {
override val name: String = "Code Golf Perfect Line"
override val valueType = MetricValueType.INT
override val value: Double
get() = sample.sum()
override fun compute(sessions: List<Session>, comparator: SuggestionsComparator): Int {
return sessions.filter { it.success }
.count()
}
}
| 0 | null | 0 | 0 | f37a7bcddf4f66018f9cc8dbc109e0d49c3832a9 | 3,121 | intellij-community | Apache License 2.0 |
src/aoc23/Day07.kt | mihassan | 575,356,150 | false | {"Kotlin": 123343} | @file:Suppress("PackageDirectoryMismatch")
package aoc23.day07
import lib.Collections.histogram
import lib.Solution
enum class Card(val symbol: Char) {
JOKER('X'),
TWO('2'),
THREE('3'),
FOUR('4'),
FIVE('5'),
SIX('6'),
SEVEN('7'),
EIGHT('8'),
NINE('9'),
TEN('T'),
JACK('J'),
QUEEN('Q'),
KING('K'),
ACE('A');
companion object {
fun parse(symbol: Char): Card {
return values().find { it.symbol == symbol } ?: error("Invalid symbol: $symbol")
}
}
}
enum class HandType {
HIGH_CARD,
ONE_PAIR,
TWO_PAIRS,
THREE_OF_A_KIND,
FULL_HOUSE,
FOUR_OF_A_KIND,
FIVE_OF_A_KIND
}
data class Hand(val cards: List<Card>, val bid: Long) {
fun type(): HandType {
val counts = cards.histogram()
return when (counts.size) {
1 -> HandType.FIVE_OF_A_KIND
2 -> if (counts.values.contains(4)) HandType.FOUR_OF_A_KIND else HandType.FULL_HOUSE
3 -> if (counts.values.contains(3)) HandType.THREE_OF_A_KIND else HandType.TWO_PAIRS
4 -> HandType.ONE_PAIR
5 -> HandType.HIGH_CARD
else -> error("Invalid hand: $this")
}
}
fun jackType(): HandType {
val counts = cards.histogram()
val jackCount = counts[Card.JACK] ?: 0
val nonJackCounts = counts.filterKeys { it != Card.JACK }
return when (jackCount) {
0 -> type()
5 -> HandType.FIVE_OF_A_KIND
else -> {
val mostCommonCard = nonJackCounts.maxByOrNull { it.value }!!.key
val updatedCards = cards.map { if (it == Card.JACK) mostCommonCard else it }
Hand(updatedCards, bid).type()
}
}
}
fun plainComparator(other: Hand): Int {
if (type() != other.type()) {
return type().compareTo(other.type())
}
cards.zip(other.cards).forEach { (a, b) ->
if (a != b) {
return a.compareTo(b)
}
}
return 0
}
fun specialJackComparator(other: Hand): Int {
if (jackType() != other.jackType()) {
return jackType().compareTo(other.jackType())
}
val thisCards = cards.map { if (it == Card.JACK) Card.JOKER else it }
val otherCards = other.cards.map { if (it == Card.JACK) Card.JOKER else it }
thisCards.zip(otherCards).forEach { (a, b) ->
if (a != b) {
return a.compareTo(b)
}
}
return 0
}
companion object {
fun parse(handStr: String): Hand {
HandType.entries.toList().sorted()
val (cards, bid) = handStr.split(" ")
return Hand(cards.map { Card.parse(it) }, bid.toLong())
}
}
}
typealias Input = List<Hand>
typealias Output = Long
private val solution = object : Solution<Input, Output>(2023, "Day07") {
override fun parse(input: String): Input = input.lines().map { Hand.parse(it) }
override fun format(output: Output): String = "$output"
override fun part1(input: Input): Output =
input.sortedWith(Hand::plainComparator)
.mapIndexed { index, hand -> (index + 1) * hand.bid }.sum()
override fun part2(input: Input): Output =
input.sortedWith(Hand::specialJackComparator)
.mapIndexed { index, hand -> (index + 1) * hand.bid }.sum()
}
fun main() = solution.run()
| 0 | Kotlin | 0 | 0 | 698316da8c38311366ee6990dd5b3e68b486b62d | 3,125 | aoc-kotlin | Apache License 2.0 |
src/day2/Day02.kt | AhmedAshour | 574,898,033 | false | {"Kotlin": 4639} | package day2
import readInput
fun main() {
val input = readInput("src/day2", "input").toString()
val formattedInput = input.trim { it == '[' || it == ']' }.split(",").map { it.trim() }
println(partOne(formattedInput))
println(partTwo(formattedInput))
}
fun partOne(input: List<String>): Int {
// Column 1 (Opponent)
// A -> Rock, B -> Paper, C -> Scissors
// Column 2 (Me)
// X -> Rock, Y -> Paper, Z -> Scissors
// Single Round Score
// 1 -> Rock, 2 -> Paper, 3 -> Scissors + outcome (Lost -> 0, Draw -> 3, Won -> 6)
var totalScore = 0
input.forEach {
val myPlay = it[2]
val opponentPlay = when (it[0]) {
'A' -> 'X'
'B' -> 'Y'
'C' -> 'Z'
else -> ' '
}
totalScore += when (myPlay) {
'X' -> 1
'Y' -> 2
'Z' -> 3
else -> 0
}
totalScore += when {
myPlay == opponentPlay -> 3
myPlay == 'X' && opponentPlay == 'Z' || myPlay == 'Y' && opponentPlay == 'X' || myPlay == 'Z' && opponentPlay == 'Y' -> 6
else -> 0
}
}
return totalScore
}
fun partTwo(input: List<String>): Int {
// Column 1 (Opponent)
// A -> Rock, B -> Paper, C -> Scissors
// Column 2 (Me)
// X -> Lose, Y -> Draw, Z -> Win
// Single Round Score
// 1 -> Rock, 2 -> Paper, 3 -> Scissors + outcome (Lost -> 0, Draw -> 3, Won -> 6)
var totalScore = 0
input.forEach {
val expectedOutcome = it[2]
val opponentPlay = when (it[0]) {
'A' -> 'X'
'B' -> 'Y'
'C' -> 'Z'
else -> ' '
}
totalScore += when (expectedOutcome) {
'Y' -> 3
'Z' -> 6
else -> 0
}
totalScore += when {
opponentPlay == 'X' && expectedOutcome == 'Z' || opponentPlay == 'Y' && expectedOutcome == 'Y' || opponentPlay == 'Z' && expectedOutcome == 'X' -> 2
opponentPlay == 'X' && expectedOutcome == 'X' || opponentPlay == 'Y' && expectedOutcome == 'Z' || opponentPlay == 'Z' && expectedOutcome == 'Y' -> 3
else -> 1
}
}
return totalScore
}
| 0 | Kotlin | 0 | 0 | 59b9e895649858de0b95fa2e6eef779bc0d8b45c | 2,229 | adventofcode-2022 | Apache License 2.0 |
src/Day03.kt | coolcut69 | 572,865,721 | false | {"Kotlin": 36853} | fun main() {
val scores = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
fun part1(inputs: List<String>): Int {
var score = 0
for (rucksack in inputs) {
val chunked = rucksack.chunked(rucksack.length / 2)
val firstCompartment = chunked.first()
val secondsCompartment = chunked.last()
val intersect = firstCompartment.toList().intersect(secondsCompartment.toList().toSet())
score += scores.indexOf(intersect.first()) + 1
}
return score
}
fun part2(inputs: List<String>): Int {
var score = 0
for (rucksack in inputs.chunked(3)) {
val intersect =
rucksack.get(0).toList().intersect(rucksack.get(1).toList()).intersect(rucksack.get(2).toList())
score += scores.indexOf(intersect.first()) + 1
}
return score
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
check(part1(input) == 8298)
println(part2(input))
check(part2(input) == 2708)
}
| 0 | Kotlin | 0 | 0 | 031301607c2e1c21a6d4658b1e96685c4135fd44 | 1,243 | aoc-2022-in-kotlin | Apache License 2.0 |
src/day21/Day21.kt | davidcurrie | 579,636,994 | false | {"Kotlin": 52697} | package day21
import java.io.File
import kotlin.math.roundToLong
fun main() {
val input = File("src/day21/input.txt").readLines()
.map { it.split(": ") }
.associate { it[0] to it[1] }
println(part1(input, "root"))
input["root"]!!.split(" ").let {
val lhs = part2(input, it[0])
val rhs = part2(input, it[2])
println(((rhs.second - lhs.second) / (lhs.first - rhs.first)).roundToLong())
}
}
fun part1(input: Map<String, String>, monkey: String): Long {
val output = input[monkey]!!
if (output.contains(" ")) {
output.split(" ").let { parts ->
val a = part1(input, parts[0])
val b = part1(input, parts[2])
return when (parts[1]) {
"+" -> a + b
"-" -> a - b
"*" -> a * b
"/" -> a / b
else -> throw IllegalStateException("Unknown operation ${parts[1]}")
}
}
}
return output.toLong()
}
fun part2(input: Map<String, String>, monkey: String): Pair<Double, Double> {
val result: Pair<Double, Double>
if (monkey == "humn") {
result = Pair(1.0, 0.0)
} else {
val output = input[monkey]!!
if (output.contains(" ")) {
output.split(" ").let { parts ->
val a = part2(input, parts[0])
val b = part2(input, parts[2])
result = when (parts[1]) {
"+" -> Pair(a.first + b.first, a.second + b.second)
"-" -> Pair(a.first - b.first, a.second - b.second)
"*" -> if (a.first == 0.0) Pair(
a.second * b.first,
a.second * b.second
) else if (b.first == 0.0) Pair(
b.second * a.first,
b.second * a.second
) else throw IllegalStateException("Multiplication by humn")
"/" -> if (b.first == 0.0) Pair(
a.first / b.second,
a.second / b.second
) else throw IllegalStateException("Division by humn")
else -> throw IllegalStateException("Unknown operation ${parts[1]}")
}
}
} else {
result = Pair(0.0, output.toDouble())
}
}
return result
} | 0 | Kotlin | 0 | 0 | 0e0cae3b9a97c6019c219563621b43b0eb0fc9db | 2,391 | advent-of-code-2022 | MIT License |
src/Day03/Day03.kt | rooksoto | 573,602,435 | false | {"Kotlin": 16098} | package Day03
import profile
import readInputActual
import readInputTest
private const val DAY = "Day03"
private const val UPPERCASE_BASELINE = 38
private const val LOWERCASE_BASELINE = 96
fun main() {
fun part1(
input: List<String>
): Int = input.map(::toCharArrayPair)
.map(::toIntersectedChar)
.map(::toIntValue)
.sum()
fun part2(
input: List<String>
): Int = input.chunked(3)
.map(::toBadgeChar)
.map(::toIntValue)
.sum()
val testInput = readInputTest(DAY)
val input = readInputActual(DAY)
check(part1(testInput) == 157)
profile(shouldLog = true) {
println("Part 1: ${part1(input)}")
} // Answer: 8109 @ 24ms
check(part2(testInput) == 70)
profile(shouldLog = true) {
println("Part 2: ${part2(input)}")
} // Answer: 2738 @ 5ms
}
private val String.halfWayPoint: Int
get() = this.length / 2
private fun <T> List<T>.second(): T = this[1]
private fun toCharArrayPair(
input: String
): Pair<CharArray, CharArray> =
with(input) {
Pair(
substring(0, halfWayPoint).toCharArray(),
substring(halfWayPoint, length).toCharArray()
)
}
private fun toBadgeChar(
stringList: List<String>
): Char = with(stringList) {
(first().toSet().intersect(second().toSet())).intersect(last().toSet())
}.first()
private fun toIntersectedChar(
stringPair: Pair<CharArray, CharArray>
): Char = with(stringPair) {
first.toSet().intersect(second.toSet()).first()
}
private fun toIntValue(
char: Char
): Int = with(char) {
if (isUpperCase()) code - UPPERCASE_BASELINE
else code - LOWERCASE_BASELINE
}
| 0 | Kotlin | 0 | 1 | 52093dbf0dc2f5f62f44a57aa3064d9b0b458583 | 1,697 | AoC-2022 | Apache License 2.0 |
src/main/kotlin/problems/Day5.kt | PedroDiogo | 432,836,814 | false | {"Kotlin": 128203} | package problems
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
class Day5(override val input: String) : Problem {
override val number: Int = 5
private val lines = input.lines().map { line -> Line.fromStr(line) }
override fun runPartOne(): String {
val straightLines = lines.filter { line -> line.isVertical() || line.isHorizontal() }
return numberOfOverlappingPoints(straightLines)
.toString()
}
override fun runPartTwo(): String {
return numberOfOverlappingPoints(lines).toString()
}
private fun numberOfOverlappingPoints(lines: List<Line>): Int {
return lines.flatMap { line -> line.points().toList() }
.groupingBy { it }
.eachCount()
.count { (_, count) -> count > 1 }
}
private data class Line(val x1: Int, val y1: Int, val x2: Int, val y2: Int) {
companion object {
fun fromStr(lineStr: String): Line {
val (x1, y1, x2, y2) = lineStr
.replace(" -> ", ",")
.split(",")
.map { i -> i.toInt() }
return Line(x1, y1, x2, y2)
}
}
fun isVertical(): Boolean {
return x1 == x2
}
fun isHorizontal(): Boolean {
return y1 == y2
}
fun points(): Set<Pair<Int, Int>> {
val length = max(abs(y2 - y1), abs(x2 - x1)) + 1
val (xRange, yRange) = when {
isVertical() -> Pair(List(length) { x1 }, getRange(y1, y2))
isHorizontal() -> Pair(getRange(x1, x2), List(length) { y1 })
else -> Pair(getRange(x1, x2), getRange(y1, y2))
}
return xRange.zip(yRange)
.toSet()
}
fun getRange(from: Int, to: Int): List<Int> {
val results = (min(from, to)..max(from, to)).toList()
return when {
from < to -> results
else -> results.reversed()
}
}
}
} | 0 | Kotlin | 0 | 0 | 93363faee195d5ef90344a4fb74646d2d26176de | 2,073 | AdventOfCode2021 | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.