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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
archive/backups/Kata/kotlin-kata/src/main/kotlin/de/felixroske/mostfrequentlyusedwords/MostFrequentlyUsedWords.kt | roskenet | 295,683,964 | false | {"HTML": 708028, "Jupyter Notebook": 571597, "TeX": 547996, "Java": 447619, "Makefile": 214272, "JavaScript": 204557, "CMake": 113090, "Kotlin": 88563, "TypeScript": 61333, "Clojure": 36776, "CSS": 25303, "C++": 19374, "Red": 13104, "Python": 12901, "Shell": 12248, "SCSS": 5588, "Go": 4797, "Dockerfile": 2073, "C": 1687, "Vim Script": 1092, "PLpgSQL": 818, "Assembly": 384, "Rust": 308, "Gherkin": 207, "Procfile": 177, "C#": 147, "PHP": 94, "Less": 91, "Ruby": 73, "sed": 26, "Batchfile": 21, "Groovy": 21} | package de.felixroske.mostfrequentlyusedwords
fun top3(s: String): List<String> {
val splitlist = s.split(' ', ';', '/', ':', '!', '?', ',', '.', '\n', '\t')
val tempMap = mutableMapOf<String, Int>()
splitlist.forEach {
val times: Int? = tempMap[it.toLowerCase()]
if(times == null) {
tempMap.put(it.toLowerCase(), 1)
} else {
tempMap.put(it.toLowerCase(), times+1)
}
}
print(tempMap)
val endList = mutableListOf<Pair<String, Int>>()
tempMap.forEach outer@{(s, i) ->
if(s.equals("") or s.equals("'") or s.equals("'''")) {
return@outer
}
if(endList.size == 0) {
endList.add(Pair(s, i))
return@outer
}
for (inneri in endList.indices) {
val (s1, i1) = endList[inneri]
if (i >= i1) {
endList.add(inneri, Pair(s, i))
return@outer
} else {
endList.add(Pair(s, i))
}
}
}
if(endList.size == 0) {
return emptyList()
}
if(endList.size == 1) {
return listOf(endList[0].first)
}
if(endList.size == 2) {
return listOf(endList[0].first, endList[1].first)
}
if(endList.size >= 3) {
return listOf(endList[0].first, endList[1].first, endList[2].first)
}
// We can never get here:
return emptyList()
}
/*
fun top3(text: String): List<String> {
val words = Regex("[A-Za-z][A-Za-z']*").findAll(text).map { it.groupValues[0].toLowerCase() }
val occurrences = mutableMapOf<String, Int>()
words.forEach { occurrences.merge(it, 1, Integer::sum) }
return occurrences.toList().sortedByDescending { it.second }.map { it.first }.take(3)
}*/
| 0 | HTML | 1 | 0 | 39975a0248f2e390f799bdafde1170322267761b | 1,777 | playground | MIT License |
src/Day04.kt | JonasDBB | 573,382,821 | false | {"Kotlin": 17550} | private fun isRangeContained(r0: List<Int>, r1: List<Int>) =
r0[0] >= r1[0] && r0[1] <= r1[1] || r1[0] >= r0[0] && r1[1] <= r0[1]
private fun doesRangeOverlap(r0: List<Int>, r1: List<Int>) =
r0[0] <= r1[0] && r0[1] >= r1[0] || r1[0] <= r0[0] && r1[1] >= r0[0]
private fun part(input: List<List<List<Int>>>, pred: (List<Int>, List<Int>) -> (Boolean)) {
println(
input.count { lists ->
pred(lists[0], lists[1])
}
)
}
fun main() {
// input is list of lines that are first split on "," and those are split on "-"
val input = readInput("04").map { line ->
line.split(",").map { range ->
range.split("-").map { nr -> nr.toInt() }
}
}
println("part 01")
part(input, ::isRangeContained)
println("part 02")
part(input, ::doesRangeOverlap)
} | 0 | Kotlin | 0 | 0 | 199303ae86f294bdcb2f50b73e0f33dca3a3ac0a | 834 | AoC2022 | Apache License 2.0 |
src/main/kotlin/g1501_1600/s1530_number_of_good_leaf_nodes_pairs/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1501_1600.s1530_number_of_good_leaf_nodes_pairs
// #Medium #Depth_First_Search #Tree #Binary_Tree
// #2023_06_12_Time_242_ms_(100.00%)_Space_39.1_MB_(100.00%)
import com_github_leetcode.TreeNode
/*
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun countPairs(root: TreeNode?, distance: Int): Int {
return if (distance < 2) {
0
} else pairsAndLeaves(root, distance)[0]
}
private fun pairsAndLeaves(node: TreeNode?, distance: Int): IntArray {
val r = IntArray(distance)
if (node == null) {
return r
}
if (node.left == null && node.right == null) {
r[1] = 1
return r
}
val rl = pairsAndLeaves(node.left, distance)
val rr = pairsAndLeaves(node.right, distance)
for (i in 2 until distance) {
r[i] = rl[i - 1] + rr[i - 1]
}
var pairs = rl[0] + rr[0]
for (dist in 2..distance) {
for (leftToNodeDist in 1 until dist) {
pairs += rl[leftToNodeDist] * rr[dist - leftToNodeDist]
}
}
r[0] = pairs
return r
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,333 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/com/newtranx/eval/utils/func.kt | ansonxing23 | 460,949,156 | false | {"Kotlin": 86034, "TeX": 212} | package com.newtranx.eval.utils
import kotlin.math.ln
import kotlin.math.min
/**
* @Author: anson
* @Date: 2022/1/29 11:41 PM
*/
inline fun <T> zip(vararg lists: List<T>): List<List<T>> {
return zip(*lists, transform = { it })
}
inline fun <T, V> zip(vararg lists: List<T>, transform: (List<T>) -> V): List<V> {
val minSize = lists.map(List<T>::size).minOrNull() ?: return emptyList()
val list = ArrayList<V>(minSize)
val iterators = lists.map { it.iterator() }
var i = 0
while (i < minSize) {
list.add(transform(iterators.map { it.next() }))
i++
}
return list
}
/**
* Extracts all ngrams (min_order <= n <= max_order) from a sentence.
* @param line: A string sentence.
* @param minOrder: Minimum n-gram order.
* @param maxOrder: Maximum n-gram order.
* @return a Counter object with n-grams counts and the sequence length.
*/
fun extractAllWordNgrams(
line: String,
minOrder: Int,
maxOrder: Int
): Pair<Counter<List<String>>, Double> {
val counter = Counter<List<String>>()
val tokens = line.split(" ")
(minOrder until maxOrder + 1).forEach { n ->
val nGrams = extractNgrams(tokens, n)
counter.update(nGrams)
}
return Pair(counter, tokens.size.toDouble())
}
fun extractNgrams(
tokens: List<String>,
n: Int = 1
): List<List<String>> {
return (0 until (tokens.size - n + 1)).map { i ->
tokens.subList(i, i + n)
}
}
class Counter<T>(
data: List<T>? = null
) {
private val store = mutableMapOf<T, Int>()
private val keys = mutableSetOf<T>()
init {
if (data != null)
this.update(data)
}
fun update(data: List<T>) {
data.forEach { key ->
val count = store[key] ?: 0
if (count == 0) {
keys.add(key)
}
store[key] = count + 1
}
}
private fun add(key: T, count: Int) {
store[key] = count
keys.add(key)
}
fun keys(): Set<T> {
return keys
}
fun values(): List<Int> {
return store.values.toList()
}
fun count(key: T): Int {
return store[key] ?: 0
}
fun exist(key: T): Boolean {
return store.containsKey(key)
}
fun intersect(counter: Counter<T>): Counter<T> {
val iKeys = this.keys intersect counter.keys
val newCounter = Counter<T>()
iKeys.forEach {
val cur = count(it)
val income = counter.count(it)
val value = min(cur, income)
newCounter.add(it, value)
}
return newCounter
}
operator fun set(key: T, count: Int) {
if (!store.containsKey(key)) {
keys.add(key)
}
store[key] = 0.takeIf { count < 0 } ?: count
}
}
inline fun <T, V> Counter<T>.map(transform: (key: T, count: Int) -> V): List<V> {
val array = mutableListOf<V>()
this.keys().forEach {
val item = transform.invoke(it, this.count(it))
array.add(item)
}
return array
}
inline fun <T> Counter<T>.forEach(action: (key: T, count: Int) -> Unit) {
this.keys().forEach {
action.invoke(it, this.count(it))
}
}
/**
* Floors the log function
* @param num: the number
* @return log(num) floored to a very low number
*/
fun myLog(num: Double): Double {
if (num == 0.0)
return -9999999999.0
return ln(num)
}
/**
* Aggregates list of numeric lists by summing.
*/
fun sumOfLists(lists: List<List<Double>>): List<Double> {
// Aggregates list of numeric lists by summing.
if (lists.size == 1) {
return lists[0]
}
// Preserve datatype
val size = lists[0].size
val total = DoubleArray(size) { 0.0 }
lists.forEach { ll ->
(0 until size).forEach { i ->
total[i] = total[i].plus(ll[i])
}
}
return total.toList()
} | 0 | Kotlin | 0 | 0 | 2f5a970378f2aab67bed6fa6aa8ba61671b6204c | 3,889 | mt-metrics | Apache License 2.0 |
src/main/kotlin/days/Day3.kt | VictorWinberg | 433,748,855 | false | {"Kotlin": 26228} | package days
class Day3 : Day(3) {
override fun partOne(): Any {
val list = inputList[0].toList().map { mutableListOf(0, 0) }
inputList.forEach {
it.toList().map { i -> "$i".toInt() }.forEachIndexed { index, i -> list[index][i] += 1 }
}
val gammaRate = list.map { pair -> if (pair[0] < pair[1]) 1 else 0 }.joinToString("").toInt(2)
val epsilonRate = list.map { pair -> if (pair[0] < pair[1]) 0 else 1 }.joinToString("").toInt(2)
return gammaRate * epsilonRate
}
override fun partTwo(): Any {
val oxygen = rating(inputList.toMutableList(), inputList[0].length) { a, b -> if (a <= b) '1' else '0' }
val co2 = rating(inputList.toMutableList(), inputList[0].length) { a, b -> if (a <= b) '0' else '1' }
return co2 * oxygen
}
private fun rating(list: MutableList<String>, bitsLength: Int, op: (Int, Int) -> Char) =
(0 until bitsLength).map { index ->
val bits = mutableListOf(0, 0)
if (list.size == 1) return@map list[0][index]
list.forEach { bits[it.toList()[index].toString().toInt()] += 1 }
list.removeAll { it[index] != op(bits[0], bits[1]) }
op(bits[0], bits[1])
}.joinToString("").toInt(2)
}
| 0 | Kotlin | 0 | 0 | d61c76eb431fa7b7b66be5b8549d4685a8dd86da | 1,277 | advent-of-code-kotlin | Creative Commons Zero v1.0 Universal |
src/main/kotlin/g0001_0100/s0040_combination_sum_ii/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0001_0100.s0040_combination_sum_ii
// #Medium #Array #Backtracking #Algorithm_II_Day_10_Recursion_Backtracking
// #2023_07_05_Time_217_ms_(93.75%)_Space_38_MB_(89.06%)
import java.util.LinkedList
class Solution {
fun combinationSum2(candidates: IntArray, target: Int): List<List<Int>> {
val sums: MutableList<List<Int>> = ArrayList()
// optimize
candidates.sort()
combinationSum(candidates, target, 0, sums, LinkedList())
return sums
}
private fun combinationSum(
candidates: IntArray,
target: Int,
start: Int,
sums: MutableList<List<Int>>,
sum: LinkedList<Int>
) {
if (target == 0) {
// make a deep copy of the current combination
sums.add(ArrayList(sum))
return
}
var i = start
while (i < candidates.size && target >= candidates[i]) {
// If candidate[i] equals candidate[i-1], then solutions for i is subset of
// solution of i-1
if (i == start || i > start && candidates[i] != candidates[i - 1]) {
sum.addLast(candidates[i])
// call on 'i+1' (not i) to avoid duplicate usage of same element
combinationSum(candidates, target - candidates[i], i + 1, sums, sum)
sum.removeLast()
}
i++
}
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 1,406 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/com/hackerrank/FormingAMagicSquare.kt | iluu | 94,996,114 | false | {"Java": 89400, "Kotlin": 14594, "Scala": 1758, "Haskell": 776} | package com.hackerrank
import java.util.*
val magicSquares = arrayOf(
intArrayOf(8, 1, 6, 3, 5, 7, 4, 9, 2),
intArrayOf(4, 3, 8, 9, 5, 1, 2, 7, 6),
intArrayOf(2, 9, 4, 7, 5, 3, 6, 1, 8),
intArrayOf(6, 7, 2, 1, 5, 9, 8, 3, 4),
intArrayOf(6, 1, 8, 7, 5, 3, 2, 9, 4),
intArrayOf(8, 3, 4, 1, 5, 9, 6, 7, 2),
intArrayOf(4, 9, 2, 3, 5, 7, 8, 1, 6),
intArrayOf(2, 7, 6, 9, 5, 1, 4, 3, 8))
fun main(args: Array<String>) {
val scan = Scanner(System.`in`)
val arr = IntArray(9)
for (i in 0..2) {
for (j in 0..2) {
arr[i * 3 + j] = scan.nextInt()
}
}
println(minimalCost(arr))
}
fun minimalCost(arr: IntArray): Int {
return magicSquares.map {
arr.zip(it)
.filter { (first, second) -> first != second }
.sumBy { (first, second) -> Math.abs(first - second) }
}.min()!!
}
| 0 | Java | 3 | 5 | a89b0d332a3d4a257618e9ae6c7f898cb1695246 | 925 | algs-progfun | MIT License |
src/main/kotlin/com/staricka/adventofcode2023/days/Day21.kt | mathstar | 719,656,133 | false | {"Kotlin": 107115} | package com.staricka.adventofcode2023.days
import com.staricka.adventofcode2023.days.GardenCell.Companion.toGardenCell
import com.staricka.adventofcode2023.framework.Day
import com.staricka.adventofcode2023.util.Grid
import com.staricka.adventofcode2023.util.GridCell
import com.staricka.adventofcode2023.util.StandardGrid
enum class GardenCell(override val symbol: Char): GridCell {
START('S'), PLOT('.'), ROCK('#');
fun isPlot() = this == START || this == PLOT
companion object {
fun Char.toGardenCell(): GardenCell {
return when (this) {
'S' -> START
'.' -> PLOT
'#' -> ROCK
else -> throw Exception()
}
}
}
}
fun Grid<GardenCell>.reachable(numSteps: Int): Int {
val (startX, startY, _) = cells().single { (_, _, v) -> v == GardenCell.START }
var toProcess = setOf(Pair(startX, startY))
for (i in 1..numSteps) {
val next = HashSet<Pair<Int, Int>>()
for (p in toProcess) {
manhattanNeighbors(p).filter {(x,y,v) -> v?.isPlot() == true }
.map { (x,y,_) -> Pair(x,y) }
.forEach {
next += it
}
}
toProcess = next
}
return toProcess.size
}
fun Grid<GardenCell>.reachableInfinite(numSteps: Int): Long {
val (startX, startY, _) = cells().single { (_, _, v) -> v == GardenCell.START }
var toProcess = setOf(Pair(startX, startY))
for (i in 1..numSteps) {
val next = HashSet<Pair<Int, Int>>()
for (p in toProcess) {
manhattanNeighbors(p)
.filter { (x,y) ->
var xp = x % (maxX + 1)
var yp = y % (maxY + 1)
while (xp < 0) xp += maxX
while (yp < 0) yp += maxY
this[xp,yp]!!.isPlot()
}.forEach { (x,y,_) -> next += Pair(x,y) }
}
toProcess = next
}
return toProcess.size.toLong()
}
class Day21(private val numSteps: Int = 64, private val numStepsPart2: Int = 26501365): Day {
override fun part1(input: String): Int {
return StandardGrid.build(input) {it.toGardenCell()}.reachable(numSteps)
}
override fun part2(input: String): Any? {
return StandardGrid.build(input) {it.toGardenCell()}.reachableInfinite(numStepsPart2)
}
} | 0 | Kotlin | 0 | 0 | 8c1e3424bb5d58f6f590bf96335e4d8d89ae9ffa | 2,405 | adventOfCode2023 | MIT License |
src/main/kotlin/Day09.kt | gijs-pennings | 573,023,936 | false | {"Kotlin": 20319} | import kotlin.math.abs
import kotlin.math.max
fun main() {
val n = 10 // use n=2 for part 1
val knots = List(n) { MutablePos() }
val allTailPos = mutableSetOf(knots.last().copy())
for (line in readInput(9)) {
repeat(line.substring(line.indexOf(' ') + 1).toInt()) {
knots.first().move(line[0])
for (i in 1 until knots.size) {
val H = knots[i-1]
val T = knots[i]
if (T.dist(H) > 1) {
if (H.x != T.x) T.x += if (H.x > T.x) 1 else -1
if (H.y != T.y) T.y += if (H.y > T.y) 1 else -1
}
}
allTailPos.add(knots.last().copy())
}
}
println(allTailPos.size)
}
private data class MutablePos(
var x: Int = 0,
var y: Int = 0
) {
fun dist(p: MutablePos) = max(abs(x - p.x), abs(y - p.y))
fun move(dir: Char) {
when (dir) {
'R' -> x++
'L' -> x--
'U' -> y++
'D' -> y--
}
}
}
| 0 | Kotlin | 0 | 0 | 8ffbcae744b62e36150af7ea9115e351f10e71c1 | 1,037 | aoc-2022 | ISC License |
src/main/kotlin/se/brainleech/adventofcode/aoc2021/Aoc2021Day14.kt | fwangel | 435,571,075 | false | {"Kotlin": 150622} | package se.brainleech.adventofcode.aoc2021
import se.brainleech.adventofcode.compute
import se.brainleech.adventofcode.readLines
import se.brainleech.adventofcode.sortedByChar
import se.brainleech.adventofcode.verify
import java.util.*
class Aoc2021Day14 {
companion object {
private const val PADDED_ARROW = " -> "
}
// 0: NNCB
// 1: NCNBCHB
// 2: NBCCNBBBCBHCB
// 3: NBBBCNCCNBBNBNBBCHBHHBCHB
// 4: NBBNBNBBCCNBCNCCNBBNBBNBBBNBBNBBCBHCBHHNHCBBCBHCB
// ...
// NOTES:
// * The first and last element character is always the same.
// * For every pair processed, the result is two new pairs
// built from the element mapped via the original pair.
interface PolymerExpander {
fun process(steps: Int): PolymerExpander
fun maxMinusMinQuantity(): Long
}
open class RealPolymerExpander(
template: String,
private val insertionRules: Map<String, String>
) : PolymerExpander {
private var chain = StringBuilder(template)
override fun process(steps: Int): PolymerExpander {
// insert the mapped element for every pair on each iteration
repeat(steps) {
chain.windowed(2).withIndex()
.map { indexedPair ->
chain.insert(1.plus(indexedPair.index.times(2)), insertionRules[indexedPair.value])
}
}
return this
}
private fun quantitiesByElement(): SortedMap<String, Long> {
return chain
.toString()
.sortedByChar()
.groupingBy { it.toString() }
.eachCount()
.mapValues { it.value.toLong() }
.toSortedMap()
}
override fun maxMinusMinQuantity(): Long {
return quantitiesByElement().map { it.value }.sorted().let { quantities ->
quantities.last().minus(quantities.first())
}
}
}
class SimulatedPolymerExpander(
private val template: String,
private val insertionRules: Map<String, String>
) : PolymerExpander {
private var quantitiesPerPair: Map<String, Long> = mapOf()
private fun String.firstCharAsString(): String = this.first().toString()
private fun String.lastCharAsString(): String = this.last().toString()
private fun Long.half(): Long = this.div(2)
private val mergeBySum: Long.(Long) -> Long = { other -> this.plus(other) }
override fun process(steps: Int): PolymerExpander {
quantitiesPerPair = template
.windowed(2)
.groupingBy { it }
.eachCount()
.mapValues { entry -> entry.value.toLong() }
repeat(steps) {
val updatedQuantities = mutableMapOf<String, Long>()
quantitiesPerPair.forEach { (pair, pairQuantity) ->
val newElement = insertionRules[pair]
val newPairBefore = "${pair.firstCharAsString()}${newElement}"
val newPairAfter = "${newElement}${pair.lastCharAsString()}"
updatedQuantities.merge(newPairBefore, pairQuantity, mergeBySum)
updatedQuantities.merge(newPairAfter, pairQuantity, mergeBySum)
}
quantitiesPerPair = updatedQuantities.toMap()
}
return this
}
override fun maxMinusMinQuantity(): Long {
// the first and last element must be counted
// separately from the pairs, since elements
// are inserted inside each pair
val quantitiesPerElement = mutableMapOf(
template.firstCharAsString() to 1L,
template.lastCharAsString() to 1L
)
// ...then split each pair and add up the totals
// (but keep in mind it will be double)
quantitiesPerPair.forEach { (pair, pairQuantity) ->
val firstElement = pair.firstCharAsString()
val secondElement = pair.lastCharAsString()
quantitiesPerElement.merge(firstElement, pairQuantity, mergeBySum)
quantitiesPerElement.merge(secondElement, pairQuantity, mergeBySum)
}
// adjust the totals by half and determine the MAX and MIN difference
return quantitiesPerElement.map { it.value.half() }.sorted().let { quantities ->
quantities.last().minus(quantities.first())
}
}
}
private fun List<String>.asPolymer(simulated: Boolean = false): PolymerExpander {
val lines = this.toList()
val template = lines.first()
val rules = lines
.asSequence()
.drop(2)
.map { line -> line.split(PADDED_ARROW) }
.groupBy(keySelector = { it.first() }, valueTransform = { it.last() })
.mapValues { it.value.first() }
return if (simulated) SimulatedPolymerExpander(template, rules)
else RealPolymerExpander(template, rules)
}
fun part1(input: List<String>): Long {
return input.asPolymer(simulated = false).process(10).maxMinusMinQuantity()
}
fun part2(input: List<String>): Long {
return input.asPolymer(simulated = true).process(40).maxMinusMinQuantity()
}
}
fun main() {
val solver = Aoc2021Day14()
val prefix = "aoc2021/aoc2021day14"
val testData = readLines("$prefix.test.txt")
val realData = readLines("$prefix.real.txt")
verify(1_588L, solver.part1(testData))
compute({ solver.part1(realData) }, "$prefix.part1 = ")
verify(2_188_189_693_529L, solver.part2(testData))
compute({ solver.part2(realData) }, "$prefix.part2 = ")
} | 0 | Kotlin | 0 | 0 | 0bba96129354c124aa15e9041f7b5ad68adc662b | 5,815 | adventofcode | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem688/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem688
/**
* LeetCode page: [688. Knight Probability in Chessboard](https://leetcode.com/problems/knight-probability-in-chessboard/);
*/
class Solution {
/* Complexity:
* Time O(k * n^2) and Space O(k * n^2);
*/
fun knightProbability(n: Int, k: Int, row: Int, column: Int): Double {
return knightProbability(n, KnightState(row, column, k))
}
private fun knightProbability(
boardSize: Int,
state: KnightState,
cachedResults: MutableMap<KnightState, Double> = hashMapOf()
): Double {
if (state in cachedResults) {
return checkNotNull(cachedResults[state])
}
if (state.hasMovedOff(boardSize)) {
return 0.0
}
if (state.remainingMoves == 0) {
return 1.0
}
var result = 0.0
for (nextState in state.possibleNextStates()) {
result += 0.125 * knightProbability(boardSize, nextState, cachedResults)
}
cachedResults[state] = result
return result
}
private data class KnightState(val row: Int, val column: Int, val remainingMoves: Int) {
fun hasMovedOff(boardSize: Int): Boolean {
return (row < 0 || row >= boardSize) || (column < 0 || column >= boardSize)
}
fun possibleNextStates(): List<KnightState> {
return listOf(
KnightState(row - 2, column + 1, remainingMoves - 1),
KnightState(row - 1, column + 2, remainingMoves - 1),
KnightState(row + 1, column + 2, remainingMoves - 1),
KnightState(row + 2, column + 1, remainingMoves - 1),
KnightState(row + 2, column - 1, remainingMoves - 1),
KnightState(row + 1, column - 2, remainingMoves - 1),
KnightState(row - 1, column - 2, remainingMoves - 1),
KnightState(row - 2, column - 1, remainingMoves - 1)
)
}
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,995 | hj-leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/g2301_2400/s2322_minimum_score_after_removals_on_a_tree/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2301_2400.s2322_minimum_score_after_removals_on_a_tree
// #Hard #Array #Depth_First_Search #Tree #Bit_Manipulation
// #2023_06_30_Time_412_ms_(100.00%)_Space_49.1_MB_(100.00%)
class Solution {
private var ans = Int.MAX_VALUE
// function to travel 2nd time on the tree and find the second edge to be removed
private fun helper(
src: Int,
graph: Array<ArrayList<Int>?>,
arr: IntArray,
par: Int,
block: Int,
xor1: Int,
tot: Int
): Int {
// Setting the value for the current subtree's XOR value
var myXOR = arr[src]
for (nbr in graph[src]!!) {
// If the current nbr is niether the parent of this node nor the blocked node , then
// only we'll proceed
if (nbr != par && nbr != block) {
val nbrXOR = helper(nbr, graph, arr, src, block, xor1, tot)
// 'src <----> nbr' is the second edge to be removed
// Getting the XOR value of the current neighbor
// The XOR of the remaining component
val xor3 = tot xor xor1 xor nbrXOR
// Getting the minimum of the three values
val max = xor1.coerceAtLeast(nbrXOR.coerceAtLeast(xor3))
// Getting the maximum of the three value
val min = xor1.coerceAtMost(nbrXOR.coerceAtMost(xor3))
ans = ans.coerceAtMost(max - min)
// Including the neighbour subtree's XOR value in the XOR value of the subtree
// rooted at src node
myXOR = myXOR xor nbrXOR
}
}
// Returing the XOR value of the current subtree rooted at the src node
return myXOR
}
// function to travel 1st time on the tree and find the first edge to be removed and
// then block the node at which the edge ends to avoid selecting the same node again
private fun dfs(src: Int, graph: Array<ArrayList<Int>?>, arr: IntArray, par: Int, tot: Int): Int {
// Setting the value for the current subtree's XOR value
var myXOR = arr[src]
for (nbr in graph[src]!!) {
// If the current nbr is not the parent of this node, then only we'll proceed
if (nbr != par) {
// After selecting 'src <----> nbr' as the first edge, we block 'nbr' node and then
// make a call to try all the second edges
val nbrXOR = dfs(nbr, graph, arr, src, tot)
// Calling the helper to find the try all the second edges after blocking the
// current node
helper(0, graph, arr, -1, nbr, nbrXOR, tot)
// Including the neighbour subtree's XOR value in the XOR value of the subtree
// rooted at src node
myXOR = myXOR xor nbrXOR
}
}
// Returing the XOR value of the current subtree rooted at the src node
return myXOR
}
fun minimumScore(arr: IntArray, edges: Array<IntArray>): Int {
val n = arr.size
val graph: Array<ArrayList<Int>?> = arrayOfNulls(n)
var tot = 0
for (i in 0 until n) {
// Initializing the graph and finding the total XOR
graph[i] = ArrayList()
tot = tot xor arr[i]
}
for (edge in edges) {
// adding the edges
val u = edge[0]
val v = edge[1]
graph[u]!!.add(v)
graph[v]!!.add(u)
}
ans = Int.MAX_VALUE
dfs(0, graph, arr, -1, tot)
return ans
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 3,624 | LeetCode-in-Kotlin | MIT License |
src/main/kotlin/biodivine/algebra/UnivariatePolynomialTools.kt | daemontus | 160,796,526 | false | null | package biodivine.algebra
import biodivine.algebra.svg.zero
import cc.redberry.rings.Rings
import cc.redberry.rings.Rings.Q
import cc.redberry.rings.bigint.BigInteger
import cc.redberry.rings.poly.univar.UnivariatePolynomial
val coder = Rings.UnivariateRingQ.mkCoder("x")
/**
* TODO: Here, we assume this goes up to degree 10 - fix it to be universal
*/
private val normalizationFactors = (0..50).map { coder.parse("(1 + x)^$it") }
/***
* transform polynomial p by formula : (1 + x)^n * p( (ax + b) / (1 + x))
*/
fun UnivariatePolynomial<NumQ>.transformPolyToInterval(lowerBound: NumQ, upperBound: NumQ): UnivariatePolynomial<NumQ> {
val result = UnivariatePolynomial.zero(Q)
var exponent = degree()
val substitutionTerm = UnivariatePolynomial.create(Q, upperBound, lowerBound)
var substitution = UnivariatePolynomial.one(Q)
for (coef in this) {
if (coef != zero) {
val normalization = normalizationFactors[exponent].copy()
result.add(normalization.multiply(substitution.copy().multiply(coef)))
}
substitution = substitution.multiply(substitutionTerm)
exponent -= 1
}
return result
}
/**
* get number of sign changes in coefficients of input polynomial
*/
fun UnivariatePolynomial<NumQ>.getNumberOfSignChanges(): Int {
var numberOfChanges = 0
var previousCoef = this.getFirstNonZeroCoefficient()
for (coef in this) {
if (!coef.isZero) {
if (isChangeInSign(previousCoef, coef)) {
numberOfChanges++
}
previousCoef = coef
}
}
return numberOfChanges
}
private fun isChangeInSign(first: NumQ, second: NumQ): Boolean {
return first.signum() != second.signum()
}
fun UnivariatePolynomial<NumQ>.getFirstNonZeroCoefficient(): NumQ {
for (coef in this) {
if (!coef.isZero) {
return coef
}
}
return Q.zero
}
fun UnivariatePolynomial<NumQ>.getDefaultBoundForDescartMethod(): NumQ {
if (this.isZero)
return Q.zero
var bound = Q.zero
for (coefficient in this) {
val fraction = (coefficient.divide(lc())).abs()
if (fraction > bound) {
bound = fraction
}
}
return bound.multiply(BigInteger.TWO)
}
fun <T> UnivariatePolynomial<T>.reductum(): UnivariatePolynomial<T> {
return copy().shiftLeft(1)
}
fun <T> UnivariatePolynomial<T>.reductaSet(): Set<UnivariatePolynomial<T>> {
if (isZero)
return emptySet()
val result = HashSet<UnivariatePolynomial<T>>(this.degree())
var poly = this
while (!poly.isZero) {
result.add(poly)
poly = poly.reductum()
}
return result
}
| 0 | Kotlin | 0 | 0 | ed4fd35015b73ea3ac36aecb1c5a568f6be7f14c | 2,705 | biodivine-algebraic-toolkit | MIT License |
src/main/kotlin/sk/mkiss/algorithms/sort/QuickSort.kt | marek-kiss | 430,858,906 | false | {"Kotlin": 85343} | package sk.mkiss.algorithms.sort
object QuickSort : SortAlgorithm() {
override fun <T : Comparable<T>> sort(array: Array<T>): Array<T> {
quickSort(array, 0, array.size)
return array
}
private fun <T : Comparable<T>> quickSort(array: Array<T>, startIndex: Int, endIndex: Int) {
if (endIndex - startIndex <= 1) return
val pivot = getPivot(array, startIndex, endIndex)
val (pivotStartIndex, pivotEndIndex) = partition(array, startIndex, endIndex, pivot)
quickSort(array, startIndex, pivotStartIndex)
quickSort(array, pivotEndIndex, endIndex)
}
private fun <T : Comparable<T>> partition(
array: Array<T>,
startIndex: Int,
endIndex: Int,
pivot: T
): Pair<Int, Int> {
var s = startIndex
var p = startIndex
var e = endIndex - 1
while (p <= e) {
when {
array[p] == pivot -> p++
array[p] < pivot -> swap(array, s++, p++)
array[p] > pivot -> swap(array, p, e--)
}
}
return Pair(s, p)
}
/**
* Select the median value of first, middle and last element from the given subarray as a pivot.
*/
private fun <T : Comparable<T>> getPivot(array: Array<T>, startIndex: Int, endIndex: Int): T {
var s = startIndex
var e = endIndex - 1
var m = startIndex + (endIndex - startIndex) / 2
if (array[s] > array[m]) swap(array, s, m)
if (array[s] > array[e]) swap(array, s, e)
if (array[m] > array[e]) swap(array, m, e)
return array[m]
}
} | 0 | Kotlin | 0 | 0 | 296cbd2e04a397597db223a5721b6c5722eb0c60 | 1,636 | algo-in-kotlin | MIT License |
src/jvmMain/kotlin/day11/initial/Grid.kt | liusbl | 726,218,737 | false | {"Kotlin": 109684} | package day11.initial
import util.set
data class Grid<T>(
// TODO this can be improved by forcing creation by row list or column list.
// Now this is ambiguous, but indeded to be created from flattened row list
private val locationList: List<Location<T>>
) {
val rowList: List<List<Location<T>>> = locationList.groupBy { it.row }.map { it.value }
val columnList: List<List<Location<T>>> = locationList.groupBy { it.column }.map { it.value }
}
fun <T> Grid<T>.inBounds(row: Int, column: Int): Boolean =
row >= 0 &&
column >= 0 &&
row < rowList.size &&
column < columnList.size
fun <T> Grid<T>.move(
fromRow: Int,
fromColumn: Int,
toRow: Int,
toColumn: Int,
filledValue: T,
replaceValue: (oldValue: T) -> T
): Grid<T> {
return update(fromRow, fromColumn) { filledValue }
.run {
if (inBounds(toRow, toColumn)) {
val toValue = rowList[toRow][toColumn].value
update(toRow, toColumn) { replaceValue(toValue) }
} else {
this
}
}
}
fun <T> Grid<T>.update(row: Int, column: Int, transform: (T) -> T): Grid<T> {
return if (inBounds(row, column)) {
val location = rowList[row][column]
val newRow = rowList[row].set(column, location.copy(value = transform(location.value)))
val newRowList = rowList.set(row, newRow)
Grid(newRowList.flatten())
} else {
this
}
}
// TODO
fun <T> Grid<T>.rotate(): Grid<T> {
return this.columnList.map { it.map { it.copy(row = it.column, column = it.row) } }.flatten().let(::Grid)
}
fun <T> Grid<T>.toPrintableString(includeLocation: Boolean): String =
if (includeLocation) {
rowList.joinToString(separator = "\n") { row ->
row.joinToString(separator = " | ") { "${it.value},${it.row},${it.column}" }
}
} else {
rowList.joinToString(separator = "\n") { row ->
row.joinToString(separator = "") { location -> location.toPrintableString() }
}
}
fun main() {
val grid = Grid<Int>(
listOf(
Location(1, 0, 0), Location(2, 0, 1), Location(3, 0, 2), Location(4, 0, 3),
Location(5, 1, 0), Location(6, 1, 1), Location(7, 1, 2), Location(8, 1, 3),
Location(9, 2, 0), Location(10, 2, 1), Location(11, 2, 2), Location(12, 2, 3)
)
)
val str = grid.toPrintableString(includeLocation = true)
println(str)
println()
println("Rotated")
val str2 = grid.rotate()/*.toPrintableString(includeLocation = true)*/
println(str2.toPrintableString(includeLocation = true))
}
| 0 | Kotlin | 0 | 0 | 1a89bcc77ddf9bc503cf2f25fbf9da59494a61e1 | 2,673 | advent-of-code | MIT License |
src/main/kotlin/com/kishor/kotlin/algo/algorithms/graph/CycleInGraph.kt | kishorsutar | 276,212,164 | false | null | package com.kishor.kotlin.algo.algorithms.graph
fun main() {
val edges = listOf(listOf(1, 3), listOf(2 ,3, 4), listOf(0), emptyList(), listOf(2, 5), emptyList())
cycleInGraph(edges)
}
fun cycleInGraph(edges: List<List<Int>>): Boolean {
val numberOfEdges = edges.size
val visited = BooleanArray(numberOfEdges) { false }
val recStack = BooleanArray(numberOfEdges) { false }
for (node in 0 until numberOfEdges) {
if (visited[node]) continue
val containsCycle = isNodeInCycle(edges, node, visited, recStack)
if (containsCycle) return true
}
return false
}
fun isNodeInCycle(edges: List<List<Int>>, node: Int, visited: BooleanArray, recStack: BooleanArray): Boolean {
visited[node] = true
recStack[node] = true
val neighbours = edges[node]
for (neighbour in neighbours) {
if (!visited[neighbour]) {
val containsCycle = isNodeInCycle(edges, neighbour, visited, recStack)
if (containsCycle) {
return true
}
} else if (recStack[neighbour]) {
return true
}
}
recStack[node] = false
return false
}
| 0 | Kotlin | 0 | 0 | 6672d7738b035202ece6f148fde05867f6d4d94c | 1,173 | DS_Algo_Kotlin | MIT License |
src/day4/Day04.kt | behnawwm | 572,034,416 | false | {"Kotlin": 11987} | package day4
import readInput
fun main() {
val fileLines = readInput("day04", "day4")
fun String.parseInput(): Pair<IntRange, IntRange> {
val (s1, e1) = substringBefore(",").split("-").map { it.toInt() }
val (s2, e2) = substringAfter(",").split("-").map { it.toInt() }
val range1 = s1..e1
val range2 = s2..e2
return range1 to range2
}
fun part1(fileLines: List<String>): Int {
var sum = 0
fileLines.forEach {
val (range1, range2) = it.parseInput()
if ((range1.first in range2 && range1.last in range2) || (range2.first in range1 && range2.last in range1))
sum += 1
}
return sum
}
fun part2(fileLines: List<String>): Int {
var sum = 0
fileLines.forEach {
val (range1, range2) = it.parseInput()
if (range1.first in range2 || range1.last in range2 || range2.first in range1 || range2.last in range1)
sum += 1
}
return sum
}
// println(part1(fileLines))
println(part2(fileLines))
} | 0 | Kotlin | 0 | 2 | 9d1fee54837cfae38c965cc1a5b267d7d15f4b3a | 1,103 | advent-of-code-kotlin-2022 | Apache License 2.0 |
src/main/kotlin/io/github/clechasseur/adventofcode/y2022/Day21.kt | clechasseur | 567,968,171 | false | {"Kotlin": 493887} | package io.github.clechasseur.adventofcode.y2022
import io.github.clechasseur.adventofcode.y2022.data.Day21Data
object Day21 {
private val input = Day21Data.input
fun part1(): Long {
val monkeys = input.toMonkeys()
return monkeys["root"]!!.equation(monkeys).value.toLong()
}
fun part2(): Long {
// I did this:
// val monkeys = input.toMonkeys().toMutableMap()
// monkeys["humn"] = Yeller("humn")
// val root = monkeys["root"]!! as MathHead
// val left = monkeys[root.monkey1]!!.equation(monkeys).value
// val right = monkeys[root.monkey2]!!.equation(monkeys).value
// println("$left == $right")
// Then simplified by hand to this:
return ((((((((((((((((((((((((((((((-((7628196411405L * 11L - 886L - 676L) / 11L) + 17319158992161L) * 5L - 351L - 846L - 297L) / 4L + 921L) * 10L + 594L) / 2L - 422L) * 2L - 668L) / 2L + 659L) / 75L - 834L) * 6L + 140L) * 6L - 978L) / 2L + 324L) * 11L + 657L) / 2L - 489L) / 2L + 290L) * 2L - 814L) / 6L - 391L) * 3L - 358L + 113L) / 2L - 958L) * 2L + 989L) * 2L - 656L) / 3L + 195L) * 5L + 173L) / 2L - 675L) / 16L - 602L) * 9L + 4L) * 3L + 505L) / 2L - 233L) / 5L + 945L) * 4L - 56L) / 58L - 697L) * 5L + 510L
// Not sure if it would've been quicker to actually implement a simplifier...
}
private val mathRegex = """(\w+) ([+*/-]) (\w+)""".toRegex()
private val monkeyRegex = "(\\w+): (\\d+|${mathRegex.pattern})".toRegex()
private val ops = mapOf<String, (Long, Long) -> Long>(
"+" to { a, b -> a + b },
"-" to { a, b -> a - b },
"*" to { a, b -> a * b },
"/" to { a, b -> a / b },
)
private sealed interface EqNode {
val value: String
}
private class ValueNode(override val value: String) : EqNode
private class OpNode(val left: EqNode, val right: EqNode, val op: String) : EqNode {
override val value: String
get() {
val leftValue = left.value
val rightValue = right.value
val leftLongValue = leftValue.toLongOrNull()
val rightLongValue = rightValue.toLongOrNull()
return if (leftLongValue != null && rightLongValue != null) {
"${ops[op]!!(leftLongValue, rightLongValue)}L"
} else {
"($leftValue $op $rightValue)"
}
}
}
private abstract class Monkey {
abstract fun equation(monkeys: Map<String, Monkey>): EqNode
}
private class Yeller(val number: String) : Monkey() {
override fun equation(monkeys: Map<String, Monkey>): EqNode = ValueNode(number)
}
private class MathHead(val monkey1: String, val monkey2: String, val op: String) : Monkey() {
override fun equation(monkeys: Map<String, Monkey>): EqNode =
OpNode(monkeys[monkey1]!!.equation(monkeys), monkeys[monkey2]!!.equation(monkeys), op)
}
private fun String.toMonkeys(): Map<String, Monkey> = lines().associate { line ->
val match = monkeyRegex.matchEntire(line) ?: error("Wrong monkey line: $line")
val (name, yell) = match.destructured
val number = yell.toLongOrNull()
if (number != null) {
name to Yeller(number.toString())
} else {
val mathMatch = mathRegex.matchEntire(yell) ?: error("Wrong math yell: $yell")
val (monkey1, op, monkey2) = mathMatch.destructured
name to MathHead(monkey1, monkey2, op)
}
}
}
| 0 | Kotlin | 0 | 0 | 7ead7db6491d6fba2479cd604f684f0f8c1e450f | 3,554 | adventofcode2022 | MIT License |
data_structures/x_fast_trie/Kotlin/XFastTrie.kt | ZoranPandovski | 93,438,176 | false | {"Jupyter Notebook": 21909905, "C++": 1692994, "Python": 1158220, "Java": 806066, "C": 560110, "JavaScript": 305918, "Go": 145277, "C#": 117882, "PHP": 85458, "Kotlin": 72238, "Rust": 53852, "Ruby": 43243, "MATLAB": 34672, "Swift": 31023, "Processing": 22089, "HTML": 18961, "Haskell": 14298, "Dart": 11842, "CSS": 10509, "Scala": 10277, "Haxe": 9750, "PureScript": 9122, "M": 9006, "Perl": 8685, "Prolog": 8165, "Shell": 7901, "Erlang": 7483, "Assembly": 7284, "R": 6832, "Lua": 6392, "LOLCODE": 6379, "VBScript": 6283, "Clojure": 5598, "Elixir": 5495, "OCaml": 3989, "Crystal": 3902, "Common Lisp": 3839, "Julia": 3567, "F#": 3376, "TypeScript": 3268, "Nim": 3201, "Brainfuck": 2466, "Visual Basic .NET": 2033, "ABAP": 1735, "Pascal": 1554, "Groovy": 976, "COBOL": 887, "Mathematica": 799, "Racket": 755, "PowerShell": 708, "Ada": 490, "CMake": 393, "Classic ASP": 339, "QMake": 199, "Makefile": 111} | /**
* X-fast trie is a data structure for storing integers from a bounded domain
* More info about the structure and complexity here: https://en.wikipedia.org/wiki/X-fast_trie
*/
class XFastTrie(domain: Long) {
private class Node(var left: Node? = null, var right: Node? = null,
var leftAdiac: Node? = null, var rightAdiac: Node? = null) {
var descendant: Node? = null
var key: Long? = null
fun isLeaf(): Boolean = (left == null && right == null)
}
private val root = Node()
private val levels: Int = java.lang.Long.numberOfLeadingZeros(0) - java.lang.Long.numberOfLeadingZeros(domain) + 1
private var hashes: Array<MutableMap<Long, Node>> = Array(this.levels, {HashMap<Long, Node>()})
fun add(key: Long) {
val pred = nodePredecessor(key)
val succ = nodeSuccessor(key)
val newNode = Node(leftAdiac = pred, rightAdiac = succ)
pred?.rightAdiac = newNode
succ?.leftAdiac = newNode
newNode.key = key
add(key, leaf = newNode)
}
private fun add(key: Long, leaf: Node) {
var currentNode = root
for (level in this.levels-2 downTo 1) {
if (((key shr level) and 1L) == 1L) {
if (currentNode.right == null) {
currentNode.right = Node()
hashes[level].put(key shr level, currentNode.right!!)
}
currentNode = currentNode.right!!
}
else {
if (currentNode.left == null) {
currentNode.left = Node()
hashes[level].put(key shr level, currentNode.left!!)
}
currentNode = currentNode.left!!
}
}
if (key and 1L == 1L)
currentNode.right = leaf
else
currentNode.left = leaf
hashes[0].put(key, leaf)
fixDescendants(root, key, this.levels-2)
}
private fun fixDescendants(currentNode: Node, key: Long, level: Int) : Pair<Node?, Node?>{
if (level == -1)
return Pair(currentNode, currentNode)
val nextNode = if (((key shr level) and 1L) == 1L) currentNode.right else currentNode.left
var (minNode, maxNode) = fixDescendants(nextNode!!, key, level-1)
if (nextNode == currentNode.right && currentNode.left == null && minNode != null)
currentNode.descendant = minNode
else if (nextNode == currentNode.right && currentNode.left != null)
minNode = null
else if (nextNode == currentNode.left && currentNode.right == null && maxNode != null)
currentNode.descendant = maxNode
else if (nextNode == currentNode.left && currentNode.right != null)
maxNode = null
return Pair(minNode, maxNode)
}
fun find(key: Long) = hashes[0].contains(key)
private fun getAncestor(key: Long): Node{
var step = 1
var level = levels-1
while (step < levels) step *= 2
while (step > 0) {
if (level - step >= 0 && hashes[level - step].containsKey(key shr (level - step)))
level -= step
step /= 2
}
return if (level == levels-1) root else hashes[level].get(key shr level)!!
}
private fun nodeSuccessor(key: Long): Node? {
val lowestAncenstor = getAncestor(key)
if (lowestAncenstor.isLeaf())
return lowestAncenstor.rightAdiac
val descendant = lowestAncenstor.descendant
if (lowestAncenstor.left == null)
return descendant
if (lowestAncenstor.right == null)
return descendant?.rightAdiac
return null
}
private fun nodePredecessor(key: Long): Node? {
val lowestAncestor = getAncestor(key)
val descendant = lowestAncestor.descendant
if (lowestAncestor.isLeaf())
return lowestAncestor.leftAdiac
if (lowestAncestor.left == null)
return descendant?.leftAdiac
if (lowestAncestor.right == null)
return descendant
return null
}
fun successor(key: Long): Long? = nodeSuccessor(key)?.key
fun predecessor(key: Long): Long? = nodePredecessor(key)?.key
/**
* Returns true if the key existed
*/
fun delete(key: Long): Boolean {
val leaf = hashes[0][key] ?: return false
val leftAdiac = leaf.leftAdiac
val rightAdiac = leaf.rightAdiac
leftAdiac?.rightAdiac = rightAdiac
rightAdiac?.leftAdiac = leftAdiac
hashes[0].remove(key)
removePath(root, key, leftAdiac, rightAdiac, levels-2, leaf)
return true
}
/**
* Return true if node is deleted
*/
private fun removePath(currentNode: Node, key: Long, leftAdiac: Node?, rightAdiac: Node?, level: Int, leaf: Node): Boolean {
if (level == -1)
return true
val nextNode = if (((key shr level) and 1L) == 1L) currentNode.right else currentNode.left
val del = removePath(nextNode!!, key, leftAdiac, rightAdiac, level - 1, leaf)
if (currentNode.right == nextNode && del) {
currentNode.right = null
currentNode.descendant = leftAdiac
}
if (currentNode.left == nextNode && del){
currentNode.left = null
currentNode.descendant = rightAdiac
}
if (currentNode.left == null && currentNode.right == null) {
hashes[level+1].remove(key shr (level+1))
return true
}
else if (currentNode.left == nextNode && currentNode.right == null &&
currentNode.descendant == leaf) {
currentNode.descendant = leftAdiac
}
else if (currentNode.right == nextNode && currentNode.left == null &&
currentNode.descendant == leaf) {
currentNode.descendant = rightAdiac
}
return false
}
}
fun checkContains(trie: XFastTrie, values: List<Long>, MAX_VALUE: Long) {
for (i in 0..MAX_VALUE) {
val myNext = values.filter({it > i}).sorted().firstOrNull()
val actualNext = trie.successor(i)
val myPrev = values.filter({it < i}).sorted().lastOrNull()
val actualPrev = trie.predecessor(i)
if (myNext != actualNext)
println("error")
if (myPrev != actualPrev)
println("error")
}
val myContent = (0..MAX_VALUE).filter { trie.find(it) }.sorted().toLongArray()
if (!(myContent contentEquals values.sorted().toLongArray()))
println("error")
}
fun main(args: Array<String>) {
val MAX_VALUE = 1023L
val TO_ADD = 200
val TO_DELETE = 80
val trie = XFastTrie(MAX_VALUE)
val values = (0..MAX_VALUE).shuffled().subList(0, TO_ADD)
values.forEach { trie.add(it) }
checkContains(trie, values, MAX_VALUE)
val toDel = values.shuffled().subList(0, TO_DELETE)
val rest = values.filter { !toDel.contains(it) }
toDel.forEach { trie.delete(it) }
checkContains(trie, rest, MAX_VALUE)
}
| 62 | Jupyter Notebook | 1,994 | 1,298 | 62a1a543b8f3e2ca1280bf50fc8a95896ef69d63 | 7,069 | al-go-rithms | Creative Commons Zero v1.0 Universal |
src/Day08.kt | carloxavier | 574,841,315 | false | {"Kotlin": 14082} | fun main() {
check(
ForestRanger(readInput("Day08_test"))
.getTreesVisibleFromOutside()
.size == 21
)
check(
ForestRanger(readInput("Day08_test"))
.getMaxVisibilityIndex() == 8
)
// Part1
println(
ForestRanger(readInput("Day08"))
.getTreesVisibleFromOutside()
.size
)
// Part2
println(
ForestRanger(readInput("Day08"))
.getMaxVisibilityIndex()
)
}
class ForestRanger(gridInput: List<String>) {
private var treeGrid: List<List<Tree>> = gridInput.mapIndexed { posX, row ->
row.mapIndexed { posY, height ->
Tree(posX, posY, height.digitToInt())
}
}
private val visibleTrees = hashSetOf<Tree>()
fun getTreesVisibleFromOutside(): Set<Tree> {
checkHorizontalVisibilities()
checkVerticalVisibilities()
return visibleTrees
}
fun getMaxVisibilityIndex(): Int {
var maxVisibility = Int.MIN_VALUE
for (i in treeGrid.indices) {
for (j in treeGrid.indices) {
val visibilityIndex = getVisibilityIndex(i, j)
if (visibilityIndex > maxVisibility) {
maxVisibility = visibilityIndex
}
}
}
return maxVisibility
}
private fun getVisibilityIndex(posX: Int, posY: Int): Int {
if (posX == 0 || posY == 0 || posX == treeGrid.size - 1 || posY == treeGrid.size - 1) {
return 0
}
val tree = treeGrid[posX][posY]
var upIndex = 0
for (i in posX - 1 downTo 0) {
upIndex++
if (treeGrid[i][posY].height >= tree.height) {
break
}
}
var downIndex = 0
for (i in posX + 1 until treeGrid.size) {
downIndex++
if (treeGrid[i][posY].height >= tree.height) {
break
}
}
var leftIndex = 0
for (i in posY - 1 downTo 0) {
leftIndex++
if (treeGrid[posX][i].height >= tree.height) {
break
}
}
var rightIndex = 0
for (i in posY + 1 until treeGrid.size) {
rightIndex++
if (treeGrid[posX][i].height >= tree.height) {
break
}
}
return upIndex * downIndex * leftIndex * rightIndex
}
private fun checkVerticalVisibilities() {
for (i in treeGrid.indices) {
var biggestHeight = Int.MIN_VALUE
// Check visibility from the top
for (j in 0 until treeGrid.first().size) {
val tree = treeGrid[j][i]
if (tree.height > biggestHeight) {
biggestHeight = tree.height
visibleTrees.add(tree)
}
}
biggestHeight = Int.MIN_VALUE
// Check visibility from the bottom
for (j in (0 until treeGrid.first().size).reversed()) {
val tree = treeGrid[j][i]
if (tree.height > biggestHeight) {
biggestHeight = tree.height
visibleTrees.add(tree)
}
}
}
}
private fun checkHorizontalVisibilities() {
treeGrid.forEach { row ->
var biggestHeight = Int.MIN_VALUE
// check visibility from the left
row.forEach { tree ->
if (tree.height > biggestHeight) {
biggestHeight = tree.height
visibleTrees.add(tree)
}
}
biggestHeight = Int.MIN_VALUE
// check visibility from the right
row.reversed().forEach { tree ->
if (tree.height > biggestHeight) {
biggestHeight = tree.height
visibleTrees.add(tree)
}
}
}
}
}
data class Tree(val posX: Int, val posY: Int, val height: Int) | 0 | Kotlin | 0 | 0 | 4e84433fe866ce1a8c073a7a1e352595f3ea8372 | 4,051 | adventOfCode2022 | Apache License 2.0 |
rmq/RangeUpdateSegmentTree.kt | wangchaohui | 737,511,233 | false | {"Kotlin": 36737} | class RangeUpdateSegmentTree(private val n: Int) {
data class Interval(
var b: Int = 0,
var v: Int = 1000000,
)
private val t = Array(n * 2) { Interval() }
private fun set(p: Int, b: Int, v: Int) {
if (p !in t.indices || t[p].v < v) return
t[p].b = b
t[p].v = v
}
private fun push(p: Int) {
var s = p.takeHighestOneBit()
while (s > 0) {
val i = p / s
if (t[i].b > 0) {
set(i * 2, t[i].b, t[i].v)
set(i * 2 + 1, t[i].b, t[i].v)
// clear lazy tag
}
s /= 2
}
}
fun query(p: Int): Interval {
val i = p + n
push(i)
return t[i]
}
fun update(l: Int, r: Int, b: Int, v: Int) {
var i = l + n
var j = r + n
while (i < j) {
if (i % 2 == 1) set(i++, b, v)
if (j % 2 == 1) set(--j, b, v)
i /= 2
j /= 2
}
// updates the parents of l & r
}
data class D(
val key: String,
val interval: Interval,
) {
override fun toString() = if (key.isNotEmpty()) "$key -> $interval" else ""
}
fun debug(): List<D> {
val l = Array(t.size) { 0 }
val r = Array(t.size) { -1 }
for (i in 0..<n) {
l[i + n] = i
r[i + n] = i
}
for (i in t.lastIndex downTo 2) {
if (i % 2 == 0) {
l[i / 2] = l[i]
} else {
r[i / 2] = r[i]
}
}
return t.mapIndexed { i, interval ->
D(
when {
l[i] > r[i] -> ""
l[i] == r[i] -> "[${l[i]}]"
else -> "[${l[i]},${r[i]}]"
},
interval,
)
}
}
}
| 0 | Kotlin | 0 | 0 | 241841f86fdefa9624e2fcae2af014899a959cbe | 1,883 | kotlin-lib | Apache License 2.0 |
src/Day10.kt | olezhabobrov | 572,687,414 | false | {"Kotlin": 27363} | import java.lang.Math.abs
fun main() {
fun part1(input: List<String>): Int {
var counter = 0
var result = 0
input.fold(1) { cur, s ->
val lst = s.split(" ")
var new = cur
if (lst.size == 1) {
counter++
} else {
counter++
if ((counter - 20) % 40 == 0 && counter <= 220) {
result += counter * cur
}
counter++
new += lst[1].toInt()
}
if ((counter - 20) % 40 == 0 && counter <= 220) {
result += counter * cur
}
new
}
return result
}
fun part2(input: List<String>) {
var cycle = 0
var result = ""
input.fold(1) { cur, s ->
val lst = s.split(" ")
var new = cur
if (lst.size == 1) {
cycle++
} else {
cycle++
if (abs(((cycle - 1) % 40) - cur) <= 1) {
result += "#"
} else {
result += "."
}
cycle++
new += lst[1].toInt()
}
if (abs(((cycle - 1) % 40) - cur) <= 1) {
result += "#"
} else {
result += "."
}
new
}
println(result.chunked(40).joinToString(System.lineSeparator()))
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day10_test")
check(part1(testInput) == 13140)
part2(testInput)
val input = readInput("Day10")
println(part1(input))
part2(input)
}
| 0 | Kotlin | 0 | 0 | 31f2419230c42f72137c6cd2c9a627492313d8fb | 1,743 | AdventOfCode | Apache License 2.0 |
day5/src/main/kotlin/aoc2015/day5/Day5.kt | sihamark | 581,653,112 | false | {"Kotlin": 263428, "Shell": 467, "Batchfile": 383} | package aoc2015.day5
/**
* [https://adventofcode.com/2015/day/5]
*/
object Day5 {
fun validatePart1() = countValid(Part1Validator())
fun validatePart2() = countValid(Part2Validator()).also {
assert(it == 53) { "there should be 53 valid string in part two" }
}
private fun countValid(validator: Validator): Int = input.filter { validator.validate(it) }.size
interface Validator {
fun validate(string: String): Boolean
}
class Part1Validator : Validator {
private val prohibitedSubstrings = listOf("ab", "cd", "pq", "xy")
private val vowels = listOf('a', 'e', 'i', 'o', 'u')
override fun validate(string: String): Boolean =
string.containsAtLeastThreeVowels()
&& string.containsDoubleLetter()
&& string.containsNoProhibitedString()
private fun String.containsAtLeastThreeVowels() = filter { it in vowels }.length >= 3
private fun String.containsDoubleLetter(): Boolean {
var latestChar = first()
drop(1).forEach {
if (latestChar == it) return true
latestChar = it
}
return false
}
private fun String.containsNoProhibitedString(): Boolean {
prohibitedSubstrings.forEach {
if (contains(it)) return false
}
return true
}
}
class Part2Validator : Validator {
override fun validate(string: String) =
string.containsRepeatTuple()
&& string.containsEnclosingRepeat()
private fun String.containsRepeatTuple(): Boolean {
val tuples = mutableSetOf<String>()
var latestChar = this.first()
this.drop(1).forEach {
tuples += latestChar.toString() + it.toString()
latestChar = it
}
val tupleCount = tuples.associateWith {
this.countNotOverlapping(it)
}
return (tupleCount.any { it.value > 1 })
}
private fun String.countNotOverlapping(subString: String): Int {
var counter = 0
var workingString = this
while (workingString.contains(subString)) {
counter++
workingString = workingString.replaceFirst(subString, "**")
}
return counter
}
private fun String.containsEnclosingRepeat(): Boolean {
forEachIndexed { index, c ->
if (c == this.getOrNull(index + 2)) return true
}
return false
}
}
}
| 0 | Kotlin | 0 | 0 | 6d10f4a52b8c7757c40af38d7d814509cf0b9bbb | 2,679 | aoc2015 | Apache License 2.0 |
solutions/src/CountSortedVowelStrings.kt | JustAnotherSoftwareDeveloper | 139,743,481 | false | {"Kotlin": 305071, "Java": 14982} | /**
* https://leetcode.com/problems/count-sorted-vowel-strings/
*/
class CountSortedVowelStrings {
fun countVowelStrings(n: Int): Int {
if (n == 1) {
return 5
}
val vowelMap : MutableMap<Pair<Int,Char>,Int> = mutableMapOf()
val vowels = mutableListOf('a','e','i','o','u')
vowels.forEach { vowelMap[Pair(1,it)] = 1 }
for (i in 1 until n) {
for (v in vowels) {
val current = vowelMap[Pair(i,v)]!!
when (v) {
'a' -> {
vowelMap[Pair(i+1,'a')] = vowelMap.getOrDefault(Pair(i+1,'a'),0)+current
vowelMap[Pair(i+1,'e')] = vowelMap.getOrDefault(Pair(i+1,'e'),0)+current
vowelMap[Pair(i+1,'i')] = vowelMap.getOrDefault(Pair(i+1,'i'),0)+current
vowelMap[Pair(i+1,'o')] = vowelMap.getOrDefault(Pair(i+1,'o'),0)+current
vowelMap[Pair(i+1,'u')] = vowelMap.getOrDefault(Pair(i+1,'u'),0)+current
}
'e' -> {
vowelMap[Pair(i+1,'e')] = vowelMap.getOrDefault(Pair(i+1,'e'),0)+current
vowelMap[Pair(i+1,'i')] = vowelMap.getOrDefault(Pair(i+1,'i'),0)+current
vowelMap[Pair(i+1,'o')] = vowelMap.getOrDefault(Pair(i+1,'o'),0)+current
vowelMap[Pair(i+1,'u')] = vowelMap.getOrDefault(Pair(i+1,'u'),0)+current
}
'i' -> {
vowelMap[Pair(i+1,'i')] = vowelMap.getOrDefault(Pair(i+1,'i'),0)+current
vowelMap[Pair(i+1,'o')] = vowelMap.getOrDefault(Pair(i+1,'o'),0)+current
vowelMap[Pair(i+1,'u')] = vowelMap.getOrDefault(Pair(i+1,'u'),0)+current
}
'o' -> {
vowelMap[Pair(i+1,'o')] = vowelMap.getOrDefault(Pair(i+1,'o'),0)+current
vowelMap[Pair(i+1,'u')] = vowelMap.getOrDefault(Pair(i+1,'u'),0)+current
}
'u' -> {
vowelMap[Pair(i+1,'u')] = vowelMap.getOrDefault(Pair(i+1,'u'),0)+current
}
}
}
}
var sum = 0
for (v in vowels) {
sum+= vowelMap[Pair(n,v)]!!
}
return sum
}
} | 0 | Kotlin | 0 | 0 | fa4a9089be4af420a4ad51938a276657b2e4301f | 2,402 | leetcode-solutions | MIT License |
cz.wrent.advent/Day12.kt | Wrent | 572,992,605 | false | {"Kotlin": 206165} | package cz.wrent.advent
fun main() {
println(partOne(test))
val result = partOne(input)
println("12a: $result")
println(partTwo(test))
println("12b: ${partTwo(input)}")
}
private fun partOne(input: String): Int {
val map = input.parse()
val start = map.entries.find { it.value.specialArea == SpecialArea.START }!!.key
map[start]!!.steps = 0
process(map, start) {
(0..it + 1)
}
return map.entries.find { it.value.specialArea == SpecialArea.END }!!.value.steps
}
private fun partTwo(input: String): Int {
val map = input.parse()
val start = map.entries.find { it.value.specialArea == SpecialArea.END }!!.key
map[start]!!.steps = 0
process(map, start) {
it - 1..Int.MAX_VALUE
}
return map.entries.filter { it.value.height == 'a'.code }.minByOrNull { it.value.steps }!!.value.steps
}
private fun process(map: Map<Pair<Int, Int>, Area>, start: Pair<Int, Int>, moveRange: (Int) -> IntRange) {
var next = listOf(start)
while (next.isNotEmpty()) {
val n = next.last()
next = next.dropLast(1)
val neighbours = n.toNeighbours()
neighbours.forEach { neighbour ->
if (map[neighbour] != null && map[neighbour]!!.height in moveRange(map[n]!!.height) && map [neighbour]!!.steps > map[n]!!.steps + 1) {
map[neighbour]!!.steps = map[n]!!.steps + 1
next = next + neighbour
}
}
}
}
fun Pair<Int, Int>.toNeighbours(): Set<Pair<Int, Int>> {
return setOf(
this.first to this.second + 1,
this.first to this.second - 1,
this.first + 1 to this.second,
this.first - 1 to this.second
)
}
private fun String.parse(): Map<Pair<Int, Int>, Area> {
val lines = this.split("\n")
val map = mutableMapOf<Pair<Int, Int>, Area>()
lines.forEachIndexed { j, line ->
line.toCharArray().map { it.code }
.forEachIndexed { i, height ->
if (height == 'S'.code) {
map[i to j] = Area('a'.code, specialArea = SpecialArea.START)
} else if (height == 'E'.code) {
map[i to j] = Area('z'.code, specialArea = SpecialArea.END)
} else {
map[i to j] = Area(height)
}
}
}
return map
}
private data class Area(
val height: Int,
var steps: Int = Int.MAX_VALUE,
val specialArea: SpecialArea? = null
)
private enum class SpecialArea {
START,
END
}
private const val test = """Sabqponm
abcryxxl
accszExk
acctuvwj
abdefghi
"""
private const val input =
"""abcccccccaaaaaaaaccccccccccaaaaaaccccccaccaaaaaaaccccccaacccccccccaaaaaaaaaaccccccccccccccccccccccccccccccccaaaaa
abcccccccaaaaaaaaacccccccccaaaaaacccccaaacaaaaaaaaaaaccaacccccccccccaaaaaaccccccccccccccccccccccccccccccccccaaaaa
abcccccccaaaaaaaaaaccccccccaaaaaacaaacaaaaaaaaaaaaaaaaaaccccccccccccaaaaaaccccccccccccccaaacccccccccccccccccaaaaa
abaaacccccccaaaaaaacccccccccaaacccaaaaaaaaaaaaaaaaaaaaaaaaacccccccccaaaaaaccccccccccccccaaacccccccccccccccccaaaaa
abaaaaccccccaaaccccccccccccccccccccaaaaaaaaacaaaacacaaaaaacccccccccaaaaaaaacccccccccccccaaaaccaaacccccccccccaccaa
abaaaaccccccaaccccaaccccccccccccccccaaaaaaacaaaaccccaaaaaccccccccccccccccacccccccccccccccaaaaaaaaacccccccccccccca
abaaaaccccccccccccaaaacccccccccaacaaaaaaaacccaaacccaaacaacccccccccccccccccccccccccccciiiiaaaaaaaacccccccccccccccc
abaaacccccccccccaaaaaacccccccccaaaaaaaaaaacccaaacccccccaacccccccccccaacccccccccccccciiiiiiijaaaaccccccccaaccccccc
abaaaccccccccccccaaaacccccccccaaaaaaaacaaacccaaaccccccccccccccccccccaaacaaacccccccciiiiiiiijjjacccccccccaaacccccc
abcccccaacaacccccaaaaaccccccccaaaaaacccccacaacccccccccccccccccccccccaaaaaaaccccccciiiinnnoijjjjjjjjkkkaaaaaaacccc
abcccccaaaaacccccaacaaccccccccccaaaacccaaaaaaccccccccccccccccccccccccaaaaaaccccccciiinnnnooojjjjjjjkkkkaaaaaacccc
abccccaaaaacccccccccccccccccccccaccccccaaaaaaaccccccccccccccccccccaaaaaaaaccccccchhinnnnnoooojjooopkkkkkaaaaccccc
abccccaaaaaaccccccccccccccccccccccccccccaaaaaaacccccccccccccccccccaaaaaaaaacccccchhhnnntttuooooooopppkkkaaaaccccc
abccccccaaaaccccccccccacccccccccccccccccaaaaaaacccaaccccccccccccccaaaaaaaaaaccccchhhnnttttuuoooooppppkkkaaaaccccc
abccccccaccccccccccccaaaacaaaccccccccccaaaaaacaaccaacccaaccccccccccccaaacaaacccchhhnnnttttuuuuuuuuupppkkccaaccccc
abccccccccccccccaaccccaaaaaaaccccccccccaaaaaacaaaaaacccaaaaaaccccccccaaacccccccchhhnnntttxxxuuuuuuupppkkccccccccc
abcccccccccccccaaaacccaaaaaaacccaccccccccccaaccaaaaaaacaaaaaaccccccccaacccaaccchhhhnnnttxxxxuuyyyuupppkkccccccccc
abcccccccccccccaaaaccaaaaaaaaacaaacccccccccccccaaaaaaaaaaaaaccccccccccccccaaachhhhmnnnttxxxxxxyyyuvppkkkccccccccc
abcccccccccccccaaaacaaaaaaaaaaaaaaccccccccccccaaaaaacaaaaaaaccccccccccccccaaaghhhmmmttttxxxxxyyyyvvpplllccccccccc
abccacccccccccccccccaaaaaaaaaaaaaaccccccccccccaaaaaacccaaaaaacccaacaacccaaaaagggmmmttttxxxxxyyyyvvppplllccccccccc
SbaaaccccccccccccccccccaaacaaaaaaaacccccccccccccccaacccaaccaacccaaaaacccaaaagggmmmsttxxxEzzzzyyvvvppplllccccccccc
abaaaccccccccccccccccccaaaaaaaaaaaaacaaccccccccccccccccaaccccccccaaaaaccccaagggmmmsssxxxxxyyyyyyvvvqqqlllcccccccc
abaaacccccccccccccccccccaaaaaaaaaaaaaaaaacccccccccccccccccccccccaaaaaaccccaagggmmmsssxxxwywyyyyyyvvvqqlllcccccccc
abaaaaacccccccccccccccccccaacaaaccaaaaaaacccccccccccccccccccccccaaaaccccccaagggmmmssswwwwwyyyyyyyvvvqqqllcccccccc
abaaaaaccccccccccccccccccccccaaaccccaaaacccccccccccccccccaaccaacccaaccccccccgggmmmmssssswwyywwvvvvvvqqqlllccccccc
abaaaaacccccccccccccaccacccccaaaccccaaaacccccccccccccccccaaaaaacccccccccccaaggggmllllsssswwywwwvvvvqqqqlllccccccc
abaaccccccccccccccccaaaaccccccccccccaccaccccccccccccccccccaaaaacccccccccccaaagggglllllssswwwwwrrqqqqqqmmllccccccc
abaaccccccccccccccccaaaaaccccccaaccaaccccccccccccccccccccaaaaaaccaacccccccaaaaggfffllllsswwwwrrrrqqqqqmmmcccccccc
abacaaaccccccccccccaaaaaaccccccaaaaaaccccccaacccccccccccaaaaaaaacaaacaaccccaaaaffffflllsrrwwwrrrmmmmmmmmmcccccccc
abaaaaaccccccccccccaaaaaaccccccaaaaaccccccaaaaccccccccccaaaaaaaacaaaaaaccccaaaaccfffflllrrrrrrkkmmmmmmmccccaccccc
abaaaacccccccccccccccaaccccccccaaaaaacccccaaaacccccccccccccaaccaaaaaaaccccccccccccffflllrrrrrkkkmmmmmccccccaccccc
abaaacccccccccccccccccccccccccaaaaaaaaccccaaaacccccccccccccaaccaaaaaaacccccccccccccfffllkrrrkkkkmddddcccccaaacccc
abaaacccccccccccccccccccccccccaaaaaaaacccccccccccccccccccccccccccaaaaaaccccccccccccfffllkkkkkkkdddddddcaaaaaacccc
abaaaacccccccccccccccccccccccccccaaccccccccccccccccccccccccccccccaacaaacccccccccccccfeekkkkkkkddddddcccaaaccccccc
abcaaacccccccccccaaaccccccccaacccaaccccaaaaaccccaaaccccccccccccccaaccccccccccccccccceeeeekkkkdddddccccccaaccccccc
abccccccccccccccaaaaaaccccccaaacaaccacaaaaaaaccaaaaccccccccccaccaaccccccccccccccccccceeeeeeeedddacccccccccccccccc
abccccccccccccccaaaaaacccccccaaaaacaaaaaccaaaaaaaacccccccccccaaaaacccccccccccccccccccceeeeeeedaaacccccccccccccaaa
abccccccaaacccccaaaaacccccccaaaaaacaaaaaaaaaaaaaaaccccccccccccaaaaaccccccccccccccccccccceeeeecaaacccccccccccccaaa
abccccccaaaccccccaaaaacccccaaaaaaaaccaaaaacaaaaaaccccccccccccaaaaaacccccccccccccccccccccaaaccccaccccccccccccccaaa
abccccaacaaaaacccaaaaacccccaaaaaaaacaaaaaaaaaaaaaaaccccaaaaccaaaacccccccccccccccccccccccaccccccccccccccccccaaaaaa
abccccaaaaaaaaccccccccccccccccaaccccaacaaaaaaaaaaaaaaccaaaaccccaaacccccccccccccccccccccccccccccccccccccccccaaaaaa"""
| 0 | Kotlin | 0 | 0 | 8230fce9a907343f11a2c042ebe0bf204775be3f | 6,991 | advent-of-code-2022 | MIT License |
src/main/kotlin/dev/bogwalk/batch4/Problem44.kt | bog-walk | 381,459,475 | false | null | package dev.bogwalk.batch4
import dev.bogwalk.util.maths.isPentagonalNumber
/**
* Problem 44: Pentagon Numbers
*
* https://projecteuler.net/problem=44
*
* Goal: For a given K, find all P_n, where n < N, such that P_n - P_(n-K) || P_n + P_(n-K) is
* also pentagonal.
*
* Constraints: 1 <= K <= 9999, K+1 <= N <= 1e6
*
* Pentagonal Number: The sequence is generated by -> pN = n(3n - 1) / 2 ->
* 1, 5, 12, 22, 35, 51, 70, 92, 117, 145,...
*
* e.g. P_7 = 70 is special in that, if K = 2:
* P_7 - P_5 = 35 = P_5; and, if K = 3:
* P_7 + P_4 = 92 = P_8
*
* e.g.: N = 10, K = 2
* output = {70}
*/
class PentagonNumbers {
fun pentagonNumbersHR(n: Int, k: Int): Set<Long> {
val pNs = List(n) { 1L * it * (3 * it - 1) / 2 }
val results = mutableSetOf<Long>()
for (i in k + 1 until n - 1) {
val pN = pNs[i]
val pNMinusK = pNs[i - k]
if (
(pN - pNMinusK).isPentagonalNumber() != null ||
(pN + pNMinusK).isPentagonalNumber() != null
) {
results.add(pN)
}
}
return results
}
/**
* Project Euler specific implementation that returns the smallest difference, |P_x - P_y|,
* for a pair of pentagonal numbers whose sum and difference are both pentagonal.
*
* Surprisingly, the first eligible pair found has the smallest difference:
* P_x = 7_042_750, where x = 2167, and
* P_y = 1_560_090, where y = 1020.
*/
fun pentagonNumbersPE(): Int {
val pentagonals = List(10_001) { it * (3 * it - 1) / 2 }
var delta = Int.MAX_VALUE
for (x in 3..10_000) {
val pX = pentagonals[x]
for (y in x - 1 downTo 2) {
val pY = pentagonals[y]
val minus = pX - pY
if (
(pX + pY).toLong().isPentagonalNumber() == null ||
(minus).toLong().isPentagonalNumber() == null
) continue
delta = minOf(delta, minus)
}
}
return delta
}
} | 0 | Kotlin | 0 | 0 | 62b33367e3d1e15f7ea872d151c3512f8c606ce7 | 2,123 | project-euler-kotlin | MIT License |
src/Day02.kt | bkosm | 572,912,735 | false | {"Kotlin": 17839} | import Shape.Paper
import Shape.Rock
import Shape.Scissors
enum class Shape(val score: Int) {
Rock(1), Paper(2), Scissors(3);
}
val beatsMapping = mapOf(
Rock to Scissors,
Paper to Rock,
Scissors to Paper,
)
val codeMapping = mapOf(
"A" to Rock,
"B" to Paper,
"C" to Scissors,
"X" to Rock,
"Y" to Paper,
"Z" to Scissors,
)
const val drawBonus = 3
const val winBonus = 6
object Day02 : DailyRunner<Int, Int> {
private fun mapInput(input: List<String>) = input.map {
val (first, second) = it.split(" ")
codeMapping[first]!! to codeMapping[second]!!
}
private fun mapScores(opponent: Shape, mine: Shape) = when (opponent) {
mine -> drawBonus + mine.score
beatsMapping[mine] -> winBonus + mine.score
else -> mine.score
}
override fun do1(input: List<String>, isTest: Boolean): Int = mapInput(input).sumOf { (opponent, mine) ->
mapScores(opponent, mine)
}
override fun do2(input: List<String>, isTest: Boolean): Int = input.sumOf {
@Suppress("RemoveRedundantCallsOfConversionMethods")
when (it) {
"A X" -> 3
"A Y" -> 4
"A Z" -> 8
"B X" -> 1
"B Y" -> 5
"B Z" -> 9
"C X" -> 2
"C Y" -> 6
"C Z" -> 7
else -> 0.toInt()
}
}
}
fun main() {
Day02.run()
}
| 0 | Kotlin | 0 | 1 | 3f9cccad1e5b6ba3e92cbd836a40207a2f3415a4 | 1,419 | aoc22 | Apache License 2.0 |
src/main/kotlin/sschr15/aocsolutions/Day12.kt | sschr15 | 317,887,086 | false | {"Kotlin": 184127, "TeX": 2614, "Python": 446} | package sschr15.aocsolutions
import sschr15.aocsolutions.util.*
/**
* AOC 2023 [Day 12](https://adventofcode.com/2023/day/12)
* Challenge: figure out just how messed up all these spring layouts are
*/
object Day12 : Challenge {
@ReflectivelyUsed
override fun solve() = challenge(2023, 12) {
// test()
val recursiveCheck = memoized<String, List<Long>, Boolean, Long> { remaining, requirements, inRequirement ->
if (remaining.isEmpty()) {
return@memoized if (requirements.isEmpty() || requirements.singleOrNull() == 0L) 1 else 0
}
if (requirements.isEmpty()) {
// no # characters allowed, but otherwise it's a single valid solution
return@memoized if ('#' !in remaining) 1 else 0
}
if (requirements.first() < 0L) return@memoized 0 // already took too many hashes
val (first, rest) = remaining.first() to remaining.drop(1)
when {
first == '?' -> {
val withHash = recurse("#$rest", requirements, false)
val withoutHash = if (!inRequirement || requirements.first() == 0L) {
// only do this if it doesn't break a requirement
val newReqs = if (inRequirement) requirements.drop(1) else requirements
recurse(".${rest.dropWhile { c -> c == '.' }}", newReqs, false)
} else 0
withHash + withoutHash
}
first == '#' -> {
if (requirements.isEmpty()) return@memoized 0
val newRest = rest.dropWhile { c -> c == '#' }
val removed = 1 + (rest.length - newRest.length)
val newRequirements = listOf(requirements.first() - removed) + requirements.drop(1)
recurse(newRest, newRequirements, true)
}
inRequirement -> {
val (firstReq, restReq) = requirements.first() to requirements.drop(1)
if (firstReq == 0L) recurse(rest, restReq, false) else 0 // invalid if there's still a partially unsatisfied requirement
}
else -> {
val noStartDot = rest.dropWhile { c -> c == '.' }
recurse(noStartDot, requirements, false)
}
}
}
part1 {
inputLines.sumOf { s ->
val (map, requirements) = s.split(" ")
val groups = requirements.findLongs()
recursiveCheck(map, groups, false)
}
}
part2 {
inputLines.sumOf {
val (fakeMap, fakeReqs) = it.split(" ")
val realMap = listOf(fakeMap, fakeMap, fakeMap, fakeMap, fakeMap).joinToString("?")
val realReqs = listOf(fakeReqs, fakeReqs, fakeReqs, fakeReqs, fakeReqs).joinToString(",")
val requirementNums = realReqs.findLongs()
recursiveCheck(realMap, requirementNums, false)
}
}
}
@JvmStatic
fun main(args: Array<String>) = println("Time: ${solve()}")
}
| 0 | Kotlin | 0 | 0 | e483b02037ae5f025fc34367cb477fabe54a6578 | 3,223 | advent-of-code | MIT License |
2022/src/main/kotlin/de/skyrising/aoc2022/day7/solution.kt | skyrising | 317,830,992 | false | {"Kotlin": 411565} | package de.skyrising.aoc2022.day7
import de.skyrising.aoc.*
import it.unimi.dsi.fastutil.objects.Object2LongMap
import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap
import java.nio.file.Path
private fun parseInput(input: PuzzleInput): Object2LongMap<Path> {
val commands = mutableListOf<Pair<String, List<String>>>()
var current: Pair<String, MutableList<String>>? = null
for (line in input.lines) {
if (line.startsWith("$")) {
if (current != null) {
commands.add(current)
}
current = Pair(line.substring(2), mutableListOf())
} else {
current!!.second.add(line)
}
}
if (current != null) {
commands.add(current)
}
val spaceUsed = Object2LongOpenHashMap<Path>()
val root = Path.of("/")
var pwd = root
for ((command, output) in commands) {
if (command.startsWith("cd ")) {
pwd = pwd.resolve(command.substring(3)).normalize()
} else if (command.startsWith("ls")) {
for (line in output) {
if (line.startsWith("dir")) continue
val size = line.substringBefore(' ').toLong()
val name = line.substringAfter(' ').trim()
val path = root.resolve(pwd.resolve(name))
for (i in 1 until path.nameCount) {
val parent = path.subpath(0, i)
spaceUsed[parent] = spaceUsed.getLong(parent) + size
}
spaceUsed[root] = spaceUsed.getLong(root) + size
}
}
}
return spaceUsed
}
@PuzzleName("No Space Left On Device")
fun PuzzleInput.part1(): Any {
val spaceUsed = parseInput(this)
var sum = 0L
for (v in spaceUsed.values) {
if (v <= 100000) sum += v
}
return sum
}
fun PuzzleInput.part2(): Any {
val spaceUsed = parseInput(this)
var smallestMatching = Long.MAX_VALUE
val used = spaceUsed.getLong(Path.of("/"))
val available = 70000000 - used
for (v in spaceUsed.values) {
if (v + available >= 30000000) {
if (v < smallestMatching) {
smallestMatching = v
}
}
}
return smallestMatching
}
| 0 | Kotlin | 0 | 0 | 19599c1204f6994226d31bce27d8f01440322f39 | 2,237 | aoc | MIT License |
src/main/kotlin/07-aug.kt | aladine | 276,334,792 | false | {"C++": 70308, "Kotlin": 53152, "Java": 10020, "Makefile": 511} | /**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
import java.util.*
class Aug07Solution {
var offset = 0
fun dfs(n: TreeNode?, x: Int, y: Int, map: HashMap<Int,ArrayList<Pair<Int,Int>>>){
if(n==null) return
offset = minOf(x, offset)
val l = map.getOrDefault(x,ArrayList<Pair<Int,Int>>())
l.add(Pair(y, n.`val`))
map[x] = l
n.left?.let {
dfs(it, x-1, y+1, map)
}
n.right?.let {
dfs(it, x+1, y+1, map)
}
}
fun verticalTraversal(root: TreeNode?): List<List<Int>> {
if (root == null) return emptyList()
val map = HashMap<Int,ArrayList<Pair<Int,Int>>>()
dfs(root,0,0,map)
val res = Array<List<Int>>(map.size) {listOf<Int>()}
for(entry in map.entries) {
res[entry.key-offset] = entry.value.sortedWith(Comparator{t1,t2 ->
if(t1.first==t2.first) t1.second-t2.second else t1.first-t2.first}).map{it.second}.toList()
}
return res.toList()
}
// fun verticalTraversal(root: TreeNode?): List<List<Int>> {
// if (root == null) return emptyList()
// val m : SortedMap<Int, Array<Int>> = TreeMap<Int, Array<Int>>()
// val curr: Queue<Pair<TreeNode, Int>> = LinkedList<Pair<TreeNode, Int>>()
// curr.offer(Pair(root, 0))
// while (curr.isNotEmpty()){
// val tmpMap: MutableMap<Int, MutableList<Int>> = mutableMapOf()
// repeat(curr.size){
// val ele = curr.poll()!!
// val rank = ele.second
// val node = ele.first
// if(!tmpMap.containsKey(rank)) tmpMap[rank] = emptyArray()
// tmpMap[rank]?.plus(node.`val`)
// node.left?.let {
// curr.offer(Pair(it, rank-1))
// }
// node.right?.let {
// curr.offer(Pair(it, rank+1))
// }
// }
// tmpMap.forEach { (t, u) ->
// val v: Array<Int> = m.getOrDefault(t, emptyArray())
//// println(v.size)
//// println(u.size)
// for (el in u) v.plus(el)
// print(v.size)
// m[t] = v
// }
// }
// return m.map { it.value.toList() }.toList()
// }
}
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
| 0 | C++ | 1 | 1 | 54b7f625f6c4828a72629068d78204514937b2a9 | 2,589 | awesome-leetcode | Apache License 2.0 |
src/test/kotlin/be/brammeerten/y2023/Day8OtherTest.kt | BramMeerten | 572,879,653 | false | {"Kotlin": 170522} | package be.brammeerten.y2023
import be.brammeerten.extractRegexGroups
import be.brammeerten.readFile
import be.brammeerten.toCharList
import org.junit.jupiter.api.Test
class Day8OtherTest {
@Test
fun `part 2`() {
val lines = readFile("2023/day8/input.txt")
val instructions = lines[0].toCharList()
val startPositions = mutableListOf<String>()
val paths = lines.drop(2).associate {
val values = extractRegexGroups("^(...) = \\((...), (...)\\)$", it)
if (values[0][2] == 'A') startPositions.add(values[0])
values[0] to Path(values[1], values[2])
}
println("Start: " + startPositions.size)
val history = mutableListOf<Pair<Int, List<Int>>>()
for (posI in 0 until startPositions.size) {
val temp = findForStartPos(startPositions[posI], instructions, paths)
history.add(temp.size to temp.mapIndexed { i, value ->
if (value[2] == 'Z') i+1 else -1
}.filter { it != -1 })
// println(temp)
println(history[posI])
println("----")
}
var count = 0
var indexOfFewest = 0
val posFewestZs = 4
while (true) {
count += history[posFewestZs].second[indexOfFewest]
val found = !history.asSequence()
.filter {
!it.second.contains(((count-1) % it.first)+1)
}
.any()
if (found) break;
indexOfFewest = (indexOfFewest+1) % history[posFewestZs].second.size
}
println("Done calculating history: " + count)
/*var instructionI = 0
var count: Long = 0
while (!allZ(positions)) {
val isLeft = instructions[instructionI] == 'L'
val pos = positions[POS_I]
positions[i] = if (isLeft) paths[pos]!!.toLeft else paths[pos]!!.toRight
count++
instructionI = (instructionI + 1) % instructions.size
}
assertThat(count).isEqualTo(6);*/
// assertThat(i).isEqualTo(14257);
}
private fun findForStartPos(startPos: String, instructions: List<Char>, paths: Map<String, Path>): List<String> {
val output = mutableListOf<String>()
var instructionI = 0
var pos = startPos
while(true) {
val isLeft = instructions[instructionI] == 'L'
pos = if (isLeft) paths[pos]!!.toLeft else paths[pos]!!.toRight
var searchI = instructionI
while(output.size > searchI) {
if (output[searchI] == pos) break;
searchI += instructions.size
}
// TODO gevonden
if (output.size > searchI) {
break;
}
output.add(pos)
instructionI = (instructionI + 1) % instructions.size
}
return output
}
private fun allZ(positions: List<String>): Boolean {
return !positions
.asSequence()
.filter { it[2] != 'Z' }
.any()
}
}
| 0 | Kotlin | 0 | 0 | 1defe58b8cbaaca17e41b87979c3107c3cb76de0 | 3,107 | Advent-of-Code | MIT License |
src/day03/Day03.kt | skokovic | 573,361,100 | false | {"Kotlin": 12166} | package day03
import readInput
fun calculateScore(char: Char): Int {
if(char.isUpperCase()) {
return char.code - 38
}
return char.code - 96
}
fun main() {
fun part1(input: List<String>): Int {
var sum = 0
input.forEach { sack ->
val size = sack.length
val first = sack.substring(0, size/2)
val second = sack.substring(size/2, size)
for (c in first) {
if (second.contains(c)) {
sum += calculateScore(c)
break
}
}
}
return sum
}
fun part2(input: List<String>): Int {
var sum = 0
var i = 0
while(i <= input.size - 2) {
val first = input[i]
val second = input[i+1]
val third = input[i+2]
for (c in first) {
if (second.contains(c) && third.contains(c)) {
sum += calculateScore(c)
break
}
}
i+=3
}
return sum
}
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | fa9aee3b5dd09b06bfd5c232272682ede9263970 | 1,186 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/SubstringFinder.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.max
/**
* 1624. Largest Substring Between Two Equal Characters
* @see <a href="https://leetcode.com/problems/largest-substring-between-two-equal-characters">Source</a>
*/
fun interface SubstringFinder {
operator fun invoke(s: String): Int
}
class SubstringFinderBF : SubstringFinder {
override fun invoke(s: String): Int {
var ans = -1
for (left in s.indices) {
for (right in left + 1 until s.length) {
if (s[left] == s[right]) {
ans = max(ans.toDouble(), (right - left - 1).toDouble()).toInt()
}
}
}
return ans
}
}
class SubstringFinderHashMap : SubstringFinder {
override fun invoke(s: String): Int {
val firstIndex: MutableMap<Char, Int> = HashMap()
var ans = -1
for (i in s.indices) {
if (firstIndex.containsKey(s[i])) {
ans = max(ans.toDouble(), (i - firstIndex.getOrDefault(s[i], 0) - 1).toDouble())
.toInt()
} else {
firstIndex[s[i]] = i
}
}
return ans
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,790 | kotlab | Apache License 2.0 |
src/Day06.kt | ked4ma | 573,017,240 | false | {"Kotlin": 51348} | /**
* [Day06](https://adventofcode.com/2022/day/6)
*/
fun main() {
fun findMarker(input: String, len: Int) : Int{
val map = mutableMapOf<Char, Int>()
(0 until len - 1).forEach {
map[input[it]] = map.getOrDefault(input[it], 0) + 1
}
for (i in len - 1 until input.length) {
map[input[i]] = map.getOrDefault(input[i], 0) + 1
if (map.keys.size == len) {
return i + 1
}
map.getValue(input[i - (len - 1)]).let {
if (it == 1) {
map.remove(input[i - (len - 1)])
} else {
map[input[i - (len - 1)]] = it - 1
}
}
}
return -1
}
fun part1(input: String): Int {
return findMarker(input, 4)
}
fun part2(input: String): Int {
return findMarker(input, 14)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")[0]
check(part1(testInput) == 7)
check(part2(testInput) == 19)
val input = readInput("Day06")[0]
println(part1(input))
println(part2(input))
} | 1 | Kotlin | 0 | 0 | 6d4794d75b33c4ca7e83e45a85823e828c833c62 | 1,189 | aoc-in-kotlin-2022 | Apache License 2.0 |
src/day18/solution.kt | bohdandan | 729,357,703 | false | {"Kotlin": 80367} | package day18
import Direction
import Position
import assert
import plus
import println
import readInput
import times
import kotlin.math.absoluteValue
fun main() {
class Command(val direction: Direction, val steps: Int, val hexColor: Int)
fun parse(input: List<String>): List<Command> {
return input.map { row ->
val parts = row.split(" ")
val direction = Direction.entries.first { it.name.startsWith(parts[0]) }
val steps = parts[1].toInt()
val color = parts[2].substring(2, 8).toInt(16)
Command(direction, steps, color)
}
}
fun List<Pair<Direction, Int>>.volume() = (
runningFold(Position(0, 0)) { position, (direction, steps) -> position + direction.position * steps}
.zipWithNext { (y1, x1), (_, x2) ->
(x2 - x1) * y1.toLong()
}.sum().absoluteValue + sumOf { it.second } / 2 + 1)
parse(readInput("day18/test1"))
.map { it.direction to it.steps }
.volume()
.assert(62L)
"Part 1:".println()
parse(readInput("day18/input"))
.map { it.direction to it.steps }
.volume()
.assert(46334L)
val codedDirections = mapOf(0 to Direction.RIGHT, 1 to Direction.DOWN, 2 to Direction.LEFT, 3 to Direction.UP)
parse(readInput("day18/test1"))
.map {command ->
val direction = codedDirections[command.hexColor % 16]!!
val steps = command.hexColor / 16
direction to steps
}
.volume()
.assert(952408144115L)
.println()
"Part 2:".println()
parse(readInput("day18/input"))
.map {command ->
val direction = codedDirections[command.hexColor % 16]!!
val steps = command.hexColor / 16
direction to steps
}
.volume()
.assert(102000662718092L)
.println()
} | 0 | Kotlin | 0 | 0 | 92735c19035b87af79aba57ce5fae5d96dde3788 | 1,907 | advent-of-code-2023 | Apache License 2.0 |
src/main/kotlin/com/gitTraining/Fibbonaci.kt | woody-lam | 383,797,784 | true | {"Kotlin": 6393} | package com.gitTraining
fun computeFibbonaciNumber(position: Int?, recursion: Boolean = false): Int {
if (recursion) return recursiveFibbonachi(position!!)
var notNullPosition = position
if (notNullPosition == null) {
notNullPosition = 1
}
if (position == 0) return 0
if (position != null) {
if (position < 0) {
return computeNegativeFibbonachi(position)
}
}
if (notNullPosition <= 2) return 1
if (position == 1 || position == 2) return 1
var smallFibbonachiNumber = 1
var largeFibbonachiNumber = 1
var currentPosition = 2
while (currentPosition < position!!) {
val nextFibbonachiNumber = smallFibbonachiNumber + largeFibbonachiNumber
smallFibbonachiNumber = largeFibbonachiNumber
largeFibbonachiNumber = nextFibbonachiNumber
currentPosition ++
}
return largeFibbonachiNumber
}
fun computeFibbonachiArray(start: Int, end: Int, efficient: Boolean = false): List<Int> {
if (!efficient) return (start..end).map { computeFibbonaciNumber(it) }
if (start > end) return listOf()
if (start == end) return listOf(computeFibbonaciNumber(start))
val output = mutableListOf(computeFibbonaciNumber(start), computeFibbonaciNumber(start + 1))
(2..(end - start)).forEach { output.add(output[it - 2] + output[it - 1]) }
return output
}
fun recursiveFibbonachi(previous: Int, current: Int, stepsLeft: Int): Int {
if (stepsLeft < 0) return 1
return when (stepsLeft) {
0 -> current
else -> recursiveFibbonachi(current, previous + current, stepsLeft - 1)
}
}
fun computeNegativeFibbonachi(position:Int): Int {
if (position >= 0) throw Exception("potition must be smaller than zero!")
val resultIsNegative = position % 2 == 0
val absoluteResult = computeFibbonaciNumber(-position)
return if (resultIsNegative) (absoluteResult * -1) else absoluteResult
}
fun recursiveFibbonachi(initialPosition: Int, left: Int = 0, right: Int = 1, position: Int = initialPosition): Int {
if (initialPosition == 0) return 0
if (position == 0) return left
if (initialPosition > 0) {
return recursiveFibbonachi(initialPosition, right, left + right, position - 1)
} else {
return recursiveFibbonachi(initialPosition, right - left, left, position + 1)
}
}
| 0 | Kotlin | 0 | 0 | c9c8885afd59dd3f4700ad632759d5e01cf16806 | 2,353 | git-training-rebasing | MIT License |
foundry-math/src/main/kotlin/com/valaphee/foundry/math/Partition.kt | valaphee | 372,059,969 | false | {"Kotlin": 267615} | /*
* Copyright (c) 2021-2022, Valaphee.
*
* 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.valaphee.foundry.math
import kotlin.math.exp
import kotlin.math.ln
import kotlin.math.max
import kotlin.math.min
import kotlin.math.sign
import kotlin.math.sqrt
fun <T> MutableList<T>.partition(k: Int, compare: (T, T) -> Int) = partition(indices, k, compare)
fun <T> MutableList<T>.partition(range: IntRange, k: Int, comparator: (T, T) -> Int) {
partition(this, range.first, range.last, k, { get(it) }, comparator, { a, b -> this[a] = this[b].also { this[b] = this[a] } })
}
fun <T> Array<T>.partition(k: Int, compare: (T, T) -> Int) = partition(indices, k, compare)
fun <T> Array<T>.partition(range: IntRange, k: Int, compare: (T, T) -> Int) {
partition(this, range.first, range.last, k, { get(it) }, compare, { a, b -> this[a] = this[b].also { this[b] = this[a] } })
}
fun <L, T> partition(elements: L, left: Int, right: Int, k: Int, get: L.(Int) -> T, compare: (T, T) -> Int, swap: L.(Int, Int) -> Unit) {
var leftVar = left
var rightVar = right
while (rightVar > leftVar) {
if (rightVar - leftVar > 600) {
val n = rightVar - leftVar + 1
val i = k - leftVar + 1
val z = ln(n.toDouble())
val s = 0.5 * exp(2.0 * z / 3.0)
val sd = 0.5 * sqrt(z * s * (n - s) / n) * sign(i - n / 2.0)
partition(elements, max(leftVar, (k - i * s / n + sd).toInt()), min(rightVar, (k + (n - i) * s / n + sd).toInt()), k, get, compare, swap)
}
val t = elements.get(k)
var i = leftVar
var j = rightVar
elements.swap(leftVar, k)
if (compare(elements.get(rightVar), t) > 0) elements.swap(rightVar, leftVar)
while (i < j) {
elements.swap(i, j)
i++
j--
while (compare(elements.get(i), t) < 0) i++
while (j >= 0 && compare(elements.get(j), t) > 0) j--
}
if (compare(elements.get(leftVar), t) == 0) elements.swap(leftVar, j) else {
j++
elements.swap(j, rightVar)
}
if (j <= k) leftVar = j + 1
if (k <= j) rightVar = j - 1
}
}
| 0 | Kotlin | 0 | 3 | 7e49a4507aa59cebefe928c4aa42f02182f95904 | 2,705 | foundry | Apache License 2.0 |
year2021/day23/amphipod/src/main/kotlin/com/curtislb/adventofcode/year2021/day23/amphipod/BurrowGraph.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | package com.curtislb.adventofcode.year2021.day23.amphipod
import com.curtislb.adventofcode.common.collection.replaceAt
import com.curtislb.adventofcode.common.graph.WeightedGraph
import com.curtislb.adventofcode.common.range.size
/**
* A graph with edges from each possible [Burrow] state to new [Burrow] states that result from
* moving a single amphipod to a valid space, weighted by the energy required to move it.
*/
internal object BurrowGraph : WeightedGraph<Burrow>() {
override fun getEdges(node: Burrow): List<Edge<Burrow>> {
val edges = mutableListOf<Edge<Burrow>>()
// Try moving each amphipod in the hallway to its destination room
node.hallway.forEachIndexed { hallwayIndex, amphipod ->
if (amphipod != null) {
val distance = node.distanceToRoom(hallwayIndex)
if (distance != null) {
val newHallway = node.hallway.replaceAt(hallwayIndex) { null }
val newRooms = node.rooms.replaceAt(amphipod.roomIndex) { it + amphipod }
val newState = node.copy(hallway = newHallway, rooms = newRooms)
val energy = distance * amphipod.energyPerStep
edges.add(Edge(node = newState, weight = energy))
}
}
}
// Try moving the outermost amphipod in each room to each hallway space
node.rooms.forEachIndexed { roomIndex, amphipods ->
val amphipod = amphipods.lastOrNull()
if (amphipod != null) {
for (hallwayIndex in node.hallway.indices) {
val distance = node.distanceToHallway(roomIndex, hallwayIndex)
if (distance != null) {
val newHallway = node.hallway.replaceAt(hallwayIndex) { amphipod }
val newRooms = node.rooms.replaceAt(roomIndex) { room ->
room.subList(0, room.lastIndex)
}
val newState = node.copy(hallway = newHallway, rooms = newRooms)
val energy = distance * amphipod.energyPerStep
edges.add(Edge(node = newState, weight = energy))
}
}
}
}
return edges
}
/**
* Returns the number of spaces the outermost [Amphipod] in the given [roomIndex] must move to
* reach the given [hallwayIndex], while obeying all rules in [Burrow.energyRequiredToOrganize].
*
* If the given [roomIndex] is empty or the amphipod can't move to the given [hallwayIndex],
* this function instead returns `null`.
*/
private fun Burrow.distanceToHallway(roomIndex: Int, hallwayIndex: Int): Int? {
val room = rooms[roomIndex]
if (room.isEmpty() || isOutsideRoom(hallwayIndex)) {
return null
}
val startIndex = Burrow.roomToHallwayIndex(roomIndex)
val moveRange = getHallwayMoveRange(startIndex, hallwayIndex)
if (isObstructed(moveRange)) {
return null
}
val distanceOutOfRoom = roomCapacity - room.lastIndex
return distanceOutOfRoom + moveRange.size()
}
/**
* Returns the number of spaces the [Amphipod] at the given [hallwayIndex] must move to reach
* the outermost unoccupied space of its destination room, while obeying all rules in
* [Burrow.energyRequiredToOrganize].
*
* If there is no amphipod at the given [hallwayIndex] or it can't move to its destination room,
* this function instead returns `null`.
*/
private fun Burrow.distanceToRoom(hallwayIndex: Int): Int? {
val amphipod = hallway[hallwayIndex] ?: return null
val targetRoom = rooms[amphipod.roomIndex]
if (targetRoom.size == roomCapacity || targetRoom.any { it != amphipod }) {
return null
}
val targetIndex = Burrow.roomToHallwayIndex(amphipod.roomIndex)
val moveRange = getHallwayMoveRange(hallwayIndex, targetIndex)
if (isObstructed(moveRange)) {
return null
}
val distanceIntoRoom = roomCapacity - targetRoom.size
return moveRange.size() + distanceIntoRoom
}
/**
* Returns if any space in the given [hallwayIndexRange] is currently occupied.
*/
private fun Burrow.isObstructed(hallwayIndexRange: IntRange): Boolean =
hallwayIndexRange.any { hallway[it] != null }
/**
* Returns if the given [hallwayIndex] represents a space that is immediately outside a room.
*/
private fun Burrow.isOutsideRoom(hallwayIndex: Int): Boolean =
hallwayIndex != 0 && hallwayIndex != hallway.lastIndex && hallwayIndex % 2 == 0
/**
* Returns an index range representing all hallway spaces from [startIndex] to [targetIndex].
*/
private fun getHallwayMoveRange(startIndex: Int, targetIndex: Int): IntRange = when {
startIndex < targetIndex -> (startIndex + 1)..targetIndex
startIndex > targetIndex -> targetIndex until startIndex
else -> IntRange.EMPTY
}
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 5,130 | AdventOfCode | MIT License |
src/test/kotlin/io/github/aarjavp/aoc/day10/Day10Test.kt | AarjavP | 433,672,017 | false | {"Kotlin": 73104} | package io.github.aarjavp.aoc.day10
import io.kotest.matchers.ints.shouldBeExactly
import io.kotest.matchers.longs.shouldBeExactly
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.DynamicTest
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestFactory
class Day10Test {
val solution = Day10()
@Test
fun part1() {
val testInput = """
[({(<(())[]>[[{[]{<()<>>
[(()[<>])]({[<{<<[]>>(
{([(<{}[<>[]}>{[]{[(<()>
(((({<>}<{<{<>}{[]{[]{}
[[<[([]))<([[{}[[()]]]
[{[{({}]{}}([{[{{{}}([]
{<[[]]>}<{[{[{[]{()[[[]
[<(<(<(<{}))><([]([]()
<{([([[(<>()){}]>(<<{{
<{([{{}}[<[[[<>{}]]]>[]]
""".trimIndent()
val actual = solution.part1(testInput.lineSequence())
actual shouldBeExactly 26397
}
@TestFactory
fun complete(): List<DynamicTest> {
data class TestCase(val input: String, val expectedClosing: String) {
fun toTest(): DynamicTest = DynamicTest.dynamicTest(input) {
val actual = solution.complete(input).joinToString("") { it.closingChar.toString() }
actual shouldBe expectedClosing
}
}
val testCases = listOf(
TestCase("[({(<(())[]>[[{[]{<()<>>", "}}]])})]"),
TestCase("[(()[<>])]({[<{<<[]>>(", ")}>]})"),
TestCase("(((({<>}<{<{<>}{[]{[]{}", "}}>}>))))"),
TestCase("{<[[]]>}<{[{[{[]{()[[[]", "]]}}]}]}>"),
TestCase("<{([{{}}[<[[[<>{}]]]>[]]", "])}>"),
TestCase("<{([{{}}[<[[[<>{}]]]>[]]])}>", ""),
)
return testCases.map { it.toTest() }
}
@Test
fun part2() {
val testInput = """
[({(<(())[]>[[{[]{<()<>>
[(()[<>])]({[<{<<[]>>(
{([(<{}[<>[]}>{[]{[(<()>
(((({<>}<{<{<>}{[]{[]{}
[[<[([]))<([[{}[[()]]]
[{[{({}]{}}([{[{{{}}([]
{<[[]]>}<{[{[{[]{()[[[]
[<(<(<(<{}))><([]([]()
<{([([[(<>()){}]>(<<{{
<{([{{}}[<[[[<>{}]]]>[]]
""".trimIndent()
val actual = solution.part2(testInput.lineSequence())
actual shouldBeExactly 288957
}
}
| 0 | Kotlin | 0 | 0 | 3f5908fa4991f9b21bb7e3428a359b218fad2a35 | 2,269 | advent-of-code-2021 | MIT License |
day09/src/Day09.kt | simonrules | 491,302,880 | false | {"Kotlin": 68645} | import java.io.File
class Day09(private val path: String) {
private val map = mutableListOf<Int>()
private var height = 0
private var width = 0
init {
var i = 0
var j = 0
File(path).forEachLine { line ->
j = line.length
line.forEach {
map.add(Character.getNumericValue(it))
}
i++
}
height = i
width = j
}
private fun getMapAt(x: Int, y: Int): Int {
return map[y * width + x]
}
private fun isLowPoint(x: Int, y: Int): Boolean {
val myDepth = getMapAt(x, y)
if (x > 0) {
if (myDepth >= getMapAt(x - 1, y)) {
return false
}
}
if (x < width - 1) {
if (myDepth >= getMapAt(x + 1, y)) {
return false
}
}
if (y > 0) {
if (myDepth >= getMapAt(x, y - 1)) {
return false
}
}
if (y < height - 1) {
if (myDepth >= getMapAt(x, y + 1)) {
return false
}
}
return true
}
private fun findBasinSizeRecurse(x: Int, y: Int, visited: Array<Boolean>): Int {
val myDepth = getMapAt(x, y)
if (myDepth == 9 || visited[y * width + x]) {
return 0
}
visited[y * width + x] = true
var total = 1
if (x > 0) {
val theirDepth = getMapAt(x - 1, y)
if (myDepth < theirDepth) {
total += findBasinSizeRecurse(x - 1, y, visited)
}
}
if (x < width - 1) {
val theirDepth = getMapAt(x + 1, y)
if (myDepth < theirDepth) {
total += findBasinSizeRecurse(x + 1, y, visited)
}
}
if (y > 0) {
val theirDepth = getMapAt(x, y - 1)
if (myDepth < theirDepth) {
total += findBasinSizeRecurse(x, y - 1, visited)
}
}
if (y < height - 1) {
val theirDepth = getMapAt(x, y + 1)
if (myDepth < theirDepth) {
total += findBasinSizeRecurse(x, y + 1, visited)
}
}
return total
}
fun part1(): Int {
var risk = 0
for (i in 0 until height) {
for (j in 0 until width) {
if (isLowPoint(j, i)) {
risk += getMapAt(j, i) + 1
}
}
}
return risk
}
fun part2(): Int {
val size = mutableListOf<Int>()
for (i in 0 until height) {
for (j in 0 until width) {
if (isLowPoint(j, i)) {
val visited = Array(map.size) { false }
size.add(findBasinSizeRecurse(j, i, visited))
}
}
}
size.sortDescending()
return size[0] * size[1] * size[2]
}
}
fun main(args: Array<String>) {
val aoc = Day09("day09/input.txt")
//println(aoc.part1())
println(aoc.part2())
}
| 0 | Kotlin | 0 | 0 | d9e4ae66e546f174bcf66b8bf3e7145bfab2f498 | 3,093 | aoc2021 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/NumOfWays.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import dev.shtanko.algorithms.MOD
/**
* 1569. Number of Ways to Reorder Array to Get Same BST
* @see <a href="https://leetcode.com/problems/number-of-ways-to-reorder-array-to-get-same-bst/">Source</a>
*/
fun interface NumOfWays {
operator fun invoke(nums: IntArray): Int
}
class NumOfWaysTriangle : NumOfWays {
override operator fun invoke(nums: IntArray): Int {
val len: Int = nums.size
val arr: MutableList<Int> = ArrayList()
for (n in nums) {
arr.add(n)
}
return getCombs(arr, getTriangle(len + 1)).toInt() - 1
}
private fun getCombs(nums: List<Int>, combs: Array<LongArray>): Long {
if (nums.size <= 2) {
return 1
}
val root = nums[0]
val left: MutableList<Int> = ArrayList()
val right: MutableList<Int> = ArrayList()
for (n in nums) {
if (n < root) {
left.add(n)
} else if (n > root) {
right.add(n)
}
}
// mod every number to avoid overflow
return combs[left.size + right.size][left.size] * (getCombs(left, combs) % MOD) % MOD * getCombs(
right,
combs,
) % MOD
}
private fun getTriangle(n: Int): Array<LongArray> {
// Yang Hui (Pascle) triangle
// 4C2 = triangle[4][2] = 6
val triangle = Array(n) { LongArray(n) }
for (i in 0 until n) {
triangle[i][i] = 1
triangle[i][0] = triangle[i][i]
}
for (i in 2 until n) {
for (j in 1 until i) {
triangle[i][j] = (triangle[i - 1][j] + triangle[i - 1][j - 1]) % MOD
}
}
return triangle
}
}
class NumOfWaysImpl : NumOfWays {
private lateinit var arr: Array<LongArray>
override operator fun invoke(nums: IntArray): Int {
val n: Int = nums.size
arr = Array(n + 1) { longArrayOf() }
for (i in 0..n) {
arr[i] = LongArray(i + 1) { 1 }
for (j in 1 until i) {
arr[i][j] = (arr[i - 1][j - 1] + arr[i - 1][j]) % MOD
}
}
var root: Node? = null
for (x in nums) {
root = insert(root, x)
}
cnt(root)
return dfs(root).toInt() - 1
}
private fun dfs(root: Node?): Long {
if (root == null) {
return 1
}
val leftLen = if (root.left == null) 0 else root.left!!.cnt
val rightLen = if (root.right == null) 0 else root.right!!.cnt
if (leftLen + rightLen <= 1) {
return 1
}
var res = dfs(root.left) * dfs(root.right) % MOD
res = res * arr[leftLen + rightLen][leftLen] % MOD
return res
}
private fun insert(root: Node?, value: Int): Node {
if (root == null) {
return Node(value)
}
if (root.value < value) {
root.left = insert(root.left, value)
} else {
root.right = insert(root.right, value)
}
return root
}
private fun cnt(root: Node?): Int {
if (root == null) {
return 0
}
root.cnt += cnt(root.left) + cnt(root.right)
return root.cnt
}
data class Node(
var value: Int,
var left: Node? = null,
var right: Node? = null,
var cnt: Int = 1,
)
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 4,045 | kotlab | Apache License 2.0 |
src/main/kotlin/days/Day18.kt | hughjdavey | 317,575,435 | false | null | package days
class Day18 : Day(18) {
// 21993583522852
override fun partOne(): Any {
return inputList.map { doCalculation(it) }.sum()
}
// 122438593522757
override fun partTwo(): Any {
return inputList.map { doCalculation(it, true) }.sum()
}
fun doCalculation(expression: String, prioritizeAddition: Boolean = false): Long {
val maybeParens = parensNoNesting.find(expression)
return if (maybeParens == null) doSingleCalculation(expression, prioritizeAddition) else {
val withoutSurroundingParens = maybeParens.value.drop(1).dropLast(1)
val replacedWithResult = expression.replaceRange(maybeParens.range, doCalculation(withoutSurroundingParens, prioritizeAddition).toString())
doCalculation(replacedWithResult, prioritizeAddition)
}
}
private fun doSingleCalculation(expression: String, prioritizeAddition: Boolean = false): Long {
val nextExpr = if (prioritizeAddition) singleExprAdd.find(expression) ?: singleExpr.find(expression)!!
else singleExpr.find(expression)!!
val result = doSingleSum(nextExpr.groupValues.drop(1))
return if (expression == nextExpr.value) result else {
val newExpr = expression.replaceRange(nextExpr.range, result.toString())
return doSingleCalculation(newExpr, prioritizeAddition)
}
}
private fun doSingleSum(parts: List<String>): Long {
val (x, y) = parts[0].replace("(", "").toLong() to parts[2].replace(")", "").toLong()
return when (parts[1]) {
"*" -> x * y
"+" -> x + y
else -> throw IllegalArgumentException()
}
}
companion object {
private val singleExpr = Regex("(\\d+) ([+\\-/*]) (\\d+)")
private val singleExprAdd = Regex("(\\d+) (\\+) (\\d+)")
private val parensNoNesting = Regex("(\\([\\d*+ ]+\\))")
}
}
| 0 | Kotlin | 0 | 1 | 63c677854083fcce2d7cb30ed012d6acf38f3169 | 1,947 | aoc-2020 | Creative Commons Zero v1.0 Universal |
solutions/src/MatrixBlockSum.kt | JustAnotherSoftwareDeveloper | 139,743,481 | false | {"Kotlin": 305071, "Java": 14982} | import kotlin.math.max
import kotlin.math.min
/**
* https://leetcode.com/problems/matrix-block-sum/
*/
class MatrixBlockSum {
fun matrixBlockSum(mat: Array<IntArray>, K: Int) : Array<IntArray> {
val sumMatrix = Array(mat.size+1){IntArray(mat[0].size+1){0} };
val m = mat.size;
val n = mat[0].size
for (i in 1..mat.size) {
for (j in 1..mat[0].size) {
val prevMat = mat[i-1][j-1];
val prevSum = sumMatrix[i-1][j-1];
val prevI = sumMatrix[i-1][j]
val prevJ = sumMatrix[i][j-1]
sumMatrix[i][j] = prevMat+prevI+prevJ-prevSum;
}
}
val ans = Array(m) { IntArray(n) }
for (r in 0 until m) {
for (c in 0 until n) {
var r1 = max(0, r - K)
var c1 = max(0, c - K)
var r2 = min(mat.size- 1, r + K)
var c2 = min(mat[0].size - 1, c + K)
r1++
c1++
r2++
c2++ // Since `sum` start with 1 so we need to increase r1, c1, r2, c2 by 1
ans[r][c] = sumMatrix[r2][c2] - sumMatrix[r2][c1 - 1] - sumMatrix[r1 - 1][c2] + sumMatrix[r1 - 1][c1 - 1]
}
}
return ans
}
} | 0 | Kotlin | 0 | 0 | fa4a9089be4af420a4ad51938a276657b2e4301f | 1,293 | leetcode-solutions | MIT License |
src/main/kotlin/days/Day22.kt | julia-kim | 569,976,303 | false | null | package days
import readInput
fun main() {
fun parseInput(input: List<String>): Pair<Array<CharArray>, List<String>> {
val blankLineIndex = input.indexOfFirst { it.isBlank() }
val board = input.subList(0, blankLineIndex).map {
it.map { char -> char }.toCharArray()
}.toTypedArray()
val paths = input.last().split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)".toRegex())
return board to paths
}
fun part1(input: List<String>): Int {
val (board, paths) = parseInput(input)
var direction = 90
var position = board[0].indexOfFirst { !it.isWhitespace() } to 0 //col to row
paths.forEach { instruction ->
when (instruction) {
"R" -> {
direction = if (direction == 360) 90 else direction + 90
}
"L" -> {
direction = if (direction == 0) 270 else direction - 90
}
else -> {
var number = instruction.toInt()
while (number > 0) {
val (nextMove, newPosition) = try {
when (direction) {
90 -> board[position.second][position.first + 1] to (position.first + 1 to position.second)
180 -> board[position.second + 1][position.first] to (position.first to position.second + 1)
270 -> board[position.second][position.first - 1] to (position.first - 1 to position.second)
0, 360 -> board[position.second - 1][position.first] to (position.first to position.second - 1)
else -> {
println(direction)
TODO()
}
}
} catch (e: ArrayIndexOutOfBoundsException) {
' ' to position
}
when (nextMove) {
'.' -> position = newPosition
'#' -> return@forEach
' ' -> {
position =
when (direction) {
90 -> {
if (board[position.second].first { !it.isWhitespace() } != '#')
board[position.second].indexOfFirst { !it.isWhitespace() } to position.second
else return@forEach
}
180 -> {
if (board.first { !it[position.first].isWhitespace() }[position.first] != '#')
position.first to board.indexOfFirst { !it[position.first].isWhitespace() }
else return@forEach
}
270 -> {
if (board[position.second].last { !it.isWhitespace() } != '#')
board[position.second].indexOfLast { !it.isWhitespace() } to position.second
else return@forEach
}
0, 360 -> {
if (board.last { it.size > position.first && !it[position.first].isWhitespace() }[position.first] != '#')
position.first to board.indexOfLast { it.size > position.first && !it[position.first].isWhitespace() }
else return@forEach
}
else -> {
TODO()
}
}
}
}
number--
}
}
}
}
val facing = when (direction) {
90 -> 0
180 -> 1
270 -> 2
0, 360 -> 3
else -> 0
}
val finalRow = position.second + 1
val finalCol = position.first + 1
val finalPassword = finalRow * 1000 + finalCol * 4 + facing
return finalPassword
}
fun part2(input: List<String>): Int {
return 0
}
val testInput = readInput("Day22_test")
check(part1(testInput) == 6032)
check(part2(testInput) == 0)
val input = readInput("Day22")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 65188040b3b37c7cb73ef5f2c7422587528d61a4 | 4,907 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/_2022/Day08.kt | novikmisha | 572,840,526 | false | {"Kotlin": 145780} | package _2022
import readInput
fun main() {
fun part1(input: List<String>): Int {
val intInput = input.map { it.map { char -> char.digitToInt() } }
val max_i = intInput.size
val max_j = intInput[0].size
var visibleInside = 0
for (i in 1 until max_i - 1) {
for (j in 1 until max_j - 1) {
val tree = intInput[i][j]
var bottomFlag = true
var rightFlag = true
var topFlag = true
var leftFlag = true
for (k in i + 1 until max_i) {
if (intInput[k][j] >= tree) {
bottomFlag = false
}
}
for (k in j + 1 until max_j) {
if (intInput[i][k] >= tree) {
rightFlag = false
}
}
for (k in i - 1 downTo 0) {
if (intInput[k][j] >= tree) {
topFlag = false
}
}
for (k in j - 1 downTo 0) {
if (intInput[i][k] >= tree) {
leftFlag = false
}
}
if (listOf(bottomFlag, rightFlag, topFlag, leftFlag).any { it }) {
visibleInside++
}
}
}
return (max_i + max_j) * 2 - 4 + visibleInside
}
fun part2(input: List<String>): Int {
val intInput = input.map { it.map { char -> char.digitToInt() } }
val max_i = intInput.size
val max_j = intInput[0].size
var scenics = mutableListOf<Int>()
for (i in 1 until max_i - 1) {
for (j in 1 until max_j - 1) {
val tree = intInput[i][j]
var bottom = 0
var right = 0
var top = 0
var left = 0
for (k in i + 1 until max_i) {
bottom++
if (intInput[k][j] >= tree) {
break
}
}
for (k in j + 1 until max_j) {
right++
if (intInput[i][k] >= tree) {
break
}
}
for (k in i - 1 downTo 0) {
top++
if (intInput[k][j] >= tree) {
break
}
}
for (k in j - 1 downTo 0) {
left++
if (intInput[i][k] >= tree) {
break
}
}
scenics.add(bottom * right * top * left)
}
}
return scenics.max()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
println(part1(testInput))
println(part2(testInput))
val input = readInput("Day08")
println(part1(input))
println(part2(input))
} | 0 | Kotlin | 0 | 0 | 0c78596d46f3a8bf977bf356019ea9940ee04c88 | 3,098 | advent-of-code | Apache License 2.0 |
src/day09/Day09.kt | molundb | 573,623,136 | false | {"Kotlin": 26868} | package day09
import readInput
import kotlin.math.abs
fun main() {
val input = readInput(parent = "src/day09", name = "Day09_input")
println(solvePartOne(input))
println(solvePartTwo(input))
}
private fun solvePartTwo(input: List<String>): Int {
val startPoint = Point(0, 0)
val tailVisitedPoints = mutableSetOf(startPoint)
val points = MutableList(10) { startPoint.copy() }
for (l in input) {
val (direction, distance) = l.split(' ')
for (i in 0 until distance.toInt()) {
when (direction) {
"R" -> points[0].x++
"D" -> points[0].y++
"L" -> points[0].x--
"U" -> points[0].y--
}
updateTailPoints(points, tailVisitedPoints)
}
}
return tailVisitedPoints.size
}
private fun updateTailPoints(
points: MutableList<Point>,
tailVisitedPoints: MutableSet<Point>
) {
var prevPoint = points[0]
for (j in 1 until points.size) {
if (notAdjacent(prevPoint, points[j])) {
if (prevPoint.x > points[j].x) {
points[j].x++
} else if (prevPoint.x < points[j].x) {
points[j].x--
}
if (prevPoint.y > points[j].y) {
points[j].y++
} else if (prevPoint.y < points[j].y) {
points[j].y--
}
if (j == points.lastIndex) {
tailVisitedPoints.add(Point(points[j].x, points[j].y))
}
} else {
break
}
prevPoint = points[j]
}
}
private fun solvePartOne(input: List<String>): Int {
val startPoint = Point(0, 0)
val currHeadPoint = startPoint.copy()
val currTailPoint = startPoint.copy()
val tailVisitedPoints = mutableSetOf(startPoint)
for (l in input) {
val (direction, distance) = l.split(' ')
for (i in 0 until distance.toInt()) {
when (direction) {
"R" -> {
currHeadPoint.x++
if (notAdjacent(currHeadPoint, currTailPoint)) {
currTailPoint.x++
currTailPoint.y = currHeadPoint.y
tailVisitedPoints.add(Point(currTailPoint.x, currTailPoint.y))
}
}
"D" -> {
currHeadPoint.y++
if (notAdjacent(currHeadPoint, currTailPoint)) {
currTailPoint.y++
currTailPoint.x = currHeadPoint.x
tailVisitedPoints.add(Point(currTailPoint.x, currTailPoint.y))
}
}
"L" -> {
currHeadPoint.x--
if (notAdjacent(currHeadPoint, currTailPoint)) {
currTailPoint.x--
currTailPoint.y = currHeadPoint.y
tailVisitedPoints.add(Point(currTailPoint.x, currTailPoint.y))
}
}
"U" -> {
currHeadPoint.y--
if (notAdjacent(currHeadPoint, currTailPoint)) {
currTailPoint.y--
currTailPoint.x = currHeadPoint.x
tailVisitedPoints.add(Point(currTailPoint.x, currTailPoint.y))
}
}
}
}
}
return tailVisitedPoints.size
}
private fun notAdjacent(currHeadPoint: Point, currTailPoint: Point) =
abs(currHeadPoint.x - currTailPoint.x) > 1 || abs(currHeadPoint.y - currTailPoint.y) > 1
data class Point(
var x: Int,
var y: Int,
) | 0 | Kotlin | 0 | 0 | a4b279bf4190f028fe6bea395caadfbd571288d5 | 3,710 | advent-of-code-2022 | Apache License 2.0 |
算法/两数之和1.kt | Simplation | 506,160,986 | false | {"Kotlin": 10116} | package com.example.rain_demo.algorithm
/**
*@author: Rain
*@time: 2022/7/14 9:40
*@version: 1.0
*@description: 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
*/
/**
* 输入:nums = [2,7,11,15], target = 9
* 输出:[0,1]
* 解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
*
* 输入:nums = [3,2,4], target = 6
* 输出:[1,2]
*
* 输入:nums = [3,3], target = 6
* 输出:[0,1]
*
*/
fun main() {
// val time1 = System.currentTimeMillis()
val newInt = IntArray(2)
// sum(newInt, intArrayOf(3, 2, 3), 0, 6)
// println(System.currentTimeMillis() - time1)
// println(newInt.toString())
val nums = intArrayOf(3, 2, 3)
val target = 6
// val size = nums.size
// repeat(size) { index0 ->
// var index = index0 + 1
// while (index < size) {
// if (nums[index0] + nums[index] == target) {
// newInt[0] = index0
// newInt[1] = index
// return
// }
// index++
// }
// }
val map = mutableMapOf<Int, Int>()
var index = 0
while (index < nums.size) {
if (map.containsKey(target - nums[index])) {
val intArrayOf = intArrayOf(map[target - nums[index]]!!, index)
println(intArrayOf[0])
println(intArrayOf[1])
}
map[nums[index]] = index
index++
}
// nums.forEachIndexed { index, i ->
// if (map.containsKey(target - i)) {
// val intArrayOf = intArrayOf(map[target - i]!!, index)
// }
// map[i] = index
// }
}
fun sum(newInt: IntArray, nums: IntArray, index: Int, target: Int) {
val size = nums.size
if (index == size - 1) {
return
}
var newIndex = index + 1
// floor(newInt, nums, index, target, size, newIndex)
while (newIndex < size) {
val i = nums[index] + nums[newIndex]
if (i == target) {
newInt[0] = index
newInt[1] = newIndex
return
}
newIndex++
}
if (newInt[1] == 0) {
sum(newInt, nums, index + 1, target)
}
}
/**
* 二层递归
* @param newIndex 后一个index
*/
fun floor(newInt: IntArray, nums: IntArray, index: Int, target: Int, size: Int, newIndex: Int) {
if (newIndex == size) {
return
}
val i = nums[index] + nums[newIndex]
if (i == target) {
newInt[0] = index
newInt[1] = newIndex
return
} else {
floor(newInt, nums, index, target, size, newIndex + 1)
}
}
| 0 | Kotlin | 0 | 0 | d45feaa4c8ea2a08ce7357ee609a2df5b0639b68 | 2,790 | OpenSourceRepository | Apache License 2.0 |
src/main/kotlin/_2018/Day10.kt | thebrightspark | 227,161,060 | false | {"Kotlin": 548420} | package _2018
import aocRun
import parseInput
import java.util.*
import java.util.regex.Pattern
fun main() {
aocRun(puzzleInput) { input ->
val points = parsePoints(input)
val lastPoints = ArrayDeque<Pair<Int, Points>>()
val lastPointsMaxSize = 5
var lastArea = Long.MAX_VALUE
var breakAfter = -1
var iteration = 1
while (true) {
if (breakAfter == 0)
break
if (breakAfter > 0)
breakAfter--
points.move()
if (lastPoints.size >= lastPointsMaxSize)
lastPoints.remove()
lastPoints.add(iteration to points.copy())
val area = points.getArea().area
//println("Iteration: $iteration -> Area: $area (${if (area < lastArea) "down" else "up"})")
if (breakAfter < 0 && area > lastArea) {
//println("Minimum area!")
breakAfter = 1
}
lastArea = area
iteration++
}
lastPoints.forEach {
println("\n---------------------------------------------------------------\n${it.first}\n")
it.second.print()
}
}
}
private fun parsePoints(input: String): Points = Points(
parseInput(
Pattern.compile("position=<\\s*(?<posX>[\\-0-9]+),\\s*(?<posY>[\\-0-9]+)> velocity=<\\s*(?<velX>[\\-0-9]+),\\s*(?<velY>[\\-0-9]+)>"),
input
) {
Point(
it.group("posX").toLong(),
it.group("posY").toLong(),
it.group("velX").toLong(),
it.group("velY").toLong()
)
}
)
private class PointsArea(points: List<Point>) {
val minX = points.minByOrNull { it.posX }!!.posX
val minY = points.minByOrNull { it.posY }!!.posY
val maxX = points.maxByOrNull { it.posX }!!.posX
val maxY = points.maxByOrNull { it.posY }!!.posY
val area = (maxX - minX) * (maxY - minY)
}
private data class Point(var posX: Long, var posY: Long, val velX: Long, val velY: Long) {
fun move() {
posX += velX
posY += velY
}
}
private class Points(val points: List<Point>) {
private var lastArea: PointsArea? = null
fun getArea(): PointsArea {
lastArea?.let { return it }
lastArea = PointsArea(points)
return lastArea!!
}
fun move() {
points.forEach { it.move() }
lastArea = null
}
fun print() {
val size = getArea()
val rows = points.groupBy { it.posY }
val rowSize = size.maxX - size.minX
(size.minY..size.maxY).forEach { y ->
val row = rows[y]
if (row == null)
print(".".repeat(rowSize.toInt()))
else
(size.minX..size.maxX).forEach { x ->
print(if (row.find { it.posX == x } == null) "." else "#")
}
println()
}
}
fun copy(): Points = Points(mutableListOf<Point>().apply { addAll(points.map { it.copy() }) })
}
private val testInput = """
position=< 9, 1> velocity=< 0, 2>
position=< 7, 0> velocity=<-1, 0>
position=< 3, -2> velocity=<-1, 1>
position=< 6, 10> velocity=<-2, -1>
position=< 2, -4> velocity=< 2, 2>
position=<-6, 10> velocity=< 2, -2>
position=< 1, 8> velocity=< 1, -1>
position=< 1, 7> velocity=< 1, 0>
position=<-3, 11> velocity=< 1, -2>
position=< 7, 6> velocity=<-1, -1>
position=<-2, 3> velocity=< 1, 0>
position=<-4, 3> velocity=< 2, 0>
position=<10, -3> velocity=<-1, 1>
position=< 5, 11> velocity=< 1, -2>
position=< 4, 7> velocity=< 0, -1>
position=< 8, -2> velocity=< 0, 1>
position=<15, 0> velocity=<-2, 0>
position=< 1, 6> velocity=< 1, 0>
position=< 8, 9> velocity=< 0, -1>
position=< 3, 3> velocity=<-1, 1>
position=< 0, 5> velocity=< 0, -1>
position=<-2, 2> velocity=< 2, 0>
position=< 5, -2> velocity=< 1, 2>
position=< 1, 4> velocity=< 2, 1>
position=<-2, 7> velocity=< 2, -2>
position=< 3, 6> velocity=<-1, -1>
position=< 5, 0> velocity=< 1, 0>
position=<-6, 0> velocity=< 2, 0>
position=< 5, 9> velocity=< 1, -2>
position=<14, 7> velocity=<-2, 0>
position=<-3, 6> velocity=< 2, -1>
""".trimIndent()
private val puzzleInput = """
position=<-32494, 54541> velocity=< 3, -5>
position=<-21598, 11014> velocity=< 2, -1>
position=< 21906, 21894> velocity=<-2, -2>
position=<-32484, -32508> velocity=< 3, 3>
position=<-54245, -21619> velocity=< 5, 2>
position=<-54251, 11012> velocity=< 5, -1>
position=<-54235, 32774> velocity=< 5, -3>
position=<-10726, 32773> velocity=< 1, -3>
position=<-43370, 21892> velocity=< 4, -2>
position=< 54586, -32500> velocity=<-5, 3>
position=<-32492, 21896> velocity=< 3, -2>
position=<-43350, 43661> velocity=< 4, -4>
position=<-54243, -10739> velocity=< 5, 1>
position=<-32494, 43661> velocity=< 3, -4>
position=<-10705, 11021> velocity=< 1, -1>
position=< 43698, 21900> velocity=<-4, -2>
position=< 54582, -54260> velocity=<-5, 5>
position=< 43686, 54533> velocity=<-4, -5>
position=< 11050, -10740> velocity=<-1, 1>
position=<-43318, -32506> velocity=< 4, 3>
position=< 32814, 32775> velocity=<-3, -3>
position=< 32842, -21624> velocity=<-3, 2>
position=< 11045, -10746> velocity=<-1, 1>
position=<-10726, 11020> velocity=< 1, -1>
position=<-43314, 21896> velocity=< 4, -2>
position=<-32442, -21620> velocity=< 3, 2>
position=< 43725, 32776> velocity=<-4, -3>
position=< 11051, 43654> velocity=<-1, -4>
position=< 54586, 21896> velocity=<-5, -2>
position=< 43682, 32773> velocity=<-4, -3>
position=<-21582, 32780> velocity=< 2, -3>
position=< 43690, -43388> velocity=<-4, 4>
position=< 32838, -21623> velocity=<-3, 2>
position=< 43691, -54261> velocity=<-4, 5>
position=<-43371, -43379> velocity=< 4, 4>
position=< 54546, -10740> velocity=<-5, 1>
position=< 21958, -32507> velocity=<-2, 3>
position=<-32454, 21899> velocity=< 3, -2>
position=<-32486, 21893> velocity=< 3, -2>
position=< 11042, -21625> velocity=<-1, 2>
position=<-10721, -10740> velocity=< 1, 1>
position=< 11042, 32781> velocity=<-1, -3>
position=<-21598, 11018> velocity=< 2, -1>
position=<-21578, -43384> velocity=< 2, 4>
position=< 43702, -43383> velocity=<-4, 4>
position=< 11077, -10748> velocity=<-1, 1>
position=<-43365, 11012> velocity=< 4, -1>
position=<-54202, -54268> velocity=< 5, 5>
position=< 32786, -10741> velocity=<-3, 1>
position=< 54582, 11017> velocity=<-5, -1>
position=<-32465, -43380> velocity=< 3, 4>
position=< 21931, -43385> velocity=<-2, 4>
position=< 43682, -54259> velocity=<-4, 5>
position=<-43349, -43386> velocity=< 4, 4>
position=<-43318, -43380> velocity=< 4, 4>
position=< 54582, -21622> velocity=<-5, 2>
position=< 21966, -21628> velocity=<-2, 2>
position=<-21553, -21628> velocity=< 2, 2>
position=<-10717, 11016> velocity=< 1, -1>
position=<-32486, -54265> velocity=< 3, 5>
position=< 11061, -32508> velocity=<-1, 3>
position=< 32844, -54264> velocity=<-3, 5>
position=<-10733, -43384> velocity=< 1, 4>
position=< 54591, -10739> velocity=<-5, 1>
position=< 21934, -54266> velocity=<-2, 5>
position=<-32438, 43657> velocity=< 3, -4>
position=< 21922, -43381> velocity=<-2, 4>
position=<-43374, 21893> velocity=< 4, -2>
position=<-21606, -21625> velocity=< 2, 2>
position=<-54251, 43656> velocity=< 5, -4>
position=< 32815, -10748> velocity=<-3, 1>
position=<-43364, -10739> velocity=< 4, 1>
position=< 21957, -43388> velocity=<-2, 4>
position=< 11082, -43381> velocity=<-1, 4>
position=<-54236, 11018> velocity=< 5, -1>
position=<-21593, -10739> velocity=< 2, 1>
position=<-10694, 32781> velocity=< 1, -3>
position=< 21963, -54268> velocity=<-2, 5>
position=<-32493, -21624> velocity=< 3, 2>
position=<-21558, 11015> velocity=< 2, -1>
position=<-43342, 32780> velocity=< 4, -3>
position=<-54246, -43380> velocity=< 5, 4>
position=<-21586, 21894> velocity=< 2, -2>
position=<-43363, -54259> velocity=< 4, 5>
position=<-43370, -21624> velocity=< 4, 2>
position=<-43317, -43384> velocity=< 4, 4>
position=<-43358, 21900> velocity=< 4, -2>
position=< 54575, 32773> velocity=<-5, -3>
position=<-43334, -54267> velocity=< 4, 5>
position=< 43703, -21628> velocity=<-4, 2>
position=<-32483, 54541> velocity=< 3, -5>
position=<-21580, 32781> velocity=< 2, -3>
position=< 54602, 54538> velocity=<-5, -5>
position=< 43723, 43656> velocity=<-4, -4>
position=< 11034, -21621> velocity=<-1, 2>
position=< 32822, -32502> velocity=<-3, 3>
position=< 54582, 32780> velocity=<-5, -3>
position=<-54238, -21620> velocity=< 5, 2>
position=< 43690, 32781> velocity=<-4, -3>
position=<-32475, 32779> velocity=< 3, -3>
position=<-21578, 32779> velocity=< 2, -3>
position=< 11084, 21892> velocity=<-1, -2>
position=< 43718, -10745> velocity=<-4, 1>
position=<-10698, 43660> velocity=< 1, -4>
position=<-32490, 43652> velocity=< 3, -4>
position=<-10674, -54268> velocity=< 1, 5>
position=< 21946, -43381> velocity=<-2, 4>
position=<-54249, 11021> velocity=< 5, -1>
position=< 11069, 54541> velocity=<-1, -5>
position=< 43669, -54259> velocity=<-4, 5>
position=< 11066, 54532> velocity=<-1, -5>
position=<-43318, -21623> velocity=< 4, 2>
position=< 11066, -21620> velocity=<-1, 2>
position=<-21586, -32501> velocity=< 2, 3>
position=< 21949, -10739> velocity=<-2, 1>
position=<-54253, -10748> velocity=< 5, 1>
position=<-21561, -32508> velocity=< 2, 3>
position=<-54237, 32777> velocity=< 5, -3>
position=< 11070, 54541> velocity=<-1, -5>
position=<-10707, 21897> velocity=< 1, -2>
position=< 54557, 43652> velocity=<-5, -4>
position=< 32821, -54268> velocity=<-3, 5>
position=<-43334, 11014> velocity=< 4, -1>
position=< 54546, -32501> velocity=<-5, 3>
position=< 54573, 43656> velocity=<-5, -4>
position=< 54582, -43388> velocity=<-5, 4>
position=< 21938, 32779> velocity=<-2, -3>
position=<-21579, 54541> velocity=< 2, -5>
position=< 43722, 32773> velocity=<-4, -3>
position=<-54198, 21892> velocity=< 5, -2>
position=<-43334, -32499> velocity=< 4, 3>
position=<-32492, -21628> velocity=< 3, 2>
position=<-32434, 11016> velocity=< 3, -1>
position=< 54548, -32508> velocity=<-5, 3>
position=< 21906, 43656> velocity=<-2, -4>
position=<-54228, -43383> velocity=< 5, 4>
position=< 54604, -54264> velocity=<-5, 5>
position=<-10718, -10747> velocity=< 1, 1>
position=< 43718, 54534> velocity=<-4, -5>
position=<-10690, -43379> velocity=< 1, 4>
position=<-21578, 43652> velocity=< 2, -4>
position=< 11050, -10747> velocity=<-1, 1>
position=<-54228, 11016> velocity=< 5, -1>
position=<-54254, -10742> velocity=< 5, 1>
position=<-43349, 11015> velocity=< 4, -1>
position=<-21574, -54265> velocity=< 2, 5>
position=<-21598, 54535> velocity=< 2, -5>
position=<-32469, 32779> velocity=< 3, -3>
position=<-10678, 11016> velocity=< 1, -1>
position=< 21940, -10739> velocity=<-2, 1>
position=< 21916, -21619> velocity=<-2, 2>
position=<-21587, 54536> velocity=< 2, -5>
position=<-32465, -54259> velocity=< 3, 5>
position=< 54567, 54541> velocity=<-5, -5>
position=< 54556, 54541> velocity=<-5, -5>
position=<-32438, -54265> velocity=< 3, 5>
position=< 54565, 32774> velocity=<-5, -3>
position=< 54598, -32506> velocity=<-5, 3>
position=< 11062, -32501> velocity=<-1, 3>
position=<-32485, -32499> velocity=< 3, 3>
position=< 32846, 32776> velocity=<-3, -3>
position=< 11042, -21623> velocity=<-1, 2>
position=< 54571, -32501> velocity=<-5, 3>
position=< 32786, 54533> velocity=<-3, -5>
position=<-10701, 21901> velocity=< 1, -2>
position=<-10707, -10743> velocity=< 1, 1>
position=<-32438, -32507> velocity=< 3, 3>
position=< 32838, -43381> velocity=<-3, 4>
position=<-43318, -43380> velocity=< 4, 4>
position=< 11066, 21895> velocity=<-1, -2>
position=< 21906, -43388> velocity=<-2, 4>
position=<-21557, 11012> velocity=< 2, -1>
position=<-54217, -43388> velocity=< 5, 4>
position=< 54546, -10744> velocity=<-5, 1>
position=<-54198, 21898> velocity=< 5, -2>
position=<-32436, -32508> velocity=< 3, 3>
position=<-32450, 43661> velocity=< 3, -4>
position=<-54222, 21899> velocity=< 5, -2>
position=<-32482, 11021> velocity=< 3, -1>
position=<-43334, 32773> velocity=< 4, -3>
position=< 11038, -32508> velocity=<-1, 3>
position=< 32803, -54264> velocity=<-3, 5>
position=<-32476, 11018> velocity=< 3, -1>
position=<-10726, 11016> velocity=< 1, -1>
position=<-32443, -32508> velocity=< 3, 3>
position=<-21601, 32773> velocity=< 2, -3>
position=< 21925, 54539> velocity=<-2, -5>
position=<-32454, 54537> velocity=< 3, -5>
position=< 32786, -10747> velocity=<-3, 1>
position=<-54245, -21628> velocity=< 5, 2>
position=<-21598, 32780> velocity=< 2, -3>
position=< 54554, -10741> velocity=<-5, 1>
position=<-43322, -10743> velocity=< 4, 1>
position=<-43338, -32506> velocity=< 4, 3>
position=<-43370, -21628> velocity=< 4, 2>
position=< 43690, 21892> velocity=<-4, -2>
position=< 32823, 43652> velocity=<-3, -4>
position=< 54559, 11020> velocity=<-5, -1>
position=<-10705, -43387> velocity=< 1, 4>
position=< 54554, 43658> velocity=<-5, -4>
position=<-54254, -54265> velocity=< 5, 5>
position=<-21578, 43658> velocity=< 2, -4>
position=<-54228, -43383> velocity=< 5, 4>
position=<-10682, -43388> velocity=< 1, 4>
position=<-32446, -10741> velocity=< 3, 1>
position=<-43358, 32781> velocity=< 4, -3>
position=< 21958, 21900> velocity=<-2, -2>
position=< 54574, 54538> velocity=<-5, -5>
position=< 11079, -32508> velocity=<-1, 3>
position=< 43682, -54264> velocity=<-4, 5>
position=< 43687, 32772> velocity=<-4, -3>
position=< 43702, 21893> velocity=<-4, -2>
position=< 32807, -32499> velocity=<-3, 3>
position=<-32467, -21623> velocity=< 3, 2>
position=< 11066, -21625> velocity=<-1, 2>
position=< 11078, 54536> velocity=<-1, -5>
position=< 54575, 21901> velocity=<-5, -2>
position=<-32446, -21620> velocity=< 3, 2>
position=< 21942, -10744> velocity=<-2, 1>
position=<-54204, 43661> velocity=< 5, -4>
position=<-10726, -43384> velocity=< 1, 4>
position=< 54598, 21898> velocity=<-5, -2>
position=<-21590, 21892> velocity=< 2, -2>
position=<-43322, 21899> velocity=< 4, -2>
position=<-21587, -43384> velocity=< 2, 4>
position=< 21957, 21901> velocity=<-2, -2>
position=< 54571, -54262> velocity=<-5, 5>
position=<-43334, -32499> velocity=< 4, 3>
position=< 54551, -43379> velocity=<-5, 4>
position=<-54230, -43379> velocity=< 5, 4>
position=<-32465, 54532> velocity=< 3, -5>
position=<-10726, 32774> velocity=< 1, -3>
position=<-32486, 11013> velocity=< 3, -1>
position=< 54582, 11019> velocity=<-5, -1>
position=<-21614, 32777> velocity=< 2, -3>
position=< 43691, -54266> velocity=<-4, 5>
position=<-43350, -32500> velocity=< 4, 3>
position=< 43722, -10742> velocity=<-4, 1>
position=<-10675, -32504> velocity=< 1, 3>
position=<-43318, 54535> velocity=< 4, -5>
position=<-21574, -21624> velocity=< 2, 2>
position=<-21574, -54261> velocity=< 2, 5>
position=<-21557, -21628> velocity=< 2, 2>
position=< 32798, -21619> velocity=<-3, 2>
position=<-21606, 54537> velocity=< 2, -5>
position=< 11066, -10742> velocity=<-1, 1>
position=< 54598, 43654> velocity=<-5, -4>
position=< 11082, 21896> velocity=<-1, -2>
position=< 21958, -43388> velocity=<-2, 4>
position=< 54581, -21619> velocity=<-5, 2>
position=<-21558, 43652> velocity=< 2, -4>
position=<-21613, 43656> velocity=< 2, -4>
position=<-54241, -54260> velocity=< 5, 5>
position=< 32802, -10742> velocity=<-3, 1>
position=<-54225, 21892> velocity=< 5, -2>
position=<-10706, -10742> velocity=< 1, 1>
position=< 43669, -43384> velocity=<-4, 4>
position=<-21558, -10739> velocity=< 2, 1>
position=< 11042, -32504> velocity=<-1, 3>
position=<-32438, -32500> velocity=< 3, 3>
position=<-10716, -32505> velocity=< 1, 3>
position=<-54250, 11021> velocity=< 5, -1>
position=<-54253, -10739> velocity=< 5, 1>
position=<-10717, 54537> velocity=< 1, -5>
position=< 11042, -43388> velocity=<-1, 4>
position=< 54594, 21899> velocity=<-5, -2>
position=< 32799, 54533> velocity=<-3, -5>
position=<-21598, -32502> velocity=< 2, 3>
position=<-21563, -10739> velocity=< 2, 1>
position=< 21922, -43387> velocity=<-2, 4>
position=< 21962, -43379> velocity=<-2, 4>
position=< 43668, 32781> velocity=<-4, -3>
position=<-54246, 54540> velocity=< 5, -5>
position=< 21908, -21628> velocity=<-2, 2>
position=< 43711, -54259> velocity=<-4, 5>
position=<-54212, -54259> velocity=< 5, 5>
position=<-21574, 32777> velocity=< 2, -3>
position=< 21942, -32507> velocity=<-2, 3>
position=< 43722, 11013> velocity=<-4, -1>
position=< 32845, 54532> velocity=<-3, -5>
position=< 43702, 21897> velocity=<-4, -2>
position=<-32492, 54536> velocity=< 3, -5>
position=<-21574, -10747> velocity=< 2, 1>
position=<-54213, -43379> velocity=< 5, 4>
position=<-54218, -32505> velocity=< 5, 3>
position=<-43316, -21624> velocity=< 4, 2>
position=<-10734, -21625> velocity=< 1, 2>
position=<-21598, -10748> velocity=< 2, 1>
position=<-10693, -43379> velocity=< 1, 4>
position=<-32491, -43384> velocity=< 3, 4>
position=< 21926, -43380> velocity=<-2, 4>
position=<-10691, -54259> velocity=< 1, 5>
position=<-54238, 54539> velocity=< 5, -5>
position=< 11031, 43652> velocity=<-1, -4>
position=<-43334, 11018> velocity=< 4, -1>
position=< 43682, -21625> velocity=<-4, 2>
position=< 21958, -54261> velocity=<-2, 5>
position=< 54595, -32499> velocity=<-5, 3>
position=< 54564, 43658> velocity=<-5, -4>
position=<-32486, -10746> velocity=< 3, 1>
""".trimIndent()
| 0 | Kotlin | 0 | 0 | ac62ce8aeaed065f8fbd11e30368bfe5d31b7033 | 17,442 | AdventOfCode | Creative Commons Zero v1.0 Universal |
solutions/aockt/y2023/Y2023D01.kt | Jadarma | 624,153,848 | false | {"Kotlin": 435090} | package aockt.y2023
import aockt.util.parse
import io.github.jadarma.aockt.core.Solution
object Y2023D01 : Solution {
/** A map from digit symbols and spellings to their numerical values. */
private val textToDigit: Map<String, Int> = buildMap {
listOf("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine")
.forEachIndexed { value, text ->
put(value.toString(), value)
put(text, value)
}
}
/**
* Processes a modified calibration string and extracts the original calibration number.
* @param acceptSpelling Whether to accept spelled-out digits. If false, only numerical notation is considered.
*/
private fun String.normalizeCalibrationNumber(acceptSpelling: Boolean): Int = parse {
val acceptable =
if(acceptSpelling) textToDigit.keys
else textToDigit.keys.filter { it.length == 1 && it.first().isDigit() }
val first = findAnyOf(acceptable)!!.second.let(textToDigit::getValue)
val last = findLastAnyOf(acceptable)!!.second.let(textToDigit::getValue)
first * 10 + last
}
/** Parses the [input], computes the calibration numbers and returns their sum. */
private fun calibrate(input: String, acceptSpelling: Boolean): Int =
input
.lineSequence()
.sumOf { it.normalizeCalibrationNumber(acceptSpelling) }
override fun partOne(input: String) = calibrate(input, acceptSpelling = false)
override fun partTwo(input: String) = calibrate(input, acceptSpelling = true)
}
| 0 | Kotlin | 0 | 3 | 19773317d665dcb29c84e44fa1b35a6f6122a5fa | 1,600 | advent-of-code-kotlin-solutions | The Unlicense |
src/Year2022Day03.kt | zhangt2333 | 575,260,256 | false | {"Kotlin": 34993} | import java.util.BitSet
fun main() {
fun Char.priority(): Int = when (this) {
in 'a'..'z' -> this - 'a' + 1
in 'A'..'Z' -> this - 'A' + 27
else -> throw IllegalArgumentException()
}
fun indexBitSet(items: String) = BitSet(60).apply {
items.forEach { this[it.priority()] = true }
}
fun part1(input: List<String>): Int {
return input.sumOf {
indexBitSet(it.substring(0, it.length / 2)).apply {
this.and(indexBitSet(it.substring(it.length / 2)))
}.nextSetBit(0)
}
}
fun part2(input: List<String>): Int {
return input.map { indexBitSet(it) }.chunked(3).sumOf { (a, b, c) ->
a.and(b)
a.and(c)
a.nextSetBit(0)
}
}
val testLines = readLines(true)
check(part1(testLines) == 157)
check(part2(testLines) == 70)
val lines = readLines()
println(part1(lines))
println(part2(lines))
}
| 0 | Kotlin | 0 | 0 | cdba887c4df3a63c224d5a80073bcad12786ac71 | 990 | aoc-2022-in-kotlin | Apache License 2.0 |
src/day10/Day10.kt | Ciel-MC | 572,868,010 | false | {"Kotlin": 55885} | package day10
import readInput
sealed interface Instruction {
fun run(state: State): Boolean
companion object {
fun parse(line: String): Instruction = when {
line.startsWith("addx ") -> AddX(line.drop(5).toInt())
line == "noop" -> NoOp
else -> throw IllegalArgumentException("Unknown instruction: $line")
}
}
}
object NoOp : Instruction {
override fun run(state: State): Boolean = true
}
data class AddX(val x: Int) : Instruction {
override fun run(state: State): Boolean {
return if (state.waited) {
state.waited = false
state.value += x
true
} else {
state.waited = true
false
}
}
}
data class State(var value: Int, var waited: Boolean = false)
fun main() {
fun part1(input: List<String>): Int {
val state = State(1)
var accumulator = 0
val instructions = input.map(Instruction.Companion::parse)
var index = 1
var instructionIndex = 0
while (instructionIndex < instructions.size) {
val instruction = instructions[instructionIndex]
if (instruction.run(state)) {
instructionIndex ++
}
index ++
if ((index - 20) % 40 == 0) {
accumulator += state.value * index
}
}
return accumulator
}
fun part2(input: List<String>) {
val state = State(1)
val instructions = input.map(Instruction.Companion::parse)
var index = 1
var instructionIndex = 0
repeat(40) {
print((it+1).toString().padStart(3, ' '))
}
println()
while (instructionIndex < instructions.size) {
val instruction = instructions[instructionIndex]
if (instruction.run(state)) {
instructionIndex ++
}
val currentX = index % 40
if (currentX in state.value-1..state.value+1) {
print("#".padStart(3, ' '))
} else {
print(".".padStart(3, ' '))
}
if (currentX == 0) {
println()
}
index++
}
}
val testInput = readInput(10, true)
part1(testInput).let { check(it == 13140) { println(it) } }
val input = readInput(10)
println(part1(input))
part2(input)
// println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 7eb57c9bced945dcad4750a7cc4835e56d20cbc8 | 2,470 | Advent-Of-Code | Apache License 2.0 |
src/day08/Day08.kt | hamerlinski | 572,951,914 | false | {"Kotlin": 25910} | package day08
import readInput
fun main() {
val input = readInput("Day08", "day08")
val forest = Forest(input)
forest.plant()
println(forest.numOfVisibleTrees())
println(forest.highestScenicScore())
}
@Suppress("DuplicatedCode")
class Forest(private val input: List<String>) {
private val trees: MutableList<MutableList<Tree>> = mutableListOf()
fun plant() {
input.listIterator().forEach { row ->
val treesRow: MutableList<Tree> = mutableListOf()
row.iterator().forEach { treeInfo ->
val tree = Tree(treeInfo.toString().toInt())
treesRow.add(tree)
}
trees.add(treesRow)
}
}
fun numOfVisibleTrees(): Int {
val forestWidth = trees[0].size
val forestHeight = trees.size
var visibleTrees = forestWidth * 2 + forestHeight * 2 - 4
for (i in 1 until trees.size - 1) {
for (j in 1 until trees[i].size - 1) {
var westernTreeIndex = j - 1
var northernTreeIndex = i - 1
var easternTreeIndex = j + 1
var southernTreeIndex = i + 1
var checkedAndVisible = false
while (westernTreeIndex >= 0) {
if (westernTreeIndex == 0 && trees[i][j].height() > trees[i][westernTreeIndex].height()) {
visibleTrees += 1
checkedAndVisible = true
break
} else if (trees[i][j].height() > trees[i][westernTreeIndex].height()) {
westernTreeIndex -= 1
} else break
}
while ((northernTreeIndex >= 0) && !checkedAndVisible) {
if (northernTreeIndex == 0 && trees[i][j].height() > trees[northernTreeIndex][j].height()) {
visibleTrees += 1
checkedAndVisible = true
break
} else if (trees[i][j].height() > trees[northernTreeIndex][j].height()) {
northernTreeIndex -= 1
} else break
}
while ((easternTreeIndex <= forestWidth - 1) && !checkedAndVisible) {
if (easternTreeIndex == (forestWidth - 1) && trees[i][j].height() > trees[i][forestWidth - 1].height()) {
visibleTrees += 1
checkedAndVisible = true
break
} else if (trees[i][j].height() > trees[i][easternTreeIndex].height()) {
easternTreeIndex += 1
} else break
}
while ((southernTreeIndex <= forestHeight - 1) && !checkedAndVisible) {
if (southernTreeIndex == (forestHeight - 1) && trees[i][j].height() > trees[forestHeight - 1][j].height()) {
visibleTrees += 1
break
} else if (trees[i][j].height() > trees[southernTreeIndex][j].height()) {
southernTreeIndex += 1
} else break
}
}
}
return visibleTrees
}
fun highestScenicScore(): Int {
val forestWidth = trees[0].size
val forestHeight = trees.size
var score = 0
for (i in 1 until trees.size - 1) {
for (j in 1 until trees[i].size - 1) {
var westernTreeIndex = j - 1
var northernTreeIndex = i - 1
var easternTreeIndex = j + 1
var southernTreeIndex = i + 1
var westViewScore = 0
var northViewScore = 0
var eastViewScore = 0
var southViewScore = 0
while (westernTreeIndex >= 0) {
if (trees[i][j].height() > trees[i][westernTreeIndex].height()) {
westViewScore += 1
westernTreeIndex -= 1
} else if (trees[i][j].height() <= trees[i][westernTreeIndex].height()) {
westViewScore += 1
westernTreeIndex -= 1
break
} else break
}
while (northernTreeIndex >= 0) {
if (trees[i][j].height() > trees[northernTreeIndex][j].height()) {
northViewScore += 1
northernTreeIndex -= 1
} else if (trees[i][j].height() <= trees[northernTreeIndex][j].height()) {
northViewScore += 1
northernTreeIndex -= 1
break
} else break
}
while (easternTreeIndex <= forestWidth - 1) {
if (trees[i][j].height() > trees[i][easternTreeIndex].height()) {
eastViewScore += 1
easternTreeIndex += 1
} else if (trees[i][j].height() <= trees[i][easternTreeIndex].height()) {
eastViewScore += 1
easternTreeIndex += 1
break
} else break
}
while (southernTreeIndex <= forestHeight - 1) {
if (trees[i][j].height() > trees[southernTreeIndex][j].height()) {
southViewScore += 1
southernTreeIndex += 1
} else if (trees[i][j].height() <= trees[southernTreeIndex][j].height()) {
southViewScore += 1
southernTreeIndex += 1
break
} else break
}
val potentialScore = westViewScore * northViewScore * eastViewScore * southViewScore
if (potentialScore > score) {
score = potentialScore
}
}
}
return score
}
}
class Tree(private val height: Int) {
fun height(): Int {
return this.height
}
}
| 0 | Kotlin | 0 | 0 | bbe47c5ae0577f72f8c220b49d4958ae625241b0 | 6,158 | advent-of-code-kotlin-2022 | Apache License 2.0 |
y2018/src/main/kotlin/adventofcode/y2018/Day03.kt | Ruud-Wiegers | 434,225,587 | false | {"Kotlin": 503769} | package adventofcode.y2018
import adventofcode.io.AdventSolution
object Day03 : AdventSolution(2018, 3, "No Matter How You Slice It") {
override fun solvePartOne(input: String): Int {
val claims = parseInput(input)
val fabric = applyClaimsToFabric(claims)
return fabric.count { it > 1 }
}
override fun solvePartTwo(input: String): String {
val claims = parseInput(input)
val fabric = applyClaimsToFabric(claims)
return claims.first { claim -> noOverlap(claim, fabric) }.id
}
private fun parseInput(input: String): Sequence<Claim> {
val rule = """#(\d+) @ (\d+),(\d+): (\d+)x(\d+)""".toRegex()
return input.lineSequence()
.map { rule.matchEntire(it)!!.destructured }
.map { (id, x, y, w, h) -> Claim(id, x.toInt(), y.toInt(), w.toInt(), h.toInt()) }
}
private fun applyClaimsToFabric(claims: Sequence<Claim>) =
ShortArray(1_000_000).apply {
claims.forEach { claim ->
for (x in claim.x until claim.x + claim.w)
for (y in claim.y until claim.y + claim.h)
this[1000 * y + x]++
}
}
private fun noOverlap(claim: Claim, fabric: ShortArray): Boolean {
for (x in claim.x until claim.x + claim.w)
for (y in claim.y until claim.y + claim.h)
if (fabric[1000 * y + x] > 1) return false
return true
}
private data class Claim(
val id: String,
val x: Int,
val y: Int,
val w: Int,
val h: Int)
} | 0 | Kotlin | 0 | 3 | fc35e6d5feeabdc18c86aba428abcf23d880c450 | 1,654 | advent-of-code | MIT License |
facebook/2019/qualification/4/main.kt | seirion | 17,619,607 | false | {"C++": 801740, "HTML": 42242, "Kotlin": 37689, "Python": 21759, "C": 3798, "JavaScript": 294} | import java.util.*
fun main(args: Array<String>) {
val n = readLine()!!.toInt()
repeat(n) {
print("Case #${it + 1}: ")
solve()
}
}
data class T(val x: Int, val y:Int, val p: Int)
fun solve() {
fail = false
val (n, M) = readLine()!!.split(" ").map { it.toInt() }
val a = IntArray(n + 1) { 0 }
val t = ArrayList<T>()
val h = HashMap<Int, Int>()
repeat(M) {
val (x, y, p) = readLine()!!.split(" ").map { it.toInt() }
t.add(T(x, y, p))
h[p] = h.getOrElse(p, { 0 }) + 1
}
val v = h.toList().sortedBy { it.second }.map { it.first }
v.forEach {
while (true) {
val index = find(it, t)
if (index == -1) break
put(t[index].x, t[index].p, a)
put(t[index].y, t[index].p, a)
t.removeAt(index)
}
}
if (!fail && isValidTree(a)) {
println(a.drop(1).joinToString(" "))
} else println("Impossible")
}
var fail = false // FIXME : bad codes
fun find(i: Int, a: ArrayList<T>) = a.indexOfFirst { it.p == i }
fun put(cc: Int, p: Int, a: IntArray) {
var c = cc
if (c == p) {
// nothing to do
} else if (a[c] == 0) {
a[c] = p
} else {
var temp = 0
while (true) {
temp++
if (temp > 100) {
fail = true
return
}
if (c == p) return
if (a[c] == 0) break
c = a[c]
}
a[c] = p
}
}
fun isValidTree(a: IntArray) =
a.indexOfFirst { cycle(it, a) } == -1
fun cycle(i: Int, a: IntArray): Boolean {
val s = HashSet<Int>()
var x = i
while (x != 0) {
if (s.contains(x)) return true
s.add(x)
x = a[x]
}
return false
}
| 0 | C++ | 4 | 4 | a59df98712c7eeceabc98f6535f7814d3a1c2c9f | 1,793 | code | Apache License 2.0 |
src/main/de/ddkfm/Day2.kt | DDKFM | 433,861,159 | false | {"Kotlin": 13522} | package de.ddkfm
import java.io.File
enum class CommandType {
FORWARD,
DOWN,
UP;
companion object {
fun parse(str : String) : CommandType {
return CommandType.valueOf(str.uppercase())
}
}
}
data class Command(
val type : CommandType,
val unit : Int
) {
fun sum() : Int {
return when(type) {
CommandType.FORWARD, CommandType.DOWN -> unit
CommandType.UP -> -unit
}
}
}
class Day2 : DayInterface<List<String>, Int> {
override fun part1(input: List<String>): Int {
return input
.map { Command(CommandType.parse(it.split(" ")[0]), it.split(" ")[1].toInt()) }
.groupBy { when(it.type) {
CommandType.FORWARD -> "horizontal"
CommandType.UP, CommandType.DOWN -> "depth"
} }
.map { it.key to it.value.sumOf { command -> command.sum() } }
.toMap()
.values
.reduce{acc, i -> acc * i }
}
override fun part2(input: List<String>): Int {
var aim = 0;
var depth = 0;
var horizontal = 0;
val commands = input
.map { Command(CommandType.parse(it.split(" ")[0]), it.split(" ")[1].toInt()) }
commands.forEach { command ->
when(command.type) {
CommandType.DOWN -> aim += command.unit
CommandType.UP -> aim -= command.unit
CommandType.FORWARD -> {
horizontal += command.unit
depth += aim * command.unit
}
}
}
return horizontal * depth
}
} | 0 | Kotlin | 0 | 0 | 6e147b526414ab5d11732dc32c18ad760f97ff59 | 1,658 | AdventOfCode21 | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem1696/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem1696
/**
* LeetCode page: [1696. Jump Game VI](https://leetcode.com/problems/jump-game-vi/);
*/
class Solution {
/* Complexity:
* Time O(N) and Space O(N) where N is the size of nums;
*/
fun maxResult(nums: IntArray, k: Int): Int {
val maxScorePerIndex = IntArray(nums.size)
val bestJumpIndexPq = CustomQueue(k) { index -> maxScorePerIndex[index] }
maxScorePerIndex[0] = nums[0]
bestJumpIndexPq.offer(0)
for (index in 1..nums.lastIndex) {
val bestJumpIndex = bestJumpIndexPq.poll(index)
maxScorePerIndex[index] = nums[index] + maxScorePerIndex[bestJumpIndex]
bestJumpIndexPq.offer(index)
}
return maxScorePerIndex.last()
}
private class CustomQueue(
private val jumpLength: Int,
private val readMaxScore: (index: Int) -> Int
) {
private val queue = ArrayDeque<Int>()
private var lastIndex = -1
fun offer(newIndex: Int) {
require(newIndex == lastIndex + 1) { "Current state is valid for index ${lastIndex + 1} only." }
lastIndex++
when {
queue.isEmpty() -> updateCaseEmpty(newIndex)
isNewBest(newIndex) -> updateCaseNewBest(newIndex)
else -> updateCaseNotBest(newIndex)
}
}
private fun updateCaseEmpty(newIndex: Int) {
queue.add(newIndex)
}
private fun isNewBest(newIndex: Int) = readMaxScore(newIndex) >= readMaxScore(queue.first())
private fun updateCaseNewBest(newIndex: Int) {
queue.clear()
queue.add(newIndex)
}
private fun updateCaseNotBest(newIndex: Int) {
val maxScore = readMaxScore(newIndex)
while (readMaxScore(queue.last()) <= maxScore) {
queue.removeLast()
}
queue.addLast(newIndex)
}
fun poll(currIndex: Int): Int {
require(currIndex == lastIndex + 1) { "Current state is valid for index ${lastIndex + 1} only." }
popFirstUntilValid(currIndex)
return queue.first()
}
private fun popFirstUntilValid(currIndex: Int) {
while (queue.first() < currIndex - jumpLength) {
queue.removeFirst()
}
}
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 2,391 | hj-leetcode-kotlin | Apache License 2.0 |
src/Day02_part1.kt | jmorozov | 573,077,620 | false | {"Kotlin": 31919} | import java.util.EnumMap
fun main() {
val inputData = readInput("Day02")
var myTotalScore = 0
for (line in inputData) {
val trimmedLine = line.trim()
val opponent = ShapePart1.from(trimmedLine.take(1))
val mine = ShapePart1.from(trimmedLine.takeLast(1))
val shapePoints = mine.point
val roundOutcomePoints = RoundOutcomePart1.get(opponent, mine).point
myTotalScore += shapePoints + roundOutcomePoints
}
println("My total score: $myTotalScore")
}
enum class ShapePart1(val point: Int) {
ROCK(1),
PAPER(2),
SCISSORS(3),
UNKNOWN(0);
companion object {
fun from(str: String): ShapePart1 = when (str) {
"A", "X" -> ROCK
"B", "Y" -> PAPER
"C", "Z" -> SCISSORS
else -> UNKNOWN
}
}
}
enum class RoundOutcomePart1(val point: Int) {
LOST(0),
DRAW(3),
WON(6);
companion object {
private val defeats: EnumMap<ShapePart1, ShapePart1> = EnumMap(mapOf(
ShapePart1.ROCK to ShapePart1.SCISSORS,
ShapePart1.PAPER to ShapePart1.ROCK,
ShapePart1.SCISSORS to ShapePart1.PAPER,
ShapePart1.UNKNOWN to ShapePart1.UNKNOWN
))
fun get(opponent: ShapePart1, mine: ShapePart1): RoundOutcomePart1 = when {
opponent == mine -> DRAW
defeats[opponent] == mine -> LOST
else -> WON
}
}
} | 0 | Kotlin | 0 | 0 | 480a98838949dbc7b5b7e84acf24f30db644f7b7 | 1,452 | aoc-2022-in-kotlin | Apache License 2.0 |
implementation/src/main/kotlin/io/github/tomplum/aoc/map/volcano/OldVolcanoMap.kt | TomPlum | 572,260,182 | false | {"Kotlin": 224955} | package io.github.tomplum.aoc.map.volcano
import io.github.tomplum.libs.extensions.cartesianProduct
import java.util.*
class OldVolcanoMap(scan: List<String>) {
private val flowRates = mutableMapOf<String, Int>()
private val valves: Map<String, List<String>> = scan.associate { line ->
val label = line.removePrefix("Valve ").split(" ")[0].trim()
val flowRate = line.split(" has flow rate=")[1].split(";")[0].toInt()
val tunnels = if (line.contains("tunnels")) {
line.split("tunnels lead to valves ")[1].trim().split(", ")
} else {
listOf(line.split("tunnel leads to valve ")[1].trim())
}
flowRates[label] = flowRate
label to tunnels
}
var valveTimes = listOf<Map<String, Int>>()
val distances = Array(52) { Array(52) { -1 } }
fun findMaximumFlowRate(): Int {
/*val distances = mutableMapOf<Char, Int>()
val next = PriorityQueue<Char>()
val start = valves.keys.first()
next.offer(start)
distances[start] = 0
while(next.isNotEmpty()) {
val currentValve = next.poll()!!
val distance = distances[currentValve]!!
valves[currentValve]?.forEach { adjacentValve ->
val updatedDistance = distance + 1
if (updatedDistance < distances.getOrDefault(adjacentValve, Int.MAX_VALUE)) {
distances[adjacentValve] = updatedDistance
next.add(adjacentValve)
}
}
}*/
val valveLabels = valves.keys.toList()
val distinctCombinations = valveLabels.cartesianProduct(valveLabels).filter { (a, b) -> a != b }
valveLabels.forEach { start ->
valveLabels.forEach { end ->
distances[start.getAlphabetIndex()][end.getAlphabetIndex()] = findShortestPath(start, end).size - 1
}
}
val valveCandidates = valveLabels.filter { label -> flowRates[label]!! > 0 }
val times = calculateFlowRates(distances, "AA", 30, valveCandidates)
this.valveTimes = times
val rates = times.map { rates ->
rates.entries.fold(0) { pressure, (valve, time) -> pressure + flowRates[valve]!! * time }
}
return rates.max()
/*rates.map { rates ->
rates.entries.sumOf { (valve, time) -> flowRates[valve]!! * time }
}.maxOf { pressure -> pressure }*/
}
private fun calculateFlowRates(
paths: Array<Array<Int>>,
source: String,
time: Int,
remaining: List<String>,
opened: Map<String, Int> = mutableMapOf()
): List<Map<String, Int>> {
// A list of valve label -> time that valve spends open
val flowRates = mutableListOf(opened)
remaining.forEachIndexed { i, target ->
val distance = paths[source.getAlphabetIndex()][target.getAlphabetIndex()]
val newTime = time - distance - 1
if (newTime < 1) {
return@forEachIndexed
}
val newlyOpened = opened.toMutableMap()
newlyOpened[target] = newTime
val newRemaining = remaining.toMutableList()
newRemaining.removeAt(i)
flowRates.addAll(calculateFlowRates(paths, target, newTime, newRemaining, newlyOpened))
}
return flowRates
}
private fun findShortestPath(startingValve: String, finishingValve: String): List<String> {
if (startingValve == finishingValve) {
return listOf(startingValve)
}
val visited = mutableSetOf(startingValve)
val next = mutableListOf<List<String>>()
next.add(listOf(startingValve))
while(next.isNotEmpty()) {
val path = next.removeFirst()
val valve = path.last()
valves[valve]?.forEach { adjacent ->
if (adjacent in visited) {
return@forEach
}
val updatedPath = path + adjacent
if (adjacent == finishingValve) {
return updatedPath
}
visited.add(adjacent)
next.add(updatedPath)
}
}
throw IllegalArgumentException("Could not find path from $startingValve -> $finishingValve")
}
private fun String.getAlphabetIndex(): Int {
return this.sumOf { it.lowercase().first().code - 'a'.code }
}
} | 0 | Kotlin | 0 | 0 | 703db17fe02a24d809cc50f23a542d9a74f855fb | 4,485 | advent-of-code-2022 | Apache License 2.0 |
src/leetcodeProblem/leetcode/editor/en/DecodeWays.kt | faniabdullah | 382,893,751 | false | null | //A message containing letters from A-Z can be encoded into numbers using the
//following mapping:
//
//
//'A' -> "1"
//'B' -> "2"
//...
//'Z' -> "26"
//
//
// To decode an encoded message, all the digits must be grouped then mapped
//back into letters using the reverse of the mapping above (there may be multiple
//ways). For example, "11106" can be mapped into:
//
//
// "AAJF" with the grouping (1 1 10 6)
// "KJF" with the grouping (11 10 6)
//
//
// Note that the grouping (1 11 06) is invalid because "06" cannot be mapped
//into 'F' since "6" is different from "06".
//
// Given a string s containing only digits, return the number of ways to decode
//it.
//
// The answer is guaranteed to fit in a 32-bit integer.
//
//
// Example 1:
//
//
//Input: s = "12"
//Output: 2
//Explanation: "12" could be decoded as "AB" (1 2) or "L" (12).
//
//
// Example 2:
//
//
//Input: s = "226"
//Output: 3
//Explanation: "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2
// 6).
//
//
// Example 3:
//
//
//Input: s = "0"
//Output: 0
//Explanation: There is no character that is mapped to a number starting with 0.
//
//The only valid mappings with 0 are 'J' -> "10" and 'T' -> "20", neither of
//which start with 0.
//Hence, there are no valid ways to decode this since all digits need to be
//mapped.
//
//
// Example 4:
//
//
//Input: s = "06"
//Output: 0
//Explanation: "06" cannot be mapped to "F" because of the leading zero ("6" is
//different from "06").
//
//
//
// Constraints:
//
//
// 1 <= s.length <= 100
// s contains only digits and may contain leading zero(s).
//
// Related Topics String Dynamic Programming 👍 5577 👎 3606
package leetcodeProblem.leetcode.editor.en
class DecodeWays {
fun solution() {
}
//below code will be used for submission to leetcode (using plugin of course)
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
fun numDecodings(s: String): Int {
val n = s.length
val dp = IntArray(n + 1)
dp[0] = 1
dp[1] = if (s[n - 1] != '0') 1 else 0
for (i in 2..n) {
val current = n - i
val one = s.substring(current, current + 1).toInt()
val two = s.substring(current, current + 2).toInt()
dp[i] = (if (one > 0) dp[i - 1] else 0) + (if (two in 10..26) dp[i - 2] else 0)
}
return dp[n]
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
fun main() {}
| 0 | Kotlin | 0 | 6 | ecf14fe132824e944818fda1123f1c7796c30532 | 2,602 | dsa-kotlin | MIT License |
src/main/kotlin/adventofcode/y2021/Day18.kt | Tasaio | 433,879,637 | false | {"Kotlin": 117806} | import adventofcode.*
import java.math.BigInteger
import kotlin.math.ceil
import kotlin.math.floor
fun main() {
val testInput = """
[[[0,[5,8]],[[1,7],[9,6]]],[[4,[1,2]],[[1,4],2]]]
[[[5,[2,8]],4],[5,[[9,9],0]]]
[6,[[[6,2],[5,6]],[[7,6],[4,7]]]]
[[[6,[0,7]],[0,9]],[4,[9,[9,0]]]]
[[[7,[6,4]],[3,[1,3]]],[[[5,5],1],9]]
[[6,[[7,3],[3,2]]],[[[3,8],[5,7]],4]]
[[[[5,4],[7,7]],8],[[8,3],8]]
[[9,3],[[9,9],[6,[4,9]]]]
[[2,[[7,7],7]],[[5,8],[[9,3],[0,2]]]]
[[[[5,2],5],[8,[3,7]]],[[5,[7,5]],[4,4]]]
""".trimIndent()
runDay(
day = Day18::class,
testInput = testInput,
testAnswer1 = 4140,
testAnswer2 = 3993
)
}
open class Day18(staticInput: String? = null) : Y2021Day(18, staticInput) {
private val input = fetchInput()
override fun reset() {
super.reset()
}
fun getPair(str: String, i: Int): Pair<Int, Int>? {
if (str[i] == '[') {
var pos = i + 1
var leftStr = ""
while (str[pos].isDigit()) {
leftStr += str[pos++]
}
if (leftStr.isEmpty()) {
return null
}
if (str[pos++] != ',') {
return null
}
var rightStr = ""
while (str[pos].isDigit()) {
rightStr += str[pos++]
}
if (rightStr.isEmpty()) {
return null
}
return Pair(leftStr.toInt(), rightStr.toInt())
}
return null
}
private fun addLeft(str: String, pos: Int, num: Int): String {
var i = pos
while (i > 0) {
if (str[i].isDigit()) {
var numStr = str[i].toString()
if (str[i - 1].isDigit()) {
numStr = str[i - 1].toString() + str[i]
}
val newNum = numStr.toInt() + num
return str.substring(0, i + 1 - numStr.length) + newNum + str.substring(i + 1)
}
i--
}
return str
}
private fun addRight(str: String, pos: Int, num: Int): String {
for (i in pos..str.lastIndex) {
if (str[i].isDigit()) {
var numStr = str[i].toString()
if (str[i + 1].isDigit()) {
numStr = str[i] + str[i + 1].toString()
}
val newNum = numStr.toInt() + num
return str.substring(0, i) + newNum + str.substring(i + numStr.length)
}
}
return str
}
fun Pair<Int, Int>.size(): Int {
return 1 + first.toString().length + 1 + second.toString().length + 1
}
fun Pair<Int, Int>.toStringPair(): String {
return "[$first,$second]"
}
fun Pair<Int, Int>.magnitude(): Int {
return first * 3 + second * 2
}
private fun explode(str: String): String? {
var cnt = 0
var i = 0
while (i < str.length) {
if (str[i] == '[') {
val pair = getPair(str, i)
if (pair == null) {
cnt++
} else {
if (cnt == 4) {
val left = addLeft(str, i - 1, pair.first)
val leftAddedSize = left.length - str.length
val right = addRight(left, i + pair.size(), pair.second)
return right.substring(0, i + leftAddedSize) + "0" + right.substring(i + pair.size() + leftAddedSize)
}
cnt++
}
} else if (str[i] == ']') {
cnt--
}
i++
}
return null
}
fun split(str: String): String? {
var i = 0
while (i < str.length) {
if (str[i].isDigit() && str[i + 1].isDigit()) {
val num = (str[i].toString() + str[i + 1].toString()).toInt()
val left = floor(num.toDouble() / 2).toInt()
val right = ceil(num.toDouble() / 2).toInt()
val pair = Pair(left, right)
return str.substring(0, i) + pair.toStringPair() + str.substring(i + 2)
}
i++
}
return null
}
fun magnitude(str: String): BigInteger {
var newStr = str
while (true) {
var i = 0
while (i < newStr.length) {
if (newStr[i] == '[') {
val pair = getPair(newStr, i)
if (pair != null) {
newStr = newStr.substring(0, i) + pair.magnitude() + newStr.substring(i + pair.size())
break
}
}
i++
}
if (newStr.count { it == '[' } == 0 && newStr.count { it == ']' } == 0) {
return newStr.parseNumbersToSingleBigInteger()
}
}
}
fun reduce(str: String): String {
var r = str
while (true) {
val e = explode(r)
if (e != null) {
r = e
continue
}
val s = split(r)
if (s != null) {
r = s
continue
}
return r
}
}
override fun part1(): Number? {
var q = input[0]
for (a in input.subList(1, input.size)) {
q = "[$q,$a]"
q = reduce(q)
}
return magnitude(q)
}
override fun part2(): Number? {
return input.maxValueOfTwoElements { a, b ->
val q = "[$a,$b]"
val r = reduce(q)
magnitude(r)
}
}
}
| 0 | Kotlin | 0 | 0 | cc72684e862a782fad78b8ef0d1929b21300ced8 | 5,689 | adventofcode2021 | The Unlicense |
day12/src/main/kotlin/com/nohex/aoc/day12/CaveMap.kt | mnohe | 433,396,563 | false | {"Kotlin": 105740} | package com.nohex.aoc.day12
const val START_NAME = "start"
const val END_NAME = "end"
class CaveMap(input: Sequence<String>) {
val pathCount: Int
get() = getPaths { path, cave -> path.canVisit(cave) }.count()
val longPathCount: Int
get() = getPaths { path, cave -> path.canVisitTwice(cave) }.count()
private val caves: Set<Cave>
init {
// Use a dictionary at build time for speed.
val tempPlaces = mutableMapOf<String, Cave>()
// Each line in the input is a path between two vertices.
for (line in input) {
val (placeAName, placeBName) = line.split("-")
// Retrieve or create the nodes.
val caveA = tempPlaces[placeAName] ?: Cave(placeAName)
val caveB = tempPlaces[placeBName] ?: Cave(placeBName)
// Link both places.
caveA.connectTo(caveB)
// Make sure the new places are in the dictionary.
tempPlaces[placeAName] = caveA
tempPlaces[placeBName] = caveB
}
caves = tempPlaces.values.toSet()
}
/**
* Get all paths from the start cave.
*/
private fun getPaths(visitableCondition: (Path, Cave) -> Boolean): List<Path> =
caves.find { it.isStart }?.let {
followPaths(it, Path(), visitableCondition)
} ?: emptyList()
/**
* Returns a list of all paths to [cave]'s connections.
*/
private fun followPaths(
cave: Cave,
path: Path,
visitableCondition: (Path, Cave) -> Boolean
): List<Path> {
// Add the current place to the path.
val currentPath = Path(path.caves + cave)
// When there are no more connections, return the path so far.
if (cave.connections.isEmpty())
return listOf(currentPath)
// Otherwise, explore the connections.
return cave.connections
// Follow all visitable paths from this place.
.filter { visitableCondition(path, cave) }
// Create a new path for each connection.
.flatMap { followPaths(it, currentPath, visitableCondition) }
}
}
| 0 | Kotlin | 0 | 0 | 4d7363c00252b5668c7e3002bb5d75145af91c23 | 2,150 | advent_of_code_2021 | MIT License |
src/groundWar/ObjectiveFunctions.kt | hopshackle | 225,904,074 | false | null | package groundWar
import kotlin.math.ln
fun compositeScoreFunction(functions: List<(LandCombatGame, Int) -> Double>): (LandCombatGame, Int) -> Double {
return { game: LandCombatGame, player: Int ->
functions.map { f -> f(game, player) }.sum()
}
}
val interimScoreFunction = simpleScoreFunction(5.0, 1.0, -5.0, -0.5)
val finalScoreFunction = simpleScoreFunction(5.0, 1.0, -5.0, -1.0)
val hasMaterialAdvantage: (LandCombatGame, Int) -> Boolean = { game: LandCombatGame, player: Int ->
finalScoreFunction(game, player) > finalScoreFunction(game, 1 - player)
}
fun allFortsConquered(player: PlayerId): (LandCombatGame) -> Boolean = { game: LandCombatGame ->
game.world.cities.filter(City::fort).all { it.owner == player }
}
fun allTargetsConquered(player: PlayerId, targets: Map<String, Double>): (LandCombatGame) -> Boolean = { game: LandCombatGame ->
game.world.cities.filter { it.name in targets }.all { it.owner == player }
}
fun stringToScoreFunction(stringRep: String?, targetMap: Map<String, Double> = emptyMap()): (LandCombatGame, Int) -> Double {
val scoreString = stringRep ?: "SC=5|-5|1|-1"
var sp = scoreString.split(Regex("[=|]")).filterNot { it.startsWith("SC") }.map { it.toDouble() }
sp = sp + (sp.size until 9).map { 0.00 }
var scoreComponents = mutableListOf(simpleScoreFunction(sp[0], sp[2], sp[1], sp[3]))
if (sp.subList(4, 6).any { it != 0.00 })
scoreComponents.add(visibilityScore(sp[4], sp[5]))
if (sp.subList(6, 7).any { it != 0.00 })
scoreComponents.add(fortressScore(sp[6]))
if (sp.subList(7, 8).any { it != 0.00 })
scoreComponents.add(entropyScoreFunction(sp[7]))
if (sp.subList(8, 9).any { it != 0.00 })
scoreComponents.add(localAdvantageScoreFunction(sp[8]))
if (targetMap.isNotEmpty())
scoreComponents.add(specificTargetScoreFunction(targetMap))
return compositeScoreFunction(scoreComponents)
}
fun simpleScoreFunction(ourCityValue: Double, ourForceValue: Double, theirCityValue: Double, theirForceValue: Double): (LandCombatGame, Int) -> Double {
return { game: LandCombatGame, player: Int ->
val playerId = numberToPlayerID(player)
with(game.world) {
val ourCities = cities.count { c -> c.owner == playerId }
val theirCities = cities.count { c -> c.owner == if (playerId == PlayerId.Blue) PlayerId.Red else PlayerId.Blue }
// then add the total of all forces
val ourForces = cities.filter { c -> c.owner == playerId }.sumByDouble { it.pop.size } +
currentTransits.filter { t -> t.playerId == playerId }.sumByDouble { it.force.effectiveSize }
val enemyForces = cities.filter { c -> c.owner != playerId }.sumByDouble { it.pop.size } +
currentTransits.filter { t -> t.playerId != playerId }.sumByDouble { it.force.effectiveSize }
ourCityValue * ourCities + ourForceValue * ourForces + theirCityValue * theirCities + theirForceValue * enemyForces
}
}
}
fun fortressScore(fortressValue: Double): (LandCombatGame, Int) -> Double {
return { game: LandCombatGame, player: Int ->
val playerId = numberToPlayerID(player)
game.world.cities.count { c -> c.fort && c.owner == playerId } * fortressValue
}
}
fun specificTargetScoreFunction(targetValues: Map<String, Double>): (LandCombatGame, Int) -> Double {
return { game: LandCombatGame, player: Int ->
val playerColour = numberToPlayerID(player)
with(game.world) {
targetValues
.filter { (name, _) -> cities.find { it.name == name }?.owner == playerColour }
.map { (_, value) -> value }
.sum()
}
}
}
fun visibilityScore(nodeValue: Double = 5.0, arcValue: Double = 2.0): (LandCombatGame, Int) -> Double {
return { game: LandCombatGame, player: Int ->
val playerColour = numberToPlayerID(player)
with(game.world) {
val citiesVisible = (cities.indices).count { checkVisible(it, playerColour) }
val arcsVisible = routes.count { checkVisible(it, playerColour) }
citiesVisible * nodeValue + arcsVisible / 2.0 * arcValue
}
}
}
fun entropyScoreFunction(coefficient: Double): (LandCombatGame, Int) -> Double {
return { game: LandCombatGame, player: Int ->
val playerColour = numberToPlayerID(player)
with(game.world) {
val distinctForces = (cities.filter { it.owner == playerColour }.map { it.pop.size } +
currentTransits.filter { it.playerId == playerColour }.map { it.force.size })
.filter { it > 0.05 }
val total = distinctForces.sum()
val distribution = distinctForces.map { it / total }
coefficient * distribution.map { -it * ln(it) }.sum()
}
}
}
fun localAdvantageScoreFunction(coefficient: Double): (LandCombatGame, Int) -> Double {
return { game: LandCombatGame, player: Int ->
val playerColour = numberToPlayerID(player)
with(game.world) {
cities.withIndex()
.filter { it.value.owner == playerColour }
.flatMap { allRoutesFromCity[it.index]?.map { r -> Pair(r.fromCity, r.toCity) } ?: emptyList() }
.filterNot { (_, toCity) -> cities[toCity].owner == playerColour }
.map { (fromCity, toCity) -> Pair(cities[fromCity].pop.size, cities[toCity].pop.size) }
.map { it.first - it.second }.sum() * coefficient
}
}
} | 0 | Kotlin | 0 | 0 | e5992d6b535b3f4a6552bf6f2351865a33d56248 | 5,610 | SmarterSims | MIT License |
Retos/Reto #19 - ANÁLISIS DE TEXTO [Media]/kotlin/malopezrom.kt | mouredev | 581,049,695 | false | {"Python": 3866914, "JavaScript": 1514237, "Java": 1272062, "C#": 770734, "Kotlin": 533094, "TypeScript": 457043, "Rust": 356917, "PHP": 281430, "Go": 243918, "Jupyter Notebook": 221090, "Swift": 216751, "C": 210761, "C++": 164758, "Dart": 159755, "Ruby": 70259, "Perl": 52923, "VBScript": 49663, "HTML": 45912, "Raku": 44139, "Scala": 30892, "Shell": 27625, "R": 19771, "Lua": 16625, "COBOL": 15467, "PowerShell": 14611, "Common Lisp": 12715, "F#": 12710, "Pascal": 12673, "Haskell": 11051, "Assembly": 10368, "Elixir": 9033, "Visual Basic .NET": 7350, "Groovy": 7331, "PLpgSQL": 6742, "Clojure": 6227, "TSQL": 5744, "Zig": 5594, "Objective-C": 5413, "Apex": 4662, "ActionScript": 3778, "Batchfile": 3608, "OCaml": 3407, "Ada": 3349, "ABAP": 2631, "Erlang": 2460, "BASIC": 2340, "D": 2243, "Awk": 2203, "CoffeeScript": 2199, "Vim Script": 2158, "Brainfuck": 1550, "Prolog": 1342, "Crystal": 783, "Fortran": 778, "Solidity": 560, "Standard ML": 525, "Scheme": 457, "Vala": 454, "Limbo": 356, "xBase": 346, "Jasmin": 285, "Eiffel": 256, "GDScript": 252, "Witcher Script": 228, "Julia": 224, "MATLAB": 193, "Forth": 177, "Mercury": 175, "Befunge": 173, "Ballerina": 160, "Smalltalk": 130, "Modula-2": 129, "Rebol": 127, "NewLisp": 124, "Haxe": 112, "HolyC": 110, "GLSL": 106, "CWeb": 105, "AL": 102, "Fantom": 97, "Alloy": 93, "Cool": 93, "AppleScript": 85, "Ceylon": 81, "Idris": 80, "Dylan": 70, "Agda": 69, "Pony": 69, "Pawn": 65, "Elm": 61, "Red": 61, "Grace": 59, "Mathematica": 58, "Lasso": 57, "Genie": 42, "LOLCODE": 40, "Nim": 38, "V": 38, "Chapel": 34, "Ioke": 32, "Racket": 28, "LiveScript": 25, "Self": 24, "Hy": 22, "Arc": 21, "Nit": 21, "Boo": 19, "Tcl": 17, "Turing": 17} | /*
* Crea un programa que analice texto y obtenga:
* - Número total de palabras.
* - Longitud media de las palabras.
* - Número de oraciones del texto (cada vez que aparecen un punto).
* - Encuentre la palabra más larga.
*
* Todo esto utilizando un único bucle.
*/
fun main(){
val text ="""
la luna asoma: <NAME>orca
cuando sale la luna
se pierden las campanas
y aparecen las sendas
impenetrables.
cuando sale la luna,
el mar cubre la tierra
y el corazón se siente
isla en el infinito.
nadie come naranjas
bajo la luna llena.
es preciso comer
fruta verde y helada.
cuando sale la luna
de cien rostros iguales,
la moneda de plata
solloza en el bolsillo.
""".trimIndent()
analizeText(text)
}
/**
* Función que analiza un texto y obtiene:
* - Número total de palabras.
* - Longitud media de las palabras.
* - Número de oraciones del texto (cada vez que aparecen un punto).
* - Palabra más larga.
*/
fun analizeText(text:String){
val wordsRegex = Regex("\\p{L}+[\\p{L}',@!.-]*")
val sentenceRegex = Regex("\\p{L}+[\\p{L}',@!.-]*\\.+\$")
val words = text.replace("\n"," ").split(" ")
var sentences =0
var longestWord= ""
var length=0
var size = 0
words.forEach {
if(wordsRegex.matches(it)){
size++
if(sentenceRegex.matches(it)){
sentences++
}
}
length += it.length
if(it.length > longestWord.length){
longestWord= it
}
}
val averageLength = length/size
println("Total de palabras: ${size}")
println("Longitud media: $averageLength")
println("Numero de frases: $sentences")
println("Palabra mas larga: $longestWord(${longestWord.length})")
}
| 4 | Python | 2,929 | 4,661 | adcec568ef7944fae3dcbb40c79dbfb8ef1f633c | 2,140 | retos-programacion-2023 | Apache License 2.0 |
src/Day01.kt | mr3y-the-programmer | 572,001,640 | false | {"Kotlin": 8306} | fun main() {
fun part1(input: List<String>): Int? {
return input
.split { line -> line.isBlank() }
.maxOfOrNull { elfCalories -> elfCalories.sumOf { it.toInt() } }
}
fun part2(input: List<String>): Int {
return input
.split { line -> line.isBlank() }
.map { elfCalories -> elfCalories.sumOf { it.toInt() } }
.sortedDescending()
.take(3)
.sum()
}
println(part1(readInput("Day01_input")))
println(part2(readInput("Day01_input")))
}
private fun List<String>.split(predicate: (String) -> Boolean): List<List<String>> {
val transformed = mutableListOf<List<String>>()
var temp = mutableListOf<String>()
forEach {
if (!predicate(it)) {
temp.add(it)
} else {
transformed.add(temp)
temp = mutableListOf()
}
}
return transformed
}
| 0 | Kotlin | 0 | 0 | 96d1567f38e324aca0cb692be3dae720728a383d | 929 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/days/aoc2023/Day3.kt | bjdupuis | 435,570,912 | false | {"Kotlin": 537037} | package days.aoc2023
import days.Day
import util.Point2d
import java.awt.Point
class Day3 : Day(2023, 3) {
override fun partOne(): Any {
return calculatePartOne(inputList)
}
fun calculatePartOne(inputList: List<String>): Int {
var sum = 0
var currentNumber = StringBuilder()
var isPartNumber = false
val processNumber = {
if (currentNumber.isNotBlank()) {
if (isPartNumber) {
sum += currentNumber.toString().toInt()
}
currentNumber.clear()
isPartNumber = false
}
}
inputList.forEachIndexed { y, line ->
line.forEachIndexed { x, c ->
when (c) {
in '0'..'9' -> {
currentNumber.append(c)
Point2d(x, y).allNeighbors().filter { it.isWithin(inputList) }.forEach {
val currentChar = inputList[it.y][it.x]
if (!currentChar.isDigit() && currentChar != '.') {
isPartNumber = true
}
}
}
else -> processNumber.invoke()
}
}
processNumber.invoke()
}
return sum
}
override fun partTwo(): Any {
return calculatePartTwo(inputList)
}
fun calculatePartTwo(inputList: List<String>): Int {
var sum = 0
inputList.forEachIndexed { y, line ->
line.forEachIndexed { x, c ->
if (!c.isDigit() && c != '.') {
val potentialGear = Point2d(x, y)
val digitNeighbors = potentialGear.allNeighbors()
.filter { it.isWithin(inputList) && inputList[it.y][it.x].isDigit() }
val adjacentPartNumbers = adjacentPartNumberPositions(potentialGear, digitNeighbors)
if (adjacentPartNumbers.count() == 2) {
sum += adjacentPartNumbers.fold(1) { acc, neighbor -> acc * partNumberFromPosition(neighbor, inputList) }
}
}
}
}
return sum
}
private fun partNumberFromPosition(point: Point2d, inputList: List<String>): Int {
// we just know that we're somewhere in a number. Find the beginning
var beginning = point
var done = false
do {
val before = beginning.copy(x = beginning.x - 1)
if (before.isWithin(inputList) && inputList[before.y][before.x].isDigit()) {
beginning = before
} else {
done = true
}
} while (!done)
val currentNumber = StringBuilder()
var current = beginning
while(current.isWithin(inputList) && inputList[current.y][current.x].isDigit()) {
currentNumber.append(inputList[current.y][current.x])
current = current.copy(x = current.x + 1)
}
return currentNumber.toString().toInt()
}
private fun adjacentPartNumberPositions(point: Point2d, pointsWithDigits: List<Point2d>): List<Point2d> {
val distinct = { points: List<Point2d> ->
// check for the case where there are two part numbers, meaning the center element
// is not a digit. If the center position is a digit then it is part of a single part
// number.
if (points.count() == 2) {
if (points.map { it.x }.contains(point.x)) {
listOf(points.first())
} else {
points
}
} else if (points.isNotEmpty()){
listOf(points.first())
} else {
emptyList()
}
}
val above = pointsWithDigits.filter { it.y == point.y - 1 }
val below = pointsWithDigits.filter { it.y == point.y + 1 }
val beside = pointsWithDigits.filter { it.y == point.y }
return beside + distinct(above) + distinct(below)
}
}
| 0 | Kotlin | 0 | 1 | c692fb71811055c79d53f9b510fe58a6153a1397 | 4,140 | Advent-Of-Code | Creative Commons Zero v1.0 Universal |
src/day02/Day02.kt | martindacos | 572,700,466 | false | {"Kotlin": 12412} | package day02
import readInput
fun main() {
fun part1(input: List<String>): Int {
var points = 0
val plays = input.map { play -> play.split(" ") }
for (play in plays) {
val myPoints = when (play.get(1)) {
"X" -> 1
"Y" -> 2
"Z" -> 3
else -> throw Exception("Error")
}
points += myPoints
val playPoints = when (play) {
listOf("A", "X") -> 3
listOf("A", "Y") -> 6
listOf("A", "Z") -> 0
listOf("B", "X") -> 0
listOf("B", "Y") -> 3
listOf("B", "Z") -> 6
listOf("C", "X") -> 6
listOf("C", "Y") -> 0
listOf("C", "Z") -> 3
else -> throw Exception("Error")
}
points += playPoints
}
return points
}
fun part2(input: List<String>): Int {
var points = 0
val plays = input.map { play -> play.split(" ") }
for (play in plays) {
//println(play)
val myPoints = when (play.get(1)) {
"X" -> 0
"Y" -> 3
"Z" -> 6
else -> throw Exception("Error")
}
points += myPoints
val playPoints = when (play) {
listOf("A", "X") -> 3
listOf("A", "Y") -> 1
listOf("A", "Z") -> 2
listOf("B", "X") -> 1
listOf("B", "Y") -> 2
listOf("B", "Z") -> 3
listOf("C", "X") -> 2
listOf("C", "Y") -> 3
listOf("C", "Z") -> 1
else -> throw Exception("Error")
}
points += playPoints
}
return points
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("/day02/Day02_test")
check(part1(testInput) == 15)
check(part2(testInput) == 12)
val input = readInput("/day02/Day02")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | f288750fccf5fbc41e8ac03598aab6a2b2f6d58a | 2,156 | 2022-advent-of-code-kotlin | Apache License 2.0 |
codeforces/kotlinheroes3/g.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.kotlinheroes3
private val digits = 1..9
fun main() {
val (m, kIn) = readInts()
listOf(2, 3, 5, 7).fold(m) { acc, p ->
var temp = acc
while (temp % p == 0) temp /= p
temp
}.takeIf { it == 1 } ?: return println(-1)
val memo = mutableMapOf<Pair<Int, Int>, Long>()
fun count(m: Int, len: Int): Long {
if (len == 0) return if (m == 1) 1 else 0
val pair = m to len
memo[pair]?.let { return it }
val res = digits.filter { m % it == 0 }.map { count(m / it, len - 1) }.sum()
memo[pair] = res
return res
}
var k = kIn - 1L
val len = (1..m + kIn).first { len ->
val here = count(m, len)
if (k >= here) {
k -= here
false
} else true
}
var mm = m
val ans = List(len) { i ->
for (d in digits.filter { mm % it == 0 }) {
val here = count(mm / d, len - 1 - i)
if (k >= here) {
k -= here
continue
}
mm /= d
return@List d
}
}
return println(ans.joinToString(""))
}
private fun readLn() = readLine()!!
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,083 | competitions | The Unlicense |
src/main/kotlin/dev/shtanko/algorithms/leetcode/MaximumErasureValue.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.max
/**
* Maximum Erasure Value
* @see <a href="https://leetcode.com/problems/maximum-erasure-value/">Source</a>
*/
fun interface MaximumErasureValue {
fun maximumUniqueSubarray(nums: IntArray): Int
}
/**
* Approach 1: Brute Force
*/
class MEVBruteForce : MaximumErasureValue {
override fun maximumUniqueSubarray(nums: IntArray): Int {
val n: Int = nums.size
var result = 0
val set: HashSet<Int> = HashSet()
for (start in 0 until n) {
// reset set and current sum for next subarray
set.clear()
var currentSum = 0
var end = start
while (end < n && !set.contains(nums[end])) {
currentSum += nums[end]
set.add(nums[end])
end++
}
// update result with maximum sum found so far
result = max(result, currentSum)
}
return result
}
}
/**
* Approach 2: Two Pointer Approach Using Set
*/
class MEVTwoPointerSet : MaximumErasureValue {
override fun maximumUniqueSubarray(nums: IntArray): Int {
var result = 0
var currentSum = 0
val set = HashSet<Int>()
var start = 0
for (end in nums.indices) {
// increment start until subarray has unique elements
while (set.contains(nums[end])) {
set.remove(nums[start])
currentSum -= nums[start]
start++
}
currentSum += nums[end]
set.add(nums[end])
// update result with maximum sum found so far
result = max(result, currentSum)
}
return result
}
}
/**
* Approach 3: Two Pointer Approach Using Boolean Array
*/
class MEVTwoPointerBooleanArray : MaximumErasureValue {
override fun maximumUniqueSubarray(nums: IntArray): Int {
var result = 0
var currentSum = 0
val isPresent = BooleanArray(ARRAY_SIZE)
var start = 0
for (end in nums.indices) {
// increment start until subarray has unique elements
while (isPresent[nums[end]]) {
isPresent[nums[start]] = false
currentSum -= nums[start]
start++
}
isPresent[nums[end]] = true
currentSum += nums[end]
// update result with maximum sum found so far
result = max(result, currentSum)
}
return result
}
companion object {
private const val ARRAY_SIZE = 10001
}
}
/**
* Approach 4: Two Pointer Approach Using Count Map
*/
class MEVTwoPointerCountMap : MaximumErasureValue {
override fun maximumUniqueSubarray(nums: IntArray): Int {
val countMap = IntArray(ARRAY_SIZE)
var start = 0
var result = 0
var currentSum = 0
for (end in nums.indices) {
val currentElement = nums[end]
countMap[currentElement]++
currentSum += currentElement
while (start < end && countMap[currentElement] > 1) {
countMap[nums[start]]--
currentSum -= nums[start]
start++
}
// update result with maximum sum found so far
result = max(result, currentSum)
}
return result
}
companion object {
private const val ARRAY_SIZE = 10001
}
}
/**
* Approach 5: Using Prefix Sum with HashMap
*/
class MEVPrefixSum : MaximumErasureValue {
override fun maximumUniqueSubarray(nums: IntArray): Int {
val n: Int = nums.size
val lastIndexMap = HashMap<Int, Int>()
val prefixSum = IntArray(n + 1)
var result = 0
var start = 0
for (end in 0 until n) {
val currentElement = nums[end]
prefixSum[end + 1] = prefixSum[end] + currentElement
if (lastIndexMap.containsKey(currentElement)) {
start = max(start, lastIndexMap[currentElement]!! + 1)
}
// update result with maximum sum found so far
result = max(result, prefixSum[end + 1] - prefixSum[start])
lastIndexMap[currentElement] = end
}
return result
}
}
/**
* Approach 6: Using Prefix Sum with Count Array
*/
class MEVPrefixSumCountArray : MaximumErasureValue {
override fun maximumUniqueSubarray(nums: IntArray): Int {
val n: Int = nums.size
val lastIndexes = IntArray(ARRAY_SIZE) { -1 }
val prefixSum = IntArray(n + 1)
var result = 0
var start = 0
for (end in 0 until n) {
val currentElement = nums[end]
prefixSum[end + 1] = prefixSum[end] + currentElement
if (lastIndexes[currentElement] != -1) {
start = max(start, lastIndexes[currentElement] + 1)
}
// update result with maximum sum found so far
result = max(result, prefixSum[end + 1] - prefixSum[start])
// update last index of current element
lastIndexes[currentElement] = end
}
return result
}
companion object {
private const val ARRAY_SIZE = 10001
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 5,862 | kotlab | Apache License 2.0 |
src/main/kotlin/cc/stevenyin/algorithms/_02_sorts/_07_QuickSort_Partition2.kt | StevenYinKop | 269,945,740 | false | {"Kotlin": 107894, "Java": 9565} | package cc.stevenyin.algorithms._02_sorts
import cc.stevenyin.algorithms.RandomType
import cc.stevenyin.algorithms.swap
import cc.stevenyin.algorithms.testSortAlgorithm
class _07_QuickSort_Partition2 : SortAlgorithm {
override val name: String = "Quick Sort with Partition 2"
override fun <T : Comparable<T>> sort(array: Array<T>) {
quickSort(array, 0, array.size - 1)
}
private fun <T : Comparable<T>> quickSort(array: Array<T>, left: Int, right: Int) {
if (left >= right) return
val pivot = partition(array, left, right)
quickSort(array, left, pivot - 1)
quickSort(array, pivot + 1, right)
}
private fun <T: Comparable<T>> partition(array: Array<T>, left: Int, right: Int): Int {
// arr[l+1, i) <= pivotValue
var i = left + 1
// arr(j, r] >= pivotValue
var j = right
val pivotValue = array[left]
while (i <= j) {
while (i < right && array[i] < pivotValue) i ++
while (j > left + 1 && array[j] > pivotValue) j --
swap(array, i, j)
i ++
j --
println(array.contentToString())
}
swap(array, left, j)
return j
}
}
fun main() {
testSortAlgorithm(10, RandomType.CHAOS, _07_QuickSort_Partition2())
}
| 0 | Kotlin | 0 | 1 | 748812d291e5c2df64c8620c96189403b19e12dd | 1,317 | kotlin-demo-code | MIT License |
app/src/main/java/com/kvl/cyclotrack/Statistics.kt | kevinvanleer | 311,970,003 | false | {"Kotlin": 902772, "JavaScript": 20979, "MDX": 5247, "CSS": 3042, "HTML": 2474} | package com.kvl.cyclotrack
import kotlin.math.pow
fun List<Double>.average(): Double =
this.reduce { acc, d -> acc + d } / this.size
fun average(newValue: Double, sampleSize: Int, lastAverage: Double): Double =
(lastAverage * (sampleSize - 1) + newValue) / sampleSize
fun List<Double>.sampleVariance(): Double {
val avg = this.average()
return this.fold(0.0, { acc, d -> acc + (d - avg).pow(2.0) }) / (this.size - 1)
}
fun sampleVariance(
newValue: Double,
oldVariance: Double,
sampleSize: Int,
oldAverage: Double,
): Double {
return (oldVariance * (sampleSize - 2) / (sampleSize - 1)) + ((newValue - oldAverage).pow(
2.0) / sampleSize)
}
fun List<Double>.populationVariance(): Double {
val avg = this.average()
return this.fold(0.0, { acc, d -> acc + (d - avg).pow(2.0) }) / this.size
}
fun exponentialSmoothing(alpha: Double, current: Double, last: Double) =
(alpha * current) + ((1 - alpha) * last)
fun doubleExponentialSmoothing(
alpha: Double,
current: Double,
smoothLast: Double,
trendLast: Double,
) =
alpha * current + ((1 - alpha) * (smoothLast + trendLast))
fun doubleExponentialSmoothingTrend(
beta: Double,
smooth: Double,
smoothLast: Double,
trendLast: Double,
) =
beta * (smooth - smoothLast) + (1 - beta) * trendLast
fun smooth(alpha: Double, data: Array<Pair<Double, Double>>): List<Pair<Double, Double>> {
var smoothedFirst = data[0].first
var smoothedSecond = data[0].second
return data.map { datum ->
smoothedFirst = exponentialSmoothing(alpha, datum.first, smoothedFirst)
smoothedSecond = exponentialSmoothing(alpha, datum.second, smoothedSecond)
Pair(smoothedFirst, smoothedSecond)
}
}
fun doubleSmooth(alpha: Double, beta: Double, data: Array<Double>): List<Double> {
var smoothed: Double = data[0]
var trend: Double = data[1] - data[0]
var smoothedLast = smoothed
return data.map { datum ->
smoothed = doubleExponentialSmoothing(alpha, datum, smoothedLast, trend)
trend = doubleExponentialSmoothingTrend(beta, smoothed, smoothedLast, trend)
smoothedLast = smoothed
smoothed
}
}
fun isRangeGreaterThan(left: Pair<Double, Double>, right: Double): Boolean {
val leftRange = Pair(left.first - left.second, left.first + left.second)
return leftRange.first > right
}
fun isRangeLessThan(left: Pair<Double, Double>, right: Double): Boolean {
val leftRange = Pair(left.first - left.second, left.first + left.second)
return leftRange.second < right
}
fun isRangeGreaterThan(left: Pair<Double, Double>, right: Pair<Double, Double>): Boolean {
val leftRange = Pair(left.first - left.second, left.first + left.second)
val rightRange = Pair(right.first - right.second, right.first + right.second)
return leftRange.first > rightRange.second
}
fun isRangeLessThan(left: Pair<Double, Double>, right: Pair<Double, Double>): Boolean {
val leftRange = Pair(left.first - left.second, left.first + left.second)
val rightRange = Pair(right.first - right.second, right.first + right.second)
return leftRange.second < rightRange.first
}
fun leastSquaresFitSlope(data: List<Pair<Double, Double>>): Double {
//https://stats.libretexts.org/Bookshelves/Introductory_Statistics/Book%3A_Introductory_Statistics_(Shafer_and_Zhang)/10%3A_Correlation_and_Regression/10.04%3A_The_Least_Squares_Regression_Line
var sumx = 0.0
var sumy = 0.0
var sumxsq = 0.0
var sumxy = 0.0
data.forEach {
sumx += it.first
sumy += it.second
sumxsq += it.first * it.first
sumxy += it.first * it.second
}
val ssxy = sumxy - ((1.0 / data.size) * sumx * sumy)
val ssxx = sumxsq - ((1.0 / data.size) * sumx * sumx)
return ssxy / ssxx
}
fun accumulateAscentDescent(elevationData: List<Pair<Double, Double>>): Pair<Double, Double> {
var totalAscent = 0.0
var totalDescent = 0.0
var altitudeCursor = elevationData[0]
elevationData.forEach { sample ->
if (isRangeGreaterThan(sample, altitudeCursor)) {
totalAscent += sample.first - altitudeCursor.first
altitudeCursor = sample
}
if (isRangeLessThan(sample, altitudeCursor)) {
totalDescent += sample.first - altitudeCursor.first
altitudeCursor = sample
}
}
return Pair(totalAscent, totalDescent)
} | 0 | Kotlin | 0 | 6 | c936057abdd328ae184e9f580963c8aff102338a | 4,435 | cyclotrack | The Unlicense |
kotlin/2021/qualification-round/cheating-detection/src/main/kotlin/AnalysisSolution.kts | ShreckYe | 345,946,821 | false | null | import kotlin.math.absoluteValue
import kotlin.math.exp
import kotlin.math.ln
fun main() {
val t = readLine()!!.toInt()
val p = readLine()!!.toInt()
repeat(t, ::testCase)
}
val numHalfExtremeQuestions = 500
fun testCase(ti: Int) {
val results = List(100) {
readLine()!!.map { it - '0' }
}
// simple estimation by averaging
val ss = results.map { inverseSigmoid(it.average()).coerceIn(-3.0, 3.0) }
val qs = (0 until 10000).map { j ->
inverseSigmoid(results.asSequence().map { it[j] }.average()).coerceIn(-3.0, 3.0)
}
val sortedIndexedQs = qs.asSequence().withIndex().sortedByDescending { it.index }.toList()
val extremeIndexedQs =
sortedIndexedQs.take(numHalfExtremeQuestions) + sortedIndexedQs.takeLast(numHalfExtremeQuestions)
val extremeQs = extremeIndexedQs.map { it.value }
val extremeRss = results.map { rs -> extremeIndexedQs.map { rs[it.index] } }
// the difference between expected number of correct answers and actual
val diffs = (ss zip extremeRss).asSequence().map { (s, extremeRs) ->
assert(extremeRs.size == extremeQs.size)
(extremeRs zip extremeQs).sumOf { (r, q) -> sigmoid(s - q) - r }.absoluteValue
//(extremeRs zip extremeQs).sumOf { (r, q) -> (sigmoid(s - q).also(::println) - r.also(::println)).also { println(it);println() } }.absoluteValue
}
println(diffs.withIndex().joinToString("\n"))
val y = diffs.withIndex().maxByOrNull { it.value }!!.index
println("Case #${ti + 1}: ${y + 1}")
}
fun sigmoid(x: Double) =
1 / (1 + exp(-x))
fun inverseSigmoid(y: Double) =
ln(y / (1 - y)) | 0 | Kotlin | 1 | 1 | 743540a46ec157a6f2ddb4de806a69e5126f10ad | 1,641 | google-code-jam | MIT License |
gcj/y2023/farewell_d/e_to_upsolve.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package gcj.y2023.farewell_d
import kotlin.random.Random
fun generate(n: Int, m: Int): MutableList<Pair<Int, Int>> {
var toAdd = m
val list = mutableListOf<Pair<Int, Int>>()
fun addEdge(v: Int, u: Int) {
toAdd--
list.add(v to u)
}
for (i in 0 until n) {
addEdge(i, (i + 1) % n)
}
for (i in 2 until n) {
// val canAdd = i - 1
// if (canAdd >= toAdd) {
// for (j in 0..i - 2) addEdge(i, j)
// continue
// }
for (j in i - 2 downTo 0) {
if (toAdd == 0) break
addEdge(i, j)
}
}
return list
}
private fun solve(nei: List<MutableList<Int>>): MutableList<Int> {
val n = nei.size
val s = nei.indices.minBy { nei[it].size }
val used = BooleanArray(n)
val path = mutableListOf(s)
used[s] = true
fun grow() {
while (nei[path.last()].size == 2) {
val v = nei[path.last()].firstOrNull { !used[it] } ?: break
path.add(v)
used[v] = true
}
}
grow()
path.reverse()
grow()
fun grow2() {
while (path.size < n) {
val v = nei[path.last()].firstOrNull { !used[it] } ?: error("")
path.add(v)
used[v] = true
}
}
// if (nei[path.last()].size < nei[path.first()].size) path.reverse()
grow2()
// for (i in path.indices) if (!nei[path[i]].contains(path[(i + 1) % n])) {
// System.setOut(java.io.PrintStream("shit.txt"))
// println(nei)
// println(path)
// println()
// for (i in 0 until n) for (j in 0 until i) if (nei[i].contains(j)) println("${i + 1} ${j + 1}")
// System.out.flush()
// System.exit(1)
// }
return path
}
private fun solve() {
val (n, m) = readInts()
val generated = generate(n, m)
println(generated.joinToString("\n") { "${it.first + 1} ${it.second + 1}" })
val nei = List(n) { mutableListOf<Int>() }
fun addEdge(v: Int, u: Int) {
nei[v].add(u); nei[u].add(v)
}
repeat(m) {
val (u, v) = readInts().map { it - 1 }
addEdge(u, v)
}
val path = solve(nei)
println(path.map { it + 1 }.joinToString(" "))
}
fun main() {
repeat(readInt()) { solve() }
// research(6, 10, 10000)
// for (n in 3..20) for (m in n..n * (n - 1) / 2) research(n, m)
// for (n in 1000..1000) for (m in n..n+10) research(n, m)
}
fun research(n: Int, m: Int, times: Int = 100) {
val graph = generate(n, m)
repeat(times) {
val random = Random(it)
val p = (0 until n).toList().shuffled(random)
println("//" + p)
val nei = List(n) { mutableListOf<Int>() }
fun addEdge(v: Int, u: Int) {
nei[v].add(u); nei[u].add(v)
}
for (edge in graph) {
addEdge(p[edge.first], p[edge.second])
}
val path = solve(nei)
require(path.size == n)
require(path.toSet() == (0 until n).toSet())
for (i in path.indices) require(nei[path[i]].contains(path[(i + 1) % n]))
println(path.map { it + 1 }.joinToString(" "))
}
}
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 | 2,874 | competitions | The Unlicense |
src/Day09.kt | kmes055 | 577,555,032 | false | {"Kotlin": 35314} | import kotlin.math.abs
fun main() {
class Node(
var x: Int = 0,
var y: Int = 0
) {
override fun toString(): String {
return "($x, $y)"
}
fun move(direction: String) {
when (direction) {
"L" -> this.x -= 1
"R" -> this.x += 1
"D" -> this.y -= 1
"U" -> this.y += 1
}
}
infix fun adjust(other: Node): Boolean = abs(x - other.x) <= 1 && abs(y - other.y) <= 1
fun follow(other: Node) {
if (this adjust other) return
if (x != other.x) {
this.x += (other.x - x) / abs(other.x - x)
}
if (y != other.y) {
this.y += (other.y - y) / abs(other.y - y)
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Node
if (x != other.x) return false
if (y != other.y) return false
return true
}
override fun hashCode(): Int {
var result = x
result = 100000 * result + y
return result
}
}
fun proc(input: List<String>, nodeNum: Int): Int {
val posSet = mutableSetOf<Node>()
val nodes = mutableListOf<Node>()
repeat(nodeNum) { nodes.add(Node(0, 0)) }
posSet.add(nodes.last())
input.forEach { line ->
val direction = line.split(' ')[0]
val distance = line.split(' ')[1].toInt()
repeat(distance) {
nodes.first().move(direction)
nodes.drop(1).forEachIndexed { i, node -> node.follow(nodes[i]) }
posSet.add(nodes.last())
}
}
return posSet.size
}
fun part1(input: List<String>): Int {
return proc(input, 2)
}
fun part2(input: List<String>): Int {
return proc(input, 10)
}
val input = readInput("Day09")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 84c2107fd70305353d953e9d8ba86a1a3d12fe49 | 2,142 | advent-of-code-kotlin | Apache License 2.0 |
algorithms/src/main/kotlin/org/baichuan/sample/algorithms/leetcode/hard/NumberToWords.kt | scientificCommunity | 352,868,267 | false | {"Java": 154453, "Kotlin": 69817} | package org.baichuan.sample.algorithms.leetcode.hard
/**
* @author: tk (<EMAIL>)
* @date: 2022/1/10
* https://leetcode-cn.com/problems/english-int-lcci/
* 面试题 16.08. 整数的英语表示
*/
class NumberToWords {
fun numberToWords(num: Int): String {
val unit = arrayOf("Billion", "Million", "Thousand", "Hundred")
val numberOfUnit = arrayOf(1000000000L, 1000000L, 1000L, 100L)
val numberWord = arrayOf(
"One",
"Two",
"Three",
"Four",
"Five",
"Six",
"Seven",
"Eight",
"Nine",
"Ten",
"Eleven",
"Twelve",
"Thirteen",
"Fourteen",
"Fifteen",
"Sixteen",
"Seventeen",
"Eighteen",
"Nineteen",
"Twenty",
"Thirty",
"Forty",
"Fifty",
"Sixty",
"Seventy",
"Eighty",
"Ninety"
)
val numberOfWord =
arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 30, 40, 50, 60, 70, 80, 90)
/*var i = 0
var result = ""
var numVar = num
while (i < number.size) {
val l = numVar / number[i]
if (l > 0) {
result += findWord(l.toInt())
numVar -= (l * number[i]).toInt()
}
i++
}
return result*/
if (num == 0) {
return "Zero"
}
val result = findResult(num, numberOfUnit, unit, numberOfWord)
return result.substring(0, result.length - 1)
}
fun findResult(
num: Int,
numberOfUnit: Array<Long>,
unit: Array<String>,
numberOfWord: Array<Int>
): String {
var i = 0
var result = ""
var numVar = num
/**
* 100及以上的数通过除法进行单位(百、千)单词查找
* 100以下的数进行减法进行数量(具体数值)单词查找
*/
if (numVar >= 100) {
while (i < numberOfUnit.size) {
val l = numVar / numberOfUnit[i]
if (l > 0) {
result += findResult(l.toInt(), numberOfUnit, unit, numberOfWord) + unit[i] + " "
numVar -= (l * numberOfUnit[i]).toInt()
//如果有余数,且余数小于100则按照减法进行单词查找
if (numVar in 1..99) {
result += findResult(numVar, numberOfUnit, unit, numberOfWord)
}
}
i++
}
} else {
var j = numberOfWord.size - 1
while (j >= 0) {
val l = numVar - numberOfWord[j]
if (l >= 0) {
result += findWord(numberOfWord[j]) + findWord(l)
break
} else {
j--
}
}
}
return result
}
fun findWord(num: Int): String {
return when (num) {
1 -> "One "
2 -> "Two "
3 -> "Three "
4 -> "Four "
5 -> "Five "
6 -> "Six "
7 -> "Seven "
8 -> "Eight "
9 -> "Nine "
10 -> "Ten "
11 -> "Eleven "
12 -> "Twelve "
13 -> "Thirteen "
14 -> "Fourteen "
15 -> "Fifteen "
16 -> "Sixteen "
17 -> "Seventeen "
18 -> "Eighteen "
19 -> "Nineteen "
20 -> "Twenty "
30 -> "Thirty "
40 -> "Forty "
50 -> "Fifty "
60 -> "Sixty "
70 -> "Seventy "
80 -> "Eighty "
90 -> "Ninety "
else -> ""
}
}
}
fun main() {
println(NumberToWords().numberToWords(1234567891))
} | 1 | Java | 0 | 8 | 36e291c0135a06f3064e6ac0e573691ac70714b6 | 4,026 | blog-sample | Apache License 2.0 |
src/day10/Day10.kt | EdwinChang24 | 572,839,052 | false | {"Kotlin": 20838} | package day10
import readInput
import kotlin.math.absoluteValue
fun main() {
part1()
part2()
}
fun part1() = common { cycles -> println(listOf(20, 60, 100, 140, 180, 220).sumOf { cycles[it - 1] * it }) }
fun part2() = common { cycles ->
val image = mutableListOf<Char>()
cycles.forEachIndexed { index, i ->
image += if ((((index + 400) % 40) - ((i + 400) % 40)).absoluteValue <= 1) '#' else '.'
}
image.forEachIndexed { index, c -> if (index % 40 == 39) println(c) else print(c) }
}
fun common(andThen: (cycles: MutableList<Int>) -> Unit) {
val input = readInput(10)
val cycles = mutableListOf(1)
for (line in input) {
cycles += cycles.last()
if (line.split(' ')[0] == "addx") cycles += cycles.last() + line.split(' ')[1].toInt()
}
andThen(cycles)
}
| 0 | Kotlin | 0 | 0 | e9e187dff7f5aa342eb207dc2473610dd001add3 | 823 | advent-of-code-2022 | Apache License 2.0 |
year2020/src/main/kotlin/net/olegg/aoc/year2020/day23/Day23.kt | 0legg | 110,665,187 | false | {"Kotlin": 511989} | package net.olegg.aoc.year2020.day23
import net.olegg.aoc.someday.SomeDay
import net.olegg.aoc.year2020.DayOf2020
/**
* See [Year 2020, Day 23](https://adventofcode.com/2020/day/23)
*/
object Day23 : DayOf2020(23) {
override fun first(): Any? {
val items = data.map { it.digitToInt() }
val queue = ArrayDeque(items)
val min = items.min()
val max = items.max()
repeat(100) {
val head = queue.removeFirst()
val took = listOf(queue.removeFirst(), queue.removeFirst(), queue.removeFirst())
var next = head - 1
var position = queue.indexOf(next)
while (position == -1) {
next--
if (next < min) {
next = max
}
position = queue.indexOf(next)
}
took.forEachIndexed { index, value ->
queue.add(position + index + 1, value)
}
queue.addLast(head)
}
val pos1 = queue.indexOf(1)
val result = queue.drop(pos1 + 1) + queue.take(pos1)
return result.joinToString("")
}
override fun second(): Any? {
val initialItems = data.map { it.digitToInt() }
val items = initialItems + ((initialItems.max() + 1)..1_000_000).toList()
val min = items.min()
val max = items.max()
val all = List(1_000_000 + 1) { Item(it) }
val queue = items.map { all[it] }
queue.zipWithNext().forEach { (prev, next) ->
prev.next = next.value
}
queue.last().next = queue.first().value
var head = queue.first()
repeat(10_000_000) { _ ->
val took = (0..<3).scan(head) { acc, _ -> all[acc.next] }
val excluded = took.map { it.value }
var place = head.value - 1
while (place < min || place in excluded) {
place--
if (place < min) {
place = max
}
}
val broken = took[3].next
val insertion = all[place]
val next = insertion.next
insertion.next = took[1].value
took[3].next = next
head.next = broken
head = all[broken]
}
val first = all[all[1].next]
val second = all[first.next]
return first.value.toLong() * second.value.toLong()
}
data class Item(
val value: Int,
var next: Int = 0,
)
}
fun main() = SomeDay.mainify(Day23)
| 0 | Kotlin | 1 | 7 | e4a356079eb3a7f616f4c710fe1dfe781fc78b1a | 2,224 | adventofcode | MIT License |
src/day01/Day01.kt | ubuntudroid | 571,771,936 | false | {"Kotlin": 7845} | package day01
import ensureBlankLastItem
import readInput
fun main() {
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
fun part1(input: List<String>): Int = input
.ensureBlankLastItem()
.map { it.toIntOrNull() }
.fold(0 to 0) { (maxCals, elfCals), lineCals ->
if (lineCals == null) {
(elfCals.takeIf { it > maxCals } ?: maxCals) to 0
} else {
maxCals to elfCals + lineCals
}
}.first
fun part2(input: List<String>): Int = input
.ensureBlankLastItem()
.map { it.toIntOrNull() }
.fold(Triple(0, 0, 0) to 0) { (maxCals, elfCals), lineCals ->
if (lineCals == null) {
(if (elfCals >= maxCals.first) {
Triple(elfCals, maxCals.first, maxCals.second)
} else if (elfCals >= maxCals.second) {
Triple(maxCals.first, elfCals, maxCals.second)
} else if (elfCals >= maxCals.third) {
Triple(maxCals.first, maxCals.second, elfCals)
} else {
maxCals
}) to 0
} else {
maxCals to elfCals + lineCals
}
}.first.let {
it.first + it.second + it.third
} | 0 | Kotlin | 0 | 0 | fde55dcf7583aac6571c0f6fc2d323d235337c27 | 1,225 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/ca/voidstarzero/isbd/titlestatement/grammar/MonographTitle.kt | hzafar | 262,218,140 | false | null | package ca.voidstarzero.isbd.titlestatement.grammar
import ca.voidstarzero.isbd.titlestatement.ast.*
import norswap.autumn.DSL.rule
/**
* Matches a string of characters.
*
* Pushes the matched string as a [TitleProper] to the parser's value stack.
*/
val TitleStatementGrammar.titleProper: rule
get() = data
.push { items -> TitleProper(items[0] as String) }
/**
* Matches a title with as many parts as possible, including other
* title info, parallel title, parallel other title info, statements
* of responsibility, and parallel statements of responsibility.
*
* Pushes the result as a [Monograph] title to the parser's value stack.
*/
val TitleStatementGrammar.title: rule
get() = seq(
titleProper,
parallelTitleList.maybe(),
longest(
otherInfoList,
seq(otherInfoList, parallelDataList),
seq(otherInfoList, parallelTitleAndOtherInfo),
seq(otherInfoList, parallelTitleAndOtherInfoList)
).maybe()
).push { items ->
val titleProper = items[0] as TitleProper
val otherInfo = mutableListOf<OtherInfo>()
val parallelOtherInfo = mutableListOf<ParallelOtherInfo>()
val parallelTitles = mutableListOf<ParallelMonograph>()
items.flatMap {
when (it) {
is NodeList -> it.values
else -> listOf(it)
}
}.forEach {
when (it) {
is OtherInfo -> otherInfo.add(it)
is ParallelOtherInfo -> parallelOtherInfo.add(it)
is ParallelMonograph -> parallelTitles.add(it)
}
}
Monograph(
titleProper = titleProper, otherInfo = otherInfo,
parallelTitles = parallelTitles, parallelOtherInfo = parallelOtherInfo
)
}
/**
* Matches a sequence of full titles.
*/
val TitleStatementGrammar.titleList: rule
get() = seq(title).sep(1, semicolon)
/**
* Matches a full title statement.
*
* Pushes the result as a [TitleStatement] to the parser's value stack.
*/
val TitleStatementGrammar.titleStatement: rule
get() = seq(
titleList,
longest(
sorList,
seq(sorList, parallelDataList),
seq(sorList, parallelTitleFull)
).maybe()
).push { items ->
val titles = mutableListOf<Monograph>()
val sors = mutableListOf<SOR>()
val parallelTitles = mutableListOf<ParallelMonograph>()
val parallelSORs = mutableListOf<ParallelSOR>()
items.flatMap {
when (it) {
is NodeList -> it.values
else -> listOf(it)
}
}.forEach {
when (it) {
is Monograph -> titles.add(it)
is SOR -> sors.add(it)
is ParallelMonograph -> parallelTitles.add(it)
is ParallelSOR -> parallelSORs.add(it)
}
}
TitleStatement(titles, sors, parallelTitles, parallelSORs)
}
/**
* Matches a sequence of full title statements.
*/
val TitleStatementGrammar.titleStatementList: rule
get() = seq(titleStatement).sep(2, period)
/**
* The root parser for parsing monograph titles.
* Matches as many title statements as possible.
*/
val TitleStatementGrammar.monographRoot: rule
get() = longest(
titleStatement,
titleStatementList
) | 2 | Kotlin | 0 | 2 | 16bb26858722ca818c0a9f659be1cc9d3e4e7213 | 3,402 | isbd-parser | MIT License |
day22/Part2.kt | anthaas | 317,622,929 | false | null | import java.io.File
fun main(args: Array<String>) {
val input = File("input.txt").bufferedReader().use { it.readText() }.split("\n\n")
.map { it.split("\n").let { it.subList(1, it.size) }.map { it.toInt() } }
val decks = input[0].toMutableList() to input[1].toMutableList()
recursiveGame(decks)
val result =
decks.first.reversed().mapIndexed { index, l -> l.toLong() * (index + 1) }.sum() + decks.second.reversed()
.mapIndexed { index, l -> l.toLong() * (index + 1) }.sum()
println(result)
}
private fun recursiveGame(decks: Pair<MutableList<Int>, MutableList<Int>>): Boolean {
val previous = mutableListOf<Pair<List<Int>, List<Int>>>()
while (decks.first.isNotEmpty() && decks.second.isNotEmpty()) {
if (decks in previous) {
return true
}
previous.add(decks.first.toList() to decks.second.toList())
val p1 = decks.first.removeFirst()
val p2 = decks.second.removeFirst()
if (decks.first.size >= p1 && decks.second.size >= p2) {
val newDecks = decks.first.toMutableList().subList(0, p1) to decks.second.toMutableList().subList(0, p2)
if (recursiveGame(newDecks)) {
decks.first.add(p1)
decks.first.add(p2)
} else {
decks.second.add(p2)
decks.second.add(p1)
}
} else {
if (p1 > p2) {
decks.first.add(p1)
decks.first.add(p2)
} else {
decks.second.add(p2)
decks.second.add(p1)
}
}
}
return decks.first.size > decks.second.size
}
| 0 | Kotlin | 0 | 0 | aba452e0f6dd207e34d17b29e2c91ee21c1f3e41 | 1,683 | Advent-of-Code-2020 | MIT License |
src/Day01.kt | cvb941 | 572,639,732 | false | {"Kotlin": 24794} | fun main() {
fun part1(input: List<String>): Int {
var maxCalories = 0
var calorieSum = 0
input.forEach {
if (it.isEmpty()) {
maxCalories = maxOf(maxCalories, calorieSum)
calorieSum = 0
} else {
calorieSum += it.toInt()
}
}
return maxCalories
}
fun part2(input: List<String>): Int {
val caloriesList = mutableListOf<Int>()
var calorieSum = 0
input.forEach {
if (it.isEmpty()) {
caloriesList += calorieSum
calorieSum = 0
} else {
calorieSum += it.toInt()
}
}
return caloriesList.sortedDescending().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))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | fe145b3104535e8ce05d08f044cb2c54c8b17136 | 1,023 | aoc-2022-in-kotlin | Apache License 2.0 |
src/day8/Day08.kt | dinoolivo | 573,723,263 | false | null | package day8
import readInput
fun main() {
fun treeMatrix(input: List<String>): List<List<Int>> = input.map { row -> row.map { elem -> elem.digitToInt() } }
fun scenicScoreFromLeft(input: List<List<Int>>, rowIndex: Int, colIndex: Int): Int {
var leftIndex = colIndex - 1
while (leftIndex > 0 && input[rowIndex][colIndex] > input[rowIndex][leftIndex]) leftIndex--
val score = colIndex - leftIndex
return if (leftIndex < 0) score - 1 else score
}
fun isVisibleFromLeft(input: List<List<Int>>, rowIndex: Int, colIndex: Int): Boolean {
var leftIndex = colIndex - 1
while (leftIndex >= 0 && input[rowIndex][colIndex] > input[rowIndex][leftIndex]) leftIndex--
return leftIndex < 0
}
fun scenicScoreFromRight(input: List<List<Int>>, rowIndex: Int, colIndex: Int): Int {
var rightIndex = colIndex + 1
while (rightIndex < input.size && input[rowIndex][colIndex] > input[rowIndex][rightIndex]) rightIndex++
val score = rightIndex - colIndex
return if (rightIndex == input.size) score - 1 else score
}
fun isVisibleFromRight(input: List<List<Int>>, rowIndex: Int, colIndex: Int): Boolean {
var rightIndex = colIndex + 1
while (rightIndex < input.size && input[rowIndex][colIndex] > input[rowIndex][rightIndex]) rightIndex++
return rightIndex == input.size
}
fun scenicScoreFromTop(input: List<List<Int>>, rowIndex: Int, colIndex: Int): Int {
var topIndex = rowIndex - 1
while (topIndex > 0 && input[rowIndex][colIndex] > input[topIndex][colIndex]) topIndex--
val score = rowIndex - topIndex
return if (topIndex < 0) score - 1 else score
}
fun isVisibleFromTop(input: List<List<Int>>, rowIndex: Int, colIndex: Int): Boolean {
var topIndex = rowIndex - 1
while (topIndex >= 0 && input[rowIndex][colIndex] > input[topIndex][colIndex]) topIndex--
return topIndex < 0
}
fun scenicScoreFromBottom(input: List<List<Int>>, rowIndex: Int, colIndex: Int): Int {
var bottomIndex = rowIndex + 1
while (bottomIndex < input.size && input[rowIndex][colIndex] > input[bottomIndex][colIndex]) bottomIndex++
val score = bottomIndex - rowIndex
return if (bottomIndex == input.size) score - 1 else score
}
fun isVisibleFromBottom(input: List<List<Int>>, rowIndex: Int, colIndex: Int): Boolean {
var bottomIndex = rowIndex + 1
while (bottomIndex < input.size && input[rowIndex][colIndex] > input[bottomIndex][colIndex]) bottomIndex++
return bottomIndex == input.size
}
fun scenicScore(input: List<List<Int>>, rowIndex: Int, colIndex: Int): Int =
scenicScoreFromLeft(input, rowIndex, colIndex) * scenicScoreFromRight(input, rowIndex, colIndex) *
scenicScoreFromTop(input, rowIndex, colIndex) * scenicScoreFromBottom(input, rowIndex, colIndex)
fun isVisible(input: List<List<Int>>, rowIndex: Int, colIndex: Int): Boolean =
isVisibleFromLeft(input, rowIndex, colIndex) || isVisibleFromRight(input, rowIndex, colIndex) ||
isVisibleFromTop(input, rowIndex, colIndex) || isVisibleFromBottom(input, rowIndex, colIndex)
fun part1(input: List<List<Int>>): Int {
val squareSize = input.size
var visibleTrees = 4 * (squareSize - 1)
for (rowIndex in 1 until squareSize - 1) {
for (colIndex in 1 until squareSize - 1) {
if (isVisible(input, rowIndex, colIndex)) {
visibleTrees = visibleTrees.inc()
}
}
}
return visibleTrees
}
fun part2(input: List<List<Int>>): Int {
val squareSize = input.size
val scores = mutableListOf<Int>()
for (rowIndex in 1 until squareSize - 1) {
for (colIndex in 1 until squareSize - 1) {
val score = scenicScore(input, rowIndex, colIndex)
scores.add(score)
}
}
return scores.max()
}
val testInput = treeMatrix(readInput("inputs/Day08_test"))
println("Test Part 1: " + part1(testInput))
println("Test Part 2: " + part2(testInput))
//execute the two parts on the real input
val input = treeMatrix(readInput("inputs/Day08"))
println("Part1: " + part1(input))
println("Part2: " + part2(input))
}
| 0 | Kotlin | 0 | 0 | 6e75b42c9849cdda682ac18c5a76afe4950e0c9c | 4,397 | aoc2022-kotlin | Apache License 2.0 |
src/Day09.kt | cornz | 572,867,092 | false | {"Kotlin": 35639} | data class Point(var x: Int, var y: Int)
fun main() {
fun move(
instruction: String,
headAndTail: Triple<Point, Point, MutableList<Point>>
): Triple<Point, Point, MutableList<Point>> {
val parts = instruction.split(" ")
val guidance = parts[0]
val run = parts[1].toInt()
val head = headAndTail.first
val tail = headAndTail.second
val points = headAndTail.third
for (i in 0 until run) {
when (guidance) {
"R" -> {
head.x++
}
"L" -> {
head.x--
}
"U" -> {
head.y++
}
else -> {
head.y--
}
}
if (kotlin.math.abs(head.x - tail.x) < 2 && kotlin.math.abs(head.y - tail.y) < 2) {
continue
}
if (head.x > tail.x && head.y == tail.y) {
tail.x++
points.add(tail.copy())
} else if (tail.x > head.x && head.y == tail.y) {
tail.x--
points.add(tail.copy())
} else if (tail.x == head.x && head.y > tail.y) {
tail.y++
points.add(tail.copy())
} else if (tail.x == head.x && head.y < tail.y) {
tail.y--
points.add(tail.copy())
} else if (head.x > tail.x && head.y > tail.y) {
tail.x++
tail.y++
points.add(tail.copy())
} else if (head.x < tail.x && head.y > tail.y) {
tail.x--
tail.y++
points.add(tail.copy())
} else if (head.x > tail.x && head.y < tail.y) {
tail.x++
tail.y--
points.add(tail.copy())
} else if (head.x < tail.x && head.y < tail.y) {
tail.x--
tail.y--
points.add(tail.copy())
}
}
return Triple(head, tail, points)
}
fun part1(input: List<String>): Int {
val head = Point(0, 0)
val tail = Point(0, 0)
val points = mutableListOf(Point(0, 0))
var res = Triple(head, tail, points)
for (line in input) {
res = move(line, res)
}
return res.third.toSet().size
}
fun part2(input: List<String>): Int {
return input.size
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("input/Day09_test")
check(part1(testInput) == 13)
//check(part2(testInput) == 1)
val input = readInput("input/Day09")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 2800416ddccabc45ba8940fbff998ec777168551 | 2,799 | aoc2022 | Apache License 2.0 |
kotlin/src/main/kotlin/year2023/Day05.kt | adrisalas | 725,641,735 | false | {"Kotlin": 130217, "Python": 1548} | package year2023
fun main() {
val input = readInput2("Day05")
Day05.part1(input).println()
Day05.part2(input).println()
}
private typealias SeedRange = Pair<Long, Long>
private typealias Decoder = Set<RangeDecoder>
private typealias Decoders = List<Decoder>
private data class RangeDecoder(val from: Long, val quantity: Long, val to: Long)
object Day05 {
fun part1(input: String): Long {
val inputChunks = input.split(DOUBLE_NEW_LINE_REGEX)
val seeds = inputChunks[0]
.split(":")[1]
.split(" ")
.filter { it.isNotBlank() }
.map { it.toLong() }
val decoders = listOf(
buildDecoder(inputChunks[1].split(NEW_LINE_REGEX)),
buildDecoder(inputChunks[2].split(NEW_LINE_REGEX)),
buildDecoder(inputChunks[3].split(NEW_LINE_REGEX)),
buildDecoder(inputChunks[4].split(NEW_LINE_REGEX)),
buildDecoder(inputChunks[5].split(NEW_LINE_REGEX)),
buildDecoder(inputChunks[6].split(NEW_LINE_REGEX)),
buildDecoder(inputChunks[7].split(NEW_LINE_REGEX))
)
return seeds
.asSequence()
.map { decoders.decode(it) }
.min()
}
fun part2(input: String): Long {
val inputChunks = input.split(DOUBLE_NEW_LINE_REGEX)
val rangedSeeds = inputChunks[0]
.split(":")[1]
.split(" ")
.filter { it.isNotBlank() }
.map { it.toLong() }
.chunked(2)
.map { Pair(it[0], it[0] + it[1]) }
val decoders = listOf(
buildDecoder(inputChunks[1].split(NEW_LINE_REGEX)),
buildDecoder(inputChunks[2].split(NEW_LINE_REGEX)),
buildDecoder(inputChunks[3].split(NEW_LINE_REGEX)),
buildDecoder(inputChunks[4].split(NEW_LINE_REGEX)),
buildDecoder(inputChunks[5].split(NEW_LINE_REGEX)),
buildDecoder(inputChunks[6].split(NEW_LINE_REGEX)),
buildDecoder(inputChunks[7].split(NEW_LINE_REGEX))
)
return decoders
.decode(rangedSeeds)
.minOfOrNull { it.first }
?: -1L
}
private fun buildDecoder(lines: List<String>): Set<RangeDecoder> {
return lines
.drop(1)
.map {
val (a, b, c) = it.split(" ")
RangeDecoder(
to = a.toLong(),
from = b.toLong(),
quantity = c.toLong()
)
}
.toSet()
}
private fun RangeDecoder.decode(value: Long): Long {
return to + value - from
}
private fun Decoder.decode(value: Long): Long {
return this
.firstOrNull {
val (from, quantity, _) = it
val end = from + quantity
value in from..end
}
?.decode(value)
?: value
}
private fun Decoders.decode(value: Long): Long {
return this.fold(value) { acc, decoder ->
decoder.decode(acc)
}
}
private fun Decoders.decode(rangedSeeds: List<SeedRange>): List<SeedRange> {
return this.fold(rangedSeeds) { acc, decoder ->
decoder.decode(acc)
}
}
private fun Decoder.decode(rangedSeeds: List<SeedRange>): List<SeedRange> {
val consumedSeeds = mutableListOf<SeedRange>()
val newSeeds = mutableListOf<SeedRange>()
for (rangeDecoder in this) {
val (from, quantity, _) = rangeDecoder
for (range in rangedSeeds) {
val intersectionMin = maxOf(from, range.first)
val intersectionMax = minOf(from + quantity, range.second)
if (intersectionMin > intersectionMax) {
continue
}
val consumed = Pair(intersectionMin, intersectionMax)
val newSeed = Pair(rangeDecoder.decode(intersectionMin), rangeDecoder.decode(intersectionMax))
//println("$consumed -> $newSeed")
consumedSeeds.add(consumed)
newSeeds.add(newSeed)
}
}
val normalizedConsumedSeeds = consumedSeeds.distinct().normalize()
val normalizedRangedSeeds = rangedSeeds.normalize()
val nonConsumedSeeds = normalizedRangedSeeds.removeRanges(normalizedConsumedSeeds)
//nonConsumedSeeds.forEach { println(it) }
//println("")
return (nonConsumedSeeds + newSeeds).normalize()
}
fun List<SeedRange>.removeRanges(toRemove: List<SeedRange>): List<SeedRange> {
val result = this.toMutableList()
var pivot1 = 0
var pivot2 = 0
while (pivot1 < result.size && pivot2 < toRemove.size) {
val range1 = result[pivot1]
val range2 = toRemove[pivot2]
if (range1.second < range2.first) {
//range1 outside range2 by the left
pivot1++
} else if (range1.first > range2.second) {
//range1 outside range2 by the right
pivot2++
} else if (range1.first < range2.first && range1.second <= range2.second) {
// range 1 has a remaining part at left
result.removeAt(pivot1)
result.add(pivot1, Pair(range1.first, range2.first - 1))
pivot1++
} else if (range1.first >= range2.first && range1.second <= range2.second) {
//range1 is fully contained in range2
result.removeAt(pivot1)
} else if (range1.first >= range2.first && range1.second > range2.second) {
// range 1 has a remaining part at right
result.removeAt(pivot1)
result.add(pivot1, Pair(range2.second + 1, range1.second))
pivot2++
} else {
//range 1 has a remaining part at left and right
result.removeAt(pivot1)
result.add(pivot1, Pair(range1.first, range2.first - 1))
result.add(pivot1 + 1, Pair(range2.second + 1, range1.second))
pivot2++
}
}
return result
}
fun List<SeedRange>.normalize(): List<SeedRange> {
if (this.isEmpty()) {
return emptyList()
}
val sortedRanges = this.sortedBy { it.first }
val result = mutableListOf<SeedRange>()
var currentRange = sortedRanges[0]
for (i in 1 until sortedRanges.size) {
val nextRange = sortedRanges[i]
if (currentRange.second >= (nextRange.first - 1)) {
currentRange = Pair(currentRange.first, maxOf(currentRange.second, nextRange.second))
} else {
result.add(currentRange)
currentRange = nextRange
}
}
result.add(currentRange)
return result
}
}
| 0 | Kotlin | 0 | 2 | 6733e3a270781ad0d0c383f7996be9f027c56c0e | 6,959 | advent-of-code | MIT License |
Kotlin/src/Combinations.kt | TonnyL | 106,459,115 | false | null | /**
* Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
*
* For example,
* If n = 4 and k = 2, a solution is:
*
* [
* [2,4],
* [3,4],
* [2,3],
* [1,2],
* [1,3],
* [1,4],
* ]
*/
class Combinations {
// Iterative solution.
// Accepted.
fun combine(n: Int, k: Int): List<List<Int>> {
var results = mutableListOf<List<Int>>()
if (n == 0 || k == 0 || k > n) {
return results
}
(1..n + 1 - k).mapTo(results) {
listOf(it)
}
for (i in 2..k) {
val tmp = mutableListOf<List<Int>>()
for (list in results) {
for (m in list[list.size - 1] + 1..n - (k - i)) {
val newList = mutableListOf<Int>()
newList.addAll(list)
newList.add(m)
tmp.add(newList)
}
}
results = tmp
}
return results
}
// Recursive solution.
// Accepted.
/*fun combine(n: Int, k: Int): List<List<Int>> {
val results = mutableListOf<List<Int>>()
if (n == 0 || k == 0 || k > n) {
return results
}
if (k == 1) {
(1..n).mapTo(results) {
listOf(it)
}
return results
}
for (list in combine(n, k - 1)) {
for (i in list[list.size - 1] until n) {
val tmp = mutableListOf<Int>()
tmp.addAll(list)
tmp.add(i + 1)
results.add(tmp)
}
}
return results*/
}
| 1 | Swift | 22 | 189 | 39f85cdedaaf5b85f7ce842ecef975301fc974cf | 1,647 | Windary | MIT License |
src/Day14.kt | cypressious | 572,898,685 | false | {"Kotlin": 77610} | import java.lang.IllegalStateException
import kotlin.math.max
import kotlin.math.min
fun main() {
data class Point(val x: Int, val y: Int) {
fun isHorizontalLine(other: Point) = y == other.y
}
class Grid(width: Int, height: Int, val offset: Int) {
private val grid = List(height) { CharArray(width) { '.' } }
operator fun get(y: Int, x: Int) = grid[y][x - offset]
operator fun set(y: Int, x: Int, c: Char) = grid[y].set(x - offset, c)
fun contains(y: Int, x: Int) = y in grid.indices && (x - offset) in grid[y].indices
override fun toString() = grid.joinToString("\n") { it.joinToString("") }
}
fun parseStructures(input: List<String>) = input.map { line ->
line
.split(" -> ")
.map { it.split(",").map(String::toInt) }
.map { (x, y) -> Point(x, y) }
}
fun buildGrid(structures: List<List<Point>>, hasFloor: Boolean): Grid {
var minX = Int.MAX_VALUE
var maxX = 0
var maxY = 0
for ((x, y) in structures.flatten()) {
minX = min(minX, x)
maxX = max(maxX, x)
maxY = max(maxY, y)
}
if (hasFloor) {
maxY += 2
// ¯\_(ツ)_/¯
val minWidth = maxY * 3
val diffX = minWidth - (maxX - minX + 1)
minX -= diffX / 2
maxX += diffX / 2
}
val grid = Grid(maxX - minX + 1, maxY + 1, minX)
for (structure in structures) {
for ((from, to) in structure.windowed(2, 1)) {
if (from.isHorizontalLine(to)) {
for (x in min(from.x, to.x)..max(from.x, to.x)) {
grid[from.y, x] = '#'
}
} else {
for (y in min(from.y, to.y)..max(from.y, to.y)) {
grid[y, from.x] = '#'
}
}
}
}
if (hasFloor) {
for (x in minX..maxX) {
grid[maxY, x] = '#'
}
}
return grid
}
val moveDirections = listOf(Point(0, 1), Point(-1, 1), Point(1, 1))
fun settle(grid: Grid, hasBottom: Boolean): Int {
var settled = 0
outerLoop@ while (grid[0, 500] == '.') {
var x = 500
var y = 0
moveLoop@ while (true) {
for ((dx, dy) in moveDirections) {
val newY = y + dy
val newX = x + dx
if (!grid.contains(newY, newX)) {
// sand leaves grid, no sand will settle anymore
if (hasBottom) throw IllegalStateException("sand can't leave grid with floor")
return settled
}
if (grid[newY, newX] == '.') {
y = newY
x = newX
continue@moveLoop
}
}
//sand settled
settled++
grid[y, x] = 'o'
break@moveLoop
}
}
return settled
}
fun part1(input: List<String>): Int {
val structures = parseStructures(input)
val grid = buildGrid(structures, false)
return settle(grid, false)
}
fun part2(input: List<String>): Int {
val structures = parseStructures(input)
val grid = buildGrid(structures, true)
return settle(grid, true)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day14_test")
check(part1(testInput) == 24)
check(part2(testInput) == 93)
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 7b4c3ee33efdb5850cca24f1baa7e7df887b019a | 3,831 | AdventOfCode2022 | Apache License 2.0 |
src/commonMain/kotlin/io/github/arashiyama11/functions.kt | arashiyama11 | 581,833,835 | false | {"Kotlin": 69471} | package io.github.arashiyama11
import kotlin.math.*
val validFunctions = listOf("sin", "cos", "tan", "log", "sqrt", "abs", "max", "min", "pow")
val specialFunctions = mapOf(
"sin" to SpecialFunction(
1,
{ Rational(sin(it[0])).reduction() },
{ t, l -> Unary("${t[0].toPolynomial().differential(l).evaluate()}cos(${t[0]})") },
{ Unary("-cos(${it[0]})") }),
"cos" to SpecialFunction(
1,
{ Rational(cos(it[0])).reduction() },
{ t, l -> Unary("-${t[0].toPolynomial().differential(l).evaluate()}sin(${t[0]})") },
{ Unary("sin(${it[0]})") }),
"tan" to SpecialFunction(1,
{ Rational(tan(it[0])).reduction() },
{ t, l -> Polynomial("${t[0].toPolynomial().differential(l).evaluate()}/(cos(${t[0]})*cos(${t[0]}))") },
{ Unary("-log(abs(cos(${it[0]})))") }),
"log" to SpecialFunction(1,
{ Rational(log(it[0], E)).reduction() },
{ t, l -> Unary("${t[0].toPolynomial().differential(l).evaluate()}/${t[0]}") },
{ Polynomial("${it[0]}log(${it[0]})-${it[0]}") }),
"sqrt" to SpecialFunction(
1,
{
if (it[0] >= 0) Rational(sqrt(it[0])).reduction() else Unary(listOf(Rational(sqrt(-it[0])), Letter('i')))
},
{ t, l -> Polynomial("${t[0].toPolynomial().differential(l).evaluate()}/2sqrt(${t[0]})") },
{ Polynomial("2${it[0]}^2sqrt(${it[0]})/3") }),
"abs" to SpecialFunction(
1,
{ Rational(abs(it[0])).reduction() },
{ t, l -> Polynomial("${t[0].toPolynomial().differential(l).evaluate()}${t[0]}/abs(${t[0]})") },
null
),
"min" to SpecialFunction(2, { Rational(min(it[0], it[1])).reduction() }, null, null),
"max" to SpecialFunction(2, { Rational(max(it[0], it[1])).reduction() }, null, null),
"pow" to SpecialFunction(2, {
Rational(it[0]).pow(it[1].toInt()).reduction()
}, null, null, { args, decimal, lang ->
if (!decimal && lang == null) {
val b = args[0].toString().let { if (it.length == 1) it else "($it)" }
val d = args[1].toString().let { if (it.length == 1) it else "($it)" }
"$b^$d"
} else {
val b = args[0].toStringWith(decimal, lang).let { if (it.length == 1) it else "($it)" }
val d = args[1].toStringWith(decimal, lang).let { if (it.length == 1) it else "($it)" }
"$b^$d"
}
})
)
data class SpecialFunction(
//null is vararg
val argLength: Int?,
val approximation: (List<Double>) -> TermBase,
val differential: ((List<TermBase>, Letter) -> TermBase)?,
val integral: ((List<TermBase>) -> TermBase)?,
val toStringFn: ((List<TermBase>, Boolean, Language?) -> String)? = null
) | 0 | Kotlin | 0 | 0 | c3832fb4248060b55d2a0528ece479ac799002d8 | 2,554 | mojishiki | MIT License |
src/main/kotlin/com/chriswk/aoc/advent2022/Day9.kt | chriswk | 317,863,220 | false | {"Kotlin": 481061} | package com.chriswk.aoc.advent2022
import com.chriswk.aoc.AdventDay
import com.chriswk.aoc.util.CompassDirection
import com.chriswk.aoc.util.Point2D
import com.chriswk.aoc.util.report
import kotlin.math.absoluteValue
import kotlin.math.sign
class Day9: AdventDay(2022, 9) {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val day = Day9()
report {
day.part1()
}
report {
day.part2()
}
}
}
fun move(head: Point2D, moves: List<CompassDirection>): Sequence<Point2D> {
return sequence {
yield(head)
moves.fold(head) { acc, dir ->
val new = acc + dir.delta
yield(new)
new
}
}
}
data class Move(val direction: CompassDirection, val count: Int)
fun parseInput(input: List<String>): List<CompassDirection> {
return input.map { parseLine(it) }.flatMap { instruction -> (0.until(instruction.count)).map { instruction.direction }}
}
fun parseLine(input: String): Move {
val (direction, count) = input.split(" ")
return Move(direction = CompassDirection.fromString(direction), count = count.toInt())
}
fun part1(): Int {
return move(Point2D(0, 0), parseInput(inputAsLines)).follow().toSet().size
}
fun part2(): Int {
return move(Point2D(0, 0), parseInput(inputAsLines)).follow().follow().follow().follow().follow().follow().follow().follow().follow().toSet().size
}
}
fun Sequence<Point2D>.follow(): Sequence<Point2D> = sequence {
var tailX = 0
var tailY = 0
yield(Point2D(tailX, tailY))
for (point in this@follow) {
val deltaX = point.x - tailX
val deltaY = point.y - tailY
if (deltaX.absoluteValue >= 2 || deltaY.absoluteValue >= 2) {
tailX = if (deltaX.absoluteValue >= deltaY.absoluteValue) {
point.x - deltaX.sign
} else {
point.x
}
tailY = if (deltaX.absoluteValue <= deltaY.absoluteValue) {
point.y - deltaY.sign
} else {
point.y
}
val new = Point2D(tailX, tailY)
yield(new)
} else {
continue
}
}
}
| 116 | Kotlin | 0 | 0 | 69fa3dfed62d5cb7d961fe16924066cb7f9f5985 | 2,360 | adventofcode | MIT License |
kotlin/src/main/kotlin/adventofcode/day13/Day13_2.kt | thelastnode | 160,586,229 | false | null | package adventofcode.day13
import java.io.File
import java.lang.IllegalArgumentException
import java.lang.IllegalStateException
import java.util.*
object Day13_2 {
enum class State(val repr: Set<Char>) {
TRACK(setOf('|', '-')),
CURVE(setOf('\\', '/')),
INTERSECTION(setOf('+')),
CART(setOf('>', 'v', '^', '<'));
}
fun stateFromChar(c: Char): State = State.values().find { c in it.repr }!!
data class Position(val x: Int, val y: Int) : Comparable<Position> {
fun left() = Position(x - 1, y)
fun right() = Position(x + 1, y)
fun up() = Position(x, y - 1)
fun down() = Position(x, y + 1)
override fun compareTo(other: Position): Int {
val yComp = y.compareTo(other.y)
if (yComp != 0) {
return yComp
}
return x.compareTo(other.x)
}
}
data class Cell(val pos: Position, val state: State, val raw: Char)
enum class NextIntersection(val next: () -> NextIntersection) {
LEFT({ NextIntersection.STRAIGHT }),
STRAIGHT({ NextIntersection.RIGHT }),
RIGHT({ NextIntersection.LEFT })
}
data class Cart(val pos: Position, val next: NextIntersection, val raw: Char) {
fun forward(): Cart {
val nextPos = when (raw) {
'>' -> pos.right()
'^' -> pos.up()
'<' -> pos.left()
'v' -> pos.down()
else -> throw IllegalArgumentException()
}
return Cart(nextPos, next, raw)
}
fun leftTurn(): Cart = Cart(pos, next, when (raw) {
'>' -> '^'
'^' -> '<'
'<' -> 'v'
'v' -> '>'
else -> throw IllegalArgumentException()
})
fun rightTurn(): Cart = Cart(pos, next, when (raw) {
'>' -> 'v'
'^' -> '>'
'<' -> '^'
'v' -> '<'
else -> throw IllegalArgumentException()
})
}
fun parse(lines: List<String>): List<Cell> {
return lines.withIndex().flatMap { (i, line) ->
line
.mapIndexed { j, x ->
when (x) {
' ' -> null
else -> Cell(Position(j, i), stateFromChar(x), x)
}
}
.filterNotNull()
}
}
private fun printGrid(grid: SortedMap<Position, Cell>, carts: List<Cart>) {
val cartPos = carts.associateBy { it.pos }
val maxX = grid.map { it.key.x }.max()!!
val maxY = grid.map { it.key.y }.max()!!
for (j in 0..maxY) {
for (i in 0..maxX) {
val p = Position(i, j)
if (p in cartPos) {
print(cartPos[p]!!.raw)
} else if (p in grid) {
print(grid[p]!!.raw)
} else {
print(' ')
}
}
println()
}
}
fun getCartReplacement(cells: SortedMap<Position, Cell>, pos: Position): Cell {
val left = pos.left().run { this in cells && cells[this]!!.raw in setOf('-', '\\', '/', '+') }
val right = pos.right().run { this in cells && cells[this]!!.raw in setOf('-', '\\', '/', '+') }
val up = pos.up().run { this in cells && cells[this]!!.raw in setOf('|', '\\', '/', '+') }
val down = pos.down().run { this in cells && cells[this]!!.raw in setOf('|', '\\', '/', '+') }
val newTrack = when {
up && down && left && right -> '+'
(up && left) || (down && right) -> '/'
(up && right) || (down && left) -> '\\'
up && down -> '|'
left && right -> '-'
else -> throw IllegalStateException()
}
return Cell(pos = pos, state = stateFromChar(newTrack), raw = newTrack)
}
fun removeCarts(cells: SortedMap<Position, Cell>): SortedMap<Position, Cell> {
return cells
.map { (_, c) ->
when (c.state) {
State.CART -> getCartReplacement(cells, c.pos)
else -> c
}
}
.associateBy { it.pos }
.toSortedMap()
}
private fun step(carts: List<Cart>, grid: SortedMap<Position, Cell>): List<Cart> {
val remainingCarts = carts.sortedBy { it.pos }.toMutableList()
val processedCarts = mutableListOf<Cart>()
fun processCart(cart: Cart) {
val (pos, next, raw) = cart
val nextPos = when (raw) {
'>' -> pos.right()
'^' -> pos.up()
'<' -> pos.left()
'v' -> pos.down()
else -> throw IllegalArgumentException()
}
val nextCell = grid[nextPos]!!
val nextRaw = when (nextCell.state) {
State.TRACK -> cart.forward()
State.INTERSECTION -> when (next) {
NextIntersection.LEFT -> cart.leftTurn()
NextIntersection.STRAIGHT -> cart.forward()
NextIntersection.RIGHT -> cart.rightTurn()
}
State.CURVE -> when {
nextCell.raw == '/' && cart.raw in setOf('v', '^') -> cart.rightTurn()
nextCell.raw == '/' && cart.raw in setOf('>', '<') -> cart.leftTurn()
nextCell.raw == '\\' && cart.raw in setOf('v', '^') -> cart.leftTurn()
nextCell.raw == '\\' && cart.raw in setOf('>', '<') -> cart.rightTurn()
else -> throw IllegalArgumentException()
}
else -> throw IllegalArgumentException()
}.raw
val nextNext = if (nextCell.state == State.INTERSECTION) next.next() else next
val cartPositions = remainingCarts.map { it.pos }.toSet().union(processedCarts.map { it.pos })
val hasCrashed = nextPos in cartPositions
if (hasCrashed) {
remainingCarts.removeIf { it.pos == nextPos }
processedCarts.removeIf { it.pos == nextPos }
} else {
processedCarts.add(Cart(nextPos, nextNext, if (hasCrashed) 'X' else nextRaw))
}
}
while (remainingCarts.isNotEmpty()) {
val nextCartToMove = remainingCarts.removeAt(0)
processCart(nextCartToMove)
}
return processedCarts
}
fun process(inputs: List<Cell>): Any? {
var carts = inputs.filter { it.state == State.CART }
.map { Cart(it.pos, NextIntersection.LEFT, it.raw) }
val grid = inputs.associateBy { it.pos }.toSortedMap()
.run { removeCarts(this) }
while (carts.size > 1) {
carts = step(carts, grid)
// printGrid(grid, carts)
}
return carts
}
}
fun main(args: Array<String>) {
val lines = File("./day13-input").readLines()
val inputs = Day13_2.parse(lines)
println(Day13_2.process(inputs))
} | 0 | Kotlin | 0 | 0 | 8c9a3e5a9c8b9dd49eedf274075c28d1ebe9f6fa | 7,103 | adventofcode | MIT License |
src/Day09.kt | SnyderConsulting | 573,040,913 | false | {"Kotlin": 46459} | import kotlin.math.abs
fun main() {
fun part1(input: List<String>): Int {
val movements = input.map { line ->
Movement.of(line)
}
val grid = Grid(2)
movements.forEach {
grid.moveHead(it)
}
return grid.knotPositions.last().distinct().size
}
fun part2(input: List<String>): Int {
val movements = input.map { line ->
Movement.of(line)
}
val grid = Grid(10)
movements.forEach {
grid.moveHead(it)
}
return grid.knotPositions.last().distinct().size
}
val input = readInput("Day09")
println(part1(input))
println(part2(input))
}
data class Movement(val direction: Direction, val amt: Int) {
companion object {
fun of(string: String): Movement {
val (directionCode, amt) = string.split(" ")
val direction = when (directionCode) {
"U" -> Direction.UP
"D" -> Direction.DOWN
"L" -> Direction.LEFT
else -> Direction.RIGHT
}
return Movement(direction, amt.toInt())
}
}
}
class Grid(knotCount: Int) {
val knotPositions = MutableList(knotCount) {
mutableListOf(Coordinates(0, 0))
}
fun moveHead(movement: Movement) {
repeat(movement.amt) {
val headPositions = knotPositions.first()
when (movement.direction) {
Direction.UP -> {
headPositions.last().also { currentPos ->
headPositions.add(Coordinates(currentPos.x, currentPos.y + 1))
}
}
Direction.DOWN -> {
headPositions.last().also { currentPos ->
headPositions.add(Coordinates(currentPos.x, currentPos.y - 1))
}
}
Direction.LEFT -> {
headPositions.last().also { currentPos ->
headPositions.add(Coordinates(currentPos.x - 1, currentPos.y))
}
}
Direction.RIGHT -> {
headPositions.last().also { currentPos ->
headPositions.add(Coordinates(currentPos.x + 1, currentPos.y))
}
}
}
knotPositions.windowed(2).forEach { (headPositions, tailPositions) ->
moveTail(headPositions.last(), tailPositions)
}
}
}
private fun moveTail(headPos: Coordinates, tailPositions: MutableList<Coordinates>) {
var tailPos = tailPositions.last()
fun moveVertical() {
//vertical move
if (headPos.y > tailPos.y) {
tailPositions.add(Coordinates(tailPos.x, headPos.y - 1))
} else {
tailPositions.add(Coordinates(tailPos.x, headPos.y + 1))
}
}
fun moveHorizontal() {
//horizontal move
if (headPos.x > tailPos.x) {
tailPositions.add(Coordinates(headPos.x - 1, tailPos.y))
} else {
tailPositions.add(Coordinates(headPos.x + 1, tailPos.y))
}
}
fun moveDiagonal() {
var yOffset = 0
var xOffset = 0
if (headPos.x > tailPos.x) {
//moving right
xOffset = 1
}
if (headPos.x < tailPos.x) {
//moving left
xOffset = -1
}
if (headPos.y > tailPos.y) {
//moving up
yOffset = 1
}
if (headPos.y < tailPos.y) {
//moving down
yOffset = -1
}
tailPositions.add(Coordinates(tailPos.x + xOffset, tailPos.y + yOffset))
}
if (abs(headPos.x - tailPos.x) <= 1 && abs(headPos.y - tailPos.y) <= 1) {
tailPositions.add(tailPos)
} else {
if (headPos.x == tailPos.x) {
moveVertical()
} else if (headPos.y == tailPos.y) {
moveHorizontal()
} else {
//diagonal move
val xDiff = abs(headPos.x - tailPos.x)
val yDiff = abs(headPos.y - tailPos.y)
if (xDiff > yDiff) {
//move left or right of head
tailPos = tailPos.copy(y = headPos.y)
moveHorizontal()
} else if (yDiff > xDiff) {
//move up or down of head
tailPos = tailPos.copy(x = headPos.x)
moveVertical()
} else {
moveDiagonal()
}
}
}
}
}
data class Coordinates(val x: Int, val y: Int)
enum class Direction {
UP,
DOWN,
LEFT,
RIGHT
} | 0 | Kotlin | 0 | 0 | ee8806b1b4916fe0b3d576b37269c7e76712a921 | 4,958 | Advent-Of-Code-2022 | Apache License 2.0 |
src/Day09.kt | sushovan86 | 573,586,806 | false | {"Kotlin": 47064} | import kotlin.math.abs
enum class Direction {
UP, DOWN, LEFT, RIGHT
}
val DIRECTION_MAP = mapOf(
"R" to Direction.RIGHT,
"L" to Direction.LEFT,
"U" to Direction.UP,
"D" to Direction.DOWN
)
data class Point(val x: Int = 0, val y: Int = 0) {
infix fun moveTowards(movement: Direction): Point = when (movement) {
Direction.LEFT -> copy(x = x - 1)
Direction.RIGHT -> copy(x = x + 1)
Direction.UP -> copy(y = y + 1)
Direction.DOWN -> copy(y = y - 1)
}
infix fun isNeighbourTo(other: Point): Boolean =
abs(x - other.x) <= 1 && abs(y - other.y) <= 1
infix fun follow(other: Point): Point {
val xOffset = (other.x - x).coerceIn(-1..1)
val yOffset = (other.y - y).coerceIn(-1..1)
return Point(x + xOffset, y + yOffset)
}
}
class RopeBridge private constructor() {
private val instructions = mutableListOf<Pair<Direction, Int>>()
private val tailPositions = mutableSetOf<Point>()
companion object {
fun loadData(instructionStringList: List<String>): RopeBridge {
val ropeBridge = RopeBridge()
for (eachInstructionString in instructionStringList) {
val (movement, value) = eachInstructionString.split(" ")
val direction = DIRECTION_MAP[movement] ?: error("Invalid Movement $movement")
ropeBridge.instructions += direction to value.toInt()
}
return ropeBridge
}
}
fun getTailPositionCount() = tailPositions.size
fun processInstructions(knotSize: Int): RopeBridge {
tailPositions.clear()
val ropeKnots = Array(knotSize) { Point() }
tailPositions += ropeKnots[knotSize - 1]
for ((direction, value) in instructions) {
repeat(value) {
processKnotsDirection(ropeKnots, direction, knotSize)
}
}
return this
}
private fun processKnotsDirection(ropeKnots: Array<Point>, direction: Direction, knotSize: Int) {
// First index in the array is head, last index is tail
ropeKnots[0] = ropeKnots[0] moveTowards direction
for (knotIndex in 1 until knotSize) {
val previousKnot = ropeKnots[knotIndex - 1]
var currentKnot = ropeKnots[knotIndex]
if (currentKnot isNeighbourTo previousKnot) {
break
}
currentKnot = currentKnot follow previousKnot
ropeKnots[knotIndex] = currentKnot
if (knotIndex == ropeKnots.lastIndex) {
tailPositions += currentKnot
}
}
}
}
fun main() {
val testInput1 = readInput("Day09_test1")
val testRopeBridge1 = RopeBridge.loadData(testInput1)
testRopeBridge1.processInstructions(2)
check(testRopeBridge1.getTailPositionCount() == 13)
val testInput2 = readInput("Day09_test2")
val testRopeBridge2 = RopeBridge.loadData(testInput2)
testRopeBridge2.processInstructions(10)
check(testRopeBridge2.getTailPositionCount() == 36)
val actualInput = readInput("Day09")
val actualRopeBridge = RopeBridge.loadData(actualInput)
actualRopeBridge.processInstructions(2)
println(actualRopeBridge.getTailPositionCount())
actualRopeBridge.processInstructions(10)
println(actualRopeBridge.getTailPositionCount())
} | 0 | Kotlin | 0 | 0 | d5f85b6a48e3505d06b4ae1027e734e66b324964 | 3,378 | aoc-2022 | Apache License 2.0 |
app/src/main/kotlin/aoc2021/day03/Day03.kt | dbubenheim | 435,284,482 | false | {"Kotlin": 31242} | package aoc2021.day03
import aoc2021.toFile
class Day03 {
companion object {
@JvmStatic
fun binaryDiagnosticPart1(): Int {
return "input-day03.txt"
.toFile()
.readLines()
.map { it.toIntArray() }
.fold(DiagnosticReport()) { report, number -> report.update(number) }
.result()
}
@JvmStatic
fun binaryDiagnosticPart2(): Int {
val numbers = "input-day03.txt"
.toFile()
.readLines()
.map { it.toIntArray() }
.toList()
val indices = numbers.first().indices
val mostCommonValue = findMostCommonValue(indices, numbers)
val leastCommonValue = findLeastCommonValue(indices, numbers)
val oxygenGeneratorRatingBinary = findOxygenGeneratorRating(numbers, indices, mostCommonValue)
val oxygenGeneratorRating = oxygenGeneratorRatingBinary.toDecimal()
val co2ScrubberRatingBinary = findCo2ScrubberRating(indices, numbers, leastCommonValue)
val co2ScrubberRating = co2ScrubberRatingBinary.toDecimal()
return oxygenGeneratorRating * co2ScrubberRating
}
private fun findCo2ScrubberRating(
indices: IntRange,
numbers: List<IntArray>,
leastCommonValue: String
): IntArray {
var n = numbers
indices.takeWhile { i ->
n = n.filter { it[i] == leastCommonValue[i].digitToInt() }
n.size != 1
}
return n.first()
}
private fun findOxygenGeneratorRating(
numbers: List<IntArray>,
indices: IntRange,
mostCommonValue: String
): IntArray {
var n = numbers
indices.takeWhile { i ->
n = n.filter { it[i] == mostCommonValue[i].digitToInt() }
n.size != 1
}
return n.first()
}
private fun findLeastCommonValue(
indices: IntRange,
input: List<IntArray>
): String {
var numbers = input
val leastCommonValue = indices.joinToString(separator = "") { index ->
val count0 = numbers.count { it[index] == 0 }
val count1 = numbers.count { it[index] == 1 }
numbers = numbers.filter { it[index] == if (count1 < count0) 1 else 0 }
if (count1 < count0) "1" else "0"
}
return leastCommonValue
}
private fun findMostCommonValue(
indices: IntRange,
input: List<IntArray>
): String {
var numbers = input
val mostCommonValue = indices.joinToString(separator = "") { index ->
val count0 = numbers.count { it[index] == 0 }
val count1 = numbers.count { it[index] == 1 }
numbers = numbers.filter { it[index] == if (count0 > count1) 0 else 1 }
if (count0 > count1) "0" else "1"
}
return mostCommonValue
}
@JvmStatic
fun main(args: Array<String>) {
println(binaryDiagnosticPart1())
println(binaryDiagnosticPart2())
}
}
}
private fun String.toIntArray(): IntArray = chars().map { Character.getNumericValue(it) }.toArray()
private fun IntArray.toDecimal() = joinToString("").toInt(2)
| 9 | Kotlin | 0 | 0 | 83a93845ebbc1a6405f858214bfa79b3448b932c | 3,506 | advent-of-code-2021 | MIT License |
src/Day01.kt | msernheim | 573,937,826 | false | {"Kotlin": 32820} | fun main() {
fun part1(input: List<String>): Int {
var cMax = 0;
var current = 0;
input.forEach { food ->
if (food.equals("")) {
if (cMax >= current) {
current = 0
} else {
cMax = current
current = 0
}
} else {
current += food.toInt()
}
}
return cMax
}
fun placeInTopThree(current: Int, topThree: MutableList<Int>) {
if (current > topThree[0]) {
topThree[2] = topThree[1]
topThree[1] = topThree[0]
topThree[0] = current
} else if(current > topThree[1]) {
topThree[2] = topThree[1]
topThree[1] = current
} else if (current > topThree[2]) {
topThree[2] = current
}
}
fun part2(input: List<String>): Int {
val topThree = mutableListOf(0, 0, 0);
var current = 0;
input.forEach { food ->
if (food.equals("")) {
placeInTopThree(current, topThree)
current = 0
} else {
current += food.toInt()
}
}
return topThree.sum()
}
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 3 | 54cfa08a65cc039a45a51696e11b22e94293cc5b | 1,359 | AoC2022 | Apache License 2.0 |
src/merge_sorted_array/README.kt | AhmedTawfiqM | 458,182,208 | false | {"Kotlin": 11105} | package merge_sorted_array
//https://leetcode.com/problems/merge-sorted-array/
/*
You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.
Merge nums1 and nums2 into a single array sorted in non-decreasing order.
The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.
Example 1:
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.
Example 2:
Input: nums1 = [1], m = 1, nums2 = [], n = 0
Output: [1]
Explanation: The arrays we are merging are [1] and [].
The result of the merge is [1].
Example 3:
Input: nums1 = [0], m = 0, nums2 = [1], n = 1
Output: [1]
Explanation: The arrays we are merging are [] and [1].
The result of the merge is [1].
Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
Constraints:
nums1.length == m + n
nums2.length == n
0 <= m, n <= 200
1 <= m + n <= 200
-109 <= nums1[i], nums2[j] <= 109
*/ | 0 | Kotlin | 0 | 1 | a569265d5f85bcb51f4ade5ee37c8252e68a5a03 | 1,464 | ProblemSolving | Apache License 2.0 |
src/main/kotlin/adventOfCode2023/Day07.kt | TetraTsunami | 726,140,343 | false | {"Kotlin": 80024} | package adventOfCode2023
import util.*
@Suppress("unused")
class Day07(input: String, context: RunContext = RunContext.PROD) : Day(input, context) {
fun getFreqMap(hand: Pair<String, Int>): Map<Char, Int> {
val freqMap = mutableMapOf<Char, Int>()
var j = 0
for (i in 0..4) {
val card = hand.first[i]
if (card == 'J') j++
else {
freqMap[card] = freqMap.getOrDefault(card, 0) + 1
}
}
// joker logic
if (freqMap.isEmpty()) {
freqMap['A'] = j
} else {
val mc = freqMap.entries.maxBy { it.value }
freqMap[mc.key] = freqMap.getOrDefault(mc.key, 0) + j
}
return freqMap
}
fun pickType(hand: Pair<String, Int>): Int {
val freqs = getFreqMap(hand).values.sortedDescending()
when (freqs[0]) {
5 -> return 6
4 -> return 5
3 -> {
if (freqs[1] == 2) return 4
return 3
}
2 -> {
if (freqs[1] == 2) return 2
return 1
}
}
return 0
}
fun compareHands(h1: Pair<String, Int>, h2: Pair<String, Int>): Int {
val type1 = pickType(h1)
val type2 = pickType(h2)
val c1 = h1.first
val c2 = h2.first
if (type1 != type2) {
return type1 - type2
}
val valueMap = mapOf('A' to 14, 'K' to 13, 'Q' to 12, 'J' to 1, 'T' to 10)
for (i in 0..4) {
if (c1[i] != c2[i]) {
return valueMap.getOrDefault(c1[i], c1[i].digitToIntOrNull())!! -
valueMap.getOrDefault(c2[i], c2[i].digitToIntOrNull())!!
}
}
return 0
}
override fun solve() {
var hands = mutableListOf<Pair<String, Int>>()
for (line in lines) {
val split = line.split(" ")
hands.add(Pair(split[0], split[1].toInt()))
}
// care about it.first = poker rules
var sum1 = 0
var sum2 = 0
val pt1hands = hands.toMutableList()
pt1hands.sortWith { o1, o2 -> compareHandsPt1(o1, o2) }
for ((i, hand) in pt1hands.withIndex()) {
sum1 += (i + 1) * hand.second
}
a(sum1)
hands.sortWith { o1, o2 -> compareHands(o1, o2) }
for ((i, hand) in hands.withIndex()) {
sum2 += (i + 1) * hand.second
}
a(sum2)
}
// Extra functions to solve part 1 and part 2 separately
fun getFreqMapPt1(hand: Pair<String, Int>): Map<Char, Int> {
val freqMap = mutableMapOf<Char, Int>()
for (i in 0..4) {
val card = hand.first[i]
val freq = freqMap.getOrDefault(card, 0)
freqMap[card] = freq + 1
}
return freqMap
}
fun pickTypePt1(hand: Pair<String, Int>): Int {
val freqs = getFreqMapPt1(hand).values.sortedDescending()
if (freqs[0] == 5) {
return 6
}
if (freqs[0] == 4) {
return 5
}
if (freqs[0] == 3) {
if (freqs[1] == 2) {
return 4
}
return 3
}
if (freqs[0] == 2) {
if (freqs[1] == 2) {
return 2
}
return 1
}
return 0
}
fun compareHandsPt1(hand1: Pair<String, Int>, hand2: Pair<String, Int>): Int {
val type1 = pickTypePt1(hand1)
val type2 = pickTypePt1(hand2)
if (type1 != type2) {
return type1 - type2
}
// highest card
// a > k > q > j > t > 9 > 8...
val valueMap = mapOf('A' to 14, 'K' to 13, 'Q' to 12, 'J' to 11, 'T' to 10)
for (i in 0..4) {
if (hand1.first[i] != hand2.first[i]) {
return valueMap.getOrDefault(hand1.first[i], hand1.first[i].digitToIntOrNull())!! -
valueMap.getOrDefault(hand2.first[i], hand2.first[i].digitToIntOrNull())!!
}
}
return 0
}
}
| 0 | Kotlin | 0 | 0 | 78d1b5d1c17122fed4f4e0a25fdacf1e62c17bfd | 4,102 | AdventOfCode2023 | Apache License 2.0 |
src/cn/ancono/math/algebra/abs/calculator/OrderedCalculators.kt | 140378476 | 105,762,795 | false | {"Java": 1912158, "Kotlin": 1243514} | package cn.ancono.math.algebra.abs.calculator
/*
* Created by liyicheng at 2021-05-06 19:32
*/
/**
* Describes an abelian group with a order relation denoted by `<, <=, >, >=`.
*
* The order must be consistent with addition, that is:
*
* x < y implies x + a < y + a, for any a
*
*
*/
interface OrderedAbelGroupCal<T> : AbelGroupCal<T>, OrderPredicate<T> {
/**
* Compares two elements.
*/
override fun compare(o1: T, o2: T): Int
/**
* Returns the absolute value `|x|` of [x]`.
* If `x >= 0` then `x` is returned, otherwise `-x` is returned.
*
* The triangle inequality is satisfied:
*
* |a + b| <= |a| + |b|
*
*/
fun abs(x: T): T {
if (compare(x, zero) < 0) {
return -x
}
return x
}
/**
* Determines whether the number is positive. This method is equivalent to `compare(x, zero) > 0`.
*
* @param x a number
* @return `x > 0`
*/
fun isPositive(x: T): Boolean {
return compare(x, zero) > 0
}
/**
* Determines whether the number is negative. This method is equivalent to `compare(x, zero) < 0`.
*
* @param x a number
* @return `x < 0`
*/
fun isNegative(x: T): Boolean {
return compare(x, zero) < 0
}
}
/**
* Describes a ring with a order relation denoted by `<, <=, >, >=`, which satisfies:
*
* x < y implies x + a < y + a, for any a
* x > 0, y > 0 implies x * y > 0
*
* The following properties hold:
*
* x > y and c > 0 implies c*x > c*y
* |a*b| = |a|*|b|
*
*
*
*/
interface OrderedRingCal<T> : RingCalculator<T>, OrderedAbelGroupCal<T>
/**
* Describes a field with a order relation denoted by `<`, which satisfies:
*
* x > 0, y > 0 implies x + y > 0, x * y > 0
* x > 0 implies -x < 0
*
*/
interface OrderedFieldCal<T> : FieldCalculator<T>, OrderedRingCal<T>
| 0 | Java | 0 | 6 | 02c2984c10a95fcf60adcb510b4bf111c3a773bc | 1,965 | Ancono | MIT License |
src/main/kotlin/PrimeSteps.kt | Flight552 | 408,072,383 | false | {"Kotlin": 26115, "Assembly": 1320} | //The prime numbers are not regularly spaced.
// For example from 2 to 3 the step is 1. From 3 to 5
// the step is 2. From 7 to 11 it is 4.
// Between 2 and 50 we have the following pairs of 2-steps primes:
//
//3, 5 - 5, 7, - 11, 13, - 17, 19, - 29, 31, - 41, 43
//
//We will write a function step with parameters:
//
//g (integer >= 2) which indicates the step we are looking for,
//
//m (integer >= 2) which gives the start of the search (m inclusive),
//
//n (integer >= m) which gives the end of the search (n inclusive)
//
//In the example above step(2, 2, 50) will return [3, 5]
//which is the first pair between 2 and 50 with a 2-steps.
//
//So this function should return the first pair of the
//two prime numbers spaced with a step of g between the limits m,
// n if these g-steps prime numbers exist otherwise
// nil or null or None or Nothing or [] or "0, 0" or {0, 0} or 0 0 or "" (depending on the language).
//
//Examples:
//step(2, 5, 7) --> [5, 7] or (5, 7) or {5, 7} or "5 7"
//
//step(2, 5, 5) --> nil or ... or [] in Ocaml or {0, 0} in C++
//
//step(4, 130, 200) --> [163, 167] or (163, 167) or {163, 167}
//
//See more examples for your language in "TESTS"
//
//Remarks:
//([193, 197] is also such a 4-steps primes between 130
//and 200 but it's not the first pair).
//
//step(6, 100, 110) --> [101, 107] though there is a
//prime between 101 and 107 which is 103; the pair 101-103 is a 2-step.
//
//Notes:
//The idea of "step" is close to that of "gap" but it is
//not exactly the same. For those interested they can have
//a look at http://mathworld.wolfram.com/PrimeGaps.html.
//
//A "gap" is more restrictive: there must be no primes in
//between (101-107 is a "step" but not a "gap". Next kata will be about "gaps":-).
//
//For Go: nil slice is expected when there are no step between m and n.
//Example: step(2,4900,4919) --> nil
object PrimeSteps {
// if these g-steps prime numbers don't exist return []
fun step(g: Int, m: Long, n: Long): LongArray {
println("g = $g, m = $m, n = $n")
if (n < m || m < 2 || g < 2)
return LongArray(0)
var array = LongArray(2)
val listOfPrimes = mutableListOf<Long>()
var stepCounter = 0
var isPrime = true
if (m == 2L || m == 3L || m == 5L) {
array[0] = m
listOfPrimes.add(m)
}
for (i in m..n) {
if (i % 2 == 0L) {
stepCounter++
continue
}
for (p in 3 .. i / 2 step 2) {
if (i % p == 0L) {
isPrime = false
break
}
isPrime = true
}
if (isPrime && i != 5L) {
println(listOfPrimes)
listOfPrimes.add(i)
}
listOfPrimes.forEachIndexed { index, l ->
val differ = listOfPrimes[listOfPrimes.size - 1] - listOfPrimes[index]
if(differ == g.toLong()) {
array[0] = listOfPrimes[index]
array[1] = listOfPrimes[listOfPrimes.size - 1]
return array
}
}
}
return if (array[1] == 0L) {
return LongArray(0)
} else {
array
}
}
}
fun main(args: Array<String>) {
var array = PrimeSteps.step(2, 7, 13)
println(array.asList())
}
| 0 | Kotlin | 0 | 0 | b9fb9378120455c55a413ba2e5a95796612143bc | 3,413 | codewars | MIT License |
src/main/kotlin/com/ginsberg/advent2016/Day13.kt | tginsberg | 74,924,040 | false | null | /*
* Copyright (c) 2016 by <NAME>
*/
package com.ginsberg.advent2016
import java.util.ArrayDeque
/**
* Advent of Code - Day 13: December 13, 2016
*
* From http://adventofcode.com/2016/day/13
*
*/
class Day13(favorite: Int, val goalX: Int, val goalY: Int, val depth: Int = 50) {
private val start = Node(1, 1, 0, favorite)
fun solvePart1(): Int = searchGrid()
fun solvePart2(): Int = countStepsToDepth()
fun searchGrid(): Int {
var found: Set<Pair<Int, Int>> = emptySet()
val queue = ArrayDeque<Node>().apply {
add(start)
}
while (queue.isNotEmpty()) {
val current = queue.poll()
found += Pair(current.x, current.y)
if (current.x == goalX && current.y == goalY) {
return current.distance
} else {
queue.addAll(
current
.neighbors()
.filterNot { found.contains(Pair(it.x, it.y)) }
)
}
}
return -1
}
fun countStepsToDepth(): Int {
var found: Set<Pair<Int, Int>> = emptySet()
val queue = ArrayDeque<Node>().apply {
add(start)
}
while (queue.isNotEmpty()) {
val current = queue.poll()
found += Pair(current.x, current.y)
queue.addAll(
current
.neighbors()
.filter { it.distance <= depth }
.filterNot { found.contains(Pair(it.x, it.y)) }
)
}
return found.size
}
data class Node(val x: Int, val y: Int, val distance: Int = 0, private val favorite: Int = 10) {
fun neighbors(): List<Node> =
listOf(
this.copy(x = x.inc(), distance = distance.inc()),
this.copy(x = x.dec(), distance = distance.inc()),
this.copy(y = y.inc(), distance = distance.inc()),
this.copy(y = y.dec(), distance = distance.inc()))
.filter { it.inBounds() }
.filter { it.isOpen() }
fun inBounds(): Boolean =
x >= 0 && y >= 0
fun isOpen(): Boolean =
Integer.bitCount(((x * x) + (3 * x) + (2 * x * y) + y + (y * y)) + favorite) % 2 == 0
}
}
| 0 | Kotlin | 0 | 3 | a486b60e1c0f76242b95dd37b51dfa1d50e6b321 | 2,340 | advent-2016-kotlin | MIT License |
src/main/kotlin/g1901_2000/s1970_last_day_where_you_can_still_cross/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g1901_2000.s1970_last_day_where_you_can_still_cross
// #Hard #Array #Depth_First_Search #Breadth_First_Search #Binary_Search #Matrix #Union_Find
// #2023_06_21_Time_703_ms_(100.00%)_Space_65.6_MB_(100.00%)
@Suppress("NAME_SHADOWING")
class Solution {
fun latestDayToCross(row: Int, col: Int, cells: Array<IntArray>): Int {
val ends = Array(row) { arrayOfNulls<Ends>(col) }
for (i in cells.indices) {
val r = cells[i][0] - 1
val c = cells[i][1] - 1
var curr: Ends? = null
if (c > 0 && ends[r][c - 1] != null) {
curr = calEnds(ends[r][c - 1], curr, c)
}
if (r > 0 && ends[r - 1][c] != null) {
curr = calEnds(ends[r - 1][c], curr, c)
}
if (c < col - 1 && ends[r][c + 1] != null) {
curr = calEnds(ends[r][c + 1], curr, c)
}
if (r < row - 1 && ends[r + 1][c] != null) {
curr = calEnds(ends[r + 1][c], curr, c)
}
if (c > 0 && r > 0 && ends[r - 1][c - 1] != null) {
curr = calEnds(ends[r - 1][c - 1], curr, c)
}
if (c > 0 && r < row - 1 && ends[r + 1][c - 1] != null) {
curr = calEnds(ends[r + 1][c - 1], curr, c)
}
if (c < col - 1 && r > 0 && ends[r - 1][c + 1] != null) {
curr = calEnds(ends[r - 1][c + 1], curr, c)
}
if (c < col - 1 && r < row - 1 && ends[r + 1][c + 1] != null) {
curr = calEnds(ends[r + 1][c + 1], curr, c)
}
if (curr == null) {
curr = Ends(i, c, c)
}
if (curr.l == 0 && curr.r == col - 1) {
return i
}
ends[r][c] = curr
}
return cells.size
}
private fun calEnds(p: Ends?, curr: Ends?, c: Int): Ends? {
var p = p
var curr = curr
while (p!!.parent != null) {
p = p.parent
}
p.l = if (curr == null) Math.min(p.l, c) else Math.min(p.l, curr.l)
p.r = if (curr == null) Math.max(p.r, c) else Math.max(p.r, curr.r)
if (curr == null) {
curr = p
} else if (curr.i != p.i) {
curr.parent = p
curr = curr.parent
}
return curr
}
internal class Ends(var i: Int, var l: Int, var r: Int) {
var parent: Ends? = null
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,470 | LeetCode-in-Kotlin | MIT License |
atcoder/agc043/d_wrong.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package atcoder.agc043
fun main() {
// val (n, m) = readInts()
val memo = HashMap<Long, Int>()
fun solve(x: Int, y: Int, z: Int): Int {
if (z == 0 && y == x - 1) return 1
if (y < 0 || y >= x || z >= x) return 0
val code = (x.toLong() shl 42) + (y.toLong() shl 21) + z
if (memo.containsKey(code)) return memo[code]!!
var res = 0
for (xx in 0 until x) {
res += solve(xx, y - (x - xx - 1), z)
}
if (z > 0) {
if (z == 1 && x - 1 - y <= 2) {
res += c(x - 1, x - 1 - y)
}
for (xx in 0 until x) {
for (r1 in 0..2) {
if (r1 > x - xx - 1) break
for (r2 in 0..2 - r1) {
if (r2 >= xx) break
if (r1 + r2 == 0) continue
res += solve(xx, y - (x - xx - 1 - r1) + r2, z - 1) * c(x - xx - 1, r1) * c(xx - 1, r2)
}
}
}
}
memo[code] = res
return res
}
fun solve(n: Int) = (0..n).sumBy { solve(3 * n, 0, it) }
println(solve(1))
println(solve(2))
}
private fun c(n: Int, k: Int): Int {
return when (k) {
0 -> 1
1 -> n
2 -> n * (n - 1) / 2
else -> error("")
}
}
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,043 | competitions | The Unlicense |
facebook/y2021/qual/b.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package facebook.y2021.qual
private fun needed(s: String): Pair<Int, Int>? {
return (s.count { it == '.' } to s.indexOf('.')).takeIf { 'O' !in s }
}
private fun solve(): String {
val field = List(readInt()) { readLn() }
val options = field.indices.flatMap { i -> listOf(
needed(field[i])?.let { it.first to (i to it.second) },
needed(field.map { it[i] }.joinToString(""))?.let { it.first to (it.second to i) }
)}.filterNotNull()
val needed = options.minOfOrNull { it.first } ?: return "Impossible"
val goodOptions = options.filter { it.first == needed }
val different = if (needed == 1) goodOptions.toSet().size else goodOptions.size
return "$needed $different"
}
fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") }
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 831 | competitions | The Unlicense |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.