path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/main/kotlin/dokerplp/bot/utli/StrignSimilarity.kt
dokerplp
407,882,967
false
{"Kotlin": 55171}
package dokerplp.bot.utli import java.util.* /* Code was taken from https://stackoverflow.com/questions/955110/similarity-string-comparison-in-java */ /** * Calculates the similarity (a number within 0 and 1) between two strings. */ fun stringSimilarity(s1: String, s2: String): Double { var longer = s1 var shorter = s2 if (s1.length < s2.length) { // longer should always have greater length longer = s2 shorter = s1 } val longerLength = longer.length return if (longerLength == 0) { 1.0 /* both strings are zero length */ } else (longerLength - editDistance(longer, shorter)) / longerLength.toDouble() /* // If you have Apache Commons Text, you can use it to calculate the edit distance: LevenshteinDistance levenshteinDistance = new LevenshteinDistance(); return (longerLength - levenshteinDistance.apply(longer, shorter)) / (double) longerLength; */ } // Example implementation of the Levenshtein Edit Distance // See http://rosettacode.org/wiki/Levenshtein_distance#Java private fun editDistance(s1: String, s2: String): Int { var s1 = s1 var s2 = s2 s1 = s1.lowercase(Locale.getDefault()) s2 = s2.lowercase(Locale.getDefault()) val costs = IntArray(s2.length + 1) for (i in 0..s1.length) { var lastValue = i for (j in 0..s2.length) { if (i == 0) costs[j] = j else { if (j > 0) { var newValue = costs[j - 1] if (s1[i - 1] != s2[j - 1]) newValue = Math.min( Math.min(newValue, lastValue), costs[j] ) + 1 costs[j - 1] = lastValue lastValue = newValue } } } if (i > 0) costs[s2.length] = lastValue } return costs[s2.length] }
0
Kotlin
0
0
b3c530a3c7aff82a9072348ba036b364f33d0769
1,701
abit-vt-bot
Apache License 2.0
src/main/kotlin/egger/software/hmm/algorithm/Viterbi.kt
eggeral
127,237,737
false
null
package egger.software.hmm.algorithm import egger.software.hmm.HiddenMarkovModelWithObservations import egger.software.hmm.StateWithProbability import egger.software.hmm.probabilityOf val <TState, TObservation> HiddenMarkovModelWithObservations<TState, TObservation>.mostLikelyStateSequence: List<TState> get() { // Simple implementation of the Viterbi Algorithm // delta(n,i) = the highest likelihood of any single path ending in state s(i) after n steps // psi(n,i) = the best path ending in state s(i) after n steps // pi(i) = probability of s(i) being the first state // Initialize delta(1,i) and psi(1,i) val delta = mutableMapOf<TState, MutableList<Double>>() val psi = mutableMapOf<TState, MutableList<TState?>>() for (state in hiddenMarkovModel.states) { val pi = hiddenMarkovModel.startingProbabilityOf(state) val b = hiddenMarkovModel.observationProbabilities.given(state) probabilityOf observations[0] delta[state] = mutableListOf(pi * b) psi[state] = mutableListOf<TState?>(null) } fun predecessorWithMaximumLikelihood(iteration: Int, targetState: TState): StateWithProbability<TState> { var result: StateWithProbability<TState>? = null for (predecessor in hiddenMarkovModel.states) { val likelihood = delta[predecessor]!![iteration - 1] * (hiddenMarkovModel.stateTransitions.given(predecessor) probabilityOf targetState) if (result == null || likelihood > result.probability) result = StateWithProbability(predecessor, likelihood) } return result!! } for (iteration in 1 until observations.size) { for (state in hiddenMarkovModel.states) { val predecessor = predecessorWithMaximumLikelihood(iteration, state) delta[state]!!.add(predecessor.probability * (hiddenMarkovModel.observationProbabilities.given(state) probabilityOf observations[iteration])) psi[state]!!.add(predecessor.state) } } val pathEnding = requireNotNull(delta.entries.map { d -> StateWithProbability(d.key, d.value[2]) }.maxBy { s -> s.probability }) var mostLikelyStateSequence = listOf(pathEnding.state) var currentState = pathEnding.state for (idx in observations.size - 1 downTo 1) { val previousState = psi[currentState]!![idx]!! mostLikelyStateSequence = listOf(previousState) + mostLikelyStateSequence currentState = previousState } return mostLikelyStateSequence }
0
Kotlin
0
0
7252d9cd552ca57b82e027ebe2be2cb1ac6e30f6
2,687
hidden-markov-model-examples
MIT License
src/main/kotlin/g1401_1500/s1477_find_two_non_overlapping_sub_arrays_each_with_target_sum/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1401_1500.s1477_find_two_non_overlapping_sub_arrays_each_with_target_sum // #Medium #Array #Hash_Table #Dynamic_Programming #Binary_Search #Sliding_Window // #2023_06_13_Time_746_ms_(100.00%)_Space_50.7_MB_(100.00%) class Solution { fun minSumOfLengths(arr: IntArray, target: Int): Int { var l = 0 var r = 0 var sum = 0 val idx = IntArray(arr.size) idx.fill(arr.size + 1) var ans = 2 * arr.size + 1 while (r < arr.size || sum >= target) { if (sum < target) { sum += arr[r] r++ } else if (sum > target) { sum -= arr[l] l++ } else { val length = r - l idx[r - 1] = length if (l > 0 && idx[l - 1] < arr.size + 1) { ans = Math.min(ans, length + idx[l - 1]) } sum -= arr[l] l++ } if (r > 1) { idx[r - 1] = Math.min(idx[r - 1], idx[r - 2]) } } return if (ans <= 2 * arr.size) ans else -1 } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,145
LeetCode-in-Kotlin
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/RelativeSortArray.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.TreeMap private const val MAX_ARRAY_SIZE = 1001 fun Pair<IntArray, IntArray>.relativeSortArray(): IntArray { val cnt = IntArray(MAX_ARRAY_SIZE) for (n in first) { cnt[n]++ } var i = 0 for (n in second) { while (cnt[n]-- > 0) { first[i++] = n } } for (n in cnt.indices) { while (cnt[n]-- > 0) { first[i++] = n } } return first } fun Pair<IntArray, IntArray>.relativeSortArrayTree(): IntArray { val tree = TreeMap<Int, Int>() for (n in first) { tree[n] = tree.getOrDefault(n, 0) + 1 } var i = 0 for (n in second) { for (j in 0 until tree[n]!!) { first[i++] = n } tree.remove(n) } for (n in tree.keys) { for (j in 0 until tree[n]!!) { first[i++] = n } } return first }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,536
kotlab
Apache License 2.0
src/main/kotlin/icfp2019/analyzers/ConservativeDistanceAnalyzer.kt
bspradling
193,332,580
true
{"JavaScript": 797310, "Kotlin": 85937, "CSS": 9434, "HTML": 5859}
package icfp2019.analyzers import icfp2019.core.Analyzer import icfp2019.core.DistanceEstimate import icfp2019.model.GameBoard import icfp2019.model.GameState import icfp2019.model.Node import icfp2019.model.Point import org.jgrapht.alg.connectivity.ConnectivityInspector import org.jgrapht.alg.spanning.PrimMinimumSpanningTree import org.jgrapht.graph.AsSubgraph data class ConservativeDistance(val estimate: DistanceEstimate, val pathNodes: Set<Node>) object ConservativeDistanceAnalyzer : Analyzer<(position: Point) -> ConservativeDistance> { override fun analyze(map: GameBoard): (state: GameState) -> (position: Point) -> ConservativeDistance { val graphAnalyzer = GraphAnalyzer.analyze(map) val shortestPathAnalyzer = ShortestPathUsingDijkstra.analyze(map) return { state -> val graph = graphAnalyzer(state) val shortestPathAlgorithm = shortestPathAnalyzer(state) val unwrappedNodes = AsSubgraph(graph, graph.vertexSet().filter { it.isWrapped.not() }.toSet()) val connectivityInspector = ConnectivityInspector(unwrappedNodes) val connectedGraphs = connectivityInspector.connectedSets(); { point -> val node = map.get(point) val randomNodesFromEach: Set<Node> = connectedGraphs.map { it.first() } .plus(node) .toSet() val nodes: Set<Node> = randomNodesFromEach.windowed(2, step = 1).map { (n1, n2) -> shortestPathAlgorithm.getPath(n1, n2) }.flatMap { it.vertexList }.plus(connectedGraphs.flatten()).toSet() val connectedUnwrappedNodes = AsSubgraph(graph, nodes) val spanningTree = PrimMinimumSpanningTree(connectedUnwrappedNodes).spanningTree ConservativeDistance( DistanceEstimate(spanningTree.count()), spanningTree.edges.flatMap { listOf( graph.getEdgeSource(it), graph.getEdgeTarget(it) ) }.toSet() ) } } } }
0
JavaScript
0
0
9f7e48cce858cd6a517d4fb69b9a0ec2d2a69dc5
2,228
icfp-2019
The Unlicense
examples/src/main/kotlin/Sudoku.kt
UnitTestBot
501,947,851
false
{"Kotlin": 2669379, "C++": 97881, "C": 3122, "Shell": 2021, "CMake": 962}
import io.ksmt.KContext import io.ksmt.expr.KExpr import io.ksmt.expr.KInt32NumExpr import io.ksmt.solver.KModel import io.ksmt.solver.KSolverStatus import io.ksmt.solver.z3.KZ3Solver import io.ksmt.sort.KBoolSort import io.ksmt.sort.KIntSort import io.ksmt.utils.mkConst import kotlin.system.measureTimeMillis import kotlin.time.Duration.Companion.seconds const val BLOCK_SIZE = 3 const val SIZE = 9 const val EMPTY_CELL_VALUE = 0 val sudokuIndices = 0 until SIZE val sudokuTask = """ 9 * 6 | * 7 * | 4 * 3 * * * | 4 * * | 2 * * * 7 * | * 2 3 | * 1 * ------ ------- ------ 5 * * | * * * | 1 * * * 4 * | 2 * 8 | * 6 * * * 3 | * * * | * * 5 ------ ------- ------ * 3 * | 7 * * | * 5 * * * 7 | * * 5 | * * * 4 * 5 | * 1 * | 7 * 8 """.trimIndent() fun main() = KContext().useWith { // Parse and display a given Sudoku grid. val initialGrid = parseSudoku(sudokuTask) println("Task:") println(printSudokuGrid(initialGrid)) // Create symbolic variables for each cell of the Sudoku grid. val symbols = sudokuIndices.map { row -> sudokuIndices.map { col -> intSort.mkConst("x_${row}_${col}") } } // Create symbolic variables constraints according to the Sudoku rules. val rules = sudokuRules(symbols) // Create variable constraints from the filled cells of the Sudoku grid. val symbolAssignments = assignSymbols(symbols, initialGrid) // Create Z3 SMT solver instance. KZ3Solver(this).useWith { // Assert all constraints. rules.forEach { assert(it) } symbolAssignments.forEach { assert(it) } while (true) { val solution: List<List<Int>> val timeMs = measureTimeMillis { // Solve Sudoku. val status = check(timeout = 1.seconds) if (status != KSolverStatus.SAT) { println("No more solutions") return } // Get the SMT model and convert it to a Sudoku solution. solution = buildSolution(symbols, model()) } println("Solution (in $timeMs ms):") println(printSudokuGrid(solution)) assert(mkAnd(assignSymbols(symbols, solution)).not()) } } } private fun KContext.sudokuRules(symbols: List<List<KExpr<KIntSort>>>): List<KExpr<KBoolSort>> { // Each cell has a value from 1 to 9. val symbolConstraints = symbols.flatten().map { (it ge 1.expr) and (it le 9.expr) } // Each row contains distinct numbers. val rowDistinctConstraints = symbols.map { row -> mkDistinct(row) } // Each column contains distinct numbers. val colDistinctConstraints = sudokuIndices.map { col -> val colSymbols = sudokuIndices.map { row -> symbols[row][col] } mkDistinct(colSymbols) } // Each 3x3 block contains distinct numbers. val blockDistinctConstraints = (0 until SIZE step BLOCK_SIZE).flatMap { blockRow -> (0 until SIZE step BLOCK_SIZE).map { blockCol -> val block = (blockRow until blockRow + BLOCK_SIZE).flatMap { row -> (blockCol until blockCol + BLOCK_SIZE).map { col -> symbols[row][col] } } mkDistinct(block) } } return symbolConstraints + rowDistinctConstraints + colDistinctConstraints + blockDistinctConstraints } private fun KContext.assignSymbols( symbols: List<List<KExpr<KIntSort>>>, grid: List<List<Int>> ): List<KExpr<KBoolSort>> = sudokuIndices.flatMap { row -> sudokuIndices.mapNotNull { col -> val value = grid[row][col] if (value != EMPTY_CELL_VALUE) symbols[row][col] eq value.expr else null } } private fun KContext.buildSolution(symbols: List<List<KExpr<KIntSort>>>, model: KModel): List<List<Int>> = symbols.map { row -> row.map { symbol -> val value = model.eval(symbol) value as KInt32NumExpr value.value } } private fun parseSudoku(task: String): List<List<Int>> = task.lines() .map { row -> row.mapNotNull { it.cellValueOrNull() } } .filterNot { it.isEmpty() } private fun Char.cellValueOrNull(): Int? = when { isDigit() -> digitToInt() this == '*' -> EMPTY_CELL_VALUE else -> null } private fun printSudokuGrid(grid: List<List<Int>>) = buildString { for ((rowIdx, row) in grid.withIndex()) { for ((colIdx, cell) in row.withIndex()) { append(if (cell == EMPTY_CELL_VALUE) "*" else cell) append(" ") if ((colIdx + 1) % BLOCK_SIZE == 0 && (colIdx + 1) != SIZE) { append("| ") } } appendLine() if ((rowIdx + 1) % BLOCK_SIZE == 0 && (rowIdx + 1) != SIZE) { appendLine("-".repeat((SIZE + 2) * 2)) } } } private inline fun <T : AutoCloseable?, R> T.useWith(block: T.() -> R): R = use { it.block() }
9
Kotlin
11
27
fa2a997312627d7bc5afcaa3dfa1f1673221ce46
5,024
ksmt
Apache License 2.0
算法/寻找两个正序数组的中位数4.kt
Simplation
506,160,986
false
{"Kotlin": 10116}
package com.example.rain_demo.algorithm /** *@author: Rain *@time: 2022/7/20 14:34 *@version: 1.0 *@description: 寻找两个正序数组的中位数 */ fun main() { val nums1 = intArrayOf(1, 3) val nums2 = intArrayOf(2) val size1 = nums1.size val size2 = nums2.size val size = size1 + size2 if (size % 2 == 0) { val midIndex1 = size / 2 - 1 val midIndex2 = size / 2 val d = (getKthElement(nums1, nums2, midIndex1 + 1) + getKthElement(nums1, nums2, midIndex2 + 1)) / 2.0 println(d) } else { val midIndex = size / 2 val kthElement = getKthElement(nums1, nums2, midIndex + 1).toDouble() println(kthElement) } } fun getKthElement(nums1: IntArray, nums2: IntArray, k: Int): Int { val size1 = nums1.size val size2 = nums2.size var index1 = 0 var index2 = 0 var ele = k while (true) { if (index1 == size1) { return nums2[index2 + ele - 1] } if (index2 == size2) { return nums1[index1 + ele - 1] } if (ele == 1) { return Math.min(nums1[index1], nums2[index2]) } val h = ele / 2 val newIndex1 = Math.min(index1 + h, size1) - 1 val newIndex2 = Math.min(index2 + h, size2) - 1 val p1 = nums1[newIndex1] val p2 = nums2[newIndex2] if (p1 <= p2) { ele -= (newIndex1 - index1 + 1) index1 = newIndex1 + 1 } else { ele -= (newIndex2 - index2 + 1) index2 = newIndex2 + 1 } } } //region 调用 list api fun findMedianSortedArrays() { val nums1 = intArrayOf(1, 2) val nums2 = intArrayOf(3, 4) val newNum = DoubleArray(nums1.size + nums2.size) val index = add(newNum, nums1, 0) val size = second(newNum, nums2, 0, index) newNum.sort() if (size % 2 == 0) { val i = size / 2 val i1 = i - 1 val i2: Double = ((newNum[i] + newNum[i1]) / 2) println(i2) } else { val i = (size - 1) / 2 val i1 = newNum[i] println(i1) } } fun add(newNum: DoubleArray, l: IntArray, index: Int): Int { return if (index < l.size) { newNum[index] = l[index].toDouble() add(newNum, l, index + 1) } else { index } } fun second(newNum: DoubleArray, l: IntArray, index: Int, newIndex: Int): Int { return if (index < l.size) { newNum[newIndex] = l[index].toDouble() second(newNum, l, index + 1, newIndex + 1) } else { newIndex } } //endregion
0
Kotlin
0
0
d45feaa4c8ea2a08ce7357ee609a2df5b0639b68
2,604
OpenSourceRepository
Apache License 2.0
src/main/kotlin/pub/edholm/aoc2017/day3/SpiralMemory.kt
Edholm
112,762,269
false
null
package pub.edholm.aoc2017.day3 import pub.edholm.aoc2017.utils.getInputForDay import pub.edholm.aoc2017.utils.getResource fun main(args: Array<String>) { // Increase stack size with -Xss before running. val formattedInput = formatInput(getInputForDay(3)) val spiralMemory = SpiralMemory() println("Day 3:") println(" Part I: ${spiralMemory.countStepsFrom(formattedInput)}") println(" Part II: ${spiralMemory.partTwo(formattedInput)}") } private fun formatInput(input: String) = input.toInt() internal class SpiralMemory { fun partTwo(input: Int): Long { return getResource("b141481.txt") .split("\n") .mapNotNull { it.toLongOrNull() } .first { it > input } } fun countStepsFrom(square: Int): Int { return coordinatefromSquare(square) .distanceTo(Coordinate.origo()) } fun coordinatefromSquare(square: Int): Coordinate { if (square < 1) throw IllegalArgumentException("Illegal square, got $square, expected >= 1") return Coordinate(calcX(square), calcY(square)) } private fun calcX(square: Int): Int { if (square == 0) return 0 val k = (Math.floor(Math.sqrt(4.0 * (square - 2) + 1)) % 4) return calcX(square - 1) + Math.sin(k * Math.PI / 2).toInt() } private fun calcY(square: Int): Int { if (square == 0) return 0 val k = (Math.floor(Math.sqrt(4.0 * (square - 2) + 1)) % 4) return calcY(square - 1) + Math.cos(k * Math.PI / 2).toInt() } } data class Coordinate(val x: Int = 0, val y: Int = 0) { companion object { fun origo() = Coordinate() } /** @return the Manhattan distance */ fun distanceTo(other: Coordinate = origo()) = Math.abs(this.x - other.x) + Math.abs(this.y + other.y) }
0
Kotlin
0
3
1a087fa3dff79f7da293852a59b9a3daec38a6fb
1,722
aoc2017
The Unlicense
src/main/kotlin/g0901_1000/s0996_number_of_squareful_arrays/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0901_1000.s0996_number_of_squareful_arrays // #Hard #Array #Dynamic_Programming #Math #Bit_Manipulation #Backtracking #Bitmask // #2023_05_12_Time_139_ms_(100.00%)_Space_34.5_MB_(100.00%) import kotlin.math.sqrt class Solution { var count = 0 fun numSquarefulPerms(nums: IntArray): Int { val n = nums.size if (n < 2) { return count } backtrack(nums, n, 0) return count } private fun backtrack(nums: IntArray, n: Int, start: Int) { if (start == n) { count++ } val set: MutableSet<Int> = HashSet() for (i in start until n) { if (set.contains(nums[i])) { continue } swap(nums, start, i) if (start == 0 || isPerfectSq(nums[start], nums[start - 1])) { backtrack(nums, n, start + 1) } swap(nums, start, i) set.add(nums[i]) } } private fun swap(array: IntArray, a: Int, b: Int) { val temp = array[a] array[a] = array[b] array[b] = temp } private fun isPerfectSq(a: Int, b: Int): Boolean { val x = a + b val sqrt = sqrt(x.toDouble()) return sqrt - sqrt.toInt() == 0.0 } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,283
LeetCode-in-Kotlin
MIT License
src/main/kotlin/aoc2015/Day02.kt
davidsheldon
565,946,579
false
{"Kotlin": 161960}
package aoc2015 import aoc2022.product import utils.InputUtils fun main() { fun sides(len: List<Int>) = listOf((len[0]*len[1]), ( len[1]*len[2]),( len[0]*len[2])) fun area(len: List<Int>) = 2*sides(len).sum() + sides(len).min() fun boxes(input: List<String>) = input.map { it.split("x").map { it.toInt() } } fun part1(input: List<String>): Int { return boxes(input).sumOf { area(it)} } fun bow(len: List<Int>) = len.product() fun ribbon(len: List<Int>) = 2 * listOf((len[0]+len[1]), ( len[1]+len[2]),( len[0]+len[2])).min() fun part2(input: List<String>): Int { return boxes(input).sumOf { ribbon(it) + bow(it) } } // test if implementation meets criteria from the description, like: val input = InputUtils.downloadAndGetLines(2015, 2).toList() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5abc9e479bed21ae58c093c8efbe4d343eee7714
888
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/day3/PerfectlySphericalHousesInAVacuum.kt
SaujanShr
685,121,393
false
null
package day3 import getInput val INPUT = getInput("day3") fun run1(): String { return getHousesVisitedNormal(INPUT).size .toString() } fun run2(): String { return getHousesVisitedRobot(INPUT).size .toString() } fun getHousesVisitedNormal(directions: String): Set<Pair<Int, Int>> { var location = Pair(0, 0) val houses = mutableSetOf(location) directions .toCharArray() .forEach { location = nextLocation(location, it) houses.add(location) } return houses.toSet() } fun getHousesVisitedRobot(directions: String): Set<Pair<Int, Int>> { var santaLocation = Pair(0, 0) var robotLocation = Pair(0, 0) val houses = mutableSetOf(santaLocation) directions .chunked(2) .map { it.toCharArray() } .forEach { (santaDir, robotDir) -> santaLocation = nextLocation(santaLocation, santaDir) robotLocation = nextLocation(robotLocation, robotDir) houses.add(santaLocation) houses.add(robotLocation) } return houses.toSet() } fun nextLocation(location: Pair<Int, Int>, direction: Char): Pair<Int, Int> { return when (direction) { '^' -> Pair(location.first, location.second+1) 'v' -> Pair(location.first, location.second-1) '<' -> Pair(location.first-1, location.second) '>' -> Pair(location.first+1, location.second) else -> Pair(0, 0) } }
0
Kotlin
0
0
c6715a9570e62c28ed022c5d9b330a10443206c4
1,467
adventOfCode2015
Apache License 2.0
src/main/kotlin/linked_lists/Question5.kt
jimmymorales
446,845,269
false
{"Kotlin": 46222}
package linked_lists private fun LinkedListNode<Int>.plus(node: LinkedListNode<Int>): LinkedListNode<Int> { var n1: LinkedListNode<Int>? = this var n2: LinkedListNode<Int>? = node val resHead = LinkedListNode(0) var current: LinkedListNode<Int>? = null var acm = 0 while (n1 != null || n2 != null) { if (current == null) { current = resHead } else { current.next = LinkedListNode(0) current = current.next } val sum = (n1?.data ?: 0) + (n2?.data ?: 0) + acm current?.data = if (sum > 9) sum - 10 else sum acm = if (sum > 9) 1 else 0 n1 = n1?.next n2 = n2?.next } if (acm != 0) { current?.next = LinkedListNode(acm) } return resHead } private fun LinkedListNode<Int>.plusRec(node: LinkedListNode<Int>): LinkedListNode<Int> { return sumHelper(this, node)!! } private fun sumHelper(node1: LinkedListNode<Int>?, node2: LinkedListNode<Int>?, carry: Int = 0): LinkedListNode<Int>? { if (node1 == null && node2 == null) { return null } val value = carry + (node1?.data ?: 0) + (node2?.data ?: 0) return LinkedListNode(value % 10).apply { next = sumHelper(node1?.next, node2?.next, if (value > 9) 1 else 0) } }
0
Kotlin
0
0
8a32d379d5f3a2e779f6594d949f63d2e02aad4c
1,295
algorithms
MIT License
string-similarity/src/commonMain/kotlin/com/aallam/similarity/Jaccard.kt
aallam
597,692,521
false
null
package com.aallam.similarity import com.aallam.similarity.internal.Shingle /** * Each input string is converted into a set of n-grams, the Jaccard index is then computed as `|A ∩ B| / |A ∪ B|`. * * Like Q-Gram distance, the input strings are first converted into sets of n-grams (sequences of n characters, also * called k-shingles), but this time the cardinality of each n-gram is not taken into account. * * Jaccard index is a metric distance. * * @param k length of k-shingles */ public class Jaccard(private val k: Int = 3) { /** * Compute Jaccard index. `|A ∩ B| / |A ∪ B|`. * @param first the first string to compare. * @param second the second string to compare. */ public fun similarity(first: String, second: String): Double { if (first == second) return 1.0 val p1 = Shingle.profile(first, k) val p2 = Shingle.profile(second, k) val union = p1.keys + p2.keys val inter = p1.keys.size + p2.keys.size - union.size return inter.toDouble() / union.size } /** * Distance is computed as 1 - similarity. * * @param first the first string to compare. * @param second the second string to compare. */ public fun distance(first: String, second: String): Double { return 1.0 - similarity(first, second) } }
0
Kotlin
0
1
40cd4eb7543b776c283147e05d12bb840202b6f7
1,353
string-similarity-kotlin
MIT License
Kotlin/src/Permutations.kt
TonnyL
106,459,115
false
null
/** * Given a collection of distinct numbers, return all possible permutations. * * For example, * [1,2,3] have the following permutations: * [ * [1,2,3], * [1,3,2], * [2,1,3], * [2,3,1], * [3,1,2], * [3,2,1] * ] * * Accepted. */ class Permutations { fun permute(nums: IntArray): List<List<Int>> { val results = mutableListOf<List<Int>>() if (nums.isEmpty()) { return results } if (nums.size == 1) { return results.apply { add(mutableListOf(nums[0])) } } val ints = IntArray(nums.size - 1) System.arraycopy(nums, 0, ints, 0, nums.size - 1) for (list in permute(ints)) { for (i in 0..list.size) { val tmp = mutableListOf<Int>() tmp.addAll(list) tmp.add(i, nums[nums.size - 1]) results.add(tmp) } } return results } }
1
Swift
22
189
39f85cdedaaf5b85f7ce842ecef975301fc974cf
965
Windary
MIT License
src/exercises/Day06.kt
Njko
572,917,534
false
{"Kotlin": 53729}
// ktlint-disable filename package exercises import readInput fun main() { // Can be solved with: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/windowed-sequence.html fun searchIndexOfMarker(data: String, markerSize: Int): Int { var startIndex = 0 var indexOfMarker = markerSize while (data.substring(startIndex until startIndex + markerSize) .toList() .distinct() .size < markerSize ) { // continue looking for marker startIndex += 1 indexOfMarker += 1 } return indexOfMarker } fun part1(input: String): Int { return searchIndexOfMarker(input, 4) } fun part2(input: String): Int { return searchIndexOfMarker(input, 14) } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") println("Test results:") println(part1(testInput[0])) check(part1(testInput[0]) == 5) check(part1("nppdvjthqldpwncqszvftbrmjlhg") == 6) check(part1("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 10) check(part1("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 11) println(part2("mjqjpqmgbljsphdztnvjfqwrcgsmlb")) check(part2("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 19) check(part2("bvwbjplbgvbhsrlpgdmjqwftvncz") == 23) check(part2("nppdvjthqldpwncqszvftbrmjlhg") == 23) check(part2("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 29) check(part2("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 26) val input = readInput("Day06") // println("Final results:") println(part1(input[0])) check(part1(input[0]) == 1707) println(part2(input[0])) check(part2(input[0]) == 3697) }
0
Kotlin
0
2
68d0c8d0bcfb81c183786dfd7e02e6745024e396
1,728
advent-of-code-2022
Apache License 2.0
src/main/kotlin/se/saidaspen/aoc/aoc2015/Day07.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2015 import se.saidaspen.aoc.util.Day fun main() = Day07.run() object Day07 : Day(2015, 7) { private var data = input.lines() private val values = mutableMapOf<String, Int>() private val consts = mutableMapOf<String, String>() private val ands = mutableMapOf<String, Pair<String, String>>() private val ors = mutableMapOf<String, Pair<String, String>>() private val lshifts = mutableMapOf<String, Pair<String, Int>>() private val rshifts = mutableMapOf<String, Pair<String, Int>>() private val nots = mutableMapOf<String, String>() init { for (line in data) { when { "AND" in line -> { val (a, _, b, _, c) = line.split(" ") ands[c] = a to b } "OR" in line -> { val (a, _, b, _, c) = line.split(" ") ors[c] = a to b } "LSHIFT" in line -> { val (a, _, b, _, c) = line.split(" ") lshifts[c] = a to b.toInt() } "RSHIFT" in line -> { val (a, _, b, _, c) = line.split(" ") rshifts[c] = a to b.toInt() } "NOT" in line -> { val (_, a, _, b) = line.split(" ") nots[b] = a } else -> { val (a, _, b) = line.split(" ") consts[b] = a } } } } private fun find(x: String): Int { values[x]?.let { return it } val i = x.toIntOrNull() if (i != null) { values[x] = i return i } consts[x]?.let { values[x] = find(it); return values[x]!! } ands[x]?.let { values[x] = find(it.first) and find(it.second); return values[x]!! } ors[x]?.let { values[x] = find(it.first) or find(it.second); return values[x]!! } lshifts[x]?.let { values[x] = (find(it.first) shl it.second) and UShort.MAX_VALUE.toInt(); return values[x]!! } rshifts[x]?.let { values[x] = find(it.first) shr it.second; return values[x]!! } nots[x]?.let { values[x] = find(it).inv() and UShort.MAX_VALUE.toInt(); return values[x]!! } error("Can't find $x") } override fun part1(): Any { return find("a") } override fun part2(): Any { val valA = find("a") values.clear() values["b"] = valA return find("a") } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
2,601
adventofkotlin
MIT License
src/main/kotlin/com/ginsberg/advent2016/Day21.kt
tginsberg
74,924,040
false
null
/* * Copyright (c) 2016 by <NAME> */ package com.ginsberg.advent2016 /** * Advent of Code - Day 21: December 21, 2016 * * From http://adventofcode.com/2016/day/21 * */ class Day21(val instructions: List<String>) { companion object { private val SWAP_POSITION = Regex("""^swap position (\d+) with position (\d+)$""") private val SWAP_LETTERS = Regex("""^swap letter (\S) with letter (\S)$""") private val ROTATE_SHIFT = Regex("""^rotate (left|right) (\d+) step(s?)$""") private val ROTATE_LETTER = Regex("""^rotate based on position of letter (\S)$""") private val REVERSE = Regex("""^reverse positions (\d+) through (\d+)$""") private val MOVE = Regex("""^move position (\d+) to position (\d+)$""") private val RIGHT_SHIFT = listOf(1,2,3,4,6,7,8,9) private val LEFT_SHIFT = listOf(9,1,6,2,7,3,8,4) } fun solvePart1(word: String): String = instructions.fold(word){ carry, next -> mutate(carry, next, true)} fun solvePart2(word: String): String = instructions.reversed().fold(word){ carry, next -> mutate(carry, next, false)} fun mutate(input: String, instruction: String, forward: Boolean): String = when { SWAP_POSITION.matches(instruction) -> { val (x, y) = SWAP_POSITION.matchEntire(instruction)!!.destructured swapPosition(input, x.toInt(), y.toInt()) } SWAP_LETTERS.matches(instruction) -> { val (x, y) = SWAP_LETTERS.matchEntire(instruction)!!.destructured swapLetters(input, x[0], y[0]) } ROTATE_SHIFT.matches(instruction) -> { val (dir, x) = ROTATE_SHIFT.matchEntire(instruction)!!.destructured if(forward) rotateShift(input, dir, x.toInt()) else rotateShift(input, if(dir == "left") "right" else "left", x.toInt()) } ROTATE_LETTER.matches(instruction) -> { val (x) = ROTATE_LETTER.matchEntire(instruction)!!.destructured rotateLetter(input, x[0], forward) } REVERSE.matches(instruction) -> { val (x, y) = REVERSE.matchEntire(instruction)!!.destructured reverse(input, x.toInt(), y.toInt()) } MOVE.matches(instruction) -> { val (x, y) = MOVE.matchEntire(instruction)!!.destructured if(forward) move(input, x.toInt(), y.toInt()) else move(input, y.toInt(), x.toInt()) } else -> input } fun swapPosition(input: String, x: Int, y: Int): String { val arr = input.toCharArray() val tmp = input[x] arr[x] = arr[y] arr[y] = tmp return arr.joinToString("") } fun swapLetters(input: String, x: Char, y: Char): String = input.map { if(it == x) y else if(it == y) x else it }.joinToString("") fun rotateShift(input: String, direction: String, steps: Int): String { val sm = steps % input.length return if (direction == "left") input.drop(sm) + input.take(sm) else input.drop(input.length - sm).take(sm) + input.take(input.length - sm) } fun rotateLetter(input: String, ch: Char, forward: Boolean): String { val idx = input.indexOf(ch) return if(forward) rotateShift(input, "right", RIGHT_SHIFT[idx]) else rotateShift(input, "left", LEFT_SHIFT[idx]) } fun reverse(input: String, x: Int, y: Int): String = input.substring(0, x) + input.drop(x).take(y-x+1).reversed() + input.drop(y+1) fun move(input: String, x: Int, y: Int): String { val ch = input[x] val unX = input.substring(0, x) + input.substring(x+1) return unX.substring(0, y) + ch + unX.substring(y) } }
0
Kotlin
0
3
a486b60e1c0f76242b95dd37b51dfa1d50e6b321
3,855
advent-2016-kotlin
MIT License
src/day01/Day01.kt
tiginamaria
573,173,440
false
{"Kotlin": 7901}
fun main() { fun sums(input: List<String>): List<Int> { val curSums = mutableListOf<Int>() var curSum = 0 input.forEach { if (it.isEmpty()) { curSums.add(curSum) curSum = 0 } else { curSum += it.toInt() } } return curSums } fun part1(input: List<String>): Int { return sums(input).max() } fun part2(input: List<String>): Int { return sums(input).sorted().takeLast(3).sum() } // test if implementation meets criteria from the description, like: val inputPart0 = readInput("Day01_part1", 1) println(part1(inputPart0)) val inputPart1 = readInput("Day01_part2", 1) println(part2(inputPart1)) }
0
Kotlin
0
0
bf81cc9fbe11dce4cefcb80284e3b19c4be9640e
781
advent-of-code-kotlin
Apache License 2.0
2020/day4/day4.kt
Deph0
225,142,801
false
null
class day4 { fun part1(input: List<String>): Int { val validFields = listOf( "byr", // (Birth Year) "iyr", // (Issue Year) "eyr", // (Expiration Year) "hgt", // (Height) "hcl", // (Hair Color) "ecl", // (Eye Color) "pid" // (Passport ID) // "cid" // (Country ID) - optional ) val inputFields = input.map { it.split(" ") } val inputKeyValue = inputFields.map { it.map { it.split(":") } } val res = inputKeyValue.map { it.count { validFields.contains(it[0]) }} // println(inputFields) // println(inputKeyValue) // println(res) return res.count { it == validFields.size } } fun part2(input: List<String>): Int { // https://stackoverflow.com/questions/39138073/regex-for-numbers-1-25 val validFieldRules = hashMapOf( "byr" to Regex("""(19[2-9]\d|200[0-3])"""), // (Birth Year) "iyr" to Regex("""20(1\d|20)"""), // (Issue Year) "eyr" to Regex("""20(2\d|30)"""), // (Expiration Year) "hgt" to Regex("""(1([5-8]\d|9[0-3])cm|([5-6]\d|7[0-6])in)"""), // (Height) "hcl" to Regex("""#([a-f0-9]{6})"""), // (Hair Color) "ecl" to Regex("""(amb|blu|brn|gry|grn|hzl|oth)"""), // (Eye Color) "pid" to Regex("""\d{9}""")// (Passport ID) ) // used for debug, change from inputFields.map to fakeinput.map val fakeinput = listOf( "" // listOf( // listOf("byr", "2002"), // valid // listOf("byr", "2003"), // invalid -fixed // listOf("hgt", "60in"), // valid // listOf("hgt", "190cm"), // valid // listOf("hgt", "190in"), // invalid -fixed // listOf("hgt", "190"), // invalid -fixed // listOf("hcl", "#123abc"), // valid // listOf("hcl", "#123abz"), // invalid // listOf("hcl", "123abc"), // invalid // listOf("ecl", "brn"), // valid // listOf("ecl", "wat"), // invalid // listOf("pid", "000000001"), // valid // listOf("pid", "0123456789") // invalid -fixed // ) // , listOf() // ---- invalid passwords but with valid fields ---- /*listOf( listOf("eyr","1972"), listOf("cid","100"), listOf("hcl","#18171d"), listOf("ecl","amb"), listOf("hgt","170"), listOf("pid","186cm"), listOf("iyr","2018"), listOf("byr","1926") ), listOf( listOf("iyr","2019"), listOf("hcl","#602927"), listOf("eyr","1967"), listOf("hgt","170cm"), listOf("ecl","grn"), listOf("pid","012533040"), listOf("byr","1946") ), listOf( listOf("hcl","dab227"), listOf("iyr","2012"), listOf("ecl","brn"), listOf("hgt","182cm"), listOf("pid","021572410"), listOf("eyr","2020"), listOf("byr","1992"), listOf("cid","277") ), listOf( listOf("hgt","59cm"), listOf("ecl","zzz"), listOf("eyr","2038"), listOf("hcl","74454a"), listOf("iyr","2023"), listOf("pid","3556412378"), listOf("byr","2007") )*/ // ---- end of invalid passports ---- // --- start of valid passports --- // listOf( // listOf("pid","087499704"), // listOf("hgt","74in"), // listOf("ecl","grn"), // listOf("iyr","2012"), // listOf("eyr","2030"), // listOf("byr","1980"), // listOf("hcl","#623a2f") // ), // listOf( // listOf("eyr","2029"), // listOf("ecl","blu"), // listOf("cid","129"), // listOf("byr","1989"), // listOf("iyr","2014"), // listOf("pid","896056539"), // listOf("hcl","#a97842"), // listOf("hgt","165cm") // ), // listOf( // listOf("hcl","#888785"), // listOf("hgt","164cm"), // listOf("byr","2001"), // listOf("iyr","2015"), // listOf("cid","88"), // listOf("pid","545766238"), // listOf("ecl","hzl"), // listOf("eyr","2022") // ), // listOf( // listOf("iyr","2010"), // listOf("hgt","158cm"), // listOf("hcl","#b6652a"), // listOf("ecl","blu"), // listOf("byr","1944"), // listOf("eyr","2021"), // listOf("pid","093154719") // ) // --- end of valid passports --- ) val inputFields = input.map { it.split(" ").map { it.split(":") } } // println(fakeinput) // println(inputFields) val res = inputFields.map { passport -> // println("--- $passport ---") val tmp = passport.map { passportdata -> val (a, b) = passportdata // key, value // var validentry = validFieldRules[a]?.containsMatchIn(b) // wrong method, not strict match var validentry = validFieldRules[a]?.matches(b) // println("k: $a v: $b valid: $validentry") validentry }.count { it == true } // println("Valid entries: $tmp\n") tmp }.count { it == validFieldRules.size } return res } init { val exampleinput = """ ecl:gry pid:860033327 eyr:2020 hcl:#fffffd byr:1937 iyr:2017 cid:147 hgt:183cm iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884 hcl:#cfa07d byr:1929 hcl:#ae17e1 iyr:2013 eyr:2024 ecl:brn pid:760753108 byr:1931 hgt:179cm hcl:#cfa07d eyr:2025 pid:166559648 iyr:2011 ecl:brn hgt:59in """.trimIndent().split("\n\n").map {it.replace("\n", " ")} println("day4-pt1-example: " + part1(exampleinput)) // 2 println("day4-pt2-example: " + part2(exampleinput)) val input = """ byr:2010 pid:#1bb4d8 eyr:2021 hgt:186cm iyr:2020 ecl:grt pid:937877382 eyr:2029 ecl:amb hgt:187cm iyr:2019 byr:1933 hcl:#888785 ecl:hzl eyr:2020 hcl:#18171d iyr:2019 hgt:183cm byr:1935 hcl:#7d3b0c hgt:183cm cid:135 byr:1992 eyr:2024 iyr:2013 pid:138000309 ecl:oth ecl:hzl hgt:176cm pid:346059944 byr:1929 cid:150 eyr:1924 hcl:#fffffd iyr:2016 iyr:2011 cid:99 ecl:amb eyr:2030 hcl:#18171d hgt:165cm pid:897123249 byr:1948 hcl:#cfa07d pid:827609097 ecl:gry iyr:2017 byr:1963 eyr:2029 hgt:72in hcl:#6b5442 eyr:2028 iyr:2016 ecl:hzl hgt:152cm pid:432183209 byr:1984 hgt:169cm hcl:#888785 ecl:hzl pid:626107466 byr:1929 iyr:2013 cid:217 eyr:2026 hcl:#bdb95d byr:1935 eyr:2023 ecl:blu iyr:2011 cid:90 hgt:64cm pid:155167914 iyr:2017 byr:1943 cid:56 hcl:#888785 hgt:193cm pid:621305634 ecl:amb eyr:2024 ecl:gry hcl:#a97842 pid:936999610 cid:169 byr:1991 eyr:2029 hgt:175cm iyr:2017 hcl:#866857 ecl:gry byr:1975 hgt:71in pid:180628540 eyr:2020 iyr:2017 hcl:#cfa07d hgt:153cm byr:1962 cid:325 iyr:2018 eyr:2020 ecl:amb pid:579364506 hcl:#6b5442 iyr:2010 ecl:amb byr:2001 eyr:2020 pid:406219444 hgt:173cm pid:#430c70 ecl:gry iyr:2018 hcl:#866857 eyr:2021 cid:97 byr:1997 hgt:75cm iyr:2023 pid:#518780 eyr:2034 ecl:zzz hgt:72cm hcl:z byr:2010 pid:1961614335 hcl:#c0946f hgt:157 ecl:grn eyr:2031 byr:1972 iyr:1992 cid:142 eyr:2022 ecl:amb hgt:68in hcl:#6b5442 byr:1927 pid:112372155 iyr:2012 byr:1972 hgt:169cm hcl:#888785 cid:75 iyr:2015 eyr:2021 ecl:oth pid:7889059161 ecl:brn iyr:2020 eyr:2026 hgt:151cm byr:1961 pid:468038868 hcl:#18171d ecl:blu hcl:#b6652a byr:1959 hgt:151cm cid:109 pid:708689901 eyr:2026 iyr:2012 ecl:grt byr:2024 iyr:1995 pid:225263933 hcl:z eyr:2040 hgt:127 cid:162 pid:683129831 cid:144 hcl:#a97842 hgt:155cm eyr:2030 byr:1962 iyr:2015 ecl:oth byr:2009 hcl:#866857 cid:329 iyr:1955 eyr:1994 pid:085929595 byr:1940 pid:936748944 hgt:160cm eyr:2024 iyr:2013 cid:205 ecl:grn hcl:#c0946f hgt:193in cid:161 iyr:1984 pid:#f82e35 byr:2018 hcl:b1a551 eyr:2014 ecl:#4d2d5b byr:1978 iyr:2011 hgt:172cm hcl:#efcc98 ecl:brn pid:759624394 eyr:2020 eyr:2020 pid:622444743 hcl:#a97842 ecl:gry iyr:2014 hgt:157cm byr:1980 hgt:181cm eyr:2020 iyr:2014 hcl:#602927 ecl:brn byr:1934 hgt:188cm ecl:blu eyr:2029 pid:757878469 hcl:#b6652a iyr:2017 byr:1995 ecl:blu hcl:#341e13 eyr:2027 iyr:2020 pid:283341241 hgt:174cm byr:1960 iyr:2012 hcl:dc007d eyr:2011 hgt:166cm pid:9889788504 ecl:#a9b3a1 ecl:hzl hgt:70in pid:620966688 iyr:1998 hcl:z eyr:2022 hgt:187cm cid:190 pid:818634983 byr:1925 ecl:gry hcl:#ceb3a1 eyr:2021 iyr:2015 hcl:#c0946f iyr:2017 byr:1953 eyr:2030 hgt:67in pid:085876735 ecl:hzl pid:205284134 hcl:#cfa07d byr:1987 hgt:167cm eyr:2022 ecl:oth iyr:2020 iyr:2018 hgt:180cm pid:232535961 eyr:2027 byr:1999 hcl:#18171d ecl:oth cid:342 hgt:171cm ecl:blu byr:1920 hcl:#18171d eyr:2023 iyr:2012 pid:353601791 byr:1956 ecl:brn pid:141896408 iyr:2012 cid:116 eyr:2028 hgt:164cm hcl:#866857 hcl:#fffffd ecl:oth eyr:2030 hgt:67in pid:855777018 byr:1975 iyr:2012 ecl:blu pid:45257034 hcl:#c5447e iyr:1928 cid:212 byr:1974 pid:080116868 cid:97 eyr:2021 iyr:2020 ecl:grn byr:1987 hgt:62in hcl:#efcc98 eyr:2027 hcl:#efcc98 iyr:2020 ecl:amb cid:111 pid:143966954 hgt:165cm iyr:2015 byr:1941 pid:798564127 hgt:183cm ecl:oth eyr:2020 byr:1999 iyr:2017 hcl:#ceb3a1 pid:640883740 hgt:164cm cid:105 ecl:hzl eyr:2022 iyr:2014 eyr:2023 ecl:grn hcl:#ceb3a1 hgt:188cm byr:1981 pid:185076942 cid:342 hgt:150cm iyr:2013 eyr:2035 cid:184 hcl:#341e13 pid:#e2dd63 byr:2014 ecl:brn eyr:2024 iyr:2015 ecl:brn hgt:76in hcl:#866857 byr:1958 pid:886486245 ecl:amb cid:113 byr:1931 pid:087380735 iyr:2010 eyr:2028 hgt:161cm byr:1926 eyr:2024 iyr:2012 pid:036335738 hcl:#c0946f hgt:153cm ecl:brn hcl:bf952a hgt:169in eyr:1925 pid:166cm iyr:2028 ecl:lzr byr:1938 hgt:154cm hcl:#733820 ecl:oth iyr:2016 byr:1925 eyr:2020 pid:590365390 eyr:2029 hgt:166cm pid:670283165 hcl:#ceb3a1 iyr:2018 byr:1955 ecl:gry hgt:181cm iyr:2016 hcl:#866857 byr:1933 eyr:2028 ecl:blu hgt:184cm cid:138 hcl:#623a2f pid:081880232 byr:1929 ecl:hzl eyr:2030 iyr:2015 pid:825698872 eyr:2026 hgt:181cm iyr:2015 hcl:#866857 byr:1950 ecl:gry eyr:2022 byr:2002 iyr:2013 hcl:#fffffd ecl:hzl pid:687380398 hgt:173cm byr:2016 ecl:zzz pid:0514910377 hcl:ebe8b2 eyr:2025 iyr:2011 hgt:183cm ecl:amb hgt:67in pid:602547016 byr:1985 eyr:2021 iyr:2014 iyr:2014 eyr:2020 ecl:grn pid:642261584 byr:1970 hgt:190cm cid:278 hcl:#7d3b0c eyr:2035 cid:226 hcl:64ac73 byr:2007 pid:176cm ecl:#927fbf iyr:2006 iyr:2019 eyr:2026 ecl:brn hgt:162cm cid:108 hcl:#ceb3a1 pid:774441166 byr:1951 hgt:166cm eyr:2024 hcl:#b6652a byr:1934 pid:260873380 iyr:2016 hcl:z iyr:2015 ecl:blu eyr:2040 byr:1927 pid:431855667 hgt:173cm cid:209 eyr:2034 cid:139 ecl:#cb7564 byr:2023 hgt:172in iyr:2027 pid:2877047600 ecl:brn cid:125 hcl:#888785 iyr:2011 pid:739399822 hgt:184cm byr:1989 hcl:#c0946f pid:891125961 hgt:175cm iyr:2010 eyr:2027 ecl:gry byr:1930 hgt:164cm byr:1935 eyr:2023 pid:684366743 ecl:oth hcl:#18171d iyr:2013 hcl:#341e13 hgt:64in byr:1959 ecl:#c53bbb iyr:2014 eyr:2029 pid:174cm eyr:1943 ecl:#e52638 hcl:06a964 byr:1959 cid:342 iyr:2029 hgt:178in pid:150cm byr:1966 hcl:#733820 iyr:2020 ecl:gry eyr:2021 pid:229789071 pid:363947487 ecl:blu hcl:#623a2f byr:1972 iyr:2017 hgt:184cm eyr:2023 ecl:oth pid:460855562 iyr:2010 cid:148 hcl:z hgt:74cm byr:2005 eyr:2027 iyr:2017 hgt:172cm byr:1975 ecl:amb cid:97 hcl:#c0946f pid:591950054 eyr:2022 ecl:oth hgt:185cm hcl:#6b5442 byr:1978 iyr:2018 pid:849124937 cid:78 iyr:1927 hgt:121 eyr:2020 ecl:#c73b1a hcl:#cfa07d pid:4505701953 byr:2020 cid:235 hgt:183cm hcl:#341e13 iyr:2019 byr:1932 ecl:#144539 pid:184cm eyr:1954 iyr:2020 cid:332 byr:1930 hcl:#6b5442 hgt:168cm ecl:amb eyr:2023 pid:332084752 ecl:blu byr:1922 cid:135 iyr:2019 eyr:2028 pid:481801918 hcl:#efcc98 hgt:76in ecl:grn pid:188906975 cid:153 hgt:173cm eyr:2029 iyr:2012 hcl:#733820 byr:2001 eyr:2029 byr:1948 iyr:2020 hgt:167cm ecl:brn hcl:#623a2f pid:577624152 hcl:#18171d pid:262528276 byr:1949 iyr:2020 eyr:2023 hcl:#c0946f iyr:2016 byr:1967 ecl:brn hgt:162cm pid:139002508 eyr:2030 eyr:2030 hgt:72in iyr:2013 pid:542944485 cid:112 byr:1950 hcl:#a97842 ecl:amb pid:772544664 eyr:2023 ecl:gry hgt:159cm iyr:2012 byr:1956 hcl:#602927 hgt:172in ecl:grt pid:668387651 byr:2019 iyr:1995 hcl:bc51ff eyr:1921 pid:322272953 ecl:brn hcl:#a97842 byr:1990 eyr:2021 iyr:2017 hgt:181cm eyr:2029 iyr:2011 pid:503169142 byr:1980 hcl:#a97842 ecl:oth pid:514042929 ecl:amb eyr:2030 hgt:154cm iyr:2010 hcl:#623a2f byr:1989 byr:1988 pid:156381939 iyr:2016 hgt:161cm eyr:2030 ecl:brn hcl:#7d3b0c pid:545819361 hgt:191cm iyr:2012 byr:1982 eyr:2025 ecl:zzz hcl:z pid:872911892 byr:1924 iyr:1974 hcl:#602927 ecl:brn hgt:154cm eyr:2028 hcl:#602927 hgt:188cm byr:2007 pid:503933918 ecl:utc eyr:2030 iyr:2020 cid:132 ecl:hzl eyr:2020 hcl:#888785 hgt:181cm pid:721383537 iyr:2018 byr:1983 cid:50 pid:8590606 hcl:#18171d eyr:2039 iyr:2024 cid:161 byr:2027 hgt:160in byr:1956 cid:214 pid:187cm iyr:2027 hcl:z eyr:2033 ecl:grn byr:2029 pid:90562860 hcl:4fa0d1 iyr:2024 eyr:2040 cid:62 ecl:#07ae33 hgt:186in pid:557319679 byr:1945 hgt:182cm eyr:2026 iyr:2012 hcl:#866857 ecl:hzl cid:219 eyr:2028 iyr:2022 ecl:zzz cid:273 hgt:133 pid:4084335529 byr:2011 hcl:z pid:69196974 hcl:z iyr:2014 ecl:amb byr:1928 hgt:183in eyr:2028 pid:771762218 byr:2003 ecl:dne hcl:70eb58 iyr:2027 cid:330 ecl:hzl pid:195721774 hcl:#602927 byr:1945 hgt:186cm eyr:2037 iyr:2011 ecl:brn eyr:2028 hgt:171cm byr:1980 hcl:#fffffd pid:563089389 iyr:2016 eyr:2027 iyr:2011 ecl:gry byr:1932 hcl:#18171d pid:398526372 pid:97363921 hgt:178cm ecl:oth eyr:2028 byr:1930 cid:345 iyr:2018 hcl:#1fb2f0 ecl:amb iyr:2012 byr:1961 pid:679312513 eyr:2026 hcl:#cfa07d hgt:174cm byr:1980 hcl:#80055d cid:235 ecl:oth pid:159696517 eyr:2030 hgt:191cm iyr:2012 iyr:2013 eyr:2027 hcl:#866857 pid:621184472 cid:137 hgt:175cm byr:2000 ecl:hzl byr:1998 hgt:166cm ecl:oth eyr:2025 iyr:2018 hcl:#a97842 pid:358495679 byr:1928 ecl:oth cid:122 hcl:#6b5442 hgt:189cm eyr:2020 iyr:2018 hgt:186cm byr:2020 hcl:79d685 ecl:grt iyr:1944 pid:3659998623 eyr:2000 hgt:63in ecl:oth eyr:2029 iyr:2013 pid:942282912 hcl:#c0946f byr:1989 byr:1997 hcl:#623a2f eyr:2026 cid:149 pid:702981538 ecl:amb hgt:178cm iyr:2017 ecl:brn iyr:2015 byr:1932 pid:191192548 cid:318 hcl:#7d3b0c eyr:2020 hcl:#866857 eyr:2028 pid:341036511 cid:343 iyr:2020 hgt:173cm byr:1973 ecl:blu iyr:2016 pid:165707654 hgt:181cm ecl:hzl cid:119 byr:1973 hcl:#b6652a iyr:2014 pid:833337583 byr:1936 cid:91 hcl:#602927 ecl:amb hgt:165cm eyr:2021 byr:1938 ecl:grn hcl:#a55daf eyr:2021 cid:199 pid:701515796 iyr:2015 hgt:71in hcl:#a97842 ecl:blu eyr:2030 iyr:2020 hgt:155cm byr:1927 pid:524488639 pid:385084163 eyr:2025 hcl:#866857 ecl:oth iyr:2020 hgt:177cm byr:2002 eyr:2029 hgt:177cm cid:142 ecl:hzl hcl:#866857 iyr:2015 byr:1946 pid:459543573 pid:826977286 eyr:2030 iyr:2016 byr:1996 hcl:#efcc98 ecl:gry hgt:180cm eyr:2029 iyr:1976 pid:872821863 ecl:gry byr:2030 hgt:191cm byr:1924 pid:918753019 ecl:blu iyr:2019 hcl:#5d69e0 eyr:2024 ecl:lzr iyr:2020 pid:991375034 byr:1947 eyr:1923 hcl:8224f6 hgt:157 eyr:2021 byr:1946 hgt:189cm ecl:grn iyr:2010 hcl:#cfa07d pid:246923037 iyr:2016 ecl:oth hgt:155cm byr:1962 pid:924702739 eyr:2028 hcl:#7d3b0c pid:7358100461 hgt:183cm byr:2011 hcl:#a97842 iyr:2020 eyr:1963 cid:71 ecl:hzl hcl:#c0946f byr:1934 hgt:183cm iyr:2018 pid:433993423 eyr:2028 hgt:183cm hcl:#cfa07d iyr:2018 byr:1975 eyr:2024 eyr:2021 ecl:amb byr:1992 hgt:164cm iyr:2020 cid:302 pid:271720491 hgt:161cm iyr:2012 byr:1947 hcl:#6b5442 ecl:grn eyr:2024 pid:860852799 eyr:2021 byr:1980 hcl:#6b5442 iyr:2010 hgt:174cm ecl:hzl hcl:#623a2f eyr:2028 iyr:2016 pid:813453232 hgt:173cm cid:131 byr:1962 byr:1975 hgt:177cm pid:290098810 cid:241 ecl:oth hcl:#a5fc9f eyr:2021 iyr:2013 byr:1947 pid:762351259 hgt:178cm ecl:amb hcl:#d07b27 iyr:2017 eyr:2028 cid:271 iyr:2012 pid:053790533 eyr:2023 ecl:grn hcl:#623a2f byr:1939 cid:70 hgt:189cm hcl:#c0946f pid:891312170 byr:1986 iyr:2012 hgt:163cm eyr:2023 cid:150 iyr:2015 byr:1963 pid:695024197 hcl:#efcc98 ecl:brn hgt:166cm eyr:2022 cid:276 eyr:1945 hgt:150in byr:2007 ecl:utc hcl:z cid:272 pid:186cm iyr:1927 pid:956296646 iyr:2015 hgt:168cm byr:1979 eyr:2029 ecl:gry hcl:#866857 pid:745452488 byr:1998 eyr:2025 hcl:#602927 hgt:158cm iyr:2015 eyr:2027 iyr:2017 pid:6173634679 byr:2001 ecl:hzl hcl:babc41 hgt:76cm ecl:grn iyr:2019 hcl:#3881ca byr:1975 eyr:2023 hgt:162cm hcl:#ceb3a1 hgt:169in pid:398759957 eyr:2020 byr:2016 iyr:2011 ecl:#be3622 hgt:156cm hcl:#b6652a pid:166cm iyr:2027 byr:2003 eyr:2036 ecl:#6d4df1 cid:109 eyr:2026 pid:295161300 ecl:gry hgt:160cm byr:1950 hcl:#746f08 iyr:2017 iyr:2010 cid:335 eyr:2024 hcl:#866857 byr:1948 hgt:166cm pid:178927953 ecl:blu hgt:161cm cid:210 eyr:2025 byr:1920 ecl:gry iyr:2020 hcl:#7d3b0c pid:443548961 iyr:2019 pid:320015839 eyr:2029 hcl:#fffffd ecl:oth byr:1953 hgt:182cm eyr:2038 hcl:abb3ad iyr:2015 pid:174cm hgt:167cm ecl:hzl byr:1982 pid:798153758 ecl:brn hgt:161cm hcl:#341e13 eyr:2023 iyr:2014 byr:1938 pid:193cm hgt:190cm ecl:amb iyr:2019 eyr:2028 cid:270 hcl:#18171d pid:711886098 byr:1962 eyr:2028 ecl:grn hgt:151cm hcl:#cfa07d iyr:2019 eyr:2028 iyr:2011 ecl:gry pid:550207629 hgt:183cm hcl:#888785 byr:1920 cid:96 ecl:utc eyr:2021 byr:1962 hgt:175cm pid:872298092 hcl:z iyr:2017 cid:197 iyr:2010 hcl:5b88b0 byr:2021 ecl:gmt eyr:2040 hgt:179cm pid:161cm pid:56869473 eyr:2036 ecl:lzr iyr:2027 hcl:z hcl:#602927 hgt:151cm pid:780342729 ecl:oth iyr:2015 byr:2027 hcl:#fffffd pid:5609758115 eyr:2037 iyr:2017 ecl:#6f0329 hgt:97 iyr:2025 hcl:z byr:2007 ecl:gmt pid:#eda9ab hgt:154in eyr:2028 cid:247 ecl:utc pid:216181141 hgt:161cm eyr:2026 hcl:#d38f20 byr:2028 ecl:grn byr:1955 hcl:#c0946f iyr:2017 eyr:2027 pid:746303487 hgt:72in pid:489225602 iyr:2018 ecl:gry hgt:65in byr:1982 cid:248 eyr:2025 hcl:#ceb3a1 pid:663798116 byr:1937 iyr:2010 hgt:167cm ecl:hzl pid:329032527 hcl:#ceb3a1 iyr:2014 ecl:gry hgt:169cm byr:1932 hcl:#545d0c ecl:brn iyr:2023 hgt:186cm cid:209 pid:886392748 eyr:2030 byr:1984 hgt:80 iyr:1943 hcl:#733820 byr:1937 eyr:2029 pid:625851706 cid:309 pid:73586582 hgt:156 cid:162 ecl:zzz eyr:2025 iyr:1990 byr:1940 hcl:z iyr:2010 eyr:2023 pid:162901454 hcl:#733820 byr:1958 ecl:gry hgt:159cm byr:2007 hcl:#cfa07d cid:261 pid:148538600 ecl:hzl hgt:64cm iyr:2021 eyr:2040 iyr:1997 byr:2007 ecl:#24adc8 pid:55794137 cid:219 eyr:2037 hgt:75cm hcl:z hcl:#efcc98 byr:1940 ecl:amb iyr:2012 pid:594237790 eyr:2029 cid:112 hgt:173cm byr:1941 cid:70 eyr:2026 hgt:178cm hcl:#733820 ecl:brn iyr:2013 pid:425263722 eyr:2025 byr:1998 iyr:2014 ecl:amb pid:188113611 hcl:#341e13 byr:1950 iyr:2017 hgt:74in cid:238 pid:897969952 ecl:hzl eyr:2022 hcl:#0a18bb eyr:2022 iyr:2015 ecl:grn hgt:179cm byr:1956 hcl:#7fd789 pid:201629099 eyr:2024 pid:483257417 ecl:hzl iyr:2010 hgt:159cm hcl:z byr:1968 pid:916586207 ecl:amb iyr:2011 eyr:2022 hgt:191cm hcl:#602927 byr:1923 pid:175608183 hgt:190cm hcl:#fffffd iyr:2017 byr:1993 ecl:blu eyr:2029 hgt:173cm pid:669662258 byr:1997 iyr:2015 ecl:brn cid:153 hcl:#888785 hcl:d899cf ecl:#876029 hgt:76cm iyr:1997 pid:40406158 eyr:2032 byr:2010 eyr:2023 ecl:hzl cid:162 hcl:#602927 iyr:2015 pid:82885029 hgt:75cm byr:1946 byr:1962 hgt:167in ecl:brn hcl:#c0946f iyr:2014 pid:488520708 eyr:2027 cid:271 hgt:180cm pid:358771245 eyr:2020 ecl:grn iyr:2018 hcl:#efcc98 byr:1979 cid:273 ecl:gry pid:424388351 iyr:2010 hcl:#c0946f byr:1988 hgt:166cm eyr:2027 ecl:gry hcl:#a97842 hgt:189cm pid:743213778 iyr:2015 byr:1959 iyr:2021 byr:2021 ecl:#a79d2e cid:89 hcl:#5fb8d7 eyr:2001 pid:#5575b3 hgt:60cm eyr:2021 iyr:2017 cid:87 hgt:164cm pid:560394910 ecl:hzl hcl:#ceb3a1 byr:1955 iyr:2018 hcl:#27f7e6 hgt:160cm eyr:2029 pid:033692111 ecl:amb byr:1920 hgt:160cm eyr:2028 iyr:2010 ecl:blu byr:1974 pid:858060501 hcl:#733820 byr:1961 pid:818700605 cid:93 eyr:2024 hgt:188cm hcl:#866857 ecl:gry eyr:2029 hgt:180cm iyr:2017 ecl:hzl byr:1951 cid:158 hcl:#888785 cid:290 eyr:2027 byr:1986 ecl:blu pid:076339632 iyr:2010 hcl:#341e13 hgt:167cm eyr:2023 iyr:1990 hcl:#623a2f byr:2005 hgt:116 hgt:167in iyr:1944 ecl:dne eyr:2031 hcl:465775 pid:2505694463 cid:93 eyr:2024 iyr:2010 hgt:143 pid:154cm ecl:#c6f352 hcl:#a97842 byr:1925 pid:600685520 byr:1967 hcl:#ceb3a1 iyr:2014 ecl:oth cid:226 hgt:179cm eyr:2026 hcl:#ceb3a1 pid:789956738 byr:1938 hgt:171cm cid:183 eyr:2021 iyr:2011 ecl:amb hcl:#613f4b hgt:151cm eyr:2025 ecl:amb byr:1985 pid:493339889 iyr:2013 hcl:78cda6 pid:36823553 iyr:2021 cid:235 byr:2028 eyr:2011 hgt:113 ecl:#02ce86 pid:529274811 iyr:2012 hgt:103 ecl:blu hcl:#341e13 eyr:2023 byr:1959 hgt:166cm iyr:2014 ecl:xry cid:276 byr:2014 hcl:#7d3b0c pid:146851133 pid:359823289 hgt:181cm byr:1978 hcl:#c0946f eyr:2022 iyr:2011 ecl:hzl pid:029400877 eyr:2026 byr:1983 iyr:2015 hcl:#cfa07d cid:70 ecl:gry hcl:#ceb3a1 eyr:2021 hgt:190cm ecl:amb iyr:2017 pid:411804678 byr:1950 byr:1926 iyr:2017 ecl:blu pid:103821113 eyr:2026 hcl:#c0946f cid:71 hgt:152cm cid:108 byr:1955 iyr:2010 eyr:2022 hgt:169cm hcl:#733820 pid:208715596 ecl:gry pid:352807405 ecl:blu hcl:#b1214c iyr:2012 hgt:165cm byr:1929 cid:139 eyr:2020 hcl:#cfa07d hgt:151cm byr:1987 eyr:2024 cid:140 pid:884441477 pid:#dade9c eyr:1979 hgt:191cm byr:2026 iyr:2018 hcl:z ecl:lzr cid:259 pid:644561358 ecl:blu hgt:164cm iyr:2013 byr:1997 eyr:2023 hcl:#108f16 ecl:oth cid:141 hgt:66in pid:877258886 iyr:2019 byr:1949 hcl:#18171d eyr:2027 byr:1932 cid:103 hgt:175cm pid:464473181 ecl:xry iyr:2013 hcl:51fd65 cid:175 iyr:2014 eyr:1959 ecl:#d83076 hgt:182cm pid:863972537 hcl:#efcc98 byr:1986 hgt:181cm pid:869641194 hcl:#efcc98 cid:141 ecl:gmt iyr:2017 byr:1981 eyr:2027 eyr:1938 iyr:2026 cid:278 ecl:brn byr:1936 hgt:150 pid:6902040050 eyr:2027 iyr:2014 pid:110887179 hcl:#a97842 ecl:brn cid:262 hgt:66in byr:1954 ecl:grn pid:498972747 eyr:2024 hcl:#341e13 iyr:2011 byr:1932 hgt:186cm cid:59 hcl:#6b5442 iyr:2018 eyr:2028 pid:866696485 hgt:178cm ecl:gry pid:598961001 eyr:2024 iyr:2019 byr:1963 ecl:grn hcl:#c0946f eyr:2024 hgt:172cm pid:295056305 ecl:blu byr:1926 iyr:2017 hcl:#341e13 byr:2001 hcl:#6b5442 hgt:164cm pid:862982189 ecl:grn iyr:2019 eyr:2030 hgt:69cm eyr:2014 ecl:hzl iyr:2025 hcl:2812c9 cid:74 byr:1980 hcl:#888785 pid:409489862 iyr:2011 hgt:186cm ecl:gry byr:1985 eyr:2028 cid:221 pid:6849250876 hgt:169cm hcl:z iyr:2013 byr:1950 eyr:2022 pid:189083891 byr:1983 hcl:#623a2f ecl:hzl iyr:2013 eyr:2026 hgt:66in pid:581546673 cid:269 eyr:2030 hgt:191cm byr:1945 hcl:#18171d iyr:2015 ecl:amb hgt:158cm ecl:hzl cid:234 eyr:2023 byr:1996 hcl:#7ac7ad iyr:2020 pid:666748924 iyr:2013 ecl:grn cid:53 hgt:172cm eyr:2028 pid:406602771 hcl:#fffffd byr:1959 hgt:63cm hcl:eaaf60 byr:2026 iyr:1981 pid:#baf2cf cid:117 ecl:hzl eyr:2035 byr:2014 iyr:2028 hcl:z ecl:#acd426 cid:261 pid:174cm hgt:182in ecl:amb pid:#4bb0a8 eyr:2027 hgt:155cm hcl:#623a2f byr:1956 iyr:2011 eyr:2012 cid:53 byr:2005 ecl:oth hgt:183in iyr:1974 pid:150cm iyr:2020 pid:833821322 ecl:blu byr:1944 hgt:169cm hcl:#623a2f eyr:2020 hgt:60in ecl:oth byr:1962 eyr:2022 cid:99 iyr:2019 pid:281039464 hcl:#733820 ecl:hzl hcl:#7d3b0c hgt:191cm pid:771871096 iyr:2012 eyr:2027 byr:2025 hgt:188in hcl:z eyr:2032 iyr:1955 byr:2027 ecl:#517bfe pid:#206bab hcl:#733820 iyr:2010 pid:784128823 hgt:169cm cid:305 ecl:grn byr:1962 cid:50 eyr:2022 hcl:a916cf pid:407148034 iyr:1926 ecl:#fa1ba7 hgt:69 byr:2028 hgt:193cm pid:507697987 cid:275 byr:1958 eyr:2023 ecl:brn iyr:2013 hcl:#326596 eyr:2025 hgt:192cm cid:95 iyr:2011 ecl:grn byr:2002 pid:399623583 hcl:#b6652a ecl:brn hcl:#602927 eyr:2023 pid:089068603 hgt:189cm byr:1953 iyr:2018 cid:160 hcl:f1bf94 byr:2030 ecl:gry hgt:60in iyr:2016 pid:4816152 hgt:154cm iyr:2015 ecl:gry eyr:2024 pid:718845487 byr:1999 hcl:#866857 cid:294 hgt:186cm eyr:2026 byr:1984 ecl:grn hcl:#ceb3a1 pid:325370778 iyr:2010 pid:156980004 hcl:#c0946f iyr:2013 ecl:brn hgt:181cm byr:1933 eyr:2023 hcl:#efcc98 byr:2002 hgt:158cm ecl:gmt iyr:1964 pid:195262032 eyr:2021 hcl:#602927 eyr:2027 hgt:192cm byr:1945 iyr:2018 pid:366509171 ecl:oth pid:163cm iyr:2016 ecl:lzr hcl:#341e13 hgt:79 cid:130 eyr:2038 byr:2030 hcl:#efcc98 byr:1979 ecl:oth eyr:2020 pid:095314628 hgt:162cm iyr:2015 byr:1998 cid:157 pid:346442779 hcl:#b6652a hgt:162cm ecl:amb eyr:2023 iyr:2018 hcl:#d6a701 byr:1971 hgt:160cm ecl:#98c896 pid:627704105 eyr:2024 iyr:2010 byr:2021 iyr:2023 eyr:1981 hgt:68cm ecl:dne hcl:z pid:20981493 pid:159037919 hgt:162cm ecl:amb cid:244 byr:1971 eyr:2027 iyr:2017 hcl:#18171d iyr:2011 pid:086826874 cid:162 hgt:189cm ecl:gry byr:1926 hcl:#888785 eyr:2022 hgt:152cm pid:919970712 byr:1955 hcl:#733820 iyr:2018 ecl:brn cid:111 ecl:#a1843f byr:2015 hcl:z iyr:1956 pid:186cm eyr:2030 byr:1991 eyr:2024 pid:050818633 hcl:#888785 cid:124 hgt:176cm ecl:gry iyr:2018 byr:1963 hgt:188cm eyr:2021 cid:255 ecl:oth hcl:#a97842 iyr:2010 pid:030540064 byr:1921 hgt:164cm pid:748078322 hcl:#c0946f ecl:blu eyr:2027 iyr:2020 eyr:2020 cid:214 hcl:7a942e hgt:191cm byr:1998 iyr:2012 ecl:grn pid:054135231 eyr:1927 pid:242147946 iyr:2010 hcl:ea3cb1 byr:2028 hgt:186cm ecl:dne ecl:brn hcl:#efcc98 eyr:2021 hgt:160cm pid:333644730 byr:1999 iyr:2019 iyr:2013 byr:1921 hcl:#a97842 eyr:2027 ecl:gry hgt:157cm pid:682013109 ecl:gry hcl:#733820 byr:1945 hgt:174cm eyr:2020 pid:505827627 iyr:2019 eyr:2021 iyr:2015 ecl:oth hgt:162cm pid:137342936 byr:1922 hcl:#888785 hcl:#efcc98 ecl:oth hgt:151cm cid:312 byr:1983 eyr:2030 pid:289512908 iyr:2020 byr:1989 iyr:2015 pid:057335770 ecl:grn eyr:2022 hgt:167cm hcl:#602927 hgt:184cm iyr:2013 hcl:#c0946f byr:1969 eyr:2028 pid:802041641 ecl:brn pid:155cm hcl:#b6652a cid:288 byr:2028 iyr:2028 hgt:150cm ecl:#996e72 eyr:1960 eyr:2020 iyr:2011 pid:934576102 byr:1994 ecl:amb hcl:#18171d eyr:1993 byr:1995 hgt:64cm iyr:2020 pid:15714997 hcl:#b6652a ecl:blu iyr:2014 eyr:2030 pid:866047540 cid:59 hcl:#733820 byr:1951 hgt:64in ecl:amb iyr:2015 byr:1962 hgt:69in ecl:brn hcl:#623a2f eyr:2023 pid:671492881 iyr:2020 ecl:oth hgt:154cm byr:1950 pid:924256973 eyr:2028 hcl:#b6652a byr:2021 hgt:116 cid:348 iyr:1930 pid:76948864 hcl:z eyr:2036 hgt:156cm iyr:2014 byr:1960 pid:720786216 cid:99 ecl:gry hcl:#a97842 eyr:2028 """.trimIndent().split("\n\n").map {it.replace("\n", " ")} println("day4-pt1: " + part1(input)) // 213 println("day4-pt2: " + part2(input)) // 147 } }
0
Kotlin
0
0
42a4fce4526182737d9661fae66c011f0948e481
30,850
adventofcode
MIT License
src/Day11.kt
a-glapinski
572,880,091
false
{"Kotlin": 26602}
import utils.readInputAsText fun main() { val input = readInputAsText("day11_input") val monkeys = input.split("\n\n").map { Monkey(note = it.lines()) } fun playKeepAway(monkeys: List<Monkey>, roundCount: Int, calculateWorryLevel: (Long, Int) -> Long): Long { val modulus = monkeys.map { it.divisor }.reduce(Int::times) repeat(roundCount) { monkeys.forEach { monkey -> monkey.items.forEach { item -> monkey.itemsInspected++ val newWorryLevel = calculateWorryLevel(monkey.operation(item), modulus) val thrownTo = if (newWorryLevel % monkey.divisor == 0L) monkey.ifTrueThrowsTo else monkey.ifFalseThrowsTo monkeys[thrownTo].items.add(newWorryLevel) } monkey.items.clear() } } return monkeys.map { it.itemsInspected.toLong() }.sortedDescending().take(2).reduce(Long::times) } val result1 = playKeepAway( monkeys = monkeys.map { it.copy(items = it.items.toMutableList()) }, roundCount = 20, calculateWorryLevel = { item, _ -> item / 3 } ) println(result1) val result2 = playKeepAway( monkeys = monkeys.map { it.copy(items = it.items.toMutableList()) }, roundCount = 10_000, calculateWorryLevel = { item, modulus -> item % modulus } ) println(result2) } data class Monkey( var itemsInspected: Int = 0, val items: MutableList<Long>, val operation: (Long) -> Long, val divisor: Int, val ifTrueThrowsTo: Int, val ifFalseThrowsTo: Int, ) { companion object { operator fun invoke(note: List<String>): Monkey { val operationArg = note[2].substringAfterLast(' ').toLongOrNull() val operationOperand = note[2].substringAfter("old ").first() return Monkey( items = note[1].substringAfter(": ").split(", ").map(String::toLong).toMutableList(), operation = { old: Long -> val arg = operationArg ?: old when (operationOperand) { '*' -> old * arg '+' -> old + arg else -> error("Unsupported operation type.") } }, divisor = note[3].takeLastWhile(Char::isDigit).toInt(), ifTrueThrowsTo = note[4].takeLastWhile(Char::isDigit).toInt(), ifFalseThrowsTo = note[5].takeLastWhile(Char::isDigit).toInt() ) } } }
0
Kotlin
0
0
c830d23ffc2ab8e9a422d015ecd413b5b01fb1a8
2,596
advent-of-code-2022
Apache License 2.0
src/main/kotlin/io/github/pshegger/aoc/y2020/Y2020D10.kt
PsHegger
325,498,299
false
null
package io.github.pshegger.aoc.y2020 import io.github.pshegger.aoc.common.BaseSolver import io.github.pshegger.aoc.common.updated import kotlin.math.pow class Y2020D10 : BaseSolver() { override val year = 2020 override val day = 10 override fun part1(): Int { val data = parseInput() val adapters = (data + listOf(0, data.maxOf { it } + 3)).sorted() val jumps = (1 until adapters.size).fold(listOf(0, 0, 0)) { acc, i -> val jumpIndex = adapters[i] - adapters[i - 1] - 1 acc.updated(jumpIndex, acc[jumpIndex] + 1) } return jumps[0] * jumps[2] } override fun part2(): Long { val data = parseInput() val adapters = (data + listOf(0, data.maxOf { it } + 3)).sorted() val mustContain = mutableListOf(0) (1 until adapters.size - 1).forEach { i -> if (adapters[i] + 3 == adapters[i + 1] || adapters[i] - 3 == adapters[i - 1]) { mustContain.add(i) } } return (0 until mustContain.size - 1).fold(1L) { acc, i -> val between = mustContain[i + 1] - mustContain[i] - 1 val m = between / 3 acc * (2.0.pow(between).toLong() - m) } } private fun parseInput() = readInput { readLines().map { it.toInt() } } }
0
Kotlin
0
0
346a8994246775023686c10f3bde90642d681474
1,335
advent-of-code
MIT License
src/main/kotlin/chapter3/sec4/listing.kt
DavidGomesh
680,857,367
false
{"Kotlin": 204685}
package chapter3.sec4 sealed class List<out A> object Nil : List<Nothing>() { override fun toString(): String = "Nil" } data class Cons<out A>(val head: A, val tail: List<A>) : List<A>() //tag::init1[] fun sum(xs: List<Int>): Int = when (xs) { is Nil -> 0 is Cons -> xs.head + sum(xs.tail) } fun product(xs: List<Double>): Double = when (xs) { is Nil -> 1.0 is Cons -> xs.head * product(xs.tail) } //end::init1[] //tag::init2[] fun <A, B> foldRight(xs: List<A>, z: B, f: (A, B) -> B): B = when (xs) { is Nil -> z is Cons -> f(xs.head, foldRight(xs.tail, z, f)) } fun sum2(ints: List<Int>): Int = foldRight(ints, 0, { a, b -> a + b }) fun product2(dbs: List<Double>): Double = foldRight(dbs, 1.0, { a, b -> a * b }) //end::init2[] fun main() { //tag::substitution1[] //tag::substitution2[] foldRight(Cons(1, Cons(2, Cons(3, Nil))), 0, { x, y -> x + y }) //end::substitution2[] 1 + foldRight(Cons(2, Cons(3, Nil)), 0, { x, y -> x + y }) 1 + (2 + foldRight(Cons(3, Nil), 0, { x, y -> x + y })) 1 + (2 + (3 + (foldRight(Nil as List<Int>, 0, { x, y -> x + y })))) 1 + (2 + (3 + (0))) 6 //end::substitution1[] }
0
Kotlin
0
0
41fd131cd5049cbafce8efff044bc00d8acddebd
1,239
fp-kotlin
MIT License
src/main/kotlin/day02_dive/Dive.kt
barneyb
425,532,798
false
{"Kotlin": 238776, "Shell": 3825, "Java": 567}
package day02_dive import util.saveTextFile import java.io.PrintWriter /** * Compound state is the name of the game: modeling the position and depth as a * single value. The input is not simple data to process either, but rather a * set of instructions to interpret, necessitating building a (very simple) * "virtual machine". * * Part two furthers the compound state mandate by adding `aim` to the tuple. It * also requires a revised virtual machine _for the same instruction set_. */ fun main() { util.solve(1840243, ::partOne) util.solve(1727785422, ::partTwo) util.solve(1727785422, ::partTwoLoop) util.solve(1727785422, ::partTwoStateful) saveTextFile(::csv, "csv") } interface OceanLocation { val pos: Int val depth: Int /** * The product of position and depth. No Manhattan distance this year! */ val location get() = pos * depth } interface Coords<T : Coords<T>> : OceanLocation { fun forward(n: Int): T fun up(n: Int): T fun down(n: Int): T } data class Coords1( override val pos: Int = 0, override val depth: Int = 0 ) : Coords<Coords1> { override fun forward(n: Int) = copy(pos = pos + n) override fun up(n: Int) = copy(depth = depth - n) override fun down(n: Int) = copy(depth = depth + n) } private fun <T : Coords<T>> Coords<T>.follow(input: String) = input .lineSequence() .fold(this) { c, line -> c.execute(line) } private fun <T : Coords<T>> Coords<T>.execute(instruction: String) = instruction.let { line -> val words = line.split(" ") val n = words[1].toInt() when (words[0]) { "forward" -> forward(n) "up" -> up(n) "down" -> down(n) else -> throw IllegalArgumentException("Unrecognized '$line' instruction") } } internal fun <T : Coords<T>> Coords<T>.trace(input: String): Sequence<T> = @Suppress("UNCHECKED_CAST") input .lineSequence() .runningFold(this as T) { c, line -> c.execute(line) } fun partOne(input: String) = Coords1().follow(input).location data class Coords2( override val pos: Int = 0, override val depth: Int = 0, val aim: Int = 0 ) : Coords<Coords2> { override fun forward(n: Int) = copy(pos = pos + n, depth = depth + aim * n) override fun up(n: Int) = copy(aim = aim - n) override fun down(n: Int) = copy(aim = aim + n) } fun partTwo(input: String) = Coords2().follow(input).location fun partTwoLoop(input: String): Int { var pos = 0 var depth = 0 var aim = 0 for (line in input.lineSequence()) { val spaceIdx = line.indexOf(" ") val n = line.substring(spaceIdx + 1).toInt() when (line[0]) { 'f' -> { pos += n depth += aim * n } 'u' -> aim -= n 'd' -> aim += n else -> throw IllegalArgumentException("Unrecognized '$line' instruction") } } return pos * depth } data class Sub( override var pos: Int = 0, override var depth: Int = 0, var aim: Int = 0 ) : OceanLocation { fun forward(n: Int) { pos += n depth += aim * n } fun up(n: Int) { aim -= n } fun down(n: Int) { aim += n } } fun partTwoStateful(input: String): Int { val sub = Sub() for (line in input.lineSequence()) { val spaceIdx = line.indexOf(" ") val n = line.substring(spaceIdx + 1).toInt() when (line[0]) { 'f' -> sub.forward(n) 'u' -> sub.up(n) 'd' -> sub.down(n) else -> throw IllegalArgumentException("Unrecognized '$line' instruction") } } return sub.location } private fun csv(input: String, out: PrintWriter) { out.println("pos,depth1,depth2") Coords1().trace(input) .zip(Coords2().trace(input)) .forEach { (a, b) -> out.println("${a.pos},${a.depth},${b.depth}") } }
0
Kotlin
0
0
a8d52412772750c5e7d2e2e018f3a82354e8b1c3
4,065
aoc-2021
MIT License
kotlin/src/com/s13g/aoc/aoc2020/Day9.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2020 import com.s13g.aoc.Result import com.s13g.aoc.Solver /** * --- Day 9: Encoding Error --- * https://adventofcode.com/2020/day/9 */ class Day9 : Solver { override fun solve(lines: List<String>): Result { val input = lines.map { it.toLong() } val resultA = partA(25, input) val resultB = partB(resultA, input) return Result("$resultA", "$resultB") } } private fun partA(preamble: Int, input: List<Long>): Long { for (i in preamble until input.size) { if (!isValidTicket(i, input, preamble)) return input[i] } error("Cannot find solution for Part A") } private fun isValidTicket(i: Int, input: List<Long>, preamble: Int): Boolean { for (x in i - preamble until i) { for (y in x until i) { if (input[x] + input[y] == input[i]) return true } } return false } private fun partB(toFind: Long, input: List<Long>): Long { for (i in input.indices) { val collect = mutableListOf<Long>() var sum = 0L for (j in i until input.size) { sum += input[j] collect.add(input[j]) if (sum == toFind) return collect.min()!! + collect.max()!! } } error("Cannot find solution for Part B") }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
1,193
euler
Apache License 2.0
app/src/y2021/day16/Day16PacketDecoder.kt
henningBunk
432,858,990
false
{"Kotlin": 124495}
package y2021.day16 import common.* import common.annotations.AoCPuzzle fun main(args: Array<String>) { Day16PacketDecoder().solveThem() } @AoCPuzzle(2021, 16) class Day16PacketDecoder : AocSolution { override val answers = Answers(samplePart1 = 31, samplePart2 = 54, part1 = 889, part2 = 739303923668) override fun solvePart1(input: List<String>): Any = BitsPacket(input.first().hexToBinary()).versionSum override fun solvePart2(input: List<String>): Any = BitsPacket(input.first().hexToBinary()).value } fun String.hexToBinary(): String = this.map { it .digitToInt(16) .toByte() .toString(2) .padStart(4, '0') }.joinToString("") class BitsPacket(private val binary: String) { val version: Int = binary .substring(versionLengthStartIndex, versionLengthEndIndex + 1) .toInt(2) val typeId: Int = binary .substring(typeIdLengthStartIndex, typeIdLengthEndIndex + 1) .toInt(2) val type: PacketType = when (typeId) { 4 -> parseLiteralValue() else -> parseOperatorPacket() } val versionSum: Int = when (type) { is Literal -> version is Operator -> version + type.subPackets.sumOf { it.versionSum } } val value: Long = when (type) { is Literal -> type.value is Operator -> when(typeId) { 0 -> type.subPackets.sumOf { it.value } 1 -> type.subPackets.fold(1) { product, next -> product * next.value} 2 -> type.subPackets.minOf { it.value } 3 -> type.subPackets.maxOf { it.value } 5 -> if (type.subPackets[0].value > type.subPackets[1].value) 1 else 0 6 -> if (type.subPackets[0].value < type.subPackets[1].value) 1 else 0 7 -> if (type.subPackets[0].value == type.subPackets[1].value) 1 else 0 else -> error("this operation is not supported") } } private fun parseLiteralValue(): Literal = binary .substring(startIndex = 6) .chunked(5) .let { chunks -> var literal: String = "" var size = 6 for (chunk in chunks) { literal += chunk.substring(1) size += 5 if (chunk[0] == '0') break } Literal(literal.toLong(2), size) } private fun parseOperatorPacket(): Operator { val lengthTypeId = Character.getNumericValue(binary[lengthTypeIdIndex]) return when (lengthTypeId) { 0 -> parseLengthType0() 1 -> parseLengthType1() else -> error("unsupported length type id: $lengthTypeId") } } private fun parseLengthType0(): Operator { val subPacketLength = binary .substring(type0subPacketLengthStartIndex, type0subPacketLengthEndIndex + 1) .toInt(2) val subPackets: MutableList<BitsPacket> = mutableListOf() var nextSubPacketStart = type0firstSubPacketStartIndex do { BitsPacket(binary.substring(nextSubPacketStart)) .let { subPackets.add(it) nextSubPacketStart += it.type.size } } while (type0firstSubPacketStartIndex + subPacketLength - nextSubPacketStart > 6) return Operator( lengthTypeId = 0, size = nextSubPacketStart, subPackets = subPackets.toTypedArray() ) } private fun parseLengthType1(): Operator { val subPacketsAmount = binary .substring(type1subPacketAmountStartIndex, type1subPacketAmountEndIndex + 1) .toInt(2) val subPackets: MutableList<BitsPacket> = mutableListOf() var nextSubPacketStart = type1firstSubPacketStartIndex repeat(subPacketsAmount) { BitsPacket(binary.substring(nextSubPacketStart)) .let { subPackets.add(it) nextSubPacketStart += it.type.size } } return Operator( lengthTypeId = 1, size = nextSubPacketStart, subPackets = subPackets.toTypedArray() ) } companion object { const val versionLengthStartIndex = 0 const val versionLengthEndIndex = 2 const val typeIdLengthStartIndex = 3 const val typeIdLengthEndIndex = 5 const val lengthTypeIdIndex = 6 const val type0subPacketLengthStartIndex = 7 const val type0subPacketLengthEndIndex = 21 const val type0firstSubPacketStartIndex = 22 const val type1subPacketAmountStartIndex = 7 const val type1subPacketAmountEndIndex = 17 const val type1firstSubPacketStartIndex = 18 } } sealed class PacketType(val size: Int) class Literal(val value: Long, size: Int) : PacketType(size) class Operator( val lengthTypeId: Int, size: Int, vararg val subPackets: BitsPacket, ) : PacketType(size)
0
Kotlin
0
0
94235f97c436f434561a09272642911c5588560d
4,983
advent-of-code-2021
Apache License 2.0
kotlin/geometry/Closest2PointsFast.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package geometry import numeric.FFT import optimization.Simplex object Closest2PointsFast { // Find closest pair in O(n*log(n)) fun findClosestPair(points: Array<Point?>): Array<Point?> { Arrays.sort(points, Comparator.comparingInt { p -> p.x }) val sortedY: Array<Point> = points.clone() Arrays.sort(sortedY, Comparator.comparingInt { p -> p.y }) val result = arrayOfNulls<Point>(2) rec(points, sortedY, 0, points.size - 1, result, Long.MAX_VALUE) return result } fun rec( sortedX: Array<Point?>, sortedY: Array<Point>, l: Int, r: Int, result: Array<Point?>, mindist2: Long ): Long { var mindist2 = mindist2 if (l == r) return Long.MAX_VALUE val mid = l + r shr 1 val midx = sortedX[mid]!!.x for (i in l..r) { sortedX[i]!!.mark = i <= mid } val sortedY1: Array<Point> = Arrays.stream(sortedY).filter { p -> p.mark } .toArray { _Dummy_.__Array__() } val sortedY2: Array<Point> = Arrays.stream(sortedY).filter { p -> !p.mark } .toArray { _Dummy_.__Array__() } val d1 = rec(sortedX, sortedY1, l, mid, result, mindist2) mindist2 = Math.min(mindist2, d1) val d2 = rec(sortedX, sortedY2, mid + 1, r, result, mindist2) mindist2 = Math.min(mindist2, d2) val t = IntArray(r - l + 1) var size = 0 for (i in t.indices) if ((sortedY[i].x - midx).toLong() * (sortedY[i].x - midx) < mindist2) t[size++] = i for (i in 0 until size) { for (j in i + 1 until size) { val a = sortedY[t[i]] val b = sortedY[t[j]] if ((b.y - a.y).toLong() * (b.y - a.y) >= mindist2) break val dist2 = dist2(a, b) if (mindist2 > dist2) { mindist2 = dist2 result[0] = a result[1] = b } } } return mindist2 } fun dist2(a: Point?, b: Point?): Long { val dx = (a!!.x - b!!.x).toLong() val dy = (a.y - b.y).toLong() return dx * dx + dy * dy } // random test fun main(args: Array<String?>?) { val rnd = Random() for (step in 0..9999) { val n = 100 val points = arrayOfNulls<Point>(n) for (i in 0 until n) { points[i] = Point(rnd.nextInt(1000) - 500, rnd.nextInt(1000) - 500) } val p = findClosestPair(points) val res1 = dist2(p[0], p[1]) val res2 = slowClosestPair(points) if (res1 != res2) throw RuntimeException("$res1 $res2") } } fun slowClosestPair(points: Array<Point?>): Long { var res = Long.MAX_VALUE for (i in points.indices) for (j in i + 1 until points.size) res = Math.min( res, dist2( points[i], points[j] ) ) return res } class Point(val x: Int, val y: Int) { var mark = false } }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
3,114
codelibrary
The Unlicense
src/day04/Day04.kt
ritesh-singh
572,210,598
false
{"Kotlin": 99540}
package day04 import readInput fun main() { fun part1(input: List<String>): Int { return input.map { it.split(",", "-").map { it.toInt() } }.count { val (first, second, third, fourth) = it (first in third..fourth && second in third..fourth) || (third in first..second && fourth in first..second) } } fun part2(input: List<String>): Int { return input.map { it.split(",", "-").map { it.toInt() } }.count { val (first, second, third, fourth) = it (first in third..fourth || second in third..fourth) || (third in first..second || fourth in first..second) } } val input = readInput("/day04/Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
17fd65a8fac7fa0c6f4718d218a91a7b7d535eab
793
aoc-2022-kotlin
Apache License 2.0
solutions/src/RegexMatching.kt
JustAnotherSoftwareDeveloper
139,743,481
false
{"Kotlin": 305071, "Java": 14982}
/** * https://leetcode.com/problems/regular-expression-matching/ */ class RegexMatching { fun isMatch(s: String, p: String) : Boolean { val dpArray = arrayOfNulls<Array<Boolean?>>(s.length+1) for (i in dpArray.indices) { dpArray[i] = arrayOfNulls(p.length+1) } for (i in dpArray.indices) { for( j in dpArray[0]!!.indices) { dpArray[i]!![j] = false } } dpArray[0]!![0] = true for(i in p.indices) { dpArray[0]!![i+1] = (p[i] == '*' && dpArray[0]!![i-1] == true) } for (i in s.indices) { for (j in p.indices) { if (p[j] == s[i] || p[j] == '.') { dpArray[i+1]!![j+1] = dpArray[i]!![j] } if (p[j] == '*') { if (p[j-1] != s[i] && p[j-1] != '.' ) { dpArray[i+1]!![j+1] = dpArray[i+1]!![j-1] } else { dpArray[i+1]!![j+1] = dpArray[i+1]!![j]!! || dpArray[i]!![j+1]!! || dpArray[i+1]!![j-1]!! } } } } return dpArray[s.length]!![p.length]!! } }
0
Kotlin
0
0
fa4a9089be4af420a4ad51938a276657b2e4301f
1,237
leetcode-solutions
MIT License
src/main/kotlin/de/mbdevelopment/adventofcode/year2021/solvers/day12/Day12Puzzle.kt
Any1s
433,954,562
false
{"Kotlin": 96683}
package de.mbdevelopment.adventofcode.year2021.solvers.day12 import de.mbdevelopment.adventofcode.year2021.solvers.PuzzleSolver abstract class Day12Puzzle : PuzzleSolver { companion object { @JvmStatic protected val START = Cave.SmallCave("start") @JvmStatic protected val END = Cave.SmallCave("end") } final override fun solve(inputLines: Sequence<String>) = countWaysThroughCaves(collectCaveConnections(inputLines)).toString() abstract fun countWaysThroughCaves(caveConnections: Map<Cave, Set<Cave>>): Int private fun collectCaveConnections(caveSystem: Sequence<String>) = caveSystem .filter { it.isNotBlank() } .map { it.split('-') } .map { it.map { cave -> if (cave == cave.lowercase()) Cave.SmallCave(cave) else Cave.BigCave(cave) } } .map { it[0] to it[1] } .toList() .let { connections -> val aToB = connections.groupBy { it.first } .mapValues { it.value.map { connection -> connection.second }.toSet() } val bToA = connections.groupBy { it.second } .mapValues { it.value.map { connection -> connection.first }.toSet() } aToB.toMutableMap().apply { bToA.forEach { (key, value) -> put(key, getOrDefault(key, emptySet()) + value) } }.toMap() } }
0
Kotlin
0
0
21d3a0e69d39a643ca1fe22771099144e580f30e
1,408
AdventOfCode2021
Apache License 2.0
src/Day10.kt
makohn
571,699,522
false
{"Kotlin": 35992}
fun main() { fun part1(input: List<String>): Int { var acc = 0 var x = 1 var cycle = 0 fun tick() { cycle++ if (cycle in (20 .. 220) step 40) { acc += cycle * x } } for (parts in input.map { it.split(" ") }) { tick() val op = parts[0] when (op) { "addx" -> { tick() x+= parts[1].toInt() } "noop" -> Unit } } return acc } fun part2(input: List<String>): Int { var x = 1 var cycle = 0 var cursor = 0 fun tick() { cycle++ val crt = if (cursor in x-1..x+1) "#" else "." print(crt) cursor++ if (cursor == 40) { println() cursor = 0 } } for (parts in input.map { it.split(" ") }) { tick() val op = parts[0] if (op == "addx") { tick() x += parts[1].toInt() } } return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") check(part1(testInput) == 13140) check(part2(testInput) == 0) val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2734d9ea429b0099b32c8a4ce3343599b522b321
1,464
aoc-2022
Apache License 2.0
src/main/kotlin/com/askrepps/advent2021/day15/Day15.kt
askrepps
726,566,200
false
{"Kotlin": 302802}
/* * MIT License * * Copyright (c) 2021-2023 <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.advent.advent2021.day15 import com.askrepps.advent.util.getInputLines import java.io.File import java.util.PriorityQueue private val NEIGHBOR_DIRECTIONS = listOf( Pair(-1, 0), Pair(1, 0), Pair(0, -1), Pair(0, 1) ) data class GridSearchPoint(val row: Int, val col: Int, val currentTotalRisk: Int) fun String.toRiskValues() = map { it.code - '0'.code } fun findMinimumPathRisk(localRiskMap: List<List<Int>>): Int { val totalPathRiskMap = localRiskMap.map { row -> MutableList(row.size) { Int.MAX_VALUE } } totalPathRiskMap[0][0] = 0 val searchQueue = PriorityQueue<GridSearchPoint>(compareBy { it.currentTotalRisk }) searchQueue.add(GridSearchPoint(0, 0, 0)) while (searchQueue.isNotEmpty()) { val (currentRow, currentCol, currentTotalRisk) = searchQueue.remove() for ((deltaRow, deltaCol) in NEIGHBOR_DIRECTIONS) { val neighborRow = currentRow + deltaRow val neighborCol = currentCol + deltaCol localRiskMap.getOrNull(neighborRow)?.getOrNull(neighborCol)?.let { neighborLocalRisk -> val possibleTotalRisk = currentTotalRisk + neighborLocalRisk if (possibleTotalRisk < totalPathRiskMap[neighborRow][neighborCol]) { totalPathRiskMap[neighborRow][neighborCol] = possibleTotalRisk searchQueue.add(GridSearchPoint(neighborRow, neighborCol, possibleTotalRisk)) } } } } return totalPathRiskMap.last().last() } fun List<List<Int>>.expandMapBy(expansionFactor: Int) = List(size * expansionFactor) { newRowIndex -> val oldRowIndex = newRowIndex % size val oldRow = get(oldRowIndex) val verticalTileDistance = newRowIndex / size List(oldRow.size * expansionFactor) { newColIndex -> val oldColIndex = newColIndex % oldRow.size val horizontalTileDistance = newColIndex / oldRow.size val totalTileDistance = verticalTileDistance + horizontalTileDistance ((oldRow[oldColIndex] + totalTileDistance - 1) % 9) + 1 } } fun getPart1Answer(riskMap: List<List<Int>>) = findMinimumPathRisk(riskMap) fun getPart2Answer(riskMap: List<List<Int>>) = findMinimumPathRisk(riskMap.expandMapBy(5)) fun main() { val riskMap = File("src/main/resources/2021/input-2021-day15.txt") .getInputLines().map { it.toRiskValues() } println("The answer to part 1 is ${getPart1Answer(riskMap)}") println("The answer to part 2 is ${getPart2Answer(riskMap)}") }
0
Kotlin
0
0
89de848ddc43c5106dc6b3be290fef5bbaed2e5a
3,723
advent-of-code-kotlin
MIT License
src/main/kotlin/enigma/util/Util.kt
aurelioklv
737,580,684
false
{"Kotlin": 83511}
package com.aurelioklv.enigma.util val alphabet = ('A'..'Z').joinToString(separator = "") val defaultWiring: Map<Char, Char> = ('A'..'Z').associateWith { it } fun validateWiring(wiring: Map<Char, Char>, kind: String) { require(wiring.isNotEmpty()) { "Wiring is empty" } require(wiring.all { (key, value) -> key.isLetter() && key.isUpperCase() && value.isLetter() && value.isUpperCase() }) { "Each character should be an uppercase letter" } when (kind) { in listOf("rotor", "plugboard") -> { require(alphabet.all { wiring.containsKey(it) && wiring.containsValue(it) }) } "reflector" -> { require(wiring.all { (key, value) -> wiring.getOrDefault(value, ' ') == key }) { "Invalid wiring $wiring" } } } wiring.mapKeys { it.key.uppercaseChar() }.mapValues { it.value.uppercaseChar() } } fun String.toWiring(kind: String): Map<Char, Char> { val input = this.uppercase() val result = when (kind) { in listOf("rotor", "reflector") -> { require(input.length == alphabet.length) { "String must be ${alphabet.length} characters long. Got ${input.length}" } alphabet.zip(input).toMap() } "plugboard" -> { val wiring = input.chunked(2).flatMap { pair -> pair.map { it to pair[(pair.indexOf(it) + 1) % 2] } }.toMap().toMutableMap() val existingChar = input.toSet() wiring += defaultWiring.filterKeys { it !in existingChar } wiring } else -> { throw IllegalArgumentException("Unknown kind: $kind") } } return result } fun String.toListOfInt(): List<Int> { return map { char -> when { char.isLetter() -> char.uppercaseChar().minus('A') else -> throw IllegalArgumentException("Invalid character: $char") } } }
0
Kotlin
0
0
2110e20ab9e5d2160b0e32bda137b0f63a93ecc3
1,993
enigma
MIT License
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[98]验证二叉搜索树.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给你一个二叉树的根节点 root ,判断其是否是一个有效的二叉搜索树。 // // 有效 二叉搜索树定义如下: // // // 节点的左子树只包含 小于 当前节点的数。 // 节点的右子树只包含 大于 当前节点的数。 // 所有左子树和右子树自身必须也是二叉搜索树。 // // // // // 示例 1: // // //输入:root = [2,1,3] //输出:true // // // 示例 2: // // //输入:root = [5,1,4,null,null,3,6] //输出:false //解释:根节点的值是 5 ,但是右子节点的值是 4 。 // // // // // 提示: // // // 树中节点数目范围在[1, 104] 内 // -231 <= Node.val <= 231 - 1 // // Related Topics 树 深度优先搜索 二叉搜索树 二叉树 // 👍 1286 👎 0 //leetcode submit region begin(Prohibit modification and deletion) /** * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { var pre = Long.MIN_VALUE var flag: Boolean = true // 当前节点小于是否大于前一个节点标记 fun isValidBST(root: TreeNode?): Boolean { //递归 遍历 //中序遍历 左中右 if (root == null) return true if (flag) isValidBST(root.left) // 遍历左子树 if (root.`val` <= pre) flag = false // 如果当前节点小于等于中序遍历的前一个节点,说明不是BST,flag = false pre = root.`val`.toLong() // 记录前一个节点 if (flag) isValidBST(root.right) // 遍历右子树 return flag // return validBST(root) } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,809
MyLeetCode
Apache License 2.0
archive/2022/Day06.kt
mathijs81
572,837,783
false
{"Kotlin": 167658, "Python": 725, "Shell": 57}
private const val EXPECTED_1 = 7 private const val EXPECTED_2 = 19 private class Day06(isTest: Boolean) : Solver(isTest) { fun firstUniqueSubstring(data: String, len: Int): Int { val lastSeen = IntArray(26) { -100 } var candidateStart = 0 data.forEachIndexed { index, char -> val code = char - 'a' candidateStart = candidateStart.coerceAtLeast(lastSeen[code] + 1) lastSeen[code] = index if (index - candidateStart + 1 >= len) { return index + 1 } } return -1 } fun part1() = firstUniqueSubstring(readAsString(), 4) fun part2() = firstUniqueSubstring(readAsString(), 14) } fun main() { val testInstance = Day06(true) val instance = Day06(false) testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } } println(instance.part1()) testInstance.part2().let { check(it == EXPECTED_2) { "part2: $it != $EXPECTED_2" } } println(instance.part2()) }
0
Kotlin
0
2
92f2e803b83c3d9303d853b6c68291ac1568a2ba
1,029
advent-of-code-2022
Apache License 2.0
2022/src/main/kotlin/de/skyrising/aoc2022/day13/solution.kt
skyrising
317,830,992
false
{"Kotlin": 411565}
package de.skyrising.aoc2022.day13 import de.skyrising.aoc.* import kotlinx.serialization.json.* private fun compare(left: JsonElement, right: JsonElement): Int { if (left is JsonPrimitive && right is JsonPrimitive) { return left.int - right.int } if (left is JsonArray && right is JsonArray) { for (i in left.indices) { if (i >= right.size) return 1 val cmp = compare(left[i], right[i]) if (cmp != 0) return cmp } if (left.size != right.size) return left.size - right.size return 0 } if (left is JsonPrimitive) { return compare(JsonArray(listOf(left)), right) } if (right is JsonPrimitive) { return compare(left, JsonArray(listOf(right))) } return 0 } @PuzzleName("Distress Signal") fun PuzzleInput.part1(): Any { val values = lines.filter(String::isNotBlank).map(Json::parseToJsonElement).chunked(2) var result = 0 for (i in values.indices) { val (left, right) = values[i] val cmp = compare(left, right) if (cmp < 0) result += i + 1 } return result } fun PuzzleInput.part2(): Any { val values = lines.filter(String::isNotBlank).mapTo(mutableListOf(), Json::parseToJsonElement) val div1 = JsonArray(listOf(JsonArray(listOf(JsonPrimitive(2))))) val div2 = JsonArray(listOf(JsonArray(listOf(JsonPrimitive(6))))) values.add(div1) values.add(div2) val sorted = values.sortedWith(::compare) val div1Index = sorted.indexOf(div1) + 1 val div2Index = sorted.indexOf(div2) + 1 return div1Index * div2Index }
0
Kotlin
0
0
19599c1204f6994226d31bce27d8f01440322f39
1,613
aoc
MIT License
src/main/kotlin/ru/spbstu/player/Christofides.kt
belyaev-mikhail
192,383,116
false
null
package ru.spbstu.player import org.graphstream.algorithm.Kruskal import org.graphstream.graph.Edge import org.graphstream.graph.Graph import org.graphstream.graph.Node import org.graphstream.graph.implementations.SingleGraph import org.jgrapht.alg.shortestpath.JohnsonShortestPaths import org.jgrapht.alg.tour.ChristofidesThreeHalvesApproxMetricTSP import org.jgrapht.graph.DefaultUndirectedWeightedGraph import org.jgrapht.graph.SimpleGraph import ru.spbstu.map.sqr import kotlin.math.sqrt fun Node.distance(that: Node): Double { val (x, y) = getArray("xy") x as Number y as Number val (tx, ty) = that.getArray("xy") tx as Number ty as Number return sqrt(sqr(tx.toDouble() - x.toDouble()) + sqr(ty.toDouble() - y.toDouble())) } fun Graph.toJGraphT(): org.jgrapht.Graph<Node, Edge> { val res = DefaultUndirectedWeightedGraph<Node, Edge>(Edge::class.java) getNodeIterator<Node>().forEach { res.addVertex(it) } getEdgeIterator<Edge>().forEach { val lhv = it.getSourceNode<Node>() val rhv = it.getTargetNode<Node>() res.addEdge(lhv, rhv, it) res.setEdgeWeight(lhv, rhv, lhv.distance(rhv)) } val allShortestPaths = JohnsonShortestPaths(res) var counter = 0 /* make graph complete */ for(lhv in getNodeIterator<Node>()) { for(rhv in getNodeIterator<Node>()) { if(lhv !== rhv && !res.containsEdge(lhv, rhv)) { res.addEdge(lhv, rhv, edgeFactory().newInstance("synth${counter++}", lhv, rhv, false)) res.setEdgeWeight(lhv, rhv, allShortestPaths.getPathWeight(lhv, rhv)) } } } return res } object Christofides { fun path(graph: Graph): List<Node> { val chris = ChristofidesThreeHalvesApproxMetricTSP<Node, Edge>() val tour = chris.getTour(graph.toJGraphT()) // val newGraph = SingleGraph("chris-display") // for(v in tour.vertexList.toSet()) { // newGraph.addNode<Node>(v.id).addAttributes(v.attributeKeySet.map { it to v.getAttribute<Any?>(it) }.toMap()) // } // for(e in tour.edgeList.toSet()) { // newGraph.addEdge<Edge>(e.id, e.getNode0<Node>().id, e.getNode1<Node>().id) // } // newGraph.display(false) val res = tour.vertexList if(res.size == 1) return res else return res.dropLast(1) } }
1
Kotlin
0
0
cd5c7d668bf6615fd7e639ddfce0c135c138de42
2,394
icfpc-2019
MIT License
src/main/kotlin/aoc03/Solution03.kt
rainer-gepardec
573,386,353
false
{"Kotlin": 13070}
package aoc03 import java.nio.file.Paths val valueMap = calculateValueMap(); fun calculateValueMap(): Map<Char, Int> { val tmpMap = mutableMapOf<Char, Int>() var c = 'a'; while (c <= 'z') { tmpMap[c] = c.code - 96; c++ } c = 'A' while (c <= 'Z') { tmpMap[c] = c.code - 38; c++ } return tmpMap; } fun main() { val lines = Paths.get("src/main/resources/aoc_03.txt").toFile().useLines { it.toList() } println(solution1(lines)) println(solution2(lines)) } fun solution1(lines: List<String>): Int { return lines.map { Pair(it.substring(0, it.length / 2), it.substring(it.length / 2)) }.map { pair -> pair.first.toCharArray().first { pair.second.contains(it) } }.sumOf { valueMap[it]!! } } fun solution2(lines: List<String>): Int { return lines .windowed(3, 3) .map { group -> val charMap = mutableMapOf<Char, Int>() group.forEach { line -> line.toCharArray() .distinct() .forEach { charMap.computeIfPresent(it) { _, v -> v + 1 } charMap.putIfAbsent(it, 1) } } charMap.maxBy { it.value }.key }.sumOf { valueMap[it]!! } }
0
Kotlin
0
0
c920692d23e8c414a996e8c1f5faeee07d0f18f2
1,378
aoc2022
Apache License 2.0
src/main/kotlin/trees/BinaryTree.kt
gabrielshanahan
306,346,842
false
{"Kotlin": 4410}
package trees import java.lang.IllegalArgumentException import kotlin.math.max import kotlin.math.min sealed class Type { object Leaf: Type() { override fun toString(): String = "Leaf" } object Single: Type() { override fun toString(): String = "Single" } object Double: Type() { override fun toString(): String = "Double" } } data class BinaryTree(val value: Int, val leftChild: BinaryTree? = null, val rightChild: BinaryTree? = null) { val type = when { leftChild == null && rightChild == null -> Type.Leaf leftChild == null || rightChild == null -> Type.Single else -> Type.Double } val maxHight: Int = max( leftChild?.maxHight ?: -1, rightChild?.maxHight ?: -1 ) + 1 val minHight: Int = min( leftChild?.minHight ?: -1, rightChild?.minHight ?: -1 ) + 1 companion object { private infix fun Int.concat(rest: List<Int>) = listOf(this) + rest private fun List<Int>.splitSortedLeadingTriplet() = when { size > 2 -> subList(0, 3).sorted().let { Triple(it[0], it[1], it[2]) to subList(3, size) } else -> throw IllegalArgumentException("Cannot split triplet from list of size $size.") } fun buildSorted(values: List<Int>): BinaryTree = when(values.size) { 0 -> throw IllegalArgumentException("Cannot build empty tree") 1 -> BinaryTree(values.single()) 2 -> values.sorted().let { it.first() asLeftChildOf it.last() } else -> values.splitSortedLeadingTriplet().let { (sortedTriplet, rest) -> sortedTriplet.second asParentOf ( sortedTriplet.first and buildSorted(sortedTriplet.third concat rest) ) } } fun buildSorted(vararg values: Int) = buildSorted(values.toList()) } } fun BinaryTree.formattedString(): String = formattedString("") private fun BinaryTree.formattedString(prefix: String = ""): String = """ |$prefix $value($type, $minHight, $maxHight) |${listOfNotNull(leftChild, rightChild).joinToString("") { it.formattedString(prefix + "\t") }} """.trimMargin()
0
Kotlin
0
0
f9f2dee8e819da5ded9ed37ee285f852e7aadc37
2,227
BinarySearchTree
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/DeepestLeavesSum.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.ArrayDeque import java.util.Deque /** * @see <a href="https://leetcode.com/problems/deepest-leaves-sum">Source</a> */ fun interface DeepestLeavesSum { operator fun invoke(root: TreeNode): Int } class DeepestLeavesSumDFS : DeepestLeavesSum { override operator fun invoke(root: TreeNode): Int { var deepestSum = 0 var depth = 0 var currDepth: Int var node: TreeNode = root val stack: Deque<Pair<TreeNode, Int>> = ArrayDeque() stack.push(node to 0) while (stack.isNotEmpty()) { val p = stack.pop() node = p.first currDepth = p.second if (node.left == null && node.right == null) { if (depth < currDepth) { deepestSum = node.value depth = currDepth } else if (depth == currDepth) { deepestSum += node.value } } else { node.right?.let { stack.push(it to currDepth + 1) } node.left?.let { stack.push(it to currDepth + 1) } } } return deepestSum } } /** * Approach 2: Iterative BFS Traversal. */ class DeepestLeavesSumBFS : DeepestLeavesSum { override operator fun invoke(root: TreeNode): Int { var deepestSum = 0 var depth = 0 var currDepth: Int val queue: Deque<Pair<TreeNode, Int>> = ArrayDeque() var node: TreeNode = root queue.offer(Pair(node, 0)) while (queue.isNotEmpty()) { val p = queue.poll() node = p.first currDepth = p.second if (node.left == null && node.right == null) { if (depth < currDepth) { deepestSum = node.value depth = currDepth } else if (depth == currDepth) { deepestSum += node.value } } else { node.right?.let { queue.push(it to currDepth + 1) } node.left?.let { queue.push(it to currDepth + 1) } } } return deepestSum } } /** * Approach 3: Optimized Iterative BFS Traversal. */ class DeepestLeavesSumOptimizedBFS : DeepestLeavesSum { override operator fun invoke(root: TreeNode): Int { val nextLevel: ArrayDeque<TreeNode> = ArrayDeque() var currLevel: ArrayDeque<TreeNode> = ArrayDeque() nextLevel.offer(root) while (nextLevel.isNotEmpty()) { currLevel = nextLevel.clone() nextLevel.clear() for (node in currLevel) { node.right?.let { nextLevel.offer(it) } node.left?.let { nextLevel.offer(it) } } } var deepestSum = 0 for (node in currLevel) { deepestSum += node.value } return deepestSum } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,764
kotlab
Apache License 2.0
lib/src/main/kotlin/com/dzirbel/robopower/util/MapExtensions.kt
dzirbel
581,328,184
false
{"Kotlin": 178493}
package com.dzirbel.robopower.util /** * Returns the key(s) whose associated values are the largest according to [comparator]. */ internal fun <K, V> Map<K, V>.maxKeysBy(comparator: Comparator<V>): Set<K> { val iterator = iterator() if (!iterator.hasNext()) throw NoSuchElementException() val first = iterator.next() var maxValue = first.value val maxKeys = mutableSetOf(first.key) while (iterator.hasNext()) { val (key, value) = iterator.next() val comparison = comparator.compare(value, maxValue) if (maxValue == null || comparison > 0) { maxValue = value maxKeys.clear() maxKeys.add(key) } else if (comparison == 0) { maxKeys.add(key) } } return maxKeys } /** * Returns the first key (or an arbitrary key for unordered maps) whose value yields the maximum non-null result for * [selector]. */ fun <K, V, R : Comparable<R>> Map<K, V>.maxKeyByOrNull(selector: (V) -> R?): K? { return this .mapNotNull { (key, value) -> selector(value)?.let { key to it } } .maxByOrNull { (_, value) -> value } ?.first }
0
Kotlin
1
1
6c6f0a17361d7ed45bdd4d4b51d257f18dee5d98
1,162
robopower
MIT License
2020/src/year2020/day09/Day09.kt
eburke56
436,742,568
false
{"Kotlin": 61133}
package year2020.day09 import util.readAllLinesAsLong private fun findFirstFailure(filename: String, preambleLength: Int): Pair<Long, List<Long>> { val original = readAllLinesAsLong(filename) val list = original.toMutableList() while (list.size > preambleLength) { val testValue = list[preambleLength] list.take(preambleLength).let { testList -> if (!testList.any { testList.contains(testValue - it) }) { return Pair(testValue, original) } } list.removeAt(0) } return Pair(-1, listOf()) } private fun findEncryptionFailure(filename: String, preambleLength: Int): Long { val (failValue, list) = findFirstFailure(filename, preambleLength) var total = list[0] var start = 0 for (i in 1 until list.size) { if (total == failValue) { return list.subList(start, i).let { checkNotNull(it.minOrNull()) + checkNotNull(it.maxOrNull()) } } total += list[i] while (total > failValue) { total -= list[start] start++ } } return -1L } fun main() { println("Test: ${findFirstFailure("test.txt", 5).first}") println("Real: ${findFirstFailure("input.txt", 25).first}") println("Test: ${findEncryptionFailure("test.txt", 5)}") println("Real: ${findEncryptionFailure("input.txt", 25)}") }
0
Kotlin
0
0
24ae0848d3ede32c9c4d8a4bf643bf67325a718e
1,414
adventofcode
MIT License
src/main/kotlin/io/nozemi/aoc/solutions/year2021/day08/impl/SegmentPattern.kt
Nozemi
433,882,587
false
{"Kotlin": 92614, "Shell": 421}
package io.nozemi.aoc.solutions.year2021.day08.impl class SegmentPattern( val outputPatterns: Array<Set<Char>>, val signalPatterns: Array<Set<Char>>, ) { private val knownLetters: MutableMap<Char, Char> = mutableMapOf() private val knownNumbers: Array<Set<Char>> = Array(10) { emptySet() } /** * [AoC - Day 8, Part 2](https://adventofcode.com/2021/day/8) * * The wire/segment connections are scrambled. They no longer match the correct one. (See below) * ``` * aaaa * b c * b c * dddd * e f * e f * gggg * ``` * * We need to map the scrambled letters to the actual one to get the correct numbers for the output number. */ fun rewireOutputPattern() { mapKnownNumbers() mapRemainingNumbers() mapLetters() } private fun mapKnownNumbers() { // We already know that the numbers 1, 4, 7 & 8 are easy to differentiate from the rest. signalPatterns.forEach { when (it.size) { 2 -> knownNumbers[1] = it 4 -> knownNumbers[4] = it 3 -> knownNumbers[7] = it 7 -> knownNumbers[8] = it } } } private fun mapRemainingNumbers() { while (knownNumbers.any { it.isEmpty() }) { signalPatterns.forEach { if (knownNumbers.contains(it)) return@forEach when (it.size) { 6 -> { // We'll process the numbers with 6 letter patterns, being 0, 6 & 9. if (!it.containsAll(knownNumbers[1])) { // We know that 6 is the only from these 3 that does not contain both letters of 1. knownNumbers[6] = it } else if (it.containsAll(knownNumbers[4])) { // We know that 9 is the only from these 3 that contains all the letters from 4. knownNumbers[9] = it } // We'll eventually find the 6 and 9, and then we know that the last one is 0 if (knownNumbers[6].isNotEmpty() && knownNumbers[9].isNotEmpty()) { knownNumbers[0] = it } } 5 -> { // We'll process the numbers with 5 letter patterns, being 2, 3 & 5. if (it.containsAll(knownNumbers[7].toList())) { // We know that this is 3, because it contains all 3 letters from 7's pattern. knownNumbers[3] = it } else if (it.intersect(knownNumbers[6]).size == 4) { knownNumbers[2] = it } else if (it.intersect(knownNumbers[6]).size == 5) { knownNumbers[5] = it } } } } } } private fun mapLetters() { // We know that 1 has only "c" and "f", so the last one in 7 is the letter "a". knownLetters['a'] = findLetter(from = 7, and = 1) // We know that the only missing letter from 1 in six is "c", which gets us the position of "c". knownLetters['c'] = findLetter(from = 1, and = 6) // Number 0 will never have "d", and number 8 has all letters, which gets us the position of "d". knownLetters['d'] = findLetter(from = 8, and = 0) // We know that the only missing letter from 9 in 3 is "b", which gets us the position of "b". knownLetters['b'] = findLetter(from = 9, and = 3) // We know that the only missing letter from 8 in 9 is "e", which gets us the position of "e". knownLetters['e'] = findLetter(from = 8, and = 9) // We know that the only missing letter from 9 in 4 that we don't already know about is "g". knownLetters['g'] = findLetter(from = 9, and = 4, additionalCondition = { char -> knownLetters['a'] != char }) // We know that the only letter 6 and 1 has in common is "f", which gets us the position of "f". knownLetters['f'] = findLetter(from = 6, and = 1, alternativeCondition = { char, number -> knownNumbers[number].contains(char) }) } private fun findLetter( from: Int, and: Int, additionalCondition: (char: Char) -> Boolean = { _ -> true }, alternativeCondition: (char: Char, number: Int) -> Boolean? = { _, _ -> null } ): Char { return knownNumbers[from].single { alternativeCondition(it, and) ?: !knownNumbers[and].contains(it) && additionalCondition(it) } } fun getOutputNumber(): Int = outputPatterns.map { when (it.size) { 5 -> { if (it.containsAll(knownNumbers[2])) 2 else if (it.containsAll(knownNumbers[3])) 3 else 5 } 6 -> { if (it.containsAll(knownNumbers[6])) 6 else if (it.containsAll(knownNumbers[9])) 9 else 0 } 2 -> 1 3 -> 7 4 -> 4 7 -> 8 else -> throw RuntimeException("You fucked up!") } }.joinToString("").toInt() /** * This is the only things we ever need to know to solve part 1. * */ fun uniqueLengthPatternsInOutput(): Int { return outputPatterns.count { when (it.size) { 2, 3, 4, 7 -> true else -> false } } } /** * Override the normal set method for this one, so we can also remove from signalPatterns at the same time. */ private operator fun MutableMap<Int, String>.set(key: Int, value: String) { this.put(key, value) } companion object { fun String.toSegmentPattern(): SegmentPattern { val (first, last) = split(" | ") return SegmentPattern( signalPatterns = first.split(' ').map { it.toSet() }.toTypedArray(), outputPatterns = last.split(' ').map { it.toSet() }.toTypedArray() ) } } }
0
Kotlin
0
0
fc7994829e4329e9a726154ffc19e5c0135f5442
6,269
advent-of-code
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/RotateImage.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 fun interface RotateImage { fun rotate(matrix: Array<IntArray>) } /** * Approach 1: Rotate Groups of Four Cells * Time complexity : O(M) * Space complexity : O(1) */ class RotateGroups : RotateImage { override fun rotate(matrix: Array<IntArray>) { val n: Int = matrix.size for (i in 0 until (n + 1) / 2) { for (j in 0 until n / 2) { val temp = matrix[n - 1 - j][i] matrix[n - 1 - j][i] = matrix[n - 1 - i][n - j - 1] matrix[n - 1 - i][n - j - 1] = matrix[j][n - 1 - i] matrix[j][n - 1 - i] = matrix[i][j] matrix[i][j] = temp } } } } /** * Approach 2: Reverse on Diagonal and then Reverse Left to Right * Time complexity : O(M) * Space complexity : O(1) */ class ReverseLeftToRight : RotateImage { override fun rotate(matrix: Array<IntArray>) { transpose(matrix) reflect(matrix) } private fun transpose(matrix: Array<IntArray>) { val n = matrix.size for (i in 0 until n) { for (j in i until n) { val tmp = matrix[j][i] matrix[j][i] = matrix[i][j] matrix[i][j] = tmp } } } private fun reflect(matrix: Array<IntArray>) { val n = matrix.size for (i in 0 until n) { for (j in 0 until n / 2) { val tmp = matrix[i][j] matrix[i][j] = matrix[i][n - j - 1] matrix[i][n - j - 1] = tmp } } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,208
kotlab
Apache License 2.0
2021/src/day24/Day24.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day24 import readInput import java.lang.IllegalStateException import java.text.SimpleDateFormat import java.util.* val POSSIBLE_DIGIT = listOf(9L, 8L, 7L, 6L, 5L, 4L, 3L, 2L, 1L) fun getVarFromStr(str: String, w: Long, x: Long, y: Long, z: Long) : Long { return when (str) { "z" -> z "w" -> w "x" -> x "y" -> y else -> str.toLong() } } fun add(left: String, right: String, w: Long, x: Long, y: Long, z: Long) : Long { return getVarFromStr(left, w, x, y, z) + getVarFromStr(right, w, x, y, z) } fun mul(left: String, right: String, w: Long, x: Long, y: Long, z: Long) : Long { return getVarFromStr(left, w, x, y, z) * getVarFromStr(right, w, x, y, z) } fun div(left: String, right: String, w: Long, x: Long, y: Long, z: Long) : Long? { val a = getVarFromStr(left, w, x, y, z) val b = getVarFromStr(right, w, x, y, z) if (b == 0L) return null return a / b } fun mod(left: String, right: String, w: Long, x: Long, y: Long, z: Long) : Long? { val a = getVarFromStr(left, w, x, y, z) val b = getVarFromStr(right, w, x, y, z) if (b == 0L) return null return a % b } fun eql(left: String, right: String, w: Long, x: Long, y: Long, z: Long) : Long { return if (getVarFromStr(left, w, x, y, z) == getVarFromStr(right, w, x, y, z)) 1 else 0 } val memo = mutableMapOf<String, String?>() fun runInstructions( idx: Int = 0, startW: Long = 0, startX: Long = 0, startY: Long = 0, startZ: Long = 0, inp: String = "", reversed: Boolean = false ): String? { if (inp.length >= 8 && startZ > 100000) return null if (inp.length >= 6 && startZ > 1000000) return null var (w, x, y, z) = listOf(startW, startX, startY, startZ) val key = "$inp/$z" if (memo.containsKey(key)) return memo[key] for (i in idx until toExec.size) { val splits = toExec[i].split(" ") val ope = splits[0] val left = splits[1] val right = splits.getOrNull(2) when (ope) { "inp" -> { val possibleDigits = if (!reversed) POSSIBLE_DIGIT else POSSIBLE_DIGIT.reversed() for (d in possibleDigits) { val (newW ,newX, newY, newZ) = when (left) { "w" -> listOf(d, x, y, z) "x" -> listOf(w, d, y, z) "y" -> listOf(w, x, d, z) "z" -> listOf(w, x, y, d) else -> throw IllegalStateException("inp with $left") } val res = runInstructions(i + 1, newW, newX, newY, newZ, inp+d, reversed) if (res != null) { memo[key] = "$d$res" return memo[key] } else { memo[key] = null } } } "add" -> { when (left) { "w" -> w = add(left, right!!, w, x, y, z) "x" -> x = add(left, right!!, w, x, y, z) "y" -> y = add(left, right!!, w, x, y, z) "z" -> z = add(left, right!!, w, x, y, z) } } "mul" -> { when (left) { "w" -> w = mul(left, right!!, w, x, y, z) "x" -> x = mul(left, right!!, w, x, y, z) "y" -> y = mul(left, right!!, w, x, y, z) "z" -> z = mul(left, right!!, w, x, y, z) } } "div" -> { when (left) { "w" -> w = div(left, right!!, w, x, y, z) ?: return null "x" -> x = div(left, right!!, w, x, y, z) ?: return null "y" -> y = div(left, right!!, w, x, y, z) ?: return null "z" -> z = div(left, right!!, w, x, y, z) ?: return null } } "mod" -> { when (left) { "w" -> w = mod(left, right!!, w, x, y, z) ?: return null "x" -> x = mod(left, right!!, w, x, y, z) ?: return null "y" -> y = mod(left, right!!, w, x, y, z) ?: return null "z" -> z = mod(left, right!!, w, x, y, z) ?: return null } } "eql" -> { when (left) { "w" -> w = eql(left, right!!, w, x, y, z) "x" -> x = eql(left, right!!, w, x, y, z) "y" -> y = eql(left, right!!, w, x, y, z) "z" -> z = eql(left, right!!, w, x, y, z) } } } } print("\\33[2K\r") print("startZ: $startZ inp:$inp - z:$z") memo[key] = if (z == 0L) "" else null return memo[key] } fun <T>measureTime(block: () -> T): T { val start = System.currentTimeMillis() return block().also { println("Solving took ${SimpleDateFormat("mm:ss:SSS").format(Date(System.currentTimeMillis() - start))}") } } var toExec: List<String> = emptyList() fun part1(lines: List<String>) = measureTime { toExec = lines memo.clear() runInstructions()?.toLong() } fun part2(lines: List<String>) = measureTime { toExec = lines memo.clear() // used this to solve pt2: https://github.com/mrphlip/aoc/blob/master/2021/24.md runInstructions(reversed = true)?.toLong() } fun main() { val input = readInput("day24/input") println("part1(input) => " + part1(input)) // 99394899891971 println("part2(input) => " + part2(input)) }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
5,621
advent-of-code
Apache License 2.0
src/Day01.kt
dakr0013
572,861,855
false
{"Kotlin": 105418}
import kotlin.test.assertEquals fun main() { fun part1(input: List<String>): Int { return input .joinToString("\n") .split("\n\n") .map { inventory -> inventory.split("\n").sumOf { it.toInt() } } .max() } fun part2(input: List<String>): Int { return input .joinToString("\n") .split("\n\n") .map { inventory -> inventory.split("\n").sumOf { it.toInt() } } .sorted() .takeLast(3) .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") assertEquals(24000, part1(testInput)) assertEquals(45000, part2(testInput)) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
6b3adb09f10f10baae36284ac19c29896d9993d9
764
aoc2022
Apache License 2.0
src/org/mjurisic/aoc2020/day14/Day14.kt
mjurisic
318,555,615
false
null
package org.mjurisic.aoc2020.day14 import java.io.File import java.math.BigInteger class Day14 { companion object { @JvmStatic fun main(args: Array<String>) = try { var mask = "" val mem = HashMap<String, BigInteger>() File(ClassLoader.getSystemResource("resources/input14.txt").file).forEachLine { if (it.startsWith("mask")) { mask = it.substring(7) } else { val groups = Regex("mem\\[(\\d+)] = (\\d+)").find(it)!!.groups val address = groups[1]!!.value val value = BigInteger(groups[2]!!.value) writeValues(mem, address, mask, value) } } var sum = BigInteger("0") mem.values.forEach { sum = sum.add(it) } println(sum) } catch (e: Exception) { e.printStackTrace() } private fun writeValues( mem: java.util.HashMap<String, BigInteger>, address: String, bitmask: String, value: BigInteger ) { val applyBitmask = applyBitmask(bitmask, BigInteger(address)) val explodeBitmask = explodeBitmask(applyBitmask, 0, listOf(applyBitmask.replace('X', '0'))) explodeBitmask.forEach{ mem[it] = value } } private fun explodeBitmask(bitmask: String, start: Int, input: List<String>): List<String> { val exploded = ArrayList<String>() exploded.addAll(input) if (start == bitmask.length) { return exploded } if (bitmask[start] == 'X') { for (i in 0 until exploded.size) { val replaced = exploded[i].replaceRange(start, start + 1, "1") exploded.add(replaced) } } return explodeBitmask(bitmask, start + 1, exploded) } private fun applyBitmask(bitmask: String, address: BigInteger): String { var result = "" val reversedAddress = address.toString(2).reversed() bitmask.reversed().forEachIndexed { i, c -> var charValue = '0' if (i < reversedAddress.length) { charValue = reversedAddress[i] } when (c) { '1' -> result += '1' '0' -> result += charValue 'X' -> result += 'X' } } return result.reversed() } private fun calculateValue(mask: String, value: BigInteger): BigInteger { var result = "" val stringValue = value.toString(2).reversed() mask.reversed().forEachIndexed { i, c -> var charValue = '0' if (i < stringValue.length) { charValue = stringValue[i] } when (c) { '0' -> result += '0' '1' -> result += '1' 'X' -> result += charValue } } return BigInteger(result.reversed(), 2) } } }
0
Kotlin
0
0
9fabcd6f1daa35198aaf91084de3b5240e31b968
3,301
advent-of-code-2020
Apache License 2.0
common/src/main/kotlin/be/swsb/aoc/common/Positioning.kt
Sch3lp
318,098,967
false
null
package be.swsb.aoc.common import be.swsb.aoc.common.Position.Companion.at import java.io.Serializable data class Quadrants<out T>( val topRight: T, val bottomRight: T, val topLeft: T, val bottomLeft: T ) : Serializable { /** * Returns string representation of the [Quadrants] including its [topRight], [bottomRight], [topLeft] and [bottomLeft] values. */ override fun toString(): String = "\n|$topLeft|$topRight\n|$bottomLeft|$bottomRight|\n" companion object {} } //Thanks ICHBINI! I cleaned it up nicely ;) /** * Partitions the given Positions into a Quadrants of Positions. * x = 0 is regarded as left, y = 0 is regarded as bottom, * So at 0,0 is in the bottom left quadrant */ fun Quadrants.Companion.quadrants(positions: Positions): Quadrants<Positions> { val (right, left) = positions.partition { it.x > 0 } .let { (right, left) -> right.partition { it.y > 0 } to left.partition { it.y > 0 } } return Quadrants(right.first, right.second, left.first, left.second) } /** * Converts this Quadrants into a list. */ fun <T> Quadrants<T>.toList(): List<T> = listOf(topRight, bottomRight, topLeft, bottomLeft) typealias Positions = List<Position> data class Position(val x: Int, val y: Int) { companion object { fun at(x: Int, y: Int): Position = Position(x, y) } infix operator fun plus(other: Position): Position = this.copy(x = this.x + other.x, y= this.y + other.y) } infix fun Position.until(other: Position): Positions { return when { this.x != other.x && this.y != other.y -> { throw java.lang.IllegalArgumentException("Cannot get a range for unrelated axis") } this == other -> { listOf(this) } this.x == other.x -> { (this.y range other.y).map { at(this.x, it) } } this.y == other.y -> { (this.x range other.x).map { at(it, this.y) } } else -> throw java.lang.IllegalArgumentException("I think we're not supposed to end up here") } } typealias ManhattanDistance = Int infix fun Position.manhattanDistanceTo(other: Position): ManhattanDistance { return (this.x range other.x).toList().size + (this.y range other.y).toList().size }
0
Kotlin
0
0
32630a7efa7893b4540fd91d52c2ff3588174c96
2,314
Advent-of-Code-2020
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/LongestNiceSubstring.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * 1763. Longest Nice Substring * @see <a href="https://leetcode.com/problems/longest-nice-substring/">Source</a> */ fun interface LongestNiceSubstring { operator fun invoke(s: String): String } class LNSDivideAndConquer : LongestNiceSubstring { override operator fun invoke(s: String): String { if (s.length < 2) return "" val arr = s.toCharArray() val set: MutableSet<Char> = HashSet() for (c in arr) set.add(c) for (i in arr.indices) { val c = arr[i] if (set.contains(c.uppercaseChar()) && set.contains(c.lowercaseChar())) continue val sub1: String = invoke(s.substring(0, i)) val sub2: String = invoke(s.substring(i + 1)) return if (sub1.length >= sub2.length) sub1 else sub2 } return s } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,472
kotlab
Apache License 2.0
src/_2022/Day04.kt
albertogarrido
572,874,945
false
{"Kotlin": 36434}
package _2022 import readInput fun main() { runTests() runScenario(readInput("2022","day04")) } private fun runScenario(input: List<String>) { println(part1(input)) println(part2(input)) } private fun part1(input: List<String>): Int { var redundancies = 0 parseAssignments(input).forEach { if(containsRange(it.first, it.second)) { redundancies++ } } return redundancies } private fun part2(input: List<String>): Int { var redundancies = 0 parseAssignments(input).forEach { if(containsAnyOfTheRange(it.first, it.second)) { redundancies++ } } return redundancies } private fun containsRange(rangeA: IntRange, rangeB: IntRange): Boolean { if(rangeA.first >= rangeB.first && rangeA.last <= rangeB.last) { return true } if(rangeB.first >= rangeA.first && rangeB.last <= rangeA.last) { return true } return false } private fun containsAnyOfTheRange(rangeA: IntRange, rangeB: IntRange): Boolean { rangeA.forEach { if(rangeB.contains(it)) { return true } } rangeB.forEach { if(rangeA.contains(it)) { return true } } return false } private fun parseAssignments(input: List<String>) = input.map { items -> val row = items.split(",", "-").map { it.toInt() } Pair(row[0]..row[1], row[2]..row[3]) } private fun runTests() { var passed = true runCatching { part1(readInput("2022", "day04_test_p1")).also { check(it == 2) { "part 1: expected 2, obtained $it" } } }.onFailure { passed = false System.err.println("[test failed] ${it.message}") } runCatching { part2(readInput("2022", "day04_test_p2")).also { check(it == 4) { "part 2: expected 4, obtained $it" } } }.onFailure { passed = false System.err.println("[test failed] ${it.message}") } if (passed) println("\u001B[32m>> all tests passed <<\u001B[0m") }
0
Kotlin
0
0
ef310c5375f67d66f4709b5ac410d3a6a4889ca6
2,109
AdventOfCode.kt
Apache License 2.0
src/main/kotlin/aoc2015/day01_almost_lisp/almost_lisp.kt
barneyb
425,532,798
false
{"Kotlin": 238776, "Shell": 3825, "Java": 567}
package aoc2015.day01_almost_lisp import kotlin.streams.toList fun main() { util.solve(280, ::partOne) util.solve(1797, ::partTwo) } private fun String.toDeltaStream() = this.chars() .map(::parenToDelta) fun partOne(input: String) = input .toDeltaStream() .reduce(0, Int::plus) fun partTwo(input: String): Int { val list = input .toDeltaStream() .toList() if (list.size == 1) { if (list.first() == -1) { return 1 } } if (!list.isEmpty()) { list.reduceIndexed { idx, prev, it -> val floor = prev + it if (floor < 0) { return idx + 1 // one-based position } floor } } throw IllegalArgumentException("Basement is never reached") } private fun parenToDelta(c: Int) = when (c.toChar()) { '(' -> 1 ')' -> -1 else -> throw IllegalArgumentException("Unknown '${c}' char") }
0
Kotlin
0
0
a8d52412772750c5e7d2e2e018f3a82354e8b1c3
952
aoc-2021
MIT License
src/medium/_215KthLargestElementInAnArray.kt
ilinqh
390,190,883
false
{"Kotlin": 382147, "Java": 32712}
package medium class _215KthLargestElementInAnArray { // 堆排序可以尽可能的降低时间复杂度 class Solution { fun findKthLargest(nums: IntArray, k: Int): Int { var heapSize = nums.size buildMaxHeap(nums, heapSize) for (i in (nums.size - 1) downTo (nums.size - k + 1)) { swap(nums, 0, i) heapSize-- maxHeapify(nums, 0, heapSize) } return nums[0] } private fun buildMaxHeap(a: IntArray, heapSize: Int) { for (i in (heapSize / 2) downTo 0) { maxHeapify(a, i, heapSize) } } private fun maxHeapify(a: IntArray, i: Int, heapSize: Int) { val left = i * 2 + 1 val right = (i + 1) * 2 var largest = i if (left < heapSize && a[left] > a[largest]) { largest = left } if (right < heapSize && a[right] > a[largest]) { largest = right } if (largest != i) { swap(a, largest, i) maxHeapify(a, largest, heapSize) } } private fun swap(a: IntArray, i: Int, j: Int) { val temp = a[i] a[i] = a[j] a[j] = temp } } }
0
Kotlin
0
0
8d2060888123915d2ef2ade293e5b12c66fb3a3f
1,194
AlgorithmsProject
Apache License 2.0
src/main/kotlin/me/grison/aoc/y2021/Day12.kt
agrison
315,292,447
false
{"Kotlin": 267552}
package me.grison.aoc.y2021 import me.grison.aoc.* import java.util.function.Predicate class Day12 : Day(12, 2021) { override fun title() = "Passage Pathing" private val graph = inputList.map { it.normalSplit("-").pair() }.toGraph() override fun partOne() = graph.countAllPaths("start", "end", trackVisit = { it.isLower() }) override fun partTwo() = graph.countAllPaths( "start", "end", trackVisit = { it.isLower() }, ignore = { it == "start" }, visitUpToTimes = 2 ) /** * Count all possible paths from source to destination. * By default node can be visited only once, but this can be changed with the * `trackVisit` predicate. * Some nodes can also be ignored by using the `ignore` predicate. */ private fun <T> Graph<T>.countAllPaths( source: T, destination: T, trackVisit: Predicate<T> = Predicate { true }, ignore: Predicate<T> = Predicate { false }, visitUpToTimes: Int = 1, ): Int { fun explore(graph: Graph<T>, current: T, visited: Set<T>, times: Int): Int { if (current == destination) return 1 var paths = 0 for (neighbor in graph[current]!!.reject { ignore.test(it) }) { paths += when (trackVisit.test(neighbor)) { true -> when (neighbor) { !in visited -> explore(graph, neighbor, visited + neighbor, times) else -> if (times > 1) explore(graph, neighbor, visited, times - 1) else 0 } else -> explore(graph, neighbor, visited, times) } } return paths } return explore(this, source, mutableSetOf(source), visitUpToTimes) } }
0
Kotlin
3
18
ea6899817458f7ee76d4ba24d36d33f8b58ce9e8
1,791
advent-of-code
Creative Commons Zero v1.0 Universal
src/main/kotlin/io/binarysearch/MedianTwoSortedArrays.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.binarysearch import kotlin.math.max import kotlin.math.min //https://leetcode.com/explore/learn/card/binary-search/146/more-practices-ii/1040/ class MedianTwoSortedArrays { fun execute(input0: IntArray, input1: IntArray): Double { val smallInput = if (input0.size < input1.size) input0 else input1 val largeInput = if (input0.size < input1.size) input1 else input0 val smallSize = smallInput.size val largeSize = largeInput.size var iMin = 0 var iMax = smallSize val halfLen = (smallSize + largeSize + 1) / 2 while (iMin <= iMax) { val i = (iMin + iMax) / 2 val j = halfLen - i if (i < iMax && largeInput[j - 1] > smallInput[i]) { iMin = i + 1 // i is too small } else if (i > iMin && smallInput[i - 1] > largeInput[j]) { iMax = i - 1 // i is too big } else { // i is perfect val maxLeft = when { i == 0 -> largeInput[j - 1] j == 0 -> smallInput[i - 1] else -> max(smallInput[i - 1], largeInput[j - 1]) } if ((smallSize + largeSize) % 2 == 1) { return maxLeft.toDouble() } val minRight = when { i == smallSize -> { largeInput[j] } j == largeSize -> { smallInput[i] } else -> { min(largeInput[j], smallInput[i]) } } return (maxLeft + minRight) / 2.0 } } return 0.0 } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
1,470
coding
MIT License
src/chapter4/section3/ex10.kt
w1374720640
265,536,015
false
{"Kotlin": 1373556}
package chapter4.section3 import edu.princeton.cs.algs4.In import edu.princeton.cs.algs4.Queue /** * 为稠密图实现EdgeWeightedGraph,使用邻接矩阵(存储权重的二维数组),不允许存在平行边。 */ class AdjacencyMatrixEWG(V: Int) : EWG(V) { private val matrix = Array(V) { Array(V) { Double.POSITIVE_INFINITY } } constructor(input: In) : this(input.readInt()) { val E = input.readInt() repeat(E) { val edge = Edge(input.readInt(), input.readInt(), input.readDouble()) addEdge(edge) } } private fun hasEdge(v: Int, w: Int): Boolean { return matrix[v][w] != Double.POSITIVE_INFINITY } override fun addEdge(edge: Edge) { val v = edge.either() val w = edge.other(v) // 不允许存在平行边 if (hasEdge(v, w)) return matrix[v][w] = edge.weight matrix[w][v] = edge.weight E++ } override fun adj(v: Int): Iterable<Edge> { val queue = Queue<Edge>() for (w in matrix[v].indices) { if (hasEdge(v, w)) { queue.enqueue(Edge(v, w, matrix[v][w])) } } return queue } override fun edges(): Iterable<Edge> { val queue = Queue<Edge>() for (v in 0 until V) { for (w in v + 1 until V) { if (hasEdge(v, w)) { queue.enqueue(Edge(v, w, matrix[v][w])) } } } return queue } override fun toString(): String { val stringBuilder = StringBuilder() .append(V) .append(" vertices, ") .append(E) .append(" edges\n") edges().forEach { stringBuilder.append(it.toString()) .append("\n") } return stringBuilder.toString() } } fun main() { val graph = AdjacencyMatrixEWG(In("./data/tinyEWG.txt")) println(graph) }
0
Kotlin
1
6
879885b82ef51d58efe578c9391f04bc54c2531d
1,999
Algorithms-4th-Edition-in-Kotlin
MIT License
src/Day25.kt
janbina
112,736,606
false
null
package Day25 import java.util.* import kotlin.test.assertEquals fun main(args: Array<String>) { //INPUT: val initialState = 1 val steps = 12_172_063 val transitions = listOf( TuringMachine.Transition(1, false, 2, true, TuringMachine.Transition.Move.RIGHT), TuringMachine.Transition(1, true, 3, false, TuringMachine.Transition.Move.LEFT), TuringMachine.Transition(2, false, 1, true, TuringMachine.Transition.Move.LEFT), TuringMachine.Transition(2, true, 4, true, TuringMachine.Transition.Move.LEFT), TuringMachine.Transition(3, false, 4, true, TuringMachine.Transition.Move.RIGHT), TuringMachine.Transition(3, true, 3, false, TuringMachine.Transition.Move.RIGHT), TuringMachine.Transition(4, false, 2, false, TuringMachine.Transition.Move.LEFT), TuringMachine.Transition(4, true, 5, false, TuringMachine.Transition.Move.RIGHT), TuringMachine.Transition(5, false, 3, true, TuringMachine.Transition.Move.RIGHT), TuringMachine.Transition(5, true, 6, true, TuringMachine.Transition.Move.LEFT), TuringMachine.Transition(6, false, 5, true, TuringMachine.Transition.Move.LEFT), TuringMachine.Transition(6, true, 1, true, TuringMachine.Transition.Move.RIGHT) ) val machine = TuringMachine(initialState, transitions) machine.run(steps) assertEquals(2474, machine.cardinality) } class TuringMachine(initialState: Int, transitions: List<Transition>) { private val tape = BitSet() private val transitions = transitions.groupBy { it.fromState } private val tapePosition get() = if (position <= 0) -position * 2 else position * 2 - 1 private val transition get() = transitions[state]!!.first { it.fromValue == tape[tapePosition] } private var position = 0 private var state = initialState val cardinality get() = tape.cardinality() fun run(steps: Int) { repeat(steps) { transition.let { state = it.toState tape[tapePosition] = it.toValue position += it.move.move } } } data class Transition( val fromState: Int, val fromValue: Boolean, val toState: Int, val toValue: Boolean, val move: Move ) { enum class Move(val move: Int) { LEFT(-1), RIGHT(1) } } }
0
Kotlin
0
0
71b34484825e1ec3f1b3174325c16fee33a13a65
2,450
advent-of-code-2017
MIT License
kotlin tutorial/scratch.kts
AlexandraDediu
244,655,422
false
null
val x = 5 //also type inference println(x) var name = "John" //daca vrem ca valoarea sa se poata modifica name = "Mary" println(name) var name1: String? = null //var can be nullable val length = name1?.length ?: -1 println(length) //val length2 = name1!!.length //println(length2) fun sumOfTwo(x: Int, y: Int): Int { return x + y } //inline fuction fun sumOfTwo1(x: Int, y: Int) = x + y println(sumOfTwo1(5, 6)) fun printName1(name: String) { println(name) } printName1("John") fun printTwoWords(x: String, y: String = "a") { println("First string is : $x, second string is : $y") } printTwoWords("b") fun getGreatestValue(x: Int, y: Int): Int { return if (x > y) { x } else { y } } fun getGreatestValue(x: Int, y: Int) = if (x > y) x else y fun printName(name: String) { when (name) { "John" -> println("<NAME>") "Mark" -> println("<NAME>") else -> println("No name") } } printName("John") fun printNumber() { for (i in 1..4) { println(i) } } printNumber() //-----------------lab2------------------- val str = "abc" str[0] str.length str.substring(0, 2) val num = 6 "My favorite number is ${num * num}" for (l in str) print("$l ") str.forEach { print("$it ") } fun isEven(num: Int) = num % 2 == 0 isEven(5) fun consonants(str: String): String { var result :String =""; for(chr in str){ if(!(chr in "AEIOUaeiou")){ result += chr } } return result } fun consonants1(str: String) =str.filterNot { it in "AEIOUaeiou" } consonants1("Hello, world!") //extension functions fun String.consonants() = filterNot { it in "AEIOUaeiou" } "Hello, wordl".consonants() fun Int.isEven() = rem(2)==0 4.isEven()
0
Kotlin
0
0
c4b37692343899083e1a643085e9db4b9b484f6c
1,852
aquamarine
Apache License 2.0
src/main/kotlin/org/team2471/frc/lib/math/Geometry.kt
TeamMeanMachine
72,503,638
false
{"Kotlin": 139167, "Java": 95325}
package org.team2471.frc.lib.math import java.lang.Math.pow import java.lang.Math.sqrt data class Point(val x: Double, val y: Double) { companion object { @JvmStatic val ORIGIN: Point = Point(0.0, 0.0) } operator fun unaryPlus() = this operator fun unaryMinus() = Point(-x, -y) operator fun plus(b: Point) = Point(x + b.x, y + b.y) operator fun plus(vec: Vector2) = Point(x + vec.x, y + vec.y) operator fun minus(b: Point) = Point(x - b.x, y - b.y) operator fun minus(vec: Vector2) = Point(x - vec.x, y - vec.y) operator fun times(scalar: Double) = Point(x * scalar, y * scalar) operator fun div(scalar: Double) = Point(x / scalar, y / scalar) fun distance(b: Point): Double = sqrt(pow(b.x - this.x, 2.0) + pow(b.y - this.y, 2.0)) fun vectorTo(b: Point): Vector2 = Vector2(b.x - this.x, b.y - this.y) fun closestPoint(firstPoint: Point, vararg additionalPoints: Point): Point = additionalPoints.fold(firstPoint) { result, next -> if (distance(next) < distance(result)) next else result } } data class Line(val pointA: Point, val pointB: Point) { val slope = (pointB.y - pointA.y) / (pointB.x - pointA.x) val intercept = -slope * pointA.x + pointA.y operator fun get(x: Double): Double = slope * x + intercept operator fun plus(vec: Vector2) = Line(pointA + vec, pointB + vec) operator fun minus(vec: Vector2) = Line(pointA - vec, pointB - vec) fun pointInLine(point: Point): Boolean = point.y == this[point.x] fun pointInSegment(point: Point): Boolean = pointInLine(point) && point.distance(pointA) + point.distance(pointB) == pointA.distance(pointB) } data class Circle(val center: Point, val radius: Double) { companion object { @JvmStatic val UNIT = Circle(Point.ORIGIN, 1.0) } // adapted from: https://stackoverflow.com/a/13055116 fun intersectingPoints(line: Line): Array<Point> { val (pointA, pointB) = line val baX = pointB.x - pointA.x val baY = pointB.y - pointA.y val caX = center.x - pointA.x val caY = center.y - pointA.y val a = baX * baX + baY * baY val bBy2 = baX * caX + baY * caY val c = caX * caX + caY * caY - radius * radius val pBy2 = bBy2 / a val q = c / a val disc = pBy2 * pBy2 - q if (disc < 0) { return emptyArray() } // if disc == 0 ... dealt with later val tmpSqrt = Math.sqrt(disc) val abScalingFactor1 = -pBy2 + tmpSqrt val abScalingFactor2 = -pBy2 - tmpSqrt val p1 = Point(pointA.x - baX * abScalingFactor1, pointA.y - baY * abScalingFactor1) if (disc == 0.0) { // abScalingFactor1 == abScalingFactor2 return arrayOf(p1) } val p2 = Point(pointA.x - baX * abScalingFactor2, pointA.y - baY * abScalingFactor2) return arrayOf(p1, p2) } operator fun plus(vec: Vector2) = Circle(center + vec, radius) operator fun minus(vec: Vector2) = Circle(center - vec, radius) operator fun times(scalar: Double) = Circle(center, radius * scalar) operator fun div(scalar: Double) = Circle(center, radius / scalar) }
3
Kotlin
3
15
93dd7e7163ec2535e11965687e563369ca899f21
3,276
meanlib
The Unlicense
day20/src/main/kotlin/ver_b.kt
jabbalaci
115,397,721
false
null
package b import java.math.BigInteger import java.io.File data class Point(var x: BigInteger, var y: BigInteger, var z: BigInteger) data class Particle(val id: Int, val line: String) { private val points = mutableListOf<Point>() init { val REGEX = Regex("""<(.*?)>""") val matchedResults = REGEX.findAll(line) for (matchedText in matchedResults) { val parts = matchedText.value.replace("<", "").replace(">", "").split(",").map { it.trim().toInt().toBigInteger() } points.add(Point(parts[0], parts[1], parts[2])) } } // these MUST come after the init! val position = points[0] private val velocity = points[1] private val acceleration = points[2] fun move() { velocity.x += acceleration.x velocity.y += acceleration.y velocity.z += acceleration.z // position.x += velocity.x position.y += velocity.y position.z += velocity.z } override fun toString(): String { val sb = StringBuilder() sb.append("p(${id})=") sb.append(position.toString()) return sb.toString() } } object Space { private val particles = mutableListOf<Particle>() fun readInput(fname: String) { var id = 0 File(fname).forEachLine { line -> particles.add(Particle(id, line)) ++id } } fun start() { var cnt = 0 val limit = 100 while (true) { // println(this) // println("-------------------------------------") for (p in particles) { p.move() } removeCollisions() ++cnt if (cnt > limit) { break } } } private fun removeCollisions() { val map = mutableMapOf<Point, MutableList<Int>>() for (p in particles) { if (p.position !in map) { map[p.position] = mutableListOf() } map[p.position]!!.add(p.id) } // for (li in map.values) { if (li.size >= 2) { println("particles before: %d".format(particles.size)) li.forEach { id -> particles.removeIf { p -> p.id == id } } println("particles after: %d".format(particles.size)) println("-----------------------------------") } } } override fun toString(): String { val sb = StringBuilder() for (p in particles) { sb.append(p.toString()) sb.append("\n") } return sb.toString() } } fun main(args: Array<String>) { // example // val fname = "example2.txt" // production val fname = "input.txt" Space.readInput(fname) // println(Space) Space.start() }
0
Kotlin
0
0
bce7c57fbedb78d61390366539cd3ba32b7726da
2,959
aoc2017
MIT License
Mastermind/src/mastermind/evaluateGuess.kt
Sharkaboi
258,941,707
false
null
package mastermind import java.lang.Integer.min data class Evaluation(val rightPosition: Int, val wrongPosition: Int) fun evaluateGuess( secret: String, guess: String): Evaluation { //count of right positions var right = 0 //A-0,B-1,C-2,D-3,E-4,F-5 //array for A-F with count for each occurrence (secret) val secretCharCount = IntArray(6) //array for A-F with count for each occurrence (guess) val guessCharCount = IntArray(6) //iterating over 4 letters for (i in 0..3){ val s = secret[i] val g = guess[i] //increasing count in appropriate index of letter ++secretCharCount[s.toInt() - 65] ++guessCharCount[g.toInt() - 65] //if equal,increase right if (s == g) ++right } /* Here we have count and actual guess and secret noOfCommonLetters contains no.of letters that are common uniquely for ex: secret-ABCD,guess-EAAA, noOfCommonLetters=1 (secret[0]-guess[1]) here secretCharCount:A=1,guessCharCount:A=3 and min gives 1 */ val noOfCommonLetters = (secretCharCount.indices).sumBy { min(secretCharCount[it], guessCharCount[it]) } //wrong letters = no.of common letters - no.of right placed letters. return Evaluation(right, noOfCommonLetters - right) }
0
Kotlin
0
0
977968b41ecc0ed1b62b50784bfebc3fa9d95a11
1,300
Kotlin-for-java-devs-course
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MctFromLeafValues.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 java.util.Stack import kotlin.math.min /** * 1130. Minimum Cost Tree From Leaf Values * @see <a href="https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/">Source</a> */ fun interface MctFromLeafValues { operator fun invoke(arr: IntArray): Int } class MctFromLeafValuesDP : MctFromLeafValues { override operator fun invoke(arr: IntArray): Int { var res = 0 val stack: Stack<Int> = Stack() stack.push(Int.MAX_VALUE) for (a in arr) { while (stack.peek() <= a) { val mid: Int = stack.pop() res += mid * min(stack.peek(), a) } stack.push(a) } while (stack.size > 2) { res += stack.pop() * stack.peek() } return res } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,438
kotlab
Apache License 2.0
src/main/kotlin/me/grison/aoc/y2020/Day23.kt
agrison
315,292,447
false
{"Kotlin": 267552}
package me.grison.aoc.y2020 import me.grison.aoc.Day import me.grison.aoc.normalSplit import kotlin.collections.set class Day23 : Day(23, 2020) { override fun title() = "Crab Cups" override fun partOne(): Any { val cups = loadCups() var cup: Cup = cups[0] for (i in 1..100) { val move = cup.next() cup.next = cup.forward(4) val destination = cup.destination(move, 1, 9) var it = cup.next() while (it.value != destination) it = it.next() move.forward(2).next = it.next it.next = move cup = cup.next() } return cup.moveUntil(1).valuesUntil(1) } override fun partTwo(): Any { val cups = loadCups() val max = 1_000_000 // add cups from 10 to 1,000,000 var cup: Cup = cups[8] for (i in 10..max) { cup.next = Cup(i, null) cup = cup.next!! } cup.next = cups[0] // also save them in a Map cup = cups[0] val cache = mutableMapOf(cup.value to cup) var it = cup.next() while (it != cup) { cache[it.value] = it it = it.next() } // make the moves for (i in 1..10 * max) { val move = cup.next() cup.next = cup.forward(4) val destination = cache[cup.destination(move, 1, max)]!! move.forward(2).next = destination.next() destination.next = move cup = cup.next() } val one = cache[1]!! return one.nextValue().toLong() * one.forward(2).value.toLong() } private fun loadCups(): List<Cup> { val cups = inputString.normalSplit("").map { Cup(it.toInt()) } return cups.mapIndexed { i, c -> c.next = cups[(i + 1) % cups.size]; c } } } data class Cup(val value: Int, var next: Cup? = null) { fun next() = next!! fun nextValue() = next().value private fun picked() = listOf(value, nextValue(), forward(2).value) fun forward(n: Int): Cup { var cup = copy() repeat(n) { cup = cup.next() } return cup } fun destination(move: Cup, min: Int, max: Int): Int { var destination = if (value == min) max else value - 1 while (destination in move.picked()) { if (--destination < min) destination = max } return destination } fun moveUntil(v: Int): Cup { var cup = copy() while (cup.value != v) cup = cup.next() return cup } fun valuesUntil(v: Int): String { var (s, cup) = Pair("", copy()) while (cup.nextValue() != v) { s += cup.nextValue() cup = cup.next() } return s } }
0
Kotlin
3
18
ea6899817458f7ee76d4ba24d36d33f8b58ce9e8
2,837
advent-of-code
Creative Commons Zero v1.0 Universal
kotest-property/src/commonMain/kotlin/io/kotest/property/arbitrary/strings.kt
ca-r0-l
258,232,982
true
{"Kotlin": 2272378, "HTML": 423, "Java": 153}
package io.kotest.property.arbitrary import io.kotest.fp.firstOption import io.kotest.property.Arb import io.kotest.property.Shrinker import kotlin.random.nextInt /** * Returns an [Arb] where each random value is a String of length between minSize and maxSize. * By default the arb uses a [ascii] codepoint generator, but this can be substituted * with any codepoint generator. There are many available, such as [katakana] and so on. * * The edge case values are a string of the min length, and a string of the max length, using the first * edgecase codepoint provided by the codepoints arb. */ fun Arb.Companion.string( minSize: Int = 0, maxSize: Int = 100, codepoints: Arb<Codepoint> = Arb.ascii() ): Arb<String> { val lowCodePoint = codepoints.edgecases().firstOption() val shortest = lowCodePoint.map { cp -> List(minSize) { cp.asString() }.joinToString("") }.orNull() val longest = lowCodePoint.map { cp -> List(maxSize) { cp.asString() }.joinToString("") }.orNull() val edgecases = listOfNotNull(shortest, longest) return arb(StringShrinker, edgecases) { rs -> val codepointsIterator = codepoints.values(rs).iterator() val size = rs.random.nextInt(minSize..maxSize) List(size) { codepointsIterator.next().value }.joinToString("") { it.asString() } } } fun Arb.Companion.string(range: IntRange, codepoints: Arb<Codepoint> = Arb.ascii()): Arb<String> = Arb.string(range.first, range.last, codepoints) object StringShrinker : Shrinker<String> { override fun shrink(value: String): List<String> { return when { value == "" -> emptyList() value == "a" -> listOf("") value.length == 1 -> listOf("", "a") else -> { val firstHalf = value.take(value.length / 2 + value.length % 2) val secondHalf = value.takeLast(value.length / 2) val secondHalfAs = firstHalf.padEnd(value.length, 'a') val firstHalfAs = secondHalf.padStart(value.length, 'a') val dropFirstChar = value.drop(1) val dropLastChar = value.dropLast(1) listOf( firstHalf, firstHalfAs, secondHalf, secondHalfAs, dropFirstChar, dropLastChar ) } } } }
0
null
0
1
e176cc3e14364d74ee593533b50eb9b08df1f5d1
2,321
kotest
Apache License 2.0
src/main/kotlin/solutions/CHK/CheckoutSolution.kt
DPNT-Sourcecode
718,056,917
false
{"Kotlin": 22059, "Shell": 2184}
package solutions.CHK import kotlin.jvm.internal.Intrinsics.Kotlin object CheckoutSolution { fun checkout(skus: String): Int { var total = 0 val counts = mutableMapOf<Char, Int>() val groupDiscountItems = listOf('S', 'T', 'X', 'Y', 'Z') val individualPrices = mapOf('S' to 20, 'T' to 20, 'X' to 17, 'Y' to 20, 'Z' to 21) for (item in skus) { when (item) { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' -> counts[item] = counts.getOrDefault(item, 0) + 1 else -> return -1 } } // Handle group discount offers var groupDiscountCount = groupDiscountItems.sumBy { counts.getOrDefault(it, 0) } while (groupDiscountCount >= 3) { total += 45 groupDiscountCount -= 3 // Remove the items that were part of the group discount from the counts map for (item in groupDiscountItems) { if (counts.getOrDefault(item, 0) > 0) { counts[item] = counts.getOrDefault(item, 0) - 1 } } } total += groupDiscountItems.sumBy { counts.getOrDefault(it, 0) * individualPrices.getOrDefault(it, 0) } // Handle E offers while (counts.getOrDefault('E', 0) >= 2) { total += 80 counts['E'] = counts.getOrDefault('E', 0) - 2 if (counts.getOrDefault('B', 0) > 0) { counts['B'] = counts.getOrDefault('B', 0) - 1 } } total += counts.getOrDefault('E', 0) * 40 // Handle F offers while (counts.getOrDefault('F', 0) >= 3) { total += 20 counts['F'] = counts.getOrDefault('F', 0) - 3 } total += counts.getOrDefault('F', 0) * 10 // Handle H offers while (counts.getOrDefault('H', 0) >= 10) { total += 80 counts['H'] = counts.getOrDefault('H', 0) - 10 } while (counts.getOrDefault('H', 0) >= 5) { total += 45 counts['H'] = counts.getOrDefault('H', 0) - 5 } total += counts.getOrDefault('H', 0) * 10 // Handle K offers while (counts.getOrDefault('K', 0) >= 2) { total += 120 counts['K'] = counts.getOrDefault('K', 0) - 2 } total += counts.getOrDefault('K', 0) * 70 // Handle N offers while (counts.getOrDefault('N', 0) >= 3) { total += 120 counts['N'] = counts.getOrDefault('N', 0) - 3 if (counts.getOrDefault('M', 0) > 0) { counts['M'] = counts.getOrDefault('M', 0) - 1 } } total += counts.getOrDefault('N', 0) * 40 // Handle P offers while (counts.getOrDefault('P', 0) >= 5) { total += 200 counts['P'] = counts.getOrDefault('P', 0) - 5 } total += counts.getOrDefault('P', 0) * 50 // Handle R offers while (counts.getOrDefault('R', 0) >= 3) { total += 150 counts['R'] = counts.getOrDefault('R', 0) - 3 if (counts.getOrDefault('Q', 0) > 0) { counts['Q'] = counts.getOrDefault('Q', 0) - 1 } } total += counts.getOrDefault('R', 0) * 50 // Handle Q offers while (counts.getOrDefault('Q', 0) >= 3) { total += 80 counts['Q'] = counts.getOrDefault('Q', 0) - 3 } total += counts.getOrDefault('Q', 0) * 30 // Handle U offers while (counts.getOrDefault('U', 0) >= 4) { total += 120 counts['U'] = counts.getOrDefault('U', 0) - 4 } total += counts.getOrDefault('U', 0) * 40 // Handle V offers while (counts.getOrDefault('V', 0) >= 3) { total += 130 counts['V'] = counts.getOrDefault('V', 0) - 3 } while (counts.getOrDefault('V', 0) >= 2) { total += 90 counts['V'] = counts.getOrDefault('V', 0) - 2 } total += counts.getOrDefault('V', 0) * 50 // Handle A offers total += (counts.getOrDefault('A', 0) / 5) * 200 counts['A'] = counts.getOrDefault('A', 0) % 5 total += (counts.getOrDefault('A', 0) / 3) * 130 counts['A'] = counts.getOrDefault('A', 0) % 3 total += counts.getOrDefault('A', 0) * 50 // Handle B offers total += (counts.getOrDefault('B', 0) / 2) * 45 counts['B'] = counts.getOrDefault('B', 0) % 2 total += counts.getOrDefault('B', 0) * 30 // Handle C and D total += counts.getOrDefault('C', 0) * 20 total += counts.getOrDefault('D', 0) * 15 // Handle G, I, J, L, O, S, T, W, Y, Z total += counts.getOrDefault('G', 0) * 20 total += counts.getOrDefault('I', 0) * 35 total += counts.getOrDefault('J', 0) * 60 total += counts.getOrDefault('L', 0) * 90 total += counts.getOrDefault('M', 0) * 15 total += counts.getOrDefault('O', 0) * 10 total += counts.getOrDefault('W', 0) * 20 return total } }
0
Kotlin
0
0
b1947b8c4243303f6998f2e23774b175423a3718
5,269
CHK-edzx01
Apache License 2.0
kotlin/src/test/kotlin/be/swsb/aoc2023/day4/Solve.kt
Sch3lp
724,797,927
false
{"Kotlin": 44815, "Rust": 14075}
package be.swsb.aoc2023.day4 import be.swsb.aoc2023.readFile import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.equals.shouldBeEqual import org.junit.jupiter.api.Test class Day4Test { private val actualInput = readFile("2023/day4/input.txt") @Test fun parse() { val input = """ Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53 Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19 Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1 Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83 Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36 Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11 """.trimIndent() parse(input).shouldContainExactly( Card(id = 1, listOf(41, 48, 83, 86, 17), numbers = listOf(83, 86, 6, 31, 17, 9, 48, 53)), Card(id = 2, listOf(13, 32, 20, 16, 61), numbers = listOf(61, 30, 68, 82, 17, 32, 24, 19)), Card(id = 3, listOf(1, 21, 53, 59, 44), numbers = listOf(69, 82, 63, 72, 16, 21, 14, 1)), Card(id = 4, listOf(41, 92, 73, 84, 69), numbers = listOf(59, 84, 76, 51, 58, 5, 54, 83)), Card(id = 5, listOf(87, 83, 26, 28, 32), numbers = listOf(88, 30, 70, 12, 93, 22, 82, 36)), Card(id = 6, listOf(31, 18, 13, 56, 72), numbers = listOf(74, 77, 10, 23, 35, 67, 36, 11)), ) } @Test fun `card worth`() { Card(id = 1, listOf(41, 48, 83, 86, 17), numbers = listOf(83, 86, 6, 31, 17, 9, 48, 53)).worth shouldBeEqual 8 Card(id = 2, listOf(13, 32, 20, 16, 61), numbers = listOf(61, 30, 68, 82, 17, 32, 24, 19)).worth shouldBeEqual 2 Card(id = 3, listOf(1, 21, 53, 59, 44), numbers = listOf(69, 82, 63, 72, 16, 21, 14, 1)).worth shouldBeEqual 2 Card(id = 4, listOf(41, 92, 73, 84, 69), numbers = listOf(59, 84, 76, 51, 58, 5, 54, 83)).worth shouldBeEqual 1 Card(id = 5, listOf(87, 83, 26, 28, 32), numbers = listOf(88, 30, 70, 12, 93, 22, 82, 36)).worth shouldBeEqual 0 Card(id = 6, listOf(31, 18, 13, 56, 72), numbers = listOf(74, 77, 10, 23, 35, 67, 36, 11)).worth shouldBeEqual 0 } @Test fun solve1() { println(parse(actualInput).sumOf { it.worth }) } }
0
Kotlin
0
1
dec9331d3c0976b4de09ce16fb8f3462e6f54f6e
2,253
Advent-of-Code-2023
MIT License
src/main/kotlin/g1601_1700/s1658_minimum_operations_to_reduce_x_to_zero/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1601_1700.s1658_minimum_operations_to_reduce_x_to_zero // #Medium #Array #Hash_Table #Binary_Search #Prefix_Sum #Sliding_Window // #2023_06_15_Time_532_ms_(50.00%)_Space_53_MB_(100.00%) class Solution { fun minOperations(nums: IntArray, x: Int): Int { var totalArraySum = 0 for (each in nums) { totalArraySum += each } if (totalArraySum == x) { return nums.size } val target = totalArraySum - x // as we need to find value equal to x so that x-x=0, // and we need to search the longest sub array with sum equal t0 total array sum -x; var sum = 0 var result = -1 var start = 0 for (end in nums.indices) { sum += nums[end] while (sum > target && start < nums.size) { sum -= nums[start] start++ } if (sum == target) { result = Math.max(result, end + 1 - start) } } return if (result == -1) { result } else { nums.size - result } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,133
LeetCode-in-Kotlin
MIT License
src/main/kotlin/org/example/adventofcode/puzzle/Day02.kt
peterlambrechtDev
573,146,803
false
{"Kotlin": 39213}
package org.example.adventofcode.puzzle import org.example.adventofcode.util.FileLoader private const val DELIMITER = " " private val part1Map = mutableMapOf(Pair("A", 1), Pair("B", 2), Pair("C", 3), Pair("X", 1), Pair("Y", 2), Pair("Z", 3)) private val part2Map = mutableMapOf( Pair(1, mutableMapOf(Pair("Z", 2), Pair("Y", 1), Pair("X", 3))), Pair(2, mutableMapOf(Pair("Z", 3), Pair("Y", 2), Pair("X", 1))), Pair(3, mutableMapOf(Pair("Z", 1), Pair("Y", 3), Pair("X", 2))) ) object Day02 { fun part1(filePath: String): Int { val matches = FileLoader.loadFromFile<String>(filePath) var score = 0 for (match in matches) { if (match.isNotEmpty()) { val shapes = match.split(DELIMITER) val opponentShape: Int = part1Map.get(shapes[0])!! val yourShape: Int = part1Map.get(shapes[1])!! var matchResult = 0 if ((opponentShape == 3 && yourShape == 1) || (yourShape - opponentShape == 1)) { matchResult = 6 } else if (opponentShape == yourShape) { matchResult = 3 } score += yourShape + matchResult } } return score } fun part2(filePath: String): Int { val matches = FileLoader.loadFromFile<String>(filePath) var score = 0 for (match in matches) { if (match.isNotEmpty()) { val shapes = match.split(DELIMITER) val opponentShape = part2Map.get(part1Map.get(shapes[0])) val desiredResult = shapes[1] val yourShape = opponentShape?.get(desiredResult) val matchResult: Int = when (desiredResult) { "X" -> { 0 } "Y" -> { 3 } else -> { 6 } } score += yourShape!! + matchResult } } return score } } fun main() { var day = "day02" println("Example 1: ${Day02.part1("/${day}_example.txt")}") println("Solution 1: ${Day02.part1("/${day}.txt")}") println("Example 2: ${Day02.part2("/${day}_example.txt")}") println("Solution 2: ${Day02.part2("/${day}.txt")}") }
0
Kotlin
0
0
aa7621de90e551eccb64464940daf4be5ede235b
2,409
adventOfCode2022
MIT License
app/src/main/java/io/github/pshegger/gamedevexperiments/algorithms/pathfinding/AStar.kt
PsHegger
99,228,633
false
null
package io.github.pshegger.gamedevexperiments.algorithms.pathfinding import io.github.pshegger.gamedevexperiments.algorithms.maze.BaseMazeGenerator import java.util.* /** * @author <EMAIL> */ class AStar(maze: List<List<BaseMazeGenerator.FieldValue>>, val heuristic: (Coordinate, Coordinate) -> Float, val tieBreaker: Float = 0.0002F) : BasePathFinder(maze) { private var pathFound = false private var unvisitedNodes = arrayListOf<NodeData>() private var visitedNodes = arrayListOf<NodeData>() private var currentNode: NodeData = NodeData(start, null, 0) private var pathBackTrack: Coordinate? = stop private var emptyBackTrack: Stack<NodeData> = Stack() override fun nextStep() { if (unvisitedNodes.isEmpty()) { val nodes = maze.mapIndexed { y, row -> row.mapIndexed { x, fieldValue -> if (fieldValue == BaseMazeGenerator.FieldValue.Empty) { Coordinate(x, y) } else { null } } }.flatten().filterNotNull().map { NodeData(it, null) } unvisitedNodes.addAll(nodes) visitedNodes.add(currentNode) } if (!pathFound) { currentNode.c.unvisitedNeighborNodes().forEach { node -> if (currentNode.distance + 1 < node.distance) { node.distance = currentNode.distance + 1 node.prev = currentNode.c } } unvisitedNodes.remove(currentNode) visitedNodes.add(currentNode) if (currentNode.c == stop) { pathFound = true } else { if (currentNode.c != start) { changeState(currentNode.c, FieldState.FieldValue.Active) } currentNode = unvisitedNodes.filter { it.distance != Int.MAX_VALUE }.minBy { it.distance + heuristic(it.c, stop) * (1 + tieBreaker) }!! } } else { pathBackTrack?.let { c -> if (c != stop && c != start) { changeState(c, FieldState.FieldValue.Path) } pathBackTrack = visitedNodes.first { it.c == c }.prev visitedNodes.filter { it.prev == pathBackTrack && getState(it.c) == FieldState.FieldValue.Active } .forEach { buildEmptyStack(it) } } ?: let { if (!emptyBackTrack.empty()) { removeState(emptyBackTrack.pop().c) } } } } private fun buildEmptyStack(n: NodeData) { emptyBackTrack.push(n) visitedNodes.filter { it.prev == n.c && getState(it.c) == FieldState.FieldValue.Active } .forEach { buildEmptyStack(it) } } private fun Coordinate.unvisitedNeighborNodes() = unvisitedNodes.filter { (c) -> possibleDestinations.any { dst -> dst == c } } private data class NodeData(val c: Coordinate, var prev: Coordinate?, var distance: Int = Int.MAX_VALUE) }
0
Kotlin
0
0
694d273a6d3dff49cf314cbe16e17b5f77c7738e
3,113
GameDevExperiments
MIT License
src/main/kotlin/dev/claudio/adventofcode2021/Day8Part2.kt
ClaudioConsolmagno
434,559,159
false
{"Kotlin": 78336}
package dev.claudio.adventofcode2021 fun main() { Day8Part2().main() } private class Day8Part2 { fun main() { val input: List<InputLine> = Support.readFileAsListString("day8-input.txt") .map { val split = it.split("|") InputLine( split[0].trim().split(" "), split[1].trim().split(" ") ) } val resultsString: List<String> = input.map { val deduction = mutableMapOf<Int, Set<Char>>() (it.signalPattern + it.outputValue).forEach { input -> if (input.length == 2) { deduction[1] = setOf(input[0], input[1]) } if (input.length == 4) { deduction[4] = setOf(input[0], input[1], input[2], input[3]) } if (input.length == 3) { deduction[3] = setOf(input[0], input[1], input[2]) } } it.outputValue.map { output: String -> var char = 'X' if (output.length == 2) { char = '1' } if (output.length == 4) { char = '4' } if (output.length == 3) { char = '7' } if (output.length == 7) { char = '8' } if (output.length == 5) { char = '5' if (deduction[1] != null) { if (output.toCharArray().toList().containsAll(deduction[1]!!)) { char = '3' } else { if (deduction[4] != null) { if (output.toCharArray().toList().count { it in deduction[4]!! } == 2) { char = '2' } else { char = '5' } } } } if (deduction[7] != null) { if (output.toCharArray().toList().containsAll(deduction[1]!!)) { char = '3' } else { if (deduction[4] != null) { if (output.toCharArray().toList().count { it in deduction[4]!! } == 2) { char = '2' } else { char = '5' } } } } } if (output.length == 6) { char = 'Z' if (deduction[1] != null) { if (output.toCharArray().toList().containsAll(deduction[1]!!)) { char = '0' } else { char = '6' } } if (deduction[4] != null) { if (output.toCharArray().toList().containsAll(deduction[4]!!)) { char = '9' } } } char }.joinToString("") } println(resultsString.map { it.toInt() }.sum()) } data class InputLine( val signalPattern: List<String>, val outputValue: List<String>, ) }
0
Kotlin
0
0
5f1aff1887ad0a7e5a3af9aca7793f1c719e7f1c
3,626
adventofcode-2021
Apache License 2.0
src/Day01.kt
NunoPontes
572,963,410
false
{"Kotlin": 7416}
fun main() { fun calculateList(input: List<String>): MutableList<Int> { val mutableListCalories = mutableListOf<Int>() mutableListCalories.add(0) input.forEach { calorie -> if (calorie.isNotBlank()) { mutableListCalories[mutableListCalories.lastIndex] = mutableListCalories[mutableListCalories.lastIndex] + calorie.toInt() } else { mutableListCalories.add(0) } } return mutableListCalories } fun part1(input: List<String>): Int { val mutableListCalories = calculateList(input) return mutableListCalories.max() } fun part2(input: List<String>): Int { val mutableListCalories = calculateList(input) return mutableListCalories.sorted().takeLast(3).sum() } val inputPart1 = readInput("Day01_part1") val inputPart2 = readInput("Day01_part2") println(part1(inputPart1)) println(part2(inputPart2)) }
0
Kotlin
0
0
78b67b952e0bb51acf952a7b4b056040bab8b05f
996
advent-of-code-2022
Apache License 2.0
app/src/main/kotlin/com/resurtm/aoc2023/day19/Part1.kt
resurtm
726,078,755
false
{"Kotlin": 119665}
package com.resurtm.aoc2023.day19 internal fun solvePart1(input: Input): Long = input.workflows.fold(0L) { acc, it -> acc + traverseWorkflow(it, input.rules) } private fun traverseWorkflow(workflow: Workflow, rules: Map<String, Rule>): Long { var curr = "in" while (curr !in arrayOf("A", "R")) { val rule = rules[curr] ?: throw Exception("A rule does not exist") conditions@ for (condition in rule.conditions) { when (condition) { is Condition.Full -> { val val0 = workflow.entries[condition.token] ?: throw Exception("An entry value does not exist") val val1 = condition.compVal when (condition.compOp) { CompOp.Less -> if (val0 < val1) { curr = condition.nextRule break@conditions } CompOp.Greater -> if (val0 > val1) { curr = condition.nextRule break@conditions } } } is Condition.Short -> { curr = condition.nextRule break@conditions } } } } return if (curr == "A") workflow.findSum() else 0 }
0
Kotlin
0
0
fb8da6c246b0e2ffadb046401502f945a82cfed9
1,366
advent-of-code-2023
MIT License
Kotlin/src/SearchA2DMatrix.kt
TonnyL
106,459,115
false
null
/** * Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: * * Integers in each row are sorted from left to right. * The first integer of each row is greater than the last integer of the previous row. * For example, * * Consider the following matrix: * * [ * [1, 3, 5, 7], * [10, 11, 16, 20], * [23, 30, 34, 50] * ] * Given target = 3, return true. * * Accepted. */ class SearchA2DMatrix { fun searchMatrix(matrix: Array<IntArray>, target: Int): Boolean { if (matrix.isEmpty() || matrix[0].isEmpty()) { return false } for (i in 0 until matrix.size - 1) { if (matrix[i][0] == target || matrix[i + 1][0] == target) { return true } else if (matrix[i][0] < target && matrix[i + 1][0] > target) { return matrix[i].binarySearch(target) >= 0 } } return matrix[matrix.size - 1].binarySearch(target) >= 0 } }
1
Swift
22
189
39f85cdedaaf5b85f7ce842ecef975301fc974cf
1,016
Windary
MIT License
src/main/kotlin/oct_challenge2021/Trie.kt
yvelianyk
405,919,452
false
{"Kotlin": 147854, "Java": 610}
package oct_challenge2021 fun main() { val trie = Trie() trie.insert("apple") val res1 = trie.search("apple") assert(res1) val res2 = trie.search("app") assert(!res2) val res3 = trie.startsWith("app") assert(res3) trie.insert("app") val res4 = trie.search("app") assert(res4) } class Trie { private val root: TrieNode? = TrieNode() fun insert(word: String) { var node = root for (currChar in word) { if (!node!!.containsKey(currChar)) { node.put(currChar, TrieNode()) } node = node.get(currChar) } node!!.isEnd = true } fun search(word: String): Boolean { val node = searchPrefix(word) return node != null && node.isEnd } fun startsWith(prefix: String): Boolean { val node = searchPrefix(prefix) return node != null } private fun searchPrefix(word: String): TrieNode? { var node = root for (currChar in word) { if (node!!.containsKey(currChar)) { node = node.get(currChar) } else { return null } } return node } } private class TrieNode { private val numberOfAlphabet = 26 private var links: Array<TrieNode?> = arrayOfNulls(numberOfAlphabet) var isEnd = false fun containsKey(char: Char): Boolean { return links[char - 'a'] != null } fun get(char: Char): TrieNode? { return links[char - 'a'] } fun put(char: Char, node: TrieNode) { links[char - 'a'] = node } }
0
Kotlin
0
0
780d6597d0f29154b3c2fb7850a8b1b8c7ee4bcd
1,629
leetcode-kotlin
MIT License
src/main/kotlin/org/mechdancer/geometry/transformation/Quaternion.kt
MechDancer
128,765,281
false
null
package org.mechdancer.geometry.transformation import org.mechdancer.algebra.doubleEquals import org.mechdancer.algebra.hash import org.mechdancer.algebra.implement.vector.vector3D import kotlin.math.sqrt /** 四元数 */ data class Quaternion( val a: Double, val b: Double, val c: Double, val d: Double ) { /** 实部 */ val r get() = a /** 虚部 */ val v get() = vector3D(b, c, d) /** 平方模长 */ val square by lazy { a * a + b * b + c * c + d * d } /** 模长 */ val length by lazy { sqrt(square) } /** 共轭 */ val conjugate get() = Quaternion(a, -b, -c, -d) /** 求逆 */ val inverse get() = conjugate / square operator fun unaryMinus() = Quaternion(-a, -b, -c, -d) operator fun plus(others: Quaternion) = Quaternion(a + others.a, b + others.b, c + others.c, d + others.d) operator fun minus(others: Quaternion) = Quaternion(a - others.a, b - others.b, c - others.c, d - others.d) operator fun times(k: Double) = Quaternion(a * k, b * k, c * k, d * k) operator fun div(k: Double) = Quaternion(a / k, b / k, c / k, d / k) operator fun times(others: Quaternion): Quaternion { val (e, f, g, h) = others return Quaternion( a * e - b * f - c * g - d * h, b * e + a * f - d * g + c * h, c * e + d * f + a * g - b * h, d * e - c * f + b * g + a * h) } override fun equals(other: Any?) = this === other || (other is Quaternion && doubleEquals(a, other.a) && doubleEquals(b, other.b) && doubleEquals(c, other.c) && doubleEquals(d, other.d)) override fun hashCode() = hash(a, b, c, d) }
1
Kotlin
1
6
2cbc7e60b3cd32f46a599878387857f738abda46
1,893
linearalgebra
Do What The F*ck You Want To Public License
src/main/io/uuddlrlrba/ktalgs/sorts/MergeSort.kt
bmaslakov
83,349,679
false
null
/* * Copyright (c) 2017 Kotlin Algorithm Club * * 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 io.uuddlrlrba.ktalgs.sorts /** * Invented in 1945 by <NAME>, merge sort is an efficient algorithm using the divide and conquer approach * which is to divide a big problem into smaller problems and solve them. Conceptually, a merge sort works as follows: * 1) Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element is considered sorted). * 2) Repeatedly merge sublists to produce new sorted sublists until there is only 1 sublist remaining. */ @ComparisonSort @StableSort class MergeSort: AbstractSortStrategy() { override fun <T : Comparable<T>> perform(arr: Array<T>) { val aux = arr.clone() sort(arr, aux, 0, arr.size - 1) } private fun <T : Comparable<T>> sort(arr: Array<T>, aux: Array<T>, lo: Int, hi: Int) { if (hi <= lo) return val mid = (lo + hi) / 2 sort(arr, aux, lo, mid) sort(arr, aux, mid + 1, hi) merge(arr, aux, lo, mid, hi) } private fun <T : Comparable<T>> merge(arr: Array<T>, aux: Array<T>, lo: Int, mid: Int, hi: Int) { System.arraycopy(arr, lo, aux, lo, hi - lo + 1) var i = lo var j = mid + 1 for (k in lo..hi) { when { i > mid -> arr[k] = aux[j++] j > hi -> arr[k] = aux[i++] aux[j] < aux[i] -> arr[k] = aux[j++] else -> arr[k] = aux[i++] } } } }
4
Kotlin
144
883
a8fa9edf615d0498bd1d2e8328f72a180d345343
2,566
kotlin-algorithm-club
MIT License
src/Day10.kt
ech0matrix
572,692,409
false
{"Kotlin": 116274}
import kotlin.math.abs fun main() { fun part1(input: List<String>): Int { var x = 1 var cycle = 0 val calcCycle = setOf(20, 60, 100, 140, 180, 220) var signal = 0 for(line in input) { cycle++ val split = line.split(' ') val command = split[0] if (calcCycle.contains(cycle)) { signal += cycle * x } if(command != "noop") { cycle++ if (calcCycle.contains(cycle)) { signal += cycle * x } x += split[1].toInt() } } return signal } fun part2(input: List<String>) { var x = 1 var cycle = 0 for(line in input) { cycle++ val split = line.split(' ') val command = split[0] // During if (cycle%40-1 == x || cycle%40-1 == x-1 || cycle%40-1 == x+1) { print("#") } else { print(".") } if (cycle%40==0) { println() } if(command != "noop") { cycle++ // During if (cycle%40-1 == x || cycle%40-1 == x-1 || cycle%40-1 == x+1) { print("#") } else { print(".") } if (cycle%40==0) { println() } x += split[1].toInt() } } } val testInput = readInput("Day10_test") check(part1(testInput) == 13140) println() part2(testInput) println() println() val input = readInput("Day10") println(part1(input)) part2(input) }
0
Kotlin
0
0
50885e12813002be09fb6186ecdaa3cc83b6a5ea
1,800
aoc2022
Apache License 2.0
src/test/kotlin/de/tek/adventofcode/y2022/day14/RegolithReservoirTest.kt
Thumas
576,671,911
false
{"Kotlin": 192328}
package de.tek.adventofcode.y2022.day14 import de.tek.adventofcode.y2022.util.math.Point import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe class CaveTest : StringSpec({ val rockPositionsFromExample = listOf( 498 to 4, 498 to 5, 498 to 6, 497 to 6, 496 to 6, 503 to 4, 502 to 4, 502 to 5, 502 to 6, 502 to 7, 502 to 8, 502 to 9, 501 to 9, 500 to 9, 499 to 9, 498 to 9, 497 to 9, 496 to 9, 495 to 9, 494 to 9 ).map(::Point).toSet() "Given the example, toString returns the expected visualization." { val cave = Cave(Point(500, 0), rockPositionsFromExample) val expectedVisualization = """......+... |.......... |.......... |.......... |....#...## |....#...#. |..###...#. |........#. |........#. |#########. """.trimMargin() cave.toString() shouldBe expectedVisualization } "Given rock below the sand source, the simulation counts 0 sand units." { val cave = Cave(Point(500, 0), setOf(Point(500, 1))) cave.runSimulation() shouldBe 0 } "Given rock 2 cells below the sand source, the simulation counts 1 sand units." { val cave = Cave(Point(500, 0), setOf(Point(500, 2))) cave.runSimulation() shouldBe 0 } /* + ##### --> o ooo ##### */ "Given a line of rock with width 5 and 2 cells below the sand source, the simulation counts 4 sand units." { val rockPositions = listOf(498 to 2, 499 to 2, 500 to 2, 501 to 2, 502 to 2).map(::Point).toSet() val cave = Cave(Point(500, 0), rockPositions) cave.runSimulation() shouldBe 4 } /* + ##### --> + o ooo ##### */ "Given a line of rock with width 5 and 3 cells below the sand source, the simulation counts 4 sand units." { val rockPositions = listOf(498 to 3, 499 to 3, 500 to 3, 501 to 3, 502 to 3).map(::Point).toSet() val cave = Cave(Point(500, 0), rockPositions) cave.runSimulation() shouldBe 4 } /* + ##### --> + o ooo ##### */ "Given a line of rock with width 5 and 4 cells below the sand source, the simulation counts 4 sand units." { val rockPositions = listOf(498 to 4, 499 to 4, 500 to 4, 501 to 4, 502 to 4).map(::Point).toSet() val cave = Cave(Point(500, 0), rockPositions) cave.runSimulation() shouldBe 4 } "Given the example, the simulation counts 24 sand units." { val cave = Cave(Point(500,0), rockPositionsFromExample) cave.runSimulation() shouldBe 24 } }) class RegolithReservoirTest : StringSpec({ val input = """498,4 -> 498,6 -> 496,6 503,4 -> 502,4 -> 502,9 -> 494,9""".split("\n") "Given the example, the result of the first analysis is 24." { part1(input) shouldBe 24 } "Given the example, the result of the second analysis is 93" { part2(input) shouldBe 93 } })
0
Kotlin
0
0
551069a21a45690c80c8d96bce3bb095b5982bf0
3,318
advent-of-code-2022
Apache License 2.0
foundations/binary-search/BinarySearch.kt
ivan-magda
102,283,964
false
null
import java.util.* fun binarySearchRecursively(array: Array<Int>, target: Int): Int { if (array.isEmpty()) { return -1 } return binarySearchRecursively(array, target, 0, array.size - 1) } private fun binarySearchRecursively(array: Array<Int>, target: Int, start: Int, end: Int): Int { if (start > end) { return -1 } val middle = start + (end - start) / 2 val currentValue = array[middle] return when { target == currentValue -> middle target > currentValue -> binarySearchRecursively(array, target, middle + 1, end) else -> binarySearchRecursively(array, target, start, middle - 1) } } fun binarySearchIterative(array: Array<Int>, target: Int): Int { var start = 0 var end = array.size - 1 while (start <= end) { val middle = start + (end - start) / 2 val currentValue = array[middle] when { target == currentValue -> return middle target > currentValue -> start = middle + 1 else -> end = middle - 1 } } return -1 } fun main(args: Array<String>) { val array = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9) println("Target array: ${Arrays.toString(array)}") println("Index of 3 is ${binarySearchIterative(array, 3)}, {iterative}") println("Index of 3 is ${binarySearchRecursively(array, 3)}, {recursively}") }
0
Kotlin
0
2
da06ec75cbd06c8e158aec86ca813e72bd22a2dc
1,390
introduction-algorithms
MIT License
codeforces/deltix2021summer/d.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.deltix2021summer fun ask(or: Boolean, i: Int, j: Int): Int { val s = if (or) "or" else "and" println("$s ${i + 1} ${j + 1}") return readInt() } fun main() { val (n, k) = readInts() val (ands, ors) = List(2) { or -> List(n - 1) { ask(or == 1, 0, it + 1) } } val and12 = ask(false, 1, 2) val a = IntArray(n) for (b in 0..29) { val t = 1 shl b val maybe0 = ands.all { (it and t) == 0 } val maybe1 = ors.all { (it and t) == t } val v = if (maybe1 && (!maybe0 || and12 and t == 0)) 1 else 0 a[0] = a[0] or (v * t) for (i in 1 until n) { val u = ((if (v == 1) ands[i - 1] else ors[i - 1]) shr b) and 1 a[i] = a[i] or (u * t) } } a.sort() println("finish ${a[k - 1]}") } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
900
competitions
The Unlicense
com/ztoais/dailycoding/algoexpert/easy/TwoNumberSum.kt
RanjithRagavan
479,563,314
false
{"Kotlin": 7371}
package com.ztoais.dailycoding.algoexpert.easy /* Two Number Sum Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum. If any two numbers in the input array sum up to the target sum, the function should return then in an array. in any order. if no two numbers sum up the target sum, the function should return an empty array. Note that the target sum has to be obtained by summing two different integers in the array: you can't add a single integer to itself in order to obtain the target sum. You can assume that there will be at most one pair of numbers summing up to the target sum. */ //Sample input /* { "array": [3, 5, -4, 8, 11, 1, -1, 6], "targetSum": 10 } //Sample output [-1,11] */ fun twoNumberSum(array: MutableList<Int>,targetSum:Int):List<Int>{ val initialValue = array[0] val newArray = mutableListOf<Int>() array.drop(1).forEach{nextValue -> if(initialValue+nextValue == targetSum){ return listOf(initialValue,nextValue) }else{ newArray.add(nextValue) } } if(newArray.size >1){ return twoNumberSum(newArray,targetSum) } return listOf() } /* //Test cases Test Case 1 { "array": [3, 5, -4, 8, 11, 1, -1, 6], "targetSum": 10 } Test Case 2 { "array": [4, 6], "targetSum": 10 } Test Case 3 { "array": [4, 6, 1], "targetSum": 5 } Test Case 4 { "array": [4, 6, 1, -3], "targetSum": 3 } Test Case 5 { "array": [1, 2, 3, 4, 5, 6, 7, 8, 9], "targetSum": 17 } Test Case 6 { "array": [1, 2, 3, 4, 5, 6, 7, 8, 9, 15], "targetSum": 18 } Test Case 7 { "array": [-7, -5, -3, -1, 0, 1, 3, 5, 7], "targetSum": -5 } Test Case 8 { "array": [-21, 301, 12, 4, 65, 56, 210, 356, 9, -47], "targetSum": 163 } Test Case 9 { "array": [-21, 301, 12, 4, 65, 56, 210, 356, 9, -47], "targetSum": 164 } Test Case 10 { "array": [3, 5, -4, 8, 11, 1, -1, 6], "targetSum": 15 } Test Case 11 { "array": [14], "targetSum": 15 } Test Case 12 { "array": [15], "targetSum": 15 } */
0
Kotlin
0
0
a5f29dd82c0c50fc7d2490fd1be6234cdb4d1d8a
2,066
daily-coding
MIT License
src/main/kotlin/OpenRange.kt
snarks
165,013,289
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 io.github.snarks.openrange /** * Represents an open-ended range of values * * [isDownward] determines whether this range opens downwards or upwards. [isInclusive] determines if [value] is * considered to belong to this range. * * ### Examples * * _Downward Inclusive:_ * ```kotlin * val range = lessOrEqual(512) * * assertTrue(0 in range) * assertTrue(512 in range) * assertFalse(1024 in range) * * assertEquals("<=512", "$range") * ``` * * _Downward Exclusive:_ * ```kotlin * val range = lessThan(512) * * assertTrue(0 in range) * assertFalse(512 in range) * assertFalse(1024 in range) * * assertEquals("<512", "$range") * ``` * * _Upward Inclusive:_ * ```kotlin * val range = moreOrEqual(512) * * assertFalse(0 in range) * assertTrue(512 in range) * assertTrue(1024 in range) * * assertEquals(">=512", "$range") * ``` * * _Upward Exclusive:_ * ```kotlin * val range = moreThan(512) * * assertFalse(0 in range) * assertFalse(512 in range) * assertTrue(1024 in range) * * assertEquals(">512", "$range") * ``` * * @see lessOrEqual * @see lessThan * @see moreOrEqual * @see moreThan */ data class OpenRange<T : Comparable<T>>(val value: T, val isDownward: Boolean, val isInclusive: Boolean) { /** * Checks whether the specified [value] belongs to the range */ operator fun contains(value: T): Boolean { val compare = this.value.compareTo(value) return when { compare < 0 -> !isDownward compare > 0 -> isDownward else -> isInclusive } } /** * Returns the string representation of this range * * Examples: * - `lessOrEqual(512)` = `<=512` * - `lessThan(512)` = `<512` * - `moreOrEqual(512)` = `>=512` * - `moreThan(512)` = `>512` */ override fun toString(): String { val pre1 = if (isDownward) '<' else '>' val pre2 = if (isInclusive) "=" else "" return pre1 + pre2 + value } } /** Returns a range that covers values from [maxInclusive] and lower (downward inclusive) */ fun <T : Comparable<T>> lessOrEqual(maxInclusive: T): OpenRange<T> = OpenRange(maxInclusive, true, true) /** Returns a range that covers values lower than [maxExclusive] (downward exclusive) */ fun <T : Comparable<T>> lessThan(maxExclusive: T): OpenRange<T> = OpenRange(maxExclusive, true, false) /** Returns a range that covers values from [minInclusive] and higher (upward inclusive) */ fun <T : Comparable<T>> moreOrEqual(minInclusive: T): OpenRange<T> = OpenRange(minInclusive, false, true) /** Returns a range that covers values higher than [minExclusive] (upward exclusive) */ fun <T : Comparable<T>> moreThan(minExclusive: T): OpenRange<T> = OpenRange(minExclusive, false, false)
0
Kotlin
0
0
96d114ebe93782a6824451b7178f5b49313a71a0
3,267
OpenRange
Apache License 2.0
src/main/kotlin/me/peckb/aoc/_2020/calendar/day16/Day16.kt
peckb1
433,943,215
false
{"Kotlin": 956135}
package me.peckb.aoc._2020.calendar.day16 import javax.inject.Inject import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory class Day16 @Inject constructor( private val generatorFactory: InputGeneratorFactory, ) { data class Field(val name: String, val lowerRange: IntRange, val upperRange: IntRange) fun partOne(filename: String) = generatorFactory.forFile(filename).read { input -> val (fields, _, otherTicketData) = setup(input) val ticketScanningErrors = otherTicketData.mapNotNull { ticketData -> val invalidTicketValues = ticketData.filterNot { ticketValue -> fields.any { (_, lowerRange, upperRange) -> lowerRange.contains(ticketValue) || upperRange.contains(ticketValue) } } if (invalidTicketValues.isNotEmpty()) { invalidTicketValues.sum() } else { null } } ticketScanningErrors.sum() } fun partTwo(filename: String) = generatorFactory.forFile(filename).read { input -> val (fields, myTicketData, otherTicketData) = setup(input) // first filter out all the bad tickets val validTickets = otherTicketData .filter { ticketValues -> val invalidTicketValues = ticketValues.filterNot { ticketValue -> fields.any { (_, lowerRange, upperRange) -> lowerRange.contains(ticketValue) || upperRange.contains(ticketValue) } } invalidTicketValues.isEmpty() } // then find out which index of our ticket scan can match to which fields val fieldIndexMap = mutableMapOf<Int, List<Field>>() fields.indices.forEach { ticketNumberIndex -> var possibleFields = fields.toList() validTickets.forEach { ticketData -> val ticketItemWeCareAbout = ticketData[ticketNumberIndex] possibleFields = possibleFields.filter { it.lowerRange.contains(ticketItemWeCareAbout) || it.upperRange.contains(ticketItemWeCareAbout) } } fieldIndexMap[ticketNumberIndex] = possibleFields } // now that we have all possible fields for each index, let's grab them one by one // and know the actual index in our scan for each field val foundFieldIndicesMap = mutableMapOf<Field, Int>() fieldIndexMap.entries.sortedBy { it.value.size } .forEach { (index, possibleFields) -> val onlyPossibility = possibleFields.filterNot { foundFieldIndicesMap.contains(it) }.first() foundFieldIndicesMap[onlyPossibility] = index } // and for the answer to the data we get the departure fields and find their product foundFieldIndicesMap .filter { it.key.name.contains("departure") } .map { myTicketData[it.value] } .fold(1L) { acc, ticketValue -> acc * ticketValue} } private fun setup(input: Sequence<String>): Triple<List<Field>, List<Int>, List<List<Int>>> { val data = input.toList() val fields = data.takeWhile { it.isNotBlank() } .map { it -> val name = it.substringBefore(':') val parts = it.substringAfter(":").split(" ") val (lowerLowerRange, lowerUpperRange) = parts[1].split("-").map{ it.toInt() } val (upperLowerRange, upperUpperRange) = parts[3].split("-").map{ it.toInt() } Field(name, lowerLowerRange..lowerUpperRange, upperLowerRange .. upperUpperRange) } val myTicketData = data.asSequence().drop(fields.size + 1) .takeWhile { it.isNotBlank() } .drop(1) .map { it.split(",").map { ticketValue -> ticketValue.toInt() } } .first() val otherTicketData = data.drop(fields.size + 4) .takeWhile { it.isNotBlank() } .drop(1) .map { it.split(",").map { ticketValue -> ticketValue.toInt() } } return Triple(fields, myTicketData, otherTicketData) } }
0
Kotlin
1
3
2625719b657eb22c83af95abfb25eb275dbfee6a
3,757
advent-of-code
MIT License
kotlin/src/main/kotlin/com/tolchev/algo/matrix/1559DetectCycles2DFast.kt
VTolchev
692,559,009
false
{"Kotlin": 53858, "C#": 47939, "Java": 1802}
package com.tolchev.algo.matrix class DetectCycles2DFast { fun containsCycle(grid: Array<CharArray>): Boolean { val possibleSteps = arrayOf (-1 to 0, 1 to 0, 0 to-1, 0 to 1) var visited = Array(grid.size){ BooleanArray(grid[0].size){false} } val maxRow = grid.size val maxCol = grid[0].size fun hasCycle(from: Pair<Int, Int>, current: Pair<Int, Int>, currentChar : Char, visited : Array<BooleanArray>): Boolean { visited[current.first][current.second] = true; for (step in possibleSteps) { var row = current.first + step.first var col = current.second + step.second val target = Pair(row, col) if (from.first == row && from.second == col) continue if (row in 0..<maxRow && col in 0 ..<maxCol && grid[row][col] == currentChar){ if (visited[target.first][target.second]) return true if (hasCycle(current, target, currentChar, visited)) return true } } return false } for (row in grid.indices) for(col in grid[0].indices) { val point = Pair(row, col) if(!visited[row][col]){ if (hasCycle(point, point, grid[row][col], visited)) return true } } return false } }
0
Kotlin
0
0
c3129f23e4e7ba42b44f9fb4af39a95f4a762550
1,471
algo
MIT License
src/main/kotlin/io/github/clechasseur/adventofcode/y2015/Day24.kt
clechasseur
568,233,589
false
{"Kotlin": 242914}
package io.github.clechasseur.adventofcode.y2015 import io.github.clechasseur.adventofcode.y2015.data.Day24Data object Day24 { private val input = Day24Data.input fun part1(): Long = minQuantumEntanglement(input.sum() / 3L) fun part2(): Long = minQuantumEntanglement(input.sum() / 4L) private fun minQuantumEntanglement(neededWeight: Long): Long = (2..input.size).asSequence().flatMap { size -> subPermutations(size).filter { it.weight == neededWeight }.sortedBy { it.quantumEntanglement } }.first().quantumEntanglement private fun subPermutations(size: Int, soFar: List<Long> = emptyList()): Sequence<List<Long>> = if (size == 0) { sequenceOf(soFar) } else { input.asSequence().filter { !soFar.contains(it) }.flatMap { element -> subPermutations(size - 1, soFar + element) } } private val List<Long>.weight: Long get() = sum() private val List<Long>.quantumEntanglement: Long get() = reduceOrNull { acc, l -> acc * l } ?: 0L }
0
Kotlin
0
0
e5a83093156cd7cd4afa41c93967a5181fd6ab80
1,076
adventofcode2015
MIT License
aoc2022/day3.kt
davidfpc
726,214,677
false
{"Kotlin": 127212}
package aoc2022 import utils.InputRetrieval fun main() { Day3.execute() } object Day3 { fun execute() { val input = readInput() println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") } private val PRIORITIES = ('a'..'z').plus('A'..'Z') private fun part1(input: List<String>): Int = input.map { it.toList() }.sumOf { rucksack -> rucksack.chunked(rucksack.size / 2).reduce { acc, items -> acc.intersect(items.toSet()).toList() }.calculatePriorities() } private fun part2(input: List<String>): Int { return input.map { it.toSet() }.chunked(3).sumOf { it.reduce { acc, rucksack -> acc.intersect(rucksack) }.calculatePriorities() } } private fun Iterable<Char>.calculatePriorities(): Int = this.sumOf { badge -> PRIORITIES.indexOf(badge) + 1 } private fun readInput(): List<String> = InputRetrieval.getFile(2022, 3).readLines() }
0
Kotlin
0
0
8dacf809ab3f6d06ed73117fde96c81b6d81464b
948
Advent-Of-Code
MIT License
src/commonMain/kotlin/com/jeffpdavidson/kotwords/model/Coded.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 com.jeffpdavidson.kotwords.util.trimmedLines data class Coded( val title: String, val creator: String, val copyright: String, val description: String, val grid: List<List<Char?>>, val assignments: List<Char>, val givens: List<Char>, ) : Puzzleable() { init { val gridLetters = grid.flatMap { it.filterNotNull() }.distinct().toSet() require(gridLetters == assignments.toSet()) { "Set of characters in the grid does not match the set of characters in the assignments" } } override suspend fun createPuzzle(): Puzzle { val assignmentMap = assignments.mapIndexed { i, ch -> ch to (i + 1) }.toMap() val puzzleGrid = grid.map { row -> row.map { ch -> if (ch == null) { Puzzle.Cell(cellType = Puzzle.CellType.BLOCK) } else { val given = givens.contains(ch) Puzzle.Cell( solution = "$ch", number = "${assignmentMap[ch]}", hint = given, entry = if (given) "$ch" else "", ) } } } val words = mutableListOf<Puzzle.Word>() var acrossWordNumber = 1 var downWordNumber = 1 Crossword.forEachCell(puzzleGrid) { x, y, _, isAcross, isDown, _ -> if (isAcross) { val word = mutableListOf<Puzzle.Coordinate>() var i = x while (i < puzzleGrid[y].size && !puzzleGrid[y][i].cellType.isBlack()) { word.add(Puzzle.Coordinate(x = i, y = y)) i++ } words.add(Puzzle.Word(acrossWordNumber++, word)) } if (isDown) { val word = mutableListOf<Puzzle.Coordinate>() var j = y while (j < puzzleGrid.size && !puzzleGrid[j][x].cellType.isBlack()) { word.add(Puzzle.Coordinate(x = x, y = j)) j++ } words.add(Puzzle.Word(1000 + downWordNumber++, word)) } } return Puzzle( title = title, creator = creator, copyright = copyright, description = description, puzzleType = Puzzle.PuzzleType.CODED, grid = puzzleGrid, clues = listOf(), words = words.sortedBy { it.id } ) } companion object { fun fromRawInput( title: String, creator: String, copyright: String, description: String, grid: String, assignments: String, givens: String, ): Coded { val gridChars = grid.uppercase().trimmedLines().map { line -> line.map { ch -> if (ch == '.') null else ch } } val assignmentList = if (assignments.isBlank()) { generateAssignments(gridChars) } else { assignments.uppercase().toList() } return Coded( title = title, creator = creator, copyright = copyright, description = description, grid = gridChars, assignments = assignmentList, givens = givens.toList(), ) } fun generateAssignments(grid: List<List<Char?>>): List<Char> = grid.flatMap { it.filterNotNull() }.distinct().shuffled() } }
5
Kotlin
5
19
c2dc23bafc7236ba076a63060e08e6dc134c8e24
3,747
kotwords
Apache License 2.0
src/main/kotlin/ctci/chaptereight/Coins.kt
amykv
538,632,477
false
{"Kotlin": 169929}
package ctci.chaptereight // 8.11 - page 136 // Given an infinite number of quarters (25 cents), dimes (10 cents), nickels (5 cents), and pennies (1 cent), write // Kotlin code to calculate the number of ways representing n cents. fun main() { val cents = 50 println("Number of ways to represent $cents cents: ${coinChange(cents)}") } //The function takes in a single parameter cents, which represents the total amount of cents we want to calculate the // number of ways to represent. // //The function starts by defining an array coinDenominations that holds the coin denominations, in this case, quarters, // dimes, nickels, and pennies. Then create an array ways of size cents + 1 with all elements initialized to 0. Set // the first element of the array to 1, which is the base case representing the number of ways to represent 0 cents, // which is 1. // //Then iterate over each denomination in coinDenominations and for each denomination it starts a nested loop that // iterates from the current denomination to the total number of cents. For each iteration, update the value in the // ways array by adding the number of ways to represent the current amount minus the current denomination. // //The function then returns the last element of the ways array, which represents the number of ways to represent the // total number of cents. fun coinChange(cents: Int): Int { val coinDenominations = intArrayOf(25, 10, 5, 1) val ways = Array(cents + 1) { 0 } ways[0] = 1 // base case: there's 1 way to represent 0 cents for (denomination in coinDenominations) { for (i in denomination..cents) { ways[i] += ways[i - denomination] } } return ways[cents] } //The time and space complexity of this solution is O(n*c) where n is the number of coin denominations and c is the // number of cents. This is because it iterates over all the coin denominations and for each denomination, iterate over // all the cents.
0
Kotlin
0
2
93365cddc95a2f5c8f2c136e5c18b438b38d915f
1,973
dsa-kotlin
MIT License
src/main/kotlin/day03/Day3.kt
limelier
725,979,709
false
{"Kotlin": 48112}
package day03 import common.InputReader private typealias PartPos = Pair<Int, Int> public fun main() { val matrix = InputReader("day03/input.txt").lines().map { it.toCharArray() } // establish bounds val rowIndices = matrix.indices val colIndices = matrix[0].indices var partNumberSum = 0 var gearRatioSum = 0 val unmatchedGearNumbers: MutableMap<PartPos, Int> = mutableMapOf() for (r in rowIndices) { val row = matrix[r] var c = 0 while (c in colIndices) { val ch = row[c] if (!ch.isDigit()) { c++ continue } // consume number var cPastNumEnd = c + 1 var numString = ch.toString() while (cPastNumEnd in colIndices && row[cPastNumEnd].isDigit()) { numString += row[cPastNumEnd] cPastNumEnd++ } val number = numString.toInt() // scan for symbol in bounding box val scanRows = rowIndices.intersect(r-1..r+1) val scanCols = colIndices.intersect(c-1..cPastNumEnd) var hasSymbol = false symbolScan@ for (rScan in scanRows) { for (cScan in scanCols) { val chScan = matrix[rScan][cScan] if (chScan == '.' || chScan.isDigit()) { continue } // part 2 segment: handle possible gear numbers if (chScan == '*') { val key = PartPos(rScan, cScan) if (key in unmatchedGearNumbers) { gearRatioSum += unmatchedGearNumbers[key]!! * number unmatchedGearNumbers.remove(key) } else { unmatchedGearNumbers[key] = number } } hasSymbol = true break@symbolScan } } c = cPastNumEnd + 1 if (hasSymbol) { partNumberSum += number } } } println("Part 1: $partNumberSum") println("Part 2: $gearRatioSum") }
0
Kotlin
0
0
0edcde7c96440b0a59e23ec25677f44ae2cfd20c
2,258
advent-of-code-2023-kotlin
MIT License
app/jvmApp/src/main/java/ru/snowmaze/barstats/GetPlayerStatisticsResultMapper.kt
Snowmaze-dev
739,169,546
false
{"Kotlin": 99000}
package ru.snowmaze.barstats import ru.snowmaze.barstats.models.GetStatisticsResult import ru.snowmaze.barstats.models.PlayerData import ru.snowmaze.barstats.models.PlayerStats import ru.snowmaze.barstats.models.WithPlayerStat import java.util.concurrent.TimeUnit fun GetStatisticsResult.mapToSection(splitter: String): Section { val stats = this.playerData val mapPlayedWith: List<WithPlayerStat>.(isEnemies: Boolean) -> List<SectionValue> = { isEnemies -> mapIndexed { index, withStats -> SectionValue.StringSectionValue( mapStats( index = index, playerName = withStats.withPlayerName, playerData = withStats.playerData, playerStats = withStats.playerStats, isEnemies = isEnemies, splitter = splitter ) ) } } return Section( name = "Player ${stats.playerName} stat", values = buildList<Pair<String, Any?>> { addAll( listOf( "Total matches count" to stats.totalMatchesCount, "Accounted matches count" to stats.accountedMatchesCount.takeIf { stats.totalMatchesCount != it }, "Won matches" to stats.wonMatchesCount, "Lost matches" to stats.lostMatchesCount, "Winrate" to stats.winrate.toString() + "%", "Average teammate skill" to stats.averageTeammateSkill, "Average ${stats.preset} enemy skill" to stats.averageEnemySkill, "Hours spent in analyzed games" to TimeUnit.MILLISECONDS.toHours(stats.overallPlayerPlaytimeMs), ) ) val unbalancedMatchesStats = unbalancedMatchesStats if (unbalancedMatchesStats != null) { addAll( listOf( "Unbalanced matches count" to unbalancedMatchesStats.unbalancedMatchesCount, "Won unbalanced matches in weaker team" to unbalancedMatchesStats.wonUnbalancedMatchesInWeakerTeam, "Lost unbalanced matches in weaker team" to unbalancedMatchesStats.lostUnbalancedMatchesInWeakerTeam, ) ) } }.map { SectionValue.KeyValueSectionValue(it.first, it.second) }, subSubsections = listOf( Section( name = "Maps stats", values = stats.mapsStats?.mapIndexed { index, mapStat -> SectionValue.StringSectionValue(buildString { append("${index + 1}. ", mapStat.mapName, splitter) append("Total matches count: ", mapStat.totalMatchesCount, splitter) append("Winrate: ${mapStat.winrate}%", splitter) append("Wins: ${mapStat.wins}", splitter) append("Loses: ${mapStat.loses}") }) } ), Section( "Best teammates", values = bestTeammates.mapPlayedWith(false), ), Section( "Lobster teammates", values = lobsterTeammates.mapPlayedWith(false) ), Section( "Best against", values = bestAgainst.mapPlayedWith(true) ), Section( "Best opponents", values = bestOpponents.mapPlayedWith(true) ) ) ) } fun mapStats( index: Int, playerName: String, playerData: PlayerData?, playerStats: PlayerStats, isEnemies: Boolean, splitter: String ) = buildString { append(index + 1, ". ", playerName, splitter) val totalGamesWithText = if (isEnemies) "Games against" else "Games together" append(totalGamesWithText, ": ", playerStats.totalGamesTogether, splitter) val withText = if (isEnemies) "against player" else "with teammate" append("Winrate ", withText, ": ", playerStats.winrate, "%", splitter) val winrate = playerData?.winrate if (winrate != null) append("Player overall winrate: ", winrate, "%", splitter) val winsWith = if (isEnemies) "against player" else "with teammate" append("Wins ", winsWith, ": ", if (isEnemies) playerStats.lostGames else playerStats.wonGames, splitter) val losesWith = if (isEnemies) "against player" else "with teammate" append("Loses ", losesWith, ": ", if (isEnemies) playerStats.wonGames else playerStats.lostGames) }
0
Kotlin
0
0
7e289b6bab307e635a9daab34afc24103c8a0636
4,601
BarStats
Apache License 2.0
advent-of-code-2020/src/test/java/aoc/Points.kt
yuriykulikov
159,951,728
false
{"Kotlin": 1666784, "Rust": 33275}
package aoc import kotlin.math.abs data class Point(val x: Int, val y: Int, val z: Int = 0, val w: Int = 0) { operator fun minus(other: Point) = Point(x - other.x, y - other.y, z - other.z, w - other.w) operator fun plus(other: Point) = Point(x + other.x, y + other.y, z + other.z, w + other.w) operator fun times(times: Int): Point = copy(x = x * times, y = y * times, z = z * times) } fun Point.left(inc: Int = 1) = copy(x = x - inc) fun Point.right(inc: Int = 1) = copy(x = x + inc) fun Point.up(inc: Int = 1) = copy(y = y - inc) fun Point.down(inc: Int = 1) = copy(y = y + inc) fun Point.manhattan(): Int = abs(x) + abs(y) + abs(z) fun Point.rotateCCW() = Point(x = -y, y = x) fun Point.rotateCW() = Point(x = y, y = -x) fun <T> printMap( tiles: Map<Point, T>, invertedY: Boolean = true, func: (T?) -> String = { "${it ?: " "}" } ) { val maxX = tiles.keys.map { it.x }.maxOrNull() ?: 0 val minX = tiles.keys.map { it.x }.minOrNull() ?: 0 val maxY = tiles.keys.map { it.y }.maxOrNull() ?: 0 val minY = tiles.keys.map { it.y }.minOrNull() ?: 0 val code = (minY..maxY) .run { if (invertedY) sorted() else sortedDescending() } .mapIndexed { index, y -> (minX..maxX).map { x -> tiles[Point(x, y)] } .joinToString(separator = "") { func(it) } } code.forEach { println(it) } } /** * Parses a string as a map * * Y is inverted (first line is y=0) */ fun parseMap(mapString: String): Map<Point, Char> { return mapString.lines() .mapIndexed { y, line -> line.mapIndexed { x, c -> Point(x, y) to c } } .flatten() .toMap() }
0
Kotlin
0
1
f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3
1,775
advent-of-code
MIT License
src/day02/Day02.kt
EdwinChang24
572,839,052
false
{"Kotlin": 20838}
package day02 import readInput fun main() { part1() part2() } fun part1() { val guide = readInput(2).map { it[0] to it[2] } var total = 0 for (strategy in guide) { total += when (strategy) { 'A' to 'X', 'B' to 'Y', 'C' to 'Z' -> 3 'A' to 'Y', 'B' to 'Z', 'C' to 'X' -> 6 else -> 0 } total += when (strategy.second) { 'X' -> 1 'Y' -> 2 'Z' -> 3 else -> 0 } } println(total) } fun part2() { val guide = readInput(2).map { it[0] to it[2] } var total = 0 for (strategy in guide) { total += when (strategy.second) { 'X' -> 0 'Y' -> 3 'Z' -> 6 else -> 0 } total += when (strategy) { 'B' to 'X', 'A' to 'Y', 'C' to 'Z' -> 1 'C' to 'X', 'B' to 'Y', 'A' to 'Z' -> 2 else -> 3 } } println(total) }
0
Kotlin
0
0
e9e187dff7f5aa342eb207dc2473610dd001add3
972
advent-of-code-2022
Apache License 2.0
src/week3/BuildTree.kt
anesabml
268,056,512
false
null
package week3 class BuildTree { /** Recursive * Preorder -> root, left, right * Inorder -> left, root, right * We get the root from the preorder traversal and the left / right from inorder traversal * We find the root index in inoder traversal array, we know that inorder traverses left before right * So : left = what is before root index * right : what is after root index */ fun buildTree(preorder: IntArray, inorder: IntArray): TreeNode? { return buildTreeRec(0, 0, inorder.size - 1, preorder, inorder) } private fun buildTreeRec( preStart: Int, inStart: Int, inEnd: Int, preorder: IntArray, inorder: IntArray ): TreeNode? { if (preStart >= preorder.size || inStart > inEnd) { return null } val root = TreeNode(preorder[preStart]) var inRoot = 0 for (i in inStart..inEnd) { if (root.`val` == inorder[i]) { inRoot = i } } root.left = buildTreeRec(preStart + 1, inStart, inRoot - 1, preorder, inorder) root.right = buildTreeRec(preStart + inRoot - inStart + 1, inRoot + 1, inEnd, preorder, inorder) return root } /** Recursive * Same as before but we ruduce the search time by using a hashmap */ fun buildTree2(preorder: IntArray, inorder: IntArray): TreeNode? { val inorderMap = hashMapOf<Int, Int>() inorder.forEachIndexed { index, i -> inorderMap[i] = index } return buildTreeRec(0, 0, inorder.size - 1, preorder, inorder, inorderMap) } private fun buildTreeRec( preStart: Int, inStart: Int, inEnd: Int, preorder: IntArray, inorder: IntArray, inorderMap: HashMap<Int, Int> ): TreeNode? { if (preStart >= preorder.size || inStart > inEnd) { return null } val root = TreeNode(preorder[preStart]) val inRoot = inorderMap[root.`val`]!! root.left = buildTreeRec(preStart + 1, inStart, inRoot - 1, preorder, inorder, inorderMap) root.right = buildTreeRec(preStart + inRoot - inStart + 1, inRoot + 1, inEnd, preorder, inorder, inorderMap) return root } }
0
Kotlin
0
1
a7734672f5fcbdb3321e2993e64227fb49ec73e8
2,269
leetCode
Apache License 2.0
AOC2022/src/main/kotlin/AOC8.kt
bsautner
575,496,785
false
{"Kotlin": 16189, "Assembly": 496}
import java.io.File class AOC8 { var maxScore = 0 fun process() { val input = File("/home/ben/aoc/input-8.txt") val sample = input.useLines { it.toList() } val matrix = sample.map { it.toCharArray() }.toTypedArray() var count = 0 matrix.mapIndexed { y, row -> row.mapIndexed { x, _ -> if (isVisible(x, y, matrix)) { count++ } scoreTree(x, y, matrix) } } println("Part 1 Answer: $count") println("Part 2 Answer: $maxScore") } private fun scoreTree(x: Int, y: Int, matrix: Array<CharArray>) : Int { if (x == 0 || x == matrix.size -1 || y == 0 || y == matrix.size -1) { return 0 } val a = matrix[y][x].digitToInt() val right = matrix[y].takeWhile { it.digitToInt() < a }.count() val left = matrix[y].reversed().takeWhile { it.digitToInt() < a }.count() val down = matrix.takeWhile { it[x].digitToInt() < a }.count() val up = matrix.reversed().takeWhile { it[x].digitToInt() < a }.count() val score = up * down * left * right if (score > maxScore) { maxScore = score } return score } private fun isVisible(x: Int, y: Int, matrix: Array<CharArray>) : Boolean { if (x == 0 || x == matrix.size -1 || y == 0 || y == matrix.size -1) { return true } val a = matrix[y][x].digitToInt() val right = matrix[y].takeWhile { it.digitToInt() < a }.count() val left = matrix[y].reversed().takeWhile { it.digitToInt() < a }.count() val down = matrix.takeWhile { it[x].digitToInt() < a }.count() val up = matrix.reversed().takeWhile { it[x].digitToInt() < a }.count() return right == 0 || left == 0 || down == 0 || up == 0 } }
0
Kotlin
0
0
5f53cb1c4214c960f693c4f6a2b432b983b9cb53
1,898
Advent-of-Code-2022
The Unlicense
src/main/kotlin/dev/bogwalk/batch2/Problem22.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch2 /** * Problem 22: Names Scores * * https://projecteuler.net/problem=22 * * Goal: Given an unsorted list of N names, first sort alphabetically, then, given 1 of the * names, multiply the sum of the value of all its characters by its position in the alphabetical * list. * * Constraints: 1 <= N <= 5200, len(NAME) < 12 * * e.g.: input = [ALEX, LUIS, JAMES, BRIAN, PAMELA] * sorted = [ALEX, BRIAN, JAMES, LUIS, PAMELA] * name = PAMELA = 16 + 1 + 13 + 5 + 12 + 1 = 48 * position = 5th * result = 5 * 48 = 240 */ class NamesScores { /** * Project Euler specific implementation that requires all the name scores of a 5000+ list * to be summed. */ fun sumOfNameScores(input: List<String>): Int { return input .sorted() .withIndex() .sumOf { (i, name) -> nameScore(i, name) } } /** * Helper function returns a score for a name as detailed in documentation above. * * @param [index] zero-indexed position found in calling function using * sortedList.indexOf("name"). * @param [name] String assumed to be in ALL_CAPS, but this could be ensured by including * name.uppercase() in the solution. */ fun nameScore(index: Int, name: String): Int { // unicode decimal value of 'A' is 65, but is normalised to represent value 1 return (index + 1) * name.sumOf { it.code - 64 } } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
1,467
project-euler-kotlin
MIT License
LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/SubstringWithConcatenationOfAllWords.kt
ani03sha
297,402,125
false
null
package org.redquark.tutorials.leetcode class SubstringWithConcatenationOfAllWords { fun findSubstring(s: String, words: Array<String>): List<Int> { // Resultant list val indices: MutableList<Int> = ArrayList() // Base conditions if (s.isEmpty() || words.isEmpty()) { return indices } // Store the words and their counts in a hash map val wordCount: MutableMap<String, Int> = HashMap() for (word in words) { wordCount[word] = wordCount.getOrDefault(word, 0) + 1 } // Length of each word in the words array val wordLength = words[0].length // Length of all the words combined in the array val wordArrayLength = wordLength * words.size // Loop for the entire string for (i in 0..s.length - wordArrayLength) { // Get the substring of length equal to wordArrayLength val current = s.substring(i, i + wordArrayLength) // Map to store each word of the substring val wordMap: MutableMap<String, Int> = HashMap() // Index to loop through the words array var index = 0 // Index to get each word in the current var j = 0 // Loop through each word of the words array while (index < words.size) { // Divide the current string into strings of length of // each word in the array val part = current.substring(j, j + wordLength) // Put this string into the wordMap wordMap[part] = wordMap.getOrDefault(part, 0) + 1 // Update j and index j += wordLength index++ } // At this point compare the maps if (wordCount == wordMap) { indices.add(i) } } return indices } } fun main() { val sObject = SubstringWithConcatenationOfAllWords() var s = "barfoothefoobarman" var words = arrayOf("foo", "bar") println(sObject.findSubstring(s, words)) s = "wordgoodgoodgoodbestword" words = arrayOf("word", "good", "best", "word") println(sObject.findSubstring(s, words)) s = "barfoofoobarthefoobarman" words = arrayOf("bar", "foo", "the") println(sObject.findSubstring(s, words)) s = "wordgoodgoodgoodbestword" words = arrayOf("word", "good", "best", "good") println(sObject.findSubstring(s, words)) }
2
Java
40
64
67b6ebaf56ec1878289f22a0324c28b077bcd59c
2,507
RedQuarkTutorials
MIT License
aoc-2015/src/main/kotlin/aoc/AocDay7.kt
triathematician
576,590,518
false
{"Kotlin": 615974}
package aoc class AocDay7: AocDay(7) { companion object { @JvmStatic fun main(args: Array<String>) { AocDay7().run() } } override val testinput = """ 123 -> x 456 -> y x AND y -> d x OR y -> e x LSHIFT 2 -> f y RSHIFT 2 -> g NOT x -> h NOT y -> i """.trimIndent().lines() data class Op(val in1: String, val in2: String, val op: OpType, val tgt: String) { var value: Int? = null fun calc(table: Map<String, Op>): Int = value ?: try { calcValue(table).also { value = it } } catch (x: NullPointerException) { println("NPE on $this") throw x } fun calcValue(table: Map<String, Op>): Int { val v1 = in1.toIntOrNull() ?: table[in1]!!.calc(table) val v2 = if (in2.isEmpty()) 0 else in2.toIntOrNull() ?: table[in2]!!.calc(table) return when (op) { OpType.ASSIGN -> v1 OpType.NOT -> v1.inv() OpType.AND -> v1 and v2 OpType.OR -> v1 or v2 OpType.LSHIFT -> v1 shl v2 OpType.RSHIFT -> v1 shr v2 } } } enum class OpType { AND, OR, LSHIFT, RSHIFT, NOT, ASSIGN } fun List<String>.opTable() = associate { val parts = it.split(" ") parts.last() to when (parts.size) { 3 -> Op(parts[0], "", OpType.ASSIGN, parts[2]) 4 -> Op(parts[1], "", OpType.NOT, parts[3]) 5 -> Op(parts[0], parts[2], OpType.valueOf(parts[1].toUpperCase()), parts[4]) else -> throw Exception("Invalid input: $it") } } override fun calc1(input: List<String>): Int { val wire = if (input.size < 50) "i" else "a" val opTable = input.opTable() return opTable[wire]!!.calc(opTable).let { if (it < 0) 65536 + it else it } } override fun calc2(input: List<String>): Int { val wire = if (input.size < 50) "i" else "a" val signal = calc1(input) val opTable = input.opTable().toMutableMap() opTable["b"] = Op(signal.toString(), "", OpType.ASSIGN, "b") return opTable[wire]!!.calc(opTable).let { if (it < 0) 65536 + it else it } } }
0
Kotlin
0
0
7b1b1542c4bdcd4329289c06763ce50db7a75a2d
2,327
advent-of-code
Apache License 2.0
src/main/kotlin/g1401_1500/s1411_number_of_ways_to_paint_n_3_grid/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1401_1500.s1411_number_of_ways_to_paint_n_3_grid // #Hard #Dynamic_Programming #2023_06_07_Time_201_ms_(100.00%)_Space_37.1_MB_(100.00%) class Solution { fun numOfWays(n: Int): Int { val dp = Array(n + 1) { IntArray(12) } dp[1].fill(1) val transfer = arrayOf( intArrayOf(5, 6, 8, 9, 10), intArrayOf(5, 8, 7, 9, -1), intArrayOf(5, 6, 9, 10, 12), intArrayOf(6, 10, 11, 12, -1), intArrayOf(1, 2, 3, 11, 12), intArrayOf(1, 3, 4, 11, -1), intArrayOf(2, 9, 10, 12, -1), intArrayOf(1, 2, 10, 11, 12), intArrayOf(1, 2, 3, 7, -1), intArrayOf(1, 3, 4, 7, 8), intArrayOf(4, 5, 6, 8, -1), intArrayOf(3, 4, 5, 7, 8) ) for (i in 2..n) { for (j in 0..11) { val prevStates = transfer[j] var sum = 0 for (s in prevStates) { if (s == -1) { break } sum = (sum + dp[i - 1][s - 1]) % MOD } dp[i][j] = sum } } var total = 0 for (i in 0..11) { total = (total + dp[n][i]) % MOD } return total } companion object { private const val MOD = 1000000007 } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,305
LeetCode-in-Kotlin
MIT License
aoc2023/day1.kt
davidfpc
726,214,677
false
{"Kotlin": 127212}
package aoc2023 import utils.InputRetrieval fun main() { Day1.execute() } private object Day1 { fun execute() { val input = readInput() println("Part 1: ${part1(input)}") println("Part 2: ${part2(input)}") } private fun part1(input: List<String>): Int = input.sumOf { val values = it.filter { value -> value.isDigit() } if (values.isEmpty()) { println("No numbers found! <<$it>>") 0 } else { "${values.first()}${values.last()}".toInt() } } private val REPLACEMENTS: List<Pair<String, String>> = listOf( "one" to "o1e", "two" to "t2o", "three" to "t3e", "four" to "4", "five" to "5e", "six" to "6", "seven" to "7n", "eight" to "e8t", "nine" to "n9e" ) private fun part2(input: List<String>): Int { val mappedInput = input.map { REPLACEMENTS.fold(it) { value, rep -> value.replace(rep.first, rep.second) } } return part1(mappedInput) } private fun readInput(): List<String> = InputRetrieval.getFile(2023, 1).readLines() }
0
Kotlin
0
0
8dacf809ab3f6d06ed73117fde96c81b6d81464b
1,168
Advent-Of-Code
MIT License
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions81.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.special fun test81() { printlnResult(intArrayOf(3, 5, 2), 8) printlnResult(intArrayOf(2, 3, 5), 10) } /** * Questions 81: Given an IntArray that doesn't contain the same integers. And, given a value, * please find all subsets that the sum of subset equals this value, integers could appear any times in one subset */ private infix fun IntArray.findSubsets(sum: Int): List<List<Int>> = buildList { backTrack(this, mutableListOf(), sum, 0) } private fun IntArray.backTrack(results: MutableList<List<Int>>, subset: MutableList<Int>, sum: Int, index: Int) { if (sum == 0) { results.add(listOf()) return } if (sum < 0) return val sumOfSubset = subset.sum() when { sumOfSubset > sum -> return sumOfSubset == sum -> { results.add(ArrayList(subset)) return } } if (index >= size) return backTrack(results, subset, sum, index + 1) subset.add(this[index]) backTrack(results, subset, sum, index) subset.removeLast() } private fun printlnResult(nums: IntArray, sum: Int) = println("The all subsets in ${nums.toList()} that sum equals $sum are ${nums findSubsets sum}")
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,222
Algorithm
Apache License 2.0
协程/collection/CollectionComparable.kt
wdfHPY
305,254,522
false
null
package com.lonbon.kotlin.collection /** * 排序 Comparable. * 1. 存在自然排序。针对一个类需要自然排序的话,那么需要实现的Comparable接口。并且实现Comparable接口。 * 2. */ class CollectionComparable { } fun main() { /* val v1 = Version(1, 2) val v2 = Version(2, 1) println(v1 > v2)*/ collectionPolymerization() } /** * 定义自然排序的话 -> 正值表示大 * 负值表示小 * 0 代表两个对象相等 */ data class Version( val majorVersion: Int, val subVersion: Int ) : Comparable<Version> { /** * 实现Comparable来定义自然顺序。 */ override fun compareTo(other: Version): Int { if (this.majorVersion != other.majorVersion) { return this.majorVersion - this.majorVersion } else if (this.subVersion != other.subVersion) { return this.subVersion - other.subVersion } else { return 0 } } } /* * 定义非自然顺序。 * 当不可以为类来定义自然顺序的时候,此时需要定义一个非自然的顺序。 * */ fun notNatureComparable() { /** * 定义一个比较器。Comparator()并且实现compareTo()方法。 */ val comparator = Comparator<String> { t, t2 -> t.length - t2.length } val list = listOf("aaa", "bb", "c") //可以调用kotlin的sortedWith方法。传入了一个Comparator即可。 println(list.sortedWith(comparator).joinToString()) //如果想快速定义一个的Comparator对象的话,可以使用 compareBy方法。该方法可以快速的定义出一个Comparator对象。 //定义comparator对象时,需要标注其类型。 val comparator2 = compareBy<String> { it.length } } fun collectionSort() { val list = listOf(1, 2, 3, 4, 5) val listVersion = listOf( Version(1, 1), Version(1, 2), Version(2, 3), Version(2, 1) ) println(list.sorted()) println(list.sortedDescending()) println(listVersion.sortedDescending()) println(listVersion.sortedDescending()) /** * sorted()和sortedDescending() 两个函数。可以针对存在自然排序的集合进行排序。 * sorted() 是自然排序的正序。sortedDescending()是自然排序的倒序。 */ /** * 自定义排序规则。通常存在两个函数sortedBy() */ val listNumber = listOf("one", "two", "three", "four", "five") //sortedBy的底层还是调用sortedWith(comparableBy{}) println(listNumber.sortedBy { it.length }.joinToString()) println(listNumber.sortedByDescending { it.length }.joinToString()) //sortWith可以使用自己的提供的Comparator } /** * 集合的倒序。kotlin * 1. reversed() 创建一个集合的副本,其中的元素的是接受者排序的逆序。 * 2. asReversed() * 3. reverse() 将集合逆转。 */ fun collectionReversed() { val list = mutableListOf(1, 2, 3, 4, 5, 6) val reverse = list.reversed() val reverse2 = list.asReversed() list.add(7) println(reverse) //由于是创建的副本的,所以那么原Collection的更改不会影响到新的倒序的Collection println(reverse2) //asRevered和reversed不相同。这个函数是针对引用来。原Collection的变化可以导致新的Collection变化。 println(list.joinToString()) } /** * shuffled洗牌算法。 */ fun collectionShuffled() { val list = listOf(1, 2, 3, 4, 5) //list.shuffled()同样是创建集合的副本然后执行洗牌 println(list.shuffled()) } /* * 集合的聚合操作: 按照某一种规则将集合聚合成一个值。 * */ fun collectionPolymerization() { val list = listOf(1, 543, 6, 89) val min = list.min() //最小值 val max = list.max() val average = list.average() val sum = list.sum() println(min) println(max) println(average) println(sum) //更高级的sum求和函数sumBy() .在集合的基础上调用上it函数 println(list.sumBy { it * 2 }) println(list.sumByDouble { it.toDouble() / 2 }) val numbers = listOf<Int>(1, 2, 3, 4) val sum2 = numbers.reduce { sum, element -> sum + element } // s = 5 T = 2、10、4 -> 5 + 2 -> 7 + 10 -> 17 + 4 = 21 val sum3 = numbers.fold(0) { sum, ele -> sum + ele * 2 // 0 + 5 + 2 + 10 + 4 -> } /** * reduce的初始值是第一个元素。在第一个元素的基础上,一直向后进行迭代调用值来调用相对应的方法。 * 在对元素进行reduce的时候,此时如果集合为空的集合,那么此时会产生异常。 * 而 fold的初始化的不是第一个元素,而是另外提供的一个初始化值。包括第一个值内一次和初始化做一定的操作。 * 当list为空的时候,此时不会产生异常,会返回初始值。 */ println(sum2) println(sum3) //fold 和 reduce 默认都是从集合的 left -> right。如何需要从集合的右侧开始进行规约。 foldRight() 或者 reduceRight() //通过查看源码发现。参数的顺序产生变化。第二个参数变成累加值。 val sum4 = numbers.foldRight(0) { sum, ele -> ele + sum * 2 // 0 + 5 + 2 + 10 + 4 -> } //如果需要加上针对Index的判断的话,那么也存在函数 val sum5 = numbers.foldIndexed(0) { index, sum, ele -> if (index % 2 == 0) sum + ele else sum + ele * 2 //0 + 1 + 4 + 3 + 8 } println(sum4) println(sum5) }
0
Kotlin
0
0
d879b0280c2e8579b480af9da484bc8a434dac0d
5,626
kotlinStudy
Apache License 2.0
src/main/kotlin/com/github/solairerove/algs4/leprosorium/searching/FindFirstAndLastPositionOfElement.kt
solairerove
282,922,172
false
{"Kotlin": 251919}
package com.github.solairerove.algs4.leprosorium.searching fun main() { val nums = listOf(5, 7, 7, 8, 8, 10) val target = 8 print(searchRange(nums, target)) // [3,4] } // O(log(n)) time | O(1) space private fun searchRange(arr: List<Int>, target: Int): Pair<Int, Int> { return Pair(findFirstIndex(arr, target), findLastIndex(arr, target)) } private fun findFirstIndex(arr: List<Int>, target: Int): Int { var idx = -1 var low = 0 var high = arr.size - 1 while (low <= high) { val mid = low + (high - low) / 2 when { arr[mid] >= target -> high = mid - 1 else -> low = mid + 1 } if (arr[mid] == target) idx = mid } return idx } private fun findLastIndex(arr: List<Int>, target: Int): Int { var idx = -1 var low = 0 var high = arr.size - 1 while (low <= high) { val mid = low + (high - low) / 2 when { arr[mid] <= target -> low = mid + 1 else -> high = mid - 1 } if (arr[mid] == target) idx = mid } return idx }
1
Kotlin
0
3
64c1acb0c0d54b031e4b2e539b3bc70710137578
1,097
algs4-leprosorium
MIT License