path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/Day01.kt
lbilger
574,227,846
false
{"Kotlin": 5366}
fun main() { fun caloriesList(input: List<String>) = input.fold(listOf<Int>()) { acc, line -> if (line.isEmpty()) acc + 0 else acc.dropLast(1) + ((acc.lastOrNull() ?: 0) + line.toInt()) } fun part1(input: List<String>): Int { return caloriesList(input).max() } fun part2(input: List<String>): Int { return caloriesList(input).sortedDescending().take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") checkTestAnswer(part1(testInput), 24000, part = 1) checkTestAnswer(part2(testInput), 45000, part = 2) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
40d94a4bb9621af822722d20675684555cbee877
725
aoc-2022-in-kotlin
Apache License 2.0
2015/src/main/kotlin/day5_func.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Parser import utils.Solution fun main() { Day5Func.run() } object Day5Func : Solution<List<String>>() { override val name = "day5" override val parser = Parser.lines override fun part1(): Int { return input .filter { word -> word.toCharArray().filter { it in setOf('a', 'e', 'i', 'o', 'u') }.count() >= 3 } .filter { word -> word.toCharArray().toList().windowed(size = 2).any { (a, b) -> a == b } } .filter { word -> listOf("ab", "cd", "pq", "xy").none { it in word } } .count() } override fun part2(): Int { return input .filter { word -> word.toCharArray().toList().windowed(size = 3).any { (a, _, b) -> a == b } } .filter { word -> val subSequences = word.toCharArray().toList().windowed(size = 2).map { it.joinToString("") }.withIndex() subSequences.any { a -> subSequences.filter { it.value == a.value }.any { b -> a.index - b.index >= 2 } } } .count() } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
1,005
aoc_kotlin
MIT License
src/test/kotlin/com/winterbe/challenge/FindPairs.kt
winterbe
152,978,821
false
null
package com.winterbe.challenge import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test /** * Given an integer array and number k, output all unique pairs that sum up to k. * Example: for input [1, 3, 2, 5, 46, 6, 7, 4] and k = 4, output (1, 3). */ fun findPairs(k: Int, array: Array<Int>): List<Pair<Int, Int>> { fun divide(fence: Int, from: Int, to: Int): Int { var index = from var end = to while (index < end) { val num = array[index] if (num > fence) { val last = array[end - 1] array[index] = last array[end - 1] = num end-- } else { index++ } } return index } fun findPairsRecursively(depth: Int, fromLeft: Int, toLeft: Int, fromRight: Int, toRight: Int): List<Pair<Int, Int>> { if (fromLeft - toLeft <= 1 || fromRight - toRight <= 1) { val pairs = mutableListOf<Pair<Int, Int>>() for (i in (fromLeft until toLeft)) { for (j in (fromRight until toRight)) { val a = array[i] val b = array[j] if (a + b == k) { pairs.add(Pair(a, b)) } } } return pairs } val nextDepth = depth + 2 val leftDivider = divide(k / nextDepth, fromLeft, toLeft) val rightDivider = divide(k / nextDepth, fromRight, toRight) return findPairsRecursively(nextDepth, fromLeft, leftDivider, rightDivider, toRight) + findPairsRecursively(nextDepth, leftDivider, toLeft, fromRight, rightDivider) } val depth = 2 val index = divide(k / depth, 0, array.size) return findPairsRecursively(depth, 0, index, index, array.size) } class FindPairsTest { @Test fun test() { val array = arrayOf(1, 3, 2, 5, 46, 6, 7, 4) assertEquals(listOf(Pair(1, 3)), findPairs(4, array)) } }
0
Kotlin
4
10
3a0a911e4f601261ddb544da86647530371c8ba9
2,051
challenge
MIT License
src/main/kotlin/adventofcode2018/Day12SubterraneanSustainability.kt
n81ur3
484,801,748
false
{"Kotlin": 476844, "Java": 275}
package adventofcode2018 class Day12SubterraneanSustainability data class PotRule(val input: String, val result: Char) { companion object { fun fromString(rule: String): PotRule { return PotRule(rule.substringBefore(" ="), rule.last()) } } } class RulesSet(val rules: List<PotRule>) { fun getResultForInput(input: List<Char>): Char { val pattern = input.joinToString(separator = "") return rules.firstOrNull { it.input == pattern }?.result ?: '.' } companion object { fun fromRules(rules: List<String>): RulesSet { val potRules = rules.map { PotRule.fromString(it) } return RulesSet(potRules) } } } class Tunnel(initialState: String, rules: List<String>) { var pots = ArrayDeque(initialState.toList()) var nullIndex = 0 val rulesSet: RulesSet = RulesSet.fromRules(rules) private fun extendPots() { repeat(3) { pots.addFirst('.') pots.addLast('.') } } fun computeGenerations(iterations: Long): Long { if (iterations < 2000) { (0 until iterations).forEach { computeNextGeneration() } return computeTotalPotsSum() } else { return computeVeryOldGeneration(iterations) } } private fun computeVeryOldGeneration(iterations: Long): Long { computeGenerations(1000) val oneThousandGenerationCount = computeTotalPotsSum() computeGenerations(1000) val twoThousandGenerationCount = computeTotalPotsSum() val oneThousandIntervalCount = twoThousandGenerationCount - oneThousandGenerationCount val numberOfIntervalls = ((iterations - 1000)/1000) return (numberOfIntervalls) * oneThousandIntervalCount + oneThousandGenerationCount } fun computeNextGeneration(): Boolean { extendPots() val newList = pots.windowed(5, 1, false).map { rulesSet.getResultForInput(it) } if (newList.first() == '#') { nullIndex++ pots = ArrayDeque(newList) } else { pots = ArrayDeque(newList.drop(1)) } return false } fun computeTotalPotsSum(): Long { var result = 0L pots.forEachIndexed { index, pot -> if (pot == '#') { result += (index - nullIndex) } } return result } }
0
Kotlin
0
0
fdc59410c717ac4876d53d8688d03b9b044c1b7e
2,464
kotlin-coding-challenges
MIT License
src/main/kotlin/g1101_1200/s1192_critical_connections_in_a_network/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1101_1200.s1192_critical_connections_in_a_network // #Hard #Depth_First_Search #Graph #Biconnected_Component // #2023_05_25_Time_1696_ms_(60.00%)_Space_237.1_MB_(40.00%) class Solution { fun criticalConnections(n: Int, connections: List<List<Int>>): List<List<Int>> { val graph: MutableList<MutableList<Int>> = ArrayList() for (i in 0 until n) { graph.add(ArrayList()) } // build graph for (conn in connections) { val x = conn[0] val y = conn[1] graph[x].add(y) graph[y].add(x) } // record rank val rank = IntArray(n) // store result val res: MutableList<List<Int>> = ArrayList() dfs(graph, 0, 1, -1, rank, res) return res } // rank[] records the each node's smallest rank(min (it's natural rank, neighbors's smallest // rank)) private fun dfs( graph: List<MutableList<Int>>, node: Int, time: Int, parent: Int, rank: IntArray, res: MutableList<List<Int>> ): Int { if (rank[node] > 0) { return rank[node] } // record the current natural rank for current node rank[node] = time for (nei in graph[node]) { // skip the parent, since this is undirected graph if (nei == parent) { continue } // step1 : run dfs to get the rank of this nei, if it is visited before, it will reach // base case immediately val neiTime = dfs(graph, nei, time + 1, node, rank, res) // if neiTime is strictly larger than current node's rank, there is no cycle, // connections between node and nei is a critically connection. if (neiTime > time) { res.add(listOf(nei, node)) } // keep updating current node's rank with nei's smaller ranks rank[node] = Math.min(rank[node], neiTime) } // return current node's rank to caller return rank[node] } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,113
LeetCode-in-Kotlin
MIT License
src/main/kotlin/algorithms/sorting/merge_sort/MergeSort.kt
AANikolaev
273,465,105
false
{"Java": 179737, "Kotlin": 13961}
package algorithms.sorting.merge_sort import algorithms.sorting.InplaceSort class MergeSort : InplaceSort { override fun sort(values: IntArray) { val sortedValues = mergeSort(values) for (i in values.indices) { values[i] = sortedValues[i] } } private fun mergeSort(ar: IntArray): IntArray { // Base case is when a single element (which is already sorted) val n = ar.size if (n <= 1) return ar // Split array into two parts and recursively sort them val left = mergeSort(ar.copyOfRange(0, n / 2)) val right = mergeSort(ar.copyOfRange(n / 2, n)) // Combine the two arrays into one larger array return merge(left, right) } // Merge two sorted arrays into a larger sorted array private fun merge(ar1: IntArray, ar2: IntArray): IntArray { val n1 = ar1.size val n2 = ar2.size val n = n1 + n2 var i1 = 0 var i2 = 0 val ar = IntArray(n) for (i in 0 until n) { if (i1 == n1) { ar[i] = ar2[i2++] } else if (i2 == n2) { ar[i] = ar1[i1++] } else { if (ar1[i1] < ar2[i2]) { ar[i] = ar1[i1++] } else { ar[i] = ar2[i2++] } } } return ar } }
0
Java
0
0
f9f0a14a5c450bd9efb712b28c95df9a0d7d589b
1,401
Algorithms
MIT License
kotest-mpp/src/commonMain/kotlin/io/kotest/mpp/reflection.kt
ca-r0-l
258,232,982
true
{"Kotlin": 2272378, "HTML": 423, "Java": 153}
package io.kotest.mpp import kotlin.reflect.KClass /** * Returns the longest possible name available for this class. * That is, in order, the FQN, the simple name, or toString. */ fun KClass<*>.bestName(): String = fqn() ?: simpleName ?: this.toString() /** * Returns the fully qualified name for this class, or null */ expect fun KClass<*>.fqn(): String? /** * Returns the annotations on this class or empty list if not supported */ expect fun KClass<*>.annotations(): List<Annotation> /** * Finds the first annotation of type T on this class, or returns null if annotations * are not supported on this platform or the annotation is missing. */ inline fun <reified T> KClass<*>.annotation(): T? = annotations().filterIsInstance<T>().firstOrNull() inline fun <reified T> KClass<*>.hasAnnotation(): Boolean = annotations().filterIsInstance<T>().isNotEmpty() /** * Returns true if this KClass is a data class, false if it is not, or null if the functionality * is not supported on the platform. */ expect val <T : Any> KClass<T>.isDataClass: Boolean? /** * Returns the names of the parameters if supported. Eg, for `fun foo(a: String, b: Boolean)` on the JVM * it would return [a, b] and on unsupported platforms an empty list. */ expect val Function<*>.paramNames: List<String>
1
null
0
1
e176cc3e14364d74ee593533b50eb9b08df1f5d1
1,301
kotest
Apache License 2.0
ceria/18/src/main/kotlin/Solution.kt
VisionistInc
317,503,410
false
null
import java.io.File fun main(args : Array<String>) { val input = File(args.first()).readLines() println("Solution 1: ${solution1(input)}") println("Solution 2: ${solution2(input)}") } private fun solution1(input :List<String>) :Long { var total = 0L for (line in input) { total += evalExpression(line, true) } return total } private fun solution2(input :List<String>) :Long { var total = 0L for (line in input) { total += evalExpression(line, false) } return total } private fun evalExpression(line :String, normalPrecedence :Boolean) : Long { var exp = StringBuilder(line) while (exp.contains("(")) { var openParen = exp.indexOf("(") var closeParen = exp.indexOf(")") while (exp.substring(openParen + 1, closeParen).contains("(")) { openParen = exp.indexOf("(", openParen + 1) } val evaluated = eval(exp.substring( openParen + 1, closeParen).trim(), normalPrecedence).toString() exp = StringBuilder(exp.replaceRange(openParen, closeParen + 1, evaluated)) } return eval(exp.toString(), normalPrecedence) } private fun eval(exp :String, normalPrecedence :Boolean) :Long { var left = 0L if (normalPrecedence) { val parts = exp.split(" ") left = parts[0].toLong() for (n in 1..parts.size - 1 step 2) { when (parts[n]) { "+" -> { left += parts[n + 1].toLong() } "*" -> { left *= parts[n + 1].toLong() } } } } else { var newExp = StringBuilder(exp) while (newExp.contains("+")) { val parts = newExp.split(" ") newExp = StringBuilder() for (n in 1..parts.size - 1 step 2) { if (parts[n].equals("+")) { var sum = parts[n - 1].toLong() + parts[n + 1].toLong() newExp.append(sum) newExp.append(" ") for (i in n + 2..parts.size - 1) { newExp.append(parts[i]) newExp.append(" ") } break } else { newExp.append(parts[n - 1]) newExp.append(" ") newExp.append(parts[n]) newExp.append(" ") } } } if (newExp.contains("*")) { val parts = newExp.toString().trim().split(" ") left = parts[0].toLong() for (n in 1..parts.size - 1 step 2) { left *= parts[n + 1].toLong() } } else { left = newExp.toString().trim().toLong() } } return left }
0
Rust
0
0
002734670384aa02ca122086035f45dfb2ea9949
2,404
advent-of-code-2020
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/ScrambleString.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 /** * 87. Scramble String * @see <a href="https://leetcode.com/problems/scramble-string/">Source</a> */ fun interface ScrambleString { fun isScramble(s1: String, s2: String): Boolean } class ScrambleStringDP : ScrambleString { override fun isScramble(s1: String, s2: String): Boolean { if (s1.length != s2.length) return false val len: Int = s1.length /** * Let F(i, j, k) = whether the substring S1[i..i + k - 1] is a scramble of S2[j..j + k - 1] or not * Since each of these substrings is a potential node in the tree, we need to check for all possible cuts. * Let q be the length of a cut (hence, q < k), then we are in the following situation: * * S1 [ x1 | x2 ] * i + q i + k - 1 * * here we have two possibilities: * * S2 [ y1 | y2 ] * j + q j + k - 1 * * or * * S2 [ y1 | y2 ] * j j + k - q j + k - 1 * * which in terms of F means: * * F(i, j, k) = for some 1 <= q < k we have: * (F(i, j, q) AND F(i + q, j + q, k - q)) OR (F(i, j + k - q, q) AND F(i + q, j, k - q)) * * Base case is k = 1, where we simply need to check for S1[i] and S2[j] to be equal * */ /** * Let F(i, j, k) = whether the substring S1[i..i + k - 1] is a scramble of S2[j..j + k - 1] or not * Since each of these substrings is a potential node in the tree, we need to check for all possible cuts. * Let q be the length of a cut (hence, q < k), then we are in the following situation: * * S1 [ x1 | x2 ] * i + q i + k - 1 * * here we have two possibilities: * * S2 [ y1 | y2 ] * j + q j + k - 1 * * or * * S2 [ y1 | y2 ] * j j + k - q j + k - 1 * * which in terms of F means: * * F(i, j, k) = for some 1 <= q < k we have: * (F(i, j, q) AND F(i + q, j + q, k - q)) OR (F(i, j + k - q, q) AND F(i + q, j, k - q)) * * Base case is k = 1, where we simply need to check for S1[i] and S2[j] to be equal */ val f = Array(len) { Array(len) { BooleanArray( len + 1, ) } } for (k in 1..len) { var i = 0 while (i + k <= len) { var j = 0 while (j + k <= len) { if (k == 1) { f[i][j][k] = s1[i] == s2[j] } else { var q = 1 while (q < k && !f[i][j][k]) { f[i][j][k] = f[i][j][q] && f[i + q][j + q][k - q] || f[i][j + k - q][q] && f[i + q][j][k - q] ++q } } ++j } ++i } } return f[0][0][len] } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,993
kotlab
Apache License 2.0
src/main/kotlin/Day12.kt
i-redbyte
433,743,675
false
{"Kotlin": 49932}
import java.util.* const val START = "start" const val END = "end" val ALPHABET = 'a'..'z' fun makeGraph(data: List<String>): HashMap<String, HashSet<String>> { val graph = HashMap<String, HashSet<String>>() for (s in data) { val (x, y) = s.split("-") graph.getOrPut(x) { HashSet() }.add(y) graph.getOrPut(y) { HashSet() }.add(x) } return graph } fun main() { val graph = makeGraph(readInputFile("day12")) fun part1(): Int { var result = 0 val vs = HashSet<String>() fun search(s: String) { if (s == END) { result++ return } for (b in graph[s]!!) { if (b == START) continue val small = b[0] in ALPHABET if (small) { if (b in vs) continue vs += b } search(b) if (small) vs -= b } } search(START) return result } fun part2(): Int { var result = 0 val vs = HashSet<String>() fun search(s: String, vt: Boolean) { if (s == END) { result++ return } for (b in graph[s]!!) { if (b == START) continue val small = b[0] in ALPHABET var nvt = vt if (small) { if (b in vs) { if (vt) continue nvt = true } else { vs += b } } search(b, nvt) if (small && nvt == vt) vs -= b } } search(START, false) return result } println("Result part1: ${part1()}") println("Result part2: ${part2()}") }
0
Kotlin
0
0
6d4f19df3b7cb1906052b80a4058fa394a12740f
1,881
AOC2021
Apache License 2.0
src/adventOfCode/day11Problem.kt
cunrein
159,861,371
false
null
package adventOfCode data class PowerGrid(val xMax: Int, val yMax: Int, val sn: Int) { val grid = Array(xMax) { Array(yMax) { 0 } } init { for (x in 0 until xMax) { for (y in 0 until yMax) { grid[x][y] = powerLevel(sn, x, y) } } } private fun powerLevel(sn: Int, x: Int, y: Int): Int { val rackId = x + 10 var powerLevel = rackId * y powerLevel += sn powerLevel *= rackId val out = getHundredthPlace(powerLevel) - 5 return out } private fun getHundredthPlace(input: Int): Int { val s = input.toString() return if (s.length >= 3) s[s.length - 3].toString().toInt() else 0 } } fun gridSum(grid: PowerGrid, topLeftX: Int, topLeftY: Int, size: Int): Int { var result = 0 for (y in topLeftY + size - 1 downTo topLeftY) { for (x in topLeftX + size - 1 downTo topLeftX) { result += grid.grid[x][y] } } return result } data class Quad(val x: Int, val y: Int, val power: Int, val size: Int) { override fun toString(): String { return "($x, $y, $size, $power)" } } fun getMostPowerful3x3Grid(powerGrid: PowerGrid): Quad { var maxSum = Integer.MIN_VALUE var cornerX = 0 var cornerY = 0 var sqSize = 0 //val size = 3 for (size in 1..300) { for (y in 0 until powerGrid.yMax - size) { for (x in 0 until powerGrid.xMax - size) { val sum = gridSum(powerGrid, x, y, size) if (sum > maxSum) { maxSum = sum cornerX = x cornerY = y sqSize = size } } } } return Quad(cornerX, cornerY, maxSum, sqSize) } fun main(args: Array<String>) { println(getMostPowerful3x3Grid(PowerGrid(300, 300, 8772))) }
0
Kotlin
0
0
3488ccb200f993a84f1e9302eca3fe3977dbfcd9
1,896
ProblemOfTheDay
Apache License 2.0
Algorithm/HackerRank/src/OrganizingContainersOfBalls.kt
chaking
180,269,329
false
{"JavaScript": 118156, "HTML": 97206, "Jupyter Notebook": 93471, "C++": 19666, "Kotlin": 14457, "Java": 8536, "Python": 4928, "Swift": 3893, "Makefile": 2257, "Scala": 890, "Elm": 191, "CSS": 56}
import java.io.* import java.math.* import java.security.* import java.text.* import java.util.* import java.util.concurrent.* import java.util.function.* import java.util.regex.* import java.util.stream.* import kotlin.collections.* import kotlin.comparisons.* import kotlin.io.* import kotlin.jvm.* import kotlin.jvm.functions.* import kotlin.jvm.internal.* import kotlin.ranges.* import kotlin.sequences.* import kotlin.text.* // Complete the organizingContainers function below. fun organizingContainers(container: Array<Array<Int>>) : String = when (MyOrganizingContainers(container)) { true -> "Possible" else -> "Impossible" } fun MyOrganizingContainers(containers: Array<Array<Int>>): Boolean { val cons = Array(containers.size) { 0 } val types = Array(containers.size) { 0 } containers.forEachIndexed { containerIndex, container -> container.forEachIndexed { typeIndex, type -> cons[containerIndex] += type types[typeIndex] += type } } println(Arrays.deepToString(cons)) println(Arrays.deepToString(types)) val consList = cons.sortedArray().toList() val typesList = types.sortedArray().toList() return consList == typesList } fun main(args: Array<String>) { val inputs = listOf( arrayOf(arrayOf(1, 3, 1), arrayOf(2, 1, 2), arrayOf(3, 3, 3)) , arrayOf(arrayOf(0, 2, 1), arrayOf(1, 1, 1), arrayOf(2, 0, 0)) ) inputs .map { organizingContainers(it) } .forEach { println(it) } }
0
JavaScript
0
0
a394f100155fa4eb1032c09cdc85816b7104804b
1,522
study
MIT License
src/main/kotlin/de/niemeyer/aoc2022/Day21.kt
stefanniemeyer
572,897,543
false
{"Kotlin": 175820, "Shell": 133}
/** * Advent of Code 2022, Day 21: Monkey Math * Problem Description: https://adventofcode.com/2022/day/21 */ package de.niemeyer.aoc2022 import de.niemeyer.aoc.utils.Resources.resourceAsList import de.niemeyer.aoc.utils.getClassName fun main() { val root = "root" val human = "humn" abstract class MonkeyMath(val name: String) { abstract fun calc(): Long abstract fun restoreResult(result: Long): Long abstract fun containsName(searchName: String): Boolean fun containsHuman() = containsName(human) fun isHuman() = name == human } var monkeys: Map<String, MonkeyMath> = mapOf() class MonkeyYell(name: String, val number: Long) : MonkeyMath(name) { override fun calc(): Long = number override fun restoreResult(result: Long): Long = error("don't call restoreResult on MonkeyYell") override fun containsName(searchName: String): Boolean = name == searchName } class MonkeyCalc( name: String, val left: String, val right: String, val func: (a: Long, b: Long) -> Long, val inverseFunc: (a: Long, b: Long) -> Long, val associative: Boolean ) : MonkeyMath(name) { val leftMonkey by lazy { monkeys.getValue(left) } val rightMonkey by lazy { monkeys.getValue(right) } override fun calc(): Long = func(leftMonkey.calc(), rightMonkey.calc()) override fun restoreResult(result: Long): Long { return if (leftMonkey.isHuman()) { val rightResult = rightMonkey.calc() val newResult = inverseFunc(result, rightResult) newResult } else if (rightMonkey.isHuman()) { val leftResult = leftMonkey.calc() val newResult = if (associative) { inverseFunc(result, leftResult) } else { func(leftResult, result) } newResult } else if (leftMonkey.containsHuman()) { val rightResult = rightMonkey.calc() val newResult = inverseFunc(result, rightResult) val leftResult = leftMonkey.restoreResult(newResult) leftResult } else if (rightMonkey.containsHuman()) { val leftResult = leftMonkey.calc() val newResult = if (associative) { inverseFunc(result, leftResult) } else { func(leftResult, result) } val rightResult = rightMonkey.restoreResult(newResult) rightResult } else { result } } override fun containsName(searchName: String): Boolean = name == searchName || monkeys.getValue(left).containsName(searchName) || monkeys.getValue(right) .containsName(searchName) } fun createMonkey(input: String): MonkeyMath { val monkeyName = input.substringBefore(":") val params = input.substringAfter(": ").split(" ") if (params.size == 1) { return MonkeyYell(monkeyName, params[0].toLong()) } val left = params.first() val right = params.last() return when (params[1]) { "+" -> MonkeyCalc(monkeyName, left, right, Long::plus, Long::minus, associative = true) "-" -> MonkeyCalc(monkeyName, left, right, Long::minus, Long::plus, associative = false) "*" -> MonkeyCalc(monkeyName, left, right, Long::times, Long::div, associative = true) "/" -> MonkeyCalc(monkeyName, left, right, Long::div, Long::times, associative = false) else -> error("unknown operator: ${params[1]}") } } fun parse(input: List<String>): Map<String, MonkeyMath> = input.map { createMonkey(it) }.associateBy { it.name } fun part1(input: List<String>): Long { monkeys = parse(input) return monkeys.getValue(root).calc() } fun part2(input: List<String>): Long { monkeys = parse(input) val rootMonkey = monkeys.getValue(root) if (rootMonkey is MonkeyCalc) { val leftMonkey = rootMonkey.leftMonkey val rightMonkey = rootMonkey.rightMonkey val noHumanResult: Long val humanResult: Long val humanLeft = leftMonkey.containsHuman() val humanRight = rightMonkey.containsHuman() check(humanLeft || humanRight) { "'$human' not found" } check(!(humanLeft && humanRight)) { "two '$human' found" } if (humanLeft) { // calculate the tree w/o the human noHumanResult = rightMonkey.calc() humanResult = leftMonkey.restoreResult(noHumanResult) } else { noHumanResult = leftMonkey.calc() humanResult = rightMonkey.restoreResult(noHumanResult) } return humanResult } error("root monkey is not a MonkeyCalc") } val name = getClassName() val testInput = resourceAsList(fileName = "${name}_test.txt") val puzzleInput = resourceAsList(fileName = "${name}.txt") check(part1(testInput) == 152L) val puzzleResultPart1 = part1(puzzleInput) println(puzzleResultPart1) check(puzzleResultPart1 == 84_244_467_642_604L) check(part2(testInput) == 301L) val puzzleResultPart2 = part2(puzzleInput) println(puzzleResultPart2) check(puzzleResultPart2 == 3_759_569_926_192L) }
0
Kotlin
0
0
ed762a391d63d345df5d142aa623bff34b794511
5,587
AoC-2022
Apache License 2.0
src/datastructure/heap/StreamMax.kt
minielectron
332,678,510
false
{"Java": 127791, "Kotlin": 48336}
package datastructure.heap /** * <> Heap: Maximum Element in a Stream Implement a function named streamMax that processes a stream of integers and returns the maximum number encountered so far for each input number. This function should take in an array of integers and return a list of integers. Given an array of integers, your function should iterate over the array and for each number, it should find the maximum number in the array up until that point, including the current number. int[] nums = {1, 5, 2, 9, 3, 6, 8}; List<Integer> result = streamMax(nums); // Expected output: [1, 5, 5, 9, 9, 9, 9] // Explanation: The maximum number for the first number is 1, // for the first two numbers is 5, for the first three numbers is 5, and so on. * */ class StreamMax { fun findStreamMax(nums: IntArray): IntArray { val result = IntArray(nums.size) { Int.MIN_VALUE } val heap = Heap() nums.forEachIndexed { index, value -> heap.insert(value) result[index] = heap.getHeap()[0] } return result } } fun main() { val streamMax = StreamMax() // Test case 1 // Test case 1 val nums1 = intArrayOf(1, 5, 2, 9, 3, 6, 8) println("Test case 1:") println("Input: [1, 5, 2, 9, 3, 6, 8]") println("Expected output: [1, 5, 5, 9, 9, 9, 9]") val output = streamMax.findStreamMax(nums1) output.forEach { print("$it, ") } println() // Test case 2 // Test case 2 val nums2 = intArrayOf(10, 2, 5, 1, 0, 11, 6) println("Test case 2:") println("Input: [10, 2, 5, 1, 0, 11, 6]") println("Expected output: [10, 10, 10, 10, 10, 11, 11]") val output2 = streamMax.findStreamMax(nums2) output2.forEach { print("$it, ") } println() }
0
Java
0
0
f2aaff0a995071d6e188ee19f72b78d07688a672
1,764
data-structure-and-coding-problems
Apache License 2.0
hacker-rank/sorting/FraudulentActivityNotifications.kt
piazentin
62,427,919
false
{"Python": 34824, "Jupyter Notebook": 29307, "Kotlin": 19570, "C++": 2465, "R": 2425, "C": 158}
// https://www.hackerrank.com/challenges/fraudulent-activity-notifications/problem fun main() { val (_, days) = readLine().orEmpty().trim().split(" ").map(String::toInt) val expenditures = readLine().orEmpty().trim().split(" ").map(String::toInt).toTypedArray() fraudulentActivityNotifications(days, expenditures) } fun fraudulentActivityNotifications(days: Int, expenditures: Array<Int>) { val countArray = IntArray(200) var qty = 0 // initialize for (i in 0 until days) { countArray[expenditures[i]]++ } for (i in days until expenditures.size) { if (expenditures[i] >= median(days, countArray)) qty++ countArray[expenditures[i - days]]-- countArray[expenditures[i]]++ } println(qty) } fun median(days: Int, countArray: IntArray): Int { var count = 0 val even = days % 2 == 0 val medianIdx = days / 2 var foundFirst = false var median = 0 for (countIdx in 0 until countArray.size) { count += countArray[countIdx] if (!even) { if (count > medianIdx) { median = countIdx * 2 break } } else { if (countArray[countIdx] > 0 && count == medianIdx) { median = countIdx foundFirst = true } else if (countArray[countIdx] > 0 && count > medianIdx) { if (foundFirst) median += countIdx else median = countIdx * 2 break } } } return median }
0
Python
0
0
db490b1b2d41ed6913b4cacee1b4bb40e15186b7
1,560
programming-challenges
MIT License
src/Day07.kt
jsebasct
572,954,137
false
{"Kotlin": 29119}
import java.math.BigInteger data class FileDevice( val name: String, var size: Int = 0, val content: MutableMap<String, FileDevice>? = null, val isDirectory: Boolean = false, val parentDirectory: FileDevice? = null, ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as FileDevice if (name != other.name) return false if (size != other.size) return false return true } override fun hashCode(): Int { var result = name.hashCode() result = 31 * result + size return result } fun getTotalSize(): Int { return if (this.isDirectory) { this.content?.toList()?.fold(0) { acc, element -> acc + element.second.getTotalSize() } ?: 0 } else { this.size } } fun setFolderSizes() { if (this.isDirectory) { val size = this.content?.toList()?.fold(0) { acc, element -> if (element.second.isDirectory) { element.second.setFolderSizes() } acc + element.second.getTotalSize() } ?: 0 this.size = size } else { this.size } } fun getDirectoriesWithAtMost(maxSize: Int): BigInteger { return this.content?.values?.fold(BigInteger.ZERO) { acc, element -> val temp = if (element.isDirectory && element.size <= maxSize) element.size.toBigInteger() else BigInteger.ZERO val temp2 = if (element.isDirectory) element.getDirectoriesWithAtMost(maxSize) else BigInteger.ZERO acc + temp + temp2 } ?: BigInteger.ZERO } fun getAllFolders(acc: MutableList<FileDevice>) { if (this.isDirectory) { acc.add(this) this.content?.values?.forEach { it.getAllFolders(acc) } } } } fun main() { fun parseInput(input: List<String>, rootDirectory: FileDevice) { var currentDirectory = rootDirectory input.forEachIndexed { index, line -> if (index > 0) { //&& index < 19 // println(line) // check if command if (line.startsWith("$")) { // means its a command // tehre are two types of commands if (line.contains("cd")) { val (_, _, nameDirectory) = line.split(" ") // println("change to this directory: $nameDirectory") if (nameDirectory == "..") { // println("que hacemos ?") currentDirectory = currentDirectory.parentDirectory!! } else { currentDirectory = currentDirectory.content!![nameDirectory]!! } } else { // ls // println("ahi viene una lista de contenido") } } else { // salida de un comando LS if (line.startsWith("dir")) { val (_, name) = line.split(" ") currentDirectory.content!![name] = FileDevice( name = name, isDirectory = true, content = mutableMapOf(), parentDirectory = currentDirectory ) } else { val (size, name) = line.split(" ") currentDirectory.content!![name] = FileDevice( name = name, size = size.toInt(), parentDirectory = currentDirectory ) } } } } } fun part71(input: List<String>, rootDirectory: FileDevice): BigInteger { parseInput(input, rootDirectory) rootDirectory.setFolderSizes() val res1 = rootDirectory.getDirectoriesWithAtMost(100000) println("total size: $res1") return res1 } fun part72(input: List<String>, rootDirectory: FileDevice): Int { val requiredUnusedSpace = 30000000 parseInput(input, rootDirectory) rootDirectory.setFolderSizes() val unusedSpace = 70000000 - rootDirectory.size val neededAtLeast = 30000000 - unusedSpace println("needed: $neededAtLeast") val acc = mutableListOf<FileDevice>() rootDirectory.getAllFolders(acc) val res2 = acc.filter { it.size >= neededAtLeast}.minBy { it.size } // accumulatorFiltered.forEach { println("${it.name}: ${it.size}") } // val res1 = rootDirectory.getDirectoriesWithAtMost(100000) // println("total size: $res1") return res2.size } val input = readInput("Day07_test") val rootDirectory = FileDevice( name="root/", content = mutableMapOf<String, FileDevice>(), isDirectory = true ) val part71Response = part71(input, rootDirectory) // check(part71Response == 95437.toBigInteger()) val rootDirectory2 = FileDevice( name="root/", content = mutableMapOf<String, FileDevice>(), isDirectory = true ) val part72Response = part72(input, rootDirectory2) println("response part2: $part72Response") // check(part72Response == 24933642) }
0
Kotlin
0
0
c4a587d9d98d02b9520a9697d6fc269509b32220
5,530
aoc2022
Apache License 2.0
src/Day03.kt
topr
572,937,822
false
{"Kotlin": 9662}
fun main() { val allItems = (('a'..'z') + ('A'..'Z')).toSet() fun commonItem(compartments: Iterable<String>) = compartments .map(CharSequence::toSet) .fold(allItems) { acc, compartment -> acc.intersect(compartment) } .first() fun priority(item: Char): Int = item.code.inc() - if (item.isUpperCase()) 'A'.code - priority('z') else 'a'.code fun part1(input: List<String>) = input .map { it.chunked(it.length / 2) } .map(::commonItem) .sumOf(::priority) fun part2(input: List<String>) = input .chunked(3) .map(::commonItem) .sumOf(::priority) val testInput = readInputLines("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInputLines("Day03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8c653385c9a325f5efa2895e94830c83427e5d87
915
advent-of-code-kotlin-2022
Apache License 2.0
src/Day23.kt
amelentev
573,120,350
false
{"Kotlin": 87839}
fun main() { val input = readInput("Day23") fun solve(part2: Boolean): Int { val map = input.map { it.toCharArray() } var res = 0 fun dfs(i: Int, j: Int, d: Int) { if (i !in map.indices || j !in map[i].indices || map[i][j] == '#' || map[i][j] == 'o') return if (i == map.lastIndex && j == map[i].lastIndex-1) { if (res < d) { res = d println(res) } return } val c = map[i][j] map[i][j] = 'o' if (part2) { dfs(i, j+1, d+1) dfs(i+1, j, d+1) dfs(i, j-1, d+1) dfs(i-1, j, d+1) } else { when (c) { '>' -> dfs(i, j+1, d+1) 'v' -> dfs(i+1, j, d+1) '<' -> dfs(i, j-1, d+1) '^' -> dfs(i+1, j, d+1) '.' -> { dfs(i, j+1, d+1) dfs(i+1, j, d+1) dfs(i, j-1, d+1) dfs(i-1, j, d+1) } else -> error(c) } } map[i][j] = c } dfs(0, 1, 0) return res } println("1:\t" + solve(false)) println("2:\t" + solve(true)) }
0
Kotlin
0
0
a137d895472379f0f8cdea136f62c106e28747d5
1,389
advent-of-code-kotlin
Apache License 2.0
aoc-2020/src/commonMain/kotlin/fr/outadoc/aoc/twentytwenty/Day12.kt
outadoc
317,517,472
false
{"Kotlin": 183714}
package fr.outadoc.aoc.twentytwenty import fr.outadoc.aoc.scaffold.Day import fr.outadoc.aoc.scaffold.readDayInput import kotlin.math.* class Day12 : Day<Long> { private sealed class Action { data class Add(val direction: Direction, val units: Int) : Action() data class TurnLeft(val angle: Int) : Action() data class TurnRight(val angle: Int) : Action() data class MoveForward(val units: Int) : Action() } private val actions: Sequence<Action> = readDayInput() .lineSequence() .map { action -> val value = action.drop(1).toInt() when (action.first()) { 'N' -> Action.Add(Direction.NORTH, value) 'S' -> Action.Add(Direction.SOUTH, value) 'E' -> Action.Add(Direction.EAST, value) 'W' -> Action.Add(Direction.WEST, value) 'L' -> Action.TurnLeft(value) 'R' -> Action.TurnRight(value) 'F' -> Action.MoveForward(value) else -> throw IllegalArgumentException() } } // region Direction private enum class Direction { NORTH, SOUTH, EAST, WEST } private val Direction.asPosition: Position get() = when (this) { Direction.NORTH -> (Position(x = 0, y = 1)) Direction.SOUTH -> (Position(x = 0, y = -1)) Direction.EAST -> (Position(x = 1, y = 0)) Direction.WEST -> (Position(x = -1, y = 0)) } private fun Direction.rotate(angle: Int): Direction = asPosition.rotateRelativeToOrigin(angle).asDirection // endregion // region Position private data class Position(val x: Int, val y: Int) { val manhattanDistance: Long get() = abs(x.toLong()) + abs(y.toLong()) } private val Position.asDirection: Direction get() = when (x to y) { 0 to 1 -> Direction.NORTH 0 to -1 -> Direction.SOUTH 1 to 0 -> Direction.EAST -1 to 0 -> Direction.WEST else -> throw IllegalArgumentException() } private operator fun Position.plus(other: Position): Position = copy(x = x + other.x, y = y + other.y) private operator fun Position.times(times: Int): Position = copy(x = x * times, y = y * times) private fun Position.rotateRelativeToOrigin(angle: Int): Position { val sin = sin(-angle * PI / 180) val cos = cos(-angle * PI / 180) return Position( x = (x * cos - y * sin).roundToInt(), y = (x * sin + y * cos).roundToInt() ) } // endregion private data class State1( val shipPosition: Position, val currentDirection: Direction ) private fun State1.reduce(action: Action) = when (action) { is Action.Add -> copy(shipPosition = shipPosition + (action.direction.asPosition * action.units)) is Action.TurnLeft -> copy(currentDirection = currentDirection.rotate(-action.angle)) is Action.TurnRight -> copy(currentDirection = currentDirection.rotate(action.angle)) is Action.MoveForward -> copy(shipPosition = shipPosition + (currentDirection.asPosition * action.units)) } private data class State2( val shipPosition: Position, val waypointRelPos: Position ) private fun State2.reduce(action: Action) = when (action) { is Action.Add -> copy(waypointRelPos = waypointRelPos + (action.direction.asPosition * action.units)) is Action.TurnLeft -> copy(waypointRelPos = waypointRelPos.rotateRelativeToOrigin(-action.angle)) is Action.TurnRight -> copy(waypointRelPos = waypointRelPos.rotateRelativeToOrigin(action.angle)) is Action.MoveForward -> copy(shipPosition = shipPosition + (waypointRelPos * action.units)) } override fun step1(): Long { val initialState = State1( shipPosition = Position(x = 0, y = 0), currentDirection = Direction.EAST ) val finalState = actions.fold(initialState) { acc, action -> acc.reduce(action) } return finalState.shipPosition.manhattanDistance } override fun step2(): Long { val initialState = State2( shipPosition = Position(x = 0, y = 0), waypointRelPos = Position(x = 10, y = 1) ) val finalState = actions.fold(initialState) { acc, action -> acc.reduce(action) } return finalState.shipPosition.manhattanDistance } override val expectedStep1: Long = 1294 override val expectedStep2: Long = 20592 }
0
Kotlin
0
0
54410a19b36056a976d48dc3392a4f099def5544
4,720
adventofcode
Apache License 2.0
src/chapter5/section1/SpecificAlphabet.kt
w1374720640
265,536,015
false
{"Kotlin": 1373556}
package chapter5.section1 import chapter3.section4.LinearProbingHashST /** * 指定具体字母的字母表 */ class SpecificAlphabet(s: String) : Alphabet { private val st = LinearProbingHashST<Char, Int>() private val reverseST = LinearProbingHashST<Int, Char>() private var size = 0 init { for (i in s.indices) { // 字母表不能包含重复字符 check(!st.contains(s[i])) { "The alphabet cannot contain repeated characters '${s[i]}'" } st.put(s[i], size) reverseST.put(size, s[i]) size++ } check(st.size() == size && reverseST.size() == size) } /** * 获取字母表中索引位置的字符 */ override fun toChar(index: Int): Char { require(index < size) return reverseST.get(index)!! } /** * 获取c的索引,在0到R-1之间 */ override fun toIndex(c: Char): Int { require(st.contains(c)) return st.get(c)!! } /** * c在字母表之中吗 */ override fun contains(c: Char): Boolean { return st.contains(c) } /** * 基数(字母表中的字符数量) */ override fun R(): Int { return size } /** * 表示一个索引所需的比特数 */ override fun lgR(): Int { // logR应该大于等于R的以2为底的log值 var logR = 0 var t = size - 1 while (t != 0) { logR++ // 右移一位,参考练习1.1.14 t = t shr 1 } return logR } /** * 将s转换为R进制的整数 */ override fun toIndices(s: String): IntArray { return IntArray(s.length) { toIndex(s[it]) } } /** * 将R进制的整数转换为基于该字母表的字符串 */ override fun toChars(indices: IntArray): String { return String(CharArray(indices.size) { toChar(indices[it]) }) } } fun main() { val alphabet = SpecificAlphabet("abcdefg") println(alphabet.toChar(2)) println(alphabet.toIndex('d')) println(alphabet.contains('f')) println(alphabet.R()) println(alphabet.lgR()) println(alphabet.toChars(intArrayOf(6, 5, 4, 3, 2, 1, 0))) println(alphabet.toIndices("ccccfga").joinToString()) }
0
Kotlin
1
6
879885b82ef51d58efe578c9391f04bc54c2531d
2,362
Algorithms-4th-Edition-in-Kotlin
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/RepeatedNTimes.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 /** * N-Repeated Element in Size 2N Array * @see <a href="https://leetcode.com/problems/n-repeated-element-in-size-2n-array/">Source</a> */ fun interface RepeatedNTimes { operator fun invoke(arr: IntArray): Int } /** * Approach 1: Count * Time Complexity: O(N) * Space Complexity: O(N) */ class RepeatedNTimesCount : RepeatedNTimes { override operator fun invoke(arr: IntArray): Int { val count: MutableMap<Int, Int> = HashMap() for (x in arr) { count[x] = count.getOrDefault(x, 0) + 1 } for (k in count.keys) { count[k]?.let { kCount -> if (kCount > 1) { return k } } } return 0 } } /** * Approach 2: Compare * Time Complexity: O(N) * Space Complexity: O(1) */ class RepeatedNTimesCompare : RepeatedNTimes { override operator fun invoke(arr: IntArray): Int { for (k in 1..3) for (i in 0 until arr.size - k) if (arr[i] == arr[i + k]) return arr[i] return 0 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,689
kotlab
Apache License 2.0
src/main/kotlin/g0901_1000/s0928_minimize_malware_spread_ii/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0901_1000.s0928_minimize_malware_spread_ii // #Hard #Array #Depth_First_Search #Breadth_First_Search #Matrix #Union_Find // #2023_04_26_Time_716_ms_(100.00%)_Space_63.5_MB_(100.00%) import java.util.LinkedList import java.util.Queue class Solution { private val adj: MutableMap<Int, ArrayList<Int>> = HashMap() private var visited: MutableSet<Int>? = null private var count = 0 private fun bfs(ind: Int, initial: IntArray) { val q: Queue<Int> = LinkedList() for (i in initial.indices) { if (i != ind) { q.add(initial[i]) visited!!.add(initial[i]) } } while (q.isNotEmpty()) { val curr = q.poll() if (curr != initial[ind]) { count++ } val children = adj[curr] if (children != null) { for (child in children) { if (!visited!!.contains(child)) { q.add(child) visited!!.add(child) } } } } } fun minMalwareSpread(graph: Array<IntArray>, initial: IntArray): Int { val n = graph.size for (i in 0 until n) { adj.putIfAbsent(i, ArrayList()) for (j in 0 until n) { if (graph[i][j] == 1) { adj.getValue(i).add(j) } } } var min = n + 1 initial.sort() var node = initial[0] for (i in initial.indices) { visited = HashSet() val children = adj.getValue(initial[i]) adj.remove(initial[i]) bfs(i, initial) if (count < min) { min = count node = initial[i] } count = 0 adj[initial[i]] = children } return node } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,929
LeetCode-in-Kotlin
MIT License
src/main/kotlin/com/leetcode/P37.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package com.leetcode // https://github.com/antop-dev/algorithm/issues/459 class P37 { fun solveSudoku(board: Array<CharArray>) { solve(board, 0) } private fun solve(board: Array<CharArray>, pos: Int): Boolean { if (pos == 81) { return true } val y = pos / 9 val x = pos % 9 val set = possible(board, y, x) if (set.isEmpty()) { return false } val before = board[y][x] for (ch in set) { board[y][x] = ch val bool = solve(board, pos + 1) if (bool) return true } board[y][x] = before // backtracking return false } private fun possible(board: Array<CharArray>, y: Int, x: Int): Set<Char> { if (board[y][x] != '.') { return setOf(board[y][x]) } val set = mutableSetOf('1', '2', '3', '4', '5', '6', '7', '8', '9') // 나와 같은 행의 수 제거 for (i in 0 until 9) { val ch = board[i][x] if (ch != '0') { set -= ch } } // 나와 같은 열의 수 제거 for (i in 0 until 9) { val ch = board[y][i] if (ch != '.') { set -= ch } } // 나와 같은 칸의 수 제거 val startY = (y / 3) * 3 val startX = (x / 3) * 3 for (i in startY until startY + 3) { for (j in startX until startX + 3) { val ch = board[i][j] if (ch != '.') { set -= ch } } } return set } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
1,680
algorithm
MIT License
facebook/y2021/round1/a3.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package facebook.y2021.round1 private fun solve(M: Int = 1_000_000_007): Int { readLn() val s = readLn() var firstChar = 0.toChar() var lastChar = 0.toChar() var firstPos = -1 var lastPos = -1 var length = 0 var pairs = 0 var leftTicks = 0 var rightTicks = 0 var answer = 0 for (i in s.indices) { if (s[i] == 'F') { rightTicks = (rightTicks + pairs) % M answer = (answer + leftTicks) % M length = (length + 1) % M continue } if (s[i] == '.') { val oldPairs = pairs pairs = (2 * pairs) % M if (firstChar != 0.toChar()) { answer = ((2 * answer + (leftTicks + rightTicks).toLong() * length) % M).toInt() leftTicks = ((leftTicks * 2 + length.toLong() * oldPairs) % M).toInt() rightTicks = ((rightTicks * 2 + length.toLong() * oldPairs) % M).toInt() if (firstChar != lastChar) { pairs = (pairs + 1) % M answer = ((answer + (lastPos + 1).toLong() * (length - firstPos + M)) % M).toInt() leftTicks = (leftTicks + lastPos + 1) % M rightTicks = ((rightTicks.toLong() + length - firstPos + M) % M).toInt() } lastPos = (lastPos + length) % M } length = (2 * length) % M continue } if (firstChar == 0.toChar()) { firstChar = s[i] lastChar = s[i] firstPos = length lastPos = length length = (length + 1) % M continue } rightTicks = (rightTicks + pairs) % M answer = (answer + leftTicks) % M if (s[i] != lastChar) { leftTicks = (leftTicks + lastPos + 1) % M rightTicks = (rightTicks + 1) % M answer = (answer + lastPos + 1) % M pairs = (pairs + 1) % M } lastPos = length lastChar = s[i] length = (length + 1) % M } return answer } fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt()
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,817
competitions
The Unlicense
src/y2016/Day09.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2016 import util.readInput object Day09 { fun part1(input: List<String>) { input.forEach { println("${decompressedLength(it)} $it") } } private fun decompressedLength(str: String): Int { val firstStart = str.indexOf('(') if (firstStart == -1) { return str.length } val firstEnd = str.indexOf(')', startIndex = firstStart) val (len, repeats) = str.substring(firstStart + 1, firstEnd).split('x').map { it.toInt() } return firstStart + len * repeats + decompressedLength(str.drop(firstEnd + 1 + len)) } private fun decompressedLengthV2(str: String): Long { val firstStart = str.indexOf('(') if (firstStart == -1) { return str.length.toLong() } val firstEnd = str.indexOf(')', startIndex = firstStart) val (len, repeats) = str.substring(firstStart + 1, firstEnd).split('x').map { it.toInt() } val subExpanded = decompressedLengthV2(str.drop(firstEnd + 1).take(len)) return firstStart + repeats * subExpanded + decompressedLengthV2(str.drop(firstEnd + 1 + len)) } fun part2(input: List<String>) { input.forEach { println("${decompressedLengthV2(it)} $it") } } } fun main() { val testInput = """ ADVENT A(1x5)BC (3x3)XYZ A(2x2)BCD(2x2)EFG (6x1)(1x3)A X(8x2)(3x3)ABCY (25x3)(3x3)ABC(2x3)XY(5x2)PQRSTX(18x9)(3x2)TWO(5x7)SEVEN """.trimIndent().split("\n") println("------Tests------") println(Day09.part1(testInput)) println(Day09.part2(testInput)) println("------Real------") val input = readInput("resources/2016/day09") println(Day09.part1(input)) println(Day09.part2(input)) }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
1,795
advent-of-code
Apache License 2.0
kotlin.kt
darian-catalin-cucer
598,114,020
false
null
class BTree<Key : Comparable<Key>, Value> { private val t = 2 // Minimum degree of the B-Tree node private var root: Node<Key, Value>? = null private class Node<Key : Comparable<Key>, Value>(var n: Int = 0, var leaf: Boolean = false) { var keys = arrayOfNulls<Key>(2 * t - 1) var values = arrayOfNulls<Value>(2 * t - 1) var children = arrayOfNulls<Node<Key, Value>>(2 * t) // Insert key-value pair in this node // Split the node if it's full fun insertNonFull(key: Key, value: Value) { var i = n - 1 if (leaf) { while (i >= 0 && keys[i]!! > key) { keys[i + 1] = keys[i] values[i + 1] = values[i] i-- } keys[i + 1] = key values[i + 1] = value n++ } else { while (i >= 0 && keys[i]!! > key) { i-- } i++ if (children[i]!!.n == 2 * t - 1) { splitChild(i) if (keys[i]!! < key) { i++ } } children[i]!!.insertNonFull(key, value) } } // Split the ith child of this node private fun splitChild(i: Int) { val newNode = Node<Key, Value>(t - 1, leaf) val child = children[i] children[i] = newNode for (j in 0 until t - 1) { newNode.keys[j] = child!!.keys[j + t] newNode.values[j] = child.values[j + t] newNode.children[j] = child.children[j + t] } newNode.children[t - 1] = child!!.children[2 * t - 1] newNode.n = t - 1 child.n = t - 1 for (j in n downTo i + 1) { keys[j] = keys[j - 1] children[j + 1] = children[j] } keys[i] = child.keys[t - 1] children[i + 1] = newNode n++ } } // Insert key-value pair in the B-Tree fun insert(key: Key, value: Value) { val r = root if (r!!.n == 2 * t - 1) { val newNode = Node<Key, Value>(t = 1, leaf = false) root = newNode newNode.children[0] = r newNode.splitChild(0) newNode.insertNonFull(key, value) } else { r.insertNonFull(key, value) } }
0
Kotlin
0
0
acd9827f1ebe29bca71ebf1254f47eb6f1ba6c57
2,514
b-tree
MIT License
src/main/kotlin/g2501_2600/s2581_count_number_of_possible_root_nodes/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2501_2600.s2581_count_number_of_possible_root_nodes // #Hard #Hash_Table #Dynamic_Programming #Depth_First_Search #Tree // #2023_07_11_Time_1352_ms_(100.00%)_Space_138.7_MB_(100.00%) import java.util.ArrayList import java.util.HashSet @Suppress("NAME_SHADOWING") class Solution { private lateinit var parents: IntArray private lateinit var graph: Array<MutableList<Int>?> private lateinit var guess: Array<HashSet<Int>?> private var ans = 0 fun rootCount(edges: Array<IntArray>, guesses: Array<IntArray>, k: Int): Int { val n = edges.size + 1 graph = arrayOfNulls(n) guess = arrayOfNulls(n) for (i in 0 until n) { graph[i] = ArrayList() guess[i] = HashSet<Int>() } // Create tree for (i in edges.indices) { graph[edges[i][0]]!!.add(edges[i][1]) graph[edges[i][1]]!!.add(edges[i][0]) } // Create guess array for (i in guesses.indices) { guess[guesses[i][0]]!!.add(guesses[i][1]) } parents = IntArray(n) fill(0, -1) var c = 0 for (i in 1 until n) { if (guess[parents[i]]!!.contains(i)) c++ } if (c >= k) ans++ for (i in graph[0]!!) dfs(i, 0, c, k) return ans } // Fill the parent array private fun fill(v: Int, p: Int) { parents[v] = p for (child in graph[v]!!) { if (child == p) continue fill(child, v) } } // Use DFS to make all nodes as root one by one private fun dfs(v: Int, p: Int, c: Int, k: Int) { var c = c if (guess[p]!!.contains(v)) c-- if (guess[v]!!.contains(p)) c++ if (c >= k) ans++ for (child in graph[v]!!) if (child != p) dfs(child, v, c, k) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,837
LeetCode-in-Kotlin
MIT License
src/main/kotlin/day11/Day11.kt
mdenburger
317,466,663
false
null
import java.io.File import java.lang.Integer.max import kotlin.math.absoluteValue fun main() { val seatLayout = File("src/main/kotlin/day11/day11-input.txt").readLines().map { it.toCharArray() } var current = seatLayout var currentHashCode = current.contentHashCode() val found = mutableSetOf<Int>() while (!found.contains(currentHashCode)) { found.add(currentHashCode) current = current.nextSeatLayout() currentHashCode = current.contentHashCode() } println("Answer 1: " + current.occupiedSeatCount()) } private fun List<CharArray>.contentHashCode(): Int = fold(0) { result, line -> result + 31 * line.contentHashCode() } private fun List<CharArray>.nextSeatLayout(): List<CharArray> { val next = toMutableList().map { it.clone() } for (row in 0 until size) { for (column in 0 until width()) { when (get(row)[column]) { 'L' -> if (noSeatsAround(row, column)) { next[row][column] = '#' } '#' -> if (atLeastFourSeatsAround(row, column)) { next[row][column] = 'L' } } } } return next } private fun List<CharArray>.width() = first().size private fun List<CharArray>.noSeatsAround(row: Int, column: Int) = forSeatsAround(row, column, true) { false } private fun List<CharArray>.atLeastFourSeatsAround(row: Int, column: Int): Boolean { var count = 0 return forSeatsAround(row, column, false) { count += 1 if (count == 4) true else null } } private fun List<CharArray>.forSeatsAround(row: Int, column: Int, default: Boolean, block: List<CharArray>.() -> Boolean?): Boolean { for (dx in -1..1) { for (dy in -1..1) { val x = column + dy val y = row + dx if (!(x == column && y == row) && x >= 0 && x < width() && y >= 0 && y < size && get(y)[x] == '#') { val result = block() if (result != null) { return result } } } } return default } private fun List<CharArray>.occupiedSeatCount() = map { row -> row.count { it == '#' } }.sum() fun List<CharArray>.print() { forEach { println(it.joinToString("")) } }
0
Kotlin
0
0
b965f465cad30f949874aeeacd8631ca405d567e
2,300
aoc-2020
MIT License
src/main/kotlin/ru/amai/study/hackerrank/practice/interviewPreparationKit/sorting/fraud/ActivityNotifications.kt
slobanov
200,526,003
false
null
package ru.amai.study.hackerrank.practice.interviewPreparationKit.sorting.fraud import java.util.* private const val MAX_EXPENDITURE = 201 fun activityNotifications(expenditure: IntArray, d: Int): Int { val counts = buildCounts(expenditure, d) return (d until expenditure.size).count { i -> val median = median(counts, d) counts[expenditure[i]] += 1 counts[expenditure[i - d]] -= 1 (expenditure[i] >= 2 * median) } } private fun buildCounts(array: IntArray, size: Int): IntArray { val counts = IntArray(MAX_EXPENDITURE) array.take(size).forEach { counts[it] += 1 } return counts } private fun median(counts: IntArray, size: Int): Double { fun medianSupport(index: Int): Double { var currIndex = 0 var value = 0.0 for ((i, count) in counts.withIndex()) { if (index in (currIndex until (currIndex + count))) { value = i.toDouble() break } currIndex += count } return value } return when (size % 2) { 1 -> medianSupport(size / 2) else -> (medianSupport(size / 2 - 1) + medianSupport(size / 2)) / 2 } } fun main() { val scan = Scanner(System.`in`) val nd = scan.nextLine().split(" ") val d = nd[1].trim().toInt() val expenditure = scan.nextLine().split(" ").map { it.trim().toInt() }.toIntArray() val result = activityNotifications(expenditure, d) println(result) }
0
Kotlin
0
0
2cfdf851e1a635b811af82d599681b316b5bde7c
1,506
kotlin-hackerrank
MIT License
src/main/kotlin/Day07.kt
SimonMarquis
570,868,366
false
{"Kotlin": 50263}
import java.nio.file.Path import java.nio.file.Paths import kotlin.io.path.div class Day07(input: List<String>) { private val fs = FileSystem(input) fun part1() = fs.dirsWithSize() .filter { (_, size) -> size <= 100_000 }.values .sum() fun part2() = fs.dirsWithSize().let { dirs -> val minSpaceToFree = dirs.getValue(root) - 40_000_000 dirs.filter { (_, size) -> size >= minSpaceToFree }.values }.min() private class FileSystem(input: List<String>) { private val files: MutableList<Pair<Path, Long>> = mutableListOf() init { var pwd: Path = root input.foldInPlace(this) { line -> when { line == "\$ ls" -> Unit line.startsWith("dir ") -> Unit line.startsWith("\$ cd ") -> { when (val dir = line.substringAfterLast(" ")) { "/" -> pwd = root ".." -> pwd = pwd.parent else -> pwd /= dir } } else -> line.split(" ").let { (size, name) -> files += pwd / name to size.toLong() } } } } fun dirsWithSize() = files.foldInPlace(mutableMapOf<Path, Long>()) { (file, size) -> file.parents().forEach { compute(it) { _, acc -> (acc ?: 0) + size } } } } } private val root: Path = Paths.get("/") private fun Path.parents() = generateSequence(parent, Path::getParent)
0
Kotlin
0
0
a2129cc558c610dfe338594d9f05df6501dff5e6
1,570
advent-of-code-2022
Apache License 2.0
src/leetcode_study_badge/data_structure/Day15.kt
faniabdullah
382,893,751
false
null
package leetcode_study_badge.data_structure import data_structure.tree.TreeNode import data_structure.tree.TreeTraversal class Day15 { fun sortedArrayToBST(nums: IntArray): TreeNode? { return partition(0, nums.size - 1, nums) } private fun partition(left: Int, right: Int, nums: IntArray): TreeNode? { val middle = left + (right - left) / 2 if (left > right) return null val result: TreeNode? = TreeNode(nums[middle]) result?.left = partition(left, middle - 1, nums) result?.right = partition(middle + 1, right, nums) return result } //https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/submissions/ var preorderIndex = 0 private var inorderIndexMap: HashMap<Int, Int> = HashMap() fun buildTree(preorder: IntArray, inorder: IntArray): TreeNode? { preorderIndex = 0 inorderIndexMap = HashMap() for (i in inorder.indices) { inorderIndexMap[inorder[i]] = i } return arrayToTree(preorder, 0, preorder.size - 1) } private fun arrayToTree(preorder: IntArray, left: Int, right: Int): TreeNode? { if (left > right) return null val rootValue = preorder[preorderIndex++] val root = TreeNode(rootValue) root.left = arrayToTree(preorder, left, inorderIndexMap[rootValue]!! - 1) root.right = arrayToTree(preorder, inorderIndexMap[rootValue]!! + 1, right) return root } } fun main() { val result = Day15().sortedArrayToBST(intArrayOf(1, 2, 3, 4, 5, 6)) println(TreeTraversal().printLevelOrder(result)) }
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
1,648
dsa-kotlin
MIT License
leetcode/src/offer/middle/Offer67.kt
zhangweizhe
387,808,774
false
null
package offer.middle fun main() { // 剑指 Offer 67. 把字符串转换成整数 // https://leetcode.cn/problems/ba-zi-fu-chuan-zhuan-huan-cheng-zheng-shu-lcof/ println(strToInt1("42")) } fun strToInt(str: String): Int { var result = 0 var index = 0 // 边界 val boundary = Int.MAX_VALUE / 10 while (index < str.length) { if (str[index] == ' ') { index++ }else { break } } if (index == str.length) { // 都是空格字符 return 0 } var sign = 1 if (str[index] == '-') { sign = -1 index++ }else if (str[index] == '+') { index++ } while (index < str.length) { val curChar = str[index] if (curChar < '0' || curChar > '9') { break } // 将要越界的条件 // 1)result > boundary,那么 result * 10 后一定越界 // 2)result == boundary,result * 10 后不会越界,但是需要关注下一个字符的值,如果是大于 7,那就会越界 if (result > boundary || (result == boundary && curChar > '7')) { return if (sign == 1) { Int.MAX_VALUE }else { Int.MIN_VALUE } } result = result * 10 + (curChar - '0') index++ } return sign * result } fun strToInt1(str: String): Int { var i = 0 // 找到第一个不是空格的字符串 while (i < str.length) { if (str[i] != ' ') { break } i++ } // 判断正负号 var positive = true if (i < str.length) { if (str[i] == '-') { positive = false i++ }else if (str[i] == '+') { i++ } } var result = 0 val left = Int.MIN_VALUE / 10 // 左边界 val right = Int.MAX_VALUE / 10 // 右边界 // 遍历剩余的字符串 while (i < str.length) { val c = str[i] if (c in '0'..'9') { // 遍历到的字符是数字 val num = c - '0' if (!positive) { // 负数 // 判断是否将要越过 Int.MIN if (result < left || (result == left && num > 8)) { // result < left,那么 result*10 之后,将会越过 Int.MIN,所以直接返回Int.MIN // result == left && num>8,那么 result*10 - num,也将越过 Int.MIN return Int.MIN_VALUE }else { // 没有越界 result = result * 10 - num } }else { // 正数 // 判断是否将要越过 Int.MAX if (result > right || (result == right && num > 7)) { return Int.MAX_VALUE }else { result = result * 10 + num } } i++ }else { break } } return result }
0
Kotlin
0
0
1d213b6162dd8b065d6ca06ac961c7873c65bcdc
3,042
kotlin-study
MIT License
src/aoc2022/Day25.kt
RobertMaged
573,140,924
false
{"Kotlin": 225650}
package aoc2022 import utils.checkEquals import kotlin.math.roundToLong fun main() { val system = mapOf('=' to -2L, '-' to -1L, '0' to 0L, '1' to 1L, '2' to 2L) val xSystem = system.map { it.value to it.key }.toMap() tailrec fun toSnafu(acc: String, n: Long): String { if (n < 1) return acc return when (n % 5) { in 0..2 -> toSnafu("${xSystem[n % 5]}$acc", n / 5) in 3..4 -> toSnafu("${xSystem[n % 5 - 5]}$acc", (n / 5.0).roundToLong()) else -> error("not supported") } } fun part1(input: List<String>): String { val n = input.map { it.fold(0L) { acc, c -> (acc * 5) + system.getValue(c) } } return toSnafu("", n.sum()) } // parts execution val testInput = readInput("Day25_test") val input = readInput("Day25") part1(testInput) // .checkEquals("4890") .checkEquals("2=-1=0") part1(input) .checkEquals("2=2-1-010==-0-1-=--2") // .sendAnswer(part = 1, day = "25", year = 2022) }
0
Kotlin
0
0
e2e012d6760a37cb90d2435e8059789941e038a5
1,061
Kotlin-AOC-2023
Apache License 2.0
2021/src/main/kotlin/sh/weller/aoc/Day05.kt
Guruth
328,467,380
false
{"Kotlin": 188298, "Rust": 13289, "Elixir": 1833}
package sh.weller.aoc import kotlin.math.abs object Day05 : SomeDay<CoordinatePair, Int> { override fun partOne(input: List<CoordinatePair>): Int { val size = input.maxOf { it.maxOf() } val map: HeightMap = (0..size).map { (0..size).map { 0 }.toMutableList() }.toMutableList() for (coordinatePair in input) { if (coordinatePair.isHorizontalLine() || coordinatePair.isVerticalLine()) { map.markLinePartOne(coordinatePair) } } return map.flatten().count { it >= 2 } } @JvmName("maxOfIntInt") private fun Coordinates.maxOf(): Int = maxOf(first, second) @JvmName("maxOfIntIntIntInt") private fun CoordinatePair.maxOf(): Int = maxOf(first.maxOf(), second.maxOf()) private fun HeightMap.markLinePartOne(coordinatePair: CoordinatePair) { if (coordinatePair.isHorizontalLine()) { val startX = minOf(coordinatePair.first.first, coordinatePair.second.first) val endX = maxOf(coordinatePair.first.first, coordinatePair.second.first) repeat(endX - startX + 1) { this[coordinatePair.first.second][startX + it] = this[coordinatePair.first.second][startX + it] + 1 } } else { val startY = minOf(coordinatePair.first.second, coordinatePair.second.second) val endY = maxOf(coordinatePair.first.second, coordinatePair.second.second) repeat(endY - startY + 1) { this[startY + it][coordinatePair.first.first] = this[startY + it][coordinatePair.first.first] + 1 } } } private fun CoordinatePair.isHorizontalLine() = first.second == second.second private fun CoordinatePair.isVerticalLine() = first.first == second.first override fun partTwo(input: List<Pair<Pair<Int, Int>, Pair<Int, Int>>>): Int { val size = input.maxOf { it.maxOf() } val map: HeightMap = (0..size).map { (0..size).map { 0 }.toMutableList() }.toMutableList() for (coordinatePair in input) { if (coordinatePair.isHorizontalLine() || coordinatePair.isVerticalLine() || coordinatePair.isDiagonalLine()) { map.markLinePartTwo(coordinatePair) } } return map.flatten().count { it >= 2 } } private fun HeightMap.markLinePartTwo(coordinatePair: CoordinatePair) { if (coordinatePair.isDiagonalLine()) { val steps = abs(coordinatePair.second.first - coordinatePair.first.first) + 1 if (coordinatePair.first.first > coordinatePair.second.first && coordinatePair.first.second > coordinatePair.second.second) { // ((3,3),(1,1)) repeat(steps) { this[coordinatePair.first.second - it][coordinatePair.first.first - it] = this[coordinatePair.first.second - it][coordinatePair.first.first - it] + 1 } } else if (coordinatePair.first.first < coordinatePair.second.first && coordinatePair.first.second < coordinatePair.second.second) { // ((1,1),(3,3)) repeat(steps) { this[coordinatePair.first.second + it][coordinatePair.first.first + it] = this[coordinatePair.first.second + it][coordinatePair.first.first + it] + 1 } } else if (coordinatePair.first.first > coordinatePair.second.first && coordinatePair.first.second < coordinatePair.second.second) { // ((9,7),(7,9)) repeat(steps) { this[coordinatePair.first.second + it][coordinatePair.first.first - it] = this[coordinatePair.first.second + it][coordinatePair.first.first - it] + 1 } } else { // ((7,9),(9,7)) repeat(steps) { this[coordinatePair.first.second - it][coordinatePair.first.first + it] = this[coordinatePair.first.second - it][coordinatePair.first.first + it] + 1 } } } else { this.markLinePartOne(coordinatePair) } } private fun CoordinatePair.isDiagonalLine(): Boolean = isHorizontalLine().not() && isVerticalLine().not() && (abs(first.first - second.first) == abs(first.second - second.second)) } private typealias CoordinatePair = Pair<Coordinates, Coordinates> private typealias Coordinates = Pair<Int, Int> private typealias HeightMap = MutableList<MutableList<Int>>
0
Kotlin
0
0
69ac07025ce520cdf285b0faa5131ee5962bd69b
4,534
AdventOfCode
MIT License
src/main/kotlin/com/staricka/adventofcode2022/Day8.kt
mathstar
569,952,400
false
{"Kotlin": 77567}
package com.staricka.adventofcode2022 import kotlin.math.max class Day8 : Day { override val id = 8 override fun part1(input: String): Any { val visible = HashSet<Pair<Int, Int>>() val grid = input.lines() for (i in grid.indices) { var maxHeight = -1 for (j in grid[i].indices) { if (grid[i][j].digitToInt() > maxHeight) { visible.add(Pair(i,j)) maxHeight = max(maxHeight, grid[i][j].digitToInt()) } } maxHeight = -1 for (j in grid[i].indices.reversed()) { if (grid[i][j].digitToInt() > maxHeight) { visible.add(Pair(i,j)) maxHeight = max(maxHeight, grid[i][j].digitToInt()) } } } for (j in grid[0].indices) { var maxHeight = -1 for (i in grid.indices) { if (grid[i][j].digitToInt() > maxHeight) { visible.add(Pair(i,j)) maxHeight = max(maxHeight, grid[i][j].digitToInt()) } } maxHeight = -1 for (i in grid.indices.reversed()) { if (grid[i][j].digitToInt() > maxHeight) { visible.add(Pair(i,j)) maxHeight = max(maxHeight, grid[i][j].digitToInt()) } } } return visible.size } private fun computeScore(grid: Array<IntArray>, x: Int, y: Int): Int { var aScore = 0 for (i in (0 until x).reversed()) { aScore++ if (grid[i][y] >= grid[x][y]) { break } } var bScore = 0 for (i in (x+1)until grid.size) { bScore++ if (grid[i][y] >= grid[x][y]) { break } } var cScore = 0 for (j in (0 until y).reversed()) { cScore++ if (grid[x][j] >= grid[x][y]) { break } } var dScore = 0 for (j in (y+1) until grid[0].size) { dScore++ if (grid[x][j] >= grid[x][y]) { break } } return aScore * bScore * cScore * dScore } override fun part2(input: String): Any { var maxScore = 0 val grid = input.lines().map { it.map(Char::digitToInt).toIntArray() }.toTypedArray() for (i in grid.indices) { for (j in grid[i].indices) { maxScore = max(maxScore, computeScore(grid, i, j)) } } return maxScore } }
0
Kotlin
0
0
2fd07f21348a708109d06ea97ae8104eb8ee6a02
2,231
adventOfCode2022
MIT License
src/Day06.kt
zhiqiyu
573,221,845
false
{"Kotlin": 20644}
import java.util.Queue import java.util.Stack fun main() { fun part1(input: List<String>): List<Int> { var result = ArrayList<Int>() for (line in input) { var queue = ArrayDeque<Char>(0) for (i in line.indices) { if (queue.size < 4) { queue.addLast(line.get(i)) } if (queue.size == 4) { if (queue.toHashSet().size == 4) { result.add(i + 1) break } else { queue.removeFirst() } } } } return result } fun part2(input: List<String>): List<Int> { var result = ArrayList<Int>() for (line in input) { var queue = ArrayDeque<Char>(0) for (i in line.indices) { if (queue.size < 14) { queue.addLast(line.get(i)) } if (queue.size == 14) { if (queue.toHashSet().size == 14) { result.add(i + 1) break } else { queue.removeFirst() } } } } return result } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") check(part1(testInput) == listOf(7, 5, 6, 10, 11)) check(part2(testInput) == listOf(19, 23, 23, 29, 26)) val input = readInput("Day06") println("----------") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d3aa03b2ba2a8def927b94c2b7731663041ffd1d
1,676
aoc-2022
Apache License 2.0
src/week4/LongestConsecutive.kt
anesabml
268,056,512
false
null
package week4 import kotlin.math.max class LongestConsecutive { /** Brute force * Time complexity : O(n3) * Space complexity : O(1) */ fun longestConsecutive(nums: IntArray): Int { var maxCount = 0 for (num in nums) { var currentNumber = num var currentCount = 1 while (contains(nums, currentNumber + 1)) { currentNumber += 1 currentCount += 1 } maxCount = max(maxCount, currentCount) } return maxCount } private fun contains(nums: IntArray, num: Int): Boolean { for (i in nums.indices) { if (num == nums[i]) { return true } } return false } /** HashSet * Time complexity : O(n) * Space complexity : O(n) */ fun longestConsecutive2(nums: IntArray): Int { if (nums.isEmpty()) return 0 val numSet = nums.toHashSet() var maxCount = 0 for (num in nums) { var currentNumber = num var currentCount = 1 while (numSet.contains(currentNumber + 1)) { currentNumber += 1 currentCount += 1 } maxCount = maxOf(maxCount, currentCount) } return maxCount } /** Sort * Time complexity : O(n log n) * Space complexity : O(1) */ fun longestConsecutive3(nums: IntArray): Int { if (nums.isEmpty()) return 0 nums.sort() var maxCount = 0 var currentCount = 1 for (i in 1 until nums.size) { if (nums[i] != nums[i - 1]) { if (nums[i] == nums[i - 1] + 1) { currentCount += 1 } else { maxCount = maxOf(maxCount, currentCount) currentCount = 1 } } } return maxOf(maxCount, currentCount) } }
0
Kotlin
0
1
a7734672f5fcbdb3321e2993e64227fb49ec73e8
1,975
leetCode
Apache License 2.0
src/Day2/December2.kt
Nandi
47,216,709
false
null
package Day2 import java.nio.file.Files import java.nio.file.Paths import java.util.stream.Stream /** * 2.December challenge from www.adventofcode.com * * Part 1 * * The elves are running low on wrapping paper, and so they need to submit an order for more. They have a list of the * dimensions (length l, width w, and height h) of each present, and only want to order exactly as much as they need. * * Fortunately, every present is a box (a perfect right rectangular prism), which makes calculating the required * wrapping paper for each gift a little easier: find the surface area of the box, which is 2*l*w + 2*w*h + 2*h*l. * The elves also need a little extra paper for each present: the area of the smallest side. * * All numbers in the elves' list are in feet. How many total square feet of wrapping paper should they order? * * Part 2 * * The elves are also running low on ribbon. Ribbon is all the same width, so they only have to worry about the length * they need to order, which they would again like to be exact. * * The ribbon required to wrap a present is the shortest distance around its sides, or the smallest perimeter of any * one face. Each present also requires a bow made out of ribbon as well; the feet of ribbon required for the perfect * bow is equal to the cubic feet of volume of the present. Don't ask how they tie the bow, though; they'll never tell. * * How many total feet of ribbon should they order? * * Created by Simon on 02/12/2015. */ class December2 { fun main() { var square = 0; var ribbon = 0; val lines = loadFile("src/Day2/2.dec_input.txt"); for (line in lines) { val dim = line.split("x"); square += packaging(dim[0].toInt(), dim[1].toInt(), dim[2].toInt()); ribbon += rapping(dim[0].toInt(), dim[1].toInt(), dim[2].toInt()); } println("$square square feet of packing paper needed to wrap all the presents"); println("$ribbon feet of ribbon is needed for all the presents") } fun packaging(l: Int, w: Int, h: Int): Int { var side1: Int = l * w; var side2 = w * h; var side3 = h * l; var extra: Int = Math.min(side1, Math.min(side2, side3)); return 2 * (side1 + side2 + side3) + extra; } fun rapping(l: Int, w: Int, h: Int): Int { return (2 * (l + w + h) - 2 * Math.max(l, Math.max(w, h))) + (l * w * h); } fun loadFile(path: String): Stream<String> { val input = Paths.get(path); val reader = Files.newBufferedReader(input); return reader.lines(); } } fun main(args: Array<String>) { December2().main(); }
0
Kotlin
0
0
34a4b4c0926b5ba7e9b32ca6eeedd530f6e95bdc
2,684
adventofcode
MIT License
day14/src/Day14.kt
simonrules
491,302,880
false
{"Kotlin": 68645}
import java.io.File class Day14(path: String) { private var template: String = "" private val rules = mutableMapOf<String, Char>() private var pairs = mutableMapOf<String, Long>() init { var line = 0 File(path).forEachLine { if (line == 0) { template = it } else if (line > 1) { val rule = it.split(" -> ") rules[rule[0]] = rule[1][0] // first char only } line++ } } fun part1(): Int { var polymer = template for (iteration in 0 until 10) { val insertList = mutableListOf<Pair<Char, Int>>() for (i in 0 until polymer.length - 1) { val pair = polymer.substring(i..i + 1) val element = rules[pair] if (element != null) { insertList.add(Pair(element, i)) } } val newPolymer = StringBuilder(polymer) var offset = 1 insertList.forEach { newPolymer.insert(it.second + offset, it.first) offset++ } polymer = newPolymer.toString() } val counts = IntArray(26) { 0 } polymer.forEach { var c = it.code - 'A'.code counts[c]++ } var min = 9999999 var max = 0 counts.forEach { if (it in 1 until min) { min = it } if (it > max) { max = it } } return max - min } private fun addToPairCounts( pair: String, pairCounts: MutableMap<String, Long>, count: Long ) { if (pair in pairCounts) { pairCounts[pair] = pairCounts[pair]!! + count } else { pairCounts[pair] = count } } fun part2(): Long { // First put count of all pairs in the map for (i in 0 until template.length - 1) { val pair = template.substring(i, i + 2) addToPairCounts(pair, pairs, 1L) } for (iteration in 0 until 40) { // Now generate new pairs via insertion rules val newPairs = mutableMapOf<String, Long>() pairs.forEach { (pair, count) -> val insert = rules[pair] if (insert == null) { newPairs[pair] = count } else { val pair1 = pair[0] + insert.toString() val pair2 = insert.toString() + pair[1] addToPairCounts(pair1, newPairs, count) addToPairCounts(pair2, newPairs, count) } } pairs = newPairs } val elementCounts = mutableMapOf<Char, Long>() pairs.forEach { (pair, count) -> if (pair[0] !in elementCounts) { elementCounts[pair[0]] = count } else { elementCounts[pair[0]] = elementCounts[pair[0]]!! + count } if (pair[1] !in elementCounts) { elementCounts[pair[1]] = count } else { elementCounts[pair[1]] = elementCounts[pair[1]]!! + count } } // The first and last chars never change, and they can't overlap, so add them back in elementCounts[template.first()] = elementCounts[template.first()]!! + 1L elementCounts[template.last()] = elementCounts[template.last()]!! + 1L // The divide by 2 accounts for overlap val most = elementCounts.values.max() / 2 val least = elementCounts.values.min() / 2 return most - least } } fun main() { val aoc = Day14("day14/input.txt") println(aoc.part1()) println(aoc.part2()) }
0
Kotlin
0
0
d9e4ae66e546f174bcf66b8bf3e7145bfab2f498
3,850
aoc2021
Apache License 2.0
src/main/kotlin/days/Day8.kt
broersma
574,686,709
false
{"Kotlin": 20754}
package days class Day8 : Day(8) { override fun partOne(): Int { val height = inputList.size val width = inputList[0].length val map = Array(height) { IntArray(width) } for (y in 0..height - 1) { for (x in 0..width - 1) { map[y][x] = inputList[y][x].digitToInt() } } val visible = Array(height) { IntArray(width) } for (y in 0..height - 1) { for (x in 0..width - 1) { search@ for (d in listOf(1 to 0, 0 to 1, -1 to 0, 0 to -1)) { var dx = x var dy = y while (true) { dx += d.first dy += d.second if (!(dx in 0..width - 1 && dy in 0..height - 1)) { visible[y][x] = 1 break@search } if (map[dy][dx] >= map[y][x]) { break } } } } } return visible.map { it.sum() }.sum() } override fun partTwo(): Int { val height = inputList.size val width = inputList[0].length val map = Array(height) { IntArray(width) } for (y in 0..height - 1) { for (x in 0..width - 1) { map[y][x] = inputList[y][x].digitToInt() } } val score = Array(height) { IntArray(width) } for (y in 0..height - 1) { for (x in 0..width - 1) { score[y][x] = 1 for (d in listOf(1 to 0, 0 to 1, -1 to 0, 0 to -1)) { var dx = x var dy = y var dirScore = 0 while (true) { dx += d.first dy += d.second if (dx in 0..width - 1 && dy in 0..height - 1) { dirScore += 1 if (map[dy][dx] >= map[y][x]) { break } } else { break } } score[y][x] *= dirScore } } } return score.map { it.max() }.max() } }
0
Kotlin
0
0
cd3f87e89f7518eac07dafaaeb0f6adf3ecb44f5
2,417
advent-of-code-2022-kotlin
Creative Commons Zero v1.0 Universal
src/Day06.kt
lsimeonov
572,929,910
false
{"Kotlin": 66434}
fun main() { fun findAnswer(s: String, l: Int): Int? { val b = ArrayDeque<Char>() s.toList().forEachIndexed { i, c -> b.addFirst(c) if (b.toSet().count() == l) { return i+1 } if (b.count() == l) { b.removeLast() } } return null } fun part1(input: List<String>): Int { val results = input.map { findAnswer(it,4) }.filterNotNull() return results[0] } fun part2(input: List<String>): Int { val results = input.map { findAnswer(it,14) }.filterNotNull() return results[0] } // test if implementation meets criteria from the description, like: // val testInput = readInput("Day06_test") // check(part1(testInput) == 7) // check(part2(testInput) == 2) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
9d41342f355b8ed05c56c3d7faf20f54adaa92f1
975
advent-of-code-2022
Apache License 2.0
src/_004/kotlin/Solution.kt
RichCodersAndMe
127,856,921
false
null
package _004.kotlin /** * @author relish * @since 2018/10/20 */ class Solution { fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double { val len = nums1.size + nums2.size return if (len % 2 == 0) { (fix(nums1, 0, nums2, 0, len / 2) + fix(nums1, 0, nums2, 0, len / 2 + 1)) / 2.0 } else { fix(nums1, 0, nums2, 0, len / 2 + 1).toDouble() } } fun fix(nums1: IntArray, n: Int, nums2: IntArray, m: Int, k: Int): Int { if (n >= nums1.size) return nums2[m + k - 1] if (m >= nums2.size) return nums1[n + k - 1] if (k == 1) return Math.min(nums1[n], nums2[m]) val i1 = n + k / 2 - 1 val i2 = m + k / 2 - 1 val v1 = if (i1 < nums1.size) nums1[i1] else Int.MAX_VALUE val v2 = if (i2 < nums2.size) nums2[i2] else Int.MAX_VALUE return if (v1 < v2) { fix(nums1, n + k / 2, nums2, m, k - k / 2) } else { fix(nums1, n, nums2, m + k / 2, k - k / 2) } } } fun main(args: Array<String>) { val solution = Solution() println(solution.findMedianSortedArrays(intArrayOf(2), intArrayOf(0))) println(solution.findMedianSortedArrays(intArrayOf(1, 2), intArrayOf(3, 4))) println(solution.findMedianSortedArrays(intArrayOf(1, 2), intArrayOf(-1, 3))) }
0
Java
4
22
96119bbc34d4655d017b57b19304890fbb142142
1,336
LeetCode-Solution
MIT License
src/main/kotlin/days/Day18.kt
hughjdavey
725,972,063
false
{"Kotlin": 76988}
package days import days.Day14.Direction import xyz.hughjd.aocutils.Coords.Coord import kotlin.math.abs class Day18 : Day(18) { override fun partOne(): Any { val (perimeter, vertices) = getPerimeterAndVertices(parseInstructions()) return getInteriorPoints(perimeter, vertices) } override fun partTwo(): Any { val (perimeter, vertices) = getPerimeterAndVertices(parseInstructionsFromColours()) return getInteriorPoints(perimeter, vertices) } private fun getPerimeterAndVertices(instructions: List<DigInstruction>): Pair<Long, List<Coord>> { return instructions.fold(0L to listOf(Coord(0, 0))) { (p, v), instruction -> val coord = v.last() val toDig = when (instruction.direction) { Direction.NORTH -> generateSequence(coord) { it.minusY(1) } Direction.SOUTH -> generateSequence(coord) { it.plusY(1) } Direction.EAST -> generateSequence(coord) { it.plusX(1) } Direction.WEST -> generateSequence(coord) { it.minusX(1) } }.take(instruction.metres + 1).toList().drop(1) p + toDig.size to v + toDig.last() } } // uses pick's theorem - thanks to reddit comment https://www.reddit.com/r/adventofcode/comments/18l0qtr/2023_day_18_solutions/kdveugr private fun getInteriorPoints(perimeterSize: Long, vertices: List<Coord>): Long { // pick is A = i + b / 2 - 1 // we have A and b but want i // so rearrange to A - b / 2 = i - 1 // and rearrange again to A - b / 2 + 1 = i // then we need to add the perimeter #s as well (b) // so final formula is A + b / 2 + 1 = i val A = getArea(vertices) val b = perimeterSize return A + (b / 2) + 1 } // uses shoelace algorithm - thanks to comments in reddit thread https://old.reddit.com/r/adventofcode/comments/18l1mdm/2023_days_10_18_how_repetitive_can_this_get for inspriation // implementation based on description here https://www.101computing.net/the-shoelace-algorithm private fun getArea(vertices: List<Coord>): Long { val points = vertices + vertices.first() val one = points.windowed(2).fold(0L) { acc, (p1, p2) -> acc + (p1.x.toLong() * p2.y) } val two = points.windowed(2).fold(0L) { acc, (p1, p2) -> acc + (p1.y.toLong() * p2.x) } return abs(two - one) / 2 } fun parseInstructions(): List<DigInstruction> { return inputList.map { it.split(' ') }.map { (d, m, c) -> DigInstruction(stringToDirection(d), m.toInt(), c.drop(1).dropLast(1)) } } fun parseInstructionsFromColours(): List<DigInstruction> { return inputList.mapNotNull { Regex("(#.{6})").find(it)?.value }.map { val (d, m) = it.takeLast(1) to it.drop(1).dropLast(1) DigInstruction(stringToDirection(d), m.toInt(16), it) } } private fun stringToDirection(s: String): Direction { return when (s) { "U", "3" -> Direction.NORTH "D", "1" -> Direction.SOUTH "R", "0" -> Direction.EAST "L", "2" -> Direction.WEST else -> throw IllegalArgumentException() } } data class DigInstruction(val direction: Direction, val metres: Int, val colour: String) }
0
Kotlin
0
0
330f13d57ef8108f5c605f54b23d04621ed2b3de
3,339
aoc-2023
Creative Commons Zero v1.0 Universal
src/main/kotlin/days/Day8.kt
vovarova
572,952,098
false
{"Kotlin": 103799}
package days class Day8 : Day(8) { val treeMap = inputList.map { it.toCharArray().map { it.digitToInt() }.toList() } fun isVisible(rows: IntProgression, columns: IntProgression, compareValue: Int): Boolean { return rows.flatMap { row -> columns.map { row to it } } .all { treeMap[it.first][it.second] < compareValue } } override fun partOne(): Any { // Brute Force algorythm var visibleTree = treeMap.size * 4 - 4 for (row in 1..treeMap.size - 2) { for (column in 1..treeMap.size - 2) { val currentCellValue = treeMap[row][column] val leftVisible = isVisible( rows = IntRange(row, row), columns = IntRange(0, column - 1), compareValue = currentCellValue ) val rightVisible = isVisible( rows = IntRange(row, row), columns = IntRange(column + 1, treeMap.size - 1), compareValue = currentCellValue ) val topVisible = isVisible( rows = IntRange(0, row - 1), columns = IntRange(column, column), compareValue = currentCellValue ) val bottomVisible = isVisible( rows = IntRange(row + 1, treeMap.size - 1), columns = IntRange(column, column), compareValue = currentCellValue ) if (leftVisible || rightVisible || topVisible || bottomVisible) { visibleTree++ } } } return visibleTree } fun calcView(rows: IntProgression, columns: IntProgression, compareValue: Int): Int { return rows.flatMap { row -> columns.map { row to it } } .takeWhile { treeMap[it.first][it.second] < compareValue } .let { if (it.isNotEmpty() && (it.last().second == 0 || it.last().first == 0 || it.last().second == treeMap.size - 1 || it.last().first == treeMap.size - 1) ) { it.size } else { it.size + 1 } } } override fun partTwo(): Any { // Brute Force algorythm var maxView = 0 for (row in 1..treeMap.size - 2) { for (column in 1..treeMap.size - 2) { val currentCellValue = treeMap[row][column] val leftVisible = calcView( rows = IntRange(row, row), columns = IntRange(0, column - 1).reversed(), compareValue = currentCellValue ) val rightVisible = calcView( rows = IntRange(row, row), columns = IntRange(column + 1, treeMap.size - 1), compareValue = currentCellValue ) val topVisible = calcView( rows = IntRange(0, row - 1).reversed(), columns = IntRange(column, column), currentCellValue ) val bottomVisible = calcView( rows = IntRange(row + 1, treeMap.size - 1), columns = IntRange(column, column), compareValue = currentCellValue ) maxView = Math.max(maxView, leftVisible * rightVisible * topVisible * bottomVisible) } } return maxView } }
0
Kotlin
0
0
e34e353c7733549146653341e4b1a5e9195fece6
3,934
adventofcode_2022
Creative Commons Zero v1.0 Universal
src/commonMain/kotlin/sequences/MultiTransforms.kt
tomuvak
511,086,330
false
{"Kotlin": 92304, "Shell": 619}
package com.tomuvak.util.sequences /** * Returns a list of sequences, each of which is the result of running the corresponding transform (of the given * [transforms]) on a sequence equivalent to (that is comprising the same elements as) the receiver sequence [this]. * Iterating over (any or all of) the returned sequences in full or in part will iterate the original sequence [this] at * most once, and at no point further than is required in order to yield the elements (of the returned sequences) * iterated over until that point. * * None of the given [transforms] is allowed to iterate its input sequence more than once. For typical use cases that * also implies none of the returned sequences can be iterated multiple times, though that really depends on the * transforms themselves: a transform is allowed to return any sequence, not each iteration of which necessarily * requiring (re)iteration of the original sequence (just as one example, the transform may cache its input and/or * output). * * This operation is _intermediate_ and _stateful_. */ fun <T, R> Sequence<T>.transform(transforms: List<(Sequence<T>) -> Sequence<R>>): List<Sequence<R>> = MultiTransformSequences(this, transforms).transformedSequences private class MultiTransformSequences<T, R>(source: Sequence<T>, transforms: List<(Sequence<T>) -> Sequence<R>>) { private val cached = source.cached(transforms.size) val transformedSequences: List<Sequence<R>> = transforms.map { it(cached.constrainOnce()) } } /** * Partitions the receiver sequence [this] into a pair of sequences, the `first` of which containing all elements which * satisfy the given [predicate], and the `second` one those elements which don't. Each of the returned sequences can * only be iterated over once. * * Similar to the standard library's [partition], but returns a pair of [Sequence]s rather than [List]s, and does not at * any point iterate the original sequence further than is necessary in order to yield the elements iterated over (in * the returned sequences) until that point. * * This operation is _intermediate_ (hence the name) and _stateful_ (as opposed to the standard library's [partition], * which is _terminal_). */ fun <T> Sequence<T>.partitionIntermediate(predicate: (T) -> Boolean): Pair<Sequence<T>, Sequence<T>> = map { it to predicate(it) }.transform(listOf( { it.filter { it.second } }, { it.filterNot {it.second } } )).map { it.map { it.first } }.let { Pair(it[0], it[1]) } /** * Returns a pair of sequences, the `first` of which containing the `first` components of the elements of the receiver * sequence [this], and the `second` one the `second` components thereof. Each of the returned sequences can only be * iterated over once. * * Similar to the standard library's [unzip], but returns a pair of [Sequence]s rather than [List]s, and does not at any * point iterate the original sequence further than is necessary in order to yield the elements iterated over (in the * returned sequences) until that point. * * This operation is _intermediate_ (hence the name) and _stateful_ (as opposed to the standard library's [unzip], which * is _terminal_). */ fun <T1, T2> Sequence<Pair<T1, T2>>.unzipIntermediate(): Pair<Sequence<T1>, Sequence<T2>> = transform(listOf( { it.map { it.first } }, { it.map { it.second } } )).let { @Suppress("UNCHECKED_CAST") Pair(it[0] as Sequence<T1>, it[1] as Sequence<T2>) }
0
Kotlin
0
0
e20cfae9535fd9968542b901c698fdae1a24abc1
3,466
util
MIT License
src/main/kotlin/days/Day2.kt
mir47
433,536,325
false
{"Kotlin": 31075}
package days class Day2 : Day(2) { override fun partOne(): Int { val xy = inputList .fold(Pair(0, 0)) { sumPair, line -> val dir = line.split(" ")[0] val units = line.split(" ")[1].toInt() when (dir) { "forward" -> Pair(sumPair.first + units, sumPair.second) "down" -> Pair(sumPair.first, sumPair.second + units) "up" -> Pair(sumPair.first, sumPair.second - units) else -> sumPair } } return xy.first * xy.second } override fun partTwo(): Int { var pos = Pair(0, 0) var aim = 0 inputList.forEach { val dir = it.split(" ")[0] val units = it.split(" ")[1].toInt() when (dir) { "forward" -> pos = Pair(pos.first + units, pos.second + (aim * units)) "down" -> aim += units "up" -> aim -= units } } return pos.first * pos.second } }
0
Kotlin
0
0
686fa5388d712bfdf3c2cc9dd4bab063bac632ce
1,067
aoc-2021
Creative Commons Zero v1.0 Universal
src/main/kotlin/Excercise06.kt
underwindfall
433,989,850
false
{"Kotlin": 55774}
import java.math.BigInteger private fun getSpawnCount( memo: MutableMap<Pair<Int, Int>, BigInteger>, timer: Int, days: Int ): BigInteger { val memoKey = Pair(timer, days) if (timer >= days) return BigInteger("1") if (memo.containsKey(memoKey)) return memo.getValue(memoKey) memo[memoKey] = getSpawnCount(memo, 6, days - timer - 1) + getSpawnCount(memo, 8, days - timer - 1) return memo.getValue(memoKey) } private fun part1() { val memo = mutableMapOf<Pair<Int, Int>, BigInteger>() getInputAsTest("06") { split(",") } .map { it.toInt() } .map { getSpawnCount(memo, it, 80) } .reduce { acc, bigInteger -> acc + bigInteger } .let { println("Part1 $it") } } private fun part2() { val memo = mutableMapOf<Pair<Int, Int>, BigInteger>() getInputAsTest("06") { split(",") } .map { it.toInt() } .map { getSpawnCount(memo, it, 256) } .reduce { acc, bigInteger -> acc + bigInteger } .let { println("Part1 $it") } } fun main() { part1() part2() }
0
Kotlin
0
0
4fbee48352577f3356e9b9b57d215298cdfca1ed
1,005
advent-of-code-2021
MIT License
src/main/java/challenges/cracking_coding_interview/trees_graphs/route_between_nodes/Question.kt
ShabanKamell
342,007,920
false
null
package challenges.cracking_coding_interview.trees_graphs.route_between_nodes import java.util.* /** * Given a directed graph, design an algorithm to find out * whether there is a route between two nodes. */ object Question { @JvmStatic fun main(a: Array<String>) { val g = createNewGraph() val n: Array<Node?> = g.nodes val start = n[3] val end = n[5] println(search(g, start, end)) } private fun createNewGraph(): Graph { val g = Graph() val temp = arrayOfNulls<Node>(6) temp[0] = Node("a", 3) temp[1] = Node("b", 0) temp[2] = Node("c", 0) temp[3] = Node("d", 1) temp[4] = Node("e", 1) temp[5] = Node("f", 0) temp[0]!!.addAdjacent(temp[1]) temp[0]!!.addAdjacent(temp[2]) temp[0]!!.addAdjacent(temp[3]) temp[3]!!.addAdjacent(temp[4]) temp[4]!!.addAdjacent(temp[5]) for (i in 0..5) { g.addNode(temp[i]) } return g } private fun search(g: Graph, start: Node?, end: Node?): Boolean { val q = LinkedList<Node>() for (u in g.nodes) { u!!.state = State.Unvisited } start!!.state = State.Visiting q.add(start) var u: Node? while (!q.isEmpty()) { u = q.removeFirst() val isFound = search(u, end, q) if (isFound) return true } return false } private fun search(_u: Node?, end: Node?, q: LinkedList<Node>): Boolean { val u = _u ?: return false for (v in u.adjacent) { when (v!!.state) { State.Visiting, State.Visited -> return false State.Unvisited -> { if (v == end) return true v.state = State.Visiting q.add(v) } } } u.state = State.Visited return false } enum class State { Unvisited, Visiting, Visited } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
2,059
CodingChallenges
Apache License 2.0
src/main/kotlin/courseraWeek2/Funcional.kt
SebastianCerquera
587,973,890
false
null
package courseraWeek2 val heroes = listOf( Hero("The Captain", 60, Gender.MALE), Hero( "Frenchy", 42, Gender.MALE), Hero( "The kid", 9, null), Hero( "<NAME>", 29, Gender.FEMALE), Hero( "<NAME>", 29, Gender.MALE), Hero( "<NAME>", 37, Gender.MALE) ) fun main() { //encontrar el último nombre val lastName = heroes.last().name println(lastName) val firstNameOrNull = heroes.firstOrNull{ it.age == 30 }?.name println(firstNameOrNull) // val firstName = heroes.first{ it.age == 30 }?.name // println(firstName) //devuelve un NoSuchElementException val mapDistinct = heroes.map { it.age }.distinct().size println(mapDistinct) val filterAge = heroes.filter { it.age < 30 }.size println(filterAge) val (youngest, oldest) = heroes.partition { it.age < 30 } println("Size youngest is ${youngest.size} and size oldest ${oldest.size}") val nameMaxOld = heroes.maxBy { it.age }?.name println(nameMaxOld) val nameMinOld = heroes.minBy { it.age }?.name println(nameMinOld) val allProperty = heroes.all { it.age < 50 } println(allProperty) val anyProperty = heroes.any { it.gender == Gender.FEMALE} println(anyProperty) //Quiz II val mapByAge: Map<Int, List<Hero>> = heroes.groupBy { it.age } val (age, group) = mapByAge.maxBy { (_, group) -> group.size }!! println(mapByAge) println(age) println(group) val mapByName: Map<String, Hero> = heroes.associateBy { it.name } val ageMapByName= mapByName["Frenchy"]?.age println(mapByName) println(ageMapByName) val unknownHero = Hero("Unknown", 0, null) mapByName.getOrElse("unknown") { unknownHero }.age println(mapByName) //WARN: como no debe escribirse una lambda: val (first, second) = heroes .flatMap { heroes.map { hero -> it to hero } } .maxBy { it.first.age - it.second.age }!! println(first.name) }
0
Kotlin
0
0
46dedbff8e7e1c505d352bfb60909fc623585eef
1,975
from-java-to-kotlin
Apache License 2.0
src/Day01.kt
Aldas25
572,846,570
false
{"Kotlin": 106964}
fun main() { fun part1(input: List<String>): Int { var answer = 0 var currentElf = 0 for (s in input) { if (s.isBlank()) { currentElf = 0 } else { currentElf += s.toInt() } answer = maxOf(answer, currentElf) } return answer } fun part2(input: List<String>): Int { var currentElf = 0 var listOfElfs: List<Int> = emptyList() for (s in input) { if (s.isBlank()) { listOfElfs = listOfElfs.plus(currentElf) currentElf = 0 } else { currentElf += s.toInt() } } listOfElfs = listOfElfs.plus(currentElf) listOfElfs = listOfElfs.sortedDescending() val answer = listOfElfs[0] + listOfElfs[1] + listOfElfs[2] return answer } val filename = // "inputs\\day01_sample" "inputs\\day01" val input = readInput(filename) println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") }
0
Kotlin
0
0
80785e323369b204c1057f49f5162b8017adb55a
1,099
Advent-of-Code-2022
Apache License 2.0
kotlin/src/katas/kotlin/skiena/graphs/MinSpanningTree.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.skiena.graphs import katas.kotlin.skiena.graphs.WeightedGraphs.diamondGraph import katas.kotlin.skiena.graphs.WeightedGraphs.linearGraph import katas.kotlin.skiena.graphs.WeightedGraphs.exampleGraph import katas.kotlin.skiena.graphs.WeightedGraphs.triangleGraph import datsok.shouldEqual import org.junit.Test import java.util.* import java.util.Comparator.comparingInt class MinimumSpanningTreeTests { @Test fun `Prim's min spanning tree`() { linearGraph.primMST() shouldEqual linearGraph triangleGraph.primMST() shouldEqual Graph.readInts("1-2/20,2-3/10") diamondGraph.primMST() shouldEqual Graph.readInts("1-2/10,1-4/20,2-3/30") exampleGraph.primMST() shouldEqual Graph.read("A-B/5,A-C/7,C-F/3,C-D/4,E-F/2,F-G/2") } @Test fun `Kruskal's min spanning tree`() { linearGraph.kruskalMST() shouldEqual linearGraph triangleGraph.kruskalMST() shouldEqual Graph.readInts("1-3/20,2-3/10") diamondGraph.kruskalMST() shouldEqual Graph.readInts("1-2/10,1-4/20,2-3/30") exampleGraph.kruskalMST() shouldEqual Graph.read("A-B/5,A-C/7,C-F/3,C-D/4,E-F/2,F-G/2") } } class DisjointSetTests { @Test fun `connect 1 and 2`() { val set = DisjointSet(listOf(1, 2)) set.find(1) shouldEqual 1 set.find(2) shouldEqual 2 set.areConnected(1, 2) shouldEqual false set.join(1, 2) set.find(1) shouldEqual 1 set.find(2) shouldEqual 1 set.areConnected(1, 2) shouldEqual true } @Test fun `connect 1, 2, 3`() { val set = DisjointSet(listOf(1, 2, 3)) set.areConnected(1, 2) shouldEqual false set.areConnected(1, 3) shouldEqual false set.join(1, 2) shouldEqual true set.join(2, 3) shouldEqual true set.join(1, 3) shouldEqual false set.areConnected(1, 2) shouldEqual true set.areConnected(1, 3) shouldEqual true } } // https://en.wikipedia.org/wiki/Disjoint-set_data_structure class DisjointSet<T>() { private class Node<T>(val value: T) { var parent: Node<T> = this var size: Int = 1 } private val nodes = HashMap<T, Node<T>>() constructor(iterable: Iterable<T>) : this() { addAll(iterable) } fun add(value: T) { nodes[value] = Node(value) } fun addAll(iterable: Iterable<T>) { iterable.forEach { add(it) } } fun areConnected(value1: T, value2: T): Boolean = find(value1) == find(value2) fun find(value: T): T = findNode(nodes[value]!!).value private tailrec fun findNode(node: Node<T>): Node<T> { return if (node.parent == node) node else findNode(node.parent) } fun join(value1: T, value2: T): Boolean { var root1 = findNode(nodes[value1]!!) var root2 = findNode(nodes[value2]!!) if (root1 == root2) return false if (root1.size < root2.size) { val tmp = root1 root1 = root2 root2 = tmp } root1.size = root1.size + root2.size root2.parent = root1 return true } } private fun <T> Graph<T>.kruskalMST(): Graph<T> { val tree = Graph<T>() val set = DisjointSet(vertices) val queue = PriorityQueue<Edge<T>>(comparingInt { it.weight!! }) queue.addAll(edges) while (queue.isNotEmpty()) { val edge = queue.remove() if (set.join(edge.from, edge.to)) { tree.addEdge(edge) } } return tree } private fun <T> Graph<T>.primMST(): Graph<T> { val tree = Graph<T>() tree.addVertex(vertices.first()) while (!tree.vertices.containsAll(vertices)) { val minEdge = tree.vertices .flatMap { vertex -> edgesByVertex[vertex]!! } .filter { edge -> edge.to !in tree.vertices } .minBy { edge -> edge.weight!! } tree.addEdge(minEdge) } return tree }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
3,910
katas
The Unlicense
src/main/kotlin/g0501_0600/s0556_next_greater_element_iii/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0501_0600.s0556_next_greater_element_iii // #Medium #String #Math #Two_Pointers #Programming_Skills_II_Day_10 // #2023_01_20_Time_137_ms_(80.00%)_Space_32.6_MB_(60.00%) @Suppress("NAME_SHADOWING") class Solution { /* - What this problem wants is finding the next permutation of n - Steps to find the next permuation: find largest index k such that inp[k] < inp[k+1]; if k == -1: return -1 else: look for largest index l such that inp[l] > inp[k] swap the two index reverse from k+1 to n.length */ fun nextGreaterElement(n: Int): Int { val inp = n.toString().toCharArray() // Find k var k = -1 for (i in inp.size - 2 downTo 0) { if (inp[i] < inp[i + 1]) { k = i break } } if (k == -1) { return -1 } // Find l var largerIdx = inp.size - 1 for (i in inp.indices.reversed()) { if (inp[i] > inp[k]) { largerIdx = i break } } swap(inp, k, largerIdx) reverse(inp, k + 1, inp.size - 1) // Build result var ret = 0 for (c in inp) { val digit = c.code - '0'.code // Handle the case if ret > Integer.MAX_VALUE - This idea is borrowed from problem 8. // String to Integer (atoi) if (ret > Int.MAX_VALUE / 10 || ret == Int.MAX_VALUE / 10 && digit > Int.MAX_VALUE % 10) { return -1 } ret = ret * 10 + (c.code - '0'.code) } return ret } private fun swap(inp: CharArray, i: Int, j: Int) { val temp = inp[i] inp[i] = inp[j] inp[j] = temp } private fun reverse(inp: CharArray, start: Int, end: Int) { var start = start var end = end while (start < end) { val temp = inp[start] inp[start] = inp[end] inp[end] = temp start++ end-- } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,120
LeetCode-in-Kotlin
MIT License
src/year2023/18/Day18.kt
Vladuken
573,128,337
false
{"Kotlin": 327524, "Python": 16475}
package year2023.`18` import readInput import utils.printDebug import utils.printlnDebug import kotlin.math.absoluteValue private const val CURRENT_DAY = "18" private data class Point( val x: Int, val y: Int, ) { val left get() = Point(x - 1, y) val right get() = Point(x + 1, y) val top get() = Point(x, y - 1) val bottom get() = Point(x, y + 1) override fun toString(): String = "[$x,$y]" } private fun Direction.calculateNextPoint(currentPoint: Point): Point { return when (this) { Direction.LEFT -> currentPoint.left Direction.RIGHT -> currentPoint.right Direction.TOP -> currentPoint.top Direction.BOTTOM -> currentPoint.bottom } } enum class Direction { BOTTOM, TOP, LEFT, RIGHT; override fun toString(): String { return when (this) { BOTTOM -> "B" TOP -> "T" LEFT -> "L" RIGHT -> "R" } } companion object { fun fromString(string: String): Direction { return when (string) { "R" -> RIGHT "L" -> LEFT "U" -> TOP "D" -> BOTTOM else -> error("") } } fun fromHex(string: String): Direction { return when (string) { "0" -> RIGHT "1" -> BOTTOM "2" -> LEFT "3" -> TOP else -> error("") } } } } private data class Line( val start: Point, val end: Point, ) data class Command( val direction: Direction, val amount: Int, ) private fun parseLineIntoCommands( line: String ): Command { val list = line.split(" ") return Command( Direction.fromString(list[0]), list[1].toInt(), ) } private fun parseHexLineIntoCommand( line: String ): Command { val list = line.split(" ") val last = list[2].drop(1).dropLast(1) return Command( Direction.fromHex(last.last().toString()), last.drop(1).dropLast(1).toInt(16), ) } private fun processLines(list: List<Command>): Set<Line> { val resSet = mutableSetOf<Line>() var currentPoint = Point(0, 0) list.forEach { command -> val listOf = mutableListOf<Point>() var cur = currentPoint repeat(command.amount) { val newPoint = when (command.direction) { Direction.BOTTOM -> cur.bottom Direction.TOP -> cur.top Direction.LEFT -> cur.left Direction.RIGHT -> cur.right } listOf.add(newPoint) cur = newPoint } resSet.add(Line(currentPoint, listOf.last())) currentPoint = listOf.last() } return resSet } private fun processCommandsIntoPoints(list: List<Command>): Set<Point> { val resSet = mutableSetOf<Point>() var currentPoint = Point(0, 0) list.forEach { command -> repeat(command.amount) { val newPoint = when (command.direction) { Direction.BOTTOM -> currentPoint.bottom Direction.TOP -> currentPoint.top Direction.LEFT -> currentPoint.left Direction.RIGHT -> currentPoint.right } resSet.add(currentPoint) currentPoint = newPoint } } return resSet } private fun printSet(set: Set<Point>) { val minX = set.minOf { it.x } val minY = set.minOf { it.y } val maxX = set.maxOf { it.x } val maxY = set.maxOf { it.y } println() for (i in minY..maxY) { for (x in minX..maxX) { val symbol = if (Point(x, i) in set) "#" else "." printDebug { symbol } } printlnDebug { } } printlnDebug { } } private fun Point.neighbours(): Set<Point> { return setOf( Point(x + 1, y), Point(x - 1, y), Point(x, y + 1), Point(x, y - 1), ) } private fun searchForInternalPoints(set: Set<Point>): Set<Point> { val minX = set.minOf { it.x } val minY = set.minOf { it.y } val maxX = set.maxOf { it.x } val maxY = set.maxOf { it.y } val initialPoint = Point(1, 1) val queue = ArrayDeque(listOf(initialPoint)) val visitedPoints = mutableSetOf<Point>() while (queue.isNotEmpty()) { val currentPoint = queue.removeFirst() if (currentPoint in visitedPoints) continue visitedPoints.add(currentPoint) currentPoint.neighbours() .filter { it !in set } .filter { it.x in minX..maxX && it.y in minY..maxY } .forEach { queue.add(it) } } visitedPoints.addAll(set) return visitedPoints } fun main() { fun part1(input: List<String>): Int { val commands = input.map { parseLineIntoCommands(it) } val points = processCommandsIntoPoints(commands) printSet(points) printlnDebug { } val allPoints = searchForInternalPoints(points) printSet(allPoints) return allPoints.size } fun part2(input: List<String>): Long { val map = input.map { parseHexLineIntoCommand(it) } val lines = processLines(map) val outerArea = lines.sumOf { val xDif = (it.start.x - it.end.x).absoluteValue val yDif = (it.start.y - it.end.y).absoluteValue xDif + yDif } val internalArea = lines.sumOf { val firstDif = it.start.x.toLong() * it.end.y.toLong() val secondDif = it.end.x.toLong() * it.start.y.toLong() firstDif - secondDif }.absoluteValue / 2L return internalArea + outerArea / 2 + 1 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day${CURRENT_DAY}_test") val part1Test = part1(testInput) println(part1Test) check(part1Test == 62) val input = readInput("Day$CURRENT_DAY") // Part 1 val part1 = part1(input) println(part1) check(part1 == 35244) val part2Test = part2(testInput) println(part2Test) check(part2Test == 952408144115L) // Part 2 val part2 = part2(input) println(part2) check(part2 == 85070763635666L) }
0
Kotlin
0
5
c0f36ec0e2ce5d65c35d408dd50ba2ac96363772
6,267
KotlinAdventOfCode
Apache License 2.0
kotlin/src/main/java/com/samelody/samples/kotlin/algorithms/mergeSort.kt
belinwu
140,991,591
false
{"Kotlin": 70895, "Java": 1117}
package com.samelody.samples.kotlin.algorithms import com.samelody.samples.kotlin.example fun IntArray.mergeSort(low: Int, high: Int) { if (low >= high) return val mid = (low + high) / 2 mergeSort(low, mid) mergeSort(mid + 1, high) merge(low, mid, high) } fun IntArray.merge(low: Int, mid: Int, high: Int) { val n1 = mid - low + 1 val n2 = high - mid val a1 = IntArray(n1) val a2 = IntArray(n2) for (i in 0 until n1) a1[i] = this[low + i] for (j in 0 until n2) a2[j] = this[mid + 1 + j] var i = 0 var j = 0 var k = low while (i < n1 && j < n2) { this[k++] = if (a1[i] <= a2[j]) a1[i++] else a2[j++] } while (i < n1) this[k++] = a1[i++] while (j < n2) this[k++] = a2[j++] } fun main() { "Merge Sort" example { val array = intArrayOf(12, 0, 3, 9, 2, 21, 2, 18, 27, 1, 5, 8, -1, 8) array.run { forEach { print("$it ") } mergeSort(0, size - 1) println() forEach { print("$it ") } } } }
0
Kotlin
0
2
dce2b98cb031df6bbf04cfc576541a2d96134b5d
1,048
samples
Apache License 2.0
kotlin/src/main/kotlin/com/ximedes/aoc/day01/ReportRepair.kt
rolfchess
314,041,772
false
null
package com.ximedes.aoc.day01 import com.javamonitor.tools.Stopwatch import com.ximedes.aoc.util.getClasspathFile fun main() { val sw = Stopwatch("Day 1", "load input") val ints = mutableSetOf<Int>() getClasspathFile("/input-1.txt").forEachLine { ints.add(it.toInt()) } sw.aboutTo("find pair") val (x, y) = find2020Pair(ints) println("Day 01 part 1 solution: ${x * y}") sw.aboutTo("find triplet (foreach version)") val (a, b, c) = findTriplet(ints) println("Day 02 part 2 solution: ${a * b * c}") sw.aboutTo("find triplet (indexed version)") val (d, e, f) = Loops(ints).find() println("Day 02 part 2 solution: ${d * e * f}") println(sw.stop().getMessage()) } fun find2020Pair(numbers: Set<Int>): Pair<Int, Int> { numbers.forEach { if (numbers.contains(2020 - it)) return Pair(it, 2020 - it) } error("incorrect puzzle input") } fun findTriplet(numbers: Set<Int>): Triple<Int, Int, Int> { val sorted = numbers.sorted().filter { it < 2020 } sorted.forEach { x -> sorted.filter { (it != x) && (it + x) < 2020 }.forEach { y -> sorted.find { z -> (z != x) && (z != y) && (x + y + z == 2020) }?.also { z -> return Triple(x, y, z) } } } error("incorrect puzzle input") } class Loops(numbers: Set<Int>) { val sorted = numbers.sorted().filter { it < 2020 } fun find():Triple<Int,Int,Int> { for (x in 0..sorted.size) { for (y in (x + 1)..sorted.size) { for (z in (y + 1)..sorted.size) { if (sorted[x] + sorted[y] + sorted[z] == 2020) return Triple(sorted[x], sorted[y], sorted[z]) } } } error("incorrect puzzle input") } }
0
Kotlin
0
0
e666ef0358980656e1c52a3ec08482dd7f86e8a3
1,788
aoc-2020
The Unlicense
ceria/06/src/main/kotlin/Solution.kt
VisionistInc
433,099,870
false
{"Kotlin": 91599, "Go": 87605, "Ruby": 65600, "Python": 21104}
import java.io.File; fun main(args : Array<String>) { val input = File(args.first()).readLines().first().split(",").map { it.toInt() } println("Solution 1: ${solution1(input)}") println("Solution 2: ${solution2(input)}") } private fun solution1(input: List<Int>) :Long { return copulate(80, input) } private fun solution2(input: List<Int>) :Long { return copulate(256, input) } private fun copulate(days: Int, input: List<Int>) :Long { var fish = input.groupingBy { it }.eachCount().mapValues { it.value.toLong() } var newFish = mutableMapOf<Int, Long>() var day = 0 while (day != days) { // For each of the possible fish days for (x in 8 downTo 0) { val count = fish.get(x)?.let{ fish.get(x) } ?: 0 if (x == 0) { newFish.put(8, count) val sixCount = newFish.get(6)?.let{ newFish.get(6) } ?: 0 newFish.put(6, sixCount + count) } else { newFish.put(x-1, count) } } fish = newFish newFish = mutableMapOf<Int, Long>() day++ } return fish.values.sum() }
0
Kotlin
4
1
e22a1d45c38417868f05e0501bacd1cad717a016
1,233
advent-of-code-2021
MIT License
src/Day02.kt
li-xin-yi
573,617,763
false
{"Kotlin": 23422}
fun main() { fun solvePart1(input: List<String>): Int { var res = 0 for (line in input) { val (a, b) = line.split(" ") res += (b[0] - 'X') + 1 when (((a[0] - 'A') - (b[0] - 'X') + 3) % 3) { 0 -> res += 3 2 -> res += 6 } } return res } fun solvePart2(input: List<String>): Int { var res = 0 for (line in input) { val (a, b) = line.split(" ") when (b) { "Z" -> res += 6 + (a[0] - 'A' + 1) % 3 + 1 "Y" -> res += 3 + (a[0] - 'A') + 1 "X" -> res += (a[0] - 'A' + 2) % 3 + 1 } } return res } val testInput = readInput("input/Day02_test") println(solvePart1(testInput)) println(solvePart2(testInput)) }
0
Kotlin
0
1
fb18bb7e462b8b415875a82c5c69962d254c8255
854
AoC-2022-kotlin
Apache License 2.0
src/main/kotlin/se/saidaspen/aoc/aoc2022/Day02.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2022 import se.saidaspen.aoc.util.* fun main() = Day02.run() object Day02 : Day(2022, 2) { override fun part1() : Any { return input.lines() .map { it.split(" ") } .map{(a,x) -> when(a to x) { "A" to "X" -> 3 + 1 "A" to "Y" -> 6 + 2 "A" to "Z" -> 0 + 3 "B" to "X" -> 0 + 1 "B" to "Y" -> 3 + 2 "B" to "Z" -> 6 + 3 "C" to "X" -> 6 + 1 "C" to "Y" -> 0 + 2 "C" to "Z" -> 3 + 3 else -> error(a to x) } }.sum() } override fun part2() : Any { return input.lines() .map{it.split(" ")}.map{(a,x) -> when(a to x) { "A" to "X" -> 0 + 3 "A" to "Y" -> 3 + 1 "A" to "Z" -> 6 + 2 "B" to "X" -> 0 + 1 "B" to "Y" -> 3 + 2 "B" to "Z" -> 6 + 3 "C" to "X" -> 0 + 2 "C" to "Y" -> 3 + 3 "C" to "Z" -> 6 + 1 else -> error(a to x) } }.sum() } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
1,223
adventofkotlin
MIT License
src/main/java/Exercise19.kt
cortinico
317,667,457
false
null
fun main() { val input = object {}.javaClass.getResource("input-19.txt").readText().split("\n\n") val rules = input[0].split("\n").map { it.split(": ") }.associateBy({ it[0] }, { it[1] }) input[1].split("\n").count { matches(it.toCharArray(), 0, rules, listOf("0")) }.also(::println) } fun matches( input: CharArray, idx: Int, map: Map<String, String>, remainingRules: List<String> ): Boolean { return when { idx >= input.size && remainingRules.isEmpty() -> true idx >= input.size && remainingRules.isNotEmpty() -> false remainingRules.isEmpty() -> false else -> { val nextRule = map[remainingRules.first()]!! if (nextRule[0] == '"') { if (nextRule[1] == input[idx]) { matches(input, idx + 1, map, remainingRules.drop(1)) } else { false } } else { nextRule.split(" | ").any { val ruleSequence = it.split(" ") + remainingRules.drop(1) matches(input, idx, map, ruleSequence) } } } } }
1
Kotlin
0
4
a0d980a6253ec210433e2688cfc6df35104aa9df
1,170
adventofcode-2020
MIT License
src/Day06.kt
thomasreader
573,047,664
false
{"Kotlin": 59975}
import java.util.LinkedList import java.util.Queue fun main() { val testInputs = listOf<String>( "bvwbjplbgvbhsrlpgdmjqwftvncz", "nppdvjthqldpwncqszvftbrmjlhg", "nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg", "zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw" ) val testOutputs = testInputs.map { partOne(it) } check(testOutputs == listOf(5, 6, 10, 11)) val input: String = readInput("Day06.txt")[0] println(partOne(input)) val testOutputs2 = testInputs.map { partTwo(it) } check(testOutputs2 == listOf(23, 23, 29, 26)) println(partTwo(input)) } private fun partX(input: String, bufferSize: Int): Int { val previousChars = SizedQueue<Char>(bufferSize) input.forEachIndexed { index, c -> previousChars.offer(c) if (previousChars.isMaxSize) { if (previousChars.hasNoDuplicates()) { return index + 1 } } } return -1 } private fun partOne(input: String): Int = partX(input, 4) private fun partTwo(input: String): Int = partX(input, 14) fun <E> Queue<E>.hasNoDuplicates() = this.toSet().size == this.size data class SizedQueue<E> private constructor( val maxSize: Int, private val linkedList: LinkedList<E> ): Queue<E> by linkedList { constructor(maxSize: Int): this(maxSize, LinkedList()) init { assert(maxSize > 0) } override fun offer(element: E): Boolean { return if (linkedList.size < maxSize) { linkedList.offer(element) } else { linkedList.poll() this.offer(element) } } val isMaxSize get() = linkedList.size == maxSize override fun add(element: E): Boolean { return this.offer(element) } }
0
Kotlin
0
0
eff121af4aa65f33e05eb5e65c97d2ee464d18a6
1,742
advent-of-code-2022-kotlin
Apache License 2.0
classroom/src/main/kotlin/com/radix2/algorithms/week3/TraditionalQuickSort.kt
rupeshsasne
190,130,318
false
{"Java": 66279, "Kotlin": 50290}
package com.radix2.algorithms.week3 import java.util.* fun less(lhs: Int, rhs: Int) = lhs < rhs fun exch(array: IntArray, i: Int, j: Int) { val temp = array[i] array[i] = array[j] array[j] = temp } fun shuffle(array: IntArray) { val rnd = Random() for (i in 1 until array.size) { val randomIndex = rnd.nextInt(i) exch(array, i, randomIndex) } } fun quickSort(array: IntArray) { shuffle(array) quickSort(array, 0, array.size - 1) } fun quickSort(array: IntArray, lo: Int, hi: Int) { if (hi <= lo) return val k = partition(array, lo, hi) quickSort(array, lo, k - 1) quickSort(array, k + 1, hi) } fun partition(array: IntArray, lo: Int, hi: Int): Int { val pivot = array[lo] var i = lo var j = hi + 1 while (true) { while (less(array[++i], pivot)) if (i == hi) break while (less(pivot, array[--j])) if (j == lo) break if (i >= j) break exch(array, i, j) } exch(array, lo, j) return j } // 0, 1, 2, 3, 4, 5, 6, 7, 9 fun main(args: Array<String>) { val array = intArrayOf(6, 10, 1, 3, 2, 6, 8, 9, 5, 15) quickSort(array) println(array.joinToString(", ")) }
0
Java
0
1
341634c0da22e578d36f6b5c5f87443ba6e6b7bc
1,232
coursera-algorithms-part1
Apache License 2.0
src/Day10.kt
phoenixli
574,035,552
false
{"Kotlin": 29419}
fun main() { fun part1(input: List<String>): Int { return sumSignalStrength(input) } fun part2(input: List<String>): Int { draw(input) return input.size } val input = readInput("Day10") println(part1(input)) println(part2(input)) } fun sumSignalStrength(input: List<String>): Int { val cycles = listOf(20, 60, 100, 140, 180, 220) var cycle = 0 var x = 1 var sum = 0 input.forEach{ if (it == "noop") { cycle++ if (cycle in cycles) { sum += cycle * x } } else { cycle++ if (cycle in cycles) { sum += cycle * x } cycle++ if (cycle in cycles) { sum += cycle * x } x += it.split(" ")[1].toInt() } } return sum } fun draw(input: List<String>) { var cycle = 0 var x = 1 var currIdx = 0 input.forEach{ if (it == "noop") { cycle++ currIdx = printChar(currIdx, x, cycle) } else { cycle++ currIdx = printChar(currIdx, x, cycle) cycle++ currIdx = printChar(currIdx, x, cycle) x += it.split(" ")[1].toInt() } } } fun printChar(currIdx: Int, x: Int, cycle: Int): Int { val newLineCycles = listOf(40, 80, 120, 160, 200, 240) var newIdx = currIdx if (currIdx == x - 1 || currIdx == x || currIdx == x + 1) { print('#') newIdx++ } else { print('.') newIdx++ } if (cycle in newLineCycles) { print('\n') newIdx = 0 } return newIdx }
0
Kotlin
0
0
5f993c7b3c3f518d4ea926a792767a1381349d75
1,700
Advent-of-Code-2022
Apache License 2.0
src/main/kotlin/days/Day101.kt
mstar95
317,305,289
false
null
package days import intcode.IntCodeProgram class Day101 : Day(101) { override fun partOne(): Any { val programs = inputList val outputs = programs.map { compute(it) } return outputs.map { it.toString() } } fun compute(program: String): Int { val programInput = program.split(",") val s = listOf(0,1,2,3,4).permutations().map { result(programInput, it)[0] } return s.maxOrNull() ?: 0 } private fun result(programInput: List<String>, input: List<Int>): List<Int> = input.fold(emptyList(), { acc, elem -> IntCodeProgram(programInput, listOf(elem) + acc).calculate() }) override fun partTwo(): Any { val a: List<Unit?> = emptyList() return 0 } fun a(): Unit? { return null } } fun <T> List<T>.permutations(): List<List<T>> = if (this.size <= 1) listOf(this) else { val elementToInsert = first() drop(1).permutations().flatMap { permutation -> (0..permutation.size).map { i -> permutation.toMutableList().apply { add(i, elementToInsert) } } } }
0
Kotlin
0
0
ca0bdd7f3c5aba282a7aa55a4f6cc76078253c81
1,232
aoc-2020
Creative Commons Zero v1.0 Universal
common/src/commonMain/kotlin/ticketToRide/scoreCalculation.kt
Kiryushin-Andrey
253,543,902
false
{"Kotlin": 278687, "Dockerfile": 845, "JavaScript": 191}
package ticketToRide import graph.* import kotlinx.collections.immutable.persistentMapOf // build a weighted graph of all segments occupied by the player fun buildSegmentsGraph(occupiedSegments: List<Segment>): Graph<String> { val segments = occupiedSegments.map { GraphSegment(it.from.value, it.to.value, it.length) } val vertices = segments.flatMap { listOf(it.from, it.to) }.distinct().toList() return vertices.map { city -> city to segments.mapNotNull { when { it.from == city -> it.to to it.weight it.to == city -> it.from to it.weight else -> null } }.let { persistentMapOf(*it.toTypedArray()) } }.let { persistentMapOf(*it.toTypedArray()) } } // calculate the list of tickets fulfilled by the player fun getFulfilledTickets( tickets: List<Ticket>, occupiedSegments: List<Segment>, placedStations: List<CityId>, segmentsOccupiedByOtherPlayers: List<Segment>, graph: Graph<String> = buildSegmentsGraph(occupiedSegments), subgraphs: List<Graph<String>> = graph.splitIntoConnectedSubgraphs().toList() ): List<Ticket> { fun getFulfilledTickets(subgraphs: List<Graph<String>>) = tickets.filter { ticket -> subgraphs.any { it.containsKey(ticket.from.value) && it.containsKey(ticket.to.value) } } return placedStations .asSequence() // get adjacent occupied segments for each station .map { city -> segmentsOccupiedByOtherPlayers.filter { s -> s.from == city || s.to == city } } .filter { it.isNotEmpty() } // pick one segment per each of the stations and add it to the graph of the player's segments // thus build a new graph for each possible usage of each station placed on the map by this player // then pick one of these graphs having the best score regarding the tickets fulfilled .allCombinations() .map { it.fold(graph.builder()) { g, s -> g.apply { addEdge(s.from.value, s.to.value, s.length) } }.build() } .map { getFulfilledTickets(it.splitIntoConnectedSubgraphs().toList()) } .maxByOrNull { it.sumOf { it.points } } ?: getFulfilledTickets(subgraphs) } fun PlayerView.getFulfilledTickets(tickets: List<Ticket>, allPlayers: List<PlayerView>) = getFulfilledTickets( tickets, occupiedSegments, placedStations, allPlayers.filter { it != this }.flatMap { it.occupiedSegments })
1
Kotlin
3
11
0ad7aa0b79f7d97cbac6bc4cd1b13b6a1d81e442
2,508
TicketToRide
MIT License
2021/src/day25/Solution.kt
vadimsemenov
437,677,116
false
{"Kotlin": 56211, "Rust": 37295}
package day25 import java.nio.file.Files import java.nio.file.Paths import kotlin.system.measureTimeMillis fun main() { fun part1(input: Input): Int { val field = input.map { it.toCharArray() } var moves = 0 val herds = ">v" val di = intArrayOf(0, 1) val dj = intArrayOf(1, 0) val moved = arrayOf<ArrayList<Pair<Int, Int>>>(arrayListOf(), arrayListOf()) do { moves++ moved.forEach { it.clear() } repeat(2) { herd -> for (i in field.indices) { for (j in field[i].indices) { if (field[i][j] == herds[herd]) { val ii = (i + di[herd]) % field.size val jj = (j + dj[herd]) % field[ii].size if (field[ii][jj] == '.') { moved[herd].add(i to j) } } } } for ((i, j) in moved[herd]) { val ii = (i + di[herd]) % field.size val jj = (j + dj[herd]) % field[ii].size field[ii][jj] = field[i][j] field[i][j] = '.' } } } while (moved.any { it.isNotEmpty() }) return moves } check(part1(readInput("test-input.txt")) == 58) val millis = measureTimeMillis { println(part1(readInput("input.txt"))) } System.err.println("Done in $millis ms") } private fun readInput(s: String): Input { return Files.newBufferedReader(Paths.get("src/day25/$s")).readLines() } private typealias Input = List<String>
0
Kotlin
0
0
8f31d39d1a94c862f88278f22430e620b424bd68
1,449
advent-of-code
Apache License 2.0
src/Day05.kt
paul-griffith
572,667,991
false
{"Kotlin": 17620}
private typealias SupplyStack = List<ArrayDeque<Char>> fun main() { fun SupplyStack.debug() { val maxStack = maxOf { it.size } for (i in maxStack downTo 0) { forEach { column -> val value = column.getOrNull(i) if (value != null) { print("[$value]") } else { print(" ") } } println() } indices.forEach { print(" ${it + 1} ") } println() } fun part1(stack: SupplyStack, moves: Sequence<String>): String { // stack.debug() // println("-".repeat(20)) val movePattern = """(\d+).+(\d+).+(\d+)""".toRegex() for (line in moves) { // println(moves) val (qty, from, to) = movePattern.find(line)!!.groupValues.drop(1).map(String::toInt) repeat(qty) { val popped = stack[from - 1].removeLast() stack[to - 1].addLast(popped) // stack.debug() } // println("-".repeat(20)) } // stack.debug() return stack.map { it.last() }.toCharArray().concatToString() } fun part2(stack: SupplyStack, moves: Sequence<String>): String { // stack.debug() // println("-".repeat(20)) val movePattern = """(\d+).+(\d+).+(\d+)""".toRegex() for (line in moves) { // println(moves) val (qty, from, to) = movePattern.find(line)!!.groupValues.drop(1).map(String::toInt) val onHook = List(qty) { stack[from - 1].removeLast() }.asReversed() stack[to - 1].addAll(onHook) // stack.debug() // println("-".repeat(20)) } // stack.debug() return stack.map { it.last() }.toCharArray().concatToString() } fun ArrayDeque(chars: CharSequence): ArrayDeque<Char> { return ArrayDeque(chars.toList()) } val sampleStack: SupplyStack = listOf( ArrayDeque("ZN"), ArrayDeque("MCD"), ArrayDeque("P"), ) val sampleMoves = """ move 1 from 2 to 1 move 3 from 1 to 3 move 2 from 2 to 1 move 1 from 1 to 2 """.trimIndent().lineSequence() val realStack: SupplyStack = listOf( ArrayDeque("FCPGQR"), ArrayDeque("WTCP"), ArrayDeque("BHPMC"), ArrayDeque("LTQSMPR"), ArrayDeque("PHJZVGN"), ArrayDeque("DPJ"), ArrayDeque("LGPZFJTR"), ArrayDeque("NLHCFPTJ"), ArrayDeque("GVZQHTCW"), ) // println(part1(realStack, readInput("day05"))) println(part2(realStack, readInput("day05"))) }
0
Kotlin
0
0
100a50e280e383b784c3edcf65b74935a92fdfa6
2,699
aoc-2022
Apache License 2.0
src/Day01.kt
davidkna
572,439,882
false
{"Kotlin": 79526}
fun main() { fun part1(input: List<List<String>>): Int = input.maxOf { l -> l.sumOf { n -> n.toInt() } } fun part2(input: List<List<String>>): Int { val max = intArrayOf(0, 0, 0) input.map { l -> l.sumOf { n -> n.toInt() } }.forEach { n -> if (n > max[0]) { max[0] = n max.sort() } } return max.sum() } val testInput = readInputDoubleNewline("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInputDoubleNewline("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ccd666cc12312537fec6e0c7ca904f5d9ebf75a3
639
aoc-2022
Apache License 2.0
Hangman/safeUserInputFunction/src/main/kotlin/jetbrains/kotlin/course/hangman/Main.kt
jetbrains-academy
504,249,857
false
{"Kotlin": 1108971}
package jetbrains.kotlin.course.hangman // You will use this function later fun getGameRules(wordLength: Int, maxAttemptsCount: Int) = "Welcome to the game!$newLineSymbol$newLineSymbol" + "In this game, you need to guess the word made by the computer.$newLineSymbol" + "The hidden word will appear as a sequence of underscores, one underscore means one letter.$newLineSymbol" + "You have $maxAttemptsCount attempts to guess the word.$newLineSymbol" + "All words are English words, consisting of $wordLength letters.$newLineSymbol" + "Each attempt you should enter any one letter,$newLineSymbol" + "if it is in the hidden word, all matches will be guessed.$newLineSymbol$newLineSymbol" + "" + "For example, if the word \"CAT\" was guessed, \"_ _ _\" will be displayed first, " + "since the word has 3 letters.$newLineSymbol" + "If you enter the letter A, you will see \"_ A _\" and so on.$newLineSymbol$newLineSymbol" + "" + "Good luck in the game!" // You will use this function later fun isWon(complete: Boolean, attempts: Int, maxAttemptsCount: Int) = complete && attempts <= maxAttemptsCount // You will use this function later fun isLost(complete: Boolean, attempts: Int, maxAttemptsCount: Int) = !complete && attempts > maxAttemptsCount fun deleteSeparator(guess: String) = guess.replace(separator, "") fun isComplete(secret: String, currentGuess: String) = secret == deleteSeparator(currentGuess) fun generateNewUserWord(secret: String, guess: Char, currentUserWord: String): String { var newUserWord = "" for (i in secret.indices) { newUserWord += if (secret[i] == guess) { "${secret[i]}$separator" } else { "${currentUserWord[i * 2]}$separator" } } // Just newUserWord will be ok for the tests return newUserWord.removeSuffix(separator) } fun generateSecret() = words.random() fun getHiddenSecret(wordLength: Int) = List(wordLength) { underscore }.joinToString(separator) fun isCorrectInput(userInput: String): Boolean { if (userInput.length != 1) { println("The length of your guess should be 1! Try again!") return false } if (!userInput[0].isLetter()) { println("You should input only English letters! Try again!") return false } return true } fun main() { // Uncomment this code on the last step of the game // println(getGameRules(wordLength, maxAttemptsCount)) // playGame(generateSecret(), maxAttemptsCount) }
14
Kotlin
1
6
bc82aaa180fbd589b98779009ca7d4439a72d5e5
2,564
kotlin-onboarding-introduction
MIT License
src/main/kotlin/exercise/easy/id121/Solution121.kt
kotler-dev
706,379,223
false
{"Kotlin": 63887}
package exercise.easy.id121 class Solution121 { fun maxProfit(prices: IntArray): Int { if (prices.size < 2) return 0 var profit = 0 var min = Int.MAX_VALUE var max = 0 for (i in 0..<prices.size) { if (prices[i] < min) { min = prices[i] max = 0 } if (prices[i] > max) max = prices[i] if (max - min > profit) profit = max - min } return profit } /* fun maxProfit(prices: IntArray): Int { if (prices.size < 2) return 0 var profit = 0 var min = Int.MAX_VALUE var max = 0 val minn = prices.slice(1..<prices.size).minBy { it } val m = prices.slice(1..<prices.size).maxBy { it } val mIndex = prices.lastIndexOf(m) for (i in 0..mIndex) { if (prices[i] < min) { min = prices[i] max = m } if (prices[i] > max) max = prices[i] if (max - min > profit) profit = max - min } return profit } fun maxProfit(prices: IntArray): Int { if (prices.size < 2) return 0 var profit = 0 for (i in prices.indices) { for (j in i + 1..<prices.size) { if (prices[j] - prices[i] > profit) { profit = prices[j] - prices[i] } } } return profit } fun maxProfit(prices: IntArray): Int { if (prices.size < 2) return 0 var profit = 0 val min = prices.slice(0..prices.size - 1).indices.minBy { prices[it] } val minIndex = prices.lastIndexOf(prices[min]) val p = prices.slice(minIndex..prices.size - 1) val max = p.indices.maxBy { p[it] } val maxIndex = p.lastIndexOf(p[max]) val result = p[maxIndex] - prices[minIndex] if (result > profit) profit = result return profit } fun maxProfit(prices: IntArray): Int { var profit = 0 for ((index, value) in prices.withIndex()) { val i1 = index + 1 if (i1 < prices.size) { if (prices[i1] > value) { val max = prices.slice(i1..prices.size - 1).max() if (profit < max - value) { profit = max - value } } } } return profit } fun maxProfit(prices: IntArray): Int { var profit = 0 val minIndex = prices.indices.minBy { prices[it] } ?: 0 val slice = prices.slice(minIndex..prices.size - 1) val maxIndex = slice.indices.maxBy { slice[it] } ?: 0 val result = slice[maxIndex] - prices[minIndex] if (result > profit) profit = result return profit } fun maxProfit(prices: IntArray): Int { if (prices.size < 2) return 0 var profit = 0 val maxSlice = prices.slice(1..prices.size - 1) val maxIndex = maxSlice.indices.maxBy { maxSlice[it] } ?: 0 val minSlice = prices.slice(0..maxSlice.lastIndexOf(maxSlice[maxIndex])) val minIndex = minSlice.indices.minBy { minSlice[it] } ?: 0 val result = maxSlice[maxIndex] - minSlice[minIndex] if (result > profit) profit = result return profit } */ }
0
Kotlin
0
0
0659e72dbf28ce0ec30aa550b6a83c1927161b14
3,359
kotlin-leetcode
Apache License 2.0
src/day04/Day04.kt
xxfast
572,724,963
false
{"Kotlin": 32696}
package day04 import readLines fun main() { fun format(input: List<String>): List<List<IntRange>> = input.map { line -> line.split(",").map { it.split("-").let { (start, end) -> start.toInt()..end.toInt() } } } fun part1(input: List<String>): Int = format(input).count { (first, second) -> (first - second).isEmpty() || (second - first).isEmpty() } fun part2(input: List<String>): Int = format(input).count { (first, second) -> first.intersect(second).isNotEmpty() } // test if implementation meets criteria from the description, like: val testInput: List<String> = readLines("day04/test.txt") check(part1(testInput) == 2) check(part2(testInput) == 4) val input: List<String> = readLines("day04/input.txt") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
a8c40224ec25b7f3739da144cbbb25c505eab2e4
787
advent-of-code-22
Apache License 2.0
src/day23/Main.kt
nikwotton
572,814,041
false
{"Kotlin": 77320}
package day23 import day23.Direction.East import day23.Direction.North import day23.Direction.South import day23.Direction.West import java.io.File val workingDir = "src/${object {}.javaClass.`package`.name}" fun main() { val sample = File("$workingDir/sample.txt") val input1 = File("$workingDir/input_1.txt") println("Step 1a: ${runStep1(sample)}") // 110 println("Step 1b: ${runStep1(input1)}") // 3689 println("Step 2a: ${runStep2(sample)}") // 20 println("Step 2b: ${runStep2(input1)}") // 965 } data class Position(var x: Int, var y: Int) { var plannedNextPosition: Position? = null } sealed class Direction { object North : Direction() object South : Direction() object East : Direction() object West : Direction() } fun runStep1(input: File): String { val elves = ArrayList<Position>() input.readLines().forEachIndexed { y, row -> row.forEachIndexed { x, elf -> if (elf == '#') elves.add(Position(x, y)) } } var order = listOf(North, South, West, East) fun tryNorth(elf: Position): Boolean = if (elves.none { it in (-1..1).map { Position(elf.x + it, elf.y - 1) } }) { elf.plannedNextPosition = Position(elf.x, elf.y - 1) true } else false fun tryEast(elf: Position) = if (elves.none { it in (-1..1).map { Position(elf.x+1, elf.y + it) } }) { elf.plannedNextPosition = Position(elf.x+1, elf.y) true } else false fun trySouth(elf: Position) = if (elves.none { it in (-1..1).map { Position(elf.x+it, elf.y + 1) } }) { elf.plannedNextPosition = Position(elf.x, elf.y+1) true } else false fun tryWest(elf: Position) = if (elves.none { it in (-1..1).map { Position(elf.x-1, elf.y + it) } }) { elf.plannedNextPosition = Position(elf.x-1, elf.y) true } else false repeat(10) { elves.forEach { elf -> if ((-1..1).flatMap { x -> (-1..1).map { y -> Position(elf.x-x, elf.y-y) } }.filter { it != elf }.any { it in elves }) { var hitHere = false order.forEach { when (it) { East -> if (!hitHere && tryEast(elf)) hitHere = true North -> if (!hitHere && tryNorth(elf)) hitHere = true South -> if (!hitHere && trySouth(elf)) hitHere = true West -> if (!hitHere && tryWest(elf)) hitHere = true } } } if (elf.plannedNextPosition == null) { elf.plannedNextPosition = elf } } val proposedPositions = elves.map { it.plannedNextPosition } elves.forEach { elf -> if (proposedPositions.count { it == Position(elf.plannedNextPosition!!.x, elf.plannedNextPosition!!.y) } == 1) { elf.x = elf.plannedNextPosition!!.x elf.y = elf.plannedNextPosition!!.y } elf.plannedNextPosition = null } order = order.drop(1) + order.first() } val minX = elves.minOf { it.x } val maxX = elves.maxOf { it.x } val minY = elves.minOf { it.y } val maxY = elves.maxOf { it.y } return (minX..maxX).sumOf { x -> (minY..maxY).map { y -> if (elves.contains(Position(x, y))) 0 else 1 }.sum() }.toString() } fun runStep2(input: File): String { val elves = ArrayList<Position>() input.readLines().forEachIndexed { y, row -> row.forEachIndexed { x, elf -> if (elf == '#') elves.add(Position(x, y)) } } var order = listOf(North, South, West, East) fun tryNorth(elf: Position): Boolean = if (elves.none { it in (-1..1).map { Position(elf.x + it, elf.y - 1) } }) { elf.plannedNextPosition = Position(elf.x, elf.y - 1) true } else false fun tryEast(elf: Position) = if (elves.none { it in (-1..1).map { Position(elf.x+1, elf.y + it) } }) { elf.plannedNextPosition = Position(elf.x+1, elf.y) true } else false fun trySouth(elf: Position) = if (elves.none { it in (-1..1).map { Position(elf.x+it, elf.y + 1) } }) { elf.plannedNextPosition = Position(elf.x, elf.y+1) true } else false fun tryWest(elf: Position) = if (elves.none { it in (-1..1).map { Position(elf.x-1, elf.y + it) } }) { elf.plannedNextPosition = Position(elf.x-1, elf.y) true } else false var count = 0 var hash = elves.joinToString(":") { "${it.x},${it.y}" } var prevHash = "" while(hash != prevHash) { elves.forEach { elf -> if ((-1..1).flatMap { x -> (-1..1).map { y -> Position(elf.x-x, elf.y-y) } }.filter { it != elf }.any { it in elves }) { var hitHere = false order.forEach { when (it) { East -> if (!hitHere && tryEast(elf)) hitHere = true North -> if (!hitHere && tryNorth(elf)) hitHere = true South -> if (!hitHere && trySouth(elf)) hitHere = true West -> if (!hitHere && tryWest(elf)) hitHere = true } } } if (elf.plannedNextPosition == null) { elf.plannedNextPosition = elf } } val proposedPositions = elves.map { it.plannedNextPosition } elves.forEach { elf -> if (proposedPositions.count { it == Position(elf.plannedNextPosition!!.x, elf.plannedNextPosition!!.y) } == 1) { elf.x = elf.plannedNextPosition!!.x elf.y = elf.plannedNextPosition!!.y } elf.plannedNextPosition = null } order = order.drop(1) + order.first() prevHash = hash hash = elves.joinToString(":") { "${it.x},${it.y}" } count++ println("Currently on round: $count") } return count.toString() }
0
Kotlin
0
0
dee6a1c34bfe3530ae6a8417db85ac590af16909
6,157
advent-of-code-2022
Apache License 2.0
src/Day06.kt
phamobic
572,925,492
false
{"Kotlin": 12697}
fun main() { fun part(input: List<String>, markerSize: Int): Int { val signal = input.first() val marker = mutableListOf<Char>() var count = 0 signal.forEach { character -> count++ marker.add(character) if (marker.size > markerSize) { marker.removeFirst() } if (marker.toSet().size == markerSize) { return count } } return count } fun part1(input: List<String>): Int = part(input = input, markerSize = 4) fun part2(input: List<String>): Int = part(input = input, markerSize = 14) val testInput1 = readInput("Day06_test_1") val testInput2 = readInput("Day06_test_2") val testInput3 = readInput("Day06_test_3") val testInput4 = readInput("Day06_test_4") val testInput5 = readInput("Day06_test_5") check(part1(testInput1) == 7) check(part1(testInput2) == 5) check(part1(testInput3) == 6) check(part1(testInput4) == 10) check(part1(testInput5) == 11) check(part2(testInput1) == 19) check(part2(testInput2) == 23) check(part2(testInput3) == 23) check(part2(testInput4) == 29) check(part2(testInput5) == 26) }
1
Kotlin
0
0
34b2603470c8325d7cdf80cd5182378a4e822616
1,240
aoc-2022
Apache License 2.0
kotest-property/src/commonMain/kotlin/io/kotest/property/arbitrary/char.kt
kotest
47,071,082
false
{"Kotlin": 4460715, "CSS": 352, "Java": 145}
package io.kotest.property.arbitrary import io.kotest.property.Arb import io.kotest.property.Gen /** * Returns a [Arb] that generates randomly-chosen Chars. Custom characters can be generated by * providing CharRanges. Distribution will be even across the ranges of Chars. * For example: * Gen.char('A'..'C', 'D'..'E') * Ths will choose A, B, C, D, and E each 20% of the time. */ fun Arb.Companion.char(range: CharRange, vararg ranges: CharRange): Arb<Char> { return Arb.char(listOf(range) + ranges) } /** * Returns a [Arb] that generates randomly-chosen Chars. Custom characters can be generated by * providing a list of CharRanges. Distribution will be even across the ranges of Chars. * For example: * Gen.char(listOf('A'..'C', 'D'..'E') * Ths will choose A, B, C, D, and E each 20% of the time. * * If no parameter is given, ASCII characters will be generated. */ fun Arb.Companion.char(ranges: List<CharRange> = CharSets.BASIC_LATIN): Arb<Char> { require(ranges.all { !it.isEmpty() }) { "Ranges cannot be empty" } require(ranges.isNotEmpty()) { "List of ranges must have at least one range" } fun makeRangeWeightedGen(): Arb<CharRange> { val weightPairs = ranges.map { range -> val weight = range.last.code - range.first.code + 1 Pair(weight, range) } return Arb.choose(weightPairs[0], weightPairs[1], *weightPairs.drop(2).toTypedArray()) } // Convert the list of CharRanges into a weighted Gen in which // the ranges are chosen from the list using the length of the // range as the weight. val arbRange: Arb<CharRange> = if (ranges.size == 1) Arb.constant(ranges.first()) else makeRangeWeightedGen() return arbRange.flatMap { charRange -> arbitrary { charRange.random(it.random) } } } /** * Returns an [Arb] that produces [CharArray]s where [length] produces the length of the arrays and * [content] produces the content of the arrays. */ fun Arb.Companion.charArray(length: Gen<Int>, content: Arb<Char>): Arb<CharArray> = toPrimitiveArray(length, content, Collection<Char>::toCharArray) private object CharSets { val CONTROL = listOf('\u0000'..'\u001F', '\u007F'..'\u007F') val WHITESPACE = listOf('\u0020'..'\u0020', '\u0009'..'\u0009', '\u000A'..'\u000A') val BASIC_LATIN = listOf('\u0021'..'\u007E') }
102
Kotlin
615
4,198
7fee2503fbbdc24df3c594ac6b240c11b265d03e
2,337
kotest
Apache License 2.0
src/main/kotlin/com/tonnoz/adventofcode23/day16/Day16.kt
tonnoz
725,970,505
false
{"Kotlin": 78395}
package com.tonnoz.adventofcode23.day16 import com.tonnoz.adventofcode23.utils.println import com.tonnoz.adventofcode23.utils.readCharMatrix import kotlinx.coroutines.runBlocking import java.lang.IllegalArgumentException import kotlin.system.measureTimeMillis object Day16 { @JvmStatic fun main(args: Array<String>) = runBlocking { val input = "input16.txt".readCharMatrix().toMutableList() val time = measureTimeMillis { val contraption = input.mapIndexed{i, row -> row.mapIndexed{j, value -> Cell(i, j, value)}} val memory = mutableMapOf<Cell,List<Direction>>() go(contraption[0][0], contraption, memory, Direction.RIGHT) contraption.flatMap { it.filter { it.energized } }.count().println() // PRINT COLORED MATRIX :) // contraption.forEach { row -> row.forEach { print(if(it.energized) it.value.bold("33") else it.value) }; println("") } } println("P1 time: $time ms") } data class Cell(val row: Int, val column: Int, val value: Char, var energized: Boolean = false) { fun nextCell(direction: Direction, contraption: List<List<Cell>>): Cell? { val contraptionHeight = contraption.size val contraptionWidth = contraption[0].size return when (direction) { Direction.UP -> if(row > 0) contraption[row-1][column] else null Direction.DOWN -> if(row < contraptionHeight -1) contraption[row+1][column] else null Direction.LEFT -> if(column > 0) contraption[row][column-1] else null Direction.RIGHT -> if(column < contraptionWidth -1) contraption[row][column+1] else null } } } enum class Direction { UP, DOWN, LEFT, RIGHT } private fun go(cell: Cell, contraption: List<List<Cell>>, memory: MutableMap<Cell, List<Direction>>, direction: Direction) { if(memory[cell]?.contains(direction) == true) return cell.energized = true memory[cell] = memory[cell]?.plus(direction) ?: listOf(direction) val nextMoves = when (cell.value) { '.' -> listOf(direction) '|' , '-' -> split(cell, direction) '/','\\' -> listOf(angle(cell, direction)) else -> throw IllegalArgumentException("Invalid cell: $cell") } nextMoves.forEach { cell.nextCell(it, contraption)?.let { nextCell -> go(nextCell, contraption, memory, it) } } } private fun split(cell: Cell, direction: Direction): List<Direction> { return when (cell.value) { '|' -> when (direction) { Direction.UP -> listOf(Direction.UP) Direction.DOWN -> listOf(Direction.DOWN) Direction.LEFT,Direction.RIGHT -> listOf(Direction.UP, Direction.DOWN) } '-' -> when (direction) { Direction.UP, Direction.DOWN -> listOf(Direction.LEFT, Direction.RIGHT) Direction.LEFT -> listOf(Direction.LEFT) Direction.RIGHT -> listOf(Direction.RIGHT) } else -> { throw IllegalArgumentException("Invalid split cell: $cell")} } } private fun angle(cell: Cell, direction: Direction): Direction { return when (cell.value) { '/' -> when (direction) { Direction.UP -> Direction.RIGHT Direction.DOWN -> Direction.LEFT Direction.LEFT -> Direction.DOWN Direction.RIGHT -> Direction.UP } '\\' -> when (direction) { Direction.UP -> Direction.LEFT Direction.DOWN -> Direction.RIGHT Direction.LEFT -> Direction.UP Direction.RIGHT -> Direction.DOWN } else -> { throw IllegalArgumentException("Invalid angle cell: $cell")} } } }
0
Kotlin
0
0
d573dfd010e2ffefcdcecc07d94c8225ad3bb38f
3,553
adventofcode23
MIT License
src/main/kotlin/days/Day13.kt
butnotstupid
571,247,661
false
{"Kotlin": 90768}
package days class Day13 : Day(13) { override fun partOne(): Any { return inputList.chunked(3).withIndex().mapNotNull { (index, lines) -> val (left, right) = parseLine(lines[0]) to parseLine(lines[1]) if (left < right) index + 1 else null }.sum() } override fun partTwo(): Any { return inputList.chunked(3).flatMap { lines -> val (left, right) = parseLine(lines[0]) to parseLine(lines[1]) listOf(left, right) }.let { packets -> (packets.count { it < parseLine("[[2]]")} + 1) * (packets.count { it < parseLine("[[6]]")} + 2) } } private fun parseLine(s: String): Packet { val root = Packet() var currentPacket = root s.substring(1, s.length - 1).forEachIndexed { index, charAt -> when (charAt) { '[' -> { currentPacket = Packet(parent = currentPacket).also { currentPacket.child.add(it) } } ',' -> { if (currentPacket.value == null && currentPacket.child.isEmpty()) { Packet(value = - 1, parent = currentPacket).also { currentPacket.child.add(it) } } else currentPacket = currentPacket.parent!! } ']' -> { if (currentPacket.value == null && currentPacket.child.isEmpty()) { Packet(value = - 1, parent = currentPacket).also { currentPacket.child.add(it) } } else currentPacket = currentPacket.parent!! } in '0'..'9' -> { if (currentPacket.value == null) { currentPacket = Packet(parent = currentPacket).also { currentPacket.child.add(it) } } currentPacket.value = (currentPacket.value ?: 0) * 10 + charAt.code - '0'.code } else -> throw IllegalStateException("Unknown input char: $charAt") } } return root } data class Packet(var value: Int? = null, var child: MutableList<Packet> = mutableListOf(), val parent: Packet? = null) { operator fun compareTo(other: Packet): Int { return when { this.value != null && other.value != null -> this.value!!.compareTo(other.value!!) this.value == null && other.value == null -> { this.child.zip(other.child).firstNotNullOfOrNull { (left, right) -> if (left.compareTo(right) == 0) null else left.compareTo(right) } ?: this.child.size.compareTo(other.child.size) } else -> { val wrap = Packet() when { this.value != null -> { this.copy(parent = wrap).also { wrap.child.add(it) } wrap.compareTo(other) } else -> { other.copy(parent = wrap).also { wrap.child.add(it) } this.compareTo(wrap) } } } } } override fun toString(): String { return if (value != null) "${if (value == -1) "" else value}" else child.map { it.toString() }.joinToString(",").let { "[$it]" } } } }
0
Kotlin
0
0
4760289e11d322b341141c1cde34cfbc7d0ed59b
3,498
aoc-2022
Creative Commons Zero v1.0 Universal
kotlin/src/com/daily/algothrim/leetcode/hard/MaximalRectangle.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode.hard import java.util.* /** * 85. 最大矩形 * * 给定一个仅包含 0 和 1 、大小为 rows x cols 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。 */ class MaximalRectangle { companion object { @JvmStatic fun main(args: Array<String>) { println(MaximalRectangle().maximalRectangle(arrayOf( charArrayOf('1', '0', '1', '0', '0'), charArrayOf('1', '0', '1', '1', '1'), charArrayOf('1', '1', '1', '1', '1'), charArrayOf('1', '0', '0', '1', '0') ))) println(MaximalRectangle().maximalRectangle(arrayOf( charArrayOf('1') ))) } } // matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]] // 6 fun maximalRectangle(matrix: Array<CharArray>): Int { val m = matrix.size if (m == 0) return 0 val n = matrix[0].size val left = Array(m) { IntArray(n) } for (i in 0 until m) { for (j in 0 until n) { if (matrix[i][j] == '1') { left[i][j] = (if (j == 0) 0 else left[i][j - 1]) + 1 } } } var result = 0 for (j in 0 until n) { val up = IntArray(m) val down = IntArray(m) val stack = LinkedList<Int>() for (i in 0 until m) { while (stack.isNotEmpty() && left[stack.peek()][j] >= left[i][j]) { stack.pop() } up[i] = if (stack.isEmpty()) -1 else stack.peek() stack.push(i) } stack.clear() for (i in m - 1 downTo 0) { while (stack.isNotEmpty() && left[stack.peek()][j] >= left[i][j]) { stack.pop() } down[i] = if (stack.isEmpty()) m else stack.peek() stack.push(i) } for (i in 0 until m) { val height = down[i] - up[i] - 1 val area = height * left[i][j] result = Math.max(result, area) } } return result } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
2,313
daily_algorithm
Apache License 2.0
src/main/kotlin/Day003.kt
teodor-vasile
573,434,400
false
{"Kotlin": 41204}
class Day003 { fun part1(input: List<String>): Int { var prioritiesSum = 0 for (rucksack in input) { val firstHalf = rucksack.subSequence(0, rucksack.length / 2) val lastHalf = rucksack.subSequence(rucksack.length / 2, rucksack.length) for (char in lastHalf) { if (firstHalf.contains(char)) { val itemPriority = if (char.isLowerCase()) char.code - 96 else char.code - 38 prioritiesSum += itemPriority break } } } return prioritiesSum } fun part2(input: List<String>): Int { val chunkedInput = input.chunked(3) var prioritiesSum = 0 for (chunk in chunkedInput) { for (char in chunk[0]) { if (chunk[1].contains(char) && chunk[2].contains(char)) { val itemPriority = if (char.isLowerCase()) char.code - 96 else char.code - 38 prioritiesSum += itemPriority break } } } return prioritiesSum // check out zipWithNext() for this solution // and intersect() method // single() to return one value } }
0
Kotlin
0
0
2fcfe95a05de1d67eca62f34a1b456d88e8eb172
1,263
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/dp/longestPalindromeSubseq/SolutionKt.kt
eleven-max
441,597,605
false
{"Java": 104251, "Kotlin": 41506}
package dp.longestPalindromeSubseq import com.evan.dynamicprogramming.Common.CommonUtil //https://leetcode-cn.com/problems/longest-palindromic-subsequence/ class SolutionKt { fun longestPalindromeSubseq(s: String): Int { val s2 = s.reversed() println(s2) return longestCommonSubsequence(s, s2) } private fun longestCommonSubsequence(text1: String, text2: String): Int { val dp = Array(text1.length + 1) { IntArray(text2.length + 1) { 0 } } for (i in 1..text1.length) { val c1 = text1[i - 1] for (j in 1..text2.length) { val c2 = text2[j - 1] if (c1 == c2) { dp[i][j] = dp[i - 1][j - 1] + 1 } else { dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]) } } } CommonUtil.printMatrix(dp) return dp[text1.length][text2.length] } } fun main(){ val solutionKt = SolutionKt() val s = "bbbab" val r = solutionKt.longestPalindromeSubseq(s) println(r) }
0
Java
0
0
2e9b234b052896c6b8be07044d2b0c6812133e66
1,078
Learn_Algorithm
Apache License 2.0
src/main/kotlin/Day01.kt
Mariyo
728,179,583
false
{"Kotlin": 10845}
class Day01 { fun sumCalibrationValuesFromInput(input: List<String>): Int { var result = 0 input.forEach { result += it.calibrate() } return result } fun sumNormalizedValuesFromInput(input: List<String>): Int { var result = 0 input.forEach { val normalized = it.normalize().calibrate() result += normalized } return result } } private fun String.normalize(): String { var normalized = "" var wordDigit = "" run loop@{ this.lowercase().forEach { oneChar -> if (oneChar.isDigit()) { normalized += oneChar return@loop } wordDigit += "$oneChar" val wordDigitAsDigit = wordDigit .replace("one", "1") .replace("two", "2") .replace("three", "3") .replace("four", "4") .replace("five", "5") .replace("six", "6") .replace("seven", "7") .replace("eight", "8") .replace("nine", "9") if (wordDigitAsDigit != wordDigit) { normalized += wordDigitAsDigit.replace(Regex("\\D+"), "") return@loop } } } wordDigit = "" run loop@{ this.lowercase().reversed().forEach { oneChar -> if (oneChar.isDigit()) { normalized += oneChar return@loop } wordDigit = "$oneChar" + wordDigit val wordDigitAsDigit = wordDigit .replace("one", "1") .replace("two", "2") .replace("three", "3") .replace("four", "4") .replace("five", "5") .replace("six", "6") .replace("seven", "7") .replace("eight", "8") .replace("nine", "9") if (wordDigitAsDigit != wordDigit) { normalized += wordDigitAsDigit.replace(Regex("\\D+"), "") return@loop } } } return normalized } private fun String.calibrate(): Int { val calibrated = this.replace(Regex("\\D+"), "") val first = calibrated.first() val last = calibrated.last() val result = "$first$last".toInt() return result }
0
Kotlin
0
0
da779852b808848a26145a81cbf4330f6af03d84
2,397
advent-of-code-kotlin-2023
Apache License 2.0
src/main/kotlin/adventofcode/PuzzleDay04.kt
MariusSchmidt
435,574,170
false
{"Kotlin": 28290}
package adventofcode import java.io.File class PuzzleDay04 { fun determineWinningBoardOrder(file: File): List<BingoBoard> { val pulls = readPulls(file) val boards = readBoards(file) return pulls.flatMap { pulledNumber -> boards.filter { !it.won } .onEach { it.drawNumber(pulledNumber) } .filter { it.won } } } private fun readPulls(file: File): List<Int> = file.useLines { seq -> seq.first().split(",").map { it.toInt() } } private fun readBoards(file: File): List<BingoBoard> = file.useLines { seq -> seq.drop(2) .flatMap { it.split(" ") } .filter { it.isNotEmpty() } .map { it.toInt() } .windowed(25, 25) .mapIndexed { index, boardNumbers -> BingoBoard(index + 1, boardNumbers.toIntArray()) } .toList() } class BingoBoard(val id: Int, numbers: IntArray) { companion object { const val X_SIZE = 5 const val Y_SIZE = 5 const val WINNING_COUNT = 5 } private val fields: Array<BingoBoardField> = numbers.map { BingoBoardField(it) }.toTypedArray() var won: Boolean = false var drawsToWin: Int = 0 var lastNumber: Int = -1 fun score(): Int = if (!won) 0 else fields.filter { !it.pulled }.sumOf { it.number } * lastNumber fun drawNumber(number: Int) { if (won) return fields.filter { it.number == number }.onEach { it.pulled = true } drawsToWin++ won = checkWon() lastNumber = number } private fun checkWon(): Boolean = ((0 until X_SIZE).map { columnFields(it) } + (0 until Y_SIZE).map { rowFields(it) }).any { it.checkWon() } private fun List<BingoBoardField>.checkWon(): Boolean = count { it.pulled } >= WINNING_COUNT private fun rowFields(rowIndex: Int): List<BingoBoardField> = fields.slice(rowIndex * X_SIZE until rowIndex * X_SIZE + X_SIZE) private fun columnFields(columnIndex: Int): List<BingoBoardField> = fields.slice(columnIndex until X_SIZE * Y_SIZE step X_SIZE) } class BingoBoardField(val number: Int) { var pulled: Boolean = false } }
0
Kotlin
0
0
2b7099350fa612cb69c2a70d9e57a94747447790
2,326
adventofcode2021
Creative Commons Zero v1.0 Universal
src/main/kotlin/me/grison/aoc/y2015/Day16.kt
agrison
315,292,447
false
{"Kotlin": 267552}
package me.grison.aoc.y2015 import me.grison.aoc.* // not parsing the input class Day16 : Day(16, 2015) { override fun title() = "Aunt Sue" private val known = mutableMapOf("children" to 3, "cats" to 7, "samoyeds" to 2, "pomeranians" to 3, "akitas" to 0, "vizslas" to 0, "goldfish" to 5, "trees" to 3, "cars" to 2, "perfumes" to 1) //val special = mapOf("cats",) override fun partOne() = findAunt { a, b -> isRealAunt1(a, b) } override fun partTwo() = findAunt { a, b -> isRealAunt2(a, b) } private fun findAunt(isRealAunt: (things: MutableList<String>, values: MutableList<String>) -> Boolean): Int { inputList.forEach { line -> val x = "^Sue (\\d+): (\\w+): (\\d+), (\\w+): (\\d+), (\\w+): (\\d+)$".regex().find(line) val num = x!!.groupValues[1].toInt() val things = mutableListOf(x.groupValues[2], x.groupValues[4], x.groupValues[6]) val values = mutableListOf(x.groupValues[3], x.groupValues[5], x.groupValues[7]) if (isRealAunt(things, values)) return num } return 0 } private fun isRealAunt1(things: MutableList<String>, values: MutableList<String>): Boolean { for ((thing, value) in things.zip(values)) if (known[thing] != value.toInt()) return false return true } private fun isRealAunt2(things: MutableList<String>, values: MutableList<String>): Boolean { for (special in listOf("cats", "trees", "pomeranians", "goldfish")) { if (special in things) { val numThings = values.removeAt(things.indexOf(special)).toInt() things.remove(special) when (special) { "cats" -> if (numThings <= known[special]!!) return false "trees" -> if (numThings <= known[special]!!) return false "pomeranians" -> if (numThings >= known[special]!!) return false "goldfish" -> if (numThings >= known[special]!!) return false } } } return isRealAunt1(things, values) } }
0
Kotlin
3
18
ea6899817458f7ee76d4ba24d36d33f8b58ce9e8
2,169
advent-of-code
Creative Commons Zero v1.0 Universal
src/main/kotlin/g0601_0700/s0677_map_sum_pairs/MapSum.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0601_0700.s0677_map_sum_pairs // #Medium #String #Hash_Table #Design #Trie #2023_02_15_Time_197_ms_(80.00%)_Space_36.1_MB_(55.00%) class MapSum { internal class Node { var `val`: Int = 0 var child: Array<Node?> = arrayOfNulls(26) } private val root: Node = Node() fun insert(key: String, `val`: Int) { var curr: Node? = root for (c in key.toCharArray()) { if (curr!!.child[c.code - 'a'.code] == null) { curr.child[c.code - 'a'.code] = Node() } curr = curr.child[c.code - 'a'.code] } curr!!.`val` = `val` } private fun sumHelper(root: Node?): Int { var o = 0 for (i in 0..25) { if (root!!.child[i] != null) { o += root.child[i]!!.`val` + sumHelper(root.child[i]) } } return o } fun sum(prefix: String): Int { var curr: Node? = root for (c in prefix.toCharArray()) { if (curr!!.child[c.code - 'a'.code] == null) { return 0 } curr = curr.child[c.code - 'a'.code] } val sum = curr!!.`val` return sum + sumHelper(curr) } } /* * Your MapSum object will be instantiated and called as such: * var obj = MapSum() * obj.insert(key,`val`) * var param_2 = obj.sum(prefix) */
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,384
LeetCode-in-Kotlin
MIT License
src/aoc2022/Day11.kt
anitakar
576,901,981
false
{"Kotlin": 124382}
package aoc2022 import println import readInput import java.util.function.UnaryOperator fun main() { class Monkey( val items: MutableList<Long>, val op: UnaryOperator<Long>, val test: Int, val trueConditionMonkey: Int, val falseConditionMonkey: Int, var itemsInspected: Long = 0, var modulo: Long = 1 ) { fun play(monkeys: MutableList<Monkey>) { for (item in items) { var newItem = op.apply(item) / 3 if (newItem % test == 0L) { monkeys[trueConditionMonkey].items.add(newItem) } else { monkeys[falseConditionMonkey].items.add(newItem) } itemsInspected += 1 } items.clear() } fun play2(monkeys: MutableList<Monkey>) { for (item in items) { var newItem = op.apply(item % modulo) if (newItem % test == 0L) { monkeys[trueConditionMonkey].items.add(newItem) } else { monkeys[falseConditionMonkey].items.add(newItem) } itemsInspected += 1 } items.clear() } } fun parseMonkeys(input: List<String>): MutableList<Monkey> { val monkeys: MutableList<Monkey> = mutableListOf() var items: MutableList<Long> = mutableListOf() var op = { a: Long -> a + 0 } var test: Int = 2 var trueConditionMonkey: Int = 0 var falseConditionMonkey: Int = 0 for (line in input) { if (line.startsWith("Monkey")) continue; if (line.startsWith(" Starting items: ")) { items = line .substring(" Starting items: ".length) .split(", ") .map { e -> e.toLong() } .toMutableList() } if (line.startsWith(" Operation: new = old * ")) { val operand = line.substring(" Operation: new = old * ".length) if (operand == "old") { op = { a: Long -> a * a } } else { op = { a: Long -> a * operand.toLong() } } } if (line.startsWith(" Operation: new = old + ")) { val operand = line.substring(" Operation: new = old + ".length).toInt() op = { a: Long -> a + operand } } if (line.startsWith(" Test: divisible by ")) { test = line.substring(" Test: divisible by ".length).toInt() } if (line.startsWith(" If true: throw to monkey ")) { trueConditionMonkey = line.substring(" If true: throw to monkey ".length).toInt() } if (line.startsWith(" If false: throw to monkey ")) { falseConditionMonkey = line.substring(" If false: throw to monkey ".length).toInt() } if (line.isBlank()) { monkeys.add(Monkey(items, op, test, trueConditionMonkey, falseConditionMonkey)) } } monkeys.add(Monkey(items, op, test, trueConditionMonkey, falseConditionMonkey)) val allModulos = monkeys.map { m -> m.test }.reduce { acc, v -> acc * v }.toLong() monkeys.forEach { m -> m.modulo = allModulos } return monkeys } fun part1(input: List<String>): Long { val monkeys = parseMonkeys(input) for (round in 0..19) { for (monkey in monkeys) { monkey.play(monkeys) } } monkeys.sortBy { m -> m.itemsInspected } return monkeys[monkeys.size - 1].itemsInspected * monkeys[monkeys.size - 2].itemsInspected } fun part2(input: List<String>): Long { val monkeys = parseMonkeys(input) for (round in 0 until 10000) { for (monkey in monkeys) { monkey.play2(monkeys) } } monkeys.sortBy { m -> m.itemsInspected } return monkeys[monkeys.size - 1].itemsInspected * monkeys[monkeys.size - 2].itemsInspected } // test if implementation meets criteria from the description, like: val testInput = readInput("Day11_test") check(part1(testInput) == 10605L) check(part2(testInput) == 2713310158) val input = readInput("Day11") part1(input).println() part2(input).println() }
0
Kotlin
0
1
50998a75d9582d4f5a77b829a9e5d4b88f4f2fcf
4,494
advent-of-code-kotlin
Apache License 2.0
Code/4Sum/Solution.kt
Guaidaodl
26,102,098
false
{"Java": 20880, "Kotlin": 6663, "C++": 4106, "Python": 1216}
class Solution { fun fourSum(nums: IntArray, target: Int): List<List<Int>> { nums.sort() val result: ArrayList<List<Int>> = ArrayList() var lastThreeResult: List<List<Int>>? = null for (i in 0 until nums.size - 3) { val r = threeSum(nums, i + 1, target - nums[i]) r.forEach {t -> lastThreeResult?.let { if (exist(it, t)) { return@forEach } } result.add(listOf(nums[i], t[0], t[1], t[2])) } lastThreeResult = if (nums[i + 1] == nums[i]) { r } else { null } } return result } fun threeSum(nums: IntArray, begin: Int, target: Int): List<List<Int>> { val result: ArrayList<List<Int>> = ArrayList() var lastTwoResult: List<List<Int>>? = null for (i in begin until nums.size - 2) { val r = twoSum(nums, i + 1, target - nums[i]) r.forEach {t -> lastTwoResult?.let { if (exist(it, t)) { return@forEach } } val lastResult = listOf(nums[i], t[0], t[1]) result.add(lastResult) } lastTwoResult = if (nums[i + 1] == nums[i]) { r } else { null } } return result } private fun exist(lastResult: List<List<Int>>, r: List<Int>): Boolean { lastResult.forEach { var same = true for (i in 0 until it.size) { if (it[i] != r[i]) { same = false break } } if (same) { return true } } return false } private fun twoSum(nums: IntArray, begin: Int, target: Int): List<List<Int>> { var b = begin var e = nums.size - 1 val result: ArrayList<List<Int>> = ArrayList() while(b < e) { val sum = nums[b] + nums[e] if (sum > target) { do { e-- } while (b < e && nums[e] == nums[e + 1]) } else { if (sum == target) { result.add(listOf(nums[b], nums[e])) } do { b++ } while (b < e && nums[b] == nums[b - 1]) } } return result } }
0
Java
0
0
a5e9c36d34e603906c06df642231bfdeb0887088
2,601
leetcode
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/CountHiddenSequences.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max import kotlin.math.min /** * 2145. Count the Hidden Sequences * @see <a href="https://leetcode.com/problems/count-the-hidden-sequences/">Source</a> */ fun interface CountHiddenSequences { fun numberOfArrays(differences: IntArray, lower: Int, upper: Int): Int } /** * Straight Forward Solution */ class CountHiddenSequencesSF : CountHiddenSequences { override fun numberOfArrays(differences: IntArray, lower: Int, upper: Int): Int { var a: Long = 0 var ma: Long = 0 var mi: Long = 0 for (d in differences) { a += d.toLong() ma = max(ma, a) mi = min(mi, a) } return max(0, upper - lower - (ma - mi) + 1).toInt() } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,382
kotlab
Apache License 2.0
18/kotlin/src/main/kotlin/se/nyquist/SnailfishNumber.kt
erinyq712
437,223,266
false
{"Kotlin": 91638, "C#": 10293, "Emacs Lisp": 4331, "Java": 3068, "JavaScript": 2766, "Perl": 1098}
package se.nyquist import java.lang.NumberFormatException interface SnailfishNumber { fun reduce() : SnailfishNumber fun findReducable(): SnailfishNumberPair? { return findReducable(4) } fun findReducable(depth: Int): SnailfishNumberPair? fun getDigits(): List<SnailfishDigit> { return getDigits(0) } fun getDigits(level : Int): List<SnailfishDigit> fun replace(pair: SnailfishNumberPair, snailfishDigit: SnailfishDigit) fun replace(snailfishDigit: SnailfishDigit, pair: SnailfishNumberPair) fun isDigit() : Boolean fun explode(): SnailfishNumber fun split(): SnailfishNumber fun magnitude(): Long } fun parse(input: String) : SnailfishNumber { if (input.first() == '[' && input.last() == ']') { var position = 1 val subitem1 = parseNext(input, position) position = subitem1.first while (input[position] != ',') { position++ } val number2 = parseNext(input, position+1) return SnailfishNumberPair(subitem1.second, number2.second) } else if (input.first().isDigit() && input.last().isDigit()) { return if (input.contains(",")) SnailfishNumberPair(SnailfishDigit(input.first().digitToInt()), SnailfishDigit(input.last().digitToInt())) else SnailfishDigit(input.toInt()) } else if (input.first() == '[' && input.last().isDigit()) { return SnailfishNumberPair(parse(input.substring(1, input.lastIndexOf(']'))), SnailfishDigit(input.last().digitToInt())) } else if (input.last() == ']' && input.first().isDigit()) { return SnailfishNumberPair(SnailfishDigit(input.first().digitToInt()), parse(input.substring(input.lastIndexOf('[') + 1, input.lastIndex))) } else { throw NumberFormatException(input) } } private fun parseNext(input: String, startPosition: Int): Pair<Int,SnailfishNumber> { var position = startPosition if (input[position] == '[') { var beginCount = 1 var endCount = 0 do { position++ if (input[position] == '[') { beginCount++ } else if (input[position] == ']') { endCount++ } } while (beginCount > endCount) return Pair(position + 1, parse(input.substring(startPosition, position + 1))) } else if (input[position].isDigit()) { return Pair(position + 1, SnailfishDigit(input[position].digitToInt())) } throw NumberFormatException(input) } operator fun SnailfishNumber.plus(number: SnailfishNumber) : SnailfishNumber { return SnailfishNumberPair(this, number).reduce() }
0
Kotlin
0
0
b463e53f5cd503fe291df692618ef5a30673ac6f
2,657
adventofcode2021
Apache License 2.0
src/main/kotlin/days/aoc2022/Day20.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2022 import days.Day class Day20 : Day(2022, 20) { override fun partOne(): Any { return calculateGroveCoordinateSum(inputList) } override fun partTwo(): Any { return calculateGroveCoordinateSumWithDecryptionKey(inputList) } fun calculateGroveCoordinateSumWithDecryptionKey(input: List<String>): Long { var numbers = parseInput(input, 811589153L) repeat(10) { numbers = mix(numbers) } val zero = numbers.indexOf(numbers.first { it.second == 0L }) return numbers[(1000 + zero) % numbers.size].second + numbers[(2000 + zero) % numbers.size].second + numbers[(3000 + zero) % numbers.size].second } fun calculateGroveCoordinateSum(input: List<String>): Int { var numbers = parseInput(input, 1L) numbers = mix(numbers) val zero = numbers.indexOf(numbers.first { it.second == 0L }) return numbers[(1000 + zero) % numbers.size].second.toInt() + numbers[(2000 + zero) % numbers.size].second.toInt() + numbers[(3000 + zero) % numbers.size].second.toInt() } private fun parseInput(input: List<String>, decryptionKey: Long): MutableList<Pair<Int, Long>> { return input.mapIndexed { index, string -> Pair(index, string.toLong() * decryptionKey) }.toMutableList() } private fun mix(numbers: MutableList<Pair<Int, Long>>): MutableList<Pair<Int, Long>> { for (i in numbers.indices) { val index = numbers.indexOf(numbers.first { i == it.first }) val number = numbers.removeAt(index) numbers.add((number.second + index).mod(numbers.size), number) } return numbers } }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
1,755
Advent-Of-Code
Creative Commons Zero v1.0 Universal
src/main/kotlin/kr/co/programmers/P136797.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package kr.co.programmers // https://github.com/antop-dev/algorithm/issues/537 class P136797 { // 한 자판에서 다른 자판으로 가는 가중치 private val costs = arrayOf( intArrayOf(1, 7, 6, 7, 5, 4, 5, 3, 2, 3), // 자판 0 intArrayOf(7, 1, 2, 4, 2, 3, 5, 4, 5, 6), intArrayOf(6, 2, 1, 2, 3, 2, 3, 5, 4, 5), intArrayOf(7, 4, 2, 1, 5, 3, 2, 6, 5, 4), intArrayOf(5, 2, 3, 5, 1, 2, 4, 2, 3, 5), intArrayOf(4, 3, 2, 3, 2, 1, 2, 3, 2, 3), intArrayOf(5, 5, 3, 2, 4, 2, 1, 5, 3, 2), intArrayOf(3, 4, 5, 6, 2, 3, 5, 1, 2, 4), intArrayOf(2, 5, 4, 5, 3, 2, 3, 2, 1, 2), intArrayOf(3, 6, 5, 4, 5, 3, 2, 4, 2, 1) // 자판 9 ) fun solution(numbers: String): Int { // 메모제이션 val memo = Array(numbers.length) { Array(10) { IntArray(10) { -1 } } } // 왼손은 4, 오른손은 6 자판에서 시작 return f(numbers, 0, memo, 4, 6) } /** * @param numbers 눌러야 할 숫자 문자열 * @param i 다음으로 눌러야하는 번호 인덱스 * @param memo 메모제이션 * @param left 현재 왼손의 자판 번호 * @param right 현재 오른손의 자판 번호 */ private fun f(numbers: String, i: Int, memo: Array<Array<IntArray>>, left: Int, right: Int): Int { if (i == numbers.length) return 0 // 이미 전에 계산했던 이력이 있다면 더 깊이 내려가지 않고 // 이전 이력 값을 사용한다. if (memo[i][left][right] != -1) { return memo[i][left][right] } // 눌러야 하는 숫자 자판 번호 val num = numbers[i] - '0' var min = Int.MAX_VALUE if (num != right) { // 왼손이 움직일 수 있는 경우 (오른손이 가야할 자판에 있다면 손이 겹치게 된다.) // (왼손이 num으로 이동) + (다음 자판~마지막 자판까지 누른 최소 가중치) val cost = costs[left][num] + f(numbers, i + 1, memo, num, right) min = minOf(min, cost) } if (num != left) { // 오른손이 움직일 수 있는 경우 // (오른손이 num으로 이동) + (다음 자판~마지막 자판까지 누른 최소 가중치) val cost = costs[right][num] + f(numbers, i + 1, memo, left, num) min = minOf(min, cost) } memo[i][left][right] = min // 메모제이션 return min } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
2,512
algorithm
MIT License
src/SpeedChallenge.kt
Tandrial
47,354,790
false
null
import java.io.File import kotlin.system.measureTimeMillis fun measureTime(name: String, part1: () -> Unit, part2: () -> Unit, maxTime: Long): Long { val timeP1 = measureTimeMillis(part1) val timeP2 = measureTimeMillis(part2) print("$name \t") print("${"%4d".format(timeP1)} \t") if (timeP2 > 0L) print("${"%4d".format(timeP2)} ") else print(" ") if (timeP1 > maxTime || timeP2 > maxTime) print("<<<") println() return timeP1 + timeP2 } data class Solution(val name: String, val part1: () -> Unit, val part2: () -> Unit) fun testAoC2017() { val days = mutableListOf<Solution>() days.add(Solution("Day_01", { val input = File("./input/2017/Day01_input.txt").readText() aoc2017.kot.Day01.partOne(input) }, { val input = File("./input/2017/Day01_input.txt").readText() aoc2017.kot.Day01.partTwo(input) })) days.add(Solution("Day_02", { val input = File("./input/2017/Day02_input.txt").to2DIntArr() aoc2017.kot.Day02.partOne(input) }, { val input = File("./input/2017/Day02_input.txt").to2DIntArr() aoc2017.kot.Day02.partTwo(input) })) days.add(Solution("Day_03", { aoc2017.kot.Day03.partOne(361527) }, { aoc2017.kot.Day03.partTwo(361527) })) days.add(Solution("Day_04", { val input = File("./input/2017/Day04_input.txt").readLines() aoc2017.kot.Day04.partOne(input) }, { val input = File("./input/2017/Day04_input.txt").readLines() aoc2017.kot.Day04.partTwo(input) })) days.add(Solution("Day_05", { val input = File("./input/2017/Day05_input.txt").readLines().map { it.toInt() } aoc2017.kot.Day05.partOne(input) }, { val input = File("./input/2017/Day05_input.txt").readLines().map { it.toInt() } aoc2017.kot.Day05.partTwo(input) })) days.add(Solution("Day_06", { val input = File("./input/2017/Day06_input.txt").readText().toIntList() aoc2017.kot.Day06.solve(input) }, { })) days.add(Solution("Day_07", { val input = File("./input/2017/Day07_input.txt").readLines() aoc2017.kot.Day07.partOne(input) }, { val input = File("./input/2017/Day07_input.txt").readLines() val result = aoc2017.kot.Day07.partOne(input) aoc2017.kot.Day07.partTwo(input, result) })) days.add(Solution("Day_08", { val input = File("./input/2017/Day08_input.txt").readLines() aoc2017.kot.Day08.solve(input) }, { })) days.add(Solution("Day_09", { val input = File("./input/2017/Day09_input.txt").readText() aoc2017.kot.Day09.solve(input) }, { })) days.add(Solution("Day_10", { val input = File("./input/2017/Day10_input.txt").readText().toIntList(",".toPattern()) aoc2017.kot.Day10.hashRound(input) }, { val input2 = File("./input/2017/Day10_input.txt").readText().toCharArray().map { it.toInt() } + listOf(17, 31, 73, 47, 23) aoc2017.kot.Day10.partTwo(input2, 64) })) days.add(Solution("Day_11", { val input = File("./input/2017/Day11_input.txt").readText().split(",") aoc2017.kot.Day11.solve(input) }, { })) days.add(Solution("Day_12", { val input = File("./input/2017/Day12_input.txt").readLines() aoc2017.kot.Day12.solve(input) }, { })) days.add(Solution("Day_13", { val input = File("./input/2017/Day13_input.txt").readLines() aoc2017.kot.Day13.partOne(input) }, { val input = File("./input/2017/Day13_input.txt").readLines() aoc2017.kot.Day13.partTwo(input) })) days.add(Solution("Day_14", { val input = "vbqugkhl" aoc2017.kot.Day14.solve(input) }, { })) days.add(Solution("Day_15", { val input = File("./input/2017/Day15_input.txt").readLines() val seeds = input.map { it.getWords()[4].toLong() } aoc2017.kot.Day15.partOne(seeds[0], seeds[1]) }, { val input = File("./input/2017/Day15_input.txt").readLines() val seeds = input.map { it.getWords()[4].toLong() } aoc2017.kot.Day15.partTwo(seeds[0], seeds[1]) })) days.add(Solution("Day_16", { val input = File("./input/2017/Day16_input.txt").readText().split(",") aoc2017.kot.Day16.solve(input) }, { val input = File("./input/2017/Day16_input.txt").readText().split(",") aoc2017.kot.Day16.solve(input, 1_000_000_000) })) days.add(Solution("Day_17", { aoc2017.kot.Day17.partOne(304, 2017) }, { aoc2017.kot.Day17.partTwo(304, 50_000_000) })) days.add(Solution("Day_18", { val input = File("./input/2017/Day18_input.txt").readLines() aoc2017.kot.Day18.partOne(input) }, { val input = File("./input/2017/Day18_input.txt").readLines() aoc2017.kot.Day18.partTwo(input) })) days.add(Solution("Day_19", { val input = File("./input/2017/Day19_input.txt").readLines().map { it.toCharArray() } aoc2017.kot.Day19.solve(input) }, { })) days.add(Solution("Day_20", { val input = File("./input/2017/Day20_input.txt").readLines() aoc2017.kot.Day20.partOne(input) }, { val input = File("./input/2017/Day20_input.txt").readLines() aoc2017.kot.Day20.partTwo(input) })) days.add(Solution("Day_21", { val input = File("./input/2017/Day21_input.txt").readLines() val start = ".#./..#/###" aoc2017.kot.Day21.solve(start, input, 5) }, { val input = File("./input/2017/Day21_input.txt").readLines() val start = ".#./..#/###" aoc2017.kot.Day21.solve(start, input, 18) })) days.add(Solution("Day_22", { val input = File("./input/2017/Day22_input.txt").readLines() aoc2017.kot.Day22.solve(input, 10000) }, { val input = File("./input/2017/Day22_input.txt").readLines() aoc2017.kot.Day22.solve(input, 10000000, true) })) days.add(Solution("Day_23", { val input = File("./input/2017/Day23_input.txt").readLines() aoc2017.kot.Day23.partOne(input) }, { aoc2017.kot.Day23.partTwoFast() })) days.add(Solution("Day_24", { val input = File("./input/2017/Day24_input.txt").readLines() aoc2017.kot.Day24.solve(input) }, { })) days.add(Solution("Day_25", { val input = File("./input/2017/Day25_input.txt").readLines() aoc2017.kot.Day25.solve(input) }, { })) println("Day\t\tPart 1\tPart 2") println("Total time: ${days.map { measureTime(it.name, it.part1, it.part2, 500) }.sum() / 1000.0} s") } fun testAoC2018() { val days = mutableListOf<Solution>() days.add(Solution("Day_01", { val input = File("./input/2018/Day01_input.txt").readLines() aoc2018.kot.Day01.partOne(input) }, { val input = File("./input/2018/Day01_input.txt").readLines() aoc2018.kot.Day01.partTwo(input) })) days.add(Solution("Day_02", { val input = File("./input/2018/Day02_input.txt").readLines() aoc2018.kot.Day02.partOne(input) }, { val input = File("./input/2018/Day02_input.txt").readLines() aoc2018.kot.Day02.partTwo(input) })) days.add(Solution("Day_03", { val input = File("./input/2018/Day03_input.txt").readLines() aoc2018.kot.Day03.partOne(input) }, { val input = File("./input/2018/Day03_input.txt").readLines() aoc2018.kot.Day03.partTwo(input) })) days.add(Solution("Day_04", { val input = File("./input/2018/Day04_input.txt").readLines() aoc2018.kot.Day04.partOne(input) }, { val input = File("./input/2018/Day04_input.txt").readLines() aoc2018.kot.Day04.partTwo(input) })) days.add(Solution("Day_05", { val input = File("./input/2018/Day05_input.txt").readText() val resultOne = aoc2018.kot.Day05.partOne(input) aoc2018.kot.Day05.partTwo(resultOne.joinToString(separator = "")) }, { })) // days.add(Solution("Day_06", { // val input = File("./input/2018/Day06_input.txt").readLines() // aoc2018.kot.Day06.partOne(input) // }, { // val input = File("./input/2018/Day06_input.txt").readLines() // aoc2018.kot.Day06.partTwo(input) // })) days.add(Solution("Day_07", { val input = File("./input/2018/Day07_input.txt").readLines() aoc2018.kot.Day07.partOne(input) }, { val input = File("./input/2018/Day07_input.txt").readLines() aoc2018.kot.Day07.partTwo(input) })) println("Day\t\tPart 1\tPart 2") println("Total time: ${days.map { measureTime(it.name, it.part1, it.part2, 500) }.sum() / 1000.0} s") } fun main(args: Array<String>) { //testAoC2017() repeat(40) { testAoC2018() } }
0
Kotlin
1
1
9294b2cbbb13944d586449f6a20d49f03391991e
8,243
Advent_of_Code
MIT License
src/main/kotlin/days/Day6.kt
sicruse
315,469,617
false
null
package days import days.Day class Day6 : Day(6) { private val groups: List<List<String>> by lazy { inputString // split the input at blank lines to form record groups .split("\\n\\n".toRegex()) .map { group -> // for every record text block gather the individual responses by splitting at newlines group.split("\\n".toRegex()) } } override fun partOne(): Any { // return the sum "yes" answers by group return groups // join group of responses to form unique set of answers .map { groupOfResponses -> groupOfResponses.joinToString(separator = "").toSet() } // sum the unique answers per group .fold(0) { acc, set -> acc + set.size } } override fun partTwo(): Any { // return the sum of questions which *everyone* in a group answered yes return groups // for each group of responses convert each participants response to a set of unique answers .map { groupOfResponses -> groupOfResponses.map { response -> response.toSet() } } // for each set of responses in each group determine the set of questions which every participant responded yes .map { groupOfResponses -> groupOfResponses.fold(groupOfResponses.first()) { acc, set -> acc.intersect(set) } } // sum the sets of answers which *everyone* in the group answered yes .fold(0) { acc, set -> acc + set.size } } }
0
Kotlin
0
0
9a07af4879a6eca534c5dd7eb9fc60b71bfa2f0f
1,555
aoc-kotlin-2020
Creative Commons Zero v1.0 Universal
src/main/kotlin/day1/part1/Part1.kt
bagguley
329,976,670
false
null
package day1.part1 import day1.data fun main() { println(sequence {for(a in 0..data.size-2) { for (b in a+1 until data.size) { if (data[a] + data[b] == 2020) yield(data[a] * data[b])} } }.first()) println((0..data.size-2).asSequence().flatMap{a->(a until data.size).map{ b->data[a] to data[b]}}.find{(x,y)->x+y==2020}?.let{(x,y)->x*y}) println((0..data.size-2).asSequence().flatMap{a->(a until data.size).map{data[it]}.filter{b->2020-b==data[a]}}.first().let{it*(2020-it)}) println(data.find{data.minus(it).contains(2020-it)}?.let{(2020-it)*it}) println(calc()) } fun calc() { val input = data.toMutableList() val result = mutableListOf<Pair<Int,Int>>() while (input.size > 1) { val x = input.removeAt(0) input.find { it + x == 2020 }?.let { result.add(x to it) } } result.forEach { println(it.first * it.second) } }
0
Kotlin
0
0
6afa1b890924e9459f37c604b4b67a8f2e95c6f2
880
adventofcode2020
MIT License
2023/19/Solution.kt
AdrianMiozga
588,519,359
false
{"Kotlin": 110785, "Python": 11275, "Assembly": 3369, "C": 2378, "Pawn": 1390, "Dart": 732}
import java.io.File import java.util.* private const val FILENAME = "2023/19/input.txt" fun main() { partOne() } private fun partOne() { val (workflows, ratings) = File(FILENAME).readText().split("\r\n\r\n") .map { it.split("\r\n") } var result = 0 for (rating in ratings) { val map = rating.removeSurrounding("{", "}").split(",").associate { val (key, value) = it.split("=") key to value.toInt() } val sum = map.values.sum() val stack = Stack<String>() stack.push(workflows.find { it.substringBefore("{") == "in" }) while (stack.isNotEmpty()) { val instructions = stack.pop().substringAfter("{").substringBefore("}").split(",") for (instruction in instructions) { if (instruction.all { it.isLetter() }) { if (instruction == "A") { result += sum } else if (instruction != "R") { stack.push(workflows.find { it.substringBefore("{") == instruction }) } break } val (letter, sign, value, ret) = Regex("""(\w)([<>])(\d+):(\w+)""").matchEntire( instruction )!!.destructured if ((sign == "<" && map[letter]!! < value.toInt()) || (sign == ">" && map[letter]!! > value.toInt())) { if (ret == "A") { result += sum } else if (ret != "R") { stack.push(workflows.find { it.substringBefore("{") == ret }) } break } } } } println(result) }
0
Kotlin
0
0
c9cba875089d8d4fb145932c45c2d487ccc7e8e5
1,852
Advent-of-Code
MIT License
src/main/kotlin/algorithms/MostProbableKmer.kt
jimandreas
377,843,697
false
null
@file:Suppress("UNUSED_PARAMETER") package algorithms /** * Profile-most Probable k-mer Problem: Find a Profile-most probable k-mer in a string. Input: A string Text, an integer k, and a 4 × k matrix Profile. Output: A Profile-most probable k-mer in Text. */ fun mostProbableKmer(genome: String, kmerLength: Int, probString: String): String { var maxProb = 0f var bestKmerString = "" val matrixList = parseProbabilityMatrix(kmerLength, probString) for (i in 0..genome.length-kmerLength) { val candidateKmer = genome.substring(i, i + kmerLength) val prob = probForGivenKmer(candidateKmer, matrixList) //println("$candidateKmer $prob") if (prob > maxProb) { maxProb = prob bestKmerString = candidateKmer } } return bestKmerString } fun mostProbableKmerGivenProbList(genome: String, kmerLength: Int, probList: List<Float>): String { var maxProb = 0f var bestKmerString = genome.substring(0, kmerLength) for (i in 0..genome.length-kmerLength) { val candidateKmer = genome.substring(i, i + kmerLength) val prob = probForGivenKmer(candidateKmer, probList) //println("$candidateKmer $prob") if (prob > maxProb) { maxProb = prob bestKmerString = candidateKmer } } return bestKmerString } /** * calculate the probability of a kmer string given * a prob matrix of the form: * A 0.2 0.2 0.3 0.2 0.3 C 0.4 0.3 0.1 0.5 0.1 G 0.3 0.3 0.5 0.2 0.4 T 0.1 0.2 0.1 0.1 0.2 ASSUMPTION: matrix is row then column and is equal to 4 * kmer.length */ fun probForGivenKmer(kmer: String, probMatrix: List<Float>): Float { val len = kmer.length if (probMatrix.size != len * 4) { println("ERROR mismatch of kmer and probMatrix lengths") return 0f } var prob = 1.0f val nucMap: HashMap<Char, Int> = hashMapOf(Pair('a', 0), Pair('c', 1), Pair('g', 2), Pair('t', 3)) for (i in kmer.indices) { val offset = nucMap[kmer[i].lowercaseChar()] if (offset == null) { println("ERROR nucleotide is not ACGT") return 0f } val probTemp = probMatrix[offset * len + i] prob *= probTemp } return prob } /** parse ACGT prob matrix for kmer - of the form: 0.2 0.2 0.3 0.2 0.3 0.4 0.3 0.1 0.5 0.1 0.3 0.3 0.5 0.2 0.4 0.1 0.2 0.1 0.1 0.2 */ fun parseProbabilityMatrix(kmerLength: Int, matrixStringIn: String): List<Float> { var curIndex = 0 val probMatrix : MutableList<Float> = mutableListOf() val matrixString = "$matrixStringIn " // make sure there is a terminating space for parsing for (i in matrixString.indices) { when (matrixString[i]) { ' ','\n' -> { val newFloat = parseFloat(matrixString.substring(curIndex, i)) probMatrix.add(newFloat) curIndex = i } } } return probMatrix } private fun parseFloat(s: String): Float { return try { s.toFloat() } catch (e: RuntimeException) { 0.toFloat() } }
0
Kotlin
0
0
fa92b10ceca125dbe47e8961fa50242d33b2bb34
3,109
stepikBioinformaticsCourse
Apache License 2.0
src/Day01.kt
simonitor
572,972,937
false
{"Kotlin": 8461}
fun main() { //part1 val elfs = readFile("inputDay1").split("\n\n").map { Elf(it) } val answer = getFattestElf(elfs).calories println("The most calories are $answer") //part2 val answerPart2 = getTopThreeElfs(elfs).sumOf { it.calories } println("The most calories are $answerPart2") } fun getFattestElf(elfs: List<Elf>) = elfs.maxBy { it.calories } class Elf(private val cal: String) { val calories = calculateCalories() fun calculateCalories(): Int { return cal.split("\n").sumOf { it.toInt() } } } fun getTopThreeElfs(elfs: List<Elf>): List<Elf>{ val topThree = emptyList<Elf>().toMutableList() val elfsMutable = elfs.toMutableList() repeat(3){ val elf = getFattestElf(elfsMutable) topThree.add(elf) elfsMutable.remove(elf) } return topThree.toList() }
0
Kotlin
0
0
11d567712dd3aaf3c7dee424a3442d0d0344e1fa
851
AOC2022
Apache License 2.0
src/Day10.kt
petoS6
573,018,212
false
{"Kotlin": 14258}
fun main() { fun part1(lines: List<String>): Int { var x = 1 var cycle = 1 var sum = 0 fun processCycle() { if (cycle % 40 == 20) sum += cycle * x cycle++ } lines.forEach { line -> if (line == "noop") { processCycle() } else { processCycle() processCycle() x += line.substringAfter(" ").toInt() } } return sum } fun part2(lines: List<String>): Unit { var x = 1 var cycle = 1 val screen = mutableMapOf<Point, Boolean>() fun processCycle() { val screenX = (cycle - 1) % 40 if (screenX in (x - 1)..(x + 1)) { screen[Point(screenX, (cycle - 1) / 40)] = true } cycle++ } fun Map<Point, Boolean>.printArea() { (0..6).forEach { y -> (0..40).forEach { x -> if (this[Point(x, y)] == true )print("#") else print(" ") } println() } } lines.forEach { line -> if (line == "noop") { processCycle() } else { processCycle() processCycle() x += line.substringAfter(" ").toInt() } } screen.printArea() } val testInput = readInput("Day10.txt") println(part1(testInput)) println(part2(testInput)) } data class Point(val x: Int, val y: Int)
0
Kotlin
0
0
40bd094155e664a89892400aaf8ba8505fdd1986
1,305
kotlin-aoc-2022
Apache License 2.0
2023/08/Solution.kt
AdrianMiozga
588,519,359
false
{"Kotlin": 110785, "Python": 11275, "Assembly": 3369, "C": 2378, "Pawn": 1390, "Dart": 732}
import java.io.File private const val FILENAME = "2023/08/input.txt" fun main() { partOne() partTwo() } private fun partOne() { val file = File(FILENAME).readLines() val instructions = file[0] var instructionIndex = 0 var steps = 0 val map: MutableMap<String, Pair<String, String>> = mutableMapOf() var currentNode = "AAA" for (line in file.slice(2 until file.size)) { val (input, left, right) = Regex("""(\w+) = \((\w+), (\w+)\)""").matchEntire( line )!!.destructured map[input] = Pair(left, right) } while (currentNode != "ZZZ") { currentNode = if (instructions[instructionIndex] == 'L') { map[currentNode]!!.first } else { map[currentNode]!!.second } steps++ instructionIndex = (instructionIndex + 1) % instructions.length } println(steps) } private fun partTwo() { val file = File(FILENAME).readLines() val instructions = file[0] var instructionIndex = 0 val map: MutableMap<String, Pair<String, String>> = mutableMapOf() val full: MutableMap<String, Pair<String, String>> = mutableMapOf() for (line in file.slice(2 until file.size)) { val (input, left, right) = Regex("""(\w+) = \((\w+), (\w+)\)""").matchEntire( line )!!.destructured full[input] = Pair(left, right) if (input.endsWith("A")) { map[input] = Pair(left, right) } } val listSteps = MutableList(map.size) { 0 } var index = 0 for (element in map) { var steps = 0 var current = element.key while (true) { current = if (instructions[instructionIndex] == 'L') { full[current]!!.first } else { full[current]!!.second } steps++ instructionIndex = (instructionIndex + 1) % instructions.length if (current.endsWith("Z")) { break } } listSteps[index] = steps index++ } println(findLCM(listSteps)) } private fun findLCM(a: Long, b: Long): Long { val larger = if (a > b) a else b val maxLcm = a * b var lcm = larger while (lcm <= maxLcm) { if (lcm % a == 0L && lcm % b == 0L) { return lcm } lcm += larger } return maxLcm } private fun findLCM(numbers: List<Int>): Long { var result = numbers[0].toLong() for (i in 1 until numbers.size) { result = findLCM(result, numbers[i].toLong()) } return result }
0
Kotlin
0
0
c9cba875089d8d4fb145932c45c2d487ccc7e8e5
2,616
Advent-of-Code
MIT License
src/main/kotlin/solutions/day04/Day4.kt
Dr-Horv
570,666,285
false
{"Kotlin": 115643}
package solutions.day04 import solutions.Solver class Day4 : Solver { private infix fun IntRange.contains(other: IntRange): Boolean = (this.contains(other.first) and this.contains(other.last)) or (other.contains(this.first) and other.contains(this.last)) private infix fun IntRange.overlaps(other: IntRange): Boolean = this.contains(other.first) or this.contains(other.last) or other.contains(this.first) or other.contains(this.last) private fun parsePair(line: String): Pair<IntRange, IntRange> { val pairsStr = line.split(","); return Pair(parseIntRange(pairsStr[0]), parseIntRange(pairsStr[1])) } private fun parseIntRange(a: String): IntRange { val rangeInts = a.split("-") .map { it.toInt() } return IntRange(rangeInts[0], rangeInts[1]) } override fun solve(input: List<String>, partTwo: Boolean): String { val condition: (Pair<IntRange, IntRange>) -> Boolean = if (!partTwo) { { it.first contains it.second } } else { { it.first overlaps it.second } } return input.map { parsePair(it) } .count(condition) .toString() } }
0
Kotlin
0
2
6c9b24de2fe2a36346cb4c311c7a5e80bf505f9e
1,280
Advent-of-Code-2022
MIT License
src/Day01.kt
defvs
572,381,346
false
{"Kotlin": 16089}
fun main() { // Returns a List of Ints containing the sum of calories for each elf. fun getAllElvesCalories(input: List<String>) = input.joinToString(separator = "\n") .split("\n\n").map { it.split("\n").sumOf { it.toInt() } } // Get the maximum value of getAllElvesCalories fun part1(input: List<String>) = getAllElvesCalories(input).max() // Sum the 3 maximum values of getAllElvesCalories fun part2(input: List<String>) = getAllElvesCalories(input).sortedDescending().take(3).sum() // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput).also { println("Test result was: $it") } == 24000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
caa75c608d88baf9eb2861eccfd398287a520a8a
763
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/pl/mrugacz95/aoc/day21/day21.kt
mrugacz95
317,354,321
false
null
package pl.mrugacz95.aoc.day21 import pl.mrugacz95.aoc.day16.HopcroftKarpSolver class Food(raw: String) { private val groups = raw.split(" (contains ") val ingredients = groups[0].split(" ").toSet() val allergens = groups[1].dropLast(1).split(", ") } fun solve(foodList: List<Food>): Map<String, String> { val allAllergens = foodList.flatMap { it.allergens }.toSet() val mayBeIn = mutableMapOf<String, Set<String>>() for (allergen in allAllergens) { val foodContaining = foodList.filter { allergen in it.allergens } val possibleIngredients = foodContaining.map { it.ingredients }.reduce { acc, i -> acc.intersect(i) } mayBeIn[allergen] = possibleIngredients } return HopcroftKarpSolver<String, String>().solve(mayBeIn.toMap()) } fun main() { val food = {}::class.java.getResource("/day21.in") .readText() .split("\n") .map { Food(it) } val matching = solve(food) println( "Answer part 1: ${ food.map { f -> f.ingredients.filter { ingredient -> ingredient !in matching.values }.count() }.sum() }" ) println("Answer part 2: ${matching.entries.sortedBy { it.key }.joinToString(",") { it.value }}") }
0
Kotlin
0
1
a2f7674a8f81f16cd693854d9f564b52ce6aaaaf
1,228
advent-of-code-2020
Do What The F*ck You Want To Public License
advent2023/src/main/kotlin/year2023/Day01.kt
bulldog98
572,838,866
false
{"Kotlin": 132847}
package year2023 import AdventDay private val additionalDigitMapping = mapOf( "one" to "1", "two" to "2", "three" to "3", "four" to "4", "five" to "5", "six" to "6", "seven" to "7", "eight" to "8", "nine" to "9" ) private val additionalDigits = additionalDigitMapping.keys object Day01 : AdventDay(2023, 1) { override fun part1(input: List<String>): Int = input.sumOf { val onlyDigits = it.filter { c -> c.isDigit() } val string = onlyDigits.first().toString() + onlyDigits.last() string.toInt() } override fun part2(input: List<String>): Int = input.sumOf { val onlyDigits = it.windowed(5, partialWindows = true).filter { window -> window.first().isDigit() || additionalDigits.any { digit -> window.startsWith(digit) } }.map { window -> if (window.first().isDigit()) window.first().toString() else additionalDigitMapping[additionalDigits.first { d -> window.startsWith(d) }] }.joinToString(separator = "") val string = onlyDigits.first().toString() + onlyDigits.last() string.toInt() } } fun main() = Day01.run()
0
Kotlin
0
0
02ce17f15aa78e953a480f1de7aa4821b55b8977
1,227
advent-of-code
Apache License 2.0