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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
solutions/aockt/y2016/Y2016D07.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2016
import io.github.jadarma.aockt.core.Solution
object Y2016D07 : Solution {
/** A valid IPv7 address. */
private data class IPv7Address(val value: String) {
/** All sequences in the address, in order. */
val sequences: List<String> = buildList {
// Note: This initialization is just for show, correctly parsing the addresses and reporting errors.
// However, since the problem input is always valid, this can be replaced with just for brevity:
//
// ```kotlin
// val sequences = value.split(Regex("""[\[\]]"""))
// ```
val sequence = StringBuilder()
var insideSequence = false
val emitSequence = {
val net = sequence.toString()
sequence.clear()
require(net.isNotEmpty()) { "Invalid address; sequences cannot be empty." }
add(net)
}
value.forEach { c ->
when (c) {
'[' -> {
require(!insideSequence) { "Invalid address; sequences cannot be nested." }
insideSequence = true
emitSequence()
}
']' -> {
require(insideSequence) { "Invalid address; unmatched closing bracket." }
insideSequence = false
emitSequence()
}
else -> {
require(c in 'a'..'z') { "Invalid address; illegal character." }
sequence.append(c)
}
}
}
require(!insideSequence) { "Invalid address; unmatched opening bracket." }
emitSequence()
}
/** Returns only the superNet sequences of the address (outside of brackets). */
val superNetSequences: List<String> get() = sequences.filterIndexed { index, _ -> index % 2 == 0 }
/** Returns only the hyperNet sequences of the address (inside of brackets). */
val hyperNetSequences: List<String> get() = sequences.filterIndexed { index, _ -> index % 2 == 1 }
/** Whether this address supports Transport-Layer Snooping. */
val supportsTls: Boolean
get() = superNetSequences.any { it.findABBAs().isNotEmpty() } &&
hyperNetSequences.all { it.findABBAs().isEmpty() }
/** Whether this address supports Super-Secret Listening. */
val supportsSsl: Boolean
get() {
val aba = superNetSequences.flatMap { it.findABAs() }.toSet()
val bab = hyperNetSequences.flatMap { it.findABAs() }.toSet()
return aba.any { a -> bab.any { b -> a[0] == b[1] && a[1] == b[0] } }
}
/** Returns a set of all Autonomous Bridge Bypass Annotation contained in this sequence. */
private fun String.findABBAs() =
windowedSequence(4)
.filter { it[0] != it[1] && it[0] == it[3] && it[1] == it[2] }
.toSet()
/** Returns a set of all Area-Broadcast Accessors and Byte Allocation Blocks contained in this sequence. */
private fun String.findABAs(): Set<String> =
windowedSequence(3)
.filter { it[0] != it[1] && it[0] == it[2] }
.toSet()
}
override fun partOne(input: String) = input.lineSequence().map(::IPv7Address).count { it.supportsTls }
override fun partTwo(input: String) = input.lineSequence().map(::IPv7Address).count { it.supportsSsl }
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 3,645 | advent-of-code-kotlin-solutions | The Unlicense |
src/2020/Day11_1.kts | Ozsie | 318,802,874 | false | {"Kotlin": 99344, "Python": 1723, "Shell": 975} | import java.io.File
val input = ArrayList<CharArray>()
File("input/2020/day11").forEachLine { input.add(it.toCharArray()) }
var previous = input
var modified = copy(input)
var runs = 0
while (isChanged(previous,modified) || runs == 0) {
previous = copy(modified)
modified = ArrayList<CharArray>()
for (y in IntRange(0,input.size-1)) {
val row = previous[y]
modified.add(CharArray(row.size))
for (x in IntRange(0,row.size-1)) {
val newState = if (modified[y][x] == '.') '.' else newState(x,y,previous[y][x],previous)
modified[y].set(x,newState)
}
}
runs++
}
var occupied = 0
modified.forEach { occupied += it.filter { it == '#' }.size }
println(occupied)
fun isChanged(previous: ArrayList<CharArray>, modified: ArrayList<CharArray>): Boolean {
for (y in IntRange(0,previous.size-1)) {
for (x in IntRange(0,previous[y].size-1)) {
if (previous[y][x] != modified[y][x]) return true
}
}
return false
}
fun copy(o: ArrayList<CharArray>) = ArrayList<CharArray>().apply {
o.forEach {
var newChArr = CharArray(it.size)
it.copyInto(newChArr)
add(newChArr)
}
}
fun newState(x: Int, y: Int, seat: Char, input: ArrayList<CharArray>): Char {
var occupied = 0
for (aY in IntRange(y-1,y+1)) {
for (aX in IntRange(x-1,x+1)) {
if (aY == y && aX == x) continue
if (aY < 0 || aY >= input.size || aX < 0 || aX >= input[aY].size) continue
if (input[aY][aX] == '#') occupied++
}
}
return if (occupied == 0 && seat == 'L') '#' else if (occupied >= 4 && seat == '#') 'L' else seat
}
| 0 | Kotlin | 0 | 0 | d938da57785d35fdaba62269cffc7487de67ac0a | 1,671 | adventofcode | MIT License |
src/main/kotlin/dev/shtanko/algorithms/codingbat/recursion2/GroupSumClump.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2024 <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.codingbat.recursion2
import java.util.Stack
/**
* Recursion-2 > groupSumClump
* @see <a href="https://codingbat.com/prob/p105136">Source</a>
*/
fun interface GroupSumClump {
operator fun invoke(start: Int, nums: IntArray, target: Int): Boolean
}
class GroupSumClumpIterative : GroupSumClump {
override fun invoke(start: Int, nums: IntArray, target: Int): Boolean {
val n = nums.size
val dp = Array(n + 1) { BooleanArray(target + 1) }
// Base case: if target is 0, we can achieve it by not selecting any elements
for (i in 0..n) {
dp[i][0] = true
}
var i = 1
while (i <= n) {
// Find the end index of the current clump
var end = i
while (end < n && nums[end] == nums[i - 1]) {
end++
}
// Calculate the sum of the current clump
val clumpSum = nums[i - 1] * (end - i + 1)
for (j in 0..target) {
// Exclude the current clump
dp[end][j] = dp[i - 1][j]
// Include the current clump if it doesn't exceed the target
if (j >= clumpSum) {
dp[end][j] = dp[end][j] || dp[i - 1][j - clumpSum]
}
}
// Move to the end of the clump
i = end + 1
}
return dp[n][target]
}
}
class GroupSumClumpRecursion : GroupSumClump {
override fun invoke(start: Int, nums: IntArray, target: Int): Boolean {
if (start >= nums.size) {
return target == 0
}
var end = start + 1
while (end < nums.size && nums[end] == nums[start]) {
end++
}
val clumpSum = nums[start].times(end.minus(start))
return invoke(end, nums, target - clumpSum) || invoke(end, nums, target)
}
}
class GroupSumClumpStack : GroupSumClump {
override fun invoke(start: Int, nums: IntArray, target: Int): Boolean {
val n = nums.size
val stack = Stack<Pair<Int, Int>>() // Pair to store index and cumulative sum
stack.push(0 to 0) // Initial state: index = 0, cumulative sum = 0
while (stack.isNotEmpty()) {
val (index, cumSum) = stack.pop()
if (index == n) {
if (cumSum == target) {
return true
}
continue
}
// Find the end index of the current clump
var end = index + 1
while (end < n && nums[end] == nums[index]) {
end++
}
// Explore two possibilities: include or exclude the current clump
stack.push(end to cumSum + (end - index) * nums[index]) // Include the current clump
stack.push(end to cumSum) // Exclude the current clump
}
return false
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,514 | kotlab | Apache License 2.0 |
src/main/kotlin/nl/fifthpostulate/specifikation/algebra/Algebra.kt | fifth-postulate | 283,838,936 | false | null | package nl.fifthpostulate.specifikation.algebra
import nl.fifthpostulate.specifikation.*
class All<T, V>(private vararg val specifications: Specification<T, V>) : Specification<T, V> {
override fun isMetBy(subject: T): Report<V> {
return specifications
.map { it.isMetBy(subject) }
.reduce { acc, report -> acc.andThen {report} }
}
}
class OneOf<T, V>(private vararg val specifications: Specification<T, V>) : Specification<T, V> {
override fun isMetBy(subject: T): Report<V> {
val partition = specifications
.map { it.isMetBy(subject) }
.partition { it is Success }
return if (partition.first.isNotEmpty()) {
partition.first.first()
} else {
partition.second.reduce { acc, report -> acc.andThen {report} }
}
}
}
data class Not<T, V>(private val specification: Specification<T, V>) : Specification<T, V> {
override fun isMetBy(subject: T): Report<V> {
return when (specification.isMetBy(subject)) {
is Success -> Failure(listOf()) // TODO message kind of failure
is Failure -> Success()
}
}
}
data class Fail<T, V>(private val violation: V) : Specification<T, V> {
override fun isMetBy(subject: T): Report<V> {
return Failure(listOf(violation))
}
}
class Succeed<T, V>(): Specification<T, V> {
override fun isMetBy(subject: T): Report<V> {
return Success()
}
}
| 0 | Kotlin | 0 | 0 | 25fc5c99cd1d426c67dfd05d5648a9b2a59779e2 | 1,476 | specifikation | MIT License |
src/Day04.kt | mkulak | 573,910,880 | false | {"Kotlin": 14860} | fun main() {
val regex = "([0-9]+)-([0-9]+),([0-9]+)-([0-9]+)".toRegex()
fun part1(input: List<String>): Int =
input.count { line ->
val (s1, e1, s2, e2) = regex.matchEntire(line)!!.groupValues.drop(1).map { it.toInt() }
s1 <= s2 && e1 >= e2 || s1 >= s2 && e1 <= e2
}
fun part2(input: List<String>): Int =
input.count { line ->
val (s1, e1, s2, e2) = regex.matchEntire(line)!!.groupValues.drop(1).map { it.toInt() }
s2 in s1..e1 || e2 in s1..e1 || s1 in s2..e2 || e1 in s2..e2
}
val input = readInput("Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 3b4e9b32df24d8b379c60ddc3c007d4be3f17d28 | 663 | AdventOfKo2022 | Apache License 2.0 |
src/day13/Comparator.kt | g0dzill3r | 576,012,003 | false | {"Kotlin": 172121} | package day13
import readInput
class ComparatorContext {
var depth = 0
val debug = false
val prefix: String
get () = " ".repeat (depth * 2)
fun print (s: String) {
if (debug) println ("${prefix}$s")
return
}
fun compare (a: Any, b: Any) {
if (debug) println ("${prefix}COMPARE $a AND $b")
depth++
}
fun pop (value: Int) {
depth --
if (debug) println ("${prefix}RETURN $value")
}
}
private fun coerceList (any: Any): List<Any> {
return when (any) {
is Int -> listOf (any)
is List<*> -> any as List<Any>
else -> throw IllegalStateException ()
}
}
/**
* Compares the two data structures and returns true if they're in
* the proper order.
*/
fun compare (left: List<Any>, right: List<Any>, ctx: ComparatorContext? = null): Int {
ctx?.apply { compare (left, right) }
for (i in 0 until left.size) {
if (right.size == i) {
ctx?.run { pop (1) }
return 1
}
val lval = left[i]
val rval = right[i]
if (lval is Int && rval is Int) {
ctx?.print ("$lval ? $rval")
when {
lval > rval -> {
ctx?.run { pop (1) }
return 1
}
rval > lval -> {
ctx?.run { pop (-1) }
return -1
}
else -> Unit
}
} else {
val check = compare (coerceList (lval), coerceList (rval), ctx)
if (check != 0) {
ctx?.run { pop (check) }
return check
}
}
}
if (left.size == right.size) {
ctx?.run { pop (0) }
return 0
}
ctx?.run { pop (-1) }
return -1
}
fun main (args: Array<String>) {
val packets = Packets.parse (readInput (13, true))
packets.data.forEach {
val (left, right) = it
val compare = compare (left, right, ComparatorContext())
println ("$left AND $right are ${if (compare (left, right) != -1) "NOT " else ""}in the right order")
println ("\n\n")
}
}
// EOF | 0 | Kotlin | 0 | 0 | 6ec11a5120e4eb180ab6aff3463a2563400cc0c3 | 2,193 | advent_of_code_2022 | Apache License 2.0 |
ceres-base/src/main/kotlin/ceres/geo/Selection.kt | regen-network | 197,295,201 | false | null | package ceres.geo
import kotlin.math.*
// Floyd-Rivest selection algorithm from https://github.com/mourner/quickselect
fun quickselect(
arr: Array<Double>,
k: Int,
left: Int = 0,
right: Int = arr.size - 1,
compare: Comparator<Double> = defaultCompare
) {
quickselectStep(arr, k, left, right, compare)
}
fun quickselectStep(
arr: Array<Double>,
k: Int,
l: Int,
r: Int,
compare: Comparator<Double>
){
var left = l
var right = r
while(right > left) {
if (right - left > 600) {
val n = right - left + 1
val m = k - left
val z = ln(n.toFloat())
val s = 0.5 * exp(2 * z / 3)
val sd = 0.5 * sqrt(z * s * (n - s) / n) * (if (m - n / 2 < 0) -1 else 1)
val newLeft = max(left, floor(k - m * s / n + sd).toInt())
val newRight = min(right, floor(k + (n - m) * s / n + sd).toInt())
quickselectStep(arr, k, newLeft, newRight, compare)
}
val t = arr[k]
var i = left
var j = right
swap(arr, left, k)
if (compare.compare(arr[right], t) > 0) swap(arr, left, right)
while (i < j) {
swap(arr, i, j)
i++
j++
while (compare.compare(arr[i], t) < 0) i++
while (compare.compare(arr[j], t) > 0) i++
}
if (compare.compare(arr[left], t) == 0) swap(arr, left, j)
else {
j++
swap(arr, j, right)
}
if (j <= k) left = j + 1
if (k <= j) right = j - 1
}
}
fun swap(arr: Array<Double>, i: Int, j: Int) {
val tmp = arr[i]
arr[i] = arr[j]
arr[j] = tmp
}
val defaultCompare: Comparator<Double> = object : Comparator<Double> {
override fun compare(a: Double, b: Double): Int = a.compareTo(b)
}
| 0 | Kotlin | 1 | 0 | ea053727b75e9adf5a76c337b006be627cd3322f | 1,836 | regen-kotlin-sdk | Apache License 2.0 |
src/main/kotlin/com/polydus/aoc18/Day6.kt | Polydus | 160,193,832 | false | null | package com.polydus.aoc18
class Day6: Day(6){
//https://adventofcode.com/2018/day/6
val map: MutableList<Pos> = mutableListOf()
init {
//partOne()
partTwo()
}
fun partOne(){
var highestX = 0
var highestY = 0
input.forEach {
val chars = it.toCharArray()
var x = 0
var y = 0
for(i in 0 until it.length){
if(chars[i] == ','){
x = it.substring(0, i).toInt()
} else if(chars[i] == ' '){
y = it.substring(i + 1, it.length).toInt()
}
}
if(x > highestX) highestX = x + 2
if(y > highestY) highestY = y + 2
map.add(Pos(x, y, (map.size + 65).toChar()))
//println(map.last())
}
val twoDMap = Array(highestY + 1) {Array<Pos?>(highestX + 1) {null} }
val closestMapId = Array(highestY + 1) {Array<Int>(highestX + 1) {-1} }
val closestMapDist = Array(highestY + 1) {Array<Int>(highestX + 1) {Integer.MAX_VALUE} }
for(pos in map.withIndex()){
twoDMap[pos.value.y][pos.value.x] = pos.value
for(y in 0 until highestY){
for(x in 0 until highestX){
val dist = pos.value.distTo(x, y)
if(dist < closestMapDist[y][x]){
closestMapDist[y][x] = dist
closestMapId[y][x] = pos.index//pos.char.toLowerCase()
} else if(dist == closestMapDist[y][x]){
closestMapId[y][x] = -1//'.'
}
}
}
}
val sizeCounters = Array<Int>(map.size){1}
for(y in 0 until highestY){
for(x in 0 until highestX){
if(twoDMap[y][x] == null){
val id = closestMapId[y][x]
if(id == -1){
print("\u001B[0m.")
} else {
if(x == 0 || y == 0 || x == highestX - 1 || y == highestY - 1){
sizeCounters[id] = -1
} else if(sizeCounters[id] > -1){
sizeCounters[id]++
}
print("\u001B[0m${map[closestMapId[y][x]].char.toLowerCase()}")
}
} else {
print("\u001B[36m${twoDMap[y][x]!!.char}")
}
}
print("\n")
}
var maxId = 0
var highest = 0
for(c in sizeCounters.withIndex()){
if(c.value > highest){
maxId = c.index
highest = c.value
}
//println("${map[c.index].char} with ${c.value}")
}
println("answer is ${map[maxId].char} with $highest")
}
fun partTwo(){
var highestX = 0
var highestY = 0
input.forEach {
val chars = it.toCharArray()
var x = 0
var y = 0
for(i in 0 until it.length){
if(chars[i] == ','){
x = it.substring(0, i).toInt()
} else if(chars[i] == ' '){
y = it.substring(i + 1, it.length).toInt()
}
}
if(x > highestX) highestX = x + 2
if(y > highestY) highestY = y + 2
map.add(Pos(x, y, (map.size + 65).toChar()))
//println(map.last())
}
val twoDMap = Array(highestY + 1) {Array<Pos?>(highestX + 1) {null} }
for(pos in map.withIndex()){
twoDMap[pos.value.y][pos.value.x] = pos.value
}
var size = 0
for(y in 0 until highestY){
for(x in 0 until highestX){
var dist = 0
for(m in map){
dist += m.distTo(x, y)
}
if(dist < 10000){
size++
}
if(twoDMap[y][x] == null){
if(dist < 10000){
print("\u001B[0m#")
} else {
print("\u001B[0m.")
}
} else {
print("\u001B[36m${twoDMap[y][x]!!.char}")
}
}
print("\n")
}
println("answer is $size")
}
class Pos(val x: Int, val y: Int, var char: Char){
fun distTo(x: Int, y: Int): Int{
return Math.abs(this.x - x) + Math.abs(this.y - y)
}
override fun equals(other: Any?): Boolean {
if(other is com.polydus.aoc18.Pos){
return other.x == x && other.y == y
}
return super.equals(other)
}
override fun toString(): String {
return "${x}x${y}y"
}
}
} | 0 | Kotlin | 0 | 0 | e510e4a9801c228057cb107e3e7463d4a946bdae | 4,937 | advent-of-code-2018 | MIT License |
src/day09/Day09.kt | daniilsjb | 726,047,752 | false | {"Kotlin": 66638, "Python": 1161} | package day09
import java.io.File
fun main() {
val data = parse("src/day09/Day09.txt")
println("🎄 Day 09 🎄")
println()
println("[Part 1]")
println("Answer: ${part1(data)}")
println()
println("[Part 2]")
println("Answer: ${part2(data)}")
}
private fun parse(path: String): List<List<Int>> =
File(path)
.readLines()
.map { it.split(" ").map(String::toInt) }
private fun part1(data: List<List<Int>>): Int =
data.sumOf { history ->
generateSequence(history) { it.zipWithNext { a, b -> b - a } }
.takeWhile { !it.all { diff -> diff == 0 } }
.sumOf { it.last() }
}
private fun part2(data: List<List<Int>>): Int =
data.sumOf { history ->
generateSequence(history) { it.zipWithNext { a, b -> b - a } }
.takeWhile { !it.all { diff -> diff == 0 } }
.toList()
.foldRight(0) { it, acc -> it.first() - acc }.toInt()
}
| 0 | Kotlin | 0 | 0 | 46a837603e739b8646a1f2e7966543e552eb0e20 | 1,004 | advent-of-code-2023 | MIT License |
codeforces/kotlinheroes8/i.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.kotlinheroes8
import java.util.*
private fun solve() {
val n = readInt()
val (from, toIn) = List(2) { readInts() }
data class Doctor(val id: Int, val from: Int, val to: Int)
val doctors = List(n) { Doctor(it, from[it], toIn[it] + 1) }
val low = doctors.sortedBy { it.from }.withIndex().maxOf { it.value.from - it.index }
val high = doctors.sortedBy { it.to }.withIndex().minOf { it.value.to - it.index }
if (low >= high) return println(-1)
val byStart = doctors.groupBy { it.from }
val queue = PriorityQueue<Doctor>(compareBy({ it.to }, { it.id }))
queue.addAll(doctors.filter { it.from <= low })
val ans = (low until low + n).map { time ->
val doctor = queue.poll()
if (doctor.to <= time) return println(-1)
queue.addAll(byStart[time + 1] ?: emptyList())
doctor.id
}
println(low)
println(ans.map { it + 1 }.joinToString(" "))
}
fun main() = repeat(readInt()) { solve() }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,100 | competitions | The Unlicense |
src/Day09.kt | TinusHeystek | 574,474,118 | false | {"Kotlin": 53071} | import extensions.*
import kotlin.math.absoluteValue
class Day09 : Day(9) {
class Command(line: String) {
var directions = Vector2(0, 0)
var amount = 0
init {
val split = line.split(" ")
when (split[0]) {
"R" -> directions = Vector2(1, 0)
"U" -> directions = Vector2(0, 1)
"L" -> directions = Vector2(-1, 0)
"D" -> directions = Vector2(0, -1)
}
amount = split[1].toInt()
}
}
private fun followTheRope(input: String, ropeLength: Int) : Int {
val commands = input.lines().map {Command(it)}
val knots = MutableList(ropeLength) { Vector2(0, 0) }
val grid = mutableMapOf<Vector2, Boolean>()
grid[knots.last()] = true
for (command in commands) {
repeat(command.amount) {
knots[0] = knots[0] + command.directions
for (index in 1 until knots.count()) {
val distance = knots[index -1] - knots[index]
if (distance.x.absoluteValue > 1 || distance.y.absoluteValue > 1) {
knots[index] = knots[index] + distance.sign
} else break
}
grid[knots.last()] = true
}
}
return grid.count { it.value }
}
// --- Part 1 ---
override fun part1ToInt(input: String): Int {
return followTheRope(input, 2)
}
// --- Part 2 ---
override fun part2ToInt(input: String): Int {
return followTheRope(input, 10)
}
}
fun main() {
Day09().printToIntResults(13, 1)
}
| 0 | Kotlin | 0 | 0 | 80b9ea6b25869a8267432c3a6f794fcaed2cf28b | 1,671 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/Snailfish_18.kt | Flame239 | 433,046,232 | false | {"Kotlin": 64209} | val numbers: List<String> by lazy {
readFile("Snailfish").split("\n")
}
fun lexemize(input: String): ArrayDeque<String> {
val lexems = ArrayDeque<String>()
var i = 0
while (i < input.length) {
val char = input[i]
if (char.isDigit()) {
var end = i
while (input[end].isDigit()) end++
lexems.add(input.substring(i, end))
i = end
} else {
lexems.add(char.toString())
i++
}
}
return lexems
}
fun reduce(input: ArrayDeque<String>): ArrayDeque<String> {
var wasReduced = true
while (wasReduced) {
wasReduced = false
if (explode(input)) {
wasReduced = true
continue
}
if (split(input)) {
wasReduced = true
}
}
return input
}
fun explode(input: ArrayDeque<String>): Boolean {
var balance = 0
val size = input.size
var i = 0
while (i < size) {
val lex = input[i]
if (lex == "[") {
balance++
if (balance >= 5) {
val isSimplePair = isNumber(input[i + 1]) && input[i + 2] == "," && isNumber(input[i + 3])
if (isSimplePair) {
val left = input[i + 1].toInt()
val right = input[i + 3].toInt()
for (j in i downTo 0) {
if (isNumber(input[j])) {
input[j] = (input[j].toInt() + left).toString()
break
}
}
for (j in i + 4 until size) {
if (isNumber(input[j])) {
input[j] = (input[j].toInt() + right).toString()
break
}
}
input[i] = "0"
// wut
input.removeAt(i + 1)
input.removeAt(i + 1)
input.removeAt(i + 1)
input.removeAt(i + 1)
return true
}
}
}
if (lex == "]") balance--
i++
}
return false
}
fun split(input: ArrayDeque<String>): Boolean {
val size = input.size
var i = 0
while (i < size) {
val lex = input[i]
if (isNumber(lex) && lex.toInt() >= 10) {
val lexVal = lex.toInt()
input[i] = "["
// wut #2
input.add(i + 1, "]")
input.add(i + 1, ((lexVal + 1) / 2).toString())
input.add(i + 1, ",")
input.add(i + 1, (lexVal / 2).toString())
return true
}
i++
}
return false
}
fun calculate(numbers: List<String>): ArrayDeque<String> {
return numbers.drop(1).fold(lexemize(numbers[0])) { lexems, s ->
lexems.addFirst("[")
lexems.addLast(",")
lexems.addAll(lexemize(s))
lexems.addLast("]")
reduce(lexems)
}
}
fun findMagnitude(lex: ArrayDeque<String>): Int {
val numbers = ArrayDeque<Int>()
for (i in lex.indices) {
val curLex = lex[i]
if (isNumber(curLex)) {
numbers.add(curLex.toInt())
}
if (curLex == "]") {
numbers.add(2 * numbers.removeLast() + 3 * numbers.removeLast())
}
}
return numbers.removeLast()
}
fun findLargestMagnitude(numbers: List<String>): Int {
return numbers.orderedPairs().maxOf { pair ->
findMagnitude(reduce(lexemize("[${pair.first},${pair.second}]")))
}
}
fun main() {
println(findMagnitude(calculate(numbers)))
println(findLargestMagnitude(numbers))
}
fun isNumber(s: String): Boolean = s[0].isDigit() | 0 | Kotlin | 0 | 0 | ef4b05d39d70a204be2433d203e11c7ebed04cec | 3,748 | advent-of-code-2021 | Apache License 2.0 |
src/Day04/Day04.kt | suttonle24 | 573,260,518 | false | {"Kotlin": 26321} | package Day04
import readInput
fun main() {
fun part1(input: List<String>): Int {
var fullContainments = 0;
val itr = input.listIterator();
itr.forEach {
var leftStr = "";
var leftLow = 0;
var leftHigh = 0;
var rightStr = "";
var rightLow = 0;
var rightHigh = 0;
leftStr = it.substring(0, it.indexOf(','));
rightStr = it.substring(it.indexOf(',') + 1, it.length);
leftLow = leftStr.substring(0, leftStr.indexOf('-')).toInt();
leftHigh = leftStr.substring(leftStr.indexOf('-') + 1, leftStr.length).toInt();
rightLow = rightStr.substring(0, rightStr.indexOf('-')).toInt();
rightHigh = rightStr.substring(rightStr.indexOf('-') + 1, rightStr.length).toInt();
if (leftLow <= rightLow && leftHigh >= rightHigh) {
fullContainments++;
} else if (leftLow >= rightLow && leftHigh <= rightHigh) {
fullContainments++;
}
}
println("Total full containments: $fullContainments");
return input.size
}
fun part2(input: List<String>): Int {
var overlaps = 0;
val itr = input.listIterator();
itr.forEach {
var leftStr = "";
var leftLow = 0;
var leftHigh = 0;
var rightStr = "";
var rightLow = 0;
var rightHigh = 0;
leftStr = it.substring(0, it.indexOf(','));
rightStr = it.substring(it.indexOf(',') + 1, it.length);
leftLow = leftStr.substring(0, leftStr.indexOf('-')).toInt();
leftHigh = leftStr.substring(leftStr.indexOf('-') + 1, leftStr.length).toInt();
rightLow = rightStr.substring(0, rightStr.indexOf('-')).toInt();
rightHigh = rightStr.substring(rightStr.indexOf('-') + 1, rightStr.length).toInt();
if (leftLow <= rightLow && leftHigh >= rightHigh) {
overlaps++;
} else if (leftLow >= rightLow && leftHigh <= rightHigh) {
overlaps++;
} else if (leftLow in rightLow..rightHigh) {
overlaps++;
} else if (leftHigh in rightLow .. rightHigh) {
overlaps++;
}
}
println("Total overlaps: $overlaps");
return input.size
}
val input = readInput("Day04/Day04")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 039903c7019413d13368a224fd402625023d6f54 | 2,511 | AoC-2022-Kotlin | Apache License 2.0 |
src/main/kotlin/d3/D3_1.kt | MTender | 734,007,442 | false | {"Kotlin": 108628} | package d3
import input.Input
fun sumOfLine(lines: List<String>, lineIndex: Int): Int {
val line = lines[lineIndex]
var sum = 0
var i = 0
while (i < line.length) {
val c = line[i]
if (!c.isDigit()) {
i++
continue
}
val numberStartIndex = i
while (i < line.length && line[i].isDigit()) i++
val numberEndIndex = i - 1
if (checkForSymbol(lines, lineIndex, numberStartIndex, numberEndIndex)) {
val numberValue = line.substring(numberStartIndex, numberEndIndex + 1).toInt()
sum += numberValue
}
i++
}
return sum
}
fun checkForSymbol(lines: List<String>, lineIndex: Int, startIndex: Int, endIndex: Int): Boolean {
val line = lines[lineIndex]
if (startIndex > 0 && isSymbol(line[startIndex - 1])) return true
if (endIndex < line.length - 1 && isSymbol(line[endIndex + 1])) return true
if (lineIndex > 0) {
val previousLine = lines[lineIndex - 1]
if (startIndex > 0 && isSymbol(previousLine[startIndex - 1])) return true
if (containsSymbol(previousLine.substring(startIndex, endIndex + 1))) return true
if (endIndex < previousLine.length - 1 && isSymbol(previousLine[endIndex + 1])) return true
}
if (lineIndex < lines.size - 1) {
val nextLine = lines[lineIndex + 1]
if (startIndex > 0 && isSymbol(nextLine[startIndex - 1])) return true
if (containsSymbol(nextLine.substring(startIndex, endIndex + 1))) return true
if (endIndex < nextLine.length - 1 && isSymbol(nextLine[endIndex + 1])) return true
}
return false
}
fun containsSymbol(s: String): Boolean {
return s.any { isSymbol(it) }
}
fun isSymbol(c: Char): Boolean {
return c != '.'
}
fun main() {
val lines = Input.read("input.txt")
println(lines.indices.sumOf { sumOfLine(lines, it) })
} | 0 | Kotlin | 0 | 0 | a6eec4168b4a98b73d4496c9d610854a0165dbeb | 1,910 | aoc2023-kotlin | MIT License |
codeforces/kotlinheroes8/h.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 den = 1_000_000.toModular()
val (n, wid, hei) = readInts()
val (pSlash, pBackslash) = List(2) { Array(wid + hei + 1) { 1.toModular() } } // prob of being free
val (vertical, horizontal) = listOf(wid, hei).map { s -> BooleanArray(s + 1).also { it[0] = true; it[s] = true } }
repeat(n) {
val (x, y, pIn) = readInts()
val p = 1 - pIn / den
vertical[x] = true; horizontal[y] = true
pBackslash[x + y] *= p; pSlash[x - y + hei] *= p
}
val vertices = (wid + 1) * (hei + 1) + wid * hei
val edgesInitial = vertical.count { it } * hei + horizontal.count { it } * wid
var ans = (1 - vertices + edgesInitial).toModular()
for (x in 0..wid) for (y in 0..hei) {
if (!vertical[x] && !horizontal[y]) ans += pBackslash[x + y] * pSlash[x - y + hei]
if (x < wid && y < hei) ans += pBackslash[x + y + 1] * pSlash[x - y + hei]
if (x + 1 <= wid && y - 1 >= 0) ans += 2 * (1 - pBackslash[x + y])
if (x + 1 <= wid && y + 1 <= hei) ans += 2 * (1 - pSlash[x - y + hei])
}
println(ans)
}
private fun Int.toModular() = Modular(this)//toDouble()
private class Modular {
companion object {
const val M = 998244353
}
val x: Int
@Suppress("ConvertSecondaryConstructorToPrimary")
constructor(value: Int) { x = (value % M).let { if (it < 0) it + M else it } }
operator fun plus(that: Modular) = Modular((x + that.x) % M)
operator fun minus(that: Modular) = Modular((x + M - that.x) % M)
operator fun times(that: Modular) = (x.toLong() * that.x % M).toInt().toModular()
private fun modInverse() = Modular(x.toBigInteger().modInverse(M.toBigInteger()).toInt())
operator fun div(that: Modular) = times(that.modInverse())
override fun toString() = x.toString()
}
private operator fun Int.plus(that: Modular) = Modular(this) + that
private operator fun Int.minus(that: Modular) = Modular(this) - that
private operator fun Int.times(that: Modular) = Modular(this) * that
private operator fun Int.div(that: Modular) = Modular(this) / that
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 2,133 | competitions | The Unlicense |
src/shreckye/coursera/algorithms/GraphParseUtils.kt | ShreckYe | 205,871,625 | false | {"Kotlin": 72136} | package shreckye.coursera.algorithms
import java.io.File
typealias VertexLabels = Pair<Int, IntArray>
fun readAdjacencyList(filename: String, initialCapacity: Int): List<VertexLabels> =
File(filename).useLines {
it.map {
val vertexLabelInts = it.splitToInts()
vertexLabelInts.first() to vertexLabelInts.drop(1).toIntArray()
}.toCollection(ArrayList(initialCapacity))
}
data class EdgeData(val vertex1Label: Int, val vertex2Label: Int)
data class WeightedEdgeData(val vertex1Label: Int, val vertex2Label: Int, val weight: Int)
fun String.splitToEdgeData(): EdgeData {
val lineInts = splitToInts()
return EdgeData(lineInts[0], lineInts[1])
}
fun String.splitToWeightedEdgeData(): WeightedEdgeData {
val lineInts = splitToInts()
return WeightedEdgeData(lineInts[0], lineInts[1], lineInts[2])
}
fun readUndirectedGraphVerticesArrayListSimplifiedEdgesFromEdges(
filename: String, indexLabelOffset: Int
): Triple<Int, Int, VerticesArrayListSimplifiedEdges> {
File(filename).bufferedReader().use {
val (numNodes, numEdges) = it.readLine().splitToInts()
val verticesEdges = VerticesArrayListSimplifiedEdges(numNodes) { ArrayList() }
it.forEachLine {
val weighetdEdgeData = it.splitToWeightedEdgeData()
val vertex1 = weighetdEdgeData.vertex1Label - indexLabelOffset
val vertex2 = weighetdEdgeData.vertex2Label - indexLabelOffset
val cost = weighetdEdgeData.weight
verticesEdges[vertex1].add(WeightedSimplifiedEdge(vertex2, cost))
verticesEdges[vertex2].add(WeightedSimplifiedEdge(vertex1, cost))
}
return Triple(numNodes, numEdges, verticesEdges)
}
}
fun readDirectedGraphVerticesArrayListSimplifiedEdgesAndInverseFromEdges(
filename: String, indexLabelOffset: Int
): Triple<Int, Int, Pair<VerticesArrayListSimplifiedEdges, VerticesArrayListSimplifiedEdges>> {
File(filename).bufferedReader().use {
val (numNodes, numEdges) = it.readLine().splitToInts()
val verticesEdges = VerticesArrayListSimplifiedEdges(numNodes) { ArrayList() }
val inverseGraphVerticesEdges = VerticesArrayListSimplifiedEdges(numNodes) { ArrayList() }
it.forEachLine {
val weighetdEdgeData = it.splitToWeightedEdgeData()
val vertex1 = weighetdEdgeData.vertex1Label - indexLabelOffset
val vertex2 = weighetdEdgeData.vertex2Label - indexLabelOffset
val cost = weighetdEdgeData.weight
verticesEdges[vertex1].add(WeightedSimplifiedEdge(vertex2, cost))
inverseGraphVerticesEdges[vertex2].add(WeightedSimplifiedEdge(vertex1, cost))
}
return Triple(numNodes, numEdges, verticesEdges to inverseGraphVerticesEdges)
}
} | 0 | Kotlin | 1 | 2 | 1746af789d016a26f3442f9bf47dc5ab10f49611 | 2,804 | coursera-stanford-algorithms-solutions-kotlin | MIT License |
day4/src/main/kotlin/day4/PlayedBingoBoard.kt | snv | 434,384,799 | false | {"Kotlin": 99328} | package day4
typealias Coordinate = Pair<Int, Int>
class PlayedBingoBoard(private val board: BingoBoard, private val drawnNumbers: DrawnNumbers){
val winsAfter: Int
private val lastCalledNumber: Int
val finalScore: Int
init {
val (winsAfter, withMarkedNumbers) = play()
this.winsAfter = winsAfter
lastCalledNumber = if (winsAfter < drawnNumbers.size) drawnNumbers[winsAfter] else drawnNumbers.last()
finalScore = lastCalledNumber *
board
.foldIndexed(0) { rowNr, totalScore, row ->
totalScore +
row.filterIndexed { colNr, _ ->
!withMarkedNumbers.positions.contains(Pair(rowNr, colNr))
}
.sum()
}
}
private fun play() = drawnNumbers.foldIndexed(
Pair(Int.MAX_VALUE, MarkedNumbers(setOf()))
) { turn, (earleastWin, markedNumbers), currentDrawnNr ->
if (earleastWin < turn) Pair(earleastWin, markedNumbers)
else {
val currentMarking = MarkedNumbers(markedNumbers.positions + board.find(currentDrawnNr))
if (currentMarking.hasWon()) Pair(turn, currentMarking)
else Pair(earleastWin, currentMarking)
}
}
}
private fun BingoBoard.find(number: Int) = foldIndexed(setOf<Coordinate>()){
rowNr, foundCoords, currentRow ->
foundCoords
.plus(
currentRow
.findPositionsInRow(number)
.map { Coordinate(rowNr, it) }
)
}
private fun List<Int>.findPositionsInRow(nr : Int) = foldIndexed(setOf<Int>()){
colNr, foundPositions, currentNr -> if (currentNr == nr) foundPositions + colNr else foundPositions
}
| 0 | Kotlin | 0 | 0 | 0a2d94f278defa13b52f37a938a156666314cd13 | 1,768 | adventOfCode21 | The Unlicense |
src/Day25.kt | kpilyugin | 572,573,503 | false | {"Kotlin": 60569} | fun main() {
fun Int.digitTo5() = when (this) {
3 -> "="
4 -> "-"
else -> toString()
}
fun Char.digitFrom5() = when (this) {
'-' -> -1
'=' -> -2
else -> this.digitToInt()
}
fun Long.to5(): String {
var res = ""
var cur = this
while (cur > 0) {
val digit = cur % 5
cur = if (digit in 0..2) cur / 5 else cur / 5 + 1
res += digit.toInt().digitTo5()
}
return res.reversed()
}
fun String.from5(): Long {
var res = 0L
var pow = 1L
for (ch in reversed()) {
res += ch.digitFrom5() * pow
pow *= 5
}
return res
}
fun part1(input: List<String>) = input.sumOf { it.from5() }.to5()
val testInput = readInputLines("Day25_test")
check(part1(testInput), "2=-1=0")
val input = readInputLines("Day25")
println(part1(input))
}
| 0 | Kotlin | 0 | 1 | 7f0cfc410c76b834a15275a7f6a164d887b2c316 | 954 | Advent-of-Code-2022 | Apache License 2.0 |
src/test/kotlin/icfp2019/TestUtils.kt | godaddy-icfp | 186,746,222 | false | {"JavaScript": 797310, "Kotlin": 116879, "CSS": 9434, "HTML": 5859, "Shell": 70} | package icfp2019
import com.google.common.base.CharMatcher
import com.google.common.base.Splitter
import icfp2019.model.*
import org.junit.jupiter.api.Assertions
import org.pcollections.PVector
import org.pcollections.TreePVector
import java.nio.file.Paths
fun String.toProblem(): Problem {
return parseTestMap(this)
}
fun String.toMultipleProblems(): List<Problem> {
val splitter = Splitter.on(CharMatcher.anyOf("-=")).omitEmptyStrings()
return splitter.splitToList(this).map { it.toProblem() }
}
fun String.toMultipleProblemsAndExpectations(): List<Pair<Problem, Problem>> {
return this.toMultipleProblems().windowed(size = 2, step = 2)
.map { (problem, expectation) -> problem to expectation }
}
fun GameState.toProblem(): Problem {
val nodes = this.board().map {
it.map { cell ->
val state = this.nodeState(cell.point)
Node(
cell.point,
isObstacle = cell.isObstacle,
isWrapped = state.isWrapped,
hasTeleporterPlanted = cell.hasTeleporterPlanted,
booster = state.booster
)
}
}
val grid = TreePVector.from<PVector<Node>>(nodes.map { TreePVector.from(it) })
return Problem(
name = "result",
size = this.mapSize,
startingPosition = this.startingPoint,
map = grid
)
}
fun loadProblem(problemNumber: Int): String {
val path = Paths.get("problems/prob-${problemNumber.toString().padStart(3, padChar = '0')}.desc").toAbsolutePath()
return path.toFile().readText()
}
fun boardString(problem: Problem, path: Set<Point> = setOf()): String =
boardString(problem.map, problem.size, problem.startingPosition, path)
fun boardString(cells: List<List<Node>>, size: MapSize, startingPosition: Point, path: Set<Point> = setOf()): String {
val lines = mutableListOf<String>()
for (y in (size.y - 1) downTo 0) {
val row = boardRowString(size, cells, y, path, startingPosition)
lines.add(row)
}
return lines.joinToString(separator = "\n")
}
private fun boardRowString(
size: MapSize,
cells: List<List<Node>>,
y: Int,
path: Set<Point>,
startingPosition: Point
): String {
return (0 until size.x).map { x ->
val node = cells[x][y]
when {
node.hasTeleporterPlanted -> '*'
node.point in path -> '|'
node.isWrapped -> 'w'
startingPosition == Point(x, y) -> '@'
node.isObstacle -> 'X'
node.booster != null -> 'o'
else -> '.'
}
}.joinToString(separator = " ")
}
fun boardComparisonString(
size: MapSize,
startingPosition: Point,
path: Set<Point> = setOf(),
left: List<List<Node>>,
right: List<List<Node>>
): String {
val lines = mutableListOf<String>()
for (y in (size.y - 1) downTo 0) {
val leftRow = boardRowString(size, left, y, path, startingPosition)
val rightRow = boardRowString(size, right, y, path, startingPosition)
lines.add(leftRow.padEnd(size.x * 2 + 5, ' ') + rightRow)
}
return lines.joinToString(separator = "\n")
}
fun printBoardComparison(expected: Problem, result: Problem, path: Set<Point> = setOf()) {
println("${expected.size}")
println("Expected".padEnd(expected.size.x*2 + 5, ' ') + "Result")
print(boardComparisonString(expected.size, expected.startingPosition, path, expected.map, result.map))
println()
}
fun GameState.assertEquals(expected: Problem) {
val result = this.toProblem()
if (expected.map != result.map) {
printBoardComparison(expected, result)
Assertions.fail<Any>("Boards are not equal")
}
}
fun printBoard(p: Problem, path: Set<Point> = setOf()) {
println("${p.size}")
print(boardString(p.map, p.size, p.startingPosition, path))
println()
}
fun printBoard(state: GameState, path: Set<Point> = setOf()) {
printBoard(state.toProblem(), path)
}
fun parseTestMap(map: String): Problem {
val mapLineSplitter = Splitter.on(CharMatcher.anyOf("\r\n")).omitEmptyStrings()
val lines = mapLineSplitter.splitToList(map)
.map { CharMatcher.whitespace().removeFrom(it) }
.filter { it.isBlank().not() }
.reversed()
val height = lines.size
val width = lines[0].length
if (lines.any { it.length != width }) throw IllegalArgumentException("Inconsistent map line lengths")
val startPoint =
(0 until width).map { x ->
(0 until height).map { y ->
if (lines[y][x] == '@') Point(x, y)
else null
}
}.flatten().find { it != null } ?: Point.origin()
return Problem("Test", MapSize(width, height), startPoint, TreePVector.from((0 until width).map { x ->
TreePVector.from((0 until height).map { y ->
val point = Point(x, y)
when (val char = lines[y][x]) {
'X' -> Node(point, isObstacle = true)
'w' -> Node(point, isObstacle = false, isWrapped = true)
'.' -> Node(point, isObstacle = false)
'@' -> Node(point, isObstacle = false)
'*' -> Node(point, isObstacle = false, hasTeleporterPlanted = true, isWrapped = true)
in Booster.parseChars -> Node(point, isObstacle = false, booster = Booster.fromChar(char))
else -> throw IllegalArgumentException("Unknown Char '$char'")
}
})
}))
}
| 13 | JavaScript | 12 | 0 | a1060c109dfaa244f3451f11812ba8228d192e7d | 5,485 | icfp-2019 | The Unlicense |
src/main/kotlin/q1_50/q11_20/Solution18.kt | korilin | 348,462,546 | false | null | package q1_50.q11_20
import java.util.*
/**
* https://leetcode-cn.com/problems/4sum
*/
class Solution18 {
fun fourSum(nums: IntArray, target: Int): List<List<Int>> {
val result = LinkedList<List<Int>>()
if(nums.size < 4) return result
nums.sort()
val n = nums.size
for (i1 in 0 until n - 3) {
if (i1 > 0 && nums[i1] == nums[i1 - 1]) continue
if (nums[i1] + nums[n - 1] + nums[n - 2] + nums[n - 3] < target) continue
if (nums[i1] + nums[i1 + 1] + nums[i1 + 2] + nums[i1 + 3] > target) break
for (i2 in i1 + 1 until n - 2) {
if (i2 > i1 + 1 && nums[i2] == nums[i2 - 1]) continue
if (nums[i1] + nums[i2] + nums[n - 1] + nums[n - 2] < target) continue
if (nums[i1] + nums[i2] + nums[i2 + 1] + nums[i2 + 2] > target) break
var i3 = i2 + 1
var i4 = n - 1
while (i3 < i4) {
if (i3 > i2 + 1 && nums[i3] == nums[i3 - 1]) {
i3++
continue
}
if (i4 < n - 1 && nums[i4] == nums[i4 + 1]) {
i4--
continue
}
when {
nums[i1] + nums[i2] + nums[i3] + nums[i4] < target -> i3++
nums[i1] + nums[i2] + nums[i3] + nums[i4] > target -> i4--
else -> result.add(listOf(nums[i1], nums[i2], nums[i3++], nums[i4]))
}
}
}
}
return result
}
} | 0 | Kotlin | 0 | 1 | 1ce05efeaf34536fff5fa6226bdcfd28247b2660 | 1,639 | leetcode_kt_solution | MIT License |
src/main/aoc2018/Day17.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2018
class Day17(input: List<String>, isGraph: Boolean = false) {
data class Pos(val x: Int, val y: Int)
private val area = mutableMapOf<Pos, Char>()
init {
if (isGraph) {
for (y in input.indices) {
for (x in input[0].indices) {
area[Pos(x, y)] = input[y][x]
}
}
} else {
input.forEach { line ->
val first = line.drop(2).substringBefore(",").toInt()
val second1 = line.substringAfterLast("=").substringBefore("..").toInt()
val second2 = line.substringAfterLast("..").toInt()
val ranges = mapOf(
line.first() to first..first,
line.substringAfter(", ").first() to second1..second2)
for (y in ranges.getValue('y')) {
for (x in ranges.getValue('x')) {
area[Pos(x, y)] = '#'
}
}
area[Pos(500, 0)] = '+'
}
}
}
fun printArea() {
for (y in area.keys.minByOrNull { it.y }!!.y..area.keys.maxByOrNull { it.y }!!.y) {
for (x in area.keys.minByOrNull { it.x }!!.x..area.keys.maxByOrNull { it.x }!!.x) {
print("${area.getOrDefault(Pos(x, y), '.')}")
}
println()
}
}
// Makes a straight column of | from the given position (not included) until it hits something
// else than air. Returns y position -1 if the water shouldn't continue flowing
private fun fall(from: Pos): Pos {
var currY = from.y
while (true) {
currY++
val content = area.getOrDefault(Pos(from.x, currY), '.')
if (currY > area.keys.maxByOrNull { it.y }!!.y) {
// Stop when it falls to infinity
return Pos(from.x, -1)
}
if (content == '|') {
// Don't continue falling if it hit other flowing water
return Pos(from.x, -1)
} else if (content == '#' || content == '~') {
// Stop falling and allow filling when it hit clay or water
return Pos(from.x, currY - 1)
}
area[Pos(from.x, currY)] = '|'
}
}
private fun fillDirection(from: Pos, direction: Int): List<Pos> {
var currX = from.x
var toSide = area.getOrDefault(Pos(currX + direction, from.y), '.')
var below = area.getOrDefault(Pos(currX, from.y + 1), '.')
while (listOf('.', '|').contains(toSide) && below != '.') {
currX += direction
area[Pos(currX, from.y)] = '~'
toSide = area.getOrDefault(Pos(currX + direction, from.y), '.')
below = area.getOrDefault(Pos(currX, from.y + 1), '.')
}
if (below == '.') {
return listOf(Pos(currX, from.y))
}
return listOf()
}
// Fill a container with ~ from the given starting point. Returns a list of
// all points where it overflows.
private fun fill(from: Pos): List<Pos> {
val overflows = mutableListOf<Pos>()
var currY = from.y
while (overflows.isEmpty()) {
// start position's column
area[Pos(from.x, currY)] = '~'
// to left and right of start position's column
listOf(-1, 1).forEach { direction -> overflows.addAll(fillDirection(Pos(from.x, currY), direction)) }
currY--
}
return overflows
}
// Converts all ~ to | in the overflowing row given that the overflow happened
// at the position 'from'. Returns 'from'
private fun overflow(from: Pos): Pos {
val direction = if (area[Pos(from.x + 1, from.y)] == '~') 1 else -1
var currX = from.x
var content = area.getOrDefault(Pos(currX, from.y), '.')
while (content == '~') {
area[Pos(currX, from.y)] = '|'
currX += direction
content = area.getOrDefault(Pos(currX, from.y), '.')
}
return from
}
private fun fillEverything() {
val toFall = mutableSetOf<Pos>()
toFall.add(area.filter { it.value == '+' }.keys.first())
while (toFall.isNotEmpty()) {
//println("$iter, toFall size: ${toFall.size}, ${toFall}")
//printArea()
val next = toFall.first()
toFall.remove(next)
val toFill = fall(next)
if (toFill.y != -1) {
val overflows = fill(toFill)
overflows.forEach { pos ->
overflow(pos)
toFall.add(pos)
}
}
}
}
fun solvePart1(): Int {
fillEverything()
val minY = area.filter { it.value == '#' }.minByOrNull { it.key.y }!!.key.y
return area.filter { it.key.y >= minY }.count { it.value == '|' || it.value == '~' }
}
fun solvePart2(): Int {
fillEverything()
return area.values.count { it == '~' }
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 5,095 | aoc | MIT License |
src/test/kotlin/Day15.kt | christof-vollrath | 317,635,262 | false | null | import io.kotest.core.spec.style.FunSpec
import io.kotest.data.forAll
import io.kotest.data.headers
import io.kotest.data.row
import io.kotest.data.table
import io.kotest.matchers.shouldBe
/*
--- Day 15: Rambunctious Recitation ---
See https://adventofcode.com/2020/day/15
*/
fun playMemGame(start: List<Int>): Sequence<Int> {
val nrPos = mutableMapOf<Int,Int>()
return sequence {
var recentNr: Int? = null
for (index in start.indices) {
val n = start[index]
if (recentNr != null) nrPos[recentNr] = index-1
recentNr = n
yield(n)
}
for (index in start.size until Int.MAX_VALUE) {
val foundPos = nrPos[recentNr]
val n = if (foundPos != null) {
index - foundPos - 1
} else 0
nrPos[recentNr!!] = index-1
recentNr = n
yield(n)
}
}
}
class Day15_Part1 : FunSpec({
context("play example game") {
val result = playMemGame(listOf(0, 3, 6))
val first2020 = result.take(2020).toList()
test("should generate the right values") {
first2020.take(10).toList() shouldBe listOf(0, 3, 6, 0, 3, 3, 1, 0, 4, 0)
}
test("should generate the right value at 2020") {
first2020.last() shouldBe 436
}
}
context("more examples") {
table(
headers("starting numbers", "expected"),
row(listOf(1,3,2), 1),
row(listOf(2,1,3), 10),
row(listOf(1,2,3), 27),
row(listOf(2,3,1), 78),
row(listOf(3,2,1), 438),
row(listOf(3,1,2), 1836),
).forAll { start, expected ->
val result = playMemGame(start)
result.drop(2019).first() shouldBe expected
}
}
})
class Day15_Part1_Exercise: FunSpec({
val solution = playMemGame(listOf(2,0,1,9,5,19)).drop(2019).first()
test("should have found solution") {
solution shouldBe 1009
}
})
class Day15_Part2 : FunSpec({
xcontext("longer examples") { // This will take 90s
table(
headers("starting numbers", "expected"),
row(listOf(0,3,6), 175594),
row(listOf(1,3,2), 2578),
row(listOf(2,1,3), 3544142),
row(listOf(1,2,3), 261214),
row(listOf(2,3,1), 6895259),
row(listOf(3,2,1), 18),
row(listOf(3,1,2), 362),
).forAll { start, expected ->
val result = playMemGame(start)
result.drop(30_000_000 - 1).first() shouldBe expected
}
}
})
class Day15_Part2_Exercise: FunSpec({
xcontext("part 2") {// will take 22s
val solution = playMemGame(listOf(2,0,1,9,5,19)).drop(30_000_000 - 1).first()
test("should have found solution") {
solution shouldBe 62714
}
}
})
| 1 | Kotlin | 0 | 0 | 8ad08350aa4bd1a29b7e18765fc7a2d6de8021e8 | 2,890 | advent_of_code_2020 | Apache License 2.0 |
src/main/kotlin/g1501_1600/s1589_maximum_sum_obtained_of_any_permutation/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1501_1600.s1589_maximum_sum_obtained_of_any_permutation
// #Medium #Array #Sorting #Greedy #Prefix_Sum
// #2023_06_14_Time_867_ms_(66.67%)_Space_81.6_MB_(66.67%)
class Solution {
fun maxSumRangeQuery(nums: IntArray, requests: Array<IntArray>): Int {
nums.sort()
val l = nums.size
val tempArr = IntArray(l)
// requests[i][0] incrementing index element by 1 and for requests[i][1]+1 decrementing by 1
// this will help me get the freq of occurrence of each index of array 'nums' in
// all 'requests' intervals when I compute the sum array of tempArr.
for (request in requests) {
val a = request[0]
val b = request[1] + 1
tempArr[a]++
if (b < l) {
tempArr[b]--
}
}
var prev = 0
for (i in 0 until l) {
tempArr[i] += prev
prev = tempArr[i]
}
tempArr.sort()
var index = l - 1
var ans: Long = 0
while (index >= 0) {
if (tempArr[index] == 0) {
break
}
val x = (tempArr[index] % 1000000007).toLong()
val y = (nums[index] % 1000000007).toLong()
index--
ans += x * y
}
return (ans % 1000000007).toInt()
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,339 | LeetCode-in-Kotlin | MIT License |
kotlin/src/commonMain/kotlin/y2015/Day2.kt | emmabritton | 358,239,150 | false | {"Rust": 18706, "Kotlin": 13302, "JavaScript": 8960} | package y2015
fun runY2015D2(input: String): Pair<String, String> {
val result = input.lines()
.map { parse(it) }
.map { calc(it) }
.reduce { acc, pair -> Pair(acc.first + pair.first, acc.second + pair.second) }
return Pair(result.first.toString(), result.second.toString())
}
private fun parse(input: String): List<Int> {
val list = input.split("x").mapNotNull { it.toIntOrNull() }
if (list.size == 3) {
return list
} else {
throw IllegalStateException("Invalid number of sides: $input")
}
}
private fun calc(input: List<Int>): Pair<Int, Int> {
val highest = input.maxOrNull()!!
val smallerSides = ArrayList(input).apply { remove(highest) }
val paper = (2 * input[0] * input[1]) + (2 * input[1] * input[2]) + (2 * input[0] * input[2]) + (smallerSides[0] * smallerSides[1])
val ribbon = (smallerSides[0] + smallerSides[0] + smallerSides[1] + smallerSides[1]) + (input[0] * input[1] * input[2])
return Pair(paper, ribbon)
} | 0 | Rust | 0 | 0 | c041d145c9ac23ce8d7d7f48e419143c73daebda | 1,011 | advent-of-code | MIT License |
2023/src/main/kotlin/org/suggs/adventofcode/Day04Scratchcards.kt | suggitpe | 321,028,552 | false | {"Kotlin": 156836} | package org.suggs.adventofcode
import org.slf4j.LoggerFactory
object Day04Scratchcards {
private val log = LoggerFactory.getLogger(this::class.java)
fun addTotalWinningCardsFrom(smallData: List<String>) =
calculateNumberOfWinningCardsFrom(smallData.mapIndexed { i, str -> Wins(i, intersectCountFrom(str), 1) })
.also { log.debug("Part 1: $it") }
fun sumPowerUpScoreForEachCardFrom(smallData: List<String>) =
smallData.fold(0) { sum, elem -> sum + addScoreForCard(elem) }
.also { log.debug("Part 2: $it") }
private fun calculateNumberOfWinningCardsFrom(wins: List<Wins>): Int {
wins.forEach { win -> incrementNextWins(wins, win.idx, win.wins, win.cardCount) }
return wins.sumOf { it.cardCount }
}
private fun incrementNextWins(wins: List<Wins>, idx: Int, number: Int, cardCount: Int) {
if (number == 0) return
wins[idx + number].cardCount += cardCount
incrementNextWins(wins, idx, number - 1, cardCount)
}
private fun addScoreForCard(card: String) =
powerUp(intersectCountFrom(card))
private fun intersectCountFrom(card: String): Int {
fun intersectCountFrom(cardLists: List<List<String>>) =
cardLists.first().toSet().intersect(cardLists.last().toSet()).count()
return intersectCountFrom(card.split(":").last().split("|").map { it.trim() }.map { it.split("\\s+".toRegex()) })
}
private fun powerUp(num: Int): Int {
return if (num <= 1) num
else 2 * powerUp(num - 1)
}
data class Wins(val idx: Int, val wins: Int, var cardCount: Int)
}
| 0 | Kotlin | 0 | 0 | 9485010cc0ca6e9dff447006d3414cf1709e279e | 1,631 | advent-of-code | Apache License 2.0 |
src/Day02.kt | EdoFanuel | 575,561,680 | false | {"Kotlin": 80963} | fun main() {
val rockPaperScissor = arrayOf(
intArrayOf(4, 8, 3),
intArrayOf(1, 5, 9),
intArrayOf(7, 2, 6)
)
val opponentCodex = arrayOf("A", "B", "C")
val yourCodex = arrayOf("X", "Y", "Z")
fun part1(input: List<String>): Int {
var score = 0
for (line in input) {
val (a, b) = line.split(" ")
score += rockPaperScissor[opponentCodex.indexOf(a)][yourCodex.indexOf(b)]
}
return score
}
fun part2(input: List<String>): Int {
var score = 0
for (line in input) {
val (a, b) = line.split(" ")
val opponent = opponentCodex.indexOf(a)
val you = yourCodex.indexOf(b) - 1
score += rockPaperScissor[opponent][(opponent + you + 3) % 3]
}
return score
}
val input = readInput("Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 46a776181e5c9ade0b5e88aa3c918f29b1659b4c | 927 | Advent-Of-Code-2022 | Apache License 2.0 |
day08/kotlin/RJPlog/day2308_1_2.kt | mr-kaffee | 720,687,812 | false | {"Rust": 223627, "Kotlin": 46100, "Python": 39390, "Shell": 3369, "Haskell": 3122, "Dockerfile": 2236, "Gnuplot": 1678, "C++": 980, "HTML": 592, "CMake": 314} | import java.io.File
import kotlin.math.*
fun wasteland(in1: Int): Int {
var lines = File("day2308_puzzle_input.txt").readLines()
var network = mutableMapOf<String, Pair<String, String>>()
var instructions = lines[0]
for (i in 2..lines.size - 1) {
network.put(
lines[i].substringBefore(" ="),
Pair(lines[i].substringAfter("(").substringBefore(","), lines[i].substringAfter(", ").substringBefore(")"))
)
}
var position = "AAA"
var count = 0
while (position != "ZZZ") {
var nextStep = instructions[count % instructions.length]
if (nextStep == 'R') {
position = network.getValue(position).second
} else {
position = network.getValue(position).first
}
count += 1
if (position.takeLast(1) == "Z") {
println("$position, $count")
}
}
return count
}
fun wasteland2(in1: Int): Long {
var lines = File("day2308_puzzle_input.txt").readLines()
var network = mutableMapOf<String, Pair<String, String>>()
var instructions = lines[0]
for (i in 2..lines.size - 1) {
network.put(
lines[i].substringBefore(" ="),
Pair(lines[i].substringAfter("(").substringBefore(","), lines[i].substringAfter(", ").substringBefore(")"))
)
}
var position = mutableListOf<String>()
network.forEach {
if(it.key.takeLast(1) == "A") {
position.add(it.key)
}
}
var count = 0L
var instructionLength = instructions.length.toLong()
println(position)
while (position.map {it.last()}.distinct().size != 1 || position.map {it.takeLast(1)}.distinct()[0] != "Z") {
var nextStep = instructions[(count % instructionLength).toInt()]
for (i in 0..position.size-1)
if (nextStep == 'R') {
position[i] = network.getValue(position[i]).second
} else {
position[i] = network.getValue(position[i]).first
}
count += 1L
//println("$nextStep: $position")
}
return count
}
fun main() {
var t1 = System.currentTimeMillis()
var solution1 = wasteland(1)
var solution2 = wasteland2(2)
//das läuft ewig. Wenn man nur jeweils einen Wert anschaut sieht man, dass man mit einem Eingangswert nur einen Ausgangswert erreicht, und das mit einer bestimmten Periode.
//Berechnet man daraus das kleinste gemeinsame Vielfache, bekommt man die richtige Lösung. Aber ist das zwingend bei allen Inputs so - theoretisch könnte es mehrere Zielpunkte
// geben mit unterschiedlichen Frequenzen und Offset? -> ich habe das hier nicht merh angepasst
//AAA GPA VDA GTA BBA VSA
//ZZZ CVZ STZ FPZ SKZ MKZ
//17287 13771 23147 20803 19631 17873 -> KgV = 18625484023687
// print solution for part 1
println("*******************************")
println("--- Day 8: Haunted Wasteland ---")
println("*******************************")
println("Solution for part1")
println(" $solution1 steps are required to reach ZZZ")
println()
// print solution for part 2
println("*******************************")
println("Solution for part2")
println(" $solution2 steps does it take before you're only on nodes that end with Z")
println()
t1 = System.currentTimeMillis() - t1
println("puzzle solved in ${t1} ms")
}
| 0 | Rust | 2 | 0 | 5cbd13d6bdcb2c8439879818a33867a99d58b02f | 3,071 | aoc-2023 | MIT License |
src/day05/Solution.kt | abhabongse | 576,594,038 | false | {"Kotlin": 63915} | /* Solution to Day 5: Supply Stacks
* https://adventofcode.com/2022/day/5
*/
package day05
import java.io.File
fun main() {
val fileName =
// "day05_sample.txt"
"day05_input.txt"
val (view, stackLabelOrder, rearrangeOps) = readInput(fileName)
// Part 1: rearrange crates by CrateMover 9000
val p1FinalView = simulateCrateMover9000(view, rearrangeOps)
val p1DesiredCrates = stackLabelOrder
.asSequence()
.map { p1FinalView[it]!!.last() }
.joinToString(separator = "")
println("Part 1: $p1DesiredCrates")
// Part 2: rearrange crates by CrateMover 9001
val p2FinalView = simulateCrateMover9001(view, rearrangeOps)
val p2DesiredCrates = stackLabelOrder
.asSequence()
.map { p2FinalView[it]!!.last() }
.joinToString(separator = "")
println("Part 2: $p2DesiredCrates")
}
/**
* Reads and parses input data according to the problem statement.
*/
fun readInput(fileName: String): Input {
val lines = File("inputs", fileName).readLines()
// Prepare crate stacking data
val crateStackingLineCount = lines
.asSequence()
.takeWhile { it.trim().isNotEmpty() }
.count()
val stackLabelLine = lines[crateStackingLineCount - 1]
val crateStackingLines = lines.subList(0, crateStackingLineCount - 1).reversed()
// Extract original crate stacking view
val view: View = hashMapOf()
val stackLabelOrder: ArrayList<Char> = ArrayList()
for ((col, stackLabel) in stackLabelLine.withIndex()) {
if (!stackLabel.isDigit()) {
continue
}
view[stackLabel] = crateStackingLines
.map { it[col] }
.takeWhile { it.isLetter() }
.toCollection(ArrayDeque())
stackLabelOrder.add(stackLabel)
}
// Extract rearrangement operations
val rearrangeOps = lines
.subList(crateStackingLineCount, lines.size)
.dropWhile { it.trim().isEmpty() }
.map { RearrangeOp from it }
.toList()
return Input(view, stackLabelOrder, rearrangeOps)
}
/**
* Represents data loaded from the input file.
*/
data class Input(val view: View, val stackLabelOrder: StackLabelOrder, val rearrangeOps: List<RearrangeOp>)
/**
* A list representing the original ordering of stack labels.
*/
typealias StackLabelOrder = List<Char>
/**
* A view representing the crate stacking configuration.
*/
typealias View = HashMap<Char, ArrayDeque<Char>>
/**
* Creates a deep copy of the view.
*/
fun View.copy(): View {
val view: View = hashMapOf()
this.entries.forEach {
view[it.key] = ArrayDeque(it.value)
}
return view
}
/**
* Simulates CrateMover 9000: moves one crate at a time.
* See problem statement for a thorough description of this machine.
*/
fun simulateCrateMover9000(originalView: View, rearrangeOps: List<RearrangeOp>): View {
val view: View = originalView.copy()
for (op in rearrangeOps) {
repeat(op.count) {
val crate = view[op.source]!!.removeLast()
view[op.dest]!!.addLast(crate)
}
}
return view
}
/**
* Simulates CrateMover 9001: moves multiple crates at once.
* See problem statement for a thorough description of this machine.
*/
fun simulateCrateMover9001(originalView: View, rearrangeOps: List<RearrangeOp>): View {
val view: View = originalView.copy()
val auxiliaryStack: ArrayDeque<Char> = ArrayDeque()
for (op in rearrangeOps) {
repeat(op.count) {
val crate = view[op.source]!!.removeLast()
auxiliaryStack.addLast(crate)
}
repeat(op.count) {
val crate = auxiliaryStack.removeLast()
view[op.dest]!!.addLast(crate)
}
}
return view
}
| 0 | Kotlin | 0 | 0 | 8a0aaa3b3c8974f7dab1e0ad4874cd3c38fe12eb | 3,774 | aoc2022-kotlin | Apache License 2.0 |
src/test/kotlin/io/noobymatze/aoc/y2022/Day18.kt | noobymatze | 572,677,383 | false | {"Kotlin": 90710} | package io.noobymatze.aoc.y2022
import io.noobymatze.aoc.Aoc
import io.noobymatze.aoc.Aoc.symmetricDifference
import kotlin.test.Test
class Day18 {
data class Pos(val x: Int, val y: Int, val z: Int) {
val sides get(): Set<Set<Pos>> {
val front = setOf(
this,
Pos(x + 1, y, z),
Pos(x, y + 1, z),
Pos(x + 1, y + 1, z),
)
val back = front.map { it.copy(z = it.z + 1) }.toSet()
val left = setOf(
this,
Pos(x, y, z + 1),
Pos(x, y + 1, z),
Pos(x, y + 1, z + 1),
)
val right = left.map { it.copy(x = it.x + 1) }.toSet()
val bottom = setOf(
this,
Pos(x + 1, y, z),
Pos(x, y, z + 1),
Pos(x + 1, y, z + 1),
)
val top = bottom.map { it.copy(y = it.y + 1) }.toSet()
return setOf(front, back, left, right, top, bottom)
}
}
@Test
fun test1() {
val result = Aoc.getInput(18)
.lineSequence()
.map { line -> line.split(",").map(String::toInt) }
.map { (x, y, z) -> Pos(x, y, z) }
// Idea: Build a set of all sides of a cube and compute
// the symmetric set difference
.map { it.sides }
.reduce { a, b -> a symmetricDifference b }
println(result.size)
}
@Test
fun test2() {
val example = """
|2,2,2
|1,2,2
|3,2,2
|2,1,2
|2,3,2
|2,2,1
|2,2,3
|2,2,4
|2,2,6
|1,2,5
|3,2,5
|2,1,5
|2,3,5
""".trimMargin()
val cubes = Aoc.getInput(18)
.lineSequence()
.map { line -> line.split(",").map(String::toInt) }
.map { (x, y, z) -> Pos(x, y, z) }
.toList()
val result = cubes.map { it.sides }.reduce { a, b -> a symmetricDifference b }
println(result.size)
}
} | 0 | Kotlin | 0 | 0 | da4b9d894acf04eb653dafb81a5ed3802a305901 | 2,144 | aoc | MIT License |
leetcode/src/offer/middle/Offer07.kt | zhangweizhe | 387,808,774 | false | null | package offer.middle
import linkedlist.TreeNode
fun main() {
// 剑指 Offer 07. 重建二叉树
// https://leetcode.cn/problems/zhong-jian-er-cha-shu-lcof/
val root = buildTree(intArrayOf(3,9,20,15,7), intArrayOf(9,3,15,20,7))
println(root?.`val`)
}
fun buildTree(preorder: IntArray, inorder: IntArray): TreeNode? {
return help(preorder, inorder, 0, 0, preorder.size - 1)
}
private fun help(
preorder: IntArray,
inorder: IntArray,
preorderRootIndex: Int,
inorderStartIndex: Int,
inorderEndIndex: Int): TreeNode? {
if (inorderStartIndex > inorderEndIndex || inorderStartIndex < 0 || inorderEndIndex >= preorder.size) {
return null
}
var inorderRootIndex = 0
val rootVal = preorder[preorderRootIndex]
for (i in inorderStartIndex .. inorderEndIndex) {
if (rootVal == inorder[i]) {
inorderRootIndex = i
break
}
}
val root = TreeNode(rootVal)
root.left = help(preorder, inorder, preorderRootIndex + 1, inorderStartIndex, inorderRootIndex - 1)
val leftChildrenCount = inorderRootIndex - inorderStartIndex
root.right = help(preorder, inorder, preorderRootIndex + leftChildrenCount + 1, inorderRootIndex + 1, inorderEndIndex)
return root
}
private fun helpReview(preorder: IntArray, inorder: IntArray, preorderRootIndex: Int, inorderStartIndex: Int, inorderEndIndex: Int): TreeNode? {
if (inorderStartIndex > inorderEndIndex || inorderStartIndex < 0 || inorderEndIndex >= preorder.size) {
return null
}
val rootValue = preorder[preorderRootIndex]
val root = TreeNode(rootValue)
var inorderRootIndex = 0
for (i in inorderStartIndex..inorderEndIndex) {
if (inorder[i] == rootValue) {
inorderRootIndex = i
break
}
}
// 左子树递归
root.left = helpReview(preorder, inorder, preorderRootIndex + 1, inorderStartIndex, inorderRootIndex-1)
// 右子树递归
val leftChildrenCount = inorderRootIndex - inorderStartIndex
root.right = helpReview(preorder, inorder, preorderRootIndex + leftChildrenCount + 1, inorderRootIndex + 1, inorderEndIndex)
return root
} | 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 2,211 | kotlin-study | MIT License |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions8.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.round1
import com.qiaoyuang.algorithm.round0.BinaryTreeNodeWithFather
fun test8() {
val a = BinaryTreeNodeWithFather('a')
val b = BinaryTreeNodeWithFather('b', a)
val c = BinaryTreeNodeWithFather('c', a)
val d = BinaryTreeNodeWithFather('d', b)
val e = BinaryTreeNodeWithFather('e', b)
val f = BinaryTreeNodeWithFather('f', c)
val g = BinaryTreeNodeWithFather('g', c)
val h = BinaryTreeNodeWithFather('h', e)
val i = BinaryTreeNodeWithFather('i', e)
a.left = b
a.right = c
b.left = d
b.right = e
c.left = f
c.right = g
e.left = h
e.right = i
fun printlnNext(node: BinaryTreeNodeWithFather<Char>) =
println("The element \"${node.value}\"'s next element in in-order is ${node.findInOrderNextElement()?.toString() ?: "null"}")
printlnNext(a)
printlnNext(b)
printlnNext(c)
printlnNext(d)
printlnNext(e)
printlnNext(f)
printlnNext(g)
printlnNext(h)
printlnNext(i)
}
/**
* Questions 8: Give you a binary node, find the node's next node in binary's in-order.
* The binary node has 3 points, left(point to left sub-node), right(point to right sub-node), father(point to father node)
*/
private fun BinaryTreeNodeWithFather<Char>.findInOrderNextElement(): Char? = father?.let {
right?.findFarLeftNode() ?: when {
it.left === this -> father!!.value
it.right === this -> father!!.findFatherThatLeftTree()
else -> throw IllegalArgumentException("This is a exceptional binary tree")
}
} ?: right?.findFarLeftNode()
private fun BinaryTreeNodeWithFather<Char>.findFarLeftNode(): Char = let {
var current = it
while (current.left != null) {
current = current.left!!
}
current.value
}
private fun BinaryTreeNodeWithFather<Char>.findFatherThatLeftTree(): Char? {
var current: BinaryTreeNodeWithFather<Char>? = this
while (current != null) {
if (current === current.father?.left)
return current.father!!.value
current = current.father
}
return null
}
| 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 2,088 | Algorithm | Apache License 2.0 |
src/test/kotlin/com/igorwojda/integer/factorial/Solution.kt | igorwojda | 159,511,104 | false | {"Kotlin": 254856} | package com.igorwojda.integer.factorial
// iterative solution
private object Solution1 {
private fun factorial(n: Int): Int {
var total = 1
(1..n).forEach {
total *= it
}
return total
}
}
// another iterative solution
private object Solution2 {
private fun factorial(n: Int): Int =
when (n) {
0 -> 1
else -> (n downTo 1).reduce { acc, it -> acc * it }
}
}
// recursive solution
private object Solution3 {
private fun factorial(n: Int): Int =
when (n) {
0, 1 -> 1
else -> n * factorial(n - 1)
}
}
// Tail-recursive solution
private object Solution4 {
private fun factorial(n: Int): Int {
fun fact(n: Int, acc: Int = 1): Int =
when (n) {
0, 1 -> acc
else -> fact(n - 1, acc * n)
}
return fact(n)
}
}
| 9 | Kotlin | 225 | 895 | b09b738846e9f30ad2e9716e4e1401e2724aeaec | 924 | kotlin-coding-challenges | MIT License |
src/main/kotlin/Day07.kt | gtruitt | 574,758,122 | false | {"Kotlin": 16663} | @file:Suppress("PackageDirectoryMismatch")
package day07
import head
import tail
const val TOKEN_SEP = " "
const val PROMPT = "$"
const val CD = "cd"
const val PATH_SEP = "/"
const val PREV_DIR = ".."
val filePattern = Regex("""\d+""")
val String.tokens get() = split(TOKEN_SEP)
val String.isCd get() = tokens.component1() == PROMPT && tokens.component2() == CD
val String.isFile get() = tokens.component1().matches(filePattern)
val String.fileSize get() = tokens.component1().toInt()
fun String.doCd(cmd: String) =
when (cmd.tokens.component3()) {
PREV_DIR -> split(PATH_SEP).dropLast(1).joinToString(PATH_SEP)
else -> split(PATH_SEP).plus(cmd.tokens.component3()).joinToString(PATH_SEP)
}
fun Map<String, Int>.addAtKey(key: String, value: Int) =
plus(key to getOrDefault(key, 0).plus(value))
tailrec fun readTerm(
lines: List<String>,
currentPath: String = "",
pathSizes: Map<String, Int> = emptyMap()
): Map<String, Int> {
val newPath = when (lines.head.isCd) {
true -> currentPath.doCd(lines.head)
false -> currentPath
}
return when {
lines.tail.isEmpty() -> pathSizes
lines.head.isCd -> readTerm(lines.tail, newPath, pathSizes.addAtKey(newPath, 0))
lines.head.isFile -> readTerm(lines.tail, newPath, pathSizes.addAtKey(newPath, lines.head.fileSize))
else -> readTerm(lines.tail, currentPath, pathSizes)
}
}
fun Map<String, Int>.rollUpDirectorySizes() =
keys.fold(this) { acc, key ->
acc.plus(key to acc.filter { it.key.startsWith(key) }.values.sum())
}
fun sumOfEligibleDirectories(terminalOutput: List<String>, maxSize: Int) =
readTerm(terminalOutput)
.rollUpDirectorySizes()
.filter { it.value <= maxSize }
.values
.sum()
const val DISK_SIZE = 70000000
const val SPACE_NEEDED = 30000000
fun sizeOfSmallestDirectory(terminalOutput: List<String>) =
readTerm(terminalOutput)
.rollUpDirectorySizes()
.let { dirSizes ->
val freeSpace = DISK_SIZE - dirSizes.values.max()
dirSizes.filter { freeSpace + it.value >= SPACE_NEEDED }.values.min()
}
| 0 | Kotlin | 0 | 2 | 1c9940faaf7508db275942feeb38d3e57aef413f | 2,164 | aoc-2022-kotlin | MIT License |
src/day09/Solution.kt | abhabongse | 576,594,038 | false | {"Kotlin": 63915} | /* Solution to Day 9: Rope Bridge
* https://adventofcode.com/2022/day/9
*/
package day09
import utils.accumulate
import java.io.File
fun main() {
val fileName =
// "day09_sample_a.txt"
// "day09_sample_b.txt"
"day09_input.txt"
val moveInstructions = readInput(fileName)
// Part 1: rope with 2 knots
val p1RopeStates = simulateAndTrackRope(Rope.atOrigin(2), moveInstructions)
val p1TailSpots = p1RopeStates.map { it.tail }.toSet().size
println("Part 1: $p1TailSpots")
// Part 2: rope with 10 knots
val p2RopeStates = simulateAndTrackRope(Rope.atOrigin(10), moveInstructions)
val p2TailSpots = p2RopeStates.map { it.tail }.toSet().size
println("Part 2: $p2TailSpots")
}
/**
* Reads and parses input data according to the problem statement.
*/
fun readInput(fileName: String): List<MoveInstruction> {
return File("inputs", fileName)
.readLines()
.map { MoveInstruction from it }
}
/**
* Simulates the experiment of moving the rope using the given instructions
* and tracks all possible rope states happened during the simulation.
*/
fun simulateAndTrackRope(initialRope: Rope, moveInstructions: List<MoveInstruction>): Sequence<Rope> =
moveInstructions
.asSequence()
.flatMap { it.iterator() }
.accumulate(initialRope) { currentState, direction -> currentState transitionBy direction }
| 0 | Kotlin | 0 | 0 | 8a0aaa3b3c8974f7dab1e0ad4874cd3c38fe12eb | 1,406 | aoc2022-kotlin | Apache License 2.0 |
src/main/kotlin/DumboOctopus_11.kt | Flame239 | 433,046,232 | false | {"Kotlin": 64209} | fun getEnergyLevels(): Array<IntArray> {
val lists: List<List<Int>> = readFile("DumboOctopus").split("\n").map { it.map { c -> c.digitToInt() } }
return Array(lists.size) { i -> IntArray(lists[i].size) { j -> lists[i][j] } }
}
fun countFlashes(): Int {
val energyLevels = getEnergyLevels()
var totalFlashes = 0
val h = energyLevels.size
val w = energyLevels[0].size
repeat(100) {
val flashed = Array(h) { BooleanArray(w) }
for (i in 0 until h) {
for (j in 0 until w) {
incrementRecursively(energyLevels, flashed, i, j)
}
}
totalFlashes += flashed.sumOf { arr -> arr.count { it } }
}
return totalFlashes
}
fun firstSynchronousFlashStep(): Int {
val energyLevels = getEnergyLevels()
val h = energyLevels.size
val w = energyLevels[0].size
for (step in 1 until Integer.MAX_VALUE) {
val flashed = Array(h) { BooleanArray(w) }
for (i in 0 until h) {
for (j in 0 until w) {
incrementRecursively(energyLevels, flashed, i, j)
}
}
if (flashed.all { arr -> arr.all { it } }) {
return step
}
}
return -1
}
fun incrementRecursively(energyLevels: Array<IntArray>, flashed: Array<BooleanArray>, i: Int, j: Int) {
val outOfBounds = outOfBounds(i, j, energyLevels.size, energyLevels[0].size)
if (outOfBounds || flashed[i][j]) {
return
}
energyLevels[i][j]++
if (energyLevels[i][j] <= 9) {
return
}
flashed[i][j] = true
energyLevels[i][j] = 0
for (di in -1..1) {
for (dj in -1..1) {
incrementRecursively(energyLevels, flashed, i + di, j + dj)
}
}
}
fun outOfBounds(i: Int, j: Int, maxI: Int, maxJ: Int) = i < 0 || i >= maxI || j < 0 || j >= maxJ
fun main() {
println(countFlashes())
println(firstSynchronousFlashStep())
} | 0 | Kotlin | 0 | 0 | ef4b05d39d70a204be2433d203e11c7ebed04cec | 1,928 | advent-of-code-2021 | Apache License 2.0 |
src/main/kotlin/day13/Solution.kt | TestaDiRapa | 573,066,811 | false | {"Kotlin": 50405} | package day13
import java.io.File
abstract class Node : Comparable<Node>
class IntNode(
val value: Int
): Node() {
override fun compareTo(other: Node): Int =
if (other is IntNode) this.value.compareTo(other.value)
else ListNode(listOf(this)).compareTo(other)
}
class ListNode(
val children: List<Node>
): Node() {
override fun compareTo(other: Node): Int =
if(other is IntNode) this.compareTo(ListNode(listOf(other)))
else {
if (this.children.isEmpty() && (other as ListNode).children.isEmpty()) 0
else if (this.children.isEmpty()) -1
else if ((other as ListNode).children.isEmpty()) 1
else if (this.children.first().compareTo(other.children.first()) == 0)
ListNode(this.children.drop(1)).compareTo(ListNode(other.children.drop(1)))
else this.children.first().compareTo(other.children.first())
}
}
//fun compareTrees(tree1: Node, tree2: Node): Int =
// if(tree1 is IntNode && tree2 is IntNode) tree1.value.compareTo(tree2.value)
// else if (tree1 is ListNode && tree2 is IntNode) compareTrees(tree1, ListNode(listOf(tree2)))
// else if (tree1 is IntNode && tree2 is ListNode) compareTrees(ListNode(listOf(tree1)), tree2)
// else {
// val l1 = tree1 as ListNode
// val l2 = tree2 as ListNode
// if (l1.children.isEmpty() && l2.children.isEmpty()) 0
// else if (l1.children.isEmpty()) -1
// else if (l2.children.isEmpty()) 1
// else if (compareTrees(l1.children.first(), l2.children.first()) == 0)
// compareTrees(ListNode(l1.children.drop(1)), ListNode(l2.children.drop(1)))
// else compareTrees(l1.children.first(), l2.children.first())
// }
tailrec fun parseListContent(rawContent: String, innerLists: List<Char> = emptyList(), parsed: List<String> = emptyList()): List<String> =
if (rawContent.isEmpty()) parsed
else if(rawContent.startsWith("[")) parseListContent(
rawContent.substring(1, rawContent.length),
innerLists + '[',
if (innerLists.isEmpty())
parsed + listOf("[")
else
parsed.dropLast(1) + listOf(parsed.last() + '[')
)
else if(innerLists.isEmpty() && rawContent.startsWith(",")) parseListContent(
rawContent.substring(1, rawContent.length),
innerLists,
parsed)
else if(innerLists.isEmpty() && rawContent.matches(Regex("^[0-9]+.*"))) parseListContent(
rawContent.replace(Regex("^[0-9]+"), ""),
innerLists,
parsed + listOf(Regex("^[0-9]+").find(rawContent)!!.value))
else if(rawContent.startsWith("]")) parseListContent(
rawContent.substring(1, rawContent.length),
innerLists.dropLast(1),
parsed.dropLast(1) + listOf(parsed.last() + "]"))
else parseListContent(
rawContent.substring(1, rawContent.length),
innerLists,
parsed.dropLast(1) + listOf(parsed.last() + rawContent[0]))
fun parseTree(rawString: String): Node =
if(rawString.first() == '[' && rawString.last() == ']') {
val rawParams = parseListContent(rawString.substring(1, rawString.length-1))
val nodes = rawParams.map { parseTree(it) }
ListNode(nodes)
} else if (rawString.matches(Regex("^[0-9]+$"))) IntNode(rawString.toInt())
else throw Exception("Invalid state")
fun parseInputFile() =
File("src/main/kotlin/day13/input.txt")
.readText()
.split(Regex("\r?\n"))
.filter{ it.isNotBlank() }
.fold(emptyList<Node>()) { acc, it ->
acc + parseTree(it)
}
fun findSumOfIndicesInRightOrder() =
parseInputFile()
.chunked(2)
.foldIndexed(0) { index, acc, it ->
if(it[0] < it[1]) acc + index + 1
else acc
}
fun findDecoderKey() =
parseInputFile().let{
val dividerStart = ListNode(listOf(ListNode(listOf(IntNode(2)))))
val dividerEnd = ListNode(listOf(ListNode(listOf(IntNode(6)))))
val sortedList = (it + listOf(dividerStart, dividerEnd)).sorted()
sortedList.foldIndexed(Pair(0, 0)) { index, acc, node ->
Pair(
index.takeIf { node.compareTo(dividerStart) == 0 } ?: acc.first,
index.takeIf { node.compareTo(dividerEnd) == 0 } ?: acc.second
)
}.let { p -> (p.first+1) * (p.second+1) }
}
fun main() {
println("The sum of the indices of the ordered pairs is ${findSumOfIndicesInRightOrder()}")
println("The decoder key for the distress signal is ${findDecoderKey()}")
} | 0 | Kotlin | 0 | 0 | b5b7ebff71cf55fcc26192628738862b6918c879 | 4,586 | advent-of-code-2022 | MIT License |
numbers/src/main/kotlin/mathtools/numbers/factors/CompareFactors.kt | RishiKumarRay | 467,793,819 | true | {"Kotlin": 182604, "Java": 53276} | package mathtools.numbers.factors
/** Functions for comparing factors of numbers
* @author DK96-OS : 2022 */
object CompareFactors {
/** Find the Greatest Common Divisor of two integers.
* @param n1 One of the integers to check
* @param n2 One of the integers to check
* @return The Greatest Common Divisor, or 1 if either number is zero */
fun gcd(
n1: Int,
n2: Int,
) : Int {
if (n1 == 0 || n2 == 0) return 1
if (n1 < 0) return gcd(-n1, n2)
if (n2 < 0) return gcd(n1, -n2)
if (n1 == 1 || n2 == 1) return 1
if (n1 == n2) return n1
return if (n1 < n2)
innerGCD(n2, n1)
else
innerGCD(n1, n2)
}
/** Assume both numbers are valid inputs, a is greater than b */
private fun innerGCD(a: Int, b: Int): Int {
val remainder = a % b
return if (remainder == 0)
b else innerGCD(b, remainder)
}
/** Find the Lowest Common Multiple of two integers.
* Ignores negative signs, will always return a positive value.
* @param n1 One of the integers to compare
* @param n2 One of the integers to compare
* @return The Lowest Common Multiple, or 1 if either number is zero */
fun lcm(
n1: Int,
n2: Int,
) : Long {
if (n1 == 0 || n2 == 0) return 1
if (n1 < 0) return lcm(-n1, n2)
if (n2 < 0) return lcm(n1, -n2)
return when {
n1 == 1 -> n2.toLong()
n2 == 1 || n1 == n2 -> n1.toLong()
else -> {
val gcd = if (n1 > n2)
innerGCD(n1, n2) else innerGCD(n2, n1)
return n1 * n2.toLong() / gcd
}
}
}
} | 0 | Kotlin | 0 | 0 | a7c4887a2ac37756b5a1c71265b6c006cf22ccb9 | 1,474 | MathTools | Apache License 2.0 |
src/main/kotlin/day17/Day17.kt | TheSench | 572,930,570 | false | {"Kotlin": 128505} | package day17
import day17.JetDirection.LEFT
import day17.JetDirection.RIGHT
import groupByBlanks
import runDay
import utils.RepeatingIterator
fun main() {
fun List<String>.simulate(num: Long) =
map {
it.map(JetDirection::fromChar)
}.map(::RepeatingIterator)
.first()
.let { jetDirections ->
val cave = Cave()
val rocks = RepeatingIterator(rockPattern)
val memoized = mutableMapOf<Long, Pair<Long, Long>>()
var i = 0L
val end = num
var heightOffset = 0L
while (i < end) {
i++
cave.addRock(rocks.next(), jetDirections)
val signature = cave.signature(rocks, jetDirections)
if (memoized.containsKey(signature)) {
val (prevI, prevSize) = memoized[signature]!!
val diffI = i - prevI
val diffSize = cave.fullSize - prevSize
val iterations = (end - i) / diffI
i += iterations * diffI
heightOffset = iterations * diffSize
break
}
memoized[signature] = i to cave.fullSize
}
while (i < end) {
cave.addRock(rocks.next(), jetDirections)
i++
}
cave.fullSize + heightOffset
}
fun part1(input: List<String>) = input.simulate(2_022L)
fun part2(input: List<String>) = input.simulate(1_000_000_000_000L)
(object {}).runDay(
part1 = ::part1,
part1Check = 3068L,
part2 = ::part2,
part2Check = 1514285714288L,
)
}
typealias Rock = List<IntRange>
typealias Rocks = RepeatingIterator<Rock>
typealias JetDirections = RepeatingIterator<JetDirection>
class Cave(
private val chamber: MutableList<MutableSet<Int>> = mutableListOf()
) : MutableList<MutableSet<Int>> by chamber {
val fullSize: Long get() = chamber.size.toLong()
private fun getTop8() = chamber.reversed().take(8).flatMap { row ->
(0..6).map {
row.contains(it)
}
}.fold(0L) { bits, next ->
bits * 2 + if (next) 1 else 0
}
fun signature(rocks: Rocks, jets: JetDirections): Long =
(getTop8() * rocks.size.toLong() +
rocks.current.toLong()) * jets.size.toLong() +
jets.current.toLong()
}
fun Cave.addRock(rock: Rock, jetDirections: JetDirections) {
val chamber = this
var y = this.size + 3
val width = rock.maxOf { it.last } + 1
var x = 2
fun tryMoveLeft(x: Int): Int {
if (x == 0) return 0
if ((rock.indices)
.filter { y + it < chamber.size }
.any { yToCheck ->
(rock[yToCheck].first + x - 1) in chamber[yToCheck + y]
}
) {
return x
}
return x - 1
}
fun tryMoveRight(x: Int): Int {
if (x + width == 7) return x
if ((rock.indices)
.filter { y + it < chamber.size }
.any { yToCheck ->
(rock[yToCheck].last + x + 1) in chamber[yToCheck + y]
}
) {
return x
}
return x + 1
}
fun Int.applyGravity(): Int {
val y = this
if (y > chamber.size) {
return y - 1
} else if (y == 0) {
return 0
} else if ((rock.indices)
.filter { y + it - 1 < chamber.size }
.any {
val yToCheck = y + it - 1
chamber[yToCheck].any { xC -> xC - x in rock[it] }
}
) {
return y
}
return y - 1
}
fun Int.applyJet(jet: JetDirection) = when (jet) {
LEFT -> tryMoveLeft(this)
RIGHT -> tryMoveRight(this)
}
while (true) {
x = x.applyJet(jetDirections.next())
val nextY = y.applyGravity()
if (nextY == y) {
break
}
y = nextY
}
rock.forEachIndexed { rockY, xs ->
val y = rockY + y
if (y >= chamber.size) {
chamber.add(mutableSetOf())
}
val row = chamber[y]
xs.forEach { xRock ->
row.add(x + xRock)
}
}
}
enum class JetDirection {
LEFT,
RIGHT;
companion object {
fun fromChar(char: Char) = when (char) {
'<' -> LEFT
'>' -> RIGHT
else -> throw IllegalArgumentException()
}
}
}
val rockPattern = """
####
.#.
###
.#.
..#
..#
###
#
#
#
#
##
##
""".trimIndent().toRocks()
fun String.toRocks() =
lines()
.groupByBlanks()
.map { it.toRock() }
fun List<String>.toRock(): Rock =
map { row ->
row.mapIndexedNotNull { i, char ->
when (char) {
'#' -> i
else -> null
}
}.let {
it.first()..it.last()
}
}.reversed()
| 0 | Kotlin | 0 | 0 | c3e421d75bc2cd7a4f55979fdfd317f08f6be4eb | 5,203 | advent-of-code-2022 | Apache License 2.0 |
2021/04/main.kt | chylex | 433,239,393 | false | null | import java.io.File
const val SIZE = 5
fun main() {
val lineIterator = File("input.txt").readLines().iterator()
val numbersToDraw = lineIterator.next().split(',').map(String::toInt).toList()
val boards = mutableListOf<Board>()
while (lineIterator.hasNext()) {
require(lineIterator.next().isEmpty())
if (!lineIterator.hasNext()) {
break
}
val numbers = Array(SIZE) {
lineIterator.next().split(' ').filter(String::isNotEmpty).map(String::toInt).toIntArray()
}
boards.add(Board(numbers))
}
part1(numbersToDraw, boards)
part2(numbersToDraw, boards)
}
class Board(private val numbers: Array<IntArray>) {
fun checkWin(drawnNumbers: Set<Int>): Boolean {
for (row in 0 until SIZE) {
if (numbers[row].all(drawnNumbers::contains)) {
return true
}
}
for (column in 0 until SIZE) {
if ((0 until SIZE).all { row -> numbers[row][column] in drawnNumbers }) {
return true
}
}
return false
}
fun getScore(drawnNumbers: Set<Int>, calledNumber: Int): Int {
return calledNumber * numbers.sumOf { it.filterNot(drawnNumbers::contains).sum() }
}
}
private fun part1(numbersToDraw: List<Int>, boards: List<Board>) {
val numbersLeftToDraw = ArrayDeque(numbersToDraw)
val drawnNumbers = mutableSetOf<Int>()
while (numbersLeftToDraw.isNotEmpty()) {
val calledNumber = numbersLeftToDraw.removeFirst()
drawnNumbers.add(calledNumber)
val winner = boards.firstOrNull { it.checkWin(drawnNumbers) }
if (winner != null) {
val score = winner.getScore(drawnNumbers, calledNumber)
println("Score of first board: $score")
return
}
}
}
private fun part2(numbersToDraw: List<Int>, boards: List<Board>) {
val numbersLeftToDraw = ArrayDeque(numbersToDraw)
val drawnNumbers = mutableSetOf<Int>()
val boardsLeft = boards.toMutableList()
while (numbersLeftToDraw.isNotEmpty()) {
val calledNumber = numbersLeftToDraw.removeFirst()
drawnNumbers.add(calledNumber)
while (true) {
val winner = boardsLeft.firstOrNull { it.checkWin(drawnNumbers) } ?: break
if (boardsLeft.size > 1) {
boardsLeft.remove(winner)
}
else {
val score = winner.getScore(drawnNumbers, calledNumber)
println("Score of last board: $score")
return
}
}
}
}
| 0 | Rust | 0 | 0 | 04e2c35138f59bee0a3edcb7acb31f66e8aa350f | 2,246 | Advent-of-Code | The Unlicense |
src/main/kotlin/g0301_0400/s0310_minimum_height_trees/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0301_0400.s0310_minimum_height_trees
// #Medium #Depth_First_Search #Breadth_First_Search #Graph #Topological_Sort
// #2022_11_09_Time_521_ms_(97.56%)_Space_64_MB_(90.24%)
class Solution {
fun findMinHeightTrees(n: Int, edges: Array<IntArray>): List<Int> {
if (n == 1) return mutableListOf(0)
val degrees = IntArray(n) { 0 }
val graph = buildGraph(degrees, n, edges)
val queue = ArrayDeque<Int>()
for ((idxNode, degree) in degrees.withIndex()) {
if (degree == 1) {
queue.addLast(idxNode)
}
}
var ans = mutableListOf<Int>()
while (queue.isNotEmpty()) {
val size = queue.size
val newLeaves = mutableListOf<Int>()
for (_sz in 0 until size) {
val cur = queue.removeFirst()
newLeaves.add(cur)
for (next in graph[cur]) {
if (--degrees[next] == 1) {
queue.addLast(next)
}
}
}
ans = newLeaves
}
return ans
}
private fun buildGraph(degrees: IntArray, n: Int, edges: Array<IntArray>): Array<ArrayList<Int>> {
val graph = Array(n) { arrayListOf<Int>() }
for (edge in edges) {
val (u, v) = edge
graph[u].add(v)
graph[v].add(u)
++degrees[u]
++degrees[v]
}
return graph
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,488 | LeetCode-in-Kotlin | MIT License |
advent-of-code-2023/src/main/kotlin/Day05.kt | jomartigcal | 433,713,130 | false | {"Kotlin": 72459} | // Day 05: If You Give A Seed A Fertilizer
// https://adventofcode.com/2023/day/5
import java.io.File
fun main() {
val lines = File("src/main/resources/Day05.txt").readLines()
val seeds = lines.first().substringAfter("seeds: ").split(" ").map {
it.toLong()
}
var index = 3
val seedToSoilList = lines.drop(index).takeWhile { it.isNotEmpty() }
index += seedToSoilList.size + 2
val soilToFertilizerList = lines.drop(index).takeWhile { it.isNotEmpty() }
index += soilToFertilizerList.size + 2
val fertilizerToWaterList = lines.drop(index).takeWhile { it.isNotEmpty() }
index += fertilizerToWaterList.size + 2
val waterToLightList = lines.drop(index).takeWhile { it.isNotEmpty() }
index += waterToLightList.size + 2
val lightToTempList = lines.drop(index).takeWhile { it.isNotEmpty() }
index += lightToTempList.size + 2
val tempToHumidityList = lines.drop(index).takeWhile { it.isNotEmpty() }
index += tempToHumidityList.size + 2
val humidityToLocList = lines.drop(index).takeWhile { it.isNotEmpty() }
val minLoc = seeds.minOf { seed ->
val soil = getDestinationFromList(seedToSoilList, seed)
val fertilizer = getDestinationFromList(soilToFertilizerList, soil)
val water = getDestinationFromList(fertilizerToWaterList, fertilizer)
val light = getDestinationFromList(waterToLightList, water)
val temp = getDestinationFromList(lightToTempList, light)
val humidity = getDestinationFromList(tempToHumidityList, temp)
getDestinationFromList(humidityToLocList, humidity)
}
println(minLoc)
}
private fun getDestinationFromList(list: List<String>, input: Long): Long {
val sourceToDestination = list.find { range ->
val (_, source, length) = range.split(" ").map { it.toLong() }
input in source..source + length
}
return if (sourceToDestination != null) {
val (destination, source, length) = sourceToDestination.split(" ").map { it.toLong() }
destination + (input - source)
} else {
input
}
}
| 0 | Kotlin | 0 | 0 | 6b0c4e61dc9df388383a894f5942c0b1fe41813f | 2,098 | advent-of-code | Apache License 2.0 |
src/day06/Day06.kt | maxmil | 578,287,889 | false | {"Kotlin": 32792} | package day06
import println
import readInputAsText
fun main() {
fun parse(input: String) = input.split(",").groupingBy { it.toInt() }.eachCount().mapValues { it.value.toLong() }
fun simulate(initial: Map<Int, Long>, days: Int): Map<Int, Long> {
val fish = initial.toMutableMap()
repeat(days) {
val reproducing = fish.getOrDefault(0, 0)
for (timer in 0..7) fish[timer] = fish.getOrDefault(timer + 1, 0)
fish[8] = reproducing
fish[6] = fish.getOrDefault(6, 0) + reproducing
}
return fish
}
fun part1(input: String) = simulate(parse(input), 80).values.sum()
fun part2(input: String) = simulate(parse(input), 256).values.sum()
val testInput = readInputAsText("day06/input_test")
check(part1(testInput) == 5934L)
check(part2(testInput) == 26984457539)
val input = readInputAsText("day06/input")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 246353788b1259ba11321d2b8079c044af2e211a | 970 | advent-of-code-2021 | Apache License 2.0 |
src/main/algorithms/searching/BinarySearchRecursive.kt | vamsitallapudi | 119,534,182 | false | {"Java": 24691, "Kotlin": 20452} | package main.algorithms.searching
fun main(args: Array<String>) {
val input = readLine()!!.trim().split(" ").map { it -> it.toInt() }.toIntArray() // to read an array (from user input)
val eleToSearch = readLine()!!.trim().toInt() // to read the element to be searched (from user input)
val pos = binarySearchRecursive(input, eleToSearch, 0, input.size -1)
if(pos >= 0 ) {
println(pos) // to print position at last
} else {
println("Position not found")
}
}
fun binarySearchRecursive(input: IntArray, eleToSearch: Int, low:Int, high:Int): Int {
while(low <=high) {
val mid = (low + high) /2
when {
eleToSearch > input[mid] -> return binarySearchRecursive(input, eleToSearch, mid+1, high) // element is greater than middle element of array, so it will be in right half. Recursion will call the right half again
eleToSearch < input[mid] -> return binarySearchRecursive(input, eleToSearch, low, mid-1) //element is less than middle element of array, so it will be in left half of the array. Recursion will call the left half again.
eleToSearch == input[mid] -> return mid // element found.
}
}
return -1
}
| 0 | Java | 1 | 1 | 9349fa7488fcabcb9c58ce5852d97996a9c4efd3 | 1,229 | HackerEarth | Apache License 2.0 |
src/main/kotlin/days/Day11.kt | andilau | 433,504,283 | false | {"Kotlin": 137815} | package days
@AdventOfCodePuzzle(
name = "<NAME>",
url = "https://adventofcode.com/2021/day/11",
date = Date(day = 11, year = 2021)
)
class Day11(val input: List<String>) : Puzzle {
private var dumbos = parseInput(input)
override fun partOne() =
flashCount(100)
override fun partTwo(): Int {
val dumbos = parseInput(input)
var cycle = 0
while (true) {
cycle++
cycle(dumbos)
if (dumbos.all { row -> row.all { it == 0 } }) {
break
}
}
return cycle
}
internal fun flashCount(generation: Int = 1): Int {
var flashCount = 0
repeat(generation) {
cycle(dumbos)
flashCount += dumbos.sumOf { row -> row.count { it == 0 } }
}
return flashCount
}
internal fun step(times: Int = 1): List<String> {
repeat(times) { cycle(dumbos) }
return dumbos.map { it.joinToString("") }
}
private fun cycle(dumbos: List<MutableList<Int>>) {
val flashed = mutableListOf<Point>()
dumbos.mapIndexed { y, row ->
row.indices.forEach { x ->
dumbos.set(y, x, flashed)
}
}
var count = 0
while (count < flashed.size) {
val point = flashed[count++]
point.neighbors().forEach { (x, y) ->
if (y in dumbos.indices && x in dumbos[y].indices) {
dumbos.set(y, x, flashed)
}
}
}
for (point in flashed) {
dumbos[point.y][point.x] = 0
}
}
private fun List<MutableList<Int>>.set(y: Int, x: Int, flashed: MutableList<Point>) {
this[y][x]++
if (this[y][x] == 10)
flashed.add(Point(x, y))
}
private fun parseInput(input: List<String>) =
input.map { line -> line.map { it.digitToInt() }.toMutableList() }
} | 0 | Kotlin | 0 | 0 | b3f06a73e7d9d207ee3051879b83e92b049a0304 | 1,961 | advent-of-code-2021 | Creative Commons Zero v1.0 Universal |
atcoder/arc158/e.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package atcoder.arc158
fun main() {
readLn()
val top = readInts()
val bottom = readInts()
val inf = Long.MAX_VALUE / 4
fun solve(from: Int, to: Int): Modular {
if (from + 1 == to) {
return (top[from] + bottom[from]).toModular() * 3.toModularUnsafe()
}
val mid = (from + to) / 2
var result = solve(from, mid) + solve(mid, to)
val (scoresLeft, scoresRight) = List(2) { mode ->
var bestUpTop = 0L
var bestUpBottom = inf
var bestDownTop = inf
var bestDownBottom = 0L
val range = if (mode == 1) mid until to else mid - 1 downTo from
val rSize = if (mode == 1) to - mid else mid - from
var scoresSum = 0.toModularUnsafe()
val improve = LongArray(rSize * 2)
var r = 0
for (i in range) {
val newBestUpTop = minOf(bestUpTop, bestUpBottom + bottom[i]) + top[i]
val newBestUpBottom = minOf(bestUpBottom, bestUpTop + top[i]) + bottom[i]
val newBestDownTop = minOf(bestDownTop, bestDownBottom + bottom[i]) + top[i]
val newBestDownBottom = minOf(bestDownBottom, bestDownTop + top[i]) + bottom[i]
scoresSum += (newBestUpTop + newBestUpBottom).toModular()
improve[r++] = - newBestDownTop + newBestUpTop
improve[r++] = - newBestDownBottom + newBestUpBottom
bestUpTop = newBestUpTop; bestUpBottom = newBestUpBottom
bestDownTop = newBestDownTop; bestDownBottom = newBestDownBottom
}
improve.sort()
scoresSum to improve
}
val s1 = scoresLeft.first
val s2 = scoresRight.first
val i1 = scoresLeft.second
val i2 = scoresRight.second
var sc = s1 * (i2.size).toModularUnsafe() + s2 * (i1.size).toModularUnsafe()
var j = i2.size
var sumJ = 0.toModularUnsafe()
for (i in i1.indices) {
while (j >= 1 && i1[i] + i2[j - 1] > 0) {
j--
sumJ += i2[j].toModular()
}
sc -= i1[i].toModular() * (i2.size - j).toModularUnsafe()
sc -= sumJ
}
result += sc * 2.toModularUnsafe()
return result
}
println(solve(0, top.size))
}
private val bufferedReader = java.io.BufferedReader(java.io.InputStreamReader(System.`in`))
private fun readLn() = bufferedReader.readLine()
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
private fun readLongs() = readStrings().map { it.toLong() }
private class Modular(val x: Int) {
companion object {
const val M = 998244353; val MOD_BIG_INTEGER = M.toBigInteger()
}
inline operator fun plus(that: Modular) = Modular((x + that.x).let { if (it >= M) it - M else it })
inline operator fun minus(that: Modular) = Modular((x - that.x).let { if (it < 0) it + M else it })
inline operator fun times(that: Modular) = Modular((x.toLong() * that.x % M).toInt())
inline operator fun div(that: Modular) = times(that.inverse())
inline fun inverse() = Modular(x.toBigInteger().modInverse(MOD_BIG_INTEGER).toInt())
override fun toString() = x.toString()
}
private fun Int.toModularUnsafe() = Modular(this)
private fun Int.toModular() = Modular(if (this >= 0) { if (this < Modular.M) this else this % Modular.M } else { Modular.M - 1 - inv() % Modular.M })
private fun Long.toModular() = Modular((if (this >= 0) { if (this < Modular.M) this else this % Modular.M } else { Modular.M - 1 - inv() % Modular.M }).toInt())
private fun java.math.BigInteger.toModular() = Modular(mod(Modular.MOD_BIG_INTEGER).toInt())
private fun String.toModular() = Modular(fold(0L) { acc, c -> (c - '0' + 10 * acc) % Modular.M }.toInt())
private class ModularArray(val data: IntArray) {
operator fun get(index: Int) = data[index].toModularUnsafe()
operator fun set(index: Int, value: Modular) { data[index] = value.x }
}
private inline fun ModularArray(n: Int, init: (Int) -> Modular) = ModularArray(IntArray(n) { init(it).x })
private val factorials = mutableListOf(1.toModularUnsafe())
private fun factorial(n: Int): Modular {
while (n >= factorials.size) factorials.add(factorials.last() * factorials.size.toModularUnsafe())
return factorials[n]
}
private fun cnk(n: Int, k: Int) = factorial(n) / factorial(k) / factorial(n - k)
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 4,040 | competitions | The Unlicense |
src/Day01.kt | BenD10 | 572,786,132 | false | {"Kotlin": 6791} | import java.lang.Integer.max
fun main() {
fun part1(input: List<String>): Int {
var currentMax = 0
var accumulator = 0
input.forEach {
if (it.isEmpty()) {
// Reached the end of this elf
currentMax = max(currentMax, accumulator)
accumulator = 0
} else {
accumulator += it.toInt()
}
}
return currentMax
}
fun part2(input: List<String>): Int {
val elfCalories = buildList<Int> {
var acc = 0
input.forEach {
if (it.isEmpty()) {
add(acc)
acc = 0
} else {
acc += it.toInt()
}
}
add(acc)
}.sortedDescending()
return elfCalories.take(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
val input = readInput("Day01")
println(part1(input))
check(part2(testInput) == 45000)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e26cd35ef64fcedc4c6e40b97a63d7c1332bb61f | 1,161 | advent-of-code | Apache License 2.0 |
day5/src/main/kotlin/com/lillicoder/adventofcode2023/day5/Day5.kt | lillicoder | 731,776,788 | false | {"Kotlin": 98872} | package com.lillicoder.adventofcode2023.day5
import kotlin.math.min
fun main() {
val day5 = Day5()
val almanac = AlmanacParser().parseFile("input.txt")
println("The lowest location number for all input single seed numbers is ${day5.part1(almanac)}.")
println("The lowest location number for all input seed number ranges is ${day5.part2(almanac)}.")
}
class Day5 {
fun part1(almanac: Almanac) = LowestLocationSearcher().searchSingle(almanac).min()
fun part2(almanac: Almanac) = LowestLocationSearcher().searchRanges(almanac)
}
/**
* Represents a seed almanac.
*/
data class Almanac(
val seeds: List<Long>,
val seedToSoil: List<Triple<Long, Long, Long>>,
val soilToFertilizer: List<Triple<Long, Long, Long>>,
val fertilizerToWater: List<Triple<Long, Long, Long>>,
val waterToLight: List<Triple<Long, Long, Long>>,
val lightToTemperature: List<Triple<Long, Long, Long>>,
val temperatureToHumidity: List<Triple<Long, Long, Long>>,
val humidityToLocation: List<Triple<Long, Long, Long>>,
)
class AlmanacParser {
/**
* Parses the raw almanac input to an equivalent [Almanac].
* @param raw Raw almanac input.
* @param separator Line separator for the given input.
* @return Almanac.
*/
fun parse(
raw: String,
separator: String = System.lineSeparator(),
): Almanac {
val sections = raw.split("$separator$separator")
// First section is seeds list
val seeds = parseSeeds(sections[0])
// Second section is seed-to-soil map
val seedToSoil = parseMap(sections[1], separator)
// Third section is soil-to-fertilizer map
val soilToFertilizer = parseMap(sections[2], separator)
// Fourth section is fertilizer-to-water map
val fertilizerToWater = parseMap(sections[3], separator)
// Fifth section is water-to-light map
val waterToLight = parseMap(sections[4], separator)
// Sixth section is light-to-temperature map
val lightToTemperature = parseMap(sections[5], separator)
// Seventh section is temperature-to-humidity map
val temperatureToHumidity = parseMap(sections[6], separator)
// Eight section is humidity-to-location map
val humidityToLocation = parseMap(sections[7], separator)
return Almanac(
seeds,
seedToSoil,
soilToFertilizer,
fertilizerToWater,
waterToLight,
lightToTemperature,
temperatureToHumidity,
humidityToLocation,
)
}
/**
* Parses the file with the given filename to an equivalent [Almanac].
* @param filename Filename.
* @return Almanac.
*/
fun parseFile(filename: String) =
parse(
javaClass.classLoader.getResourceAsStream(filename)!!.reader().readText(),
)
/**
* Parses the given section of almanac mappings to a list of triplets.
* @param section Map section to parse.
* @return Section map.
*/
private fun parseMap(
section: String,
separator: String,
) = section.substringAfter(":").split(separator).filter { it.isNotEmpty() }.map { line ->
val parts = line.split(" ").filter { it.isNotEmpty() }.map { it.toLong() }
Triple(parts[0], parts[1], parts[2])
}
/**
* Parses the list of seed numbers from the given input.
* @param section Seeds section to parse.
* @return Seed numbers.
*/
private fun parseSeeds(section: String) =
section.substringAfter(": ").split(" ").filter {
it.isNotEmpty()
}.map {
it.toLong()
}
}
/**
* Searcher that can find the lowest location numbers for one or more seed numbers.
*/
class LowestLocationSearcher {
/**
* Searches for the lowest location numbers for each seed number in the given [Almanac]'s seeds.
* @param almanac Almanac to search.
* @return List of lowest location numbers.
*/
fun searchSingle(almanac: Almanac) = almanac.seeds.map { findLowestLocation(it, almanac) }
/**
* Searches for the lowest location numbers for each seed number range in the given [Almanac]'s seeds.
* @param almanac Almanac to search.
* @return List of lowest location numbers.
*/
fun searchRanges(almanac: Almanac): Long {
var lowestLocationNumber = Long.MAX_VALUE
almanac.seeds.windowed(2, 2).forEach { pair ->
// First value is seed, second value is range
for (seed in pair.first()..(pair.sum())) {
lowestLocationNumber = min(lowestLocationNumber, findLowestLocation(seed, almanac))
}
}
return lowestLocationNumber
}
/**
* Finds the lowest eligible location number for the given seed number in
* the given [Almanac].
* @param seed Seed number.
* @param almanac Almanac to search.
* @return Lowest eligible location number.
*/
private fun findLowestLocation(
seed: Long,
almanac: Almanac,
): Long {
/**
* We need to hop from map to map until we get the final value from the [Almanac.humidityToLocation] map.
*/
val soil = findMatch(seed, almanac.seedToSoil)
val fertilizer = findMatch(soil, almanac.soilToFertilizer)
val water = findMatch(fertilizer, almanac.fertilizerToWater)
val light = findMatch(water, almanac.waterToLight)
val temperature = findMatch(light, almanac.lightToTemperature)
val humidity = findMatch(temperature, almanac.temperatureToHumidity)
return findMatch(humidity, almanac.humidityToLocation)
}
/**
* Finds the corresponding destination from the given mapping for the given source.
* @param source Source value.
* @param map Mapping of sources to destinations.
* @return Corresponding destination.
*/
private fun findMatch(
source: Long,
map: List<Triple<Long, Long, Long>>,
) = when (val mapping = map.find { source in it.second..(it.second + it.third) }) {
/**
* Each section has the following format:
*
* T destination U source range
*
* Example:
*
* seed-to-soil map:
* 2702707184 1771488746 32408643
*
* To determine if an arbitrary source is in a mapping:
*
* if (source is in [U, U + range]) { destination = source + (T - U) }
* else { destination = source }
*
* Procedure should be:
* 1) Determine which, if any, of the mappings has a range that contains the source
* 2) If (1), then compute the destination value using said range
* 3) If not (1), then the source is one-to-one with the destination, just return that value
*/
null -> source
else -> source + (mapping.first - mapping.second)
}
}
| 0 | Kotlin | 0 | 0 | 390f804a3da7e9d2e5747ef29299a6ad42c8d877 | 6,992 | advent-of-code-2023 | Apache License 2.0 |
classroom/src/main/kotlin/com/radix2/algorithms/extras/MinAvg.kt | rupeshsasne | 190,130,318 | false | {"Java": 66279, "Kotlin": 50290} | package com.radix2.algorithms.extras
import java.util.*
fun minimumAverage(orders: Sequence<Order>): Long {
val arrivalTimes = PriorityQueue<Order> { o1, o2 -> o1.arrivalTime.compareTo(o2.arrivalTime) }
val burstTimes = PriorityQueue<Order> { o1, o2 -> o1.burstTime.compareTo(o2.burstTime) }
for (order in orders) {
arrivalTimes.add(order)
}
var currentTime = 0L
var totalWaitTime = 0L
var numberOfOrdersServed = 0L
fun processOrder(order: Order) {
totalWaitTime += (currentTime - order.arrivalTime + order.burstTime)
currentTime += order.burstTime
numberOfOrdersServed++
}
fun enqueueOrders() {
while (!arrivalTimes.isEmpty() && arrivalTimes.peek().arrivalTime <= currentTime) {
burstTimes.add(arrivalTimes.poll())
}
}
while (!arrivalTimes.isEmpty()) {
var order = arrivalTimes.poll()
currentTime = if (burstTimes.isEmpty()) order.arrivalTime else currentTime + order.arrivalTime
processOrder(order)
enqueueOrders()
while (!burstTimes.isEmpty()) {
order = burstTimes.poll()
processOrder(order)
enqueueOrders()
}
}
return totalWaitTime / numberOfOrdersServed
}
data class Order(val arrivalTime: Long, val burstTime: Long)
fun main(args: Array<String>) {
val reader = System.`in`.bufferedReader()
val n = reader.readLine().trim().toInt()
val orders = Array<Order?>(n) { null }
for (ordersRowItr in 0 until n) {
val (arrivalTime, burstTime) = reader.readLine().split(" ").map { it.trim().toLong() }
orders[ordersRowItr] = Order(arrivalTime, burstTime)
}
val result = minimumAverage(orders.asSequence().filterNotNull())
println(result)
}
| 0 | Java | 0 | 1 | 341634c0da22e578d36f6b5c5f87443ba6e6b7bc | 1,798 | coursera-algorithms-part1 | Apache License 2.0 |
src/main/kotlin/com/jaspervanmerle/aoc2021/day/Day17.kt | jmerle | 434,010,865 | false | {"Kotlin": 60581} | package com.jaspervanmerle.aoc2021.day
import kotlin.math.max
class Day17 : Day("23005", "2040") {
private data class TargetArea(val horizontalRange: IntRange, val verticalRange: IntRange) {
fun contains(x: Int, y: Int): Boolean {
return x in horizontalRange && y in verticalRange
}
fun isOutOfReach(x: Int, y: Int): Boolean {
return x > horizontalRange.last || y < verticalRange.first
}
}
private val targetArea = parseTargetArea()
override fun solvePartOne(): Any {
return (0..1000)
.flatMap { velX ->
(0..1000).map { velY ->
simulate(velX, velY)
}
}
.filterNotNull()
.maxOf { it }
}
override fun solvePartTwo(): Any {
return (0..1000)
.flatMap { velX ->
(-1000..1000).map { velY ->
simulate(velX, velY)
}
}
.count { it != null }
}
private fun parseTargetArea(): TargetArea {
val inputNumbers = Regex("(-?\\d+)")
.findAll(input)
.map { it.groupValues[0].toInt() }
.toList()
return TargetArea(inputNumbers[0]..inputNumbers[1], inputNumbers[2]..inputNumbers[3])
}
private fun simulate(initialVelocityX: Int, initialVelocityY: Int): Int? {
var x = 0
var y = 0
var velX = initialVelocityX
var velY = initialVelocityY
var maxY = 0
while (!targetArea.isOutOfReach(x + velX, y + velY)) {
x += velX
y += velY
maxY = max(maxY, y)
if (velX < 0) {
velX++
} else if (velX > 0) {
velX--
}
velY--
}
return if (targetArea.contains(x, y)) maxY else null
}
}
| 0 | Kotlin | 0 | 0 | dcac2ac9121f9bfacf07b160e8bd03a7c6732e4e | 1,895 | advent-of-code-2021 | MIT License |
dcp_kotlin/src/main/kotlin/dcp/day201/day201.kt | sraaphorst | 182,330,159 | false | {"C++": 577416, "Kotlin": 231559, "Python": 132573, "Scala": 50468, "Java": 34742, "CMake": 2332, "C": 315} | package dcp.day201
// day201.kt
// By <NAME>
import kotlin.math.max
// The problem is really represented by an upper triangle of a matrix.
fun maximumWeightPath(lists: List<MutableList<Int>>): Int {
val errorMessage: (Int) -> String = { "row $it must have length ${it + 1}" }
if (lists.isEmpty())
return 0
if (lists.size == 1) {
require(lists[0].size == 1) { errorMessage(0) }
return lists[0][0]
}
// It makes more sense to start at the bottom of the triangle and work your way towards the top, as then
// you can do so in time O(n) and space O(1). We could do this functionally in space O(n), but we aim for
// efficiency in this particular solution.
// Skip the last row, as every node contains the value of the maximum path passing through that node.
for (row in lists.size-2 downTo 0) {
require(lists[row].size == row + 1) { errorMessage(row) }
for (col in lists[row].indices) {
// Calculate the maximum path weight passing through this node.
// It includes the weight of this node and the maximum path weight passing through one of its vertically
// adjacent nodes.
lists[row][col] = lists[row][col] + max(lists[row + 1][col], lists[row + 1][col + 1])
}
}
// Now the top number is the maximum weight path.
return lists[0][0]
}
| 0 | C++ | 1 | 0 | 5981e97106376186241f0fad81ee0e3a9b0270b5 | 1,398 | daily-coding-problem | MIT License |
src/main/java/me/olegthelilfix/leetcoding/old/FindMedianSortedArrays.kt | olegthelilfix | 300,408,727 | false | null | package me.olegthelilfix.leetcoding.old
/**
* Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
* The overall run time complexity should be O(log (m+n)).
*/
class FindMedianSortedArrays {
fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double {
val result = IntArray(nums1.size + nums2.size)
var i = 0
var j = 0
var index = 0
val s1 = nums1.size
val s2 = nums2.size
while (index < result.size) {
val n1 = if (s1 > i) nums1[i] else Int.MAX_VALUE
val n2 = if (s2 > j) nums2[j] else Int.MAX_VALUE
if(n1 < n2) {
result[index] = nums1[i]
i++
}
else {
result[index] = nums2[j]
j++
}
index++
}
return if ((result.size) % 2 != 0) {
result[(result.size) / 2].toDouble()
}
else {
(result[result.size/2] +result[result.size/2 - 1])/2.0
}
}
}
fun main() {
println(
FindMedianSortedArrays().findMedianSortedArrays(
listOf(1, 2).toIntArray(),
listOf(3, 4).toIntArray(),
))
}
| 0 | Kotlin | 0 | 0 | bf17d2f6915b7a491d93f57f8e7461adda7029c0 | 1,266 | MyKata | MIT License |
src/main/kotlin/g2201_2300/s2234_maximum_total_beauty_of_the_gardens/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2201_2300.s2234_maximum_total_beauty_of_the_gardens
// #Hard #Array #Sorting #Greedy #Binary_Search #Two_Pointers
// #2023_06_27_Time_699_ms_(100.00%)_Space_50.9_MB_(100.00%)
class Solution {
fun maximumBeauty(flowers: IntArray, newFlowers: Long, target: Int, full: Int, partial: Int): Long {
val n = flowers.size
val prefix = LongArray(n + 1)
flowers.sort()
for (i in 0 until n) {
prefix[i + 1] = prefix[i] + Math.min(flowers[i], target)
}
var res: Long = 0
var i = n - 1
for (c in 0..n) {
val remain = prefix[n] - prefix[n - c] + newFlowers - c * target.toLong()
var min: Long = 0
if (0 > remain) {
break
}
i = Math.min(i, n - c - 1)
while (0 <= i &&
(
target <= flowers[i] ||
flowers[i] * (i + 1).toLong() - prefix[i + 1] > remain
)
) {
i--
}
if (0 <= i) {
val dif = flowers[i] * (i + 1).toLong() - prefix[i + 1]
min = Math.min(target - 1L, flowers[i] + (remain - dif) / (i + 1))
if (i + 1 < n - c) {
min = Math.min(min, flowers[i + 1].toLong())
}
}
res = Math.max(res, c * full.toLong() + min * partial)
}
return res
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,464 | LeetCode-in-Kotlin | MIT License |
src/day08/Day08Util.kt | Longtainbin | 573,466,419 | false | {"Kotlin": 22711} | package day08
import kotlin.math.max
fun upLookMatrix(matrix: Array<IntArray>): Array<IntArray> {
val row = matrix.size
val col = matrix.first().size
val result = Array(row) { IntArray(col) }
for (j in 0 until col) {
result[0][j] = matrix[0][j]
var h = result[0][j]
for (i in 1 until row) {
result[i][j] = max(result[i - 1][j], h)
h = max(result[i][j],matrix[i][j])
}
}
return result
}
fun downLookMatrix(matrix: Array<IntArray>): Array<IntArray> {
val row = matrix.size
val col = matrix.first().size
val result = Array(row) { IntArray(col) }
for (j in 0 until col) {
result[row - 1][j] = matrix[row - 1][j]
var h = result[row - 1][j]
for (i in (row - 2) downTo 0) {
result[i][j] = max(result[i + 1][j], h)
h = max(result[i][j],matrix[i][j])
}
}
return result
}
fun leftLookMatrix(matrix: Array<IntArray>): Array<IntArray> {
val row = matrix.size
val col = matrix.first().size
val result = Array(row) { IntArray(col) }
for (i in 0 until row) {
result[i][0] = matrix[i][0]
var h = result[i][0]
for (j in 1 until col) {
result[i][j] = max(result[i][j - 1], h)
h = max(result[i][j],matrix[i][j])
}
}
return result
}
fun rightLookMatrix(matrix: Array<IntArray>): Array<IntArray> {
val row = matrix.size
val col = matrix.first().size
val result = Array(row) { IntArray(col) }
for (i in 0 until row) {
result[i][col - 1] = matrix[i][col - 1]
var h = result[i][col - 1]
for (j in (col - 2) downTo 0) {
result[i][j] = max(result[i][j + 1], h)
h = max(result[i][j],matrix[i][j])
}
}
return result
}
fun isOnEdge(matrix: Array<IntArray>, i: Int, j: Int): Boolean {
val row = matrix.size
val col = matrix.first().size
return i == 0 || j == 0 || i == row - 1 || j == col - 1
} | 0 | Kotlin | 0 | 0 | 48ef88b2e131ba2a5b17ab80a0bf6a641e46891b | 2,003 | advent-of-code-2022 | Apache License 2.0 |
src/day11.kt | skuhtic | 572,645,300 | false | {"Kotlin": 36109} | fun main() {
day11.execute(onlyTests = false, forceBothParts = true)
}
val day11 = object : Day<Long>(11, 10605, 2713310158) {
override val testInput: InputData
get() = TEST_INPUT.trimIndent().lines()
override fun part1(input: InputData): Long { // divisibleBys: [23, 19, 13, 17]
val monkeys = mutableListOf<Monkey>()
input.chunked(7).map { Monkey.fromLinesToGroup(it, monkeys) }
repeat(20) {
monkeys.forEach { it.turn() }
}
return monkeys.map { it.inspections }.sortedDescending().take(2).fold(1L) { acc, i -> acc * i }
}
override fun part2(input: InputData): Long { // divisibleBys: [2, 7, 13, 3, 19, 17, 11, 5]
val monkeys = mutableListOf<Monkey>()
input.chunked(7).map { Monkey.fromLinesToGroup(it, monkeys) }
val common = monkeys.fold(1) { acc, m -> acc * m.testDivBy }
monkeys.forEach { m ->
m.setReliefFunctionTo { it % common }
}
repeat(10_000) {
monkeys.forEach { it.turn() }
}
return monkeys.map { it.inspections }.sortedDescending().take(2).fold(1L) { acc, i -> acc * i }
}
}
private class Monkey private constructor(
val id: Int,
val operation: (Long) -> Long,
val monkeyGroup: List<Monkey>,
val testDivBy: Int,
val toIfTestTrue: Int,
val toIfTestFalse: Int,
initialItems: List<Long>
) {
private val items: ArrayDeque<Long> = ArrayDeque(initialItems)
override fun toString(): String = "Monkey$id ($inspections): $items"
var inspections: Int = 0
private set
fun add(item: Long) = items.addLast(item)
var relief: (Long) -> Long = { it / 3 }
private set
fun setReliefFunctionTo(reliefFunction: (Long) -> Long) {
relief = reliefFunction
}
fun turn() {
items.removeAll { i ->
val x = relief(operation(i))
inspections++
val to = if (x % testDivBy == 0L) toIfTestTrue else toIfTestFalse
monkeyGroup[to].add(x)
true
}
}
companion object {
fun fnSum(with: Long): (Long) -> Long = { it + with }
fun fnProduct(with: Long): (Long) -> Long = { it * with }
val fnSquare: (Long) -> Long = { it * it }
fun fromLinesToGroup(lines: InputData, monkeyGroup: MutableList<Monkey>): Monkey {
val l = if (lines.first().isEmpty()) lines.drop(1) else lines
require(l.size in 6..7)
val id = l[0].substringAfterLast("Monkey ").trimEnd(':').toInt()
val items = l[1].substringAfterLast("items: ").split(", ").map { it.toLong() }
val opDef = l[2].substringAfter("= old ")
val testDivBy = l[3].substringAfter("divisible by ").toInt()
val toIfTestTrue = l[4].substringAfter("true: throw to monkey ").toInt()
val toIfTestFalse = l[5].substringAfter("false: throw to monkey ").toInt()
val operation: (Long) -> Long = when {
opDef.startsWith('+') -> fnSum(opDef.substringAfter(' ').toLong())
opDef == "* old" -> fnSquare
opDef.startsWith('*') -> fnProduct(opDef.substringAfter(' ').toLong())
else -> error("Invalid input")
}
val monkey = Monkey(id, operation, monkeyGroup, testDivBy, toIfTestTrue, toIfTestFalse, items)
monkeyGroup.add(monkey)
return monkey
}
}
}
private const val TEST_INPUT = """
Monkey 0:
Starting items: 79, 98
Operation: new = old * 19
Test: divisible by 23
If true: throw to monkey 2
If false: throw to monkey 3
Monkey 1:
Starting items: 54, 65, 75, 74
Operation: new = old + 6
Test: divisible by 19
If true: throw to monkey 2
If false: throw to monkey 0
Monkey 2:
Starting items: 79, 60, 97
Operation: new = old * old
Test: divisible by 13
If true: throw to monkey 1
If false: throw to monkey 3
Monkey 3:
Starting items: 74
Operation: new = old + 3
Test: divisible by 17
If true: throw to monkey 0
If false: throw to monkey 1""" | 0 | Kotlin | 0 | 0 | 8de2933df90259cf53c9cb190624d1fb18566868 | 4,099 | aoc-2022 | Apache License 2.0 |
solutions/aockt/y2015/Y2015D20.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2015
import io.github.jadarma.aockt.core.Solution
object Y2015D20 : Solution {
/**
* Finds the first house to get enough presents from the infinite elves.
*
* @param target The minimum amount of gifts per house.
* @param giftsPerVisit How many gifts each elf visit adds to the house total.
* @param maxVisitsPerElf Elves will stop delivering after this many stops. A negative value means infinite visits.
* @return The number of the first house to have received at least [target] gifts, or -1 if not possible.
*/
private fun houseGifts(target: Int, giftsPerVisit: Int, maxVisitsPerElf: Int = -1): Int {
if (target <= 0 || giftsPerVisit <= 0) return -1
val maximumHouses = target / giftsPerVisit
fun maxHouseFor(elf: Int) = when {
maxVisitsPerElf < 0 -> maximumHouses
else -> minOf(maximumHouses, elf * maxVisitsPerElf + 1)
}
return IntArray(maximumHouses) { 0 }
.apply {
for (elf in 1 until maximumHouses) {
for (number in elf until maxHouseFor(elf) step elf) {
this[number] += elf * giftsPerVisit
}
}
}
.indexOfFirst { it >= target }
}
override fun partOne(input: String) = houseGifts(target = input.toInt(), giftsPerVisit = 10)
override fun partTwo(input: String) = houseGifts(target = input.toInt(), giftsPerVisit = 11, maxVisitsPerElf = 50)
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 1,519 | advent-of-code-kotlin-solutions | The Unlicense |
gcj/y2020/qual/c.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package gcj.y2020.qual
private fun solve(initials: String = "CJ", impossible: String = "IMPOSSIBLE"): String {
data class Activity(val start: Int, val end: Int, val id: Int)
val activities = List(readInt()) { val (start, end) = readInts(); Activity(start, end, it) }
val ans = IntArray(activities.size)
val free = IntArray(2)
activities.sortedBy { it.start }.forEach {
val who = free.indices.minByOrNull { i -> free[i] }!!
if (free[who] > it.start) return impossible
free[who] = it.end
ans[it.id] = who
}
return ans.map { initials[it] }.joinToString("")
}
fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 831 | competitions | The Unlicense |
src/main/kotlin/com/marcdenning/adventofcode/day05/Day05a.kt | marcdenning | 317,730,735 | false | {"Kotlin": 87536} | package com.marcdenning.adventofcode.day05
import java.io.File
import java.util.*
import java.util.regex.MatchResult
import java.util.stream.Stream
private const val NUMBER_OF_ROWS = 128
private const val NUMBER_OF_COLUMNS = 8
fun main(args: Array<String>) {
Scanner(File(args[0])).use { scanner ->
val maxSeatId = scanner.findAll("[BF]{7}[LR]{3}")
.map(::getSeatId)
.max { o1, o2 -> o1 - o2 }
.orElseThrow()
println("Max seat ID: $maxSeatId")
}
}
fun extractRow(seat: String) = seat.substring(0..6)
fun extractColumn(seat: String) = seat.substring(7..9)
fun determineRow(specifier: String, index: Int, lower: Int, upper: Int): Int {
if (index == specifier.length - 1) {
return if (specifier[index] == 'F') lower else upper
} else if (specifier[index] == 'F') {
return determineRow(specifier, index + 1, lower, lower + ((upper - lower) / 2))
} else {
return determineRow(specifier, index + 1, upper - ((upper - lower) / 2), upper)
}
}
fun determineColumn(specifier: String, index: Int, lower: Int, upper: Int): Int {
if (index == specifier.length - 1) {
return if (specifier[index] == 'L') lower else upper
} else if (specifier[index] == 'L') {
return determineColumn(specifier, index + 1, lower, lower + ((upper - lower) / 2))
} else {
return determineColumn(specifier, index + 1, upper - ((upper - lower) / 2), upper)
}
}
fun getSeatId(matchResult: MatchResult): Int {
val rowId = extractRow(matchResult.group())
val columnId = extractColumn(matchResult.group())
return 8 * determineRow(rowId, 0, 0, NUMBER_OF_ROWS - 1) +
determineColumn(columnId, 0, 0, NUMBER_OF_COLUMNS - 1)
}
| 0 | Kotlin | 0 | 0 | b227acb3876726e5eed3dcdbf6c73475cc86cbc1 | 1,755 | advent-of-code-2020 | MIT License |
aoc-2017/src/main/kotlin/nl/jstege/adventofcode/aoc2017/days/Day07.kt | JStege1206 | 92,714,900 | false | null | package nl.jstege.adventofcode.aoc2017.days
import nl.jstege.adventofcode.aoccommon.days.Day
import nl.jstege.adventofcode.aoccommon.utils.extensions.extractValues
/**
*
* @author <NAME>
*/
class Day07 : Day(title = "Recursive Circus") {
private companion object Configuration {
private const val INPUT_PATTERN_STRING = """(\w+) \((\d+)\)( -> ([\w, ]+))?"""
private val INPUT_REGEX = INPUT_PATTERN_STRING.toRegex()
private const val NAME_INDEX = 1
private const val WEIGHT_INDEX = 2
private const val NODES_INDEX = 4
private val PARAM_INDICES = intArrayOf(NAME_INDEX, WEIGHT_INDEX, NODES_INDEX)
}
override fun first(input: Sequence<String>): Any = input.findRoot().name
override fun second(input: Sequence<String>): Any = input.findRoot().findWrongWeight()
private fun Sequence<String>.findRoot(): Program {
val cache = mutableMapOf<String, Program>()
return this
.map { it.extractValues(INPUT_REGEX, *PARAM_INDICES) }
.map { (name, weight, nodes) ->
cache.getOrPut(name) { Program(name) }.apply {
this.weight = weight.toInt()
if (nodes.isNotBlank()) {
this.children += nodes
.split(", ").asSequence()
.map { cache.getOrPut(it) { Program(it) } }
.onEach { it.parent = this }
.toList()
}
}
}
.toList()
.first { it.parent == null }
}
private tailrec fun Program.findWrongWeight(): Int {
val groups = children.groupBy { it.totalWeight }
val wrongNode = groups.values.minBy { it.size }!!.first()
if (wrongNode.children.map { it.totalWeight }.toSet().size < 2) {
return groups.values.maxBy { it.size }!!.first()
.totalWeight - (wrongNode.totalWeight - wrongNode.weight)
}
return wrongNode.findWrongWeight()
}
private data class Program(
val name: String,
var weight: Int = 0,
var parent: Program? = null,
val children: MutableSet<Program> = mutableSetOf()
) {
val totalWeight: Int by lazy { weight + children.map { it.totalWeight }.sum() }
override fun equals(other: Any?): Boolean =
other != null && other is Program && other.name == name
override fun hashCode(): Int = name.hashCode()
}
}
| 0 | Kotlin | 0 | 0 | d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025 | 2,539 | AdventOfCode | MIT License |
src/main/kotlin/util/Evaluator.kt | WarriorsSami | 430,104,951 | false | {"Kotlin": 10902, "Assembly": 20} | package util
import model.LogicConfiguration
import java.util.*
enum class StatementType(s: String) {
VALID("valid"),
SATISFIABLE("satisfiable"),
CONTINGENT("contingent"),
INVALID("invalid"),
}
// evaluate operation
fun evaluate(operator: TokenType, operand1: Boolean, operand2: Boolean): Boolean {
return when(operator) {
TokenType.NOT -> operand2.logicNot()
TokenType.AND -> operand1.logicAnd(operand2)
TokenType.OR -> operand1.logicOr(operand2)
TokenType.XOR -> operand1.logicXor(operand2)
TokenType.IMPL -> operand1.logicImpl(operand2)
TokenType.IFF -> operand1.logicEquiv(operand2)
else -> throw IllegalArgumentException("Unknown operator: $operator")
}
}
// evaluate the entire list of boolean configurations at the same time
fun evaluateConfig(configurations: List<LogicConfiguration>, operatorsStack: Stack<TokenType>) {
val op = operatorsStack.pop()
configurations.forEach { config ->
val operand2 = config.operandsStack.pop()
val operand1 = if (op == TokenType.NOT) true
else config.operandsStack.pop()
config.operandsStack.push(
evaluate(op, operand1, operand2)
)
}
}
// evaluate the stream of tokens
fun evaluateExpression(tokens: List<Pair<TokenType, String>>, listOfConfiguration: List<LogicConfiguration>) {
// declare stack of operators
val operatorsStack = Stack<TokenType>()
// evaluate each expression in the context
tokens.forEach {
when(it.first) {
TokenType.IDENTIFIER -> {
listOfConfiguration.forEach { config ->
config.operandsStack.push(
config.booleanConfiguration[config.operandsMap[it.second]!!]
)
}
}
TokenType.L_PAREN -> {
operatorsStack.push(it.first)
}
TokenType.R_PAREN -> {
while (!operatorsStack.empty() &&
!TokenType.isLeftParen(operatorsStack.peek())) {
evaluateConfig(listOfConfiguration, operatorsStack)
}
// pop the left parenthesis
if (!operatorsStack.empty()) {
operatorsStack.pop()
}
}
else -> {
while (!operatorsStack.empty() &&
TokenType.getPrecedence(operatorsStack.peek()) >=
TokenType.getPrecedence(it.first)) {
evaluateConfig(listOfConfiguration, operatorsStack)
}
operatorsStack.push(it.first)
}
}
}
// apply remaining operators
while (!operatorsStack.empty()) {
evaluateConfig(listOfConfiguration, operatorsStack)
}
}
fun getStatementType(configurations: List<Boolean>): List<StatementType> {
val valid = configurations.all { it }
val satisfiable = configurations.any { it }
val contingent = configurations.any { it } && configurations.any { !it }
val invalid = configurations.all { !it }
return when {
valid -> listOf(StatementType.VALID, StatementType.SATISFIABLE)
contingent -> listOf(StatementType.CONTINGENT, StatementType.SATISFIABLE)
satisfiable -> listOf(StatementType.SATISFIABLE)
invalid -> listOf(StatementType.INVALID)
else -> throw IllegalArgumentException("Unknown statement type")
}
} | 0 | Kotlin | 0 | 1 | cf23e6f52f4074f13549c745f50aa1d9fd639911 | 3,498 | LogicParser | Apache License 2.0 |
aoc2023/src/main/kotlin/de/havox_design/aoc2023/day19/Aplenty.kt | Gentleman1983 | 737,309,232 | false | {"Kotlin": 746488, "Java": 441473, "Scala": 33415, "Groovy": 5725, "Python": 3319} | package de.havox_design.aoc2023.day19
import java.util.*
class Aplenty(private var filename: String) {
private val ICON_ACCEPT = "A"
private val ICON_REJECT = "R"
private val ICON_START = "in"
private val ICON_LESS_THAN = '<'
private val ELEMENT_DELIMITER = ','
private val RULE_START_DELIMITER = '{'
private val SOLUTION_DELIMITER = ':'
@SuppressWarnings("kotlin:S6611")
fun solvePart1(): Long {
val (rules, assignments) = readInput()
return assignments
.filter { assignment ->
var current = ICON_START
while (current != ICON_ACCEPT && current != ICON_REJECT) {
val rule = rules[current]!!
current = (rule.decisions.firstOrNull { it.test(assignment) }?.successLabel) ?: rule.elseRule
}
current == ICON_ACCEPT
}
.sumOf { it.total() }
}
@SuppressWarnings("kotlin:S6611")
fun solvePart2(): Long {
val (rules) = readInput()
val results = mutableListOf<RangeAssignment>()
val queue = linkedListOf(RangeAssignment() to ICON_START)
while (queue.isNotEmpty()) {
val (current, label) = queue.removeFirst()
when (label) {
ICON_ACCEPT -> {
results.add(current)
continue
}
ICON_REJECT -> continue
}
val rule = rules[label]!!
val result = rule
.decisions
.runningFold(Triple(current, current, label)) { (_, falseValue), condition ->
falseValue
.split(condition)
.let { (a, b) -> Triple(a, b, condition.successLabel) }
}
.drop(1)
result
.map { it.first to it.third }
.filter { it.first.isValid() }
.toCollection(queue)
when {
result.last().second.isValid() -> {
queue.add(result.last().second to rule.elseRule)
}
}
}
return results
.sumOf { it.sum() }
}
private fun <T> linkedListOf(vararg elements: T) =
elements.toCollection(LinkedList())
private fun readInput(): Pair<Map<String, SortRule>, List<Assignment>> {
val input = getResourceAsText(filename)
val rules = input
.takeWhile { it.isNotBlank() }
.associate { row ->
val (name, rules) = row.split(RULE_START_DELIMITER, limit = 2)
val splitRules = rules.split(ELEMENT_DELIMITER)
val elseCondition = splitRules.last().dropLast(1)
val conditions = splitRules.dropLast(1).map {
val (test, label) = it.split(SOLUTION_DELIMITER, limit = 2)
val conditionName = test.first()
val lessThen = test[1] == ICON_LESS_THAN
val value = test.drop(2).toLong()
Condition(conditionName, lessThen, value, label)
}
name to SortRule(name, conditions, elseCondition)
}
val regex = Regex("\\{x=(\\d+),m=(\\d+),a=(\\d+),s=(\\d+)}")
val assignments = input
.dropWhile { it.isNotBlank() }
.drop(1)
.map { row ->
regex
.matchEntire(row)!!
.destructured
.let { (x, m, a, s) ->
Assignment(
x.toLong(),
m.toLong(),
a.toLong(),
s.toLong()
)
}
}
return rules to assignments
}
private fun getResourceAsText(path: String): List<String> =
this.javaClass.classLoader.getResourceAsStream(path)!!.bufferedReader().readLines()
} | 4 | Kotlin | 0 | 1 | 35ce3f13415f6bb515bd510a1f540ebd0c3afb04 | 4,041 | advent-of-code | Apache License 2.0 |
src/main/kotlin/aoc2023/Day01.kt | lukellmann | 574,273,843 | false | {"Kotlin": 175166} | package aoc2023
import AoCDay
import util.illegalInput
// https://adventofcode.com/2023/day/1
object Day01 : AoCDay<Int>(
title = "Trebuchet?!",
part1ExampleAnswer = 142 + (11 + 11 + 22 + 33 + 42 + 24 + 77),
part1Answer = 54597,
part2ExampleAnswer = 142 + 281,
part2Answer = 54504,
) {
private val DIGIT_REGEX = Regex("[0-9]|one|two|three|four|five|six|seven|eight|nine")
private fun digitToInt(digit: String) = when (digit) {
"one" -> 1
"two" -> 2
"three" -> 3
"four" -> 4
"five" -> 5
"six" -> 6
"seven" -> 7
"eight" -> 8
"nine" -> 9
else -> if (digit.length == 1 && digit[0] in '0'..'9') digit[0] - '0' else illegalInput(digit)
}
override fun part1(input: String) = input
.lineSequence()
.sumOf { line ->
val firstDigit = line.first { it in '0'..'9' }
val lastDigit = line.last { it in '0'..'9' }
(firstDigit - '0') * 10 + (lastDigit - '0')
}
override fun part2(input: String) = input
.lineSequence()
.sumOf { line ->
val firstDigit = DIGIT_REGEX.find(line)?.value ?: illegalInput(line)
val lastDigit = line.indices
.reversed()
.firstNotNullOf { index -> DIGIT_REGEX.find(line, startIndex = index)?.value }
digitToInt(firstDigit) * 10 + digitToInt(lastDigit)
}
}
| 0 | Kotlin | 0 | 1 | 344c3d97896575393022c17e216afe86685a9344 | 1,442 | advent-of-code-kotlin | MIT License |
Problems/Algorithms/1926. Nearest Exit from Entrance in Maze/NearestExit.kt | xuedong | 189,745,542 | false | {"Kotlin": 332182, "Java": 294218, "Python": 237866, "C++": 97190, "Rust": 82753, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65} | class Solution {
fun nearestExit(maze: Array<CharArray>, entrance: IntArray): Int {
val n = maze.size
val m = maze[0].size
val neighbors = arrayOf(intArrayOf(0, 1), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0))
val visited = Array(n) { BooleanArray(m) { false } }
val queue = ArrayDeque<IntArray>()
queue.add(intArrayOf(entrance[0], entrance[1], 0))
visited[entrance[0]][entrance[1]] = true
while (!queue.isEmpty()) {
val curr = queue.removeFirst()
val r = curr[0]
val c = curr[1]
val d = curr[2]
if (d != 0 && (r == 0 || r == n-1 || c == 0 || c == m-1)) {
return d
}
for (neighbor in neighbors) {
val x = r + neighbor[0]
val y = c + neighbor[1]
if (isValid(n, m, x, y) && !visited[x][y] && maze[x][y] == '.') {
visited[x][y] = true
queue.add(intArrayOf(x, y, d+1))
}
}
}
return -1
}
private fun isValid(n: Int, m: Int, r: Int, c: Int): Boolean {
return r >= 0 && c >= 0 && r < n && c < m
}
}
| 0 | Kotlin | 0 | 1 | 5e919965b43917eeee15e4bff12a0b6bea4fd0e7 | 1,292 | leet-code | MIT License |
src/2023/Day08.kt | nagyjani | 572,361,168 | false | {"Kotlin": 369497} | package `2023`
import java.io.File
import java.lang.RuntimeException
import java.math.BigInteger
import java.util.*
fun main() {
Day08().solve()
}
class Day08 {
val input1 = """
RL
AAA = (BBB, CCC)
BBB = (DDD, EEE)
CCC = (ZZZ, GGG)
DDD = (DDD, DDD)
EEE = (EEE, EEE)
GGG = (GGG, GGG)
ZZZ = (ZZZ, ZZZ)
""".trimIndent()
val input2 = """
LLR
AAA = (BBB, BBB)
BBB = (AAA, ZZZ)
ZZZ = (ZZZ, ZZZ)
""".trimIndent()
val input3 = """
LR
11A = (11B, XXX)
11B = (XXX, 11Z)
11Z = (11B, XXX)
22A = (22B, XXX)
22B = (22C, 22C)
22C = (22Z, 22Z)
22Z = (22B, 22B)
XXX = (XXX, XXX)
""".trimIndent()
fun steps(instructions: String, m: Map<String, Pair<String, String>>, start: String, goals: Set<String>): Long {
var i = 0L
var p = start
val reached = mutableMapOf<String,MutableSet<Long>>()
// while (!goals.contains(p)) {
while (true) {
val i1 = (i % instructions.length).toInt()
when (instructions[i1]) {
'L' -> p = m[p]!!.first
'R' -> p = m[p]!!.second
}
i++
if (p.endsWith('Z')) {
val s = reached.getOrDefault(p, mutableSetOf())
if (s.any{ (i-it) % instructions.length.toLong() == 0L}) {
if (s.size == 1 && s.first() * 2 == i) {
return i/2
}
break
}
s.add(i)
reached[p] = s
}
}
return i
}
fun solve() {
val f = File("src/2023/inputs/day08.in")
val s = Scanner(f)
// val s = Scanner(input1)
// val s = Scanner(input2)
// val s = Scanner(input3)
var sum = 0
var sum1 = 0
var lineix = 0
val lines = mutableListOf<String>()
val m = mutableMapOf<String, Pair<String, String>>()
val instructions = s.nextLine().trim()
val starts = mutableSetOf<String>()
val goals = mutableSetOf<String>()
while (s.hasNextLine()) {
lineix++
val line = s.nextLine().trim()
if (line.isEmpty()) {
continue
}
lines.add(line)
val l1 = line.split(Regex("[,= \\(\\)]")).filter{it.isNotEmpty()}
m[l1[0]] = Pair(l1[1], l1[2])
when (l1[0].last()) {
'A' -> starts.add(l1[0])
'Z' -> goals.add(l1[0])
}
}
val lengths = starts.map {
steps(instructions, m, it, goals)
}
val r = lengths.map{BigInteger(it.toString())}.fold(BigInteger.ONE){acc, it ->
lcm(acc, it)
}
print("$r\n")
// var i1 = 0L
// var p1 = starts.toSet()
// while (!p1.all{it.last() == 'Z'}) {
// val i2 = (i1 % instructions.length).toInt()
// p1 =
// p1.map {
// when (instructions[i2]) {
// 'L' -> m[it]!!.first
// 'R' -> m[it]!!.second
// else -> {throw RuntimeException()}
// }
// }.toSet()
// i1++
// if (i1 % 1000000 == 0L) {
// print("$i1 $p1 ${instructions.length} ${m.size}\n")
// }
// }
//
// print("$i1\n")
// print("${steps(instructions, m, "AAA", "ZZZ")}\n")
}
fun lcm(l1: BigInteger, l2: BigInteger): BigInteger {
return l1 * l2 / gcd(l1, l2)
}
fun gcd(l1: BigInteger, l2: BigInteger): BigInteger {
var l11 = l1
var l22 = l2
while (l11 != l22) {
if (l11 > l22) {
if (l11 % l22 == BigInteger.ZERO) {
return l22
}
l11 = l11 % l22
} else {
if (l22 % l11 == BigInteger.ZERO) {
return l11
}
l22 = l22 % l11
}
}
return l11
}
} | 0 | Kotlin | 0 | 0 | f0c61c787e4f0b83b69ed0cde3117aed3ae918a5 | 4,142 | advent-of-code | Apache License 2.0 |
src/main/kotlin/algorithms/sorting/radix_sort/RadixSort.kt | AANikolaev | 273,465,105 | false | {"Java": 179737, "Kotlin": 13961} | package algorithms.sorting.radix_sort
import algorithms.sorting.InplaceSort
import kotlin.math.log10
class RadixSort : InplaceSort {
override fun sort(values: IntArray) {
radixSort(values)
}
fun getMax(array: IntArray): Int {
var max = array[0]
for (i in array.indices) {
if (array[i] > max) {
max = array[i]
}
}
return max
}
fun calculateNumberOfDigits(number: Int): Int {
return log10(number.toDouble()).toInt() + 1
}
// Requires all numbers to be greater than or equal to 1
fun radixSort(numbers: IntArray?) {
if (numbers == null || numbers.size <= 1) {
return
}
val maximum = getMax(numbers)
var numberOfDigits = calculateNumberOfDigits(maximum)
var placeValue = 1
while (numberOfDigits-- > 0) {
countSort(numbers, placeValue)
placeValue *= 10
}
}
private fun countSort(numbers: IntArray, placeValue: Int) {
val range = 10
val frequency = IntArray(range)
val sortedValues = IntArray(numbers.size)
for (i in numbers.indices) {
val digit = numbers[i] / placeValue % range
frequency[digit]++
}
for (i in 1 until range) {
frequency[i] += frequency[i - 1]
}
for (i in numbers.indices.reversed()) {
val digit = numbers[i] / placeValue % range
sortedValues[frequency[digit] - 1] = numbers[i]
frequency[digit]--
}
System.arraycopy(sortedValues, 0, numbers, 0, numbers.size)
}
} | 0 | Java | 0 | 0 | f9f0a14a5c450bd9efb712b28c95df9a0d7d589b | 1,656 | Algorithms | MIT License |
src/Day19.kt | RusticFlare | 574,508,778 | false | {"Kotlin": 78496} | import java.util.*
import kotlin.math.ceil
import kotlin.math.max
private class Factory(val blueprint: Blueprint, val minutes: Int) {
fun findBest(): Int {
var currentBest = 0
val queue = PriorityQueue<Day19State>().apply { add(Day19State(minutes = minutes)) }
while (queue.isNotEmpty()) {
val state = queue.poll()
if (state.canOutproduce(currentBest)) {
queue.addAll(state.nextSensibleStates())
}
currentBest = max(currentBest, state.geode + state.geodeRobots * (state.minutes - 1))
}
return currentBest
}
private fun Day19State.nextSensibleStates() = buildList {
if (blueprint.maxOre > oreRobots) {
add(nextWith(blueprint.oreRobot))
}
if (blueprint.maxClay > clayRobots) {
add(nextWith(blueprint.clayRobot))
}
if (clayRobots > 0 && blueprint.maxObsidian > obsidianRobots) {
add(nextWith(blueprint.obsidianRobot))
}
if (obsidianRobots > 0) {
add(nextWith(blueprint.geodeRobot))
}
}.filter { it.minutes > 0 }
}
private data class Day19State(
val minutes: Int,
val ore: Int = 1,
val clay: Int = 0,
val obsidian: Int = 0,
val geode: Int = 0,
val oreRobots: Int = 1,
val clayRobots: Int = 0,
val obsidianRobots: Int = 0,
val geodeRobots: Int = 0,
) : Comparable<Day19State> {
override fun compareTo(other: Day19State) = other.geode.compareTo(geode)
fun nextWith(robot: Robot): Day19State {
val minutes = timeToBuild(robot)
return copy(
minutes = this.minutes - minutes,
ore = ore + oreRobots * minutes - robot.oreCost,
clay = clay + clayRobots * minutes - robot.clayCost,
obsidian = obsidian + obsidianRobots * minutes - robot.obsidianCost,
geode = geode + geodeRobots * minutes,
oreRobots = oreRobots + robot.oreRobotsBuilt,
clayRobots = clayRobots + robot.clayRobotsBuilt,
obsidianRobots = obsidianRobots + robot.obsidianRobotsBuilt,
geodeRobots = geodeRobots + robot.geodeRobotsBuilt
)
}
fun canOutproduce(best: Int): Boolean {
val potentialProduction = (0 until minutes - 1).sumOf { it + geodeRobots }
return geode + potentialProduction > best
}
private fun timeToBuild(robot: Robot): Int {
val remainingOre = (robot.oreCost - ore).coerceAtLeast(0)
val remainingClay = (robot.clayCost - clay).coerceAtLeast(0)
val remainingObsidian = (robot.obsidianCost - obsidian).coerceAtLeast(0)
return maxOf(
ceil(remainingOre / oreRobots.toFloat()).toInt(),
ceil(remainingClay / clayRobots.toFloat()).toInt(),
ceil(remainingObsidian / obsidianRobots.toFloat()).toInt(),
) + 1
}
}
private data class Robot(
val oreCost: Int = 0,
val clayCost: Int = 0,
val obsidianCost: Int = 0,
val oreRobotsBuilt: Int = 0,
val clayRobotsBuilt: Int = 0,
val obsidianRobotsBuilt: Int = 0,
val geodeRobotsBuilt: Int = 0,
)
private data class Blueprint(
val id: Int,
val oreRobot: Robot,
val clayRobot: Robot,
val obsidianRobot: Robot,
val geodeRobot: Robot
) {
val maxOre = maxOf(oreRobot.oreCost, clayRobot.oreCost, obsidianRobot.oreCost, geodeRobot.oreCost)
val maxClay = obsidianRobot.clayCost
val maxObsidian = geodeRobot.obsidianCost
companion object {
private val pattern = """\d+""".toRegex()
fun from(line: String): Blueprint {
val numbers = pattern.findAll(line).map { it.value.toInt() }.toList()
return Blueprint(
id = numbers[0],
oreRobot = Robot(oreCost = numbers[1], oreRobotsBuilt = 1),
clayRobot = Robot(oreCost = numbers[2], clayRobotsBuilt = 1),
obsidianRobot = Robot(oreCost = numbers[3], clayCost = numbers[4], obsidianRobotsBuilt = 1),
geodeRobot = Robot(oreCost = numbers[5], obsidianCost = numbers[6], geodeRobotsBuilt = 1)
)
}
}
}
fun main() {
fun part1(input: List<String>): Int {
return input.map(Blueprint::from)
.sumOf { it.id * Factory(it, minutes = 24).findBest() }
}
fun part2(input: List<String>): Int {
return input.map(Blueprint::from)
.take(3)
.map { Factory(it, minutes = 32).findBest() }
.reduce(Int::times)
}
// test if implementation meets criteria from the description, like:
val testInput = readLines("Day19_test")
check(part1(testInput) == 33)
val input = readLines("Day19")
with(part1(input)) {
check(this == 1725)
println(this)
}
with(part2(input)) {
check(this == 15510)
println(this)
}
}
| 0 | Kotlin | 0 | 1 | 10df3955c4008261737f02a041fdd357756aa37f | 4,892 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountNumberOfTeams.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
/**
* 1395. Count Number of Teams
* @see <a href="https://leetcode.com/problems/count-number-of-teams">Source</a>
*/
fun interface CountNumberOfTeams {
operator fun invoke(rating: IntArray): Int
}
class CountNumberOfTeamsSolution : CountNumberOfTeams {
override fun invoke(rating: IntArray): Int {
var res = 0
for (i in 1 until rating.size - 1) {
val less = countLess(rating, i)
val greater = countGreater(rating, i)
res += less[0] * greater[1] + greater[0] * less[1]
}
return res
}
private fun countLess(rating: IntArray, index: Int): IntArray {
val less = intArrayOf(0, 0)
for (j in rating.indices) {
if (rating[index] < rating[j]) {
++less[if (j > index) 1 else 0]
}
}
return less
}
private fun countGreater(rating: IntArray, index: Int): IntArray {
val greater = intArrayOf(0, 0)
for (j in rating.indices) {
if (rating[index] > rating[j]) {
++greater[if (j > index) 1 else 0]
}
}
return greater
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,791 | kotlab | Apache License 2.0 |
kotlin/0721-accounts-merge.kt | neetcode-gh | 331,360,188 | false | {"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750} | class DSU(val n: Int) {
val parent = IntArray(n) {it}
val rank = IntArray(n) {1}
fun find(x: Int): Int {
if (x != parent[x])
parent[x] = find(parent[x])
return parent[x]
}
fun union(x: Int, y: Int): Boolean {
val pX = find(x)
val pY = find(y)
if(pX == pY)
return false
if (rank[pX] > rank[pY]) {
parent[pY] = pX
rank[pX] += rank[pY]
} else {
parent[pX] = pY
rank[pY] += rank[pX]
}
return true
}
}
class Solution {
fun accountsMerge(accounts: List<List<String>>): List<List<String>> {
val uf = DSU(accounts.size)
val emailToAcc = HashMap<String, Int>()
for ((i,accs) in accounts.withIndex()) {
for (j in 1..accs.lastIndex) {
val e = accs[j]
if (e in emailToAcc.keys) {
uf.union(i, emailToAcc[e]!!)
} else {
emailToAcc[e] = i
}
}
}
val emails = hashMapOf<Int, ArrayList<String>>()
for ((e, i) in emailToAcc) {
val main = uf.find(i)
emails[main] = emails.getOrDefault(main, ArrayList<String>()).apply { this.add(e) }
}
val res = ArrayList<ArrayList<String>>()
for ((i, em) in emails.entries) {
em.sort()
em.add(0, accounts[i][0])
res.add(em)
}
return res
}
}
| 337 | JavaScript | 2,004 | 4,367 | 0cf38f0d05cd76f9e96f08da22e063353af86224 | 1,527 | leetcode | MIT License |
LeetCode2020April/week1/src/test/kotlin/net/twisterrob/challenges/leetcode2020april/week1/happy_number/SquaredSumTest.kt | TWiStErRob | 136,539,340 | false | {"Kotlin": 104880, "Java": 11319} | package net.twisterrob.challenges.leetcode2020april.week1.happy_number
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.DynamicTest.dynamicTest
import org.junit.jupiter.api.TestFactory
class SquaredSumTest {
private fun squaredSumTest(input: Int, expected: Int) =
dynamicTest("$input has squared sum of digits: $expected") {
testSquaredSum(input, expected)
}
private fun testSquaredSum(input: Int, expected: Int) {
val result = input.squaredSum()
assertEquals(expected, result)
}
@TestFactory fun squaredSumOf19Chain() = arrayOf(
squaredSumTest(19, 1 * 1/*1*/ + 9 * 9/*81*/),
squaredSumTest(82, 8 * 8/*81*/ + 2 * 2/*4*/),
squaredSumTest(68, 6 * 6/*36*/ + 8 * 8/*81*/),
squaredSumTest(100, 1 * 1/*1*/ + 0 * 0/*0*/ + 0 * 0/*0*/),
squaredSumTest(1, 1 * 1/*1*/),
)
@TestFactory fun squaredSumOf2Chain() = arrayOf(
squaredSumTest(2, 2 * 2/*4*/),
// loop start
squaredSumTest(4, 4 * 4/*16*/),
squaredSumTest(16, 1 * 1/*1*/ + 6 * 6/*36*/),
squaredSumTest(37, 3 * 3/*9*/ + 7 * 7/*49*/),
squaredSumTest(58, 5 * 5/*25*/ + 8 * 8/*64*/),
squaredSumTest(89, 8 * 8/*64*/ + 9 * 9/*81*/),
squaredSumTest(145, 1 * 1/*1*/ + 4 * 4/*16*/ + 5 * 5/*25*/),
squaredSumTest(42, 4 * 4/*16*/ + 2 * 2/*4*/),
squaredSumTest(20, 2 * 2/*4*/ + 0 * 0/*0*/),
// loop
)
@TestFactory fun squaredSumOf3Chain() = arrayOf(
squaredSumTest(3, 3 * 3/*9*/),
squaredSumTest(9, 9 * 9/*81*/),
squaredSumTest(81, 8 * 8/*64*/ + 1 * 1 /*1*/),
squaredSumTest(65, 6 * 6/*36*/ + 5 * 5 /*25*/),
squaredSumTest(61, 6 * 6/*36*/ + 1 * 1/*1*/),
squaredSumTest(37, 3 * 3/*9*/ + 7 * 7/*49*/),
// loop start
squaredSumTest(58, 5 * 5/*25*/ + 8 * 8/*64*/),
squaredSumTest(89, 8 * 8/*64*/ + 9 * 9/*81*/),
squaredSumTest(145, 1 * 1/*1*/ + 4 * 4/*16*/ + 5 * 5/*25*/),
squaredSumTest(42, 4 * 4/*16*/ + 2 * 2/*4*/),
squaredSumTest(20, 2 * 2/*4*/ + 0 * 0/*0*/),
squaredSumTest(4, 4 * 4/*16*/),
squaredSumTest(16, 1 * 1/*1*/ + 6 * 6/*36*/),
squaredSumTest(37, 3 * 3/*9*/ + 7 * 7/*49*/),
// loop
)
@TestFactory fun squaredSum() = arrayOf(
squaredSumTest(0, 0),
squaredSumTest(1, 1),
squaredSumTest(27, 53),
squaredSumTest(52, 29),
squaredSumTest(53, 34),
squaredSumTest(64, 52),
squaredSumTest(67, 85),
squaredSumTest(80, 64),
squaredSumTest(83, 73),
squaredSumTest(84, 80),
)
}
| 1 | Kotlin | 1 | 2 | 5cf062322ddecd72d29f7682c3a104d687bd5cfc | 2,357 | TWiStErRob | The Unlicense |
2022/main/day_13/Main.kt | Bluesy1 | 572,214,020 | false | {"Rust": 280861, "Kotlin": 94178, "Shell": 996} | package day_13_2022
import java.io.File
@Suppress("NAME_SHADOWING")
internal class Packet(packet: String) : Comparable<Packet?> {
private var children: MutableList<Packet>
var value = 0
private var integer = true
var str: String
init {
var packet = packet
str = packet
children = mutableListOf()
if (packet == "[]") {
value = -1
}
if (!packet.startsWith("[")) {
value = packet.toInt()
} else {
packet = packet.substring(1, packet.length - 1)
var level = 0
var tmp = ""
for (c in packet) {
if (c == ',' && level == 0) {
children.add(Packet(tmp))
tmp = ""
} else {
level += if (c == '[') 1 else if (c == ']') -1 else 0
tmp += c
}
}
if (tmp != "") {
children.add(Packet(tmp))
}
integer = false
}
}
override operator fun compareTo(other: Packet?): Int {
if (other == null) {
return 0
}
if (integer && other.integer) {
return other.value - value
}
if (!integer && !other.integer) {
for (i in 0 until children.size.coerceAtMost(other.children.size)) {
val value = children[i].compareTo(other.children[i])
if (value != 0) {
return value
}
}
return other.children.size - children.size
}
val lst1 = if (integer) Packet("[$value]") else this
val lst2 = if (other.integer) Packet("[" + other.value + "]") else other
return lst1.compareTo(lst2)
}
}
fun part1(input: List<String>) {
input.chunked(3)
.map{ Packet(it[0]) to Packet(it[1]) }
.mapIndexed{ index, pair -> if ((pair.first > pair.second)) index + 1 else 0}
.sum()
.let { print("The sum of the indices is $it.") }
}
fun part2(input: List<String>) {
val packets = input.filterNot(String::isEmpty).map(::Packet).toMutableList()
packets.add(Packet("[[2]]"))
packets.add(Packet("[[6]]"))
packets.sortDescending()
packets.mapIndexed{ index, packet -> if (packet.str == "[[2]]" || packet.str == "[[6]]" ) index + 1 else 0}
.filter { it != 0 }
.reduce(Int::times)
.let { print("The decoder key is $it.") }
}
fun main(){
val inputFile = File("2022/inputs/Day_13.txt")
print("\n----- Part 1 -----\n")
part1(inputFile.readLines())
print("\n----- Part 2 -----\n")
part2(inputFile.readLines())
} | 0 | Rust | 0 | 0 | 537497bdb2fc0c75f7281186abe52985b600cbfb | 2,696 | AdventofCode | MIT License |
src/main/kotlin/g1801_1900/s1896_minimum_cost_to_change_the_final_value_of_expression/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1801_1900.s1896_minimum_cost_to_change_the_final_value_of_expression
// #Hard #String #Dynamic_Programming #Math #Stack
// #2023_06_22_Time_252_ms_(100.00%)_Space_41.3_MB_(100.00%)
class Solution {
private class Result(var `val`: Int, var minFlips: Int)
private var cur = 0
fun minOperationsToFlip(expression: String): Int {
cur = 0
return term(expression).minFlips
}
private fun term(s: String): Result {
var res = factor(s)
while (cur < s.length && (s[cur] == '|' || s[cur] == '&')) {
val c = s[cur]
cur++
res = if (c == '|') {
or(res, factor(s))
} else {
and(res, factor(s))
}
}
return res
}
private fun factor(s: String): Result {
if (s[cur] == '(') {
cur++
val res = term(s)
cur++
return res
}
return number(s)
}
private fun number(s: String): Result {
return if (s[cur] == '1') {
cur++
Result(1, 1)
} else {
cur++
Result(0, 1)
}
}
private fun or(res1: Result, res2: Result): Result {
return if (res1.`val` + res2.`val` == 0) {
Result(
0,
Math.min(res1.minFlips, res2.minFlips)
)
} else if (res1.`val` + res2.`val` == 2) {
Result(
1,
1 + Math.min(res1.minFlips, res2.minFlips)
)
} else {
Result(1, 1)
}
}
private fun and(res1: Result, res2: Result): Result {
return if (res1.`val` + res2.`val` == 0) {
Result(
0,
1 + Math.min(res1.minFlips, res2.minFlips)
)
} else if (res1.`val` + res2.`val` == 2) {
Result(
1,
Math.min(res1.minFlips, res2.minFlips)
)
} else {
Result(0, 1)
}
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,056 | LeetCode-in-Kotlin | MIT License |
2020/day11/day11.kt | flwyd | 426,866,266 | false | {"Julia": 207516, "Elixir": 120623, "Raku": 119287, "Kotlin": 89230, "Go": 37074, "Shell": 24820, "Makefile": 16393, "sed": 2310, "Jsonnet": 1104, "HTML": 398} | /*
* Copyright 2021 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
package day11
import kotlin.time.ExperimentalTime
import kotlin.time.TimeSource
import kotlin.time.measureTimedValue
/* Input: grid of floor (.), open (L), occupied (#) seats. Output is number of occupied seats after
applying rules repeatedly until they stabilize. */
fun List<String>.toCharArrays() = Array(size) { get(it).toCharArray() }
object Part1 {
fun solve(input: Sequence<String>): String {
var grid = Grid(input.toList().toCharArrays())
while (true) {
val next = grid.evolve()
if (next === grid) {
return grid.cells.map { it.count('#'::equals) }.sum().toString()
}
grid = next
// println(grid.cells.map { it.joinToString("") }.joinToString("\n"))
// println()
}
}
/* If open and adjacent to no closed spots, spot becomes occupied.
If occupied and adjacent to >= 4 occupied, becomes open. */
class Grid(val cells: Array<CharArray>) {
private val height = cells.size
private val width = cells[0].size
fun evolve(): Grid {
val newCells = Array(height) { CharArray(width) }
var changes = 0
for (i in 0 until height) {
for (j in 0 until width) {
newCells[i][j] = when (cells[i][j]) {
'L' -> if (countNeighbors(i, j, '#') == 0) '#' else 'L'
'#' -> if (countNeighbors(i, j, '#') >= 4) 'L' else '#'
'.' -> '.'
else -> throw IllegalStateException("Invalid character in $cells")
}
if (cells[i][j] != newCells[i][j]) {
changes++
}
}
}
return if (changes == 0) this else Grid(newCells)
}
private fun countNeighbors(row: Int, col: Int, c: Char): Int {
var matches = 0
for (i in ((row - 1)..(row + 1)).intersect(0 until height)) {
for (j in ((col - 1)..(col + 1)).intersect(0 until width)) {
if (cells[i][j] == c && (i != row || j != col)) {
matches++
}
}
}
return matches
}
}
}
object Part2 {
fun solve(input: Sequence<String>): String {
var grid = Grid(input.toList().toCharArrays())
while (true) {
val next = grid.evolve()
if (next === grid) {
return grid.cells.map { it.count('#'::equals) }.sum().toString()
}
grid = next
// println(grid.cells.map { it.joinToString("") }.joinToString("\n"))
// println()
}
}
/* Decisions are made by line-of-sight. If open can't see occupied, becomes occupied.
If occupied and sees >= 5 occupied, becomes open. */
class Grid(val cells: Array<CharArray>) {
private val height = cells.size
private val width = cells[0].size
fun evolve(): Grid {
val newCells = Array(height) { CharArray(width) }
var changes = 0
for (i in 0 until height) {
for (j in 0 until width) {
newCells[i][j] = when (cells[i][j]) {
'L' -> if (countVisible(i, j, '#') == 0) '#' else 'L'
'#' -> if (countVisible(i, j, '#') >= 5) 'L' else '#'
'.' -> '.'
else -> throw IllegalStateException("Invalid character in $cells")
}
if (cells[i][j] != newCells[i][j]) {
changes++
}
}
}
return if (changes == 0) this else Grid(newCells)
}
private fun countVisible(row: Int, col: Int, c: Char): Int {
var matches = 0
for (Δr in -1..1) {
for (Δc in -1..1) {
if (Δr != 0 || Δc != 0) {
var i = row + Δr
var j = col + Δc
while (i in 0 until height && j in 0 until width) {
if (cells[i][j] == c) {
matches++
break
} else if (cells[i][j] != '.') {
break
}
i += Δr
j += Δc
}
}
}
}
return matches
}
}
}
@ExperimentalTime
@Suppress("UNUSED_PARAMETER")
fun main(args: Array<String>) {
val lines = generateSequence(::readLine).toList()
print("part1: ")
TimeSource.Monotonic.measureTimedValue { Part1.solve(lines.asSequence()) }.let {
println(it.value)
System.err.println("Completed in ${it.duration}")
}
print("part2: ")
TimeSource.Monotonic.measureTimedValue { Part2.solve(lines.asSequence()) }.let {
println(it.value)
System.err.println("Completed in ${it.duration}")
}
}
| 0 | Julia | 1 | 5 | f2d6dbb67d41f8f2898dbbc6a98477d05473888f | 4,568 | adventofcode | MIT License |
src/main/kotlin/com/leetcode/monthly_challenges/2021/april/palindrome_linked_list/Main.kt | frikit | 254,842,734 | false | null | package com.leetcode.monthly_challenges.`2021`.april.palindrome_linked_list
fun main() {
println("Test case 1:")
val li = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5, null)))))
println("" + Solution().isPalindrome(li) + "==" + false)
println()
println("Test case 2:")
val li2 = ListNode(1, ListNode(2, ListNode(2, ListNode(1, null))))
println("" + Solution().isPalindrome(li2) + "==" + true)
println()
println("Test case 3:")
val li3 = ListNode(1, ListNode(2, ListNode(2, null)))
println("" + Solution().isPalindrome(li3) + "==" + false)
println()
println("Test case 4:")
val li4 = ListNode(1, ListNode(2, null))
println("" + Solution().isPalindrome(li4) + "==" + false)
println()
println("Test case 5:")
val li5 = ListNode(1, ListNode(0, ListNode(1, null)))
println("" + Solution().isPalindrome(li5) + "==" + true)
println()
println("Test case 6:")
val li6 = ListNode(1, ListNode(2, ListNode(2, ListNode(2, ListNode(1, null)))))
println("" + Solution().isPalindrome(li6) + "==" + true)
println()
}
class Solution {
fun isPalindrome(head: ListNode?): Boolean {
var node = head
val list = ArrayList<Int>()
if (head == null) return true
while (node != null) {
list.add(node.`val`)
node = node.next
}
for (i in 0..(list.size - 1) / 2) {
if (list[i] != list[list.size - 1 - i])
return false
}
return true
}
}
data class ListNode(var `val`: Int, var next: ListNode? = null)
| 0 | Kotlin | 0 | 0 | dda68313ba468163386239ab07f4d993f80783c7 | 1,607 | leet-code-problems | Apache License 2.0 |
Kotlin/src/main/kotlin/org/algorithm/problems/0190_minimize_maximum_pair_sum.kt | raulhsant | 213,479,201 | true | {"C++": 1035543, "Kotlin": 114509, "Java": 27177, "Python": 16568, "Shell": 999, "Makefile": 187} | package org.algorithm.problems
// Problem Statement
// The pair sum of a pair (a,b) is equal to a + b. The maximum pair sum is the largest pair sum in a list of pairs.
// For example, if we have pairs (1,5), (2,3), and (4,4), the maximum pair sum would be max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8.
// Given an array nums of even length n, pair up the elements of nums into n / 2 pairs such that:
// Each element of nums is in exactly one pair, and
// The maximum pair sum is minimized.
// Return the minimized maximum pair sum after optimally pairing up the elements.
class `0190_minimize_maximum_pair_sum` {
fun minPairSum(nums: IntArray): Int {
nums.sort()
var result : Int = 0
var start = 0
var end = nums.size - 1;
while(start < end){
result = Math.max(result,nums[start]+nums[end])
start++
end--
}
return result
}
}
| 0 | C++ | 0 | 0 | 1578a0dc0a34d63c74c28dd87b0873e0b725a0bd | 924 | algorithms | MIT License |
Kotlin/problems/0046_odd_even_jump.kt | oxone-999 | 243,366,951 | true | {"C++": 961697, "Kotlin": 99948, "Java": 17927, "Python": 9476, "Shell": 999, "Makefile": 187} | // Problem Statement
// You are given an integer array A. From some starting index, you can make a
// series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called odd
// numbered jumps, and the (2nd, 4th, 6th, ...) jumps in the series are called even numbered jumps.
//
// You may from index i jump forward to index j (with i < j) in the following way:
//
// *During odd numbered jumps (ie. jumps 1, 3, 5, ...), you jump to the index j
// such that A[i] <= A[j] and A[j] is the smallest possible value.
// If there are multiple such indexes j, you can only jump to the smallest such index j.
// *During even numbered jumps (ie. jumps 2, 4, 6, ...), you jump to the index j
// such that A[i] >= A[j] and A[j] is the largest possible value.
// If there are multiple such indexes j, you can only jump to the smallest such index j.
// *(It may be the case that for some index i, there are no legal jumps.)
//
// A starting index is good if, starting from that index, you can reach the end of
// the array (index A.length - 1) by jumping some number of times (possibly 0 or more than once.)
//
// Return the number of good starting indexes.
class BST{
data class Node(
var value: Int,
var index: Int,
var left: Node? = null,
var right: Node? = null
)
private var root: Node? = null
fun add(value : Int, index : Int){
if(root==null){
root = Node(value,index)
}else{
var it = root
while(it!=null){
if(it.value == value){
it.index = index
break
}else if(it.value<value){
if(it.right==null){
it.right = Node(value,index)
break
}else{
it = it.right
}
}else{
if(it.left==null){
it.left = Node(value,index)
break
}else{
it = it.left
}
}
}
}
}
fun getMaxSmallest(value: Int): Int?{
var it = root
var curr: Node? = null
while(it!=null){
if(it.value<=value){
curr = it
it = it.right
}else{
it = it.left
}
}
return curr?.index
}
fun getMinBiggest(value:Int) : Int?{
var it = root
var curr: Node? = null
while(it!=null){
if(it.value>=value){
curr = it
it = it.left
}else{
it = it.right
}
}
return curr?.index
}
}
class Solution {
fun oddEvenJumps(A: IntArray): Int {
val bst = BST()
var result = 0
val oddJump = IntArray(A.size){0}
val evenJump = IntArray(A.size){0}
oddJump[A.size-1] = 1
evenJump[A.size-1] = 1
bst.add(A[A.size-1],A.size-1)
for(i in A.size-2 downTo 0){
val indexOdd = bst.getMinBiggest(A[i])
val indexEven = bst.getMaxSmallest(A[i])
indexEven?.let{
evenJump[i] = oddJump[indexEven]
}
indexOdd?.let{
oddJump[i] = evenJump[indexOdd]
}
bst.add(A[i],i)
}
for(jump in oddJump){
result+=jump
}
return result
}
}
fun main(args: Array<String>) {
val arr = intArrayOf(10,13,12,14,15)
val sol = Solution()
println(sol.oddEvenJumps(arr))
} | 0 | null | 0 | 0 | 52dc527111e7422923a0e25684d8f4837e81a09b | 3,666 | algorithms | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/StrongPasswordChecker.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
private const val START_VALUE = 1
private const val STRONG_PASSWORD_VALUE = 6
private const val OVER_LENGTH = 20
enum class CharacterType {
LOWER_CASE, UPPER_CASE, DIGIT
}
fun strongPasswordChecker(s: String): Int {
var res = 0
var lowerCases = START_VALUE
var upperCases = START_VALUE
var digits = START_VALUE
val carr = s.toCharArray()
val arr = IntArray(carr.size)
calculateCharacterCounts(arr, carr) { characterType ->
when (characterType) {
CharacterType.LOWER_CASE -> lowerCases = 0
CharacterType.UPPER_CASE -> upperCases = 0
CharacterType.DIGIT -> digits = 0
}
}
val totalMissing = lowerCases + upperCases + digits
if (arr.size < STRONG_PASSWORD_VALUE) {
res += calculateMissingCharacters(arr.size, totalMissing)
} else {
val local = arr.size - OVER_LENGTH
val overLen = local.coerceAtLeast(0)
res += handleExcessLength(arr, overLen)
val leftOver = calculateLeftOver(arr)
res += totalMissing.coerceAtLeast(leftOver)
}
return res
}
private fun calculateCharacterCounts(
arr: IntArray,
carr: CharArray,
action: (type: CharacterType) -> Unit,
) {
var i = 0
while (i < arr.size) {
if (Character.isLowerCase(carr[i])) action.invoke(CharacterType.LOWER_CASE)
if (Character.isUpperCase(carr[i])) action.invoke(CharacterType.UPPER_CASE)
if (Character.isDigit(carr[i])) action.invoke(CharacterType.DIGIT)
val j = i
while (i < carr.size && carr[i] == carr[j]) i++
arr[j] = i - j
}
}
private fun calculateMissingCharacters(size: Int, totalMissing: Int): Int {
return totalMissing + 0.coerceAtLeast(STRONG_PASSWORD_VALUE - (size + totalMissing))
}
private fun handleExcessLength(arr: IntArray, overLen: Int): Int {
var res = overLen
for (k in 1..2) {
var i = 0
while (i < arr.size && overLen > 0) {
if (arr[i] < 3 || arr[i] % 3 != k - 1) {
i++
continue
}
arr[i] -= overLen.coerceAtMost(k)
res -= k
i++
}
}
return res
}
private fun calculateLeftOver(arr: IntArray): Int {
var leftOver = 0
var overLen = 0
for (k in arr.indices) {
if (arr[k] >= 3 && overLen > 0) {
val need = arr[k] - 2
arr[k] -= overLen
overLen -= need
}
if (arr[k] >= 3) leftOver += arr[k] / 3
}
return leftOver
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,176 | kotlab | Apache License 2.0 |
src/Year2022Day07.kt | zhangt2333 | 575,260,256 | false | {"Kotlin": 34993} | internal class FileSystem {
val root = Directory("/", null)
val allDirectories = mutableListOf<Directory>(root)
var currentDir = root
fun cd(name: String) {
currentDir = when (name) {
"/" -> root
".." -> currentDir.parent ?: throw IllegalArgumentException()
else -> currentDir.getSubDir(name)
}
}
fun createDir(name: String) {
currentDir.children.computeIfAbsent(name) {
Directory(name, currentDir).apply { allDirectories.add(this) }
}
}
fun createFile(name: String, size: Int) {
currentDir.children.computeIfAbsent(name) {
updateDirSize(size)
File(name, currentDir, size)
}
}
private fun updateDirSize(delta: Int) {
var curr: Directory? = currentDir
while (curr != null) {
curr.size += delta
curr = curr.parent
}
}
sealed interface FileSystemEntry {
val name: String
val parent: Directory?
val size: Int
}
data class Directory(
override val name: String,
override val parent: Directory?,
override var size: Int = 0
): FileSystemEntry {
val children = mutableMapOf<String, FileSystemEntry>()
fun getSubDir(name: String): Directory =
children.get(name) as? Directory ?: throw IllegalArgumentException()
}
data class File(
override val name: String,
override val parent: Directory?,
override val size: Int
): FileSystemEntry {
}
}
fun main() {
fun parse(input: List<String>): FileSystem {
val fs = FileSystem()
for (line in input) {
if (line == "$ ls") {
continue
}
val subDir = line.substringAfter("$ cd ")
if (subDir != line) {
fs.cd(subDir)
continue
}
val (typeOrSize, name) = line.split(" ")
if (typeOrSize == "dir") {
fs.createDir(name)
} else {
fs.createFile(name, typeOrSize.toInt())
}
}
return fs
}
fun part1(input: List<String>): Int {
return parse(input).allDirectories.filter { it.size <= 100000 }.sumOf { it.size }
}
fun part2(input: List<String>): Int {
val fs = parse(input)
val sizeToDelete = fs.root.size - (70000000 - 30000000)
if (sizeToDelete <= 0) {
return 0
}
return parse(input).allDirectories.filter { it.size >= sizeToDelete }.minOf { it.size }
}
val testLines = readLines(true)
check(part1(testLines) == 95437)
check(part2(testLines) == 24933642)
val lines = readLines()
println(part1(lines))
println(part2(lines))
}
| 0 | Kotlin | 0 | 0 | cdba887c4df3a63c224d5a80073bcad12786ac71 | 2,825 | aoc-2022-in-kotlin | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/RestoreIPAddresses.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.HALF_OF_BYTE
/**
* 93. Restore IP Addresses
* @see <a href="https://leetcode.com/problems/restore-ip-addresses/">Source</a>
*/
fun interface RestoreIPAddresses {
operator fun invoke(s: String): List<String>
}
class RestoreIPAddressesDFS : RestoreIPAddresses {
override operator fun invoke(s: String): List<String> {
val solutions: MutableList<String> = ArrayList()
restoreIp(s, solutions, 0, "", 0)
return solutions
}
private fun restoreIp(ip: String, solutions: MutableList<String>, idx: Int, restored: String, count: Int) {
if (count > 4) return
if (count == 4 && idx == ip.length) solutions.add(restored)
for (i in 1..3) {
if (idx + i > ip.length) break
val s = ip.substring(idx, idx + i)
if (s.startsWith("0") && s.length > 1 || i == 3 && s.toInt() >= HALF_OF_BYTE) continue
restoreIp(ip, solutions, idx + i, restored + s + if (count == 3) "" else ".", count + 1)
}
}
}
class RestoreIPAddressesFast : RestoreIPAddresses {
override operator fun invoke(s: String): List<String> {
val ret: MutableList<String> = ArrayList()
val ip = StringBuffer()
for (a in 1..3) for (b in 1..3) for (c in 1..3) for (d in 1..3) {
if (a + b + c + d == s.length) {
val n1: Int = s.substring(0, a).toInt()
val n2: Int = s.substring(a, a + b).toInt()
val n3: Int = s.substring(a + b, a + b + c).toInt()
val n4: Int = s.substring(a + b + c).toInt()
if (n1 <= 255 && n2 <= 255 && n3 <= 255 && n4 <= 255) {
ip.append(n1).append('.').append(n2)
.append('.').append(n3).append('.').append(n4)
if (ip.length == s.length + 3) ret.add(ip.toString())
ip.delete(0, ip.length)
}
}
}
return ret
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 2,624 | kotlab | Apache License 2.0 |
src/main/kotlin/com/litekite/essentials/problems/matrix/DiagonalDiff.kt | svignesh93 | 400,829,980 | false | {"Java": 92174, "Kotlin": 41550} | /*
* Copyright 2022 LiteKite Startup. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.litekite.essentials.problems.matrix
import kotlin.math.abs
/**
* The function is expected to return an INTEGER.
* The function accepts 2D_INTEGER_ARRAY arr as parameter.
*/
fun diagonalDiff(arr: Array<Array<Int>>): Int {
// Write your code here
var primaryDiagonal = 0
var secondaryDiagonal = 0
for (i in arr.indices) {
println("primaryDiagonal: index: $i, val: ${arr[i][i]}")
primaryDiagonal += arr[i][i]
}
val reversedArray = arr.reversed()
for (i in reversedArray.indices) {
println("secondaryDiagonal: index: $i, val: ${reversedArray[i][i]}")
secondaryDiagonal += reversedArray[i][i]
}
return abs(primaryDiagonal - secondaryDiagonal)
}
/**
* Calculates the diagonal differences
*
* Size:
* n = 3
*
* 2D Array:
* 1 2 3
* 4 5 6
* 7 8 9
*
* First Diagonal - 1 5 9 = 15 total
* Second Diagonal - 7 5 3 = 15 total
* Difference = 0
*/
fun main() {
val n = readLine()!!.trim().toInt()
val arr: Array<Array<Int>> = Array(n) { Array(n) { 0 } }
for (i in 0 until n) {
arr[i] = readLine()!!.trimEnd().split(" ").map { it.toInt() }.toTypedArray()
}
val result = diagonalDiff(arr)
println("Diagonal difference: $result")
}
| 0 | Java | 0 | 2 | f8cf1d13b420c1d8ffbdfadd76fb11796298dbbf | 1,871 | Essentials | Apache License 2.0 |
Next_highest_int_from_digits/Kotlin/src/NextHighestIntFromDigits.kt | ncoe | 108,064,933 | false | {"D": 425100, "Java": 399306, "Visual Basic .NET": 343987, "C++": 328611, "C#": 289790, "C": 216950, "Kotlin": 162468, "Modula-2": 148295, "Groovy": 146721, "Lua": 139015, "Ruby": 84703, "LLVM": 58530, "Python": 46744, "Scala": 43213, "F#": 21133, "Perl": 13407, "JavaScript": 6729, "CSS": 453, "HTML": 409} | import java.math.BigInteger
import java.text.NumberFormat
fun main() {
for (s in arrayOf(
"0",
"9",
"12",
"21",
"12453",
"738440",
"45072010",
"95322020",
"9589776899767587796600",
"3345333"
)) {
println("${format(s)} -> ${format(next(s))}")
}
testAll("12345")
testAll("11122")
}
private val FORMAT = NumberFormat.getNumberInstance()
private fun format(s: String): String {
return FORMAT.format(BigInteger(s))
}
private fun testAll(str: String) {
var s = str
println("Test all permutations of: $s")
val sOrig = s
var sPrev = s
var count = 1
// Check permutation order. Each is greater than the last
var orderOk = true
val uniqueMap: MutableMap<String, Int> = HashMap()
uniqueMap[s] = 1
while (next(s).also { s = it }.compareTo("0") != 0) {
count++
if (s.toLong() < sPrev.toLong()) {
orderOk = false
}
uniqueMap.merge(s, 1) { a: Int?, b: Int? -> Integer.sum(a!!, b!!) }
sPrev = s
}
println(" Order: OK = $orderOk")
// Test last permutation
val reverse = StringBuilder(sOrig).reverse().toString()
println(" Last permutation: Actual = $sPrev, Expected = $reverse, OK = ${sPrev.compareTo(reverse) == 0}")
// Check permutations unique
var unique = true
for (key in uniqueMap.keys) {
if (uniqueMap[key]!! > 1) {
unique = false
}
}
println(" Permutations unique: OK = $unique")
// Check expected count.
val charMap: MutableMap<Char, Int> = HashMap()
for (c in sOrig.toCharArray()) {
charMap.merge(c, 1) { a: Int?, b: Int? -> Integer.sum(a!!, b!!) }
}
var permCount = factorial(sOrig.length.toLong())
for (c in charMap.keys) {
permCount /= factorial(charMap[c]!!.toLong())
}
println(" Permutation count: Actual = $count, Expected = $permCount, OK = ${count.toLong() == permCount}")
}
private fun factorial(n: Long): Long {
var fact: Long = 1
for (num in 2..n) {
fact *= num
}
return fact
}
private fun next(s: String): String {
val sb = StringBuilder()
var index = s.length - 1
// Scan right-to-left through the digits of the number until you find a digit with a larger digit somewhere to the right of it.
while (index > 0 && s[index - 1] >= s[index]) {
index--
}
// Reached beginning. No next number.
if (index == 0) {
return "0"
}
// Find digit on the right that is both more than it, and closest to it.
var index2 = index
for (i in index + 1 until s.length) {
if (s[i] < s[index2] && s[i] > s[index - 1]) {
index2 = i
}
}
// Found data, now build string
// Beginning of String
if (index > 1) {
sb.append(s.subSequence(0, index - 1))
}
// Append found, place next
sb.append(s[index2])
// Get remaining characters
val chars: MutableList<Char> = ArrayList()
chars.add(s[index - 1])
for (i in index until s.length) {
if (i != index2) {
chars.add(s[i])
}
}
// Order the digits to the right of this position, after the swap; lowest-to-highest, left-to-right.
chars.sort()
for (c in chars) {
sb.append(c)
}
return sb.toString()
}
| 0 | D | 0 | 4 | c2a9f154a5ae77eea2b34bbe5e0cc2248333e421 | 3,409 | rosetta | MIT License |
src/main/kotlin/adventofcode/year2022/Day10CathodeRayTube.kt | pfolta | 573,956,675 | false | {"Kotlin": 199554, "Dockerfile": 227} | package adventofcode.year2022
import adventofcode.Puzzle
import adventofcode.PuzzleInput
class Day10CathodeRayTube(customInput: PuzzleInput? = null) : Puzzle(customInput) {
override val name = "<NAME>"
private val instructionCycles by lazy { input.toInstructionCycles() }
override fun partOne() = instructionCycles
.filter { (cycle, _, _) -> cycle in setOf(20, 60, 100, 140, 180, 220) }
.sumOf { (cycle, _, x) -> cycle * x }
override fun partTwo() = instructionCycles
.map { (cycle, _, x) ->
val pixel = (cycle - 1) % SCREEN_WIDTH
val spritePosition = listOf(x - 1, x, x + 1)
spritePosition.contains(pixel)
}
.chunked(SCREEN_WIDTH)
.joinToString(separator = "\n", prefix = "\n", postfix = "\n") { row -> row.joinToString("") { cell -> if (cell) "█" else " " } }
companion object {
private const val SCREEN_WIDTH = 40
private fun String.toInstructionCycles() = lines()
.fold(listOf(Triple("", 0, 1))) { acc, instruction ->
val (_, _, xAfterPreviousCycle) = acc.last()
acc + when {
instruction.startsWith("addx ") -> listOf(
Triple("noop", xAfterPreviousCycle, xAfterPreviousCycle),
Triple(instruction, xAfterPreviousCycle, xAfterPreviousCycle + instruction.split(" ").last().toInt())
)
else -> listOf(Triple(instruction, xAfterPreviousCycle, xAfterPreviousCycle))
}
}
.mapIndexed { cycle, (instruction, xBeforeCycle, _) -> Triple(cycle, instruction, xBeforeCycle) }
.drop(1)
}
}
| 0 | Kotlin | 0 | 0 | 72492c6a7d0c939b2388e13ffdcbf12b5a1cb838 | 1,728 | AdventOfCode | MIT License |
aoc2022/day20.kt | davidfpc | 726,214,677 | false | {"Kotlin": 127212} | package aoc2022
import utils.InputRetrieval
import kotlin.math.abs
fun main() {
Day20.execute()
}
object Day20 {
fun execute() {
val input = readInput()
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
private fun part1(input: List<FileNumber>): Long {
val mappedInput = input.toMutableList()
mappedInput.mixElements(input)
return mappedInput.getFinalResult()
}
private fun part2(input: List<FileNumber>, decryptionKey: Int = 811589153): Long {
input.forEach { it.value *= decryptionKey }
val mappedInput = input.toMutableList()
repeat(10) {
mappedInput.mixElements(input)
}
return mappedInput.getFinalResult()
}
/**
* Add the initial position to provide uniqueness to the value and data class
*/
data class FileNumber(val initialPos: Int, var value: Long)
private fun MutableList<FileNumber>.getFinalResult(finalPositionsToSum: Set<Int> = setOf(1_000, 2_000, 3_000)): Long {
val finalInput = this.map { it.value }.toList()
val zeroPosIndex = finalInput.indexOfFirst { it == 0L }
return finalPositionsToSum.sumOf { finalInput[(it + zeroPosIndex) % finalInput.size] }
}
private fun MutableList<FileNumber>.mixElements(input: List<FileNumber>) {
input.forEach {
val valueIndex = this.indexOf(it)
this.remove(it)
val tmpPos = valueIndex + it.value
val newPos = if (tmpPos > 0) {
tmpPos % this.size
} else if (tmpPos < 0) {
((tmpPos + ((abs(it.value) / this.size) + 1) * this.size) % this.size)
} else {
this.size
}
this.add(newPos.toInt(), it)
}
}
fun readInput(): List<FileNumber> = InputRetrieval.getFile(2022, 20).readLines().mapIndexed { index, it -> FileNumber(index, it.toLong()) }
}
| 0 | Kotlin | 0 | 0 | 8dacf809ab3f6d06ed73117fde96c81b6d81464b | 1,971 | Advent-Of-Code | MIT License |
src/Day04.kt | Hwajun1323 | 574,962,608 | false | {"Kotlin": 6799} | fun main() {
fun convertToSection(Elf: String): IntRange {
val (start, end) = Elf.split("-")
return start.toInt()..end.toInt()
}
fun checkContain(firstSection: IntRange, secondSection: IntRange): Boolean{
return (firstSection.first >= secondSection.first && firstSection.last <= secondSection.last)
}
fun part1(input: List<String>): Int {
return input.count {
val (firstElf, secondElf) = it.split(",")
checkContain(convertToSection(firstElf),convertToSection(secondElf))
|| checkContain(convertToSection(secondElf), convertToSection(firstElf))
}
}
// fun part2(input: List<String>): Int {
// return input.count{
// }
// }
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day04_test")
val input = readInput("Day04")
println(part1(input))
// println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 667a8c7a0220bc10ddfc86b74e3e6de44b73d5dd | 964 | advent-of-code-2022 | Apache License 2.0 |
aoc/src/Calibration.kt | aragos | 726,211,893 | false | {"Kotlin": 16232} | import java.io.File
fun main() {
println(Calibration.readCalibrationDigitsAndWords("aoc/inputs/calibration.txt").sum())
}
object Calibration {
fun readCalibrationDigits(): List<Int> = buildList {
File("aoc/inputs/calibration.txt").forEachLine { line ->
val allDigits = Regex("[1-9]").findAll(line).map { it.value }
val twoDigits = (allDigits.first() + allDigits.last()).toInt()
add(twoDigits)
}
}
fun readCalibrationDigitsAndWords(fileLocation: String): List<Int> = buildList {
File(fileLocation).forEachLine { line ->
add(digitAndWordLineToNumber(line))
}
}
fun digitAndWordLineToNumber(line: String): Int {
val allDigits = Regex("(?=([1-9]|one|two|three|four|five|six|seven|eight|nine)).")
.findAll(line)
.mapNotNull { it.groups[1]?.value }
.map(::numberToDigit)
.toList()
return (allDigits.first() + allDigits.last()).toInt()
}
private fun numberToDigit(number: String) = when (number) {
// No zeros here!
"one" -> "1"
"two" -> "2"
"three" -> "3"
"four" -> "4"
"five" -> "5"
"six" -> "6"
"seven" -> "7"
"eight" -> "8"
"nine" -> "9"
else -> number
}
}
| 0 | Kotlin | 0 | 0 | 7bca0a857ea42d89435adc658c0ff55207ca374a | 1,195 | aoc2023 | Apache License 2.0 |
src/Day01.kt | Akaneiro | 572,883,913 | false | null | fun main() {
fun getElvesCalSums(input: List<String>): List<Int> =
mutableListOf<Int>().apply {
var currentCalSum = 0
input.forEachIndexed { index, element ->
when {
element.isBlank() -> {
this.add(currentCalSum)
currentCalSum = 0
}
index == input.size - 1 -> {
currentCalSum += element.toInt()
this.add(currentCalSum)
}
else -> currentCalSum += element.toInt()
}
}
}
fun part1(input: List<String>): Int = getElvesCalSums(input).max()
fun part2(input: List<String>): Int = getElvesCalSums(input).sorted().takeLast(3).sum()
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f987830a70a2a1d9b88696271ef668ba2445331f | 1,102 | aoc-2022 | Apache License 2.0 |
src/day09/Day09.kt | zypus | 573,178,215 | false | {"Kotlin": 33417, "Shell": 3190} | package day09
import AoCTask
import kotlin.math.abs
import kotlin.math.sign
// https://adventofcode.com/2022/day/9
data class Direction(val x: Int, val y: Int) {
companion object {
fun fromString(string: String): Direction {
val (dir, dist) = string.split(" ")
val intDist = dist.toInt()
return when (dir) {
"R" -> Direction(intDist, 0)
"L" -> Direction(-intDist, 0)
"U" -> Direction(0, intDist)
"D" -> Direction(0, -intDist)
else -> throw Exception("Should not happen")
}
}
}
val length = maxOf(abs(x), abs(y))
fun normalized(): Direction {
return Direction(x.sign, y.sign)
}
override fun toString(): String {
return "($x, $y)->"
}
}
data class Position(val x: Int, val y: Int) {
override fun toString(): String {
return "($x, $y)"
}
}
operator fun Position.plus(direction: Direction) = Position(x + direction.x, y + direction.y)
operator fun Position.minus(other: Position) = Direction(x - other.x, y - other.y)
// H
// TH .
// T..H T. H.T
//
private fun headPath(
dir: Direction,
head: Position
): List<Position> {
val step = dir.normalized()
return (1..dir.length).scan(head) { currentHead, _ ->
currentHead + step
}
}
private fun tailPathFromHeadPath(
path: List<Position>,
tail: Position
): List<Position> {
val tailPath = path.filterIndexed { index, position ->
if (index < path.size - 1) {
(tail - position).length > 1 || (tail - path[index + 1]).length > 1
} else {
false
}
}
return tailPath
}
private fun path(from: Position, to: Position): List<Position> {
var delta = to - from
val path = mutableListOf(from)
while (delta.x != 0 || delta.y != 0) {
val dirX = delta.x.sign
val dirY = delta.y.sign
path.add(path.last() + Direction(dirX, dirY))
delta = Direction(delta.x - dirX, delta.y - dirY)
}
return path
}
fun testPaths() {
val tail = Position(0,0)
// check same starting point distance 1
check(tailPathFromHeadPath(headPath(Direction(1, 0), Position(0,0)), tail).size == 0) {
"Same starting point, R 1 doesn't work"
}
check(tailPathFromHeadPath(headPath(Direction(-1, 0), Position(0,0)), tail).size == 0) {
"Same starting point, L 1 doesn't work"
}
check(tailPathFromHeadPath(headPath(Direction(0, 1), Position(0,0)), tail).size == 0) {
"Same starting point, U 1 doesn't work"
}
check(tailPathFromHeadPath(headPath(Direction(0, -1), Position(0,0)), tail).size == 0) {
"Same starting point, D 1 doesn't work"
}
// check same starting point distance 2
check(tailPathFromHeadPath(headPath(Direction(2, 0), Position(0,0)), tail).size == 1) {
"Same starting point, R 2 doesn't work"
}
check(tailPathFromHeadPath(headPath(Direction(-2, 0), Position(0,0)), tail).size == 1) {
"Same starting point, L 2 doesn't work"
}
check(tailPathFromHeadPath(headPath(Direction(0, 2), Position(0,0)), tail).size == 1) {
"Same starting point, U 2 doesn't work"
}
check(tailPathFromHeadPath(headPath(Direction(0, -2), Position(0,0)), tail).size == 1) {
"Same starting point, D 2 doesn't work"
}
}
fun drawRope(segments: List<Position>, drawOnlyHashes: Boolean = false) {
val minX = segments.minOf { it.x }
val minY = segments.minOf { it.y }
val maxX = segments.maxOf { it.x }
val maxY = segments.maxOf { it.y }
(maxY downTo minY).forEach { y ->
(minX..maxX).forEach { x ->
val index = segments.indexOfFirst { it.x == x && it.y == y }
val symbol = when (index) {
-1 -> "."
0 -> if (drawOnlyHashes) "#" else "H"
else -> if (drawOnlyHashes) "#" else index
}
print(symbol)
}
println()
}
}
fun part1(input: List<String>): Int {
val directions = input.map { Direction.fromString(it) }
var head = Position(0, 0)
var tail = Position(0, 0)
val visitedPositions = mutableSetOf(tail)
directions.forEach {dir ->
val path = headPath(dir, head)
head = path.last()
val tailPath = tailPathFromHeadPath(path, tail)
// println(dir)
// println("Head: $path")
// println("Tail: $tailPath")
tail = tailPath.lastOrNull() ?: tail
visitedPositions.addAll(tailPath)
}
return visitedPositions.size
}
fun part2(input: List<String>): Int {
val directions = input.map { Direction.fromString(it) }
val ropeLength = 10
val rope = MutableList(ropeLength) { Position(0,0) }
val visitedPositions = mutableSetOf(rope.first())
directions.forEach {dir ->
val step = dir.normalized()
repeat(dir.length) {
var previousSegmentPosition = rope.first()
rope.forEachIndexed { index, segment ->
val newPosition = if (index == 0) {
segment + step
} else {
if ((rope[index - 1] - segment).length > 1) {
path(segment, rope[index - 1]).dropLast(1).last()
} else {
segment
}
}
if (index == rope.size - 1) {
visitedPositions.add(newPosition)
}
previousSegmentPosition = segment
rope[index] = newPosition
}
}
// println()
// drawRope(rope)
}
// drawRope(visitedPositions.toList(), true)
return visitedPositions.size
}
fun main() = AoCTask("day09").run {
testPaths()
// test if implementation meets criteria from the description, like:
check(part1(testInput) == 13)
check(part2(testInput) == 1)
check(part2(readTestInput(2)) == 36)
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f37ed8e9ff028e736e4c205aef5ddace4dc73bfc | 6,110 | aoc-2022 | Apache License 2.0 |
src/main/kotlin/days/aoc2023/Day22.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2023
import days.Day
import kotlin.math.min
import util.Point3d
import util.toward
class Day22 : Day(2023, 22) {
override fun partOne(): Any {
return calculatePartOne(inputList)
}
override fun partTwo(): Any {
return calculatePartTwo(inputList)
}
class Brick(private val xRange: IntProgression, private val yRange: IntProgression, var zRange: IntProgression): Cloneable {
public override fun clone(): Any {
return Brick(xRange, yRange, zRange)
}
fun fall() {
zRange = (zRange.min() - 1) .. (zRange.max() - 1)
}
fun canFall(otherBricks: List<Brick>): Boolean {
return zRange.min() > 1 && supportingBricks(otherBricks).isEmpty()
}
fun supportingBricks(otherBricks: List<Brick>): List<Brick> {
val supportingBricks = mutableSetOf<Brick>()
// see if we're on the ground
if (zRange.min() == 1) {
return emptyList()
}
supportingBricks.addAll(otherBricks.filter { ((zRange.min() - 1) == it.zRange.max()) && ((xRange intersect it.xRange).isNotEmpty() && (yRange intersect it.yRange).isNotEmpty()) })
return supportingBricks.toList()
}
fun isOnlySupportingBrick(otherBricks: List<Brick>): Boolean {
return otherBricks.filter { it.zRange.min() == (zRange.max() + 1) }.any {
val supportingBricks = it.supportingBricks(otherBricks.plus(this).minus(it))
supportingBricks.contains(this) && supportingBricks.size == 1
}
}
// a brick can be disintegrated if it is not the only supporting brick
// for any other brick
fun canBeDisintegrated(otherBricks: List<Brick>): Boolean {
return !isOnlySupportingBrick(otherBricks)
}
}
fun calculatePartOne(input: List<String>): Int {
val bricks = input.map { line ->
Regex("(\\d),(\\d),(\\d+)~(\\d),(\\d),(\\d+)").matchEntire(line)?.destructured?.let {(x1, y1, z1, x2, y2, z2) ->
Brick(x1.toInt() toward x2.toInt(), y1.toInt() toward y2.toInt(), z1.toInt() toward z2.toInt())
} ?: throw IllegalStateException("input wrong")
}.sortedBy { it.zRange.min() }
letBricksFall(bricks)
return bricks.count { it.canBeDisintegrated(bricks.minus(it)) }
}
private fun letBricksFall(bricks: List<Brick>): Int {
var bricksFell = true
val bricksThatFell = mutableSetOf<Brick>()
while (bricksFell) {
bricksFell = false
bricks.filter { it.canFall(bricks.minus(it)) }.forEach {
it.fall()
bricksThatFell.add(it)
bricksFell = true
}
}
return bricksThatFell.size
}
fun calculatePartTwo(input: List<String>): Int {
val bricks = input.map { line ->
Regex("(\\d),(\\d),(\\d+)~(\\d),(\\d),(\\d+)").matchEntire(line)?.destructured?.let {(x1, y1, z1, x2, y2, z2) ->
Brick(x1.toInt() toward x2.toInt(), y1.toInt() toward y2.toInt(), z1.toInt() toward z2.toInt())
} ?: throw IllegalStateException("input wrong")
}.sortedBy { it.zRange.min() }
letBricksFall(bricks)
var sum = 0
bricks.forEachIndexed { i, _ ->
val newStack = bricks.map { it.clone() as Brick }
val bricksThatFell = letBricksFall(newStack.minus(newStack[i]))
sum += bricksThatFell
println("$bricksThatFell bricks fell after removing number $i, making $sum so far")
}
return sum
}
} | 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 3,689 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
core/algorithm/src/main/java/com/memorati/algorithm/Algorithm.kt | HeidelX | 640,943,698 | false | {"Kotlin": 321291, "Ruby": 1925} | package com.memorati.algorithm
import com.memorati.core.model.AdditionalInfo
import com.memorati.core.model.Flashcard
import kotlinx.datetime.Clock
import kotlin.math.ln
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.minutes
fun Flashcard.review(
answerCorrect: Boolean,
wordCorrectnessCount: Int,
weeksOfReview: Int,
): Flashcard {
val flashcard = handleReviewResponse(answerCorrect)
return if (flashcard.additionalInfo.consecutiveCorrectCount >= wordCorrectnessCount) {
flashcard.copy(
nextReviewAt = lastReviewAt.plus(weeksOfReview.times(7).days),
)
} else {
flashcard.scheduleNextReview()
}
}
internal fun Flashcard.scheduleNextReview(): Flashcard {
val adaptiveInterval = calculateAdaptiveInterval(
additionalInfo.difficulty,
additionalInfo.consecutiveCorrectCount,
)
val timeWeightedInterval =
calculateTimeWeightedInterval(additionalInfo.memoryStrength)
// Choose the shorter interval between adaptive and time-weighted intervals.
val nextReviewInterval = maxOf(adaptiveInterval, timeWeightedInterval).minutes
// Calculate the next review date by adding the interval to the last review date.
return copy(
nextReviewAt = lastReviewAt.plus(nextReviewInterval),
)
}
internal fun Flashcard.handleReviewResponse(
isCorrect: Boolean,
): Flashcard {
val (difficulty, consecutiveCorrectCount) = if (isCorrect) {
// Increase difficulty for correct responses
additionalInfo.difficulty * 1.1 to (additionalInfo.consecutiveCorrectCount + 1)
} else {
// Decrease difficulty for incorrect responses
additionalInfo.difficulty * 0.9 to 0
}
return copy(
additionalInfo = AdditionalInfo(
difficulty = difficulty,
consecutiveCorrectCount = consecutiveCorrectCount,
// Apply decay to memory strength over time
memoryStrength = additionalInfo.memoryStrength * 0.95,
),
lastReviewAt = Clock.System.now(),
)
}
private fun calculateAdaptiveInterval(difficulty: Double, consecutiveCorrectCount: Int): Long {
// Adjust the base interval based on the flashcard's difficulty
val baseInterval = 1000 // Base interval in milliseconds
val adjustedInterval = baseInterval * difficulty
// Apply a multiplier based on the consecutive correct count
val multiplier = when (consecutiveCorrectCount) {
0 -> 0.5 // If no consecutive correct answers, decrease the interval by half
1 -> 1.0 // If 1 consecutive correct answer, maintain the same interval
else -> 1.5 // If more than 1 consecutive correct answer, increase the interval by 50%
}
// Calculate the final adaptive interval by multiplying the adjusted interval with the multiplier
return (adjustedInterval * multiplier).toLong()
}
private fun calculateTimeWeightedInterval(memoryStrength: Double): Long {
// Set the base interval based on the desired initial review interval
val baseInterval = 2000 // Base interval in milliseconds
// Set the decay factor based on how quickly you want the memory strength to decay over time
val decayFactor = 0.9 // Adjust this value based on your preference
// Calculate the time-weighted interval using logarithmic decay
return (baseInterval * (1 - ln(memoryStrength) / ln(decayFactor))).toLong()
}
| 1 | Kotlin | 0 | 0 | e848ec96866f16c283c6be1e871c2e9e0c47bd98 | 3,439 | Memorati | MIT License |
src/main/kotlin/recur/FindInKArr.kt | yx-z | 106,589,674 | false | null | package recur
import util.INF
import util.OneArray
import util.oneArrayOf
// given k SORTED arrays A1, A2,... Ak, w/ a total of n distinct numbers
// and another number x, find the smallest number y : y > x in these arrays
fun OneArray<OneArray<Int>>.find(x: Int): Int {
val A = this
val k = size
val n = map { size }.sum()
// find the closest number in each array w/ binary search
// now we have k numbers, traverse through them to find the best one
return A.map { it.binSearch(x) }.min() ?: -1
// let si represent the size of the i-th array
// then s1 + s2 + s3 + ... + sk = n
// and we will spend log(s1) + log(s2) + ... + log(sk) time
// since si < n for all i, it is at most O(k log n)
// finally, we will do O(k) work to find the best one
// therefore the total time would be O(k log n + k) = O (k log n)
}
// variant of binary search that returns the smallest number larger than x
// in this sorted array A of size n
fun OneArray<Int>.binSearch(x: Int): Int {
val A = this
val n = size
var l = 1
var h = n
while (l < h) {
val m = l + (h - l) / 2
if (A[m] == x) {
return A[m]
}
if (A[m] > x) {
h = m - 1
} else { // A[m] < x
l = m + 1
}
}
return if (A[h] > x) A[h] else INF
}
fun main(args: Array<String>) {
val A = oneArrayOf(
oneArrayOf(1, 5, 9, 10, 20),
oneArrayOf(3, 23, 25, 30),
oneArrayOf(11, 15, 22)
)
println(A.find(17)) // should find 20
} | 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 1,417 | AlgoKt | MIT License |
Kotlin/days/src/day4.kt | dukemarty | 224,307,841 | false | null | const val puzzleInputDay4 = "273025-767253"
data class PasswordRange(val range: String) {
val lowerBound: Int
val upperBound: Int
init {
val parts = range.split("-")
lowerBound = parts[0].toInt()
upperBound = parts[1].toInt()
}
}
fun main(args: Array<String>) {
println("--- Day 3: Crossed Wires ---");
val range = PasswordRange(puzzleInputDay4)
genericPart("One", ::checkPasswordValidityPart1, range)
genericPart("Two", ::checkPasswordValidityPart2, range)
}
fun genericPart(part: String, checker: (String) -> Boolean, passwordRange: PasswordRange) {
println("\n--- Part $part ---");
var count = 0
for (i in IntRange(passwordRange.lowerBound, passwordRange.upperBound)) {
if (checker(i.toString())) {
++count
}
}
println("Found number of valid passwords: $count")
}
private fun checkPasswordValidityPart1(candidate: String): Boolean {
var doubleFound = false
for (i in IntRange(1, 5)) {
if (candidate[i].toInt() < candidate[i - 1].toInt()) {
return false
}
if (candidate[i] == candidate[i - 1]) {
doubleFound = true
}
}
return doubleFound
}
private fun checkPasswordValidityPart2(candidate: String): Boolean {
var doubleFound = false
var matchCount = 1
for (i in IntRange(1, 5)) {
if (candidate[i].toInt() < candidate[i - 1].toInt()) {
return false
}
if (candidate[i] == candidate[i - 1]) {
++matchCount
} else {
if (matchCount == 2) {
doubleFound = true
}
matchCount = 1
}
}
if (matchCount == 2) {
doubleFound = true
}
return doubleFound
}
| 0 | Kotlin | 0 | 0 | 6af89b0440cc1d0cc3f07d5a62559aeb68e4511a | 1,787 | dukesaoc2019 | MIT License |
2021/kotlin/src/main/kotlin/com/pietromaggi/aoc2021/day25/Day25.kt | pfmaggi | 438,378,048 | false | {"Kotlin": 113883, "Zig": 18220, "C": 7779, "Go": 4059, "CMake": 386, "Awk": 184} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pietromaggi.aoc2021.day25
import com.pietromaggi.aoc2021.readInput
data class Point(val x: Int, val y: Int)
fun parse(input: List<String>): Map<Point, Char> {
val n = input.size
val m = input[0].length
val status = buildMap {
for (i in 0 until n) for (j in 0 until m) {
val c = input[i][j]
if ((c == '>') or (c == 'v')) {
this[Point(i, j)] = c
}
}
}
return status
}
fun doStep(status: Map<Point, Char>, n: Int, m: Int): Pair<Map<Point, Char>, Boolean> {
var updated = false
val newStatus = mutableMapOf<Point, Char>()
for ((point, c) in status) {
var (x, y) = point
if (c == '>') {
y = (point.y + 1) % m
}
val newPoint = Point(x, y)
if (status.containsKey(newPoint)) {
newStatus[point] = c
} else {
newStatus[newPoint] = c
updated = true
}
}
val finalStatus = mutableMapOf<Point, Char>()
for ((point, c) in newStatus) {
var (x, y) = point
if (c == 'v') {
x = (point.x + 1) % n
}
val newPoint = Point(x, y)
if (newStatus.containsKey(newPoint)) {
finalStatus[point] = c
} else {
finalStatus[newPoint] = c
updated = true
}
}
return Pair(finalStatus, updated)
}
fun part1(input: List<String>): Int {
var status = parse(input)
val n = input.size
val m = input[0].length
var count = 0
var updated = true
while (updated) {
count++
doStep(status, n, m).let {
status = it.first
updated = it.second
}
}
return count
}
fun main() {
val input = readInput("Day25")
println("""
### DAY 25 ###
==============
What is the first step on which no sea cucumbers move?
--> ${part1(input)}
""")
} | 0 | Kotlin | 0 | 0 | 7c4946b6a161fb08a02e10e99055a7168a3a795e | 2,534 | AdventOfCode | Apache License 2.0 |
solutions/src/solutions/y21/day 16.kt | Kroppeb | 225,582,260 | false | null | @file:Suppress("PackageDirectoryMismatch", "UnusedImport")
package solutions.y21.d16
/*
import grid.Clock
import helpers.*
import itertools.*
import kotlin.math.*
*/
import grid.Clock
import helpers.getLines
val xxxxx = Clock(6, 3);
/*
*/
data class Parsed<T>(val t: T, val remaining: List<Int>) {
fun <R> map(p: (T) -> R): Parsed<R> {
return Parsed(p(t), remaining)
}
}
var versions = 0L
fun parseInt(data: List<Int>, length: Int): Long {
var x = 0L;
repeat(length) {
x = x * 2 + data[it]
}
return x;
}
fun parse(data: List<Int>): Parsed<Long> {
data.map { it.toString() }.joinToString("")/*.log()*/
val version = data[0] * 4 + data[1] * 2 + data[2]
versions += version/*.log()*/
val opcode = data[3] * 4 + data[4] * 2 + data[5]
when (opcode/*.log()*/) {
4 -> {
var i = 6
var res = 0L
while (data[i] != 0) {
var section = data[i + 1] * 8 + data[i + 2] * 4 + data[i + 3] * 2 + data[i + 4]
i += 5
res = res * 16L + section
}
var section = data[i + 1] * 8 + data[i + 2] * 4 + data[i + 3] * 2 + data[i + 4]
i += 5
res = res * 16L + section
//res.log()
return Parsed(res, data.subList(i, data.size))
}
0 ->
return parseSub(data.subList(6, data.size)).map { it.sum() }
1 ->
return parseSub(data.subList(6, data.size)).map { it.fold(1L, Long::times) }
2 ->
return parseSub(data.subList(6, data.size)).map { it.minOrNull()!! }
3 ->
return parseSub(data.subList(6, data.size)).map { it.maxOrNull()!! }
5 ->
return parseSub(data.subList(6, data.size)).map { (a, b) -> if (a > b) 1 else 0 }
6 ->
return parseSub(data.subList(6, data.size)).map { (a, b) -> if (a < b) 1 else 0 }
7 ->
return parseSub(data.subList(6, data.size)).map { (a, b) -> if (a == b) 1 else 0 }
else -> error("Unknown opcode $opcode")
}
}
fun parseSub(data: List<Int>): Parsed<List<Long>> {
if (data[0] == 0) {
val size = parseInt(data.subList(1, data.size), 15)
var d = data.subList(16, data.size)
var remainingSize = d.size - size
val list = mutableListOf<Long>()
while (d.size > remainingSize) {
var (t, remaining) = parse(d)
d = remaining;
list.add(t)
}
return Parsed(list, d)
} else {
var count = parseInt(data.subList(1, data.size), 11)
var d = data.subList(12, data.size)
val list = mutableListOf<Long>()
repeat(count.toInt()) {
var (t, remaining) = parse(d)
d = remaining
list.add(t)
}
return Parsed(list, d)
}
}
private fun parts() {
var data = getLines(2021_16).first().flatMap {
when (it) {
'0' -> listOf(0, 0, 0, 0)
'1' -> listOf(0, 0, 0, 1)
'2' -> listOf(0, 0, 1, 0)
'3' -> listOf(0, 0, 1, 1)
'4' -> listOf(0, 1, 0, 0)
'5' -> listOf(0, 1, 0, 1)
'6' -> listOf(0, 1, 1, 0)
'7' -> listOf(0, 1, 1, 1)
'8' -> listOf(1, 0, 0, 0)
'9' -> listOf(1, 0, 0, 1)
'A' -> listOf(1, 0, 1, 0)
'B' -> listOf(1, 0, 1, 1)
'C' -> listOf(1, 1, 0, 0)
'D' -> listOf(1, 1, 0, 1)
'E' -> listOf(1, 1, 1, 0)
'F' -> listOf(1, 1, 1, 1)
else -> error(it)
}
}
//data.map{ it.toString() }.joinToString("").log()
var parsed = parse(data)
println(versions)
println(parsed.t)
}
fun main() {
println("Day 16: ")
parts()
}
fun <T> T.log(): T = also { println(this) } | 0 | Kotlin | 0 | 1 | 744b02b4acd5c6799654be998a98c9baeaa25a79 | 3,844 | AdventOfCodeSolutions | MIT License |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MissingRanges.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
// Missing Ranges
class MissingRanges {
fun findMissingRanges(nums: IntArray, lower: Int, upper: Int): List<String> {
val n = nums.size
if (n == 0) {
return listOf(formatRange(lower, upper))
}
val missingRanges: MutableList<String> = ArrayList()
// Edge case 1) Missing ranges at the beginning
if (nums[0] > lower) {
missingRanges.add(formatRange(lower, nums[0] - 1))
}
// Missing ranges between array elements
for (i in 1 until n) {
if (nums[i] - nums[i - 1] > 1) {
missingRanges.add(formatRange(nums[i - 1] + 1, nums[i] - 1))
}
}
// Edge case 2) Missing ranges at the end
if (nums[n - 1] < upper) {
missingRanges.add(formatRange(nums[n - 1] + 1, upper))
}
return missingRanges
}
// formats range in the requested format
private fun formatRange(lower: Int, upper: Int): String {
return if (lower == upper) {
lower.toString()
} else {
"$lower->$upper"
}
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,761 | kotlab | Apache License 2.0 |
src/Day09_part1.kt | jmorozov | 573,077,620 | false | {"Kotlin": 31919} | import kotlin.math.absoluteValue
fun main() {
val inputData = readInput("Day09")
part1(inputData)
}
private fun part1(inputData: List<String>) {
val visitedByTail = mutableSetOf<Point>()
val startPoint = Point.start()
visitedByTail.add(startPoint)
var state = RopeState(
head = startPoint,
tail = startPoint
)
for (line in inputData) {
val (direction, steps) = parseMovement(line) ?: continue
state = when (direction) {
"L" -> goLeft(state, visitedByTail, steps)
"R" -> goRight(state, visitedByTail, steps)
"U" -> goUp(state, visitedByTail, steps)
"D" -> goDown(state, visitedByTail, steps)
else -> state
}
}
println("Positions, which the tail of the rope visit at least once: ${visitedByTail.size}")
}
private data class RopeState(
val head: Point,
val tail: Point
)
private fun goLeft(currentState: RopeState, visitedByTail: MutableSet<Point>, steps: Int): RopeState {
var newState = currentState
for (step in 1..steps) {
val head = newState.head.left()
var tail = newState.tail
if ((tail.x - head.x).absoluteValue > 1) {
tail = if (head.y == tail.y) {
tail.left()
} else {
if (head.y > tail.y) {
tail.up().left()
} else {
tail.down().left()
}
}
visitedByTail.add(tail)
}
newState = RopeState(head, tail)
}
return newState
}
private fun goRight(currentState: RopeState, visitedByTail: MutableSet<Point>, steps: Int): RopeState {
var newState = currentState
for (step in 1..steps) {
val head = newState.head.right()
var tail = newState.tail
if ((tail.x - head.x).absoluteValue > 1) {
tail = if (head.y == tail.y) {
tail.right()
} else {
if (head.y > tail.y) {
tail.up().right()
} else {
tail.down().right()
}
}
visitedByTail.add(tail)
}
newState = RopeState(head, tail)
}
return newState
}
private fun goUp(currentState: RopeState, visitedByTail: MutableSet<Point>, steps: Int): RopeState {
var newState = currentState
for (step in 1..steps) {
val head = newState.head.up()
var tail = newState.tail
if ((tail.y - head.y).absoluteValue > 1) {
tail = if (head.x == tail.x) {
tail.up()
} else {
if (head.x > tail.x) {
tail.right().up()
} else {
tail.left().up()
}
}
visitedByTail.add(tail)
}
newState = RopeState(head, tail)
}
return newState
}
private fun goDown(currentState: RopeState, visitedByTail: MutableSet<Point>, steps: Int): RopeState {
var newState = currentState
for (step in 1..steps) {
val head = newState.head.down()
var tail = newState.tail
if ((tail.y - head.y).absoluteValue > 1) {
tail = if (head.x == tail.x) {
tail.down()
} else {
if (head.x > tail.x) {
tail.right().down()
} else {
tail.left().down()
}
}
visitedByTail.add(tail)
}
newState = RopeState(head, tail)
}
return newState
}
| 0 | Kotlin | 0 | 0 | 480a98838949dbc7b5b7e84acf24f30db644f7b7 | 3,616 | aoc-2022-in-kotlin | Apache License 2.0 |
src/Day17.kt | Allagash | 572,736,443 | false | {"Kotlin": 101198} | import java.io.File
import kotlin.math.max
// Advent of Code 2022, Day 17, Pyroclastic Flow
interface Rock {
val rows: List<String> // 4 strings, 4 char long
val height: Int
val width: Int
}
class Rock1 : Rock {
// maybe reverse list?
override val rows = listOf("....", "....", "....", "####").reversed()
override val height = 1
override val width = 4
}
class Rock2 : Rock {
override val rows = listOf("....", ".#..", "###.", ".#..").reversed()
override val height = 3
override val width = 3
}
class Rock3 : Rock {
override val rows = listOf("....", "..#.", "..#.", "###.").reversed()
override val height = 3
override val width = 3
}
class Rock4 : Rock {
override val rows = listOf("#...", "#...", "#...", "#...").reversed()
override val height = 4
override val width = 1
}
class Rock5 : Rock {
override val rows = listOf("....", "....", "##..", "##..").reversed()
override val height = 2
override val width = 2
}
data class Offset(val x: Int, val y: Int)
data class Point(val x: Long, val y: Long)
data class Day17CacheItem(val rockIdx: Long, val moveIdx: Long, val yHeight: ULongArray) {
@OptIn(ExperimentalUnsignedTypes::class)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Day17CacheItem
if (rockIdx != other.rockIdx) return false
if (moveIdx != other.moveIdx) return false
if (!yHeight.contentEquals(other.yHeight)) return false
return true
}
@OptIn(ExperimentalUnsignedTypes::class)
override fun hashCode(): Int {
var result = rockIdx
result = 31 * result + moveIdx
result = 31 * result + yHeight.contentHashCode()
return result.toInt()
}
}
val shapes = listOf(Rock1(), Rock2(), Rock3(), Rock4(), Rock5())
fun main() {
fun readInputAsOneLine(name: String) = File("src", "$name.txt").readText().trim()
fun intersect(pt: Offset, rock: Rock, world: Array<CharArray>): Boolean {
if (pt.x < 0 || pt.y < 0 || pt.x + rock.width > 7) return true
for (y in rock.rows.indices) {
for (x in rock.rows[y].indices) {
if (rock.rows[y][x] != '#') continue
val worldPt = world[pt.y + y][pt.x + x]
if (worldPt != ' ' && worldPt != '.') {
return true
}
}
}
return false
}
fun printWorld(highestY: Int, world: Array<CharArray>) {
for (y in highestY + 4 downTo 0) {
print('|')
print(world[y])
println('|')
}
println("+-------+")
}
fun part1(input: String): Int {
val world = Array(2022 * 4 + 10) { CharArray(7) {' '} }
var highestY = -1
var moveIdx = -1
repeat(2022) {i ->
val rock = shapes[i % shapes.size]
var pt = Offset(2, highestY + 4)
while (true) {
moveIdx = (moveIdx+1) % input.length
val push = if (input[moveIdx] == '<') -1 else 1
var nextPt = Offset(pt.x + push, pt.y)
if (!intersect(nextPt, rock, world)) {
pt = nextPt
}
nextPt = Offset(pt.x, pt.y - 1)
if (intersect(nextPt, rock, world)) {
break
}
pt = nextPt
}
// freeze it
for (y in rock.rows.indices) {
for (x in rock.rows[y].indices) {
if (rock.rows[y][x] != '#') continue
world[pt.y + y][pt.x + x] = rock.rows[y][x]
}
}
highestY = max(highestY, pt.y + rock.height - 1)
}
//printWorld(highestY, world)
return highestY + 1
}
class Day17(input: String) {
val jets = input
val rock0 = listOf(Point(0, 0), Point(1, 0), Point(2, 0), Point(3, 0))
val rock1 = listOf(Point(1, 0), Point(0, 1), Point(1, 1), Point(2, 1), Point(1, 2))
val rock2 = listOf(Point(0, 0), Point(1, 0), Point(2, 0), Point(2, 1), Point(2,2))
val rock3 = listOf(Point(0, 0), Point(0, 1), Point(0, 2), Point(0, 3))
val rock4 = listOf(Point(0, 0), Point(1, 0), Point(0, 1), Point(1, 1))
val rocks = listOf(rock0, rock1, rock2, rock3, rock4)
fun printWorld(highestY: Long, world: Set<Point>) {
for (y in highestY + 4 downTo 0L) {
print('|')
for (x in 0L..6L) {
val c = if (Point(x, y) in world) '#' else '.'
print(c)
}
println('|')
}
println("+-------+\n")
}
fun intersect(pt: Point, rock: List<Point>, world: Set<Point>): Boolean {
rock.forEach {
val x = it.x + pt.x
val y = it.y + pt.y
if (x < 0 || y < 0 || x >= 7) return true // >= 7 or just >?
if (Point(x,y) in world) return true
}
return false
}
fun getCacheItem(rockIdx: Long, moveIdx: Long, yHeight: LongArray, world: Set<Point>) : Day17CacheItem {
val arr = ULongArray(7)
val max = yHeight.max()
for (x in 0L..6L) {
var bitmask : ULong = 0u
val startVal = max(0, max - 64 + 1).toLong()
check(max - startVal + 1 <= 64)
for (i in startVal..max) {
val bit : UInt = if (Point(x, i) in world) 1u else 0u
bitmask = bitmask.shl(1) + bit
}
arr[x.toInt()] = bitmask
}
return Day17CacheItem(rockIdx, moveIdx, arr)
}
fun findHeight() : Long {
var highestY = -1L
var highYPrev = 0L
var moveIdx : Long = -1
var prevRock = -1L
val deltaYs = mutableListOf<Long>()
val world = mutableSetOf<Point>()
val yHeight = LongArray(7)
val cache = mutableSetOf<Day17CacheItem>()
var useCache = true
var yOffset = -1L
println("jets len = ${jets.length}")
var rocksLeft = 1_000_000_000_000
while (rocksLeft > 0) {
val i = 1_000_000_000_000 - rocksLeft
rocksLeft--
println("rocksLeft = $rocksLeft")
val rockIdx = (i % rocks.size).toLong()
val rock = rocks[rockIdx.toInt()]
var pt = Point(2, highestY + 4)
while (true) {
moveIdx = (moveIdx+1) % jets.length
val cacheItem = getCacheItem(rockIdx, moveIdx, yHeight, world)
if (useCache && cacheItem in cache) {
println("Hit the cache at i $i, move $moveIdx, rock $rockIdx, high Y $highestY, delta Y = ${highestY - highYPrev}, delta rock = ${i - prevRock}")
val deltaY = highestY - highYPrev
if (deltaY in deltaYs) {
useCache = false
val deltaRock = i - prevRock
val cyclesLeft = rocksLeft / deltaRock
rocksLeft -= cyclesLeft * deltaRock
yOffset = cyclesLeft * deltaY
} else {
deltaYs.add(highestY - highYPrev)
}
highYPrev = highestY
prevRock = i
cache.clear()
}
cache.add(cacheItem)
check(jets[moveIdx.toInt()] == '<' || jets[moveIdx.toInt()] == '>')
val push = if (jets[moveIdx.toInt()] == '<') -1 else 1
var nextPt = Point(pt.x + push, pt.y)
if (!intersect(nextPt, rock, world)) {
pt = nextPt
}
nextPt = Point(pt.x, pt.y - 1)
if (intersect(nextPt, rock, world)) {
break
}
pt = nextPt
}
// freeze it
rock.forEach {
val x = it.x + pt.x
val y = it.y + pt.y
world.add(Point(x,y))
highestY = max(highestY, y )
yHeight[x.toInt()] = max(y + 1, yHeight[x.toInt()])
}
// printWorld(highestY, world)
}
println(yHeight.toList())
return highestY + yOffset + 1 // first row filled in is y = 0
}
}
fun part2(input: String): Long {
val d = Day17(input)
return d.findHeight()
}
val testInput = readInputAsOneLine("Day17_test")
check(part1(testInput)==3068)
// println("${part2(testInput)} should equal 3068")
val input = readInputAsOneLine("Day17")
// println(part1(input))
println(part2(input))
// println(part2(input, 4_000_000))
// println(part2(input, 4_000_000))
} | 0 | Kotlin | 0 | 0 | 8d5fc0b93f6d600878ac0d47128140e70d7fc5d9 | 9,281 | AdventOfCode2022 | Apache License 2.0 |
src/Day11.kt | fercarcedo | 573,142,185 | false | {"Kotlin": 60181} | import kotlin.math.floor
private val MONKEY_REGEX = "Monkey\\s+(?<monkeyNumber>\\d+):".toRegex()
private val STARTING_ITEMS_REGEX = "\\s+Starting\\s+items:\\s+(?<items>\\d+(,\\s+\\d+)*)".toRegex()
private val OPERATION_REGEX = "\\s+Operation:\\s+new\\s+=\\s+old\\s+(?<operation>[+*])\\s+(?<value>(\\d+|old))".toRegex()
private val TEST_REGEX = "\\s+Test:\\s+divisible\\s+by\\s+(?<value>\\d+)".toRegex()
private val TEST_IF_REGEX = "\\s+If\\s+(?<result>true|false):\\s+throw\\s+to\\s+monkey\\s+(?<monkeyNumber>\\d+)".toRegex()
data class Monkey(
val items: MutableList<Long>,
val operation: (Long) -> Long,
val test: (Long) -> Boolean,
val throwMap: Map<Boolean, Int>
)
data class MonkeysResult(
val monkeys: List<Monkey>,
val dividends: Set<Long>
)
fun main() {
fun parseOperation(operation: Char, valueString: String): (Long) -> Long {
if (operation == '*' && valueString == "old") {
return { it * it }
}
if (operation == '+' && valueString == "old") {
return { it + it }
}
val value = valueString.toLong()
return if (operation == '+') {
{ it + value }
} else {
{ it * value }
}
}
fun parseInput(input: List<String>): MonkeysResult {
val monkeys = mutableListOf<Monkey>()
var monkeyNumber = 0
var items: MutableList<Long> = mutableListOf()
var operationFunction: (Long) -> Long = { it }
var test: (Long) -> Boolean = { true }
var throwMap: MutableMap<Boolean, Int> = mutableMapOf()
val dividends = mutableSetOf<Long>()
for (line in input) {
if (line.isBlank()) {
continue
}
if (MONKEY_REGEX.matches(line)) {
monkeyNumber = MONKEY_REGEX.matchEntire(line)!!.groups["monkeyNumber"]!!.value.toInt()
throwMap = mutableMapOf()
} else if (STARTING_ITEMS_REGEX.matches(line)) {
items = STARTING_ITEMS_REGEX.matchEntire(line)!!.groups["items"]!!.value.split(",").map { it.trim().toLong() }.toMutableList()
} else if (OPERATION_REGEX.matches(line)) {
val matchResult = OPERATION_REGEX.matchEntire(line)!!
val operation = matchResult.groups["operation"]!!.value.first()
val valueString = matchResult.groups["value"]!!.value
operationFunction = parseOperation(operation, valueString)
} else if (TEST_REGEX.matches(line)) {
val value = TEST_REGEX.matchEntire(line)!!.groups["value"]!!.value.toLong()
test = { it % value == 0L }
dividends.add(value)
} else if (TEST_IF_REGEX.matches(line)) {
val matchResult = TEST_IF_REGEX.matchEntire(line)!!
val result = matchResult.groups["result"]!!.value.toBoolean()
throwMap[result] = matchResult.groups["monkeyNumber"]!!.value.toInt()
if (!result) {
monkeys.add(monkeyNumber, Monkey(items, operationFunction, test, throwMap))
}
}
}
return MonkeysResult(monkeys, dividends)
}
fun play(input: List<String>, partOne: Boolean = true): Long {
val monkeysResult = parseInput(input)
val lcmDividends = monkeysResult.dividends.reduce { acc, next -> acc * next }
val monkeyInspectionsMap: MutableMap<Int, Long> = mutableMapOf()
val numRounds = if (partOne) 20 else 10000
for (round in 0 until numRounds) {
for ((index, monkey) in monkeysResult.monkeys.withIndex()) {
for (item in monkey.items) {
if (index !in monkeyInspectionsMap) {
monkeyInspectionsMap[index] = 1
} else {
monkeyInspectionsMap[index] = monkeyInspectionsMap[index]!! + 1
}
val worryLevel = if (partOne) {
floor(monkey.operation(item) / 3.0).toLong()
} else {
monkey.operation(item) % lcmDividends
}
val testResult = monkey.test(worryLevel)
val monkeyToThrowTo = monkey.throwMap[testResult]!!
monkeysResult.monkeys[monkeyToThrowTo].items.add(worryLevel)
}
monkey.items.clear()
}
}
return monkeyInspectionsMap.map { it.value }.sortedDescending().take(2).reduce { acc, next -> acc * next }
}
fun part1(input: List<String>) = play(input)
fun part2(input: List<String>) = play(input, false)
val testInput = readInput("Day11_test")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158L)
val input = readInput("Day11")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | e34bc66389cd8f261ef4f1e2b7f7b664fa13f778 | 4,931 | Advent-of-Code-2022-Kotlin | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinStepsAnagram.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2024 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.ALPHABET_LETTERS_COUNT
import kotlin.math.max
/**
* 1347. Minimum Number of Steps to Make Two Strings Anagram
* @see <a href="https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram">Source</a>
*/
fun interface MinStepsAnagram {
operator fun invoke(str: String, target: String): Int
}
class MinStepsAnagramMap : MinStepsAnagram {
override fun invoke(str: String, target: String): Int {
val count = IntArray(ALPHABET_LETTERS_COUNT)
// Storing the difference of frequencies of characters in t and s.
for (i in str.indices) {
count[target[i] - 'a']++
count[str[i] - 'a']--
}
var ans = 0
// Adding the difference where string t has more instances than s.
// Ignoring where t has fewer instances as they are redundant and
// can be covered by the first case.
for (i in 0..<ALPHABET_LETTERS_COUNT) {
ans += max(0, count[i])
}
return ans
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,678 | kotlab | Apache License 2.0 |
src/main/kotlin/day1/Day1_2.kt | remhiit | 727,182,240 | false | {"Kotlin": 12212} | package day1
import Main
fun main() {
val inputD1 = Main::class.java.getResource("day1.txt")?.readText()
var nb = 0
val calc = inputD1?.split("\r\n")
?.filter { it.isNotBlank() }
?.map { findFirstDigit(it).plus(findLastDigit(it)).toInt() }
?.reduce { acc, i -> acc + i }
println(calc)
}
val convert = mapOf(
"one" to "1",
"1" to "1",
"two" to "2",
"2" to "2",
"three" to "3",
"3" to "3",
"four" to "4",
"4" to "4",
"five" to "5",
"5" to "5",
"six" to "6",
"6" to "6",
"seven" to "7",
"7" to "7",
"eight" to "8",
"8" to "8",
"nine" to "9",
"9" to "9",
)
fun findFirstDigit(l: String): String {
return findDigitsInText(l).minByOrNull { it.key }?.value ?: "0"
}
fun findLastDigit(l: String): String {
return findDigitsInText(l).maxByOrNull { it.key }?.value ?: "0"
}
fun findDigitsInText(l: String): Map<Int, String> {
return convert.map { d -> Regex(d.key).findAll(l).map { it.range.first }.map { (it to d.value) } }
.flatMap { it }
.filter { d -> d.first != -1 }
.toMap()
}
| 0 | Kotlin | 0 | 0 | 122ee235df1af8e3d0ea193b9a37162271bad7cb | 1,127 | aoc2023 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2016/2016-11.kt | ferinagy | 432,170,488 | false | {"Kotlin": 787586} | package com.github.ferinagy.adventOfCode.aoc2016
import com.github.ferinagy.adventOfCode.searchGraph
import com.github.ferinagy.adventOfCode.singleStep
import com.github.ferinagy.adventOfCode.subSets
import java.util.*
import kotlin.system.measureTimeMillis
fun main() {
println("Part1:")
val time1 = measureTimeMillis {
println(part1(testInput1))
println(part1(input))
}
println("took $time1")
println()
println("Part2:")
val time2 = measureTimeMillis {
println(part2(testInput1))
println(part2(input))
}
println("took $time2")
}
private fun part1(input: String): Int {
return searchGraph(
start = RtgState.parse(input),
isDone = RtgState::isDone,
nextSteps = { it.nextSteps().singleStep() },
)
}
private fun part2(input: String): Int {
val rtgState = RtgState.parse(input)
val nextInput = rtgState.copy(
elementCount = rtgState.elementCount + 2,
floors = rtgState.floors.mapIndexed { index, bitSet ->
if (index != 0) bitSet else bitSet.also { it.set(rtgState.elementCount * 2, rtgState.elementCount * 2 + 4) }
}
)
return searchGraph(
start = nextInput,
isDone = RtgState::isDone,
nextSteps = { it.nextSteps().singleStep() },
)
}
private data class RtgState(
val elevator: Int = 0,
val elementCount: Int,
val floors: List<BitSet>
) {
companion object {
fun parse(input: String): RtgState {
val elements = regex.findAll(input)
.map { it.groupValues[1] }
.distinct()
.withIndex()
.map { it.value to it.index }
.toMap()
val floors = input.lines().map { line ->
val bitSet = BitSet(elements.size * 2)
regex.findAll(line).map { it.destructured }.forEach { (e, t) ->
val index = elements[e]!!
if (t == " generator") {
bitSet.set(index * 2)
} else {
bitSet.set(index * 2 + 1)
}
}
bitSet
}
return RtgState(floors = floors, elementCount = elements.size)
}
}
override fun toString(): String = buildString {
floors.asReversed().forEachIndexed { index, floor ->
append('F').append(floors.size - index).append(' ')
if (elevator == floors.lastIndex - index) append("E") else append('.')
append(' ')
append(floor)
append("\n")
}
}
fun isDone(): Boolean = floors.dropLast(1).all { it.isEmpty() }
fun nextSteps(): Set<RtgState> = buildSet {
val current = floors[elevator]
val toMove = current.let { it.subSets(1) + it.subSets(2) }.filter { it.isValid() }
toMove.forEach { moving ->
val nextCurrent = current.clone().let { it as BitSet }.also { it.andNot(moving) }
fun move(to: Int) {
if (to in floors.indices) {
val target = floors[to]
val nextTarget = target.clone().let { it as BitSet }.also { it.or(moving) }
if (nextCurrent.isValid() && nextTarget.isValid()) this += RtgState(
elevator = to,
elementCount = elementCount,
floors = floors.mapIndexed { index, floor ->
when (index) {
elevator -> nextCurrent
to -> nextTarget
else -> floor
}
}
)
}
}
move(elevator.inc())
move(elevator.dec())
}
}
private fun BitSet.isValid(): Boolean {
var index = nextSetBit(0)
var hasUnshieldedChip = false
var hasGenerator = false
while (index != -1) {
if (index % 2 == 0) {
hasGenerator = true
} else {
if (!get(index - 1)) hasUnshieldedChip = true
}
index = nextSetBit(index + 1)
}
return !hasGenerator || !hasUnshieldedChip
}
}
private val regex = """(\w+)(-compatible microchip| generator)""".toRegex()
private const val testInput1 =
"""The first floor contains a hydrogen-compatible microchip and a lithium-compatible microchip.
The second floor contains a hydrogen generator.
The third floor contains a lithium generator.
The fourth floor contains nothing relevant."""
private const val input =
"""The first floor contains a thulium generator, a thulium-compatible microchip, a plutonium generator, and a strontium generator.
The second floor contains a plutonium-compatible microchip and a strontium-compatible microchip.
The third floor contains a promethium generator, a promethium-compatible microchip, a ruthenium generator, and a ruthenium-compatible microchip.
The fourth floor contains nothing relevant."""
| 0 | Kotlin | 0 | 1 | f4890c25841c78784b308db0c814d88cf2de384b | 5,140 | advent-of-code | MIT License |
aoc2023/day6.kt | davidfpc | 726,214,677 | false | {"Kotlin": 127212} | package aoc2023
import utils.InputRetrieval
fun main() {
Day6.execute()
}
private object Day6 {
fun execute() {
val input = readInput()
println("Part 1: ${part1(input)}")
println("Part 2: ${part2(input)}")
}
private fun part1(input: List<Race>): Long = input
.map { race -> (0L..race.time).filter { holdingTime: Long -> holdingTime * (race.time - holdingTime) > race.recordDistance }.size.toLong() }
.reduce { acc: Long, i: Long -> acc * i }
private fun part2(input: List<Race>): Long {
val race = input.reduce { acc, race -> Race("${acc.time}${race.time}".toLong(), "${acc.recordDistance}${race.recordDistance}".toLong()) }
return part1(listOf(race))
}
private fun readInput(): List<Race> {
val (rawTime, rawDistance) = InputRetrieval.getFile(2023, 6).readLines()
val time = rawTime.removePrefix("Time:").split(' ').filter { it.isNotBlank() }
val distance = rawDistance.removePrefix("Distance:").split(' ').filter { it.isNotBlank() }
return time.mapIndexed { i, c -> Race(c.toLong(), distance[i].toLong()) }
}
private data class Race(val time: Long, val recordDistance: Long)
}
| 0 | Kotlin | 0 | 0 | 8dacf809ab3f6d06ed73117fde96c81b6d81464b | 1,210 | Advent-Of-Code | MIT License |
src/main/kotlin/com/kingchampion36/dsa/arrays/KthSmallestAndLargestElement.kt | KingChampion36 | 666,647,634 | false | null | package com.kingchampion36.dsa.arrays
import java.util.PriorityQueue
/**
* Sort the list and find kth smallest element
* Time complexity - O(n * log(n))
*/
fun List<Int>.kthSmallestElementBySorting(k: Int) = when {
isEmpty() -> throw IllegalArgumentException("List should not be empty")
k <= 0 || k >= size -> throw IllegalArgumentException("Invalid value $k of k")
else -> sorted()[k - 1]
}
/**
* Time Complexity - O(n * log(k))
*/
fun List<Int>.kthSmallestElementByUsingMaxHeap(k: Int): Int {
require(isNotEmpty()) { "List should not be empty" }
// k should be between 0 and size (0 < k <= size)
require(k in 1..size) { "Invalid value of k" }
val maxHeap = PriorityQueue<Int>(reverseOrder())
// Build a max heap with first k elements
for (i in 0 until k) {
maxHeap.offer(this[i])
}
for (i in k until size) {
// If current element is smaller than the top element of max heap,
// pop it and insert current element in the max heap
if (this[i] < maxHeap.peek()) {
maxHeap.poll()
maxHeap.offer(this[i])
}
}
return maxHeap.peek()
}
/**
* Time Complexity - O(n * log(k))
*/
fun List<Int>.kthLargestElementByUsingMinHeap(k: Int): Int {
require(isNotEmpty()) { "List should not be empty" }
// k should be between 0 and size (0 < k <= size)
require(k in 1..size) { "Invalid value of k" }
val minHeap = PriorityQueue<Int>()
// Build a min heap with first k elements
for (i in 0 until k) {
minHeap.offer(this[i])
}
for (i in k until size) {
// If current element is greater than the top element of min heap,
// pop it and insert current element in the min heap
if (this[i] > minHeap.peek()) {
minHeap.poll()
minHeap.offer(this[i])
}
}
return minHeap.peek()
}
| 0 | Kotlin | 0 | 0 | a276937ca52cb9d55e4e92664478ad4a69e491a7 | 1,780 | data-structures-and-algorithms | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.