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
foundations/inversions/Main.kt
ivan-magda
102,283,964
false
null
import kotlin.collections.ArrayList fun getInversions(array: Array<Int>): List<Pair<Int, Int>> { val inversions = mutableListOf<Pair<Int, Int>>() for (i in 0 until array.size) { (i + 1 until array.size) .asSequence() .filter { i < it && array[i] > array[it] } .mapTo(inversions) { Pair(i, it) } } return ArrayList(inversions) } fun countInversions(array: Array<Int>): Long { return sort(array, Array<Int>(array.size, { 0 }), 0, array.size - 1) } private fun sort(array: Array<Int>, buffer: Array<Int>, start: Int, end: Int): Long { if (start >= end) { return 0 } val middle = start + (end - start) / 2 val left = sort(array, buffer, start, middle) val right = sort(array, buffer, middle + 1, end) return left + right + mergeHalves(array, buffer, start, middle, end) } private fun mergeHalves(array: Array<Int>, buffer: Array<Int>, start: Int, middle: Int, end: Int): Long { var count: Long = 0 val rightStart = middle + 1 val size = end - start + 1 var left = start var right = rightStart var index = start while (left <= middle && right <= end) { if (array[left] <= array[right]) { buffer[index++] = array[left++] } else { buffer[index++] = array[right++] count += (middle - left + 1).toLong() } } System.arraycopy(array, left, buffer, index, middle - left + 1) System.arraycopy(array, right, buffer, index, end - right + 1) System.arraycopy(buffer, start, array, start, size) return count } fun main(args: Array<String>) { val array = arrayOf(2, 3, 8, 6, 1) println("Inversions: ${getInversions(array)}") println("Count inversions = ${countInversions(array)}") }
0
Kotlin
0
2
da06ec75cbd06c8e158aec86ca813e72bd22a2dc
1,807
introduction-algorithms
MIT License
library/src/commonMain/kotlin/com/darkrockstudios/symspellkt/common/WeightedDamerauLevenshteinDistance.kt
Wavesonics
752,869,721
false
{"Kotlin": 123713, "HTML": 304}
package com.darkrockstudios.symspellkt.common import com.darkrockstudios.symspellkt.api.CharDistance import com.darkrockstudios.symspellkt.api.StringDistance /** * DamerauLevenshteinDistance is a string metric for measuring the edit distance between two * sequences. Informally, the Damerau–Levenshtein distance between two words is the minimum number * of operations (consisting of insertions, deletions or substitutions of a single character, or * transposition of two adjacent characters) required to change one word into the other. * * In this variant of DamerauLevenshteinDistance, it has different weights associated to each * action. */ class WeightedDamerauLevenshteinDistance( private val deletionWeight: Double = 0.8, private val insertionWeight: Double = 1.01, private val replaceWeight: Double = 0.9, private val transpositionWeight: Double = 0.7, private val charDistance: CharDistance?, ) : StringDistance { override fun getDistance(w1: String, w2: String): Double { if (w1 == w2) { return 0.0 } if (w1.isEmpty()) { return w2.length.toDouble() } if (w2.isEmpty()) { return w1.length.toDouble() } val useCharDistance = (charDistance != null && w1.length == w2.length) val d = Array(w2.length + 1) { DoubleArray( w1.length + 1 ) } // 2d matrix // Step 2 for (i in w2.length downTo 0) { d[i][0] = i * insertionWeight // Add insertion weight } for (j in w1.length downTo 0) { d[0][j] = j * deletionWeight } for (i in 1..w2.length) { val target_i = w2[i - 1] for (j in 1..w1.length) { val source_j = w1[j - 1] val cost = getReplaceCost(target_i, source_j, useCharDistance) var min = min( d[i - 1][j] + insertionWeight, //Insertion d[i][j - 1] + deletionWeight, //Deltion d[i - 1][j - 1] + cost ) //Replacement if (isTransposition(i, j, w1, w2)) { min = kotlin.math.min(min, d[i - 2][j - 2] + transpositionWeight) // transpose } d[i][j] = min } } return d[w2.length][w1.length] } override fun getDistance(w1: String, w2: String, maxEditDistance: Double): Double { val distance = getDistance(w1, w2) if (distance > maxEditDistance) { return -1.0 } return distance } private fun min(a: Double, b: Double, c: Double): Double { return kotlin.math.min(a, kotlin.math.min(b, c)) } private fun min(a: Double, b: Double, c: Double, d: Double): Double { return kotlin.math.min(a, kotlin.math.min(b, kotlin.math.min(c, d))) } private fun isTransposition(i: Int, j: Int, source: String?, target: String?): Boolean { return i > 2 && j > 2 && source!![j - 2] == target!![i - 1] && target[i - 2] == source[j - 1] } private fun getReplaceCost(aI: Char, bJ: Char, useCharDistance: Boolean): Double { return if (aI != bJ && useCharDistance) { replaceWeight * charDistance!!.distance(aI, bJ) } else if (aI != bJ) { replaceWeight } else { 0.0 } } }
1
Kotlin
0
16
e20a9ef48fe6a154aa1c2a35de701654e1cd0ef1
2,944
SymSpellKt
MIT License
src/main/kotlin/Word.kt
jGleitz
232,886,761
false
{"Kotlin": 22060, "Java": 683}
@file:JvmName("StringToWord") package de.joshuagleitze.stringnotation /** * A notation-agnostic representation of a string. This is a “word” in the sense of “word over the Unicode alphabet”, not in the sense of a * word in any spoken language. A `Word` consists of [parts]. * * @property parts The different parts this word consists of. A [StringNotation] will [parse][StringNotation.parse] a given input into its * [parts] and [print][StringNotation.print] a `Word` by combining its [parts] appropriately. */ class Word(val parts: Sequence<String>) { constructor(vararg parts: String): this(parts.asSequence()) constructor(parts: List<String>): this(parts.asSequence()) /** * Gives the [parts] as a [List]. */ val partsList get() = parts.toList() /** * Converts this word into a string according to the given [notation]. */ fun toNotation(notation: StringNotation) = notation.print(this) /** * Creates a new word, with all its parts transformed by the provided [transform] function. */ fun mapParts(transform: (String) -> String) = Word(parts.map(transform)) /** * Creates a new word, with all its parts transformed by the provided [transform] function, which may return more than one new part for * every existing part. */ fun flatMapParts(transform: (String) -> Sequence<String>) = Word(parts.flatMap(transform)) /** * Creates a new word, with all its parts parsed by the provided [notation]. Allows to parse words that use a combination of notations. */ fun partsFromNotation(notation: StringNotation) = Word(parts.flatMap { it.fromNotation(notation).parts }) /** * Creates a copy of this word with the provided [part] appended. */ operator fun plus(part: String) = Word(parts + part) /** * Creates a copy of this word with all provided [parts] appended. */ fun plus(vararg parts: String) = Word(this.parts + parts) /** * Creates a copy of this word with all parts of the provided [word] appended. */ operator fun plus(word: Word) = Word(parts + word.parts) override fun toString() = "Word(${parts.joinToString { "\"$it\"" }})" override fun equals(other: Any?) = this === other || (other is Word && partsList == other.partsList) override fun hashCode() = partsList.hashCode() } /** * Converts `this` string, into a [Word] according to the provided [notation]. This method expects that the input is formatted according to * the [notation] and creates a notation-agnostic representation of it. */ fun String.fromNotation(notation: StringNotation): Word = notation.parse(this)
2
Kotlin
0
0
a3fdd5d16da4318ca3aea7727c9c68a18eacafdb
2,564
string-notation
MIT License
src/me/bytebeats/algo/kt/Solution10.kt
bytebeats
251,234,289
false
null
package me.bytebeats.algo.kt import me.bytebeats.algs.ds.TreeNode class Solution10 { class Node(val `val`: Int) { var prev: Node? = null var next: Node? = null var child: Node? = null } fun flatten(root: Node?): Node? {//430, recursive if (root == null) return root val dummy = Node(-1) dummy.next = root flattenDFS(dummy, root) dummy.next?.prev = null return dummy.next } private fun flattenDFS(pre: Node?, cur: Node?): Node? { if (cur == null) return pre pre?.next = cur cur?.prev = pre val next = cur.next val tail = flattenDFS(cur, cur?.child) cur?.child = null return flattenDFS(tail, next) } fun flatten2(root: Node?): Node? {//430, loop if (root == null) return root val dummy = Node(-1) dummy.next = root var pre: Node? = dummy var cur: Node? = null val stack = mutableListOf<Node>() stack.add(root) while (stack.isNotEmpty()) { cur = stack.removeAt(stack.lastIndex) pre?.next = cur cur?.prev = pre if (cur?.next != null) stack.add(cur?.next!!) if (cur?.child != null) { stack.add(cur?.child!!) cur?.child = null } pre = cur } dummy.next?.prev = null return dummy.next } fun countSmaller(nums: IntArray): List<Int> {//315 val ans = mutableListOf<Int>() val set = mutableSetOf<Int>() set.addAll(nums.toTypedArray()) val a = set.toList().sorted() val c = IntArray(nums.size + 5) { 0 } var id = 0 for (i in nums.lastIndex downTo 0) { id = a.binarySearch(nums[i]) + 1 var ret = 0 var pos = id - 1 while (pos > 0) { ret += c[pos] pos -= pos and (-pos) } ans.add(ret) pos = id while (pos < c.size) { c[pos] += 1 pos += pos and -pos } } return ans.reversed() } fun countSmaller1(nums: IntArray): List<Int> {//315 val ans = mutableListOf<Int>() if (nums.isNotEmpty()) { ans.add(0) val size = nums.size for (i in size - 2 downTo 0) { nums.sort(i + 1) if (nums.last() < nums[i]) { ans.add(size - i - 1) } else if (nums[i] <= nums[i + 1]) { ans.add(0) } else { var left = i + 1 var right = size - 1 var mid = 0 while (left < right) { mid = left + (right - left) / 2 if (nums[mid] >= nums[i]) { right = mid } else { left = mid + 1 } } ans.add(left - i - 1) } } } return ans.reversed() } fun flatten(root: TreeNode?): Unit {//114 if (root == null) return if (root.left != null) { val right = root.right//获取右子树 root.right = root.left//右子树的位置放置左子树 root.left = null var p = root while (p?.right != null) { p = p?.right } p?.right = right//右子树放在原先左子树的(右子树的)右子树 } flatten(root.right) } fun subsets(nums: IntArray): List<List<Int>> {//78 val ans = mutableListOf<MutableList<Int>>() var pow = 1 shl nums.size for (i in 0 until pow) { val list = mutableListOf<Int>() var nn = i var j = 0 while (nn > 0) { if (nn and 1 == 1) { list.add(nums[j]) } j += 1 nn /= 2 } ans.add(list) } return ans } fun reformatDate(date: String): String {//1507 val months = mapOf( "Jan" to 1, "Feb" to 2, "Mar" to 3, "Apr" to 4, "May" to 5, "Jun" to 6, "Jul" to 7, "Aug" to 8, "Sep" to 9, "Oct" to 10, "Nov" to 11, "Dec" to 12 ) val strs = date.split(" ") var d = strs[0].substring(0, strs[0].length - 2) if (d.length < 2) { d = "0$d" } var m = months[strs[1]].toString() if (m.length < 2) { m = "0$m" } return "${strs[2]}-${m}-${d}" } fun rangeSum(nums: IntArray, n: Int, left: Int, right: Int): Int { val mod = Math.pow(10.0, 9.0).toInt() + 7 val arr = IntArray(n * (n + 1) / 2) var i = 0 for (j in nums.indices) { var sum = 0 for (k in j until nums.size) { sum += nums[k] arr[i++] = sum } } arr.sort() var sum = 0 for (i in left - 1 until right) { sum += arr[i] sum %= mod } return sum } fun minDifference(nums: IntArray): Int { val s = nums.size if (s <= 4) return 0 nums.sort() return (nums[s - 4] - nums[0]).coerceAtMost(nums[s - 1] - nums[3]) } fun winnerSquareGame(n: Int): Boolean { var nn = n var isAlice = true var sqrt = Math.sqrt(nn.toDouble()).toInt() var sn = sqrt * sqrt while (sn <= nn) { nn -= sn if (nn == 0) { return isAlice } sqrt = Math.sqrt(nn.toDouble()).toInt() sn = sqrt * sqrt isAlice = !isAlice } return false } fun numIdenticalPairs(nums: IntArray): Int { var ans = 0 for (i in 0 until nums.size - 1) { for (j in i + 1 until nums.size) { if (nums[i] == nums[j]) { ans += 1 } } } return ans } fun numSub(s: String): Int {//1513 var ans = 0L var count = 0L var mod = 1000000007L for (i in s.indices) { if (s[i] == '1') { count += 1L } else { ans = (ans + count * (count + 1) / 2L) % mod count = 0L } } ans = (ans + count * (count + 1) / 2L) % mod return ans.toInt() } fun getMinDistSum(positions: Array<IntArray>): Double { if (positions.size <= 1) return 0.0 var p1 = positions[0] var p2 = positions[1] var cx = (p1[0] + p2[0]) / 2.0 var cy = (p1[1] + p2[1]) / 2.0 var a = p1[0] - cx var b = p1[1] - cy var square = a * a + b * b println("x=$cx, y=$cy, squre=$square") for (i in 2 until positions.size) { val p = positions[i] val aa = cx - p[0] val bb = cy - p[1] if (aa * aa + bb * bb <= square) { continue } else { for (j in 0 until i) { var x = (positions[j][0] + p[0]) / 2.0 var y = (positions[j][1] + p[1]) / 2.0 var flag = true for (k in 0 until i) { val xx = positions[k][0] - x val yy = positions[k][1] - y var flag = true if (xx * xx + yy * yy > square) { cx = (p[0] + positions[k][0]) / 2.0 cy = (p[1] + positions[k][1]) / 2.0 val xxx = cx - p[0] val yyy = cy - p[1] square = xxx * xxx + yyy * yyy flag = false break } if (!flag) { continue } } } } } var ans = 0.0 for (i in positions.indices) { val p = positions[i] val x = p[0] val y = p[1] val a = cx - x val b = cy - y ans += Math.sqrt(a * a + b * b) } return ans } fun reverseBits(n: Int): Int {//190 var ans = 0 var l = 32 var nn = n while (l-- > 0) { ans = ans shl 1 ans = ans or (nn and 1) nn = nn shr 1 } return ans } fun findRelativeRanks(nums: IntArray): Array<String> {//506 val map = mutableMapOf<Int, Int>() nums.sortedDescending().forEachIndexed { index, i -> map[i] = index } val ans = Array(nums.size) { "" } for (i in nums.indices) { val rank = map[nums[i]] ?: 0 if (rank == 0) { ans[i] = "Gold Medal" } else if (rank == 1) { ans[i] = "Silver Medal" } else if (rank == 2) { ans[i] = "Bronze Medal" } else { ans[i] = "${rank + 1}" } } return ans } private val dirs = arrayOf(intArrayOf(-1, 0), intArrayOf(1, 0), intArrayOf(0, -1), intArrayOf(0, 1)) fun longestIncreasingPath(matrix: Array<IntArray>): Int {//329 if (matrix.isEmpty() || matrix[0].isEmpty()) return 0 val row = matrix.size val column = matrix[0].size val dp = Array(row) { IntArray(column) } var ans = 0 for (i in 0 until row) { for (j in 0 until column) { ans = ans.coerceAtLeast(dfs(matrix, i, j, dp, row, column)) } } return ans } private fun dfs(matrix: Array<IntArray>, r: Int, c: Int, dp: Array<IntArray>, m: Int, n: Int): Int { if (dp[r][c] != 0) return dp[r][c] dp[r][c] += 1 for (dir in dirs) { val newR = r + dir[0] val newC = c + dir[1] if (newR in 0 until m && newC in 0 until n && matrix[newR][newC] > matrix[r][c]) { dp[r][c] = dp[r][c].coerceAtLeast(dfs(matrix, newR, newC, dp, m, n) + 1) } } return dp[r][c] } fun leastInterval(tasks: CharArray, n: Int): Int {//621 val map = IntArray(26) for (task in tasks) { map[task - 'A'] += 1 } map.sort() var time = 0 while (map[25] > 0) { var i = 0 while (i <= n) { if (map[25] == 0) break if (i < 26 && map[25 - i] > 0) { map[25 - i]-- } time++ i++ } map.sort() } return time } fun wordBreak(s: String, wordDict: List<String>): List<String> {//140 val size = s.length val dp = BooleanArray(size) { false } val set = mutableSetOf<String>() set.addAll(wordDict) for (i in 0 until size) { if (set.contains(s.substring(0, i + 1))) { dp[i] = true continue } for (j in 0 until i) { if (dp[j] && set.contains(s.substring(j + 1, i + 1))) { dp[i] = true break } } } val ans = mutableListOf<String>() if (dp.last()) { val q = mutableListOf<String>() dfs(s, size - 1, set, ans, q, dp) return ans } return ans } private fun dfs( s: String, end: Int, wordSet: Set<String>, ans: MutableList<String>, q: MutableList<String>, dp: BooleanArray ) { if (wordSet.contains(s.substring(0, end + 1))) { q.add(0, s.substring(0, end + 1)) val sb = StringBuilder() for (word in q) { sb.append(word) sb.append(" ") } sb.deleteCharAt(sb.lastIndex) ans.add(sb.toString()) q.removeAt(0) } for (i in 0 until end) { if (dp[i]) { val suffix = s.substring(i + 1, end + 1) if (wordSet.contains(suffix)) { q.add(0, suffix) dfs(s, i, wordSet, ans, q, dp) q.removeAt(0) } } } } fun smallestRange(nums: List<List<Int>>): IntArray {//632 val s = nums.size val indices = mutableMapOf<Int, MutableList<Int>>() var xMin = Int.MAX_VALUE var xMax = Int.MIN_VALUE for (i in 0 until s) { for (x in nums[i]) { val list = indices.getOrDefault(x, mutableListOf()) list.add(i) indices[x] = list xMin = xMin.coerceAtMost(x) xMax = xMax.coerceAtLeast(x) } } val freq = IntArray(s) var inside = 0 var left = xMin var right = xMin - 1 var bestLeft = xMin var bestRight = xMax while (right < xMax) { right += 1 if (indices.containsKey(right)) { indices[right]?.forEach { freq[it] += 1 if (freq[it] == 1) { inside += 1 } } while (inside == s) { if (right - left < bestRight - bestLeft) { bestLeft = left bestRight = right } if (indices.containsKey(left)) { indices[left]?.forEach { freq[it] -= 1 if (freq[it] == 0) { inside -= 1 } } } left += 1 } } } return intArrayOf(bestLeft, bestRight) } fun buddyStrings(A: String, B: String): Boolean {//859 if (A.length != B.length) return false if (A == B) { val count = IntArray(26) for (i in A.indices) { count[A[i] - 'a'] += 1 } for (c in count) { if (c > 1) return true } return false } else { var first = -1 var second = -1 for (i in A.indices) { if (A[i] != B[i]) { if (first == -1) { first = i } else if (second == -1) { second = i } else { return false } } } return second != -1 && A[first] == B[second] && A[second] == B[first] } } fun countGoodTriplets(arr: IntArray, a: Int, b: Int, c: Int): Int {//5475 var count = 0 val s = arr.size for (i in 0 until s - 2) { for (j in i + 1 until s - 1) { for (k in j + 1 until s) { if (Math.abs(arr[i] - arr[j]) <= a && Math.abs(arr[j] - arr[k]) <= b && Math.abs(arr[i] - arr[k]) <= c) { count += 1 } } } } return count } fun surfaceArea(grid: Array<IntArray>): Int {//892 val dr = intArrayOf(0, 1, 0, -1) val dc = intArrayOf(1, 0, -1, 0) val N = grid.size var ans = 0 for (r in 0 until N) for (c in 0 until N) if (grid[r][c] > 0) { ans += 2 for (k in 0..3) { val nr = r + dr[k] val nc = c + dc[k] var nv = 0 if (nr in 0 until N && nc in 0 until N) nv = grid[nr][nc] ans += Math.max(grid[r][c] - nv, 0) } } return ans } fun allCellsDistOrder(R: Int, C: Int, r0: Int, c0: Int): Array<IntArray> {//1030 val ans = Array(R * C) { r -> intArrayOf(r / C, r % C) } ans.sortBy { arr -> Math.abs(arr[0] - r0) + Math.abs(arr[1] - c0) } return ans } fun numRookCaptures(board: Array<CharArray>): Int {//999 var ans = 0 var start = 0 var end = 0 val dx = intArrayOf(0, 1, 0, -1) val dy = intArrayOf(1, 0, -1, 0) for (i in 0 until 8) for (j in 0 until 8) { if (board[i][j] == 'R') { start = i end = j break } } for (i in 0 until 4) { var step = 0 while (true) { val tx = start + step * dx[i] val ty = end + step * dy[i] if (tx < 0 || tx >= 8 || ty < 0 || ty >= 8 || board[tx][ty] == 'B') break if (board[tx][ty] == 'p') { ans += 1 break } step += 1 } } return ans } fun reorderLogFiles(logs: Array<String>): Array<String> {//937 logs.sortWith(Comparator { o1, o2 -> val regex = Regex(" ") val split1 = o1.split(regex, 2) val split2 = o2.split(regex, 2) val isDigit1 = split1[1][0].isDigit() val isDigit2 = split2[1][0].isDigit() if (!isDigit1 && !isDigit2) { val cmp = split1[1].compareTo(split2[1]) if (cmp != 0) return@Comparator cmp else return@Comparator split1[0].compareTo(split2[0]) } return@Comparator if (isDigit1) if (isDigit2) 0 else 1 else -1 }) return logs } fun numMagicSquaresInside(grid: Array<IntArray>): Int {//840 var count = 0 val row = grid.size val col = grid[0].size for (i in 0 until row - 2) for (j in 0 until col - 2) { val set = mutableSetOf<Int>() var min = Int.MAX_VALUE var max = Int.MIN_VALUE for (ii in i..i + 2) for (jj in j..j + 2) { set.add(grid[ii][jj]) min = min.coerceAtMost(grid[ii][jj]) max = max.coerceAtLeast(grid[ii][jj]) } if (set.size != 9 || min != 1 || max != 9) { continue } val sum = grid[i][j] + grid[i][j + 1] + grid[i][j + 2] if (sum != grid[i + 1][j] + grid[i + 1][j + 1] + grid[i + 1][j + 2]) continue if (sum != grid[i + 2][j] + grid[i + 2][j + 1] + grid[i + 2][j + 2]) continue if (sum != grid[i][j] + grid[i + 1][j] + grid[i + 2][j]) continue if (sum != grid[i][j + 1] + grid[i + 1][j + 1] + grid[i + 2][j + 1]) continue if (sum != grid[i][j + 2] + grid[i + 1][j + 2] + grid[i + 2][j + 2]) continue if (sum != grid[i][j] + grid[i + 1][j + 1] + grid[i + 2][j + 2]) continue if (sum != grid[i + 2][j] + grid[i + 1][j + 1] + grid[i][j + 2]) continue count += 1 } return count } fun countPrimeSetBits(L: Int, R: Int): Int {//762 var count = 0 for (num in L..R) { if (isSmallPrime(compute(num))) { count += 1 } } return count } private fun compute(num: Int): Int { var count = 0 var n = num while (n != 0) { count += n and 1 n = n shr 1 } return count } private fun isSmallPrime(n: Int): Boolean = (n == 2 || n == 3 || n == 5 || n == 7 || n == 11 || n == 13 || n == 17 || n == 19) fun maxDistToClosest(seats: IntArray): Int {//849 val idx = mutableListOf<Int>() for (i in seats.indices) { if (seats[i] == 1) { idx.add(i) } } var ans = idx.first().coerceAtLeast(seats.size - 1 - idx.last()) for (i in 1..idx.lastIndex) { if (idx[i] - idx[i - 1] > 1) { ans = ans.coerceAtLeast((idx[i] - idx[i - 1]) / 2) } } return ans } fun transpose(A: Array<IntArray>): Array<IntArray> {//867 val row = A.size val col = A[0].size val ans = Array(col) { IntArray(row) } for (i in 0 until row) for (j in 0 until col) { ans[j][i] = A[i][j] } return ans } fun isLongPressedName(name: String, typed: String): Boolean {//925 var j = 0 for (c in name) { if (j == typed.length) return false if (c != typed[j]) { if (j == 0 || typed[j - 1] != typed[j]) return false val ch = typed[j] while (j < typed.length && typed[j] == ch) j += 1 if (j == typed.length || c != typed[j]) return false } j += 1 } while (j < typed.length && typed[j - 1] == typed[j]) j += 1 return j == typed.length } fun diStringMatch(S: String): IntArray {//942 val n = S.length var low = 0 var high = n val ans = IntArray(n + 1) for (i in S.indices) { if (S[i] == 'I') { ans[i] = low++ } else { ans[i] = high-- } } ans[n] = low return ans } fun minDeletionSize(A: Array<String>): Int {//944 var count = 0 val r = A.size val c = A[0].length for (j in 0 until c) for (i in 1 until r) { if (A[i][j] < A[i - 1][j]) { count += 1 break } } return count } fun orangesRotting(grid: Array<IntArray>): Int {//994 val r = grid.size val c = grid[0].size val rottens = mutableListOf<IntArray>() var fresh = 0 for (i in 0 until r) for (j in 0 until c) { if (grid[i][j] == 2) rottens.add(intArrayOf(i, j)) else if (grid[i][j] == 1) fresh += 1 } if (rottens.isEmpty()) { if (fresh == 0) return 0 else return -1 } var seconds = -1 val adjacent = mutableListOf<IntArray>() while (rottens.isNotEmpty()) { while (rottens.isNotEmpty()) { val rotten = rottens.removeAt(0) val x = rotten[0] val y = rotten[1] if (x > 0 && grid[x - 1][y] == 1) { grid[x - 1][y] = 2 adjacent.add(intArrayOf(x - 1, y)) } if (x < r - 1 && grid[x + 1][y] == 1) { grid[x + 1][y] = 2 adjacent.add(intArrayOf(x + 1, y)) } if (y > 0 && grid[x][y - 1] == 1) { grid[x][y - 1] = 2 adjacent.add(intArrayOf(x, y - 1)) } if (y < c - 1 && grid[x][y + 1] == 1) { grid[x][y + 1] = 2 adjacent.add(intArrayOf(x, y + 1)) } } rottens.addAll(adjacent) adjacent.clear() seconds += 1 } for (i in 0 until r) for (j in 0 until c) { if (grid[i][j] == 1) return -1 } return seconds } fun restoreIpAddresses(s: String): List<String> {//93 val n = s.length val ans = mutableListOf<String>() if (n in 4..12) { for (i in 0..2) { if (n - i - 1 !in 3..9) continue for (j in i + 1..i + 3) { if (n - j - 1 !in 2..6) continue for (k in j + 1..j + 3) { if (n - k - 1 !in 1..3) continue val first = s.substring(0, i + 1) if (first.toInt() !in 0..255 || first.toInt().toString() != first) continue val second = s.substring(i + 1, j + 1) if (second.toInt() !in 0..255 || second.toInt().toString() != second) continue val third = s.substring(j + 1, k + 1) if (third.toInt() !in 0..255 || third.toInt().toString() != third) continue val forth = s.substring(k + 1, n) if (forth.toInt() !in 0..255 || forth.toInt().toString() != forth) continue ans.add("$first.$second.$third.$forth") } } } } return ans } fun findKthPositive(arr: IntArray, k: Int): Int {//5648 val set = mutableSetOf<Int>() for (i in arr) { set.add(i) } val max = arr.last() for (i in 1..max) { if (set.contains(i)) set.remove(i) else set.add(i) } if (k <= set.size) { return set.toList()[k - 1] } else { return max + (k - set.size) } } fun makeGood(s: String): String {//5483, 1544 var ss = s var idx = idx(ss) while (idx > -1) { ss = "${ss.substring(0, idx)}${ss.substring(idx + 2, ss.length)}" idx = idx(ss) } return ss } private fun idx(s: String): Int { for (i in 0 until s.length - 1) { if (s[i] != s[i + 1] && s[i].toLowerCase() == s[i + 1].toLowerCase()) { return i } } return -1 } fun maxArea(height: IntArray): Int {//11 var max = 0 var tmp = 0 var i = 0 var j = height.size - 1 while (i < j) { if (height[i] > height[j]) { tmp = height[j] * (j - i) j-- } else { tmp = height[i] * (j - i) i++ } max = max.coerceAtLeast(tmp) } return max } fun letterCombinations(digits: String): List<String> {//17 val map = mapOf( '2' to charArrayOf('a', 'b', 'c'), '3' to charArrayOf('d', 'e', 'f'), '4' to charArrayOf('g', 'h', 'i'), '5' to charArrayOf('j', 'k', 'l'), '6' to charArrayOf('m', 'n', 'o'), '7' to charArrayOf('p', 'q', 'r', 's'), '8' to charArrayOf('t', 'u', 'v'), '9' to charArrayOf('w', 'x', 'y', 'z') ) val ans = mutableListOf<String>() for (d in digits) { val chs = map[d]!! val tmp = mutableListOf<String>() tmp.addAll(ans) ans.clear() if (tmp.isEmpty()) { for (ch in chs) { ans.add(ch.toString()) } } else { for (ch in chs) { for (str in tmp) { ans.add("$str$ch") } } } } return ans } fun titleToNumber(s: String): Int { var num = 0 for (c in s) { num *= 26 num += c - 'A' + 1 } return num } fun getRow(rowIndex: Int): List<Int> { val triangle = mutableListOf<Int>() for (i in 1..rowIndex + 1) { for (j in i - 1 downTo 0) { if (j == i - 1) { triangle.add(1) } else if (j == 0) { break } else { triangle[j] = triangle[j] + triangle[j - 1] } } } return triangle } fun isValid(s: String): Boolean {//20 val stack = mutableListOf<Char>() for (c in s) { if (c == '(' || c == '[' || c == '{') { stack.add(c) } else if (c == ')') { if (stack.isEmpty() || stack.last() != '(') return false stack.removeAt(stack.lastIndex) } else if (c == ']') { if (stack.isEmpty() || stack.last() != '[') return false stack.removeAt(stack.lastIndex) } else if (c == '}') { if (stack.isEmpty() || stack.last() != '{') return false stack.removeAt(stack.lastIndex) } } return stack.isEmpty() } fun longestPalindrome(s: String): Int {//409 val counts = IntArray(52) for (c in s) { if (c >= 'a') { counts[c - 'a' + 26] += 1 } else { counts[c - 'A'] += 1 } } var evenSum = 0 var oddSum = 0 var oddCount = 0 for (count in counts) { if (count and 1 == 0) { evenSum += count } else { oddCount += 1 oddSum += count } } if (oddCount > 0) { oddSum -= oddCount - 1 } return evenSum + oddSum } fun eraseOverlapIntervals(intervals: Array<IntArray>): Int {//435 if (intervals.isEmpty()) return 0 intervals.sortWith(Comparator { o1, o2 -> o1[0] - o2[0] }) var prev = 0 var count = 0 for (i in 1 until intervals.size) { if (intervals[prev][1] > intervals[i][0]) { if (intervals[prev][1] > intervals[i][1]) { prev = i } count += 1 } else { prev = i } } return count } fun threeConsecutiveOdds(arr: IntArray): Boolean {//5185, 1550 if (arr.size < 3) return false for (i in 0 until arr.size - 2) { if (arr[i] and 1 == 1 && arr[i + 1] and 1 == 1 && arr[i + 2] and 1 == 1) { return true } } return false } fun minDepth(root: TreeNode?): Int {//111 var minDepth = 0 if (root != null) { val q = mutableListOf<TreeNode>() q.add(root) var cur = 0 var countDown = 1 var p = root minDepth += 1 while (q.isNotEmpty()) { p = q.removeAt(0) if (p.left == null && p.right == null) { return minDepth } countDown -= 1 if (p.left != null) { q.add(p.left) cur += 1 } if (p.right != null) { q.add(p.right) cur += 1 } if (countDown == 0) { minDepth += 1 countDown = cur cur = 0 } } } return minDepth } fun rangeBitwiseAnd(m: Int, n: Int): Int {//201 var ans = n while (ans > m) { ans = ans and (ans - 1) } return ans } fun hammingDistance(x: Int, y: Int): Int {//461 var xx = x var yy = y var ans = 0 while (xx != 0 || yy != 0) { ans += (xx and 1) xor (yy and 1) xx = xx shr 1 yy = yy shr 1 } return ans } fun thousandSeparator(n: Int): String {//5479, 1556 val ans = StringBuilder() val src = n.toString().reversed() var three = 3 for (i in src.indices) { three -= 1 ans.append(src[i]) if (three == 0 && src[i].isDigit() && i != src.lastIndex) { ans.append(".") three = 3 } } return ans.reverse().toString() } fun findSubsequences(nums: IntArray): List<List<Int>> {//491 val ans = mutableListOf<MutableList<Int>>() for (num in nums) { val size = ans.size for (i in 0 until size) { if (ans[i].last() <= num) { val newList = mutableListOf<Int>() newList.addAll(ans[i]) newList.add(num) ans.add(newList) } } val list = mutableListOf<Int>() list.add(num) ans.add(list) } return ans.distinctBy { it.joinToString() }.filter { it.size > 1 } } fun shortestPalindrome(s: String): String {//214 var maxIdx = 0 for (i in s.lastIndex downTo 0) { if (isPalindrome(s, i)) { maxIdx = i break } } val ans = StringBuilder() for (j in maxIdx + 1 until s.length) { ans.append(s[j]) } ans.reverse() ans.append(s) return ans.toString() } private fun isPalindrome(s: String, end: Int): Boolean { var i = 0 var j = end while (i < j) { if (s[i] != s[j]) { return false } i += 1 j -= 1 } return true } fun pancakeSort(A: IntArray): List<Int> {//969 val ans = mutableListOf<Int>() var idx = A.lastIndex while (idx >= 0) { val idxOfMax = findIdxOfMax(A, idx) if (idxOfMax != idx) { ans.add(idxOfMax + 1) ans.add(idx + 1) pancake(A, idxOfMax) pancake(A, idx) } idx -= 1 } return ans } private fun pancake(A: IntArray, end: Int) { var i = 0 var j = end var tmp = 0 while (i < j) { tmp = A[i] A[i] = A[j] A[j] = tmp i += 1 j -= 1 } } private fun findIdxOfMax(A: IntArray, end: Int): Int { var idxOfMax = end for (i in 0 until end) { if (A[i] > A[idxOfMax]) { idxOfMax = i } } return idxOfMax } fun canVisitAllRooms(rooms: List<List<Int>>): Boolean {//841 val visited = mutableSetOf<Int>() val inRooms = mutableListOf<Int>() inRooms.add(0) visited.add(0) while (inRooms.isNotEmpty()) { val curKeys = rooms[inRooms.removeAt(0)] for (key in curKeys) { if (!visited.contains(key)) { inRooms.add(key) visited.add(key) } } } return visited.size == rooms.size } fun deleteNode(root: TreeNode?, key: Int): TreeNode? {//450 if (root == null) return null if (root.`val` > key) { root.left = deleteNode(root.left, key) return root } else if (root.`val` < key) { root.right = deleteNode(root.right, key) return root } else { var p = root.left ?: return root.right while (p.right != null) { p = p.right } p.right = root.right return root.left } } fun containsPattern(arr: IntArray, m: Int, k: Int): Boolean {//1566 if (m * k <= arr.size) { for (i in 0..arr.size - m * k) { val sub = arr.copyOfRange(i, i + m).joinToString() var cnt = 0 while (arr.copyOfRange(i + m * cnt, i + m * cnt + m).joinToString() == sub) { cnt += 1 if (cnt >= k) { return true } } } } return false } fun PredictTheWinner(nums: IntArray): Boolean {//486 return total(nums, 0, nums.lastIndex, 1) >= 0 } private fun total(nums: IntArray, start: Int, end: Int, turn: Int): Int { if (start == end) return nums[start] * turn val scoreStart = nums[start] * turn + total(nums, start + 1, end, -turn) val scoreEnd = nums[end] * turn + total(nums, start, end - 1, -turn) return (scoreStart * turn).coerceAtLeast(scoreEnd * turn) * turn } fun largestTimeFromDigits(A: IntArray): String {//949 var ans = -1 //choose i, j, k, l as a permutation of 0, 1, 2, 3 for (i in 0 until 4) for (j in 0 until 4) if (i != j) for (k in 0 until 4) if (k != i && k != j) { val l = 6 - i - j - k val hours = 10 * A[i] + A[j] val mins = 10 * A[k] + A[l] if (hours < 24 && mins < 60) { ans = ans.coerceAtLeast(hours * 60 + mins) } } return if (ans >= 0) "%02d:%02d".format(ans / 60, ans % 60) else "" } }
0
Kotlin
0
1
7cf372d9acb3274003bb782c51d608e5db6fa743
37,133
Algorithms
MIT License
src/main/kotlin/com/github/davio/aoc/y2020/Day2.kt
Davio
317,510,947
false
{"Kotlin": 405939}
package com.github.davio.aoc.y2020 import com.github.davio.aoc.general.Day import com.github.davio.aoc.general.call import com.github.davio.aoc.general.getInputAsSequence fun main() { Day2.getResultPart1() Day2.getResultPart2() } object Day2 : Day() { /* * --- Day 2: Password Philosophy --- Your flight departs in a few days from the coastal airport; the easiest way down to the coast from here is via toboggan. The shopkeeper at the North Pole Toboggan Rental Shop is having a bad day. "Something's wrong with our computers; we can't log in!" You ask if you can take a look. Their password database seems to be a little corrupted: some of the passwords wouldn't have been allowed by the Official Toboggan Corporate Policy that was in effect when they were chosen. To try to debug the problem, they have created a list (your puzzle input) of passwords (according to the corrupted database) and the corporate policy when that password was set. For example, suppose you have the following list: 1-3 a: abcde 1-3 b: cdefg 2-9 c: ccccccccc Each line gives the password policy and then the password. The password policy indicates the lowest and highest number of times a given letter must appear for the password to be valid. For example, 1-3 a means that the password must contain a at least 1 time and at most 3 times. In the above example, 2 passwords are valid. The middle password, cdefg, is not; it contains no instances of b, but needs at least 1. The first and third passwords are valid: they contain one a or nine c, both within the limits of their respective policies. How many passwords are valid according to their policies? * * --- Part Two --- While it appears you validated the passwords correctly, they don't seem to be what the Official Toboggan Corporate Authentication System is expecting. The shopkeeper suddenly realizes that he just accidentally explained the password policy rules from his old job at the sled rental place down the street! The Official Toboggan Corporate Policy actually works a little differently. Each policy actually describes two positions in the password, where 1 means the first character, 2 means the second character, and so on. (Be careful; Toboggan Corporate Policies have no concept of "index zero"!) Exactly one of these positions must contain the given letter. Other occurrences of the letter are irrelevant for the purposes of policy enforcement. Given the same example list from above: 1-3 a: abcde is valid: position 1 contains a and position 3 does not. 1-3 b: cdefg is invalid: neither position 1 nor position 3 contains b. 2-9 c: ccccccccc is invalid: both position 2 and position 9 contain c. How many passwords are valid according to the new interpretation of the policies? */ fun getResultPart1() { getInputAsSequence() .map { getLineParts(it) } .count { isResultPart1Valid(it) } .call { println(it) } } private fun getLineParts(line: String): Pair<String, String> { val parts = splitLine(line) val policy = parts[0] val password = parts[1].trim() return Pair(policy, password) } private fun splitLine(line: String) = line.split(":") private fun isResultPart1Valid(parts: Pair<String, String>): Boolean { return PasswordPolicy.parse(parts.first).checkPart1(parts.second) } fun getResultPart2() { getInputAsSequence() .map { getLineParts(it) } .count { isResultPart2Valid(it) } .call { println(it) } } private fun isResultPart2Valid(parts: Pair<String, String>): Boolean { return PasswordPolicy.parse(parts.first).checkPart2(parts.second) } class PasswordPolicy private constructor( private val n1: Int, private val n2: Int, private val char: Char ) { fun checkPart1(password: String) = password.count { it == char } in n1..n2 fun checkPart2(password: String) = (password[n1 - 1] == char) xor (password[n2 - 1] == char) companion object { fun parse(policy: String): PasswordPolicy { val policyParts = policy.split(" ") val numberParts = policyParts[0].split("-") return PasswordPolicy( numberParts[0].toInt(), numberParts[1].toInt(), policyParts[1][0] ) } } } }
1
Kotlin
0
0
4fafd2b0a88f2f54aa478570301ed55f9649d8f3
4,599
advent-of-code
MIT License
src/main/java/Day3.kt
mattyb678
319,195,903
false
null
class Day3 : Day { override fun asInt(): Int = 3 override fun part1InputName(): String = "day3" override fun part1(input: List<String>): String { println("Day 3, Part 1") val treeCount = treeCountForSlope(3, 1, input) return treeCount.toString() } private fun treeCountForSlope(x: Int, y: Int, rows: List<String>): Int { var rowIdx = 0 + y var colIdx = 0 var treeCount = 0 while (rowIdx < rows.size) { colIdx += x val row = rows[rowIdx] val toCheck = colIdx % row.count() if (row[toCheck] == TREE) { treeCount += 1 } rowIdx += y } return treeCount } override fun part2InputName(): String = "day3" override fun part2(input: List<String>): String { val counts = listOf( treeCountForSlope(1, 1, input), treeCountForSlope(3, 1, input), treeCountForSlope(5, 1, input), treeCountForSlope(7, 1, input), treeCountForSlope(1, 2, input) ) return counts.map { it.toDouble() }.reduce(Double::times).toBigDecimal().toPlainString() } companion object { private const val TREE = '#' } }
0
Kotlin
0
1
f677d61cfd88e18710aafe6038d8d59640448fb3
1,274
aoc-2020
MIT License
Kotlin/problem021.kt
emergent
116,013,843
false
null
// Problem 21 - Project Euler // http://projecteuler.net/index.php?section=problems&id=21 import kotlin.math.* fun divisors(x: Int): List<Int> { val lim = ceil(sqrt(x.toDouble())).toInt() return (1..lim) .map { n -> if (x % n == 0) listOf(n, x/n) else null } .filterNotNull() .flatten() .distinct() .toList() } fun d(x: Int) = divisors(x).sum() - x fun amicable_pair(x: Int): Int? { val dx = d(x) return if (d(dx) == x && dx != x) dx else null } fun main(args: Array<String>) { val ans = (1..10000-1).map { amicable_pair(it) } .filterNotNull() .filter { it < 10000 } .sum() println(ans) }
0
Rust
0
0
d04f5029385c09a569c071254191c75d582fe340
741
ProjectEuler
The Unlicense
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[389]找不同.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给定两个字符串 s 和 t,它们只包含小写字母。 // // 字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。 // // 请找出在 t 中被添加的字母。 // // // // 示例 1: // // 输入:s = "abcd", t = "abcde" //输出:"e" //解释:'e' 是那个被添加的字母。 // // // 示例 2: // // 输入:s = "", t = "y" //输出:"y" // // // 示例 3: // // 输入:s = "a", t = "aa" //输出:"a" // // // 示例 4: // // 输入:s = "ae", t = "aea" //输出:"a" // // // // // 提示: // // // 0 <= s.length <= 1000 // t.length == s.length + 1 // s 和 t 只包含小写字母 // // Related Topics 位运算 哈希表 // 👍 211 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun findTheDifference(s: String, t: String): Char { //将字符串 s t 中每个字符的 ASCII 码的值求和相减得到多出字符值 //时间复杂 O(n) var a = 0 var b = 0 for(i in t.indices ){ if(i<s.length) a += s[i].toInt() b += t[i].toInt() } return (b-a).toChar() } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,252
MyLeetCode
Apache License 2.0
scratch/src/main/kotlin/x/scratch/difference-engine.kt
binkley
184,655,460
false
null
package x.scratch fun main() { println("==DIFFERENCE ENGINE") val ours = listOf( Left("ALICE", 2), // common, unchanged Left("BOB", 3), // added Left("DAVE", 5), // common, changed ) val theirs = listOf( Right("ALICE", "2"), // common, unchanged Right("CAROL", "4"), // removed Right("DAVE", "6"), // common, changed ) val engine = DifferenceEngine(Left::key, Right::key) { a, b -> "${a.satelliteData}" == b.satelliteData } val diff = engine.diff(ours, theirs) println() println("ADDED -> ${diff.addedByUs}") println("REMOVED -> ${diff.removedByUs}") println("CHANGED -> ${diff.changedByUs}") } class DifferenceEngine<KEY, OURS, THEIRS>( private val ourCommonKey: (OURS) -> KEY, private val theirCommonKey: (THEIRS) -> KEY, private val equivalent: (OURS, THEIRS) -> Boolean, ) { fun diff( ours: Collection<OURS>, theirs: Collection<THEIRS>, ): Difference<KEY, OURS, THEIRS> { return Difference( ourCommonKey, theirCommonKey, equivalent, ours, theirs ) } } class Difference<KEY, OURS, THEIRS>( ourCommonKey: (OURS) -> KEY, theirCommonKey: (THEIRS) -> KEY, equivalent: (OURS, THEIRS) -> Boolean, ours: Collection<OURS>, theirs: Collection<THEIRS>, ) { val addedByUs: List<OURS> val removedByUs: List<THEIRS> val changedByUs: List<Pair<OURS, THEIRS>> init { val oursByKey = ours.map { ourCommonKey(it) to it }.toMap() val theirsByKey = theirs.map { theirCommonKey(it) to it }.toMap() addedByUs = oursByKey.entries .filter { !theirsByKey.containsKey(it.key) } .map { it.value } .toList() removedByUs = theirsByKey.entries .filter { !oursByKey.containsKey(it.key) } .map { it.value } .toList() // Suppress is unfortunate: Kotlin compiler does not understand after // the filter line that "second" cannot be NULL. This the rare case // where Java code compiles more efficiently @Suppress("UNCHECKED_CAST") changedByUs = oursByKey.entries .map { it.value to theirsByKey[it.key] } .filter { val them = it.second null != them && !equivalent(it.first, them) } .toList() as List<Pair<OURS, THEIRS>> } } private data class Left(val key: String, val satelliteData: Int) private data class Right(val key: String, val satelliteData: String)
0
Kotlin
1
2
4787a43f8e27dbde3a967b35f5a3363864cbd51f
2,665
spikes
The Unlicense
rtron-math/src/main/kotlin/io/rtron/math/range/RangeSetExtensions.kt
tum-gis
258,142,903
false
{"Kotlin": 1425220, "C": 12590, "Dockerfile": 511, "CMake": 399, "Shell": 99}
package io.rtron.math.range import io.rtron.std.powerSet /** * Unions a set of [RangeSet] to a single [RangeSet]. */ fun <T : Comparable<*>> Set<RangeSet<T>>.unionRangeSets(): RangeSet<T> = reduce { acc, element -> acc.union(element) } /** * Returns the intersecting [RangeSet]. * * @receiver provided set of [RangeSet] for which the intersecting [RangeSet] is evaluated * @return minimum intersecting range set */ fun <T : Comparable<*>> Set<RangeSet<T>>.intersectionRangeSets(): RangeSet<T> = reduce { acc, element -> acc.intersection(element) } /** * Returns true, if set of [RangeSet] contains intersecting [RangeSet] pairs. */ fun <T : Comparable<*>> Set<RangeSet<T>>.containsIntersectingRangeSets(): Boolean { val rangeSetPairCombinations = powerSet().filter { it.size == 2 }.map { Pair(it.first(), it.last()) } return rangeSetPairCombinations.any { it.first.intersects(it.second) } } /** * Conversion to [RangeSet]. * * @receiver [Range] to be converted */ fun <T : Comparable<*>> Range<T>.toRangeSet(): RangeSet<T> = RangeSet.of(this)
4
Kotlin
12
38
27969aee5a0c8115cb5eaf085ca7d4c964e1f033
1,085
rtron
Apache License 2.0
app/src/main/java/com/dlight/algoguide/dsa/sorting/quick_sort/QuickSort.kt
kodeflap
535,790,826
false
{"Kotlin": 129527}
package com.dlight.algoguide.dsa.sorting.quick_sort /** * Quick sort * * @constructor Create empty Quick sort */ class QuickSort { suspend fun quickSort( arr: IntArray, left: Int, right: Int) { /*First finding the partioning index using thepartion function */ val index = partition (arr, left, right) if (left < index - 1) /*checking for better position left or right then performing thr sort*/ quickSort(arr, left, index - 1) if (index < right ) quickSort(arr, index, right) } /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ private fun partition(arr: IntArray, left: Int, right: Int): Int { var left = left var right = right /* Pivot point */ val pivot = arr[(left + right) / 2] while (left <= right) { while (arr[left] < pivot) left++ while (arr[right] > pivot) right-- if (left <= right) { swap(arr, left, right) left++ right-- } } return left } /*Swap function that helps in swaping the numbers */ private fun swap(arr: IntArray, left: Int, right: Int) { val temp = arr [left] arr[left] = arr[right] arr[right] = temp } }
0
Kotlin
9
10
c4a7ddba54daecb219a1befa12583e3e8f3fa066
1,518
Algo_Guide
Apache License 2.0
src/main/kotlin/de/mbdevelopment/adventofcode/year2021/solvers/day9/Day9Puzzle1.kt
Any1s
433,954,562
false
{"Kotlin": 96683}
package de.mbdevelopment.adventofcode.year2021.solvers.day9 import de.mbdevelopment.adventofcode.year2021.solvers.PuzzleSolver class Day9Puzzle1 : PuzzleSolver { override fun solve(inputLines: Sequence<String>) = lowPointRiskLevelSum(inputLines).toString() private fun lowPointRiskLevelSum(rawHeightMap: Sequence<String>): Int { val heightMap = rawHeightMap .filter { it.isNotBlank() } .map { line -> line.map { it.digitToInt() } } .toList() val riskLevels = (heightMap.first().indices).map { x -> (heightMap.indices).map { y -> val adjacentHeights = listOfNotNull( heightMap[y].getOrNull(x - 1), // value to the left heightMap[y].getOrNull(x + 1), // value to the right heightMap.getOrNull(y - 1)?.get(x), // value above heightMap.getOrNull(y + 1)?.get(x), // value below ) val currentHeight = heightMap[y][x] if (adjacentHeights.all { currentHeight < it }) 1 + currentHeight else 0 } } return riskLevels.map { it.reduce(Int::plus) }.reduce(Int::plus) } }
0
Kotlin
0
0
21d3a0e69d39a643ca1fe22771099144e580f30e
1,228
AdventOfCode2021
Apache License 2.0
src/commonMain/kotlin/com/jeffpdavidson/kotwords/model/SpellWeaving.kt
jpd236
143,651,464
false
{"Kotlin": 4390419, "HTML": 41919, "Rouge": 3731, "Perl": 1705, "Shell": 744, "JavaScript": 618}
package com.jeffpdavidson.kotwords.model import com.jeffpdavidson.kotwords.formats.Puzzleable import kotlin.math.sqrt data class SpellWeaving( val title: String, val creator: String, val copyright: String, val description: String, val answers: List<String>, val clues: List<String> ) : Puzzleable() { override suspend fun createPuzzle(): Puzzle { val filteredAnswers = answers.map { answer -> answer.uppercase().filter { it in 'A'..'Z' } } val length = filteredAnswers.sumOf { it.length } val middleRowLengthDouble = (1 + sqrt(4 * length - 3.0)) / 2 val middleRowLength = middleRowLengthDouble.toInt() require(middleRowLength > 2 && middleRowLength % 2 == 0 && middleRowLengthDouble - middleRowLength == 0.0) { "Answers do not fit into a standard Spell Weaving grid." } val words = mutableListOf<List<Pair<Int, Int>>>() var position = Position(x = 0, y = middleRowLength / 2 - 1, direction = Direction.RIGHT) val gridMap = mutableMapOf<Pair<Int, Int>, CellState>() filteredAnswers.forEachIndexed { answerIndex, answer -> val word = mutableListOf<Pair<Int, Int>>() answer.forEachIndexed { i, ch -> val cellState = gridMap.getOrPut(position.x to position.y) { CellState(solution = "$ch") } require(cellState.solution == "$ch") { "Conflict at cell (${position.x}, ${position.y}) for answer $answerIndex ($answer): " + "${cellState.solution} from previous answer does not match $ch from this answer." } word.add(position.x to position.y) // Add clue number for the first letter of each answer. if (i == 0) { cellState.numbers.add("${answerIndex + 1}") } position = getNextPosition(position, middleRowLength) // Add borders after last letter of each answer (except the final answer). if (answerIndex < answers.size - 1 && i == answer.length - 1) { cellState.borderDirections.add( when (position.direction) { Direction.UP -> Puzzle.BorderDirection.TOP Direction.DOWN -> Puzzle.BorderDirection.BOTTOM Direction.RIGHT -> Puzzle.BorderDirection.RIGHT Direction.LEFT -> Puzzle.BorderDirection.LEFT } ) } } words.add(word) } val grid = (0 until middleRowLength).map { y -> (0 until middleRowLength).map { x -> val cell = gridMap[x to y] if (cell == null) { Puzzle.Cell(cellType = Puzzle.CellType.VOID) } else { require(cell.numbers.size <= 2) { "More than 2 entries start at position ($x, $y) which is not supported by JPZ files." } Puzzle.Cell( solution = cell.solution, number = if (cell.numbers.isNotEmpty()) cell.numbers[0] else "", topRightNumber = if (cell.numbers.size > 1) cell.numbers[1] else "", borderDirections = cell.borderDirections ) } } } val (puzzleClues, puzzleWords) = clues.mapIndexed { i, clue -> val puzzleClue = Puzzle.Clue(i + 1, "${i + 1}", clue) val puzzleWord = Puzzle.Word(i + 1, words[i].map { (x, y) -> Puzzle.Coordinate(x = x, y = y) }) puzzleClue to puzzleWord }.unzip() return Puzzle( title = title, creator = creator, copyright = copyright, description = description, grid = grid, clues = listOf(Puzzle.ClueList("Clues", puzzleClues)), words = puzzleWords, ) } private enum class Direction { UP, DOWN, RIGHT, LEFT } private data class Position(val x: Int, val y: Int, val direction: Direction) private data class CellState( var solution: String, var numbers: MutableList<String> = mutableListOf(), val borderDirections: MutableSet<Puzzle.BorderDirection> = mutableSetOf() ) companion object { private fun getNextPosition(position: Position, middleRowLength: Int): Position { when (position.direction) { Direction.UP -> { if (isPointInGrid(position.x, position.y - 1, middleRowLength)) { return position.copy(y = position.y - 1) } return position.copy(x = position.x + 1, direction = Direction.RIGHT) } Direction.DOWN -> { if (isPointInGrid(position.x, position.y + 1, middleRowLength)) { return position.copy(y = position.y + 1) } return position.copy(x = position.x - 1, direction = Direction.LEFT) } Direction.RIGHT -> { if (isPointInGrid(position.x + 1, position.y, middleRowLength)) { return position.copy(x = position.x + 1) } return position.copy(y = position.y + 1, direction = Direction.DOWN) } Direction.LEFT -> { if (isPointInGrid(position.x - 1, position.y, middleRowLength)) { return position.copy(x = position.x - 1) } return position.copy(y = position.y - 1, direction = Direction.UP) } } } private fun isPointInGrid(x: Int, y: Int, middleRowLength: Int): Boolean { return if (y < middleRowLength / 2) { // Must be in the center 2 * (y + 1) squares val range = 2 * (y + 1) x - ((middleRowLength - range) / 2) in 0 until range } else { // Must be in the center 2 * (middleRowLength - y) - 1 squares, shifted 1 right val range = 2 * (middleRowLength - y) - 1 x - ((middleRowLength - range) / 2) - 1 in 0 until range } } } }
5
Kotlin
5
19
c2dc23bafc7236ba076a63060e08e6dc134c8e24
6,505
kotwords
Apache License 2.0
src/main/kotlin/it/anesin/DefaultPackaging.kt
pieroanesin
540,757,888
false
{"Kotlin": 14170}
package it.anesin class DefaultPackaging(private val catalogue: Catalogue) : Packaging { override fun wrapFlowers(quantity: Int, type: FlowerType): List<Package> { val bundles = catalogue.bundlesOf(type).sortedBy { it.size } val bundleCounter = initBundleCounter(quantity, bundles) if (quantity < smallestBundle(bundles).size) throw Exception("$quantity ${type.description} is less than the smallest bundle") for (bundle in bundles) { for (numFlowers in 1..quantity) { if (numFlowers >= bundle.size) { val remainingFlowers = numFlowers - bundle.size if (isRemainingFlowersCompositionValid(bundleCounter, remainingFlowers)) { when { isNewFlowerCompositionSmaller(bundleCounter, numFlowers, remainingFlowers) -> bundleCounter[numFlowers] = newFlowerComposition(bundleCounter, remainingFlowers, bundle) isNewFlowerCompositionEqual(bundleCounter, numFlowers, remainingFlowers) && isNewFlowerCompositionCheaper(bundleCounter, numFlowers, remainingFlowers, bundle) -> bundleCounter[numFlowers] = newFlowerComposition(bundleCounter, remainingFlowers, bundle) } } } } } if (bundleCounter[quantity]!!.sumOf { it.bundleQuantity } >= Int.MAX_VALUE) throw Exception("$quantity ${type.description} can't be wrapped") return bundleCounter[quantity]!!.sortedByDescending { it.bundle.size }.filter { it.bundleQuantity > 0 } } private fun smallestBundle(bundles: List<Bundle>) = bundles.minBy { it.size } private fun initBundleCounter(quantity: Int, bundles: List<Bundle>): MutableMap<Int, List<Package>> { val bundleCounter = mutableMapOf<Int, List<Package>>() bundleCounter[0] = listOf(Package(0, smallestBundle(bundles))) for (i in 1..quantity) bundleCounter[i] = listOf(Package(Int.MAX_VALUE, smallestBundle(bundles))) return bundleCounter } private fun isRemainingFlowersCompositionValid(bundleCounter: MutableMap<Int, List<Package>>, remainingFlowers: Int) = bundleCounter[remainingFlowers]!!.sumOf { it.bundleQuantity } != Int.MAX_VALUE private fun isNewFlowerCompositionSmaller(bundleCounter: MutableMap<Int, List<Package>>, actualFlowers: Int, remainingFlowers: Int) = bundleCounter[actualFlowers]!!.sumOf { it.bundleQuantity } > bundleCounter[remainingFlowers]!!.sumOf { it.bundleQuantity } + 1 private fun isNewFlowerCompositionEqual(bundleCounter: MutableMap<Int, List<Package>>, actualFlowers: Int, remainingFlowers: Int) = bundleCounter[actualFlowers]!!.sumOf { it.bundleQuantity } == bundleCounter[remainingFlowers]!!.sumOf { it.bundleQuantity } + 1 private fun isNewFlowerCompositionCheaper(bundleCounter: MutableMap<Int, List<Package>>, numFlowers: Int, remainingFlowers: Int, bundle: Bundle) = bundleCounter[numFlowers]!!.sumOf { it.price() } > bundleCounter[remainingFlowers]!!.sumOf { it.price() } + bundle.price private fun newFlowerComposition(bundleCounter: MutableMap<Int, List<Package>>, remainingFlowers: Int, bundle: Bundle) = bundleCounter[remainingFlowers]!! .filterNot { it.bundle == bundle } .plus(Package((bundleCounter[remainingFlowers]!!.singleOrNull { it.bundle == bundle }?.bundleQuantity ?: 0) + 1, bundle)) }
0
Kotlin
0
0
48d7f000126e201092e7278bc7d9c52fd34bae08
3,281
flower-shop
MIT License
src/academy/learnprogramming/challenges/KotlinOOBicycles.kt
bladefistx2
430,293,814
false
{"Kotlin": 19902, "Java": 1795}
package academy.learnprogramming.challenges fun main(args: Array<String>) { val mtb = KotlinMountainBike(33, 1000, 25, 7) mtb.printDescription() val bike = KotlinBicycle(1, 1) bike.printDescription() val bike2 = KotlinMountainBike("green",1, 2, 1) bike2.printDescription() println("===") println(KotlinMountainBike.availableColors) println("===") KotlinMountainBike.availableColors.forEach(::println) } open class KotlinBicycle(var cadence: Int, var speed: Int, var gear: Int = 1, val type: String = "") { fun applyBrake(decrement: Int) { speed -= decrement } fun speedUp(increment: Int) { speed += increment } open fun printDescription() = println(""" The $type bike is in gear $gear with a cadence of $cadence travelling at the speed of $speed. """.trimIndent()) } class KotlinMountainBike(var seatHeight: Int, cadence: Int, speed: Int, gear: Int = 1): KotlinBicycle(cadence, speed, gear, "mountain") { constructor(color: String, seatHeight: Int, cadence: Int, speed: Int, gear: Int = 1): this(seatHeight, cadence, speed, gear) { println("mtb color is $color") } override fun printDescription(){ super.printDescription() println("The seat hight is $seatHeight mm.") } companion object { val availableColors: List<String> = listOf("blue", "red", "green", "black") } } class KotlinRoadBike(val tireWidth: Int, cadence: Int, speed: Int, gear: Int): KotlinBicycle(cadence, speed, gear, "road") { override fun printDescription(){ super.printDescription() println("The tire width is $tireWidth mm.") } }
0
Kotlin
0
0
a8349446e202c187a0860614acc503fb412967ea
1,761
learn-kotlin
Apache License 2.0
solutions/src/solutions/y20/day 7.kt
Kroppeb
225,582,260
false
null
@file:Suppress("PackageDirectoryMismatch") package solutions.y20.d07 import helpers.* import collections.* import grid.* import graph.BFS import itertools.count import kotlinx.coroutines.* import kotlin.math.pow val xxxxx = Clock(3, 6); private fun part1(data: Data) { val mm = data.map { val (a, b) = it.split(" bags contain ") val c = b.split(", ").map { val u = it.split(" bag")[0].split(' ') u.subList(1, u.size).joinToString(" ") } a to c }.toMap() val mg = mutableMapOf("shiny gold" to 1, "other" to 0) fun find(i: String): Int { return if (i in mg) { mg[i]!! } else { val p = mm[i]!!.sumBy { find(it) } mg[i] = p p } } for (i in mm) { find(i.key) } println(mg.count { it.value > 0 } - 1) } private fun part2(data: Data) { val mm = data.map { val (a, b) = it.split(" bags contain ") val c = b.split(", ").map { val u = it.split(" bag")[0].split(' ') (u[0].toIntOrNull()?: 0 ) to u.subList(1, u.size).joinToString(" ") } a to c }.toMap() val mg = mutableMapOf("other" to 0) fun find(i: String): Int { return if (i in mg) { mg[i]!! } else { val p = mm[i]!!.sumBy { it.first * find(it.second) } + 1 mg[i] = p p; } } for (i in mm) { find(i.key) } println(find("shiny gold") - 1) } private typealias Data = Lines fun main() { val data: Data = getLines(2020_07) part1(data) part2(data) }
0
Kotlin
0
1
744b02b4acd5c6799654be998a98c9baeaa25a79
1,388
AdventOfCodeSolutions
MIT License
src/main/kotlin/aoc23/Day10.kt
tahlers
725,424,936
false
{"Kotlin": 65626}
package aoc23 import aoc23.Day10.PipeType.HORIZONTAL import aoc23.Day10.PipeType.NORTH_EAST import aoc23.Day10.PipeType.NORTH_WEST import aoc23.Day10.PipeType.SOUTH_EAST import aoc23.Day10.PipeType.SOUTH_WEST import aoc23.Day10.PipeType.START import aoc23.Day10.PipeType.VERTICAL object Day10 { enum class PipeType { VERTICAL, HORIZONTAL, NORTH_EAST, NORTH_WEST, SOUTH_WEST, SOUTH_EAST, START } data class Pos(val x: Int, val y: Int) { fun isLeft(other: Pos) = other.x < x && other.y == this.y } data class Pipe(val type: PipeType, val pos: Pos) { fun nextStep(previousPipe: Pipe?, field: Field): Pipe { val possibilitiesOnField = (possibleConnectionPipes() - previousPipe).filter { field.pipes[it!!.pos] == it } return if (possibilitiesOnField.size == 1 || type == START) { possibilitiesOnField.first()!! } else { throw IllegalStateException("Not on Pipe Loop!") } } private fun possibleConnectionPipes(): Set<Pipe> { val northPos = Pos(pos.x, pos.y - 1) val southPos = Pos(pos.x, pos.y + 1) val westPos = Pos(pos.x - 1, pos.y) val eastPos = Pos(pos.x + 1, pos.y) val northConnections = genPipe(northPos, VERTICAL, SOUTH_WEST, SOUTH_EAST) val southConnections = genPipe(southPos, VERTICAL, NORTH_WEST, NORTH_EAST) val eastConnections = genPipe(eastPos, HORIZONTAL, NORTH_WEST, SOUTH_WEST) val westConnections = genPipe(westPos, HORIZONTAL, NORTH_EAST, SOUTH_EAST) return when (type) { VERTICAL -> northConnections + southConnections HORIZONTAL -> eastConnections + westConnections NORTH_EAST -> northConnections + eastConnections NORTH_WEST -> northConnections + westConnections SOUTH_WEST -> southConnections + westConnections SOUTH_EAST -> southConnections + eastConnections START -> northConnections + southConnections + eastConnections + westConnections } } private fun genPipe(genPos: Pos, vararg types: PipeType) = (types.map { Pipe(it, genPos) } + Pipe(START, genPos)).toSet() } data class Field(val startPos: Pos, val pipes: Map<Pos, Pipe>) private val northTypes = setOf(VERTICAL, NORTH_EAST, NORTH_WEST) fun calculateStepCount(input: String): Int { val field = parseInputToField(input) val startPipe = field.pipes[field.startPos]!! val firstStep = startPipe.nextStep(null, field) val path = generateSequence(startPipe to firstStep) { (prev, current) -> if (current.type == START) { null } else { current to current.nextStep(prev, field) } } return (path.toList().size / 2) } fun calculateEnclosedTiles(input: String): Int { val field = parseInputToField(input) val startPipe = field.pipes[field.startPos]!! val firstStep = startPipe.nextStep(null, field) val pathSet = generateSequence(startPipe to firstStep) { (prev, current) -> if (current.type == START) { null } else { current to current.nextStep(prev, field) } }.map { it.second }.associateBy { it.pos } val maxX = input.lines().first().length val maxY = input.trim().lines().size val innerPositions = (0..<maxY).flatMap { y -> (0..<maxX).mapNotNull { x -> val current = Pos(x, y) if (current in pathSet) { null } else { val leftCount = pathSet.filter { current.isLeft(it.key) && it.value.type in northTypes }.size val isInner = (leftCount % 2) == 1 if (isInner) current else null } } } return innerPositions.size } private fun parseInputToField(input: String): Field { // prettyPrint(input) val lines = input.trim().lines() val pipes = lines.flatMapIndexed { y, line -> line.mapIndexedNotNull { x, c -> when (c) { '|' -> Pipe(VERTICAL, Pos(x, y)) '-' -> Pipe(HORIZONTAL, Pos(x, y)) 'L' -> Pipe(NORTH_EAST, Pos(x, y)) 'J' -> Pipe(NORTH_WEST, Pos(x, y)) '7' -> Pipe(SOUTH_WEST, Pos(x, y)) 'F' -> Pipe(SOUTH_EAST, Pos(x, y)) 'S' -> Pipe(START, Pos(x, y)) else -> null } } } val pipeMap = pipes.associateBy { it.pos } val startPos = pipeMap.values.first { it.type == START }.pos return Field(startPos, pipeMap) } private fun prettyPrint(input: String) { val transformed = input .replace('-', '─') .replace('|', '│') .replace('F', '┌') .replace('7', '┐') .replace('L', '└') .replace('J', '┘') .replace('.', ' ') println(transformed) } }
0
Kotlin
0
0
0cd9676a7d1fec01858ede1ab0adf254d17380b0
5,275
advent-of-code-23
Apache License 2.0
src/main/java/tarehart/rlbot/math/Ray2.kt
tarehart
101,009,961
true
{"Kotlin": 781564, "Python": 29120, "Batchfile": 324}
package tarehart.rlbot.math import tarehart.rlbot.input.CarData import tarehart.rlbot.math.vector.Vector2 import kotlin.math.pow import kotlin.math.sqrt open class Ray2(val position: Vector2, direction: Vector2) { val direction = direction.normalized() /** * Taken from https://math.stackexchange.com/a/311956/550722 */ fun firstCircleIntersection(circle: Circle): Vector2? { val a = direction.magnitudeSquared() val b = 2 * direction.x * (position.x - circle.center.x) + 2 * direction.y * (position.y - circle.center.y) val c = square(position.x - circle.center.x) + square(position.y - circle.center.y) - square(circle.radius) val discrim = b * b - 4 * a * c if (discrim < 0) { return null } val t = 2 * c / (-b + sqrt(discrim)) if (t < 0) { return null } return position + direction * t } private fun square(n: Float): Float { return n * n } companion object { /** * https://stackoverflow.com/a/2931703/280852 * * Returns the intersection point if it exists, followed by the distance of that intersection * along ray A. */ fun getIntersection(a: Ray2, b: Ray2): Pair<Vector2?, Float> { val dx = b.position.x - a.position.x val dy = b.position.y - a.position.y val det = b.direction.x * a.direction.y - b.direction.y * a.direction.x val u = (dy * b.direction.x - dx * b.direction.y) / det val v = (dy * a.direction.x - dx * a.direction.y) / det if (u < 0 || v < 0) { return Pair(null, u) } return Pair(a.position + a.direction * u, u) } fun fromCar(car: CarData): Ray2 { return Ray2(car.position.flatten(), car.orientation.noseVector.flatten()) } } }
0
Kotlin
7
10
8a5ba0ba751235e775d383c9796ee8fa966030b9
1,926
ReliefBot
MIT License
src/main/kotlin/days/Day9.kt
andilau
429,557,457
false
{"Kotlin": 103829}
package days @AdventOfCodePuzzle( name = "All in a Single Night", url = "https://adventofcode.com/2015/day/9", date = Date(day = 9, year = 2015) ) class Day9(input: List<String>) : Puzzle { private val legDistances: Map<Pair<Location, Location>, Int> = input.parseDistances() internal val totals: List<Int> = legDistances .keys.flatMap { it.toList() }.toSet() .permutations() .map { route -> route.totalDistance(legDistances) } override fun partOne(): Int = totals.minOrNull() ?: error("No distances") override fun partTwo(): Int = totals.maxOrNull() ?: error("No distances") private fun List<String>.parseDistances() = map { line -> line.split(" = ", limit = 2) } .associate { (fromTo, distance) -> fromTo .split(" to ") .let { Location(it.first()) to Location(it.last()) } to distance.toInt() } private fun Iterable<Location>.totalDistance(legDistances: Map<Pair<Location, Location>, Int>) = zipWithNext().fold(0) { total, leg -> total + (legDistances[leg] ?: legDistances[leg.let { it.second to it.first }] ?: error("Distance not found: $leg")) } data class Location(val name: String) }
0
Kotlin
0
0
55932fb63d6a13a1aa8c8df127593d38b760a34c
1,344
advent-of-code-2015
Creative Commons Zero v1.0 Universal
src/Day06.kt
Vlisie
572,110,977
false
{"Kotlin": 31465}
import java.io.File fun main() { fun uniqueCharacters(str: String): Boolean{ val chArray = str.toCharArray() chArray.sort() for (i in 0..chArray.size - 2) { if (chArray[i] == chArray[i + 1]) return false else continue } return true } fun part1(file: File): Int { var charOfAppearance = 1 var previous3Chars = "" file.readText() .map { if(!previous3Chars.contains(it) && charOfAppearance > 3 && uniqueCharacters(previous3Chars)){ return charOfAppearance }else { if(charOfAppearance > 3) previous3Chars = previous3Chars.drop(1) previous3Chars += it charOfAppearance++ } } return charOfAppearance } fun part2(file: File): Int { var charOfAppearance = 1 var previous13Chars = "" file.readText() .map { if(!previous13Chars.contains(it) && charOfAppearance > 13 && uniqueCharacters(previous13Chars)){ return charOfAppearance }else { if(charOfAppearance > 13) previous13Chars = previous13Chars.drop(1) previous13Chars += it charOfAppearance++ } } return charOfAppearance } // test if implementation meets criteria from the description, like: val testInput = File("src/input", "testInput.txt") check(part1(testInput) == 7) check(part2(testInput) == 19) val input = File("src/input", "input6.txt") println("Part 1 -----------") println(part1(input)) println("Part 2 -----------") println(part2(input)) }
0
Kotlin
0
0
b5de21ed7ab063067703e4adebac9c98920dd51e
1,783
AoC2022
Apache License 2.0
src/Year2021Day02.kt
zhangt2333
575,260,256
false
{"Kotlin": 34993}
import kotlin.math.abs internal data class SubmarinePosition( var x: Int, var y: Int, var aim: Int, ) fun main() { fun parse(lines: List<String>) = lines.map { val (direction, distance) = it.split(" ") direction to distance.toInt() } fun part1(lines: List<String>): Int { return parse(lines) .fold(Point(0, 0)) { p, (direction, distance) -> when (direction) { "forward" -> p.x += distance "up" -> p.y += distance "down" -> p.y -= distance } p }.let { abs(it.x * it.y) } } fun part2(lines: List<String>): Int { return parse(lines) .fold(SubmarinePosition(0, 0, 0)) { p, (direction, distance) -> when (direction) { "forward" -> { p.y += p.aim * distance p.x += distance } "down" -> p.aim += distance "up" -> p.aim -= distance } p }.let { abs(it.x * it.y) } } val testLines = readLines(true) assertEquals(150, part1(testLines)) assertEquals(900, part2(testLines)) val lines = readLines() println(part1(lines)) println(part2(lines)) }
0
Kotlin
0
0
cdba887c4df3a63c224d5a80073bcad12786ac71
1,360
aoc-2022-in-kotlin
Apache License 2.0
src/main/aoc2020/Day17.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2020 class Day17(val input: List<String>) { data class Point(val x: Int, val y: Int, val z: Int, val w: Int, private val dimensions: Int) { // We're accessing neighbours frequently, only calculate the neighbours once and return // a cached value if calling this later. In this case, much (~30%) faster than a by lazy property // https://stackoverflow.com/questions/65543747/why-does-using-by-lazy-make-my-kotlin-code-slower/ fun getNeighbours(): Set<Point> { if (!this::nb.isInitialized) { nb = buildSet { for (dx in -1..1) { for (dy in -1..1) { for (dz in -1..1) { for (dw in if (dimensions == 4) -1..1 else 0..0) { add(Point(x + dx, y + dy, z + dz, w + dw, dimensions)) } } } } remove(this@Point) } } return nb } private lateinit var nb: Set<Point> } private fun parseInput(dimensions: Int): Map<Point, Char> { return input.indices.flatMap { y -> input[0].indices.map { x -> Point(x, y, 0, 0, dimensions) to input[y][x] } }.toMap() } private fun runGame(space: Map<Point, Char>): Map<Point, Char> { var current = space repeat(6) { val next = current.toMutableMap() val points = next.keys.flatMap { it.getNeighbours() }.toSet() // any neighbour can be transformed for (point in points) { val activeNeighbours = point.getNeighbours().count { current[it] == '#' } when (current.getOrDefault(point, '.')) { '#' -> if (activeNeighbours !in 2..3) next[point] = '.' '.' -> if (activeNeighbours == 3) next[point] = '#' } } current = next.toMap() } return current } fun solvePart1(): Int { return runGame(parseInput(3)).values.count { it == '#' } } fun solvePart2(): Int { return runGame(parseInput(4)).values.count { it == '#' } } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
2,289
aoc
MIT License
src/main/kotlin/com/leetcode/P93.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package com.leetcode // https://github.com/antop-dev/algorithm/issues/331 class P93 { val answer = mutableListOf<String>() fun restoreIpAddresses(s: String): List<String> { if (s.length !in 4..12) return listOf() dfs(s, 0, 0, StringBuffer()) return answer } /** * @param s 원본 문자열 * @param i 문자열의 현재 인덱스 * @param dots 사용된 쩜(".")의 개수 * @param ip 만들어가고 있는 문자열 */ fun dfs(s: String, i: Int, dots: Int, ip: StringBuffer) { // 쩜을 다 사용했지만 문자열을 다 소비 못한 경우 if (dots > 3 && i < s.length) { return } if (i == s.length && dots > 3) { // 완성 answer += ip.toString() return } val prevLength = ip.length // 백트래킹할 이전 문자열 길이 if (i > 0) ip.append(".") // 쩜이 한번 사용됨 var num = 0 // 한자리, 두자리, 세자리 계산 val maxIndex = minOf(s.lastIndex - (3 - dots), i + 2) for (j in i..maxIndex) { val c = s[j] // IP는 0 ~ 225만 허용된다. num = (num * 10) + (c - '0') if (num > 255) break ip.append(c) dfs(s, j + 1, dots + 1, ip) // IP의 첫자리가 0이면 두세번째 자리는 패스 if (num == 0) break } // 백트래킹 ip.setLength(prevLength) } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
1,513
algorithm
MIT License
src/Day21.kt
EdoFanuel
575,561,680
false
{"Kotlin": 80963}
import java.util.* class Day21 { data class Monkey(var value: Long? = null, val operation: Char?, val leftChild: String?, val rightChild: String?) private val leafPattern = "(\\w{4}): (\\d+)" private val trunkPattern = "(\\w{4}): (\\w{4}) ([+\\-\\/\\*]) (\\w{4})" fun parseLine(line: String): Pair<String, Monkey> { val leafGroup = line.match(leafPattern)?.groupValues val trunkGroup = line.match(trunkPattern)?.groupValues if (leafGroup != null) { return leafGroup[1] to Monkey(leafGroup[2].toLong(), null, null, null) } if (trunkGroup != null) { return trunkGroup[1] to Monkey(null, trunkGroup[3][0], trunkGroup[2], trunkGroup[4]) } throw UnknownFormatConversionException("Cannot parse $line") } fun evalP1(monkey: Monkey, group: Map<String, Monkey>): Long { if (monkey.value == null) { monkey.value = when (monkey.operation) { '+' -> evalP1(group[monkey.leftChild!!]!!, group) + evalP1(group[monkey.rightChild!!]!!, group) '-' -> evalP1(group[monkey.leftChild!!]!!, group) - evalP1(group[monkey.rightChild!!]!!, group) '*' -> evalP1(group[monkey.leftChild!!]!!, group) * evalP1(group[monkey.rightChild!!]!!, group) '/' -> evalP1(group[monkey.leftChild!!]!!, group) / evalP1(group[monkey.rightChild!!]!!, group) else -> throw UnknownFormatConversionException("Cannot recognize operand ${monkey.operation}") } } return monkey.value!! } fun evalP2(key: String, group: Map<String, Monkey>): List<String> { if (key == "humn") return listOf("n") val monkey = group[key]!! if (monkey.value != null) return listOf(monkey.value.toString()) val result = mutableListOf<String>() result += evalP2(monkey.leftChild!!, group) result += evalP2(monkey.rightChild!!, group) result += monkey.operation!!.toString() return result } fun evalRPN(tokens: List<String>): Long? { val stack = Stack<Long>() for (token in tokens) { when(token) { "n" -> return null in listOf("+", "-", "*", "/") -> { val right = stack.pop() val left = stack.pop() val result = when(token) { "+" -> left + right "-" -> left - right "*" -> left * right "/" -> left / right else -> throw IllegalArgumentException("Shouldn't be possible to receive $token here.") } stack.push(result) } else -> stack.push(token.toLong()) } } return stack.pop() } fun solveEquation(key: String, graph: Map<String, Monkey>, target: Long): Long { if (key == "humn") return target val root = graph[key]!! val left = evalRPN(evalP2(root.leftChild!!, graph)) val right = evalRPN(evalP2(root.rightChild!!, graph)) return when (root.operation) { '+' -> solveEquation( if (left == null) root.leftChild else root.rightChild, graph, target - (left ?: right)!! ) '*' -> solveEquation( if (left == null) root.leftChild else root.rightChild, graph, target / (left ?: right)!! ) '-' -> solveEquation( if (left == null) root.leftChild else root.rightChild, graph, if (left == null) target + right!! else left - target ) '/' -> return solveEquation( if (left == null) root.leftChild else root.rightChild, graph, if (left == null) target * right!! else left / target ) else -> throw IllegalStateException("Unrecognized operation: ${root.operation}") } } } fun main() { val day = Day21() fun part1(input: List<String>): Long { val monkeys = input.associate { day.parseLine(it) } return day.evalP1(monkeys["root"]!!, monkeys) } fun part2(input: List<String>): Long { val monkeys = input.associate { day.parseLine(it) }.filter { it.key != "humn" } val root = monkeys["root"]!! val left = day.evalRPN(day.evalP2(root.leftChild!!, monkeys)) val right = day.evalRPN(day.evalP2(root.rightChild!!, monkeys)) val target = left ?: right return day.solveEquation( if (left == null) root.leftChild else root.rightChild, monkeys, target!! ) } val test = readInput("Day21_test") println("=== Part 1 (test) ===") println(part1(test)) println("=== Part 2 (test) ===") println(part2(test)) val input = readInput("Day21") println("=== Part 1 (puzzle) ===") println(part1(input)) println("=== Part 2 (puzzle) ===") println(part2(input)) }
0
Kotlin
0
0
46a776181e5c9ade0b5e88aa3c918f29b1659b4c
5,163
Advent-Of-Code-2022
Apache License 2.0
kotlin/src/com/s13g/aoc/aoc2021/Day12.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2021 import com.s13g.aoc.Result import com.s13g.aoc.Solver /** * --- Day 12: Passage Pathing --- * https://adventofcode.com/2021/day/12 */ class Day12 : Solver { override fun solve(lines: List<String>): Result { val connections = lines.map { it.split('-') }.map { Pair(it[0], it[1]) } val system = mutableMapOf<String, Node>() for (conn in connections) { if (!system.containsKey(conn.first)) system[conn.first] = Node(conn.first) if (!system.containsKey(conn.second)) system[conn.second] = Node(conn.second) system[conn.first]!!.connections.add(system[conn.second]!!) system[conn.second]!!.connections.add(system[conn.first]!!) } val partA = countRoutes(system["start"]!!, setOf(), false) val partB = countRoutes(system["start"]!!, setOf(), true) return Result("$partA", "$partB") } private fun countRoutes(from: Node, noGos: Set<String>, smallException: Boolean): Int { if (noGos.contains(from.id) && (!smallException || from.id == "start")) return 0 if (from.id == "end") return 1 val newSmallException = if (noGos.contains(from.id)) false else smallException val newNoGos = noGos.toMutableSet() if (from.small) { newNoGos.add(from.id) } return from.connections.map { countRoutes(it, newNoGos, newSmallException) }.sum() } private data class Node(val id: String) { val small: Boolean = id[0].isLowerCase() val connections: MutableSet<Node> = mutableSetOf<Node>() } }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
1,507
euler
Apache License 2.0
src/iii_conventions/MyDate.kt
trueddd
166,991,808
true
{"Kotlin": 73247, "Java": 4952}
package iii_conventions data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int) : Comparable<MyDate>{ override fun compareTo(other: MyDate): Int { return when{ this.year != other.year -> this.year - other.year this.month != other.month -> this.month - other.month else -> this.dayOfMonth - other.dayOfMonth } } } operator fun MyDate.rangeTo(other: MyDate): DateRange { return DateRange(this, other) } enum class TimeInterval { DAY, WEEK, YEAR } class DateRange(override val start: MyDate, override val endInclusive: MyDate) : ClosedRange<MyDate>, Iterable<MyDate> { override fun contains(value: MyDate): Boolean { return this.start <= value && value <= this.endInclusive } override fun iterator(): Iterator<MyDate> = DateIterator(this) } class DateIterator(val dateRange: DateRange) : Iterator<MyDate> { var current: MyDate = dateRange.start override fun next(): MyDate { val result = current current = current.nextDay() return result } override fun hasNext(): Boolean = current <= dateRange.endInclusive } class RepeatedTimeIntervals(val timeInterval: TimeInterval, val number: Int) operator fun TimeInterval.times(number: Int) = RepeatedTimeIntervals(this, number) operator fun MyDate.plus(value: TimeInterval) = addTimeIntervals(value, 1) operator fun MyDate.plus(value: RepeatedTimeIntervals) = addTimeIntervals(value.timeInterval, value.number)
0
Kotlin
0
0
9b73d9cf2ddccdd04d083e797c900a2f8a7c3814
1,509
kotlin-koans
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/SortedListToBST.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 /** * */ fun interface SortedListToBST { operator fun invoke(head: ListNode?): TreeNode? } /** * Approach 1: Recursion */ class SortedListToBSTRecursion : SortedListToBST { override operator fun invoke(head: ListNode?): TreeNode? { // If the head doesn't exist, then the linked list is empty if (head == null) { return null } // Find the middle element for the list. // Find the middle element for the list. val mid = findMiddleElement(head) // The mid becomes the root of the BST. val node = TreeNode(mid?.value!!) // Base case when there is just one element in the linked list // Base case when there is just one element in the linked list if (head === mid) { return node } // Recursively form balanced BSTs using the left and right halves of the original list. // Recursively form balanced BSTs using the left and right halves of the original list. node.left = this.invoke(head) node.right = this.invoke(mid.next) return node } private fun findMiddleElement(head: ListNode): ListNode? { // The pointer used to disconnect the left half from the mid-node. var prevPtr: ListNode? = null var slowPtr: ListNode? = head var fastPtr: ListNode? = head // Iterate until fastPr doesn't reach the end of the linked list. while (fastPtr?.next != null) { prevPtr = slowPtr slowPtr = slowPtr!!.next fastPtr = fastPtr.next!!.next } // Handling the case when slowPtr was equal to head. if (prevPtr != null) { prevPtr.next = null } return slowPtr } } /** * Approach 2: Recursion + Conversion to Array */ class SortedListToBSTArray : SortedListToBST { private val values: MutableList<Int> = ArrayList() override operator fun invoke(head: ListNode?): TreeNode { this.mapListToValues(head) // Convert the array to return convertListToBST(0, this.values.size - 1)!! } private fun mapListToValues(head: ListNode?) { var node: ListNode? = head while (node != null) { values.add(node.value) node = node.next } } private fun convertListToBST(left: Int, right: Int): TreeNode? { // Invalid case if (left > right) { return null } // Middle element forms the root. val mid = (left + right) / 2 val node = TreeNode(values[mid]) // Base case for when there is only one element left in the array if (left == right) { return node } // Recursively form BST on the two halves node.left = convertListToBST(left, mid - 1) node.right = convertListToBST(mid + 1, right) return node } } /** * Approach 3: Inorder Simulation */ class SortedListToBSTInorder : SortedListToBST { private var head: ListNode? = null override operator fun invoke(head: ListNode?): TreeNode? { // Get the size of the linked list first val size = findSize(head) this.head = head // Form the BST now that we know the size return convertListToBST(0, size - 1) } private fun convertListToBST(l: Int, r: Int): TreeNode? { // Invalid case if (l > r) { return null } val mid = (l + r) / 2 // First step of simulated inorder traversal. Recursively form // the left half val left = convertListToBST(l, mid - 1) // Once left half is traversed, process the current node val node = TreeNode(head?.value!!) node.left = left // Maintain the invariance mentioned in the algorithm head = head!!.next // Recurse on the right hand side and form BST out of them node.right = convertListToBST(mid + 1, r) return node } private fun findSize(head: ListNode?): Int { var ptr: ListNode? = head var c = 0 while (ptr != null) { ptr = ptr.next c += 1 } return c } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
4,865
kotlab
Apache License 2.0
LeetCode2020April/week3/src/test/kotlin/net/twisterrob/challenges/leetcode2020april/week3/search_rotated/SolutionTest.kt
TWiStErRob
136,539,340
false
{"Kotlin": 104880, "Java": 11319}
package net.twisterrob.challenges.leetcode2020april.week3.search_rotated import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.DynamicTest import org.junit.jupiter.api.DynamicTest.dynamicTest import org.junit.jupiter.api.TestFactory class SolutionTest { private fun solutionTest(target: Int, input: IntArray, expectedResult: Int): DynamicTest = dynamicTest("${target} in ${input.toList()} is at position ${expectedResult}") { testSolution(target, input, expectedResult) } private fun testSolution(target: Int, input: IntArray, expectedResult: Int) { val result = Solution().search(input, target) assertEquals(expectedResult, result) } @TestFactory fun `example 1`() = solutionTest(0, intArrayOf(4, 5, 6, 7, 0, 1, 2), 4) @TestFactory fun `example 2`() = solutionTest(3, intArrayOf(4, 5, 6, 7, 0, 1, 2), -1) @TestFactory fun `old tests`() = arrayOf( solutionTest(0, intArrayOf(0), 0), solutionTest(0, intArrayOf(0, 1), 0), solutionTest(0, intArrayOf(1, 0), 1), solutionTest(0, intArrayOf(0, 1, 2), 0), solutionTest(0, intArrayOf(2, 0, 1), 1), solutionTest(0, intArrayOf(1, 2, 0), 2), solutionTest(0, intArrayOf(0, 1, 2, 4, 5, 6), 0), solutionTest(0, intArrayOf(6, 0, 1, 2, 4, 5), 1), solutionTest(0, intArrayOf(5, 6, 0, 1, 2, 4), 2), solutionTest(0, intArrayOf(4, 5, 6, 0, 1, 2), 3), solutionTest(0, intArrayOf(2, 4, 5, 6, 0, 1), 4), solutionTest(0, intArrayOf(1, 2, 4, 5, 6, 0), 5), solutionTest(0, intArrayOf(0, 1, 2, 4, 5, 6, 7), 0), solutionTest(0, intArrayOf(7, 0, 1, 2, 4, 5, 6), 1), solutionTest(0, intArrayOf(6, 7, 0, 1, 2, 4, 5), 2), solutionTest(0, intArrayOf(5, 6, 7, 0, 1, 2, 4), 3), solutionTest(0, intArrayOf(4, 5, 6, 7, 0, 1, 2), 4), solutionTest(0, intArrayOf(2, 4, 5, 6, 7, 0, 1), 5), solutionTest(0, intArrayOf(1, 2, 4, 5, 6, 7, 0), 6), ) }
1
Kotlin
1
2
5cf062322ddecd72d29f7682c3a104d687bd5cfc
1,853
TWiStErRob
The Unlicense
src/main/kotlin/com/psmay/exp/advent/y2021/day18/snailfish/Atom.kt
psmay
434,705,473
false
{"Kotlin": 242220}
package com.psmay.exp.advent.y2021.day18.snailfish import com.psmay.exp.advent.y2021.util.mapIterator import com.psmay.exp.advent.y2021.util.splice import com.psmay.exp.advent.y2021.util.withPeeking internal sealed class Atom { open val depthChange: Int get() = 0 object DescendAtom : Atom() { override val depthChange get() = 1 } object AscendAtom : Atom() { override val depthChange get() = -1 } data class FigureAtom(val figure: Element.Figure) : Atom() } internal fun Element.getAtoms(): Sequence<Atom> = when (this) { is Element.Figure -> sequenceOf(Atom.FigureAtom(this)) is Element.Doublet -> sequence { val doublet = this@getAtoms yield(Atom.DescendAtom) yieldAll(doublet.x.getAtoms()) yieldAll(doublet.y.getAtoms()) yield(Atom.AscendAtom) } } internal fun Sequence<Atom>.getElements(): Sequence<Element> { return mapIterator { it.withPeeking().pullZeroOrMoreElements().iterator() } } private fun Sequence<Atom>.indexOfExplodablePair(): Int { data class WindowResult(val depthAfterFirst: Int, val windowIsExplodable: Boolean) val windowResults = windowed(4) .runningFold(WindowResult(0, false)) { (depth, _), window -> val (a, b, c, d) = window val depthAfterFirst = depth + a.depthChange val windowIsExplodable = depthAfterFirst >= 5 && a is Atom.DescendAtom && b is Atom.FigureAtom && c is Atom.FigureAtom && d is Atom.AscendAtom WindowResult(depthAfterFirst, windowIsExplodable) } .drop(1) // Skip the synthetic first result return windowResults.indexOfFirst { it.windowIsExplodable } } private fun Sequence<Atom>.indexOfSplittableFigure(): Int { return indexOfFirst { it is Atom.FigureAtom && it.figure.value >= 10 } } private fun MutableList<Atom>.explode(): Boolean { val foundIndexOfPair = this.asSequence().indexOfExplodablePair() if (foundIndexOfPair < 0) { return false } // Known indices val indicesOfPair = foundIndexOfPair..foundIndexOfPair + 3 val indexOfXAtom = indicesOfPair.first + 1 val indexOfYAtom = indicesOfPair.first + 2 val indicesOfWAtom = scanForFigureAtom((indicesOfPair.first - 1 downTo 0), indicesOfPair.first) val indicesOfZAtom = scanForFigureAtom((indicesOfPair.last + 1..lastIndex), indicesOfPair.last + 1) val wAtoms = this.slice(indicesOfWAtom).map { it as Atom.FigureAtom } val xAtom = this[indexOfXAtom] as Atom.FigureAtom val yAtom = this[indexOfYAtom] as Atom.FigureAtom val zAtoms = this.slice(indicesOfZAtom).map { it as Atom.FigureAtom } val replacementWAtoms = wAtoms.map { wAtom -> sumOfFigureAtoms(wAtom, xAtom) } val replacementZAtoms = zAtoms.map { zAtom -> sumOfFigureAtoms(yAtom, zAtom) } val replacementAtomForPair = Atom.FigureAtom(Element.Figure(0)) this.splice(indicesOfWAtom, replacementWAtoms) this.splice(indicesOfZAtom, replacementZAtoms) this.splice(indicesOfPair, listOf(replacementAtomForPair)) return true } private fun sumOfFigureAtoms(a: Atom.FigureAtom, b: Atom.FigureAtom): Atom.FigureAtom { return Atom.FigureAtom(Element.Figure(a.figure.value + b.figure.value)) } private fun splitFigureAtom(atom: Atom.FigureAtom): List<Atom> { val value = atom.figure.value val halfRoundedDown = value / 2 val halfRoundedUp = value - halfRoundedDown return listOf( Atom.DescendAtom, Atom.FigureAtom(Element.Figure(halfRoundedDown)), Atom.FigureAtom(Element.Figure(halfRoundedUp)), Atom.AscendAtom, ) } private fun MutableList<Atom>.scanForFigureAtom(indicesToScan: Iterable<Int>, emptyIndexPosition: Int): IntRange { val foundIndex = indicesToScan.firstOrNull { index -> this[index] is Atom.FigureAtom } return if (foundIndex == null) // result is an empty range emptyIndexPosition until emptyIndexPosition else // result is a single-element range foundIndex..foundIndex } private fun MutableList<Atom>.split(): Boolean { val index = this.asSequence().indexOfSplittableFigure() if (index < 0) { return false } val indicesToReplace = index..index val splitResult = splitFigureAtom(this[index] as Atom.FigureAtom) this.splice(indicesToReplace, splitResult) return true } private fun MutableList<Atom>.snailReduceOnce() = this.explode() || this.split() internal fun MutableList<Atom>.snailReduce(): Boolean { val changed = this.snailReduceOnce() if (changed) { while (this.snailReduceOnce()) { // continue } } return changed }
0
Kotlin
0
0
c7ca54612ec117d42ba6cf733c4c8fe60689d3a8
4,729
advent-2021-kotlin
Creative Commons Zero v1.0 Universal
Algorithms/30 - Substring with Concatenation of All Words/src/Solution.kt
mobeigi
202,966,767
false
null
class Solution { fun findSubstring(s: String, words: Array<String>): List<Int> { if (words.isEmpty()) { return emptyList() } // Find useful lengths we will be working with val wordLength = words.first().length val concatenatedSubstringLength = wordLength * words.size // Early exit optimization for impossible case if (s.length < concatenatedSubstringLength) { return emptyList() } val solutionIndices = mutableListOf<Int>() // Create frequency map for our words val wordFrequency = HashMap<String, Int>() words.forEach { word -> wordFrequency[word] = wordFrequency.getOrDefault(word, 0) + 1 } // We will iterate over all possible substrings that can possibly be valid solutions val lastPossibleStartingIndex = s.length - concatenatedSubstringLength for (i in 0 .. lastPossibleStartingIndex) { val subString = s.substring(i, i+concatenatedSubstringLength) val currentFrequency = HashMap<String,Int>() run earlyExit@{ // Count number of matching words by building a frequency map for this substring var matchedWordCount = 0 subString.chunkedSequence(wordLength).forEach { chunkedWord -> if (!wordFrequency.contains(chunkedWord)) { return@earlyExit } currentFrequency[chunkedWord] = currentFrequency.getOrDefault(chunkedWord, 0) + 1 if (currentFrequency[chunkedWord]!! > wordFrequency[chunkedWord]!!) { return@earlyExit } ++matchedWordCount } if (matchedWordCount == words.size) { solutionIndices.add(i) } } } return solutionIndices } }
0
Kotlin
0
0
e5e29d992b52e4e20ce14a3574d8c981628f38dc
2,017
LeetCode-Solutions
Academic Free License v1.1
Kotlin/src/dev/aspid812/leetcode/problem0541/Solution.kt
Const-Grigoryev
367,924,342
false
{"Python": 35682, "Kotlin": 11162, "C++": 2688, "Java": 2168, "C": 1076}
package dev.aspid812.leetcode.problem0541 /* 541. Reverse String II * ---------------------- * * Given a string `s` and an integer `k`, reverse the first `k` characters for every `2k` characters counting * from the start of the string. * * If there are fewer than `k` characters left, reverse all of them. If there are less than `2k` but greater than * or equal to `k` characters, then reverse the first `k` characters and left the other as original. * * ### Constraints: * * * `1 <= s.length <= 10^4` * * `s` consists of only lowercase English letters. * * `1 <= k <= 10^4` */ import kotlin.math.min class Solution { fun CharArray.swap(i: Int, j: Int) { val c = this[i] this[i] = this[j] this[j] = c } fun CharArray.reverse(start: Int, end: Int) { var i = start var j = end - 1 while (i < j) { swap(i++, j--) } } fun reverseStr(str: String, k: Int): String { val s = str.toCharArray() for (i in s.indices.step(2 * k)) { s.reverse(i, min(i + k, s.size)) } return String(s) } } fun main() { val s = Solution() println("${s.reverseStr(str="abcdefg", k=2)} == \"bacdfeg\"") println("${s.reverseStr(str="abcd", k=2)} == \"bacd\"") }
0
Python
0
0
cea8e762ff79878e2d5622c937f34cf20f0b385e
1,303
LeetCode
MIT License
src/main/kotlin/g2401_2500/s2438_range_product_queries_of_powers/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2401_2500.s2438_range_product_queries_of_powers // #Medium #Array #Bit_Manipulation #Prefix_Sum // #2023_07_05_Time_1115_ms_(100.00%)_Space_94.9_MB_(100.00%) @Suppress("NAME_SHADOWING") class Solution { fun productQueries(n: Int, queries: Array<IntArray>): IntArray { val length = queries.size val mod = (1e9 + 7).toLong() // convert n to binary form // take the set bit and find the corresponding 2^i // now answer for the query val powerTracker = IntArray(32) val productTakingPowers: MutableList<Long> = ArrayList() val result = IntArray(length) fillPowerTracker(powerTracker, n) fillProductTakingPowers(productTakingPowers, powerTracker) var index = 0 for (query in queries) { val left = query[0] val right = query[1] var product: Long = 1 for (i in left..right) { product = product * productTakingPowers[i] % mod } result[index++] = (product % mod).toInt() } return result } private fun fillPowerTracker(powerTracker: IntArray, n: Int) { var n = n var index = 0 while (n > 0) { powerTracker[index++] = n and 1 n = n shr 1 } } private fun fillProductTakingPowers(productTakingPowers: MutableList<Long>, powerTracker: IntArray) { for (i in 0..31) { if (powerTracker[i] == 1) { val power = Math.pow(2.0, i.toDouble()).toLong() productTakingPowers.add(power) } } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,633
LeetCode-in-Kotlin
MIT License
src/main/basicprogramming/implementation/kotlin/BatmanAndTicTacToe.kt
vamsitallapudi
119,534,182
false
{"Java": 24691, "Kotlin": 20452}
package main.basicprogramming.implementation.kotlin fun main(args: Array<String>) { var testCases:Int = readLine()!!.toInt() while(testCases-- > 0) { val line1 = readLine()!! val line2 = readLine()!! val line3 = readLine()!! val line4 = readLine()!! if(ticTacToeLogic(line1,line2,line3,line4)) println("YES") else println("NO") } } fun ticTacToeLogic(line1:String, line2:String, line3:String, line4:String) : Boolean { // TODO: need to change some logic in case of expected next move // case -1 row check: if(checkPattern(line1) || checkPattern(line2) || checkPattern(line3) || checkPattern(line4)) return true // case -2 column check else if(performColumnCheck(line1,line2,line3,line4)) return true // case -3 diagonal check else if(performDiagonalCheck(line1, line2, line3, line4)) return true return false } fun performDiagonalCheck(line1: String, line2: String, line3: String, line4: String): Boolean { // diagonals with 4 nodes val diagonalString1 = (line1[0].toString() + line2[1] + line3[2] + line4[3]) val diagonalString2 = (line1[3].toString() + line2[2] + line3[1] + line4[0]) // small diagonals with 3 nodes val diagonalString3 = (line1[1].toString() + line2[2] + line3[3]) val diagonalString4 = (line1[2].toString() + line2[1] + line3[0]) val diagonalString5 = (line2[0].toString() + line3[1] + line4[2]) val diagonalString6 = (line2[2].toString() + line3[1] + line4[0]) val diagonalString7 = (line2[3].toString() + line3[2] + line4[1]) return (checkPattern(diagonalString1) || checkPattern(diagonalString2) || checkPattern(diagonalString3) || checkPattern(diagonalString4) || checkPattern(diagonalString5) || checkPattern(diagonalString6) || checkPattern(diagonalString7)) } fun performColumnCheck(line1: String, line2: String, line3: String, line4: String): Boolean { for(i in 0..3) { val columnString = (line1[i].toString()+line2[i]+line3[i]+line4[i]) if(checkPattern(columnString)) return true } return false } fun checkPattern(str:String) : Boolean{ return str.contains("xx.") || str.contains(".xx") || str.contains("x.x") }
0
Java
1
1
9349fa7488fcabcb9c58ce5852d97996a9c4efd3
2,209
HackerEarth
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem2706/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem2706 import kotlin.math.max import kotlin.math.min /** * LeetCode page: [2706. Buy Two Chocolates](https://leetcode.com/problems/buy-two-chocolates/); */ class Solution { /* Complexity: * Time O(N) and Space O(1) where N is the size of prices; */ fun buyChoco(prices: IntArray, money: Int): Int { val minCost = findTwoSmallest(prices).sum() return if (minCost <= money) money - minCost else money } private fun findTwoSmallest(prices: IntArray): IntArray { var smallest = min(prices[0], prices[1]) var secondSmallest = max(prices[0], prices[1]) for (index in 2..<prices.size) { when { prices[index] < smallest -> { secondSmallest = smallest smallest = prices[index] } prices[index] < secondSmallest -> { secondSmallest = prices[index] } } } return intArrayOf(smallest, secondSmallest) } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,066
hj-leetcode-kotlin
Apache License 2.0
src/palindrome_int/PalindRomeInt.kt
AhmedTawfiqM
458,182,208
false
{"Kotlin": 11105}
package palindrome_int //https://leetcode.com/problems/palindrome-number object PalindRomeInt { private fun isPalindrome(input: Int): Boolean { if (input < 0 || input >= Int.MAX_VALUE) return false if (input in 0..9) return true var original = input var reversed = 0 while (original != 0) { reversed = (reversed * 10) + original % 10 original /= 10 } return input == reversed } @JvmStatic fun main(args: Array<String>) { println(isPalindrome(121)) println(isPalindrome(-121)) println(isPalindrome(10)) } } /** * Given an integer x, return true if x is palindrome integer. An integer is a palindrome when it reads the same backward as forward. For example, 121 is a palindrome while 123 is not. Example 1: Input: x = 121 Output: true Explanation: 121 reads as 121 from left to right and from right to left. Example 2: Input: x = -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. Example 3: Input: x = 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome. Constraints: -231 <= x <= 231 - 1 Follow up: Could you solve it without converting the integer to a string? **/
0
Kotlin
0
1
a569265d5f85bcb51f4ade5ee37c8252e68a5a03
1,335
ProblemSolving
Apache License 2.0
src/main/kotlin/com/github/michaelbull/advent2023/math/Math.kt
michaelbull
726,012,340
false
{"Kotlin": 195941}
package com.github.michaelbull.advent2023.math import kotlin.math.abs /* https://en.wikipedia.org/wiki/Greatest_common_divisor */ tailrec fun greatestCommonDivisor(a: Long, b: Long): Long { return if (b == 0L) { a } else { greatestCommonDivisor(b, a % b) } } fun Iterable<Long>.greatestCommonDivisor(): Long { return reduce(::greatestCommonDivisor) } fun Sequence<Long>.greatestCommonDivisor(): Long { return reduce(::greatestCommonDivisor) } fun leastCommonMultiple(a: Long, b: Long): Long { return abs(a * b) / greatestCommonDivisor(a, b) } fun Iterable<Long>.leastCommonMultiple(): Long { return reduce(::leastCommonMultiple) } fun Sequence<Long>.leastCommonMultiple(): Long { return reduce(::leastCommonMultiple) } /* https://en.wikipedia.org/wiki/Triangular_number */ fun triangular(n: Int): Int { return (n * (n + 1)) / 2 } fun triangular(n: Long): Long { return (n * (n + 1)) / 2 }
0
Kotlin
0
1
ea0b10a9c6528d82ddb481b9cf627841f44184dd
956
advent-2023
ISC License
solutions/aockt/y2015/Y2015D03.kt
Jadarma
624,153,848
false
{"Kotlin": 435090}
package aockt.y2015 import io.github.jadarma.aockt.core.Solution object Y2015D03 : Solution { /** Keeps track of Santa's visits. */ private class SantaTracker { private var currentLocation = 0 to 0 private val _visited = mutableSetOf(currentLocation) /** A set of coordinates of houses that this tracker delivered presents to. */ val visited: Set<Pair<Int, Int>> = _visited /** Travels and delivers a present to the house in the given [direction]. */ fun travel(direction: Char) { currentLocation = currentLocation.transpose(direction) _visited.add(currentLocation) } /** Given a coordinate, gets the coordinates of the next point in the given [direction]. */ private fun Pair<Int, Int>.transpose(direction: Char): Pair<Int, Int> = when (direction) { '^' -> first to second + 1 'v' -> first to second - 1 '<' -> first - 1 to second '>' -> first + 1 to second else -> throw IllegalArgumentException("Invalid direction: '$direction'.") } } override fun partOne(input: String) = SantaTracker().run { input.forEach(this::travel) visited.count() } override fun partTwo(input: String): Any { val trackers = List(2) { SantaTracker() } input.forEachIndexed { index, direction -> trackers[index % 2].travel(direction) } return trackers .map { it.visited } .reduce(Set<*>::plus) .count() } }
0
Kotlin
0
3
19773317d665dcb29c84e44fa1b35a6f6122a5fa
1,559
advent-of-code-kotlin-solutions
The Unlicense
server/src/main/kotlin/database.kt
GuillaumeEveillard
259,152,854
false
null
import com.google.gson.Gson import parser.ParserResult import java.io.File import java.time.Instant import java.time.LocalDate import java.time.ZoneId import kotlin.math.max data class Item(val id: Long, val frenchName: String?, val englishName: String?) { fun complete() = frenchName != null && englishName != null } data class Auction(val itemId: Long, val quantity: Long, val bid: Long, val buyout: Long?, val timestamp: Instant) { fun bidByUnit() = bid.toDouble() / quantity.toDouble() fun buyoutByUnit() = if(buyout == null) null else buyout.toDouble() / quantity.toDouble() } data class Database(val items: Collection<Item>, val auctions: List<Auction>) { val itemById = items.map { it.id to it } private val auctionsPerItem = auctions.groupBy { it.itemId }.mapValues { ItemAuctions(it.value) } fun findItemByName(name: String) : Item? { return items.find { it.frenchName == name || it.englishName == name } } fun latestBestBuyout(itemId: Long) : Double { return bestBuyout(itemId).toSortedMap().values.last() } fun bestBuyout(itemId: Long) : Map<Instant, Double> { val auctions = auctionsPerItem[itemId]?: throw IllegalArgumentException("Item $itemId unknown") return auctions.bestBuyout() } fun bestBuyoutPerDay(itemId: Long) : Map<LocalDate, Double> { val auctions = auctionsPerItem[itemId]?: throw IllegalArgumentException("Item $itemId unknown") return auctions.bestBuyoutPerDay() } fun bestAverageBuyout(itemId: Long, n: Long) : Map<Instant, Double> { val auctions = auctionsPerItem[itemId]?: throw IllegalArgumentException("Item $itemId unknown") return auctions.bestAverageBuyout(n) } } fun loadDatabaseFromJsonFiles(folder: File): Database { val items = mutableMapOf<Long, Item>() val auctions = mutableListOf<Auction>() folder .listFiles { f -> f.name.startsWith("result-")} .forEach { val r = Gson().fromJson<ParserResult>(it.readText(), ParserResult::class.java) r.items.forEach { items.compute(it.id) {id, i -> buildItem(i, it)} } auctions.addAll(r.auctions) } return Database(items.values, auctions) } private fun buildItem(item: Item?, item2: Item): Item { if(item == null || item2.complete()) { return item2 } return Item(item2.id, item.frenchName ?: item2.frenchName, item.englishName ?: item2.englishName) } class ItemAuctions(auctions: List<Auction>) { private val auctionsPerTimestamp : Map<Instant, Collection<Auction>> = auctions.groupBy { it.timestamp } fun bestBuyoutPerDay() : Map<LocalDate, Double> { return auctionsPerTimestamp.entries .groupBy({ k -> k.key.atZone(ZoneId.systemDefault()).toLocalDate()}, { v -> v.value}) .mapValues { it.value.flatten().mapNotNull { a -> a.buyoutByUnit() }.min() } .filterValues { it != null } as Map<LocalDate, Double> } fun bestBuyout(): Map<Instant, Double> { return auctionsPerTimestamp .mapValues { a -> a.value.mapNotNull { a -> a.buyoutByUnit() }.min() } .filterValues { it != null } as Map<Instant, Double> } fun bestAverageBuyout(n: Long): Map<Instant, Double> { return auctionsPerTimestamp .mapValues { a -> bestAverageBuyout(a.value, n) } .filterValues { it != null } as Map<Instant, Double> } private fun bestAverageBuyout(auctions: Collection<Auction>, n: Long) : Double? { val avgPrice = auctions .filter { it.buyoutByUnit() != null } .map { AveragePrice(it.buyoutByUnit()!!, it.quantity) } .sortedBy { it.price } .reduce { acc, pair -> acc.addPrice(pair.price, pair.quantity, n) } return if (avgPrice.quantity < n) null else avgPrice.price } } data class AveragePrice(val price: Double, val quantity: Long) { fun addPrice(price: Double, quantity: Long, limit: Long) : AveragePrice{ if(this.quantity >= limit) { return this } else { val totalQuantity = max(this.quantity + quantity, limit) val avgPrice = (this.price * this.quantity + price*(totalQuantity - this.quantity)) / totalQuantity return AveragePrice(avgPrice, this.quantity + quantity) } } }
0
Kotlin
0
0
7beb62c8416a84ef2d0619ac1be29f9555515d32
4,500
ah-charts
MIT License
shared/src/commonMain/kotlin/com/somabits/spanish/regularity/RegularityChecker.kt
chiljamgossow
581,781,635
false
{"Kotlin": 918432, "Swift": 1817}
package com.somabits.spanish.regularity import com.somabits.spanish.comparison.ConjugationComparison import com.somabits.spanish.comparison.SubstringComparisonResult import com.somabits.spanish.comparison.compareSubstrings import com.somabits.spanish.verb.Conjugation import com.somabits.spanish.verb.VerbForm class ConjugationRegularityChecker( override val conjugation: Conjugation, val regularConjugation: Conjugation? = conjugation.findCorrespondingRegularConjugation(), ) : ConjugationComparison( conjugation = conjugation, targetConjugation = regularConjugation, ) { val isRegular = super.isMatching } class VerbFormRegularityChecker( val verbForm: VerbForm, private val regularVerbForm: VerbForm = verbForm.getCorrespondingRegularVerbForm(), ) { val substringRegularities by lazy { verbForm.conjugatedForm.compareSubstrings(regularVerbForm.conjugatedForm) } val isRegular: Boolean = verbForm.conjugatedForm == regularVerbForm.conjugatedForm } fun Conjugation.findCorrespondingRegularConjugation(): Conjugation? { return VerbConjugation( infinitive, ).getTenseConjugation(tense) } fun VerbForm.getCorrespondingRegularVerbForm(): VerbForm { return when (this) { is VerbForm.Participio -> VerbConjugation( infinitive, ).participio is VerbForm.Gerundio -> VerbConjugation( infinitive, ).gerundio } } val List<SubstringComparisonResult>.isMatching: Boolean get() = all { it.isMatching }
1
Kotlin
0
0
e680c7048721fb9a2cbfb7cb5a9db3e39ac73b45
1,529
Spanish
MIT License
lesson-3_dynamic-programming/0-1-knapsack-problem/memoization/main.kt
BioniCosmos
471,716,962
false
null
import kotlin.math.max fun main() { var tmp = readLine()!!.split(' ') val n = tmp[0].toInt() val balance = tmp[1].toInt() val values = Array(n) { 0 } val like = Array(n) { 0 } val rec = Array(n) { Array(balance + 1) { 0 } } for (i in 0 until n) { tmp = readLine()!!.split(' ') values[i] = tmp[0].toInt() like[i] = tmp[1].toInt() } println(getFav(n - 1, balance, values, like, rec)) } fun getFav(i: Int, balance: Int, values: Array<Int>, like: Array<Int>, rec: Array<Array<Int>>): Int { if (i == -1 || balance <= 0) { return 0 } if (rec[i][balance] == 0) { if (values[i] > balance) { rec[i][balance] = getFav(i - 1, balance, values, like, rec) } else { rec[i][balance] = max( getFav(i - 1, balance, values, like, rec), getFav(i - 1, balance - values[i], values, like, rec) + like[i], ) } } return rec[i][balance] }
0
Rust
0
1
5d6a15ff9aa476956ba3658f1fa9a61351d3f0cd
996
neko-programming-class
MIT License
10/part_one.kt
ivanilos
433,620,308
false
{"Kotlin": 97993}
import java.io.File fun readInput() : List<String> { return File("input.txt") .readLines() } class SyntaxChecker { companion object { val OPEN_CHARS = listOf('(', '[', '{', '<') val MATCH = mapOf('(' to ')', '[' to ']', '{' to '}', '<' to '>') val SCORE_TABLE = mapOf(')' to 3, ']' to 57, '}' to 1197, '>' to 25137) } fun calcScore(line : String) : Int { val stack = mutableListOf<Char>() for (ch in line) { if (ch in OPEN_CHARS) { stack.add(ch) } else { if (stack.isNotEmpty() && MATCH[stack.last()] == ch) { stack.removeLast() } else { return SCORE_TABLE[ch]!! } } } return 0 } } fun solve(lines : List<String>) : Int { var result = 0 val syntaxChecker = SyntaxChecker() for (line in lines) { result += syntaxChecker.calcScore(line) } return result } fun main() { val lines = readInput() val ans = solve(lines) println(ans) }
0
Kotlin
0
3
a24b6f7e8968e513767dfd7e21b935f9fdfb6d72
1,173
advent-of-code-2021
MIT License
src/main/kotlin/Day10.kt
goblindegook
319,372,062
false
null
package com.goblindegook.adventofcode2020 import com.goblindegook.adventofcode2020.extension.asIntList import com.goblindegook.adventofcode2020.input.load fun main() { val adapters = load("/day10-input.txt").asIntList() println(multiplyJoltageDiffs(adapters)) println(countPermutations(adapters)) } tailrec fun multiplyJoltageDiffs(adapters: List<Int>, diff1: Int = 1, diff3: Int = 1, joltage: Int = 1): Int = when { joltage + 1 in adapters -> multiplyJoltageDiffs(adapters, diff1 + 1, diff3, joltage + 1) joltage + 2 in adapters -> multiplyJoltageDiffs(adapters, diff1, diff3, joltage + 2) joltage + 3 in adapters -> multiplyJoltageDiffs(adapters, diff1, diff3 + 1, joltage + 3) else -> diff1 * diff3 } fun countPermutations(adapters: List<Int>): Long = adapters .sorted() .fold(mapOf(0 to 1L)) { counts, jolts -> counts + (jolts to counts.filterKeys { it in jolts - 3 until jolts }.values.sum()) } .values .last()
0
Kotlin
0
0
85a2ff73899dbb0e563029754e336cbac33cb69b
999
adventofcode2020
MIT License
src/main/kotlin/day12/SpringGroup.kt
limelier
725,979,709
false
{"Kotlin": 48112}
package day12 internal typealias Springs = String internal class SpringGroup( springs: Springs, private val damagedGroups: List<Int> ) { private val springs = springs.trimStart('.') companion object { val waysToCompleteCache = mutableMapOf<String, Long>() val potentialDamageSpringPrefixRegex = "^([?#]+).*$".toRegex() fun parseSprings(text: String, numbers: String): SpringGroup { val damagedGroups = numbers.split(",").map { it.toInt() } return SpringGroup(text, damagedGroups) } } fun waysToComplete(): Long = waysToCompleteCache.getOrPut(this.toString()) { waysToCompleteCacheMiss() } private fun waysToCompleteCacheMiss(): Long { if (damagedGroups.isEmpty()) { return if (springs.isEmpty() || springs.none { it == '#' }) 1 else 0 } if (springs.length < damagedGroups.size - 1 + damagedGroups.sum()) return 0 if (springs.startsWith('#')) { val prefix = springs.take(damagedGroups[0]) if ('.' in prefix) return 0 if (prefix.length >= springs.length) return 1 if (springs[prefix.length] == '#') return 0 return SpringGroup(springs.drop(prefix.length + 1), damagedGroups.drop(1)).waysToComplete() } // springs starts with '?' val potentialDamageGroup = potentialDamageSpringPrefixRegex.matchEntire(springs)!!.groupValues[1].length var sum = SpringGroup(springs.drop(1), damagedGroups).waysToComplete() // replace ? with . if (potentialDamageGroup >= damagedGroups[0]) { sum += SpringGroup("#".repeat(damagedGroups[0]) + springs.drop(damagedGroups[0]), damagedGroups) .waysToComplete() } return sum } override fun toString(): String = "$springs ${damagedGroups.joinToString(",")}" }
0
Kotlin
0
0
0edcde7c96440b0a59e23ec25677f44ae2cfd20c
1,878
advent-of-code-2023-kotlin
MIT License
src/main/java/com/booknara/problem/backtracking/CombinationSumIIKt.kt
booknara
226,968,158
false
{"Java": 1128390, "Kotlin": 177761}
package com.booknara.problem.backtracking /** * 40. Combination Sum II (Medium) * https://leetcode.com/problems/combination-sum-ii/ */ class CombinationSumIIKt { // T:O(2^n), S:O(2^n) fun combinationSum2(candidates: IntArray, target: Int): List<List<Int>> { // input check, the length of candidates >= 1 val res: MutableList<List<Int>> = ArrayList() candidates.sort() val list: MutableList<Int> = ArrayList() helper(candidates, 0, target, list, res) return res } fun helper(candidates: IntArray, index: Int, remaining: Int, list: MutableList<Int>, res: MutableList<List<Int>>) { if (remaining < 0) return if (remaining == 0) { res.add(ArrayList<Int>(list)) return } if (index == candidates.size) return // Pruning if (candidates[index] > remaining) return for (i in index until candidates.size) { if (i > index && candidates[i - 1] == candidates[i]) continue list.add(candidates[i]) helper(candidates, i + 1, remaining - candidates[i], list, res) list.removeAt(list.size - 1) } } }
0
Java
1
1
04dcf500ee9789cf10c488a25647f25359b37a53
1,226
playground
MIT License
year2016/src/main/kotlin/net/olegg/aoc/year2016/day1/Day1.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2016.day1 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.Directions.Companion.CCW import net.olegg.aoc.utils.Directions.Companion.CW import net.olegg.aoc.utils.Directions.U import net.olegg.aoc.utils.Vector2D import net.olegg.aoc.year2016.DayOf2016 /** * See [Year 2016, Day 1](https://adventofcode.com/2016/day/1) */ object Day1 : DayOf2016(1) { private val SHIFT = mapOf( 'L' to CCW, 'R' to CW, ) override fun first(): Any? { return data .split(", ") .map { it[0] to it.substring(1).toInt() } .fold(Pair(Vector2D(), U)) { (pos, dir), command -> val newDir = SHIFT[command.first]?.get(dir) ?: dir Pair(pos + newDir.step * command.second, newDir) } .first .manhattan() } override fun second(): Any? { val visited = mutableSetOf<Vector2D>() data .split(", ") .map { it[0] to it.substring(1).toInt() } .fold(Pair(Vector2D(), U)) { (pos, dir), command -> val newDir = SHIFT[command.first]?.get(dir) ?: dir val steps = (1..command.second).map { pos + newDir.step * it } steps .firstOrNull { it in visited } ?.let { return it.manhattan() } visited.addAll(steps) return@fold Pair(pos + newDir.step * command.second, newDir) } return null } } fun main() = SomeDay.mainify(Day1)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,396
adventofcode
MIT License
src/main/kotlin/com/askrepps/advent2022/day07/Day07.kt
askrepps
726,566,200
false
{"Kotlin": 99712}
/* * MIT License * * Copyright (c) 2022 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.askrepps.advent2022.day07 import com.askrepps.advent2022.util.getInputLines import java.io.File interface Node { val name: String val size: Long } class FileNode(override val name: String, override val size: Long) : Node class DirectoryNode(override val name: String, val parent: DirectoryNode? = null) : Node { private val _childNodes = mutableMapOf<String, Node>() val childNodes: Map<String, Node> get() = _childNodes private var cachedSize: Long? = null override val size: Long get() = cachedSize ?: childNodes.values.sumOf { it.size }.also { cachedSize = it } fun addChild(node: Node) { _childNodes[node.name] = node invalidateCachedSize() } private fun invalidateCachedSize() { cachedSize = null parent?.invalidateCachedSize() } fun getDirectoriesRecursive(): List<DirectoryNode> = childNodes.values.filterIsInstance<DirectoryNode>() .flatMap { it.getDirectoriesRecursive() } + this } fun String.lastToken() = split(" ").last() fun List<String>.toFileTree(): DirectoryNode { val rootNode = DirectoryNode("/") var currentNode = rootNode subList(1, size).forEach { line -> when { line.startsWith("dir") -> { val dirName = line.lastToken() currentNode.addChild(DirectoryNode(dirName, currentNode)) } line.first().isDigit() -> { val (fileSize, fileName) = line.split(" ") currentNode.addChild(FileNode(fileName, fileSize.toLong())) } line == "$ cd .." -> { currentNode = checkNotNull(currentNode.parent) { "node ${currentNode.name} does not have a parent directory" } } line.startsWith("$ cd") -> { val dirName = line.lastToken() currentNode = checkNotNull(currentNode.childNodes[dirName] as? DirectoryNode) { "directory $dirName not found in node ${currentNode.name}" } } } } return rootNode } fun findSumOfDirectoriesUnderLimit(root: DirectoryNode, limit: Long) = root.getDirectoriesRecursive() .filter { it.size <= limit } .sumOf { it.size } fun findSmallestDirectoryToDelete(root: DirectoryNode, diskSize: Long, spaceNeeded: Long): Long { val freeSpace = diskSize - root.size return root.getDirectoriesRecursive() .filter { freeSpace + it.size >= spaceNeeded } .minOf { it.size } } fun getPart1Answer(root: DirectoryNode) = findSumOfDirectoriesUnderLimit(root, limit = 100000L) fun getPart2Answer(root: DirectoryNode) = findSmallestDirectoryToDelete(root, diskSize = 70000000L, spaceNeeded = 30000000L) fun main() { val root = File("src/main/resources/2022/day07.txt") .getInputLines().toFileTree() println("The answer to part 1 is ${getPart1Answer(root)}") println("The answer to part 2 is ${getPart2Answer(root)}") }
0
Kotlin
0
0
5ce2228b0951db49a5cf2a6d974112f57e70030c
4,202
advent-of-code-kotlin
MIT License
archive/src/main/kotlin/com/grappenmaker/aoc/year16/Day04.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year16 import com.grappenmaker.aoc.PuzzleSet import com.grappenmaker.aoc.deepen fun PuzzleSet.day4() = puzzle { val rooms = inputLines.map { l -> val (name, info) = l.substringBeforeLast('-') to l.substringAfterLast('-') val (id, check) = info.substringBeforeLast('[') to info.substringAfterLast('[') RoomCheck(name, id.toInt(), check.removeSuffix("]").deepen().sorted()) } val filtered = rooms.filter { (name, _, check) -> val chars = name.filter { it.isLetter() }.groupingBy { it }.eachCount().toList() .sortedWith(compareByDescending<Pair<Char, Int>> { it.second }.then(compareBy { it.first })) chars.take(5).map { it.first }.sorted() == check } partOne = filtered.sumOf { it.id }.s() partTwo = filtered.first { (text, shift) -> text.deepen().joinToString("") { c -> when { c.isLetter() -> ((c.code - 97 + shift) % 26 + 97).toChar() c == '-' -> ' ' else -> c }.toString() } == "northpole object storage" }.id.s() } data class RoomCheck(val name: String, val id: Int, val checksum: List<Char>)
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
1,198
advent-of-code
The Unlicense
src/main/kotlin/com/sherepenko/leetcode/solutions/LongestCommonSubstring.kt
asherepenko
264,648,984
false
null
package com.sherepenko.leetcode.solutions import com.sherepenko.leetcode.Solution import kotlin.math.max class LongestCommonSubstring( private val text1: String, private val text2: String ) : Solution { companion object { fun longestCommonSubsequence(text1: String, text2: String): Int { val m = text1.length val n = text2.length val dp = Array(m) { IntArray(n) } var result = 0 for (i in 0 until m) { for (j in 0 until n) { if (text1[i] == text2[j]) { dp[i][j] = if (i == 0 || j == 0) { 1 } else { dp[i - 1][j - 1] + 1 } } result = max(result, dp[i][j]) } } return result } } override fun resolve() { val result = longestCommonSubsequence(text1, text2) println( "Longest Common Substring: \n" + " Input: $text1, $text2; \n" + " Result: $result \n" ) } }
0
Kotlin
0
0
49e676f13bf58f16ba093f73a52d49f2d6d5ee1c
1,211
leetcode
The Unlicense
src/main/kotlin/leetcode/kotlin/hashtable/247. Strobogrammatic Number II.kt
sandeep549
251,593,168
false
null
package leetcode.kotlin.hashtable import java.util.* import kotlin.collections.ArrayList /** A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Find all strobogrammatic numbers that are of length = n. Example: Input: n = 2 Output: ["11","69","88","96"] */ fun main() { println(findStrobogrammatic2(2)) } // O(no count to check * size of each number) // O(10^n * n) // Time Limit Exceeded private fun findStrobogrammatic(n: Int): List<String> { var map = mapOf<Char, Char>('0' to '0', '1' to '1', '6' to '9', '8' to '8', '9' to '6') fun check(num: String): Boolean { var l = 0 var r = num.length - 1 var arr = num.toCharArray() while (l <= r) { if (!map.containsKey(arr[l]) || map.get(arr[l++]) != arr[r--]) return false } return true } var ans = ArrayList<String>() var start = Math.pow(10.toDouble(), n - 1.toDouble()).toInt() if (start == 1) start = 0 // handle single digit case, where we need 0 in input space var end = Math.pow(10.toDouble(), n.toDouble()) - 1 while (start <= end) { if (check(start.toString())) ans.add(start.toString()) start++ } return ans } // O(n) recursive // TODO do it without recursion fun findStrobogrammatic2(n: Int): List<String>? { fun helper(n: Int, m: Int): List<String> { if (n == 0) return ArrayList(listOf("")) // its not empty list,list with one empty space item if (n == 1) return ArrayList(listOf("0", "1", "8")) val list = helper(n - 2, m) val res = ArrayList<String>() for (i in list.indices) { val s = list[i] if (n != m) res.add("0" + s + "0") res.add("1" + s + "1") res.add("6" + s + "9") res.add("8" + s + "8") res.add("9" + s + "6") } return res } return helper(n, n) }
0
Kotlin
0
0
9cf6b013e21d0874ec9a6ffed4ae47d71b0b6c7b
1,947
kotlinmaster
Apache License 2.0
src/Day01.kt
sgc109
576,491,331
false
{"Kotlin": 8641}
fun main() { fun part1(input: String): Long { return input.split("\n\n").maxOfOrNull { chunk -> chunk.split("\n").sumOf { numStr -> numStr.toLong() } }!! } fun part2(input: String): Long { val sums = input.split("\n\n").map { it.split("\n").sumOf { it.toLong() } } return sums.sortedDescending().subList(0, 3).sum() } val testInput = readText("Day01_test") check(part1(testInput) == 24000L) val input = readText("Day01") part1(input).println() part2(input).println() }
0
Kotlin
0
0
03e4e85283d486430345c01d4c03419d95bd6daa
600
aoc-2022-in-kotlin
Apache License 2.0
src/advent/of/code/18thPuzzle.kt
1nco
725,911,911
false
{"Kotlin": 112713, "Shell": 103}
package advent.of.code import advent.of.code.types.Pos import java.util.* import kotlin.math.absoluteValue object `18thPuzzle` { private const val DAY = "18"; private var input: MutableList<String> = arrayListOf(); private var result = 0L; private var resultSecond = 0L; private val dirMap: Map<String, Pos> = mapOf(Pair("U", Pos(-1, 0)), Pair("D", Pos(1, 0)), Pair("R", Pos(0, 1)), Pair("L", Pos(0, -1))) fun solve() { val startingTime = Date(); input.addAll(Reader.readInput(DAY)); // first(); second(); println("first: $result"); println("second: $resultSecond"); println(startingTime); println(Date()); } private fun first() { val vertices: MutableList<Pos> = arrayListOf(); vertices.add(Pos(0, 0)) input.forEach { line -> val direction = line.split(" ")[0] val length = line.split(" ")[1].toLong() val color = line.split(" ")[2] var v = vertices.last().copy(); for (i in 0..<length) { v.line += dirMap[direction]!!.line; v.column += dirMap[direction]!!.column; result += 1; } vertices.add(v) } vertices.removeLast(); result /= 2 result += vertices .asSequence() .plus(vertices.first()) .windowed(2) .sumOf { (a, b) -> a.line * b.column - a.column * b.line } .absoluteValue .div(2) .plus(1) .toLong() } private fun second() { val vertices: MutableList<Pos> = arrayListOf(); vertices.add(Pos(0, 0)) input.forEach { line -> val color = line.split(" ")[2] val direction = getDirection(color.replace("(", "").replace(")", "").replace("#", "")[5].toString()); val length = color.replace("(", "").replace(")", "").replace("#", "").dropLast(1).toLong(radix = 16) var v = vertices.last().copy(); for (i in 0..<length) { v.line += dirMap[direction]!!.line; v.column += dirMap[direction]!!.column; resultSecond += 1; } vertices.add(v) } vertices.removeLast(); resultSecond /= 2 resultSecond += vertices .asSequence() .plus(vertices.first()) .windowed(2) .sumOf { (a, b) -> a.line * b.column - a.column * b.line } .absoluteValue .div(2) .plus(1) .toLong() } fun getDirection(s: String): String { if (s == "0") { return "R" } if (s == "1") { return "D" } if (s == "2") { return "L" } if (s == "3") { return "U" } return ""; } }
0
Kotlin
0
0
0dffdeba1ebe0b44d24f94895f16f0f21ac8b7a3
2,962
advent-of-code
Apache License 2.0
src/Day14.kt
zt64
572,594,597
false
null
private object Day14 : Day(14) { private val grid = MutableList(1000) { y -> MutableList<Point>(1000) { x -> Air(x, y) } } private val directionPairs = listOf( 0 to 1, // Down -1 to 1, // Down-left 1 to 1 // Down-right ) private val spawnPoint = Point(500, 0) init { val paths = input.lines().map { path -> path.replace(" ", "") .split("->") .map { pair -> val (x, y) = pair.split(",") Point(x.toInt(), y.toInt()) } } paths.forEach { path -> path.windowed(2) { (previousPoint, currentPoint) -> val xRange = if (previousPoint.x < currentPoint.x) { previousPoint.x..currentPoint.x } else { currentPoint.x..previousPoint.x } val yRange = if (previousPoint.y < currentPoint.y) { previousPoint.y..currentPoint.y } else { currentPoint.y..previousPoint.y } xRange.forEach { x -> yRange.forEach { y -> grid[y][x] = Rock(x, y) } } } } } private fun simulate(): Int { var restingSand = 0 var hitAbyss = false while (!hitAbyss) { if (grid[spawnPoint.y][spawnPoint.x] !is Air) return restingSand var sand = Sand(spawnPoint.x, spawnPoint.y) grid[sand.y][sand.x] = sand while (true) { try { if ( directionPairs.none { (dx, dy) -> val (x, y) = sand.x + dx to sand.y + dy if (grid[y][x] is Air) { grid[sand.y][sand.x] = Air(sand.x, sand.y) sand = Sand(x, y) grid[y][x] = sand true } else false } ) { restingSand++ break } } catch (e: IndexOutOfBoundsException) { hitAbyss = true break } } } return restingSand } override fun part1() = simulate() override fun part2(): Int { // Reset to initial state grid.forEach { row -> row.replaceAll { if (it is Sand) Air(it.x, it.y) else it } } // Find the lowest rock + 2 val groundRowIndex = 2 + grid.indexOfLast { row -> row.any { it is Rock } } // Set entire ground row to rock grid[groundRowIndex].indices.forEach { x -> grid[groundRowIndex][x] = Rock(x, groundRowIndex) } return simulate() } private open class Point(val x: Int, val y: Int) private class Air(x: Int, y: Int) : Point(x, y) private class Sand(x: Int, y: Int) : Point(x, y) private class Rock(x: Int, y: Int) : Point(x, y) } private fun main() = Day14.main()
0
Kotlin
0
0
4e4e7ed23d665b33eb10be59670b38d6a5af485d
3,296
aoc-2022
Apache License 2.0
kotlin/src/com/daily/algothrim/leetcode/hard/LargestRectangleArea.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode.hard import java.util.* /** * 84. 柱状图中最大的矩形 * * 给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。 * 求在该柱状图中,能够勾勒出来的矩形的最大面积。 */ class LargestRectangleArea { companion object { @JvmStatic fun main(args: Array<String>) { println(LargestRectangleArea().largestRectangleArea(intArrayOf(2, 1, 5, 6, 2, 3))) println(LargestRectangleArea().largestRectangleArea(intArrayOf(2, 4))) } } // 输入:heights = [2,1,5,6,2,3] // 输出:10 fun largestRectangleArea(heights: IntArray): Int { var largest = Int.MIN_VALUE val size = heights.size val left = IntArray(size) val right = IntArray(size) Arrays.fill(right, size) val stack = Stack<Int>() for (i in 0 until size) { while (stack.isNotEmpty() && heights[stack.peek()] >= heights[i]) { right[stack.peek()] = i stack.pop() } left[i] = if (stack.isEmpty()) -1 else stack.peek() stack.push(i) } for (j in 0 until size) { largest = Math.max(largest, (right[j] - left[j] - 1) * heights[j]) } return largest } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
1,385
daily_algorithm
Apache License 2.0
src/main/kotlin/main.kt
ngothanhtuan1203
359,752,793
false
null
fun main(args: Array<String>) { print( "answer1:${ solution( listOf( intArrayOf(1, 4), intArrayOf(3, 4), intArrayOf(3, 10) ).toTypedArray() ).contentToString() }\n" ) print( "answer2:${ solution( listOf( intArrayOf(1, 1), intArrayOf(2, 2), intArrayOf(1, 2) ).toTypedArray() ).contentToString() }" ) } /** * Follow direction from pointA to pointB */ fun getVector(pointA: IntArray, pointB: IntArray): IntArray = intArrayOf(pointB[0] - pointA[0], pointB[1] - pointA[1]) fun dotProduct(vectorA: IntArray, vectorB: IntArray): Int = vectorA[0] * vectorB[0] + vectorA[1] * vectorB[1] /** * Use vector to calculate the fourth point. * There is 2 problem need to be addressed * 1. define 2 vectors make the angle * 2. define the last point. * E.g: * Have rectangle ABCD: AB and BC combine to a angle at B when: vectorAB dotProduct vectorBC = 0 * So B is the angle point --> vectorBA = vectorCD hence we can get D point (fourth point) */ fun solution(v: Array<IntArray>): IntArray { if (v.size != 3) { throw Exception("Illegal parameter") } val length = v.size for (i in 0..length) { val subV = v.withIndex().filter { (j) -> j != i }.map { (j, value) -> value } val pA = v[i] val pB = subV[0] val pC = subV[1] val vectorAB = getVector(pA, pB) val vectorAC = getVector(pA, pC) val vectorBA = getVector(pB, pA) if (dotProduct(vectorAB, vectorAC) == 0) { val xD = pC[0] - vectorBA[0] val yD = pC[1] - vectorBA[1] return intArrayOf(xD, yD) } } throw Exception("Not found") }
0
Kotlin
0
0
5544f73ac70ea35adf605ac0a2a9210e9f475973
1,904
rectangle_find_fourth_point
Apache License 2.0
30-days-leetcoding-challenge/April 18/src/Solution.kt
alexey-agafonov
240,769,182
false
null
class Solution { fun minPathSum(grid: Array<IntArray>): Int { val m = grid.size val n = grid[0].size val result = Array(m) { Array(n) {0} } result[0][0] = grid[0][0] // fill the first row for (i in 1 until n) { result[0][i] = result[0][i - 1] + grid[0][i] } // fill the first column for (i in 1 until m) { result[i][0] = result[i - 1][0] + grid[i][0] } // fill the remaining elements for (i in 1 until m) { for (j in 1 until n) { if (result[i - 1][j] > result[i][j - 1]) result[i][j] = result[i][j - 1] + grid[i][j] else result[i][j] = result[i - 1][j] + grid[i][j] } } return result[m - 1][n - 1] } } fun main() { val solution = Solution() println(solution.minPathSum(arrayOf(intArrayOf(1, 3, 1), intArrayOf(1, 5, 1), intArrayOf(4, 2, 1)))) }
0
Kotlin
0
0
d43d9c911c6fd89343e392fd6f93b7e9d02a6c9e
1,076
leetcode
MIT License
src/main/kotlin/com/kishor/kotlin/algo/recursion/Recursion.kt
kishorsutar
276,212,164
false
null
package com.kishor.kotlin.algo.recursion fun main() { // headRecursion(5) // tailRecursion(5) // println("Result head ${factorial(10)}") // println("Result tail ${factoTail(10)}") println("Fibo Head ${headFibonacci(20)}") println("Fibo Tail ${tailFibo(100, 0, 1)}") println("Iterative Fibo ${iterativeFibo(10)}") } fun headRecursion(n: Int) { println("Head recursion call n=$n") // base condition if (n == 0) return // recursion call headRecursion(n - 1) // some operation println("Head recursion for $n") } fun tailRecursion(n: Int) { println("Tail recursion call n=$n") // base condition if (n == 0) return // some operation println("Tail recursion for $n") // recursive call tailRecursion(n - 1) } // factorial with head recursion fun factorial(n: Int): Int { if (n == 1) return 1 val result = n * factorial(n - 1) return result } fun factoTail(n: Int): Int { return factorial(n, 1) } fun factorial(n: Int, accumulator: Int): Int { if (n == 1) return accumulator return factorial(n - 1, n * accumulator) } // head recursion fibonacci number fun headFibonacci(n: Int): Int { if (n == 0) return 0 if (n == 1) return 1 val res = headFibonacci(n -1) + headFibonacci(n -2) return res } fun tailFibo(n: Int, a: Long, b: Long): Long { if (n == 0) return a if (n == 1) return b return tailFibo(n - 1, b, a + b) } fun iterativeFibo(n: Int): Int { var result = 0 var num = n while (num > 0) { if (num == 1) { result = 1 } result = (num - 1) + (num - 2) num-- } return result }
0
Kotlin
0
0
6672d7738b035202ece6f148fde05867f6d4d94c
1,680
DS_Algo_Kotlin
MIT License
src/commonMain/kotlin/math/Path2d.kt
stewsters
272,030,492
false
null
package math fun findPath2d( size: Vec2, cost: (Vec2) -> Double, heuristic: (Vec2, Vec2) -> Double, neighbors: (Vec2) -> List<Vec2>, start: Vec2, end: Vec2 ): List<Vec2>? { val costs = Matrix2d(size.x, size.y) { _, _ -> Double.MAX_VALUE } val parent = Matrix2d<Vec2?>(size.x, size.y) { _, _ -> null } val fScore = Matrix2d(size.x, size.y) { _, _ -> Double.MAX_VALUE } val openSet = mutableListOf<Vec2>() val closeSet = HashSet<Vec2>() openSet.add(start) costs[start] = 0.0 fScore[start] = heuristic(start, end) while (openSet.isNotEmpty()) { // Grab the next node with the lowest cost val cheapestNode: Vec2 = openSet.minBy { fScore[it] }!! if (cheapestNode == end) { // target found, we have a path val path = mutableListOf(cheapestNode) var node = cheapestNode while (parent[node] != null) { node = parent[node]!! path.add(node) } return path.reversed() } openSet.remove(cheapestNode) closeSet.add(cheapestNode) // get the neighbors // for each point, set the cost, and a pointer back if we set the cost for (it in neighbors(cheapestNode)) { if (it.x < 0 || it.y < 0 || it.x >= size.x || it.y >= size.y) continue if (closeSet.contains(it)) continue val nextCost = costs[cheapestNode] + cost(it) if (nextCost < costs[it]) { costs[it] = nextCost fScore[it] = nextCost + heuristic(it, end) parent[it] = cheapestNode if (closeSet.contains(it)) { closeSet.remove(it) } openSet.add(it) } } } // could not find a path return null }
1
Kotlin
2
10
c5b657801d325e2072dad9736db24144d29eddf8
1,934
dungeon
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/LongestSubsequence.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 /** * 1218. Longest Arithmetic Subsequence of Given Difference * @see <a href="https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/">Source</a> */ fun interface LongestSubsequence { operator fun invoke(arr: IntArray, difference: Int): Int } class LongestSubsequenceDP : LongestSubsequence { override operator fun invoke(arr: IntArray, difference: Int): Int { val map: MutableMap<Int, Int> = HashMap() var res = 1 for (num in arr) { val prev = map[num - difference] ?: 0 map[num] = prev + 1 res = max(map[num] ?: 0, res) } return res } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,324
kotlab
Apache License 2.0
2021/19/program.kt
skrim
434,960,545
false
{"F#": 75199, "Zig": 61792, "Assembly": 6641, "Go": 4962, "Kotlin": 4486, "Julia": 3849, "PureScript": 3764, "Ada": 3369, "D": 3090, "Erlang": 3087, "Dhall": 2957, "Lua": 2895, "Fortran": 2626, "Shell": 2444, "Dart": 2246, "TSQL": 2240, "C++": 2189, "Crystal": 2018, "Racket": 1961, "C": 1476, "JetBrains MPS": 1426, "Raku": 1366, "Swift": 1237, "Rebol": 1085, "JavaScript": 470, "Smalltalk": 447}
data class Coordinate(val x: Int, val y: Int, val z: Int) { fun add(other: Coordinate) : Coordinate = Coordinate(x + other.x, y + other.y, z + other.z) fun subtract(other: Coordinate) : Coordinate = Coordinate(x - other.x, y - other.y, z - other.z) fun manhattanDistance(other: Coordinate) : Int = Math.abs(x - other.x) + Math.abs(y - other.y) + Math.abs(z - other.z) private fun getHeading(heading: Int) : Coordinate { when (heading) { // heading 0 -> return Coordinate(x, y, z) 1 -> return Coordinate(-y, x, z) 2 -> return Coordinate(-x, -y, z) 3 -> return Coordinate(y, -x, z) 4 -> return Coordinate(-z, y, x) 5 -> return Coordinate(z, y, -x) else -> throw Exception("Wut") } } private fun getRotation(rotation: Int) : Coordinate { when (rotation) { // rotation 0 -> return Coordinate(x, y, z); 1 -> return Coordinate(x, -z, y); 2 -> return Coordinate(x, -y, -z); 3 -> return Coordinate(x, z, -y); else -> throw Exception("Wut") } } fun transform(direction: Int) : Coordinate = getHeading(direction / 4).getRotation(direction % 4) } class Scanner() { var coordinates: MutableList<Coordinate> = mutableListOf<Coordinate>() var position: Coordinate = Coordinate(0, 0, 0) fun getRotatedCoordinates(rotation: Int, delta: Coordinate) : MutableList<Coordinate> = coordinates.map({ it.transform(rotation).subtract(delta) }).toMutableList() fun normalize(rotation: Int, delta: Coordinate) { coordinates = getRotatedCoordinates(rotation, delta) position = Coordinate(0, 0, 0).subtract(delta) } } class Program { var pendingLocation : MutableList<Scanner> = mutableListOf<Scanner>() var pendingCompare : MutableList<Scanner> = mutableListOf<Scanner>() var completed : MutableList<Scanner> = mutableListOf<Scanner>() fun load() { var first = true var current : Scanner = Scanner() pendingCompare.add(current) java.io.File("input.txt").forEachLine { if (it.startsWith("---")) { if (!first) { current = Scanner() pendingLocation.add(current) } first = false } else if (!it.isNullOrEmpty()) { val tokens = it.split(",") current.coordinates.add(Coordinate(tokens[0].toInt(), tokens[1].toInt(), tokens[2].toInt())) } } } fun iterate() { val first = pendingCompare[0] var i = 0 while (i < pendingLocation.count()) { val second = pendingLocation[i] var found = false var fi = 0 while (!found && fi < first.coordinates.count()) { val c1 = first.coordinates[fi++] var si = 0 while (!found && si < second.coordinates.count()) { val c2 = second.coordinates[si++] for (rotation in 0..23) { val tc2 = c2.transform(rotation) val delta = tc2.subtract(c1) var matchAttempt = second.getRotatedCoordinates(rotation, delta) var result = first.coordinates.intersect(matchAttempt) if (result.count() == 12) { second.normalize(rotation, delta) found = true } } } } if (found) { pendingLocation.removeAt(i) pendingCompare.add(second) } else { i++ } } pendingCompare.removeAt(0) completed.add(first) } fun coordinateCount() : Int = completed.flatMap { it.coordinates }.distinct().count() fun maxDistance() : Int { var result = 0 completed.forEach { first -> completed.forEach { second -> result = Math.max(result, first.position.manhattanDistance(second.position)) } } return result } fun run() { load() while (pendingLocation.count() + pendingCompare.count() > 0) iterate() println("Part 1: ${coordinateCount()}") println("Part 2: ${maxDistance()}") } } fun main() = Program().run()
0
F#
1
0
0e7f425fd50c96d52deca7e7868fcbf2a095d51c
4,486
AdventOfCode
The Unlicense
src/main/kotlin/dev/shtanko/algorithms/leetcode/PathSum.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.Stack fun interface PathSumStrategy { operator fun invoke(root: TreeNode?, sum: Int): Boolean } class PathSumRecursive : PathSumStrategy { override fun invoke(root: TreeNode?, sum: Int): Boolean { if (root == null) return false return if (root.left == null && root.right == null && sum - root.value == 0) { true } else { invoke(root.left, sum - root.value) || invoke(root.right, sum - root.value) } } } class PathSumStack : PathSumStrategy { override fun invoke(root: TreeNode?, sum: Int): Boolean { val stack: Stack<TreeNode> = Stack() stack.push(root) while (stack.isNotEmpty() && root != null) { val cur: TreeNode = stack.pop() if (cur.left == null && cur.right == null && cur.value == sum) { return true } if (cur.right != null) { cur.right?.value = cur.value + cur.right!!.value stack.push(cur.right) } if (cur.left != null) { cur.left?.value = cur.value + cur.left!!.value stack.push(cur.left) } } return false } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,863
kotlab
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/LargestMultipleOfThree.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode private val m1 = intArrayOf(1, 4, 7, 2, 5, 8) private val m2 = intArrayOf(2, 5, 8, 1, 4, 7) private const val ARRAY_SIZE = 10 private const val ZERO_CHAR = '0' fun largestMultipleOfThree(digits: IntArray): String { var sum = 0 val ds = IntArray(ARRAY_SIZE) for (d in digits) { ++ds[d] sum += d } while (sum % 3 != 0) { val n = if (sum % 3 == 1) m1 else m2 for (i in n) { if (ds[i] > 0) { --ds[i] sum -= i break } } } val sb = StringBuilder() for (i in ARRAY_SIZE - 1 downTo 0) { sb.append(ZERO_CHAR.plus(i).toString().repeat(ds[i])) } return if (sb.isNotEmpty() && sb[0] == ZERO_CHAR) "0" else sb.toString() }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,413
kotlab
Apache License 2.0
src/Day05.kt
halirutan
575,809,118
false
{"Kotlin": 24802}
class Cargo(input: List<String>) { data class Move(val quantity: Int, val from: Int, val to: Int) private val crates: List<MutableList<Char>> = List(9, init= { mutableListOf() }) private val moves: MutableList<Move> init { // Read in the cargo on all crates for (s in input) { if(s[1] == '1') break val chars =s.toCharArray() for ((crateNum, i) in (1 until chars.size step 4).withIndex()) { if (chars[i] != ' ') { crates[crateNum].add(chars[i]) } } } // Reverse so that bottom crates are at the beginning for (crate in crates) { crate.reverse() } // Read the moves moves = mutableListOf() for (s in input) { if (s.startsWith("move")) { val split = s.split(" ") moves.add(Move(split[1].toInt(), split[3].toInt()-1, split[5].toInt()-1)) } } } private fun applyMove(m: Move) { for (i in 1..m.quantity) { assert(crates[m.from].isNotEmpty()) crates[m.to].add(crates[m.from].last()) crates[m.from].removeLast() } } private fun applyMove2(m: Move) { val from = crates[m.from] assert(from.size >= m.quantity) val toMove = from.subList(from.size - m.quantity, from.size) crates[m.to].addAll(toMove) for (i in 1..m.quantity) { crates[m.from].removeLast() } } fun doRearranging() { for (m in moves) { applyMove(m) } } fun doRearranging2() { for (m in moves) { applyMove2(m) } } fun printCrates() { for (c in crates) { for (i in c) { print("[$i] ") } println() } } fun printMoves() { for (m in moves) { println(m) } } fun getTopCrates(): String { val builder = StringBuilder() for (c in crates) { if (c.isNotEmpty()) { builder.append(c.last()) } } return builder.toString() } } fun main() { val testInput = readInput("Day05_test") val realInput = readInput("Day05") val c = Cargo(realInput) c.doRearranging() c.printCrates() println(c.getTopCrates()) val c2 = Cargo(realInput) c2.doRearranging2() c2.printCrates() println(c2.getTopCrates()) }
0
Kotlin
0
0
09de80723028f5f113e86351a5461c2634173168
2,542
AoC2022
Apache License 2.0
src/main/kotlin/org/cryptobiotic/mixnet/VectorQ.kt
JohnLCaron
754,705,115
false
{"Kotlin": 363510, "Java": 246365, "Shell": 7749, "C": 5751, "JavaScript": 2517}
package org.cryptobiotic.mixnet import electionguard.core.* data class MatrixQ(val elems: List<VectorQ> ) { val nrows = elems.size val width = elems[0].nelems fun elem(row: Int, col: Int) = elems[row].elems[col] constructor(group: GroupContext, llist: List<List<ElementModQ>>): this(llist.map{ VectorQ(group, it) }) // right multiply fun rmultiply(colv: VectorQ) : List<ElementModQ> { require(colv.nelems == width) return elems.map{ row -> row.innerProduct(colv) } } fun invert(psi: Permutation) = MatrixQ(psi.invert(this.elems)) fun permute(psi: Permutation) = MatrixQ(psi.permute(this.elems)) } data class VectorQ(val group: GroupContext, val elems: List<ElementModQ> ) { val nelems = elems.size fun permute(psi: Permutation) = VectorQ(group, psi.permute(elems)) fun invert(psi: Permutation) = VectorQ(group, psi.invert(elems)) fun product(): ElementModQ { if (elems.isEmpty()) { group.ONE_MOD_Q } if (elems.count() == 1) { return elems[0] } return elems.reduce { a, b -> (a * b) } } fun sum(): ElementModQ { if (elems.isEmpty()) { group.ZERO_MOD_Q } if (elems.count() == 1) { return elems[0] } return elems.reduce { a, b -> (a + b) } } operator fun times(other: VectorQ): VectorQ { require(nelems == other.nelems) return VectorQ(group, List(nelems) { elems[it] * other.elems[it] }) } operator fun plus(other: VectorQ): VectorQ { require(nelems == other.nelems) return VectorQ(group, List(nelems) { elems[it] + other.elems[it] }) } fun timesScalar(scalar: ElementModQ): VectorQ { return VectorQ(group, List(nelems) { elems[it] * scalar }) } fun powScalar(scalar: ElementModP): VectorP { return VectorP(group, List(nelems) { scalar powP elems[it] }) } fun innerProduct(other: VectorQ): ElementModQ { return this.times(other).sum() } fun gPowP(): VectorP { return VectorP(group, List(nelems) { group.gPowP(elems[it]) }) } companion object { fun randomQ(group: GroupContext, n: Int): VectorQ { val elems = List(n) { group.randomElementModQ(minimum = 1) } return VectorQ(group, elems) } fun empty(group: GroupContext): VectorQ { return VectorQ(group, emptyList()) } } fun gPowP(vp: VectorQ): VectorP { return vp.gPowP() } fun shiftPush(elem0: ElementModQ): VectorQ { return VectorQ(group, List (this.nelems) { if (it == 0) elem0 else this.elems[it - 1] }) } } fun Prod(vp: VectorQ): ElementModQ { return vp.product() }
0
Kotlin
0
0
63de19eb8ca2fb2b2d3286213b71c71097ab1d85
2,770
egk-mixnet-vmn
MIT License
dataStructuresAndAlgorithms/src/main/java/dev/funkymuse/datastructuresandalgorithms/heap/AbstractHeap.kt
FunkyMuse
168,687,007
false
{"Kotlin": 1728251}
package dev.funkymuse.datastructuresandalgorithms.heap import java.util.Collections abstract class AbstractHeap<T> : Heap<T> { abstract fun compare(first: T, second: T): Int var elements: ArrayList<T> = ArrayList() override fun peek(): T? = elements.firstOrNull() private fun leftChildIndex(index: Int) = (2 * index) + 1 private fun rightChildIndex(index: Int) = (2 * index) + 2 private fun parentIndex(index: Int) = (index - 1) / 2 override fun insert(element: T) { elements.add(element) shiftUp(count - 1) } private fun shiftUp(index: Int) { var child = index var parent = parentIndex(child) while (child > 0 && compare(elements[child], elements[parent]) > 0) { Collections.swap(elements, child, parent) child = parent parent = parentIndex(child) } } override fun remove(): T? { if (isEmpty) return null Collections.swap(elements, 0, count - 1) val item = elements.removeAt(count - 1) shiftDown(0) return item } private fun shiftDown(index: Int) { var parent = index while (true) { val left = leftChildIndex(parent) val right = rightChildIndex(parent) var candidate = parent if (left < count && compare(elements[left], elements[candidate]) > 0) { candidate = left } if (right < count && compare(elements[right], elements[candidate]) > 0) { candidate = right } if (candidate == parent) { return } Collections.swap(elements, parent, candidate) // 8 parent = candidate } } override fun removeAt(index: Int): T? = when { index >= count -> null index == count - 1 -> elements.removeAt(index) else -> { Collections.swap(elements, index, count - 1) val item = elements.removeAt(count - 1) shiftDown(index) shiftUp(index) item } } private fun index(element: T, i: Int): Int? { if (i >= count) { return null } if (compare(element, elements[i]) > 0) { return null } if (element == elements[i]) { return i } val leftChildIndex = index(element, leftChildIndex(i)) if (leftChildIndex != null) return leftChildIndex val rightChildIndex = index(element, rightChildIndex(i)) if (rightChildIndex != null) return rightChildIndex return null } protected fun heapify(values: ArrayList<T>) { elements = values if (elements.isNotEmpty()) { (count / 2 downTo 0).forEach { shiftDown(it) } } } override fun getNthSmallestT(n: T): T? { var current = 1 while (!isEmpty) { val element = remove() if (current == n) { return element } current += 1 } return null } override fun merge(heap: AbstractHeap<T>) { elements.addAll(heap.elements) buildHeap() } private fun buildHeap() { if (elements.isNotEmpty()) { (count / 2 downTo 0).forEach { shiftDown(it) } } } override fun isMinHeap(): Boolean { if (isEmpty) return true (count / 2 - 1 downTo 0).forEach { val left = leftChildIndex(it) val right = rightChildIndex(it) if (left < count && compare(elements[left], elements[it]) < 0) { return false } if (right < count && compare(elements[right], elements[it]) < 0) { return false } } return true } override val count: Int get() = elements.count() }
0
Kotlin
92
771
e2afb0cc98c92c80ddf2ec1c073d7ae4ecfcb6e1
4,108
KAHelpers
MIT License
src/algorithms/MillerRabinPrimalityTest.kt
tpltn
119,588,847
false
null
package algorithms import java.util.* /** * Тест простоты Миллера-Рабина * @return true, если число вероятно простое */ fun millerRabinPrimalityTest(n: Int, rounds: Int = Math.log(n.toDouble()).toInt()): Boolean { if (n % 2 == 0) { return false } val (s, u) = extractPowerOfTwo(n - 1) for (r in 1..rounds) { // проверяем a как свидетеля простоты n val a = (2..n).random() var x = powMod(a.toLong(), u.toLong(), n.toLong()).toInt() if (x == 1 || x == n - 1) { continue } for (i in 1 until s) { x = powMod(x.toLong(), 2, n.toLong()).toInt() if (x == 1) { return false } if (x == n - 1) { continue } return false } } return true } /** * Приведение числа к виду n = 2^s * u * @return <s, u> */ fun extractPowerOfTwo(n: Int): Pair<Int, Int> { var s = 0 var u = n while (u % 2 == 0) { s++ u /= 2 } return Pair(s, u) } /** * (0..10) => between 0 and 9 inclusive */ fun ClosedRange<Int>.random() = Random().nextInt(endInclusive - start) + start
0
Kotlin
1
0
2257a6a968bb8440f8a2a65a5fd31ff0fa5a5e8f
1,298
ads
The Unlicense
kotlin/src/com/daily/algothrim/leetcode/medium/MaxArea.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode.medium /** * 11. 盛最多水的容器 * 给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。 */ class MaxArea { companion object { @JvmStatic fun main(args: Array<String>) { println(MaxArea().maxArea(intArrayOf(1, 8, 6, 2, 5, 4, 8, 3, 7))) println(MaxArea().maxArea(intArrayOf(1, 1))) println(MaxArea().maxArea(intArrayOf(4, 3, 2, 1, 4))) println(MaxArea().maxArea(intArrayOf(1, 2, 1))) } } // [1,8,6,2,5,4,8,3,7] fun maxArea(height: IntArray): Int { var start = 0 var end = height.size - 1 var max = 0 var min = Int.MIN_VALUE while (start < end) { val startValue = height[start] val endValue = height[end] val minValue = Math.min(startValue, endValue) if (minValue > min) { min = minValue max = Math.max(max, (end - start) * min) } if (startValue <= min) { start++ } else { end-- } } return max } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
1,388
daily_algorithm
Apache License 2.0
exercises/practice/largest-series-product/.meta/src/reference/kotlin/LargestSeriesProduct.kt
exercism
47,675,865
false
{"Kotlin": 382097, "Shell": 14600}
import java.lang.Math.max class Series(private val digits: String) { init { require(digits.all { it.isDigit() }) } fun getLargestProduct(span: Int): Long { require(span >= 0) require(digits.length >= span) if(digits.isEmpty()) { return 1 } return calculateRec(digits.map { it.intValue() }, span, 0) } private tailrec fun calculateRec(digits: List<Int>, span: Int, maxSoFar: Long): Long { val currentProduct = digits.subList(0, span).prod() val newMax = kotlin.math.max(currentProduct, maxSoFar) if(digits.size == span) { //since we won't be checking 'remainders' of the list, the end condition is simply when the size is the same as the span return newMax } return calculateRec(digits.tail(), span, newMax) } } fun Char.intValue() : Int { if(!this.isDigit()) { throw IllegalArgumentException("Char ${this} is not a legal DEC character") } return this.intDiff('0') } fun Char.intDiff(other: Char) = this.code - other.code fun List<Int>.prod() : Long = this.fold(1L) {productSoFar, item -> item*productSoFar} fun <T> List<T>.tail() = this.subList(1, this.size)
51
Kotlin
190
199
7f1c7a11cfe84499cfef4ea2ecbc6c6bf34a6ab9
1,229
kotlin
MIT License
src/test/kotlin/aoc/Day8.kt
Lea369
728,236,141
false
{"Kotlin": 36118}
package aoc_2023 import org.junit.jupiter.api.Nested import java.math.BigInteger import java.nio.file.Files import java.nio.file.Paths import java.util.stream.Collectors import kotlin.test.Test import kotlin.test.assertEquals class Day8 { data class Noeud(val origin: String, val destination: Pair<String, String>) data class NextExit(val index: BigInteger, val originExit: String) data class Periodicity(val start: Long, val period: Long) @Nested internal inner class Day8Test { private val day8: Day8 = Day8() @Test fun testPart1() { assertEquals(6, day8.solveP1("./src/test/resources/2023/inputExample8")) } @Test fun testPart2() { assertEquals(BigInteger.valueOf(6L), day8.solveP2("./src/test/resources/2023/input8")) } } private fun solveP1(s: String): Int { val instructions: String = Files.lines(Paths.get(s)).collect(Collectors.toList())[0] val nodes: List<Noeud> = Files.lines(Paths.get(s)).collect(Collectors.toList()).filterIndexed { index, _ -> index >= 2 } .map { Noeud( it.split(" = ")[0], it.split(" = (")[1].split(", ")[0] to it.split(" = (")[1].split(", ")[1].replace(")", "") ) } var result = 0 var origin = "AAA" while (origin.last() != 'Z') { val instruction = instructions[result % instructions.length] origin = if (instruction == 'L') nodes.first { it.origin == origin }.destination.first else nodes.first { it.origin == origin }.destination.second result++ } return result } private fun solveP2(s: String): BigInteger { val instructions: String = Files.lines(Paths.get(s)).collect(Collectors.toList())[0] val nodes: List<Noeud> = Files.lines(Paths.get(s)).collect(Collectors.toList()).filterIndexed { index, _ -> index >= 2 } .map { Noeud( it.split(" = ")[0], it.split(" = (")[1].split(", ")[0] to it.split(" = (")[1].split(", ")[1].replace(")", "") ) } //return BigInteger.valueOf(22411)* BigInteger.valueOf(18727)* BigInteger.valueOf(24253)* BigInteger.valueOf(14429)* BigInteger.valueOf(16271)* BigInteger.valueOf(20569) return findLCMOfListOfNumbers(nodes.filter { it.origin.last() == 'A' }.map {findNextExit(instructions, nodes, NextExit(BigInteger.ZERO, it.origin)).index }) } private fun findNextExit(instructions: String, nodes: List<Noeud>, originExit: NextExit): NextExit { var result = originExit.index var origin = originExit.originExit while (origin.last() != 'Z' || result == originExit.index) { val instruction = instructions[result.toInt() % instructions.length] origin = if (instruction == 'L') nodes.first { it.origin == origin }.destination.first else nodes.first { it.origin == origin }.destination.second result++ } return NextExit(result, origin) } fun findLCM(a: BigInteger, b: BigInteger): BigInteger { val larger = if (a > b) a else b val maxLcm = a * b var lcm = larger while (lcm <= maxLcm) { if (lcm % a == BigInteger.ZERO && lcm % b == BigInteger.ZERO) { return lcm } lcm += larger } return maxLcm } fun findLCMOfListOfNumbers(numbers: List<BigInteger>): BigInteger { var result = numbers[0] for (i in 1 until numbers.size) { result = findLCM(result, numbers[i]) } return result } }
0
Kotlin
0
0
1874184df87d7e494c0ff787ea187ea3566fbfbb
3,828
AoC
Apache License 2.0
src/Day04_part2.kt
yashpalrawat
573,264,560
false
{"Kotlin": 12474}
fun main() { val input = readInput("Day04") /* basically check if one pair is included within other pair Pair(a,b) Pair(c,d) the are inclusive if c >= a && d <= b a >= c && b <= d * */ val result = input.sumOf { val firstPair = it.split(",")[0].toIntPair() val secondPair = it.split(",")[1].toIntPair() countIfOverlap(firstPair, secondPair) } print(result) } fun countIfOverlap(firstAssignment: Pair<Int, Int>, secondAssignment: Pair<Int, Int>) : Int { val result = (secondAssignment.first in firstAssignment.first..firstAssignment.second) || (secondAssignment.second in firstAssignment.first..firstAssignment.second) || (firstAssignment.first in secondAssignment.first..secondAssignment.second) || (firstAssignment.second in secondAssignment.first..secondAssignment.second) return if(result) { 1 } else { 0 } }
0
Kotlin
0
0
78a3a817709da6689b810a244b128a46a539511a
970
code-advent-2022
Apache License 2.0
src/main/kotlin/dp/MinDecomp.kt
yx-z
106,589,674
false
null
package dp import util.min import kotlin.math.roundToInt // given an integer, decompose it with combinations of 1, +, and * // report the minimum amount of 1s needed // ex. 14 = (1 + 1) * ((1 + 1 + 1) * (1 + 1) + 1) -> 8 fun main(args: Array<String>) { val ints = intArrayOf(14, 21) ints.forEach { println(it.minDecomp()) } } fun Int.minDecomp(): Int { // dp[i] = minimum amount of 1s that make up i // dp[i] = min(dp[a] + dp[b], dp[c] + dp[d]), for all possible a * b == i, c + d == i val dp = IntArray(this + 1) { it } // an upper bound is simply adding 1s, making `it` 1s for (i in 2..this) { for (a in 2..Math.sqrt(i.toDouble()).roundToInt()) { if (i % a == 0) { val b = i / a dp[i] = min(dp[a] + dp[b], dp[i]) } } for (c in 1..i / 2) { dp[i] = min(dp[c] + dp[i - c], dp[i]) } } return dp[this] }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
837
AlgoKt
MIT License
src/main/kotlin/me/peckb/aoc/_2020/calendar/day11/Day11.kt
peckb1
433,943,215
false
{"Kotlin": 956135}
package me.peckb.aoc._2020.calendar.day11 import javax.inject.Inject import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory import java.util.* import kotlin.math.max import kotlin.math.min @Suppress("LocalVariableName") class Day11 @Inject constructor( private val generatorFactory: InputGeneratorFactory, ) { fun partOne(filename: String) = generatorFactory.forFile(filename).read { input -> val seatingArea = setupSeats(input) runSeating( seatingArea, { y, x -> directNeighborsAreEmpty(seatingArea, y, x) }, { y, x -> tooManyDirectNeighbors(seatingArea, y, x) }, ) countOccupiedSeats(seatingArea) } fun partTwo(filename: String) = generatorFactory.forFile(filename).read { input -> val seatingArea = setupSeats(input) runSeating( seatingArea, { y, x -> lineNeighborsAreEmpty(seatingArea, y, x) }, { y, x -> tooManyLineNeighbors(seatingArea, y, x) }, ) countOccupiedSeats(seatingArea) } private fun setupSeats(input: Sequence<String>): Array<Array<Char>> { val data = input.toList() val seatingArea = Array(data.size) { Array(data.first().length) { FLOOR } } data.forEachIndexed { y, row -> row.forEachIndexed { x, location -> seatingArea[y][x] = location } } return seatingArea } private fun runSeating( seatingArea: Array<Array<Char>>, emptyCheck: (Int, Int) -> Boolean, occupiedCheck: (Int, Int) -> Boolean, ) { do { val seatsToOccupy = mutableListOf<Location>() val seatsToVacate = mutableListOf<Location>() seatingArea.forEachIndexed { y, row -> row.forEachIndexed { x, loc -> if (loc == EMPTY && emptyCheck(y, x)) { seatsToOccupy.add(Location(y, x)) } if (loc == OCCUPIED && occupiedCheck(y, x)) { seatsToVacate.add(Location(y, x)) } } } seatsToOccupy.forEach { (y, x) -> seatingArea[y][x] = OCCUPIED } seatsToVacate.forEach { (y, x) -> seatingArea[y][x] = EMPTY } val changesMade = seatsToOccupy.isNotEmpty() || seatsToVacate.isNotEmpty() } while(changesMade) } private fun countOccupiedSeats(seatingArea: Array<Array<Char>>): Int { return seatingArea.sumOf { row -> row.count { it == OCCUPIED } } } private fun directNeighborsAreEmpty(seatingArea: Array<Array<Char>>, y: Int, x: Int): Boolean { val (minY, maxY, minX, maxX) = ranges(seatingArea, y, x) return (minY..maxY).none { y1 -> (minX .. maxX).any { x1 -> seatingArea[y1][x1] == OCCUPIED } } } private fun tooManyDirectNeighbors(seatingArea: Array<Array<Char>>, y: Int, x: Int): Boolean { val (minY, maxY, minX, maxX) = ranges(seatingArea, y, x) val occupiedNeighbors = (minY..maxY).sumOf { y1 -> (minX .. maxX).count { x1 -> seatingArea[y1][x1] == OCCUPIED } } - 1 // we don't enter tooManyNeighbors unless the seat is occupied, so we'll be one extra seat over return occupiedNeighbors >= 4 } private fun lineNeighborsAreEmpty(seatingArea: Array<Array<Char>>, y: Int, x: Int): Boolean { return findSeats(seatingArea, y, x).none { it == OCCUPIED } } private fun tooManyLineNeighbors(seatingArea: Array<Array<Char>>, y: Int, x: Int): Boolean { return findSeats(seatingArea, y, x).count { it == OCCUPIED } >= 5 } private fun findSeats(seatingArea: Array<Array<Char>>, y: Int, x: Int): List<Char> { val N = findFirstSeat(seatingArea, y, x, { yDelta -> yDelta - 1 }, { xDelta -> xDelta }) val NE = findFirstSeat(seatingArea, y, x, { yDelta -> yDelta - 1 }, { xDelta -> xDelta + 1 }) val E = findFirstSeat(seatingArea, y, x, { yDelta -> yDelta }, { xDelta -> xDelta + 1 }) val SE = findFirstSeat(seatingArea, y, x, { yDelta -> yDelta + 1 }, { xDelta -> xDelta + 1 }) val S = findFirstSeat(seatingArea, y, x, { yDelta -> yDelta + 1 }, { xDelta -> xDelta }) val SW = findFirstSeat(seatingArea, y, x, { yDelta -> yDelta + 1 }, { xDelta -> xDelta - 1 }) val W = findFirstSeat(seatingArea, y, x, { yDelta -> yDelta }, { xDelta -> xDelta - 1 }) val NW = findFirstSeat(seatingArea, y, x, { yDelta -> yDelta - 1 }, { xDelta -> xDelta - 1 }) return listOfNotNull(N, NE, E, SE, S, SW, W, NW) } private fun findFirstSeat( seatingArea: Array<Array<Char>>, y: Int, x: Int, yDelta: (Int) -> Int, xDelta: (Int) -> Int ): Char? { var newY = yDelta(y) var newX = xDelta(x) while(newY in (seatingArea.indices) && newX in (0 until seatingArea[newY].size)) { if (seatingArea[newY][newX] != FLOOR) return seatingArea[newY][newX] newY = yDelta(newY) newX = xDelta(newX) } return null } private fun ranges(seatingArea: Array<Array<Char>>, y: Int, x: Int): Ranges { val minY = max(y - 1, 0) val maxY = min(y + 1, seatingArea.size - 1) val minX = max(x - 1, 0) val maxX = min(x + 1, seatingArea[y].size - 1) return Ranges(minY, maxY, minX, maxX) } data class Ranges(val minY: Int, val maxY: Int, val minX: Int, val maxX: Int) data class Location(val y: Int, val x: Int) companion object { private const val FLOOR = '.' private const val EMPTY = 'L' private const val OCCUPIED = '#' } }
0
Kotlin
1
3
2625719b657eb22c83af95abfb25eb275dbfee6a
5,322
advent-of-code
MIT License
src/test/kotlin/io/github/aarjavp/aoc/day14/Day14Test.kt
AarjavP
433,672,017
false
{"Kotlin": 73104}
package io.github.aarjavp.aoc.day14 import io.github.aarjavp.aoc.day14.Day14.Rule import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.longs.shouldBeExactly import io.kotest.matchers.maps.shouldContainExactly import org.junit.jupiter.api.Test class Day14Test { val solution = Day14() val testInput = """ NNCB CH -> B HH -> N CB -> H NH -> C HB -> C HC -> B HN -> C NN -> C BH -> H NC -> B NB -> B BN -> B BB -> N BC -> B CC -> N CN -> C """.trimIndent() @Test fun testParse() { val state = solution.parseState(testInput.lineSequence()) state.rules shouldContainExactlyInAnyOrder listOf( Rule("CH", 'B'), Rule("HH", 'N'), Rule("CB", 'H'), Rule("NH", 'C'), Rule("HB", 'C'), Rule("HC", 'B'), Rule("HN", 'C'), Rule("NN", 'C'), Rule("BH", 'H'), Rule("NC", 'B'), Rule("NB", 'B'), Rule("BN", 'B'), Rule("BB", 'N'), Rule("BC", 'B'), Rule("CC", 'N'), Rule("CN", 'C'), ) state.pairCounts shouldContainExactly mapOf( "NN" to 1, "NC" to 1, "CB" to 1 ) state.characterCounts shouldContainExactly mapOf( 'N' to 2, 'C' to 1, 'B' to 1 ) } @Test fun testApplySteps() { val state = solution.parseState(testInput.lineSequence()) state.applyRules() //1 state.characterCounts shouldContainExactly mapOf( 'N' to 2, 'C' to 2, 'B' to 2, 'H' to 1 ) repeat(9) { state.applyRules() } // including above, result will be after 10 steps state.characterCounts shouldContainExactly mapOf( 'B' to 1749, 'C' to 298, 'H' to 161, 'N' to 865 ) } @Test fun testPart1() { val actual = solution.part1(testInput.lineSequence()) actual shouldBeExactly 1588 } @Test fun testPart2() { val actual = solution.part2(testInput.lineSequence()) actual shouldBeExactly 2188189693529 } }
0
Kotlin
0
0
3f5908fa4991f9b21bb7e3428a359b218fad2a35
2,345
advent-of-code-2021
MIT License
src/Day01.kt
mkfsn
573,042,358
false
{"Kotlin": 29625}
fun main() { fun makeGroups(input: List<String>): List<Int> { return input.chunkedBy { ele -> ele == "" }.map { nums -> nums.sumOf { it.toInt() } } } fun part1(input: List<String>): Int { return makeGroups(input).max() } fun part2(input: List<String>): Int { return makeGroups(input).sortedDescending().take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
8c7bdd66f8550a82030127aa36c2a6a4262592cd
651
advent-of-code-kotlin-2022
Apache License 2.0
src/day7/Day7.kt
crmitchelmore
576,065,911
false
{"Kotlin": 115199}
package day7 import helpers.ReadFile class File { var size: Int = 0 var parent: File? = null var contents: MutableMap<String, File>? = null constructor(size: Int, parent: File?) { if (size == 0) { contents = mutableMapOf() } this.parent = parent this.size = size } } class Day7 { val lines = ReadFile.named("src/day7/input.txt").drop(1) // val lines = listOf( // "$ ls", // "dir a", // "14848514 b.txt", // "8504156 c.dat", // "dir d", // "$ cd a", // "$ ls", // "dir e", // "29116 f", // "2557 g", // "62596 h.lst", // "$ cd e", // "$ ls", // "584 i", // "$ cd ..", // "$ cd ..", // "$ cd d", // "$ ls", // "4060174 j", // "8033020 d.log", // "5626152 d.ext", // "7214296 k" // ) var root = File(size = 0, parent = null) var currentDir = root fun result1(): String { for (line in lines) { val chunks = line.split(" ") println(line) if (line.startsWith("$ ")) { val cmd = chunks[1] if (cmd == "cd") { val dir = chunks[2] if (dir == "..") { currentDir = currentDir.parent!! } else if (currentDir.contents!![dir] == null) { throw Exception("no such directory") } else { currentDir = currentDir.contents!![dir]!! } } else if (cmd == "ls") { //Do nothing } else { throw Exception("Unknown command $cmd") } } else { val size = if (chunks[0] == "dir") 0 else chunks[0].toInt() currentDir.contents!![chunks[1]] = File(size, parent = currentDir) } } val totalSpace = 70000000 val usedSpace = calculateDirSize(root) val freeSpace = totalSpace - usedSpace val requiredSpace = 30000000 val whichDelete = allDirs(root, listOf()).sortedBy { it.size }.first { it.size + freeSpace >= requiredSpace } return whichDelete.size.toString() // val dirs = dirsWithAtMost100k(root, listOf()) // println(dirs) // return dirs.sumOf { it.size }.toString() } fun allDirs(f: File, dirs: List<File>): List<File> { var moreDirs = dirs.toMutableList() f.contents!!.values.forEach() { if (it.contents != null) { moreDirs.add(it) moreDirs.addAll(allDirs(it, dirs)) } } return moreDirs } fun dirsWithAtMost100k(f: File, dirs: List<File>): List<File> { var moreDirs = dirs.toMutableList() f.contents!!.values.forEach() { if (it.contents != null) { if (it.size <= 100000) { moreDirs.add(it) } moreDirs.addAll(dirsWithAtMost100k(it, dirs)) } } return moreDirs } fun calculateDirSize(f: File): Int { if (f.size == 0) { f.size = f.contents!!.values.fold(0, { acc, file -> acc + calculateDirSize(file) }) return f.size } return f.size } }
0
Kotlin
0
0
fd644d442b5ff0d2f05fbf6317c61ee9ce7b4470
3,316
adventofcode2022
MIT License
Algorithms/Warmup/A Very Big Sum/Solution.kt
ahmed-mahmoud-abo-elnaga
449,443,709
false
{"Kotlin": 14218}
/* Problem: https://www.hackerrank.com/challenges/a-very-big-sum/problem Kotlin Language Version Tool Version : Android Studio Thoughts : 1. Store all the input numbers in an array of size n. 2. Let the sum of all the input numbers be s. Initialize s to 0. Ensure that storage width of the data type of s is 64 bit. 3. Start iterating the elments of an array in a loop 3.1 Let the current element be c. 3.2 Increment s by c. 3.3 Move to next element in the array and repeat steps 3.1 through 3.2. 4. Print s. Time Complexity: O(n) //A loop is required which iterates through n elements in the array to create their sum. Space Complexity: O(n) //Space complexity doesn't matches optimal O(1) solution */ object Main { /* * Complete the 'aVeryBigSum' function below. * * The function is expected to return a LONG_INTEGER. * The function accepts LONG_INTEGER_ARRAY ar as parameter. */ fun aVeryBigSum(ar: Array<Long>): Long { // Write your code here var bigSum: Long = 0L ar.forEach { item -> bigSum += item } return bigSum } fun main(args: Array<String>) { val arCount = readLine()!!.trim().toInt() val ar = readLine()!!.trimEnd().split(" ").map { it.toLong() }.toTypedArray() val result = aVeryBigSum(ar) println(result) } }
0
Kotlin
1
1
a65ee26d47b470b1cb2c1681e9d49fe48b7cb7fc
1,385
HackerRank
MIT License
Collection/List/part06.kt
scp504677840
133,541,707
false
null
package part06 import java.util.TreeSet fun main(args: Array<String>) { /*val treeSet = TreeSet<String>() treeSet.add("adbbcc") treeSet.add("abbabc") treeSet.add("acbcc") treeSet.add("abbc") treeSet.add("abcc") val iterator = treeSet.iterator() while (iterator.hasNext()) { println(iterator.next()) }*/ /* //元素自身具备比较性,实现Comparable接口即可。 val treeSet = TreeSet<Student>() treeSet.add(Student("aa", 11)) treeSet.add(Student("bb", 22)) treeSet.add(Student("cc", 8)) treeSet.add(Student("dd", 6)) treeSet.add(Student("ee", 6)) val iterator = treeSet.iterator() while (iterator.hasNext()) { val student = iterator.next() println("student:${student.name}--${student.age}") }*/ //当元素不具备比较性,我们可以传入自定义比较器 val treeSet = TreeSet<Student>(MyCompare()) treeSet.add(Student("aa", 11)) treeSet.add(Student("bb", 22)) treeSet.add(Student("cc", 8)) treeSet.add(Student("dd", 6)) treeSet.add(Student("ee", 6)) val iterator = treeSet.iterator() while (iterator.hasNext()) { val student = iterator.next() println("student:${student.name}--${student.age}") } } /** * 实现Comparable接口,实现比较方法 */ private data class Student constructor(var name: String, var age: Int) : Comparable<Student> { override fun compareTo(other: Student): Int { if (age > other.age) return 1 //注意:比较了主要条件以后,需要比较次要条件。 if (age == other.age) { return name.compareTo(other.name) } return -1 } } /** * 自定义比较器(推荐这种比较形式) */ private class MyCompare : Comparator<Student> { override fun compare(o1: Student, o2: Student): Int { val compareTo = o1.age.compareTo(o2.age) if (compareTo == 0) { return o1.name.compareTo(o2.name) } return compareTo } }
0
Kotlin
0
0
36f9b85bf8d955b12a69684fc013125a26cae846
2,051
JavaKotlin
Apache License 2.0
src/main/kotlin/arraysandstrings/NextClosestTime.kt
e-freiman
471,473,372
false
{"Kotlin": 78010}
package arraysandstrings fun isValid(arr: IntArray): Boolean { var hour = arr[0] * 10 + arr[1] var minute = arr[2] * 10 + arr[3] return hour < 24 && minute < 60 } fun totalMinutes(arr: IntArray): Int { var hour = arr[0] * 10 + arr[1] var minute = arr[2] * 10 + arr[3] return hour * 60 + minute } fun diff(minutes1: Int, minutes2: Int): Int { return when { minutes2 > minutes1 -> minutes2 - minutes1 minutes2 > minutes1 -> 60*24 - minutes1 + minutes2 else -> 60*24 } } var base: Int = 0 var baseArr: IntArray = intArrayOf() var minDiff = 60*24 + 1 var res: IntArray = intArrayOf() fun Char.digitToInt() = this.toInt() - '0'.toInt() fun traverse(arr: IntArray, start: Int) { if (start > arr.lastIndex) { if (isValid(arr)) { val curDiff = diff(base, totalMinutes(arr)) if (curDiff in 1 until minDiff) { minDiff = curDiff res = arr } //println(arr.contentToString()) } return } for (j in baseArr.indices) { val newArr = arr.clone() newArr[start] = baseArr[j] traverse(newArr, start + 1) } } fun nextClosestTime(time: String): String { val arr = intArrayOf( time[0].digitToInt(), time[1].digitToInt(), time[3].digitToInt(), time[4].digitToInt()) base = totalMinutes(arr) baseArr = arr.clone() traverse(arr, 0) return "${res[0]}${res[1]}:${res[2]}${res[3]}" } fun main() { println(nextClosestTime("19:34")) }
0
Kotlin
0
0
fab7f275fbbafeeb79c520622995216f6c7d8642
1,578
LeetcodeGoogleInterview
Apache License 2.0
bench/algorithm/pidigits/2n.kt
yonillasky
509,064,681
true
{"C#": 228581, "Rust": 201439, "Common Lisp": 142537, "Zig": 72107, "D": 66591, "Java": 60453, "C": 54246, "Go": 51605, "Kotlin": 48614, "Python": 45008, "TypeScript": 44466, "Dart": 40852, "OCaml": 38288, "Julia": 36099, "Chapel": 34726, "Crystal": 34498, "C++": 33006, "JavaScript": 32368, "Nim": 30426, "Odin": 30083, "Vue": 26491, "Haxe": 23709, "V": 23352, "Swift": 20990, "Racket": 20474, "Fortran": 19285, "Ruby": 18347, "Pony": 9939, "Lua": 8189, "Wren": 7547, "Elixir": 6620, "Perl": 5588, "Hack": 4541, "Raku": 4441, "PHP": 3343, "Haskell": 2823, "SCSS": 503, "Shell": 341, "HTML": 53}
/* The Computer Language Benchmarks Game https://salsa.debian.org/benchmarksgame-team/benchmarksgame/ Based on Java version (1) by <NAME> Contributed by <NAME> Modified by hanabi1224 */ import com.soywiz.kbignum.* fun main(args: Array<String>) { val L = 10 var n = args[0].toInt() var j = 0 val digits = PiDigitSpigot() while (n > 0) { if (n >= L) { for (i in 0..L - 1) print(digits.next()) j += L } else { for (i in 0..n - 1) print(digits.next()) for (i in n..L - 1) print(" ") j += n } print("\t:") println(j) n -= L } } internal class PiDigitSpigot { var z: Transformation var x: Transformation var inverse: Transformation init { z = Transformation(1, 0, 0, 1) x = Transformation(0, 0, 0, 0) inverse = Transformation(0, 0, 0, 0) } operator fun next(): Int { val y = digit() if (isSafe(y)) { z = produce(y) return y } else { z = consume(x.next()) return next() } } fun digit(): Int { return z.extract(3) } fun isSafe(digit: Int): Boolean { return digit == z.extract(4) } fun produce(i: Int): Transformation { return inverse.qrst(10, -10 * i, 0, 1).compose(z) } fun consume(a: Transformation): Transformation { return z.compose(a) } } internal class Transformation { var q: BigInt var r: BigInt var s: BigInt var t: BigInt var k: Int = 0 constructor(q: Int, r: Int, s: Int, t: Int) { this.q = q.bi this.r = r.bi this.s = s.bi this.t = t.bi k = 0 } constructor(q: BigInt, r: BigInt, s: BigInt, t: BigInt) { this.q = q this.r = r this.s = s this.t = t k = 0 } operator fun next(): Transformation { k++ q = k.bi r = (4 * k + 2).bi s = 0.bi t = (2 * k + 1).bi return this } fun extract(j: Int): Int { val bigj = j.bi val numerator = q.times(bigj).plus(r) val denominator = s.times(bigj).plus(t) return numerator.div(denominator).toInt() } fun qrst(q: Int, r: Int, s: Int, t: Int): Transformation { this.q = q.bi this.r = r.bi this.s = s.bi this.t = t.bi k = 0 return this } fun compose(a: Transformation): Transformation { return Transformation( q.times(a.q), q.times(a.r).plus(r.times(a.t)), s.times(a.q).plus(t.times(a.s)), s.times(a.r).plus(t.times(a.t)) ) } }
0
C#
0
0
f72b031708c92f9814b8427b0dd08cb058aa6234
2,790
Programming-Language-Benchmarks
MIT License
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[28]实现 strStr().kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//实现 strStr() 函数。 // // 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如 //果不存在,则返回 -1。 // // 示例 1: // // 输入: haystack = "hello", needle = "ll" //输出: 2 // // // 示例 2: // // 输入: haystack = "aaaaa", needle = "bba" //输出: -1 // // // 说明: // // 当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。 // // 对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。 // Related Topics 双指针 字符串 // 👍 669 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun strStr(haystack: String, needle: String): Int { //双指针 时间复杂度 O(N) if(needle.isEmpty()) return 0 var i = 0 var j = 0 while(i<haystack.length && j<needle.length){ if(haystack[i]==needle[j]) { i++ j++ } else { i=i-j+1 j=0 } } return if(j==needle.length) i-needle.length else -1 } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,336
MyLeetCode
Apache License 2.0
src/medium/_31NextPermutation.kt
ilinqh
390,190,883
false
{"Kotlin": 382147, "Java": 32712}
package medium class _31NextPermutation { class Solution { fun nextPermutation(nums: IntArray) { var i = nums.size - 2 while (i >= 0 && nums[i] >= nums[i + 1]) { i-- } if (i >= 0) { var j = nums.size - 1 while (j >= 0 && nums[i] >= nums[j]) { j-- } swap(nums, i, j) } reverse(nums, i + 1) } private fun swap(nums: IntArray, i: Int, j: Int) { val temp = nums[i] nums[i] = nums[j] nums[j] = temp } private fun reverse(nums: IntArray, start: Int) { var left = start var right = nums.size - 1 while (left < right) { swap(nums, left, right) left++ right-- } } } // Best class BestSolution { fun nextPermutation(nums: IntArray): Unit { var needChange = -1 for (i in nums.size - 1 downTo 1) { if (nums[i - 1] < nums[i]) { needChange = i - 1 break } } if (needChange == -1) { nums.reverse() return } var firstMaxChang = -1 for (i in nums.size - 1 downTo needChange + 1) { if (nums[i] > nums[needChange]) { firstMaxChang = i break } } nums.swap(needChange, firstMaxChang) var left = needChange + 1 var right = nums.size - 1 while (left < right) { nums.swap(left, right) left++ right-- } } private fun IntArray.swap(i: Int, j: Int) { if (i < 0 || j < 0 || i >= this.size || j >= this.size) { return } val temp = this[i] this[i] = this[j] this[j] = temp } } }
0
Kotlin
0
0
8d2060888123915d2ef2ade293e5b12c66fb3a3f
2,116
AlgorithmsProject
Apache License 2.0
app/src/main/java/com/denox/yugitournament/algorithm/Player.kt
AlleMazza
479,006,331
false
{"Kotlin": 46651}
package com.denox.yugitournament.algorithm import com.denox.yugitournament.database.PlayerEntry class Player(var seed: Int, var name: String = "placeholder") { private var matchHistory = mutableListOf<Pair<Int, Int>?>() // 0 loss 1 draw 3 win // seed -1 = bye var isDropped = false var randomSeed = 0 fun points() = matchHistory.sumOf { it?.second ?: 0 } // dropped players count as having lost all following rounds, don't know if it is the right way fun winRate(numberOfRounds: Int = matchHistory.size): Double { val hadBye = receivedBye() return (matchHistory.sumOf { it?.second ?: 0 } - hadBye*3) / 3.0 / (numberOfRounds-hadBye) } fun getResultAgainst(seed: Int) = matchHistory.firstOrNull { (it?.first ?: -999) == seed }?.second fun removeResultAgainst(seed: Int) = matchHistory.removeAt(matchHistory.indexOfFirst { it?.first == seed }) fun dropAllResults() = matchHistory.clear() fun dropLastResult() = matchHistory.removeLast() fun getResultsList() = matchHistory.toList() fun getMatchHistorySize() = matchHistory.size fun changeResult(seed: Int, result: Int) { val ix = matchHistory.indexOfFirst { it?.first == seed } if (ix < 0) { nextMatchResult(seed, result) } else { matchHistory[matchHistory.indexOfFirst { it?.first == seed }] = Pair(seed, result) } } fun nextMatchResult(seed: Int, result: Int) { matchHistory.add(Pair(seed, result)) } fun skipRound() { matchHistory.add(null) } fun receivedBye() = matchHistory.count { (it?.first ?: 0) < 0 } private fun skippedRounds(): List<Int> { val list = mutableListOf<Int>() for (i in 0 until matchHistory.size) { if (matchHistory[i] == null) { list.add(i) } } return list } private fun matchHistoryToPlainList(): List<Int> { val list = mutableListOf<Int>() matchHistory.forEach { result -> if (result != null) { list.add(result.first) list.add(result.second) } } return list } private fun matchHistoryFromPlainListAndSkippedRounds(list: List<Int>, skippedRounds: List<Int>) { matchHistory = mutableListOf() var skipped = 0 for (i in 0 until (list.size/2 + skippedRounds.size)) { if (skipped < skippedRounds.size && skippedRounds.contains(i)) { matchHistory.add(null) ++skipped } else { matchHistory.add(Pair(list[i*2], list[i*2+1])) } } } fun toPlayerEntry(tournamentId: Int) = PlayerEntry( tournamentId, seed, name, matchHistoryToPlainList(), isDropped, randomSeed, skippedRounds(), ) companion object { fun fromPlayerEntry(pe: PlayerEntry) = Player( pe.seed, pe.name ).apply { matchHistoryFromPlainListAndSkippedRounds(pe.matchHistory, pe.skippedRounds) isDropped = pe.isDropped randomSeed = pe.randomSeed } } }
0
Kotlin
0
0
5c418bb2023acd76715d2d97f5731a1ef0d0679d
3,236
YugiTournament
MIT License
src/Day06.kt
eo
574,058,285
false
{"Kotlin": 45178}
// https://adventofcode.com/2022/day/6 fun main() { fun findMarker(input: String, markerSize: Int): Int? { val markerCharacters = input .take(markerSize - 1) .groupingBy { it } .eachCount() .toMutableMap() for ((index, newChar) in input.withIndex().drop(markerSize - 1)) { val oldChar = input[index - markerSize + 1] markerCharacters[newChar] = markerCharacters.getOrDefault(newChar, 0) + 1 if (markerCharacters.size == markerSize) return index + 1 markerCharacters[oldChar] = markerCharacters.getOrDefault(oldChar, 0) - 1 markerCharacters.remove(oldChar, 0) } return null } fun part1(input: String): Int? { return findMarker(input, 4) } fun part2(input: String): Int? { return findMarker(input, 14) } val input = readText("Input06") println("Part 1: " + part1(input)) println("Part 2: " + part2(input)) }
0
Kotlin
0
0
8661e4c380b45c19e6ecd590d657c9c396f72a05
1,031
aoc-2022-in-kotlin
Apache License 2.0
src/Day05.kt
ty-garside
573,030,387
false
{"Kotlin": 75779}
// Day 05 - Supply Stacks // https://adventofcode.com/2022/day/5 fun main() { fun Iterator<String>.initStacks() = mutableListOf<ArrayDeque<Char>>().apply { while (hasNext()) { val line = next() if (line.isBlank()) break line.chunked(4) { it.trim() } .forEachIndexed { index, it -> if (it.startsWith('[') && it.endsWith(']')) { while (size <= index) this += ArrayDeque<Char>() this[index].addLast(it[1]) } } } }.toList() val regex = Regex("move (\\d+) from (\\d+) to (\\d+)") fun Iterator<String>.executeMoves(stacks: List<ArrayDeque<Char>>, multi: Boolean) { while (hasNext()) { val (move, from, to) = regex.matchEntire(next())!!.destructured repeat(move.toInt()) { stacks[to.toInt() - 1].add( if (multi) it else 0, stacks[from.toInt() - 1].removeFirst() ) } // println("$line $stacks") } } fun List<ArrayDeque<Char>>.topLayer() = map { it.first() }.joinToString("") fun part1(input: List<String>): String { with(input.iterator()) { val stacks = initStacks() executeMoves(stacks, false) return stacks.topLayer() } } fun part2(input: List<String>): String { with(input.iterator()) { val stacks = initStacks() executeMoves(stacks, true) return stacks.topLayer() } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") check(part1(testInput) == "CMZ") val input = readInput("Day05") println(part1(input)) println(part2(input)) } /* --- Day 5: Supply Stacks --- The expedition can depart as soon as the final supplies have been unloaded from the ships. Supplies are stored in stacks of marked crates, but because the needed supplies are buried under many other crates, the crates need to be rearranged. The ship has a giant cargo crane capable of moving crates between stacks. To ensure none of the crates get crushed or fall over, the crane operator will rearrange them in a series of carefully-planned steps. After the crates are rearranged, the desired crates will be at the top of each stack. The Elves don't want to interrupt the crane operator during this delicate procedure, but they forgot to ask her which crate will end up where, and they want to be ready to unload them as soon as possible so they can embark. They do, however, have a drawing of the starting stacks of crates and the rearrangement procedure (your puzzle input). For example: [D] [N] [C] [Z] [M] [P] 1 2 3 move 1 from 2 to 1 move 3 from 1 to 3 move 2 from 2 to 1 move 1 from 1 to 2 In this example, there are three stacks of crates. Stack 1 contains two crates: crate Z is on the bottom, and crate N is on top. Stack 2 contains three crates; from bottom to top, they are crates M, C, and D. Finally, stack 3 contains a single crate, P. Then, the rearrangement procedure is given. In each step of the procedure, a quantity of crates is moved from one stack to a different stack. In the first step of the above rearrangement procedure, one crate is moved from stack 2 to stack 1, resulting in this configuration: [D] [N] [C] [Z] [M] [P] 1 2 3 In the second step, three crates are moved from stack 1 to stack 3. Crates are moved one at a time, so the first crate to be moved (D) ends up below the second and third crates: [Z] [N] [C] [D] [M] [P] 1 2 3 Then, both crates are moved from stack 2 to stack 1. Again, because crates are moved one at a time, crate C ends up below crate M: [Z] [N] [M] [D] [C] [P] 1 2 3 Finally, one crate is moved from stack 1 to stack 2: [Z] [N] [D] [C] [M] [P] 1 2 3 The Elves just need to know which crate will end up on top of each stack; in this example, the top crates are C in stack 1, M in stack 2, and Z in stack 3, so you should combine these together and give the Elves the message CMZ. After the rearrangement procedure completes, what crate ends up on top of each stack? Your puzzle answer was BZLVHBWQF. --- Part Two --- As you watch the crane operator expertly rearrange the crates, you notice the process isn't following your prediction. Some mud was covering the writing on the side of the crane, and you quickly wipe it away. The crane isn't a CrateMover 9000 - it's a CrateMover 9001. The CrateMover 9001 is notable for many new and exciting features: air conditioning, leather seats, an extra cup holder, and the ability to pick up and move multiple crates at once. Again considering the example above, the crates begin in the same configuration: [D] [N] [C] [Z] [M] [P] 1 2 3 Moving a single crate from stack 2 to stack 1 behaves the same as before: [D] [N] [C] [Z] [M] [P] 1 2 3 However, the action of moving three crates from stack 1 to stack 3 means that those three moved crates stay in the same order, resulting in this new configuration: [D] [N] [C] [Z] [M] [P] 1 2 3 Next, as both crates are moved from stack 2 to stack 1, they retain their order as well: [D] [N] [C] [Z] [M] [P] 1 2 3 Finally, a single crate is still moved from stack 1 to stack 2, but now it's crate C that gets moved: [D] [N] [Z] [M] [C] [P] 1 2 3 In this example, the CrateMover 9001 has put the crates in a totally different order: MCD. Before the rearrangement process finishes, update your simulation so that the Elves know where they should stand to be ready to unload the final supplies. After the rearrangement procedure completes, what crate ends up on top of each stack? Your puzzle answer was TDGJQTZSL. Both parts of this puzzle are complete! They provide two gold stars: ** */
0
Kotlin
0
0
49ea6e3ad385b592867676766dafc48625568867
6,066
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/console/Runner.kt
oQaris
402,822,990
false
{"Kotlin": 147623}
package console import algorithm.* import com.udojava.evalex.Expression import graphs.Graph import kotlin.math.roundToInt fun printPath(g: Graph, u: Int, v: Int) { g.checkCorrectVer(u, v) val path = route(g, u, v) if (path.isEmpty()) println("The vertex $v is not reachable from $u.") else println(path.joinToString(" ")) } fun printMaxFlow(g: Graph, u: Int, v: Int) { g.checkCorrectVer(u, v) val maxFlow = maxFlow(g, u, v) if (maxFlow.value == 0) print("The vertex $v is not reachable from $u.") else { println("The value of the maximum flow from $u to $v: ${maxFlow.value}") println("List of augmentation paths:") for (path in maxFlow.flow) { print("(${path.value}) ") println(path.path.joinToString(" -> ")) } } } fun printHCycle(g: Graph, tree: Boolean) { if (vertexConnectivity(g) < 2) { println("There is no Hamiltonian cycle in this graph.") return } try { println(hamiltonCycle(g, 1, true, tree)) } catch (ex: IllegalArgumentException) { println(ex.message) } } fun printHChain(g: Graph, start: Int, tree: Boolean) { require(start >= 0 && start < g.numVer) { "Incorrect entry of the vertex for the start." } if (start == 0) { // Мультистарт var cc = 0 for (i in 1..g.numVer) try { hamiltonCycle(g, i, cycle = false, tree = false) break } catch (e: IllegalArgumentException) { cc++ } if (cc == g.numVer) println("The graph does not contain a Hamiltonian chain.") else println( hamiltonCycle(g, cc + 1, false, tree) ) } else // Старт с заданной вершины try { println(hamiltonCycle(g, start, false, tree)) } catch (e: IllegalArgumentException) { println("The graph does not contain a Hamiltonian chain from a given vertex.") } } fun printECycle(g: Graph) { if (vertexConnectivity(g) < 2) { println("There is no Euler cycle in this graph.") return } var numEvenVer = 0 for (i in g.numVer - 1 downTo 0) if (g.deg(i) % 2 == 0) numEvenVer++ if (g.numVer - numEvenVer == 0) println( "ЭЦ: " + eulerCycle( g, 1 ) ) else println("There is no Euler cycle in this graph.") } fun printEChain(g: Graph, start: Int) { var numEvenVer = 0 var oddVer = 0 for (i in g.numVer - 1 downTo 0) if (g.deg(i) % 2 == 0) numEvenVer++ else oddVer = i if (g.numVer - numEvenVer == 2) { println("There is an Euler chain:") if (start == 0) println( eulerCycle( g, oddVer + 1 ) ) else if (g.deg(start) % 2 == 1) println( eulerCycle( g, start ) ) else println("There is no Euler chain from the given vertex in this graph.") } else println("There is no Euler chain in this graph.") } fun redo(g: Graph, exprStr: String, isRound: Boolean) { val exp = Expression(exprStr) val count = redo(g) { u, v, w -> val res = exp.with("u", u.toString()) .and("v", v.toString()) .and("w", w.toString()) .eval() if (isRound) res.toDouble().roundToInt() else res.intValueExact() } println( "Обновлены веса в $count ${ if (g.oriented) "дугах" else "рёбрах" }" ) } fun connectivity(g: Graph, isVertex: Boolean, isEdge: Boolean) { val vc = vertexConnectivity(g) val ec = edgeConnectivity(g) if (vc != 0 && ec != 0) println( "Graph $vc" + if (ec != vc) ("-vertex-connected and $ec-edge-connected") else "-connected" ) else println("The graph is not connected.") }
1
Kotlin
0
2
2424cf11cf382c86e4fb40500dd5fded24f1858f
3,976
GraphProcessor
Apache License 2.0
src/main/kotlin/algorithms/LongestPathInDirectedGraph.kt
jimandreas
377,843,697
false
null
@file:Suppress( "SameParameterValue", "UnnecessaryVariable", "UNUSED_VARIABLE", "ControlFlowWithEmptyBody", "unused", "MemberVisibilityCanBePrivate", "LiftReturnOrAssignment" ) package algorithms import java.lang.Integer.max /** Code Challenge: Solve the Longest Path in a DAG Problem. Input: An integer representing the starting node to consider in a graph, followed by an integer representing the ending node to consider, followed by a list of edges in the graph. The edge notation "0->1:7" indicates that an edge connects node 0 to node 1 with weight 7. You may assume a given topological order corresponding to nodes in increasing order. Output: The length of a longest path in the graph, followed by a longest path. (If multiple longest paths exist, you may return any one.) * * See also: * stepik: @link: https://stepik.org/lesson/240303/step/7?unit=212649 * rosalind: @link: http://rosalind.info/users/jimandreas/ * book (5.8): https://www.bioinformaticsalgorithms.org/bioinformatics-chapter-5 */ class LongestPathInDirectedGraph { // each conn in the connList is a pair of { nodeNum, connWeight } var startNodeNum = 0 var endNodeNum = 0 data class Edge( val nodeNum: Int, val connList: MutableList<Pair<Int, Int>>, var maxConn: Pair<Int, Int> = Pair(-1, -1) ) /** * backtrack setup * Like in the LongestCommonSubsequenceLCS algorithmm - * the backtrack algorithm sets up the path with the highest weights. * The outputDAG routine (below) then follows this in reverse. */ fun backtrack(node: Int, fromNode: Int, weight: Int, list: MutableMap<Int, Edge>): Int { val thisNode = list[node] if (thisNode == null) { println("ERROR node $node is not in list") return 0 } var maxWeight = weight /* * for each edge, recursively call backtrack adding up the weights */ for (anEdge in thisNode.connList) { val toNode = anEdge.first val toNodeWeight = anEdge.second val maxConn = thisNode.maxConn /* * if the toNode is an endnode, then just create its max pair */ val listEntry = list[toNode] if (listEntry != null && listEntry.connList.size == 0) { maxWeight += toNodeWeight if (listEntry.maxConn.second < maxWeight) { listEntry.maxConn = Pair(node, maxWeight) } if (maxConn.second < maxWeight) { thisNode.maxConn = Pair(fromNode, maxWeight) } } else { // otherwise recurse further val totalWeight = backtrack(toNode, node, weight + toNodeWeight, list) if (maxConn.second < totalWeight) { thisNode.maxConn = Pair(fromNode, totalWeight) } maxWeight = max(maxWeight, totalWeight) } } return maxWeight } /** * output the highest weight path in the list from the start node to the end node * The graph has already been walked recursively and the highest weight noted. * Now just traverse the graph in reverse and build the connection list. */ fun outputDAG(list: MutableMap<Int, Edge>): Pair<Int, List<Int>> { val weight = list[endNodeNum]!!.maxConn.second // already calculated var curNodeNum = endNodeNum val outList: MutableList<Int> = mutableListOf() outList.add(curNodeNum) while (curNodeNum != startNodeNum) { val node = list[curNodeNum] if (node != null) { curNodeNum = node.maxConn.first outList.add(0, curNodeNum) // insert the node at the start of the list } else { println("ERROR no node at $curNodeNum") break } } return Pair(weight, outList) } /** * Solve the Longest Path in a DAG Problem * scan a well formed string of 0 // starting node 4 // ending node 0->1:7 // node connection with weight 0->2:4 No error checking is performed. */ fun readDirectedGraphInfo(connList: String): MutableMap<Int, Edge> { val list: MutableMap<Int, Edge> = mutableMapOf() val reader = connList.reader() val lines = reader.readLines() startNodeNum = lines[0].toInt() endNodeNum = lines[1].toInt() /* * add connections - if the node already exists in the list, just add new pairs of * node nums and weights */ for (i in 2 until lines.size) { val arc = lines[i].split("->") val nodeNum = arc[0].toInt() val toNodeWeight = arc[1].split(":") val nodeAndWeight = Pair(toNodeWeight[0].toInt(), toNodeWeight[1].toInt()) val connNode = nodeAndWeight.first if (!list.containsKey(nodeNum)) { list[nodeNum] = Edge(nodeNum, mutableListOf(nodeAndWeight)) } else { list[nodeNum]!!.connList.add(nodeAndWeight) } // add a placeholder for all edges if (!list.containsKey(connNode)) { list[connNode] = Edge(connNode, mutableListOf()) } } /* * now do a list fixup - insert any missing nodes with a dummy entry */ for (i in startNodeNum..endNodeNum) { if (!list.containsKey(i)) { list[i] = Edge(i, mutableListOf()) // dummy entry } } return list } }
0
Kotlin
0
0
fa92b10ceca125dbe47e8961fa50242d33b2bb34
5,721
stepikBioinformaticsCourse
Apache License 2.0
src/main/kotlin/com/jacobhyphenated/day17/Day17.kt
jacobhyphenated
572,119,677
false
{"Kotlin": 157591}
package com.jacobhyphenated.day17 import com.jacobhyphenated.Day import com.jacobhyphenated.day9.IntCode import java.io.File // Set And Forget class Day17: Day<List<Long>> { override fun getInput(): List<Long> { return this.javaClass.classLoader.getResource("day17/input.txt")!! .readText() .split(",") .map { it.toLong() } } /** * The IntCode input is a program that looks at cameras and controls the robot. * The robot communicates through ASCII characters. The output of running the program * shows where the scaffolding spaces that the robot can move on are located. * * The output is in ASCII where 35 == # == scaffold and 46 == . == empty space. * New lines use the new line character of 10. * The robot is always facing a certain direction and is represented by <, >, ^, or v * * The scaffolding generally is a straight path, but there are points where the paths intersect. * For each intersection, take the row and column index locations and multiply them. Add the results. */ override fun part1(input: List<Long>): Number { val asciiBot = IntCode(input) asciiBot.execute() val (rows, direction) = parseAsciiOutput(asciiBot.output) printGrid(rows, direction) // An intersection cannot occur on the edge, no need to iterate through edge spaces val intersections = mutableSetOf<Pair<Int,Int>>() for (r in 1 until rows.size -1) { for (c in 1 until rows[r].size - 1) { if (rows[r][c] == Space.EMPTY) { continue } // If this space is a scaffold and all adjacent spaces are scaffolds, this space is an intersection if (listOf(rows[r-1][c], rows[r+1][c], rows[r][c-1], rows[r][c+1]) .all { it == Space.SCAFFOLD || it == Space.ROBOT }){ intersections.add(Pair(r,c)) } } } return intersections.sumOf { (r,c) -> r * c } } /** * Give the robot a command sequence to visit all spaces on the scaffolding at least once. * * The robot only knows 3 movement commands (a,b,c). The main program tells the robot what order * and how often to execute a,b, and c. * * A movement command is either R (turn right), L (turn left) or some number of spaces to move forward. * * Example: L,6,L,2 translates in ascii to 76, 44, 54, 44, 76, 44, 50, 10 * (use 44 for commas and 10 to represent a new line. * * First, put the robot in move mode by setting the IntCode value at 0 to 2 * * Then give the program that is: * main * a * b * c * * Then add a final line that is debug mode (n or y) * Terminate all lines with a new line character (10). * * The last value of the output is the amount of dust collected. Return that. */ override fun part2(input: List<Long>): Number { val wakeUp = input.toMutableList() wakeUp[0] = 2 val asciiBot = IntCode(wakeUp) // Solved here with Pen and Paper, then checked by running the code. // My approach was to look at the first steps and the last steps, which must // always hve the same pattern of instructions. Then look at some loops and what steps // would traverse the loops. Once I identified several repeating patterns, I fit // those patterns to the data and double-checked that it worked. val mainRunner = "C,B,C,B,A,B,C,A,B,A".toCharArray().map { it.code } val a = "R,10,L,8,L,4,R,10".toCharArray().map { it.code } val b = "L,6,L,4,L,12".toCharArray().map { it.code } val c = "L,12,L,8,R,10,R,10".toCharArray().map { it.code } val enableVideo = "n".toCharArray().map { it.code } val program: List<Int> = mutableListOf<Int>().apply { addAll(mainRunner) add(10) addAll(a) add(10) addAll(b) add(10) addAll(c) add(10) addAll(enableVideo) add(10) } asciiBot.execute(program.map { it.toLong() }) return asciiBot.output.last() } private fun printGrid(grid: List<List<Space>>, direction: Direction) { val sb = java.lang.StringBuilder() for (row in grid) { for (col in row) { if (col == Space.ROBOT) { sb.append(direction.character) } else { sb.append(col.character) } } sb.append("\n") } println(sb.toString()) } private fun parseAsciiOutput(output: List<Long>): Pair<List<List<Space>>, Direction> { val rows = mutableListOf<MutableList<Space>>() var cols = mutableListOf<Space>() var robotDirection = Direction.DOWN for (element in output) { val code = element.toInt() val space = spaceFromCode(code) if (space == Space.NEW_LINE) { if (cols.size > 0) { rows.add(cols) } cols = mutableListOf() continue } cols.add(space) if (space == Space.ROBOT) { robotDirection = when(code) { 60 -> Direction.LEFT 62 -> Direction.RIGHT 94 -> Direction.UP 118 -> Direction.DOWN else -> throw NotImplementedError("Invalid space code $code") } } } return Pair(rows, robotDirection) } private fun spaceFromCode(code: Int): Space { return when(code) { 10 -> Space.NEW_LINE 35 -> Space.SCAFFOLD 46 -> Space.EMPTY 60,62,94,118 -> Space.ROBOT else -> throw NotImplementedError("Invalid space code $code") } } } private enum class Space(val character: String) { SCAFFOLD("#"), EMPTY("."), ROBOT("R"), NEW_LINE(""), } private enum class Direction(val character: String) { UP("^"), DOWN("v"), LEFT("<"), RIGHT(">") }
0
Kotlin
0
0
1a0b9cb6e9a11750c5b3b5a9e6b3d63649bf78e4
6,297
advent2019
The Unlicense
src/test/kotlin/dev/shtanko/algorithms/leetcode/PalindromePermutationTest.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.stream.Stream import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.extension.ExtensionContext import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.ArgumentsProvider import org.junit.jupiter.params.provider.ArgumentsSource abstract class PalindromePermutationTest<out T : PalindromePermutationBehavior>(private val strategy: T) { private class InputArgumentsProvider : ArgumentsProvider { override fun provideArguments(context: ExtensionContext?): Stream<out Arguments> = Stream.of( Arguments.of("", true), Arguments.of("a", true), Arguments.of("tenet", true), Arguments.of("abc", false), Arguments.of("code", false), Arguments.of("aab", true), Arguments.of("carerac", true), ) } @ParameterizedTest @ArgumentsSource(InputArgumentsProvider::class) fun `can permute palindrome test`(s: String, expected: Boolean) { val actual = strategy.canPermutePalindrome(s) assertEquals(expected, actual) } } class PalindromePermutationBruteForceTest : PalindromePermutationTest<PalindromePermutationBruteForce>(PalindromePermutationBruteForce()) class PalindromePermutationHashMapTest : PalindromePermutationTest<PalindromePermutationHashMap>(PalindromePermutationHashMap()) class PalindromePermutationArrayTest : PalindromePermutationTest<PalindromePermutationArray>(PalindromePermutationArray()) class PalindromePermutationSinglePassTest : PalindromePermutationTest<PalindromePermutationSinglePass>(PalindromePermutationSinglePass()) class PalindromePermutationSetTest : PalindromePermutationTest<PalindromePermutationSet>(PalindromePermutationSet()) class PalindromePermutationTreeTest : PalindromePermutationTest<PalindromePermutationTree>(PalindromePermutationTree())
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,608
kotlab
Apache License 2.0
constraints/src/test/kotlin/com/alexb/constraints/core/constraints/ConstraintsTest.kt
alexbaryzhikov
201,620,351
false
null
/* Copyright 2019 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.alexb.constraints.core.constraints import com.alexb.constraints.Problem import com.google.common.truth.Truth.assertThat import org.junit.Test class ConstraintsTest { @Test fun uniFunctionalConstraint() { val problem = Problem<String, Int>().apply { addVariables(listOf("a", "b"), listOf(1, 2)) addConstraint({ a -> a == 2 }, "a") } val solutions = problem.getSolutions() assertThat(solutions).containsExactly( mapOf("a" to 2, "b" to 1), mapOf("a" to 2, "b" to 2) ) } @Test fun biFunctionalConstraint() { val problem = Problem<String, Int>().apply { addVariables(listOf("a", "b"), listOf(1, 2, 3)) addConstraint({ a, b -> b < a }, listOf("a", "b")) } val solutions = problem.getSolutions() assertThat(solutions).containsExactly( mapOf("a" to 2, "b" to 1), mapOf("a" to 3, "b" to 1), mapOf("a" to 3, "b" to 2) ) } @Test fun triFunctionalConstraint() { val problem = Problem<String, Int>().apply { addVariables(listOf("a", "b", "c"), listOf(1, 2, 3)) addConstraint({ a, b, c -> a + b == c }, listOf("a", "b", "c")) } val solutions = problem.getSolution() assertThat(solutions).isEqualTo(mapOf("a" to 1, "b" to 1, "c" to 2)) } @Test fun functionalConstraint() { val problem = Problem<String, Int>().apply { addVariables(listOf("a", "b"), listOf(1, 2)) addConstraint({ args -> args.any { it == 1 } }) } val solutions = problem.getSolutions() assertThat(solutions).containsExactly( mapOf("a" to 1, "b" to 1), mapOf("a" to 1, "b" to 2), mapOf("a" to 2, "b" to 1) ) } @Test fun allDifferentConstraint() { val problem = Problem<String, Int>() problem.addVariables(listOf("a", "b"), listOf(1, 2, 3)) problem.addConstraint(AllDifferentConstraint()) val solutions = problem.getSolutions() assertThat(solutions).containsExactly( mapOf("a" to 1, "b" to 2), mapOf("a" to 1, "b" to 3), mapOf("a" to 2, "b" to 1), mapOf("a" to 2, "b" to 3), mapOf("a" to 3, "b" to 1), mapOf("a" to 3, "b" to 2) ) } @Test fun allEqualConstraint() { val problem = Problem<String, Int>() problem.addVariables(listOf("a", "b"), listOf(1, 2, 3)) problem.addConstraint(AllEqualConstraint()) val solutions = problem.getSolutions() assertThat(solutions).containsExactly( mapOf("a" to 1, "b" to 1), mapOf("a" to 2, "b" to 2), mapOf("a" to 3, "b" to 3) ) } @Test fun maxSumConstraint() { val problem = Problem<String, Int>() problem.addVariables(listOf("a", "b"), listOf(1, 2, 3)) problem.addConstraint(MaxSumConstraint(3)) val solutions = problem.getSolutions() assertThat(solutions).containsExactly( mapOf("a" to 1, "b" to 1), mapOf("a" to 1, "b" to 2), mapOf("a" to 2, "b" to 1) ) } @Test fun exactSumConstraint() { val problem = Problem<String, Int>() problem.addVariables(listOf("a", "b"), listOf(1, 2, 3)) problem.addConstraint(ExactSumConstraint(3)) val solutions = problem.getSolutions() assertThat(solutions).containsExactly( mapOf("a" to 1, "b" to 2), mapOf("a" to 2, "b" to 1) ) } @Test fun minSumConstraint() { val problem = Problem<String, Double>() problem.addVariables(listOf("a", "b"), listOf(1.1, 2.5, 3.2)) problem.addConstraint(MinSumConstraint(5.0)) val solutions = problem.getSolutions() assertThat(solutions).containsExactly( mapOf("a" to 2.5, "b" to 2.5), mapOf("a" to 2.5, "b" to 3.2), mapOf("a" to 3.2, "b" to 2.5), mapOf("a" to 3.2, "b" to 3.2) ) } @Test fun inSetConstraint() { val problem = Problem<String, Int>() problem.addVariables(listOf("a", "b"), listOf(1, 2, 3)) problem.addConstraint(InSetConstraint(setOf(1))) val solutions = problem.getSolutions() assertThat(solutions).containsExactly( mapOf("a" to 1, "b" to 1) ) } @Test fun notInSetConstraint() { val problem = Problem<String, Int>() problem.addVariables(listOf("a", "b"), listOf(1, 2, 3)) problem.addConstraint(NotInSetConstraint(setOf(2))) val solutions = problem.getSolutions() assertThat(solutions).containsExactly( mapOf("a" to 1, "b" to 1), mapOf("a" to 1, "b" to 3), mapOf("a" to 3, "b" to 1), mapOf("a" to 3, "b" to 3) ) } @Test fun someInSetConstraintNotExact() { val problem = Problem<String, Int>() problem.addVariables(listOf("a", "b", "c"), listOf(1, 2)) problem.addConstraint(SomeInSetConstraint(setOf(2), 2)) val solutions = problem.getSolutions() assertThat(solutions).containsExactly( mapOf("a" to 1, "b" to 2, "c" to 2), mapOf("a" to 2, "b" to 1, "c" to 2), mapOf("a" to 2, "b" to 2, "c" to 1), mapOf("a" to 2, "b" to 2, "c" to 2) ) } @Test fun someInSetConstraintExact() { val problem = Problem<String, Int>() problem.addVariables(listOf("a", "b", "c"), listOf(1, 2)) problem.addConstraint(SomeInSetConstraint(setOf(2), 2, true)) val solutions = problem.getSolutions() assertThat(solutions).containsExactly( mapOf("a" to 1, "b" to 2, "c" to 2), mapOf("a" to 2, "b" to 1, "c" to 2), mapOf("a" to 2, "b" to 2, "c" to 1) ) } @Test fun someNotInSetConstraintNotExact() { val problem = Problem<String, Int>() problem.addVariables(listOf("a", "b", "c"), listOf(1, 2)) problem.addConstraint(SomeNotInSetConstraint(setOf(2), 2)) val solutions = problem.getSolutions() assertThat(solutions).containsExactly( mapOf("a" to 1, "b" to 1, "c" to 1), mapOf("a" to 1, "b" to 1, "c" to 2), mapOf("a" to 1, "b" to 2, "c" to 1), mapOf("a" to 2, "b" to 1, "c" to 1) ) } @Test fun someNotInSetConstraintExact() { val problem = Problem<String, Int>() problem.addVariables(listOf("a", "b", "c"), listOf(1, 2)) problem.addConstraint(SomeNotInSetConstraint(setOf(2), 2, true)) val solutions = problem.getSolutions() assertThat(solutions).containsExactly( mapOf("a" to 1, "b" to 1, "c" to 2), mapOf("a" to 1, "b" to 2, "c" to 1), mapOf("a" to 2, "b" to 1, "c" to 1) ) } }
0
Kotlin
0
0
e67ae6b6be3e0012d0d03988afa22236fd62f122
7,599
kotlin-constraints
Apache License 2.0
src/main/kotlin/me/peckb/aoc/_2023/calendar/day02/Day02.kt
peckb1
433,943,215
false
{"Kotlin": 956135}
package me.peckb.aoc._2023.calendar.day02 import javax.inject.Inject import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory import kotlin.math.max class Day02 @Inject constructor( private val generatorFactory: InputGeneratorFactory, ) { fun partOne(filename: String) = generatorFactory.forFile(filename).readAs(::game) { games -> val maxRed = 12 val maxGreen = 13 val maxBlue = 14 games.filter { game -> game.rounds.none { round -> round.red > maxRed || round.blue > maxBlue || round.green > maxGreen } }.sumOf { it.id } } fun partTwo(filename: String) = generatorFactory.forFile(filename).readAs(::game) { games -> games.sumOf { game -> var minRequiredRed = 0 var minRequiredBlue = 0 var minRequiredGreen = 0 game.rounds.forEach { round -> minRequiredRed = max(minRequiredRed, round.red) minRequiredBlue = max(minRequiredBlue, round.blue) minRequiredGreen = max(minRequiredGreen, round.green) } minRequiredRed * minRequiredGreen * minRequiredBlue } } private fun game(line: String): Game { val (gameIdString, roundData) = line.split(": ") val id = gameIdString.split(" ").last().toInt() val roundStrings = roundData.split("; ") val rounds = roundStrings.map { roundInformation -> var red = 0 var blue = 0 var green = 0 roundInformation.split(", ") .forEach { colourInformation -> val (count, colour) = colourInformation.split(" ") when (colour) { "red" -> red = count.toInt() "blue" -> blue = count.toInt() "green" -> green = count.toInt() } } Round(red, green, blue) } return Game(id, rounds) } data class Game(val id: Int, val rounds: List<Round>) data class Round(val red: Int, val green: Int, val blue: Int) }
0
Kotlin
1
3
2625719b657eb22c83af95abfb25eb275dbfee6a
1,905
advent-of-code
MIT License
constraints/src/test/kotlin/com/alexb/constraints/ProblemTest.kt
alexbaryzhikov
201,620,351
false
null
/* Copyright 2019 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.alexb.constraints import com.google.common.truth.Truth.assertThat import org.junit.Test class ProblemTest { @Test fun solutionsAbc() { val problem = Problem<String, Int>().apply { addVariables(listOf("a", "b", "c"), (1..9).toList()) } var minvalue = 999.0 / (9 * 3) var minSolution: Map<String, Int> = emptyMap() for (solution in problem.getSolutionSequence()) { val a = solution.getValue("a") val b = solution.getValue("b") val c = solution.getValue("c") val value = (a * 100 + b * 10 + c).toDouble() / (a + b + c) if (value < minvalue) { minvalue = value minSolution = solution } } assertThat(minSolution).containsExactlyEntriesIn(mapOf("a" to 1, "b" to 9, "c" to 9)) } @Test fun reset() { val problem = Problem<String, Int>().apply { addVariable("a", listOf(1, 2)) reset() } assertThat(problem.getSolution()).isNull() } @Test fun addVariable() { val problem = Problem<String, Int>().apply { addVariable("a", listOf(1, 2)) } assertThat(problem.getSolution()).isIn(listOf(mapOf("a" to 1), mapOf("a" to 2))) } @Test fun addVariables() { val problem = Problem<String, Int>().apply { addVariables(listOf("a", "b"), listOf(1, 2, 3)) } assertThat(problem.getSolutions()).hasSize(9) } @Test fun addConstraint1() { val problem = Problem<String, Int>().apply { addVariables(listOf("a", "b"), listOf(1, 2, 3)) addConstraint({ args -> args[1] == args[0] + 1 }, listOf("a", "b")) } assertThat(problem.getSolutions()).containsExactly( mapOf("a" to 1, "b" to 2), mapOf("a" to 2, "b" to 3) ) } @Test fun addConstraint2() { val problem = Problem<String, Int>().apply { addVariables(listOf("a", "b", "c"), listOf(1, 2, 3)) addConstraint({ a, b, c -> a + b == c }, listOf("a", "b", "c")) } assertThat(problem.getSolution()).isIn( listOf( mapOf("a" to 1, "b" to 1, "c" to 2), mapOf("a" to 1, "b" to 2, "c" to 3), mapOf("a" to 2, "b" to 1, "c" to 3) ) ) } @Test fun addConstraint3() { val problem = Problem<String, Int>().apply { addVariables(listOf("a", "b"), listOf(1, 2, 3)) addConstraint({ a, b -> b == a + 1 }, listOf("a", "b")) } assertThat(problem.getSolutions()).containsExactly( mapOf("a" to 1, "b" to 2), mapOf("a" to 2, "b" to 3) ) } @Test fun addConstraint4() { val problem = Problem<String, Int>().apply { addVariables(listOf("a", "b"), listOf(1, 2)) addConstraint({ a -> a == 2 }, "a") } assertThat(problem.getSolutions()).containsExactly( mapOf("a" to 2, "b" to 1), mapOf("a" to 2, "b" to 2) ) } @Test fun getSolution() { val problem = Problem<String, Int>() assertThat(problem.getSolution()).isNull() problem.addVariable("a", listOf(42)) assertThat(problem.getSolution()).isEqualTo(mapOf("a" to 42)) } @Test fun getSolutions() { val problem = Problem<String, Int>() assertThat(problem.getSolutions()).isEmpty() problem.addVariable("a", listOf(42)) assertThat(problem.getSolutions()).containsExactly(mapOf("a" to 42)) } @Test fun getSolutionSequence() { val problem = Problem<String, Int>() assertThat(problem.getSolutionSequence().toList()).isEmpty() problem.addVariable("a", listOf(42)) assertThat(problem.getSolutionSequence().toList()).containsExactly(mapOf("a" to 42)) } }
0
Kotlin
0
0
e67ae6b6be3e0012d0d03988afa22236fd62f122
4,550
kotlin-constraints
Apache License 2.0
shared/src/main/kotlin/edu/cornell/cs/apl/attributes/Trees.kt
s-ren
386,161,765
true
{"Kotlin": 878757, "Java": 43761, "C++": 13898, "Python": 11991, "Lex": 6620, "Dockerfile": 1844, "Makefile": 1785, "SWIG": 1212, "Shell": 698}
package edu.cornell.cs.apl.attributes import java.util.IdentityHashMap import kotlinx.collections.immutable.PersistentList import kotlinx.collections.immutable.toPersistentList /** * Computes and stores parent/child/sibling relations in a tree structure. * * This class is a simplified version of Kiama's tree relations. * Refer to the sections on * [Attribute Grammars](https://github.com/inkytonik/kiama/blob/master/wiki/Attribution.md#tree-relations) * and * [Relations](https://github.com/inkytonik/kiama/blob/master/wiki/Relations.md). * in Kiama's user manual for more information. * * @param Node The type of nodes in the tree. * @param RootNode The type of the root node of the tree. * @param root The root node of the tree. */ class Tree<Node : TreeNode<Node>, out RootNode : Node>(val root: RootNode) { private val relations: MutableMap<Node, NodeRelations<Node>> = IdentityHashMap() init { fun addNode(parent: Node?, node: Node, nodeIndex: Int) { val children = node.children.toPersistentList() if (relations.put(node, NodeRelations(parent, children, nodeIndex)) != null) { // TODO: custom exception class error("Duplicate child node $node.") } children.forEachIndexed { index, child -> addNode(node, child, index) } } addNode(null, root, 0) } /** Returns the parent of [node], or `null` if [node] is the root. */ fun parent(node: Node): Node? = relations[node]!!.parent /** Returns the index of [node] in its parent's children list. */ fun childIndex(node: Node): Int = relations[node]!!.index /** * Returns the node that occurs just before [node] in its parent's children list, or `null` * if [node] is the root or [node] is its parent's first child. */ fun previousSibling(node: Node): Node? { val nodeInfo = relations[node]!! return nodeInfo.parent?.let { parent -> relations[parent]!!.children.getOrNull(nodeInfo.index - 1) } } /** * Returns the node that occurs just after [node] in its parent's children list, or `null` * if [node] is the root or [node] is its parent's last child. */ fun nextSibling(node: Node): Node? { val nodeInfo = relations[node]!! return nodeInfo.parent?.let { parent -> relations[parent]!!.children.getOrNull(nodeInfo.index + 1) } } } /** A node in a [Tree]. */ interface TreeNode<out Node> { /** The list of all children nodes. This is empty for leaf nodes. */ // TODO: this should be a list val children: Iterable<Node> } /** * Stores ancestry information about a node. * * @param parent The parent of this node, or `null` if this is the root node. * @param children The list of all children nodes. * @param index The index of this node in [parent]'s children list. */ private data class NodeRelations<Node>( val parent: Node?, val children: PersistentList<Node>, val index: Int )
0
null
0
0
337b3873e10f642706b195b10f939e9c1c7832ef
3,037
viaduct
MIT License
src/Day10.kt
ostersc
572,991,552
false
{"Kotlin": 46059}
import kotlin.math.absoluteValue class CPU(var cycle: Int = 0, var register: Int = 1, var total: Int = 0) { fun tick() { cycle++ maybeAccumulate() } private fun maybeAccumulate() { if (20 == cycle % 40) { total += register * cycle } } fun add(toAdd: Int) { register += toAdd } } class CRT(private var pixels: BooleanArray = BooleanArray(240), var cpu: CPU = CPU()) { fun render() { for (i in 0..pixels.lastIndex) { if (pixels[i]) print("█") else print(" ") if ((i + 1) % 40 == 0) println() } } fun tick(){ if(((cpu.register-(cpu.cycle%40))).absoluteValue<=1){ pixels[cpu.cycle]=true } cpu.tick() } } fun main() { fun part1(input: List<String>): Int { val cpu = CPU() for (line in input) { if (line == "noop") { cpu.tick() } else { cpu.tick() cpu.tick() cpu.add(line.substringAfter(' ').toInt()) } } return cpu.total } fun part2(input: List<String>){ val crt = CRT() for (line in input) { if (line == "noop") { crt.tick() } else { crt.tick() crt.tick() crt.cpu.add(line.substringAfter(' ').toInt()) } } crt.render() } var testInput = readInput("Day10_test") check(part1(testInput) == 0) testInput = readInput("Day10_test2") check(part1(testInput) == 13140) part2(testInput) val input = readInput("Day10") val part1 = part1(input) println(part1) check(part1 == 14540) part2(input) }
0
Kotlin
0
1
3eb6b7e3400c2097cf0283f18b2dad84b7d5bcf9
1,784
advent-of-code-2022
Apache License 2.0
src/main/kotlin/day5/day5part1.kts
avrilfanomar
433,723,983
false
null
package day5 import java.io.File import kotlin.math.max import kotlin.math.min val resultMap = HashMap<String, Int>() File("input.txt").forEachLine { line -> val parts = line.split("->") val x1y1 = parts[0].trim().split(",").map { it.trim().toInt() } val x2y2 = parts[1].trim().split(",").map { it.trim().toInt() } if (x1y1[0] == x2y2[0]) { val min = min(x1y1[1], x2y2[1]) val max = max(x1y1[1], x2y2[1]) for (i in min..max) { resultMap.compute("${x1y1[0]},$i") { _, v -> v?.plus(1) ?: 1 } } } else if (x1y1[1] == x2y2[1]) { val min = min(x1y1[0], x2y2[0]) val max = max(x1y1[0], x2y2[0]) for (i in min..max) { resultMap.compute("$i,${x1y1[1]}") { _, v -> v?.plus(1) ?: 1 } } } } println(resultMap.filter { it.value > 1 }.size)
0
Kotlin
0
0
266131628b7a58e9b577b7375d3ad6ad88a00954
843
advent-of-code-2021
Apache License 2.0
src/main/kotlin/g2101_2200/s2192_all_ancestors_of_a_node_in_a_directed_acyclic_graph/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2101_2200.s2192_all_ancestors_of_a_node_in_a_directed_acyclic_graph // #Medium #Depth_First_Search #Breadth_First_Search #Graph #Topological_Sort // #2023_06_26_Time_841_ms_(100.00%)_Space_84.4_MB_(100.00%) class Solution { private lateinit var adjList: MutableList<MutableList<Int>> private lateinit var result: MutableList<MutableList<Int>> fun getAncestors(n: Int, edges: Array<IntArray>): List<MutableList<Int>> { adjList = ArrayList() result = ArrayList() for (i in 0 until n) { adjList.add(ArrayList()) result.add(ArrayList()) } for (edge in edges) { val start = edge[0] val end = edge[1] adjList[start].add(end) } // DFS for each node from 0 --> n , and add that node as root/parent into each reachable // node and their child // Use visited[] to identify if any of the child or their childs are already visited for // that perticular root/parent, // so will not add the root to avoid duplicacy and call reduction . for (i in 0 until n) { val visited = BooleanArray(n) val childList: List<Int> = adjList[i] for (child in childList) { if (!visited[child]) { dfs(i, child, visited) } } } return result } private fun dfs(root: Int, node: Int, visited: BooleanArray) { if (visited[node]) { return } visited[node] = true result[node].add(root) val childList: List<Int> = adjList[node] for (child in childList) { if (!visited[child]) { dfs(root, child, visited) } } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,791
LeetCode-in-Kotlin
MIT License
gcj/y2020/round1a/b.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package gcj.y2020.round1a private fun solve(n: Int) = (0..n).first { solve(n.toLong(), it, true) } private fun solve(n: Long, p: Int, dir: Boolean): Boolean { if (p < 0) return true if (n <= p || n >= 1L shl (p + 1)) return false val order = if (dir) 0..p else p downTo 0 when { solve(n - (1L shl p), p - 1, !dir) -> order solve(n - 1, p - 1, dir) -> order.last..order.last else -> return false }.forEach { println("${p + 1} ${it + 1}") } return true } fun main() = repeat(readInt()) { println("Case #${it + 1}:"); solve(readInt()) } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt()
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
627
competitions
The Unlicense
src/Day01.kt
Frosendroska
575,572,338
false
{"Kotlin": 1582}
fun main() { fun part1(input: List<String>): Int { var max = 0 var cur = 0 for (i in input.indices) { if (input[i].isNotEmpty()) { cur += Integer.parseInt(input[i]) max = Math.max(max, cur) } else { cur = 0 } } return max } fun part2(input: List<String>): Int { val arr = mutableListOf<Int>() arr.add(0) var cur = 0 var max = 0 for (i in input.indices) { if (input[i].isNotEmpty()) { cur += input[i].toInt() } else { arr.add(cur) cur = 0 } } arr.sortDescending() for (i in 0 .. 2) { max += arr[i] } return max } val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
012db7bf55ec0137d2246552676effd98b8cccfb
919
advent-of-code-kotlin-Frosendroska
Apache License 2.0
src/main/kotlin/03.kts
reitzig
318,492,753
false
null
import java.io.File val map = File(args[0]).readLines() val mapWidth = map[0].length assert(args[0][0] == '.') assert(args.all { it.length == mapWidth }) // I prefered this for part 1, but didn't see a neat way to generalize it //var trees = map // .mapIndexed { rowIndex, row -> row[(rowIndex * 3) % mapWidth]} // .count { it == '#' } fun metTrees(map: List<String>, shiftRight: Int, shiftDown: Int): Long { var trees = 0L for ( rowIndex in 0..map.lastIndex step shiftDown ) { val nextSquare = map[rowIndex][(rowIndex / shiftDown * shiftRight) % mapWidth] if ( nextSquare == '#' ) { trees += 1 } } return trees } // Part 1 println(metTrees(map, 3, 1)) // Part 2 println( listOf(Pair(1,1), Pair(3,1), Pair(5,1), Pair(7,1), Pair(1,2)) .map { metTrees(map, it.first, it.second) } .reduce(Long::times) )
0
Kotlin
0
0
f17184fe55dfe06ac8897c2ecfe329a1efbf6a09
900
advent-of-code-2020
The Unlicense
base/impl/src/main/kotlin/com/yandex/yatagan/base/comparators.kt
yandex
570,094,802
false
{"Kotlin": 1413320}
/* * Copyright 2022 Yandex LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yandex.yatagan.base class ListComparator<T>( private val comparator: Comparator<T>, private val asSorted: Boolean, ) : Comparator<List<T>> { override fun compare(o1: List<T>, o2: List<T>): Int { if (o1.size != o2.size) return o1.size.compareTo(o2.size) val sorted1 = if (asSorted) o1.sortedWith(comparator) else o1 val sorted2 = if (asSorted) o2.sortedWith(comparator) else o2 for (i in sorted1.indices) { val v = comparator.compare(sorted1[i], sorted2[i]) if (v != 0) return v } return 0 } companion object { fun <T : Comparable<T>> ofComparable( asSorted: Boolean, ) = ListComparator<T>( comparator = Comparabletor.obtain(), asSorted = asSorted, ) } } class MapComparator<K, V>( private val keyComparator: Comparator<K>, private val valueComparator: Comparator<V>, ) : Comparator<Map<K, V>> { override fun compare(o1: Map<K, V>, o2: Map<K, V>): Int { if (o1.size != o2.size) return o1.size.compareTo(o2.size) val keys1 = o1.keys.sortedWith(keyComparator) val keys2 = o2.keys.sortedWith(keyComparator) ListComparator(keyComparator, asSorted = false /* already sorted*/) .compare(keys1, keys2).let { if (it != 0) return it } for (k in keys1) { valueComparator.compare(o1[k]!!, o2[k]!!).let { if (it != 0) return it } } return 0 } companion object { fun <K : Comparable<K>, V> ofComparableKey( valueComparator: Comparator<V>, ) = MapComparator<K, V>( keyComparator = Comparabletor.obtain(), valueComparator = valueComparator, ) fun <K, V : Comparable<V>> ofComparableValue( keyComparator: Comparator<K>, ) = MapComparator<K, V>( keyComparator = keyComparator, valueComparator = Comparabletor.obtain(), ) fun <K : Comparable<K>, V : Comparable<V>> ofComparable( ) = MapComparator<K, V>( keyComparator = Comparabletor.obtain(), valueComparator = Comparabletor.obtain(), ) } } // Yes, a comparator for comparable - comparabletor private object Comparabletor : Comparator<Comparable<Any>> { override fun compare(o1: Comparable<Any>, o2: Comparable<Any>): Int = o1.compareTo(o2) fun <T : Comparable<T>> obtain(): Comparator<T> { @Suppress("UNCHECKED_CAST") return this as Comparator<T> } }
15
Kotlin
9
214
cf1b298942c137d1681f8a1a0e6c38f4e0d7deb8
3,154
yatagan
Apache License 2.0
src/Day05.kt
colmmurphyxyz
572,533,739
false
{"Kotlin": 19871}
import java.util.Stack import kotlin.properties.Delegates fun main() { fun inputToStacks(input: List<String>): List<Stack<Char>> { val stacks = List<Stack<Char>>(9) { Stack<Char>()} // val stacks = listOf(Stack<Char>(), Stack<Char>(), Stack<Char>()) for (line in input) { for (charIndex in 1..33 step 4) { if (charIndex >= line.length) continue if (!line[charIndex].isWhitespace()) { stacks[charIndex / 4].push(line[charIndex]) } } } return stacks.map { it -> it.invert() } } fun part1(input: List<String>, firstBlankLineIndex: Int): String { val stacks = inputToStacks(input.slice(0..(firstBlankLineIndex - 2))) val operations = input.slice((firstBlankLineIndex + 1)..input.lastIndex) for (operation in operations) { val components = operation.split(" ") repeat (components[1].toInt()) { val from = components[3].toInt() - 1 val to = components[5].toInt() - 1 stacks[to].push(stacks[from].pop()) } } return stacks.joinToString(separator = "") { it -> it.peek().toString() } } fun part2(input: List<String>, firstBlankLineIndex: Int): String { val stacks = inputToStacks(input.slice(0..(firstBlankLineIndex - 2))).toMutableList() val operations = input.slice((firstBlankLineIndex + 1)..input.lastIndex) for (operation in operations) { val components = operation.split(" ") val from = stacks[components[3].toInt() - 1] val to = stacks[components[5].toInt() - 1] stacks[components[5].toInt() - 1] = moveNItems(from, to, components[1].toInt()) } return stacks.joinToString(separator = "") { it -> it.peek().toString() } } val input = readInput("Day05") var firstBlankLineIndex by Delegates.notNull<Int>() for (i in input.indices) { if (input[i].isBlank()) { println("first blank line = $i") firstBlankLineIndex = i break } } println("Part 1 answer: ${part1(input, firstBlankLineIndex)}") println("Part 2 answer: ${part2(input, firstBlankLineIndex)}") }
0
Kotlin
0
0
c5653691ca7e64a0ee7f8e90ab1b450bcdea3dea
2,299
aoc-2022
Apache License 2.0
src/main/kotlin/kotlinkoans/algorithms/QSort.kt
marregui
306,930,708
false
null
/* * Licensed to <NAME> ("marregui") under one or more contributor * license agreements. See the LICENSE file distributed with this work * for additional information regarding copyright ownership. You may * obtain a copy 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. * * Copyright 2020, <NAME> a.k.a. marregui */ package kotlinkoans.algorithms fun <T: Comparable<T>> qsort(array: Array<T>) { val stack = IndexStack() stack.push(0, array.size - 1) while (stack.size > 0) { val (start, end) = stack.pop() var p = start for (i in p until end) { if (array[i] > array[end]) { if (i != p) { array[p] = array[i].also { array[i] = array[p] } } p++ } } array[p] = array[end].also { array[end] = array[p] } if (p - 1 > start) { stack.push(start, p - 1) // there are elements left of pivot, push left } if (p + 1 < end) { stack.push(p + 1, end) // there are elements right of pivot, push right } } } private class IndexStack { private var stack = Array<Pair<Int, Int>?>(5) { null } private var insertIdx = 0 fun push(start: Int, end: Int) { if (insertIdx >= stack.size) { stack = stack.copyOf(stack.size * 2) } stack[insertIdx++] = Pair(start, end) } fun pop(): Pair<Int, Int> { if (insertIdx <= 0) { throw IllegalStateException("stack is empty") } return stack[--insertIdx]!!.also { stack[insertIdx] = null } } val size: Int get() = insertIdx }
11
Kotlin
0
0
7609ec91ee125dae87bb3e654cd36e48853bc9ab
2,009
kotlin-koans
Apache License 2.0