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/kt/kotlinalgs/app/graph/GraphMColoring.ws.kts
sjaindl
384,471,324
false
null
package kt.kotlinalgs.app.graph import java.util.* println("Test") Solution().test() data class Vertice<T>( val value: T, var color: Int = -1 ) { override fun equals(other: Any?): Boolean { val oth = other as? Vertice<*> ?: return false return oth.value == value } override fun hashCode(): Int { return value.hashCode() } } class DirectedGraphWithAdjList<T>(val vertices: List<Vertice<T>> = emptyList()) { private val adjList: MutableMap<Vertice<T>, MutableList<Vertice<T>>> = mutableMapOf() fun addEdge(from: Vertice<T>, to: Vertice<T>) { val neighbours = adjList[from] ?: mutableListOf() neighbours.add(to) adjList[from] = neighbours } fun neighbours(of: Vertice<T>): List<Vertice<T>> { return adjList[of] ?: emptyList() } } // https://www.geeksforgeeks.org/m-coloring-problem-backtracking-5/ // TODO! Somehow bipartite graph algo landed here instead of backtracking + BFS.. class BipartiteChecker<T> { fun isBipartiteBFS(graph: DirectedGraphWithAdjList<T>): Boolean { if (graph.vertices.size <= 2) return true graph.vertices.forEach { it.color = -1 } graph.vertices.forEach { if (it.color != -1) return@forEach if (!isBipartiteBFSUtil(graph, it)) return false } return true } fun isBipartiteBFSUtil(graph: DirectedGraphWithAdjList<T>, vertice: Vertice<T>): Boolean { val queue = LinkedList<Vertice<T>>() vertice.color = 0 queue.add(vertice) while (!queue.isEmpty()) { val cur = queue.remove() graph.neighbours(cur).forEach { if (it.color == cur.color) return false else if (it.color == -1) { it.color = if (cur.color == 0) 1 else 0 queue.add(it) } } } return true } fun isBipartiteDFS(graph: DirectedGraphWithAdjList<T>): Boolean { if (graph.vertices.size <= 2) return true graph.vertices.forEach { it.color = -1 } graph.vertices.forEach { if (it.color == -1 && !isBipartiteDFSRec(graph, it, -1)) return false } return true } private fun isBipartiteDFSRec( graph: DirectedGraphWithAdjList<T>, vertice: Vertice<T>, prevColor: Int ): Boolean { vertice.color = when (prevColor) { -1 -> 0 0 -> 1 else -> 0 } graph.neighbours(vertice).forEach { if (it.color == vertice.color) return false else if (it.color == -1) { if (!isBipartiteDFSRec(graph, it, vertice.color)) return false } } return true } } class Solution { fun test() { val vertice1 = Vertice(1) val vertice2 = Vertice(2) val vertice3 = Vertice(3) val vertice4 = Vertice(4) val vertice5 = Vertice(5) val vertice6 = Vertice(6) val graph = DirectedGraphWithAdjList<Int>( vertices = listOf( vertice1, vertice2, vertice3, vertice4, vertice5, vertice6 ) ) graph.addEdge(vertice1, vertice2) graph.addEdge(vertice2, vertice3) graph.addEdge(vertice3, vertice4) graph.addEdge(vertice4, vertice5) graph.addEdge(vertice5, vertice6) graph.addEdge(vertice6, vertice1) // 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 1 .. (cycle) val bipartiteChecker = BipartiteChecker<Int>() println(bipartiteChecker.isBipartiteDFS(graph)) println(bipartiteChecker.isBipartiteBFS(graph)) // -------------------------------------------------- val vertice1_2 = Vertice(1) val vertice2_2 = Vertice(2) val vertice3_2 = Vertice(3) val vertice4_2 = Vertice(4) val vertice5_2 = Vertice(5) val graph_2 = DirectedGraphWithAdjList<Int>( vertices = listOf( vertice1_2, vertice2_2, vertice3_2, vertice4_2, vertice5_2 ) ) graph_2.addEdge(vertice1_2, vertice2_2) graph_2.addEdge(vertice2_2, vertice3_2) graph_2.addEdge(vertice3_2, vertice4_2) graph_2.addEdge(vertice4_2, vertice5_2) graph_2.addEdge(vertice5_2, vertice1_2) // 1 -> 2 -> 3 -> 4 -> 5 -> 1 .. (cycle) val bipartiteChecker2 = BipartiteChecker<Int>() println(bipartiteChecker2.isBipartiteDFS(graph_2)) println(bipartiteChecker2.isBipartiteBFS(graph_2)) } }
0
Java
0
0
e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0
4,636
KotlinAlgs
MIT License
kotlin/19.kt
NeonMika
433,743,141
false
{"Kotlin": 68645}
import kotlin.math.abs class Day19 : Day<List<Day19.Scanner>>("19") { data class Vertex(val x: Int, val y: Int, val z: Int) { // https://stackoverflow.com/questions/16452383/how-to-get-all-24-rotations-of-a-3-dimensional-array private fun roll() = Vertex(x, z, -y) // Away from me (= rotate around x axis) private fun r() = roll() private fun turn() = Vertex(-y, x, z) // Top stays top (= rotate around y axis) private fun t() = turn() val possibleRotations: List<Vertex> by lazy { listOf( this, t(), t().t(), t().t().t(), r(), r().t(), r().t().t(), r().t().t().t(), r().r(), r().r().t(), r().r().t().t(), r().r().t().t().t(), r().r().r(), r().r().r().t(), r().r().r().t().t(), r().r().r().t().t().t(), t().r(), t().r().t(), t().r().t().t(), t().r().t().t().t(), t().t().t().r(), t().t().t().r().t(), t().t().t().r().t().t(), t().t().t().r().t().t().t() ) } fun distanceTo(other: Vertex) = abs(other.x - x) + abs(other.y - y) + abs(other.z - z) operator fun plus(other: Vertex) = Vertex(x + other.x, y + other.y, z + other.z) operator fun minus(other: Vertex) = Vertex(x - other.x, y - other.y, z - other.z) } data class Scanner(val id: Int, val beacons: Set<Vertex>) { var address: Vertex? = null val rotatedBeacons: List<Set<Vertex>> by lazy { (0..23).map { i -> beacons.map { beacon -> beacon.possibleRotations[i] }.toSet() } } } override fun dataStar1(lines: List<String>): List<Scanner> { val scanners = mutableListOf<Scanner>() var withSeps = lines.map { if (it.startsWith("---")) "-" else it } var id = 0 while (withSeps.isNotEmpty()) { withSeps = withSeps.drop(1) scanners += Scanner(id, withSeps.takeWhile { it != "-" } .map { it.ints(",").let { (x, y, z) -> Vertex(x, y, z) } }.toSet()) withSeps = withSeps.dropWhile { it != "-" } id++ } return scanners } private fun absoluteScanners(originalScanners: List<Scanner>): List<Scanner> { val absoluteScanners = mutableListOf(originalScanners[0].copy().apply { address = Vertex(0, 0, 0) }) val alreadyFixedScanners = mutableListOf(0) Outer@ while (absoluteScanners.size < originalScanners.size) { val toCheck = absoluteScanners.cross(originalScanners.filter { !alreadyFixedScanners.contains(it.id) }) for ((absoluteReference, relativeOther) in toCheck) { for (rotatedRelativeOther in relativeOther.rotatedBeacons) { val differenceCounts = rotatedRelativeOther .flatMap { otherBeacon -> absoluteReference.beacons.map { my -> my - otherBeacon } } .groupingBy { it } .eachCount() val offsetFromOrigin = differenceCounts.entries.find { (sameDiff, amount) -> amount == 12 }?.key if (offsetFromOrigin != null) { alreadyFixedScanners += relativeOther.id absoluteScanners += Scanner( relativeOther.id, rotatedRelativeOther.map { it + offsetFromOrigin }.toSet() ).apply { address = offsetFromOrigin } continue@Outer } } } } return absoluteScanners } override fun star1(data: List<Scanner>) = absoluteScanners(data).flatMap { it.beacons }.distinct().size override fun star2(data: List<Scanner>) = absoluteScanners(data).run { this.crossNotSelf(this).maxOf { (a, b) -> a.address!!.distanceTo(b.address!!) } } } fun main() { Day19()() }
0
Kotlin
0
0
c625d684147395fc2b347f5bc82476668da98b31
3,935
advent-of-code-2021
MIT License
src/main/kotlin/nl/kelpin/fleur/advent2018/Day12.kt
fdlk
159,925,533
false
null
package nl.kelpin.fleur.advent2018 class Day12(val initialState: State, val rules: Map<String, Char>) { companion object { fun of(input: List<String>): Day12 = Day12(State(input[0], 0), input.drop(1).map { it.split(" => ") }.map { it[0] to it[1][0] }.toMap()) } data class State(val pots: String, val indexOfFirstPot: Long) { fun value(): Long = pots.toCharArray().foldIndexed(0L) { pot: Int, sum: Long, c: Char -> if (c != '#') sum else sum + pot + indexOfFirstPot } } fun State.next(): State { val mapped = ("....$pots....").windowed(5).map { rules.getOrDefault(it, '.') } return State(mapped.dropWhile { it == '.' } .dropLastWhile { it == '.' } .joinToString(""), indexOfFirstPot - 2 + mapped.indexOf('#')) } fun part1(): Long { var state = initialState repeat(20){ state = state.next() } return state.value() } fun part2(): Long { var state = initialState var previousState: State var iteration = 0 do { previousState = state state = state.next() iteration++ } while (state.pots != previousState.pots) return state.copy(indexOfFirstPot = 50000000000 - iteration + state.indexOfFirstPot).value() } }
0
Kotlin
0
3
a089dbae93ee520bf7a8861c9f90731eabd6eba3
1,410
advent-2018
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem692/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem692 import java.util.* /** * LeetCode page: [692. Top K Frequent Words](https://leetcode.com/problems/top-k-frequent-words/); */ class Solution { /* Complexity: * Time O(NLogK) and Space O(N) where N is the size of words and K equals k; */ fun topKFrequent(words: Array<String>, k: Int): List<String> { val freqPerWord = getFreqPerWord(words) val topKPq = getTopKPq(freqPerWord, k) return getSortedTopKFrequentWords(topKPq) } private fun getFreqPerWord(words: Array<String>) = words.groupingBy { it }.eachCount() private fun getTopKPq(freqPerWord: Map<String, Int>, k: Int): PriorityQueue<Map.Entry<String, Int>> { /* The comparator assumes that at the same frequency, the one with greater lexicographical order * will be discarded first; */ val comparator = compareBy<Map.Entry<String, Int>> { it.value }.thenByDescending { it.key } val topKPq = PriorityQueue(comparator) for (entry in freqPerWord) { topKPq.offer(entry) if (topKPq.size > k) topKPq.poll() } return topKPq } private fun getSortedTopKFrequentWords(topKPq: PriorityQueue<Map.Entry<String, Int>>): List<String> { val topK = MutableList(topKPq.size) { topKPq.poll().key } topK.reverse() return topK } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,392
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/MakeConnected.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.LinkedList import java.util.Queue /** * 1319. Number of Operations to Make Network Connected * @see <a href="https://leetcode.com/problems/number-of-operations-to-make-network-connected/">Source</a> */ fun interface MakeConnected { operator fun invoke(n: Int, connections: Array<IntArray>): Int fun findParent(parent: IntArray, i: Int): Int { var i0 = i while (i0 != parent[i0]) i0 = parent[i0] return i0 // without path compression } } /** * ✔️ Solution 1a: Naive Union-Find ~ 23ms */ class MakeConnectedNaiveUnionFind : MakeConnected { override operator fun invoke(n: Int, connections: Array<IntArray>): Int { if (connections.size < n - 1) return -1 // To connect all nodes need at least n-1 edges val parent = IntArray(n) for (i in 0 until n) parent[i] = i var components = n for (c in connections) { val p1 = findParent(parent, c[0]) val p2 = findParent(parent, c[1]) if (p1 != p2) { parent[p1] = p2 // Union 2 component components-- } } return components - 1 // Need (components-1) cables to connect components together } } /** * ✔️ Solution 1c: Union-Find with Path Compression and Union by Size ~ 3ms */ class UnionBySizeMakeConnected : MakeConnected { override operator fun invoke(n: Int, connections: Array<IntArray>): Int { if (connections.size < n - 1) return -1 // to connect all nodes need at least n-1 edges val parent = IntArray(n) val size = IntArray(n) for (i in 0 until n) { parent[i] = i size[i] = 1 } var components = n for (c in connections) { val p1: Int = findParent(parent, c[0]) val p2: Int = findParent(parent, c[1]) if (p1 != p2) { if (size[p1] < size[p2]) { // merge small size to large size size[p2] += size[p1] parent[p1] = p2 } else { size[p1] += size[p2] parent[p2] = p1 } components-- } } return components - 1 // need (components-1) cables to connect components together } } /** * ✔️ Solution 2: DFS ~ 11ms */ class MakeConnectedDFS : MakeConnected { override operator fun invoke(n: Int, connections: Array<IntArray>): Int { if (connections.size < n - 1) return -1 // To connect all nodes need at least n-1 edges val graph: Array<MutableList<Int>> = Array(n) { mutableListOf() } for (i in 0 until n) graph[i] = ArrayList() for (c in connections) { graph[c[0]].add(c[1]) graph[c[1]].add(c[0]) } var components = 0 val visited = BooleanArray(n) for (v in 0 until n) { components += dfs(v, graph, visited) } return components - 1 // Need (components-1) cables to connect components together } private fun dfs(u: Int, graph: Array<MutableList<Int>>, visited: BooleanArray): Int { if (visited[u]) return 0 visited[u] = true for (v in graph[u]) dfs(v, graph, visited) return 1 } } /** * ✔️ Solution 3: BFS ~ 12ms */ class MakeConnectedBFS : MakeConnected { override operator fun invoke(n: Int, connections: Array<IntArray>): Int { if (connections.size < n - 1) { return -1 // To connect all nodes need at least n-1 edges } val graph: Array<MutableList<Int>> = Array(n) { mutableListOf() } for (c in connections) { graph[c[0]].add(c[1]) graph[c[1]].add(c[0]) } var components = 0 val visited = BooleanArray(n) for (v in 0 until n) components += bfs(v, graph.map { it.toList() }.toTypedArray(), visited) return components - 1 // Need (components-1) cables to connect components together } private fun bfs(src: Int, graph: Array<List<Int>>, visited: BooleanArray): Int { if (visited[src]) return 0 visited[src] = true val q: Queue<Int> = LinkedList() q.offer(src) while (q.isNotEmpty()) { val u: Int = q.poll() for (v in graph[u]) { if (!visited[v]) { visited[v] = true q.offer(v) } } } return 1 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
5,149
kotlab
Apache License 2.0
codeforces/vk2022/round1/h1_to_upsolve.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.vk2022.round1 import kotlin.time.ExperimentalTime import kotlin.time.measureTime private fun solve() { val (h, w, k) = readInts() val zero = 0.toModular() val one = 1.toModular() val broken = List(k) { readInts().map { it - 1 } } val powerOfTwo = Array(h * w + 1) { one } for (i in 1 until powerOfTwo.size) { powerOfTwo[i] = 2 * powerOfTwo[i - 1] } var ans = 0.toModular() for (hei in 1..h) for (wid in 1..w) { for (y0 in 0 until hei) for (y1 in 0 until hei) for (x0 in 0 until wid) for (x1 in 0 until wid) { if ((x0 == 0) xor (y0 == 0)) continue if ((x1 == wid - 1) xor (y1 == hei - 1)) continue // if ((x0 == wid - 1) && (y1 != 0)) continue // if ((y0 == hei - 1) && (x1 != 0)) continue val emptyByBorders = (if (y0 == 0) 0 else (y0 + x0 - 1)) + (if (y1 == hei - 1) 0 else (hei - y1 + wid - x1 - 3)) val borderImportant = setOf(0 to x0, y0 to 0, hei - 1 to x1, y1 to wid - 1) val variable = hei * wid - emptyByBorders - borderImportant.size // println("$hei $wid $y0 $y1 $x0 $x1 -> $variable") // ans += powerOfTwo[variable] } } println(ans) } @OptIn(ExperimentalTime::class) fun main() { measureTime { repeat(readInt()) { solve() } }.also { System.err.println(it) } } //private fun Int.toModular() = toDouble(); typealias Modular = Double private fun Int.toModular() = Modular1(this)//toDouble() private class Modular1 { companion object { const val M = 998244353 } val x: Int @Suppress("ConvertSecondaryConstructorToPrimary") constructor(value: Int) { x = (value % M).let { if (it < 0) it + M else it } } operator fun plus(that: Modular1) = Modular1((x + that.x) % M) operator fun minus(that: Modular1) = Modular1((x + M - that.x) % M) operator fun times(that: Modular1) = (x.toLong() * that.x % M).toInt().toModular() private fun modInverse() = Modular1(x.toBigInteger().modInverse(M.toBigInteger()).toInt()) operator fun div(that: Modular1) = times(that.modInverse()) override fun toString() = x.toString() } private operator fun Int.plus(that: Modular1) = Modular1(this) + that private operator fun Int.minus(that: Modular1) = Modular1(this) - that private operator fun Int.times(that: Modular1) = Modular1(this) * that private operator fun Int.div(that: Modular1) = Modular1(this) / that private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
2,460
competitions
The Unlicense
text2summary/src/main/java/com/ml/quaterion/text2summary/TFIDFSummarizer.kt
shubham0204
255,777,901
false
null
package com.ml.quaterion.text2summary import java.lang.Exception import kotlin.collections.ArrayList import kotlin.collections.HashMap // Uses Term Frequency-Inverse Document Frequency ( TF-IDF ) to summarize texts. First, we vectorize the sentences, // such that each token has its own TF-IDF score. We take the sum of all TF-IDF scores in a sentence. The sentences with // top N highest sums are included in the summary. class TFIDFSummarizer { // Returns the indices of sentences of a summary of the given text. Here, rate is the fraction of the text whose length equals the summary length. // For instance, a rate of 0.7 means that the summary will consist of 7 sentences given 10 sentences of text. fun compute( text : String , rate : Float ) : Array<Int> { // Check whether the rate lies in the given range. if ( !Tokenizer.checkRate( rate ) ){ throw Exception( "The compression rate must lie in the interval ( 0 , 1 ].") } // Get sentences from the text. val sentences = Tokenizer.paragraphToSentence( Tokenizer.removeLineBreaks( text ) ) val sentenceTokens = sentences.map { Tokenizer.sentenceToToken( it ) } val tokensList = ArrayList<String>() // Collect all the words present in the text. sentenceTokens.forEach { tokensList.addAll( it ) } // Create a ( word , frequency ) vocab. val vocab = Tokenizer.buildVocab( tokensList.toTypedArray() ) val tfidfSumList = ArrayList<Float>() // For each sentence, calculate TF, IDF and then TFIDF. Take the sum of all TF-IDF scores for all words in the // sentence and append it to a list. for ( tokenizedSentence in sentenceTokens ){ val termFrequency = computeTermFrequency( tokenizedSentence , vocab ) val inverseDocumentFrequency = computeInverseDocumentFrequency( termFrequency , sentenceTokens.toTypedArray() ) val tfIDF = computeTFIDF( termFrequency , inverseDocumentFrequency ) tfidfSumList.add( tfIDF.values.sum() ) } // Get the indices of top N maximum values from `weightedFreqSums`. val N = Math.floor((sentences.size * rate).toDouble()).toInt() val topNIndices = Tokenizer.getTopNIndices( tfidfSumList.toTypedArray(), tfidfSumList.toTypedArray().apply{ sort() reverse() }, N ) return topNIndices } // Computes the Term Frequency for a given sentence. For a token in a sentence, term frequency equals, // term_frequency = frequency_in_sentence / num_tokens_in_sentence private fun computeTermFrequency(s: Array<String>, vocab: HashMap<String,Int> ): HashMap<String, Float> { val freqMatrix = HashMap<String, Float>() for (word in vocab.keys) { freqMatrix[word] = 0f } for (word in s) { freqMatrix[word] = freqMatrix[word]!! + 1f } val tfFreqMatrix = HashMap<String, Float>() for ((word, count) in freqMatrix) { tfFreqMatrix[word] = count / s.size.toFloat() // Calculation of TF } return tfFreqMatrix } // Computes Inverse Document Frequency ( IDF ). It calculates the frequency of a tokens in all documents ( sentences ). // The IDF value is given by, // IDF = log10( num_docs / frequency_in_docs ) private fun computeInverseDocumentFrequency(freqMatrix : HashMap<String,Float> , docs : Array<Array<String> >) : HashMap<String,Float> { val freqInDocMap = HashMap<String,Float>() for( word in freqMatrix.keys ){ freqInDocMap[word] = 0f } for ( doc in docs ){ for( word in freqMatrix.keys ){ if ( doc.contains( word )){ freqInDocMap[ word ] = freqInDocMap[ word ]!! + 1f } } } val numDocs = docs.size.toFloat() val idfMap = HashMap<String,Float>() for ( ( word , freqInDoc ) in freqInDocMap ){ idfMap[ word ] = Math.log10( numDocs.toDouble() / freqInDoc.toDouble() ).toFloat() } return idfMap } // Calculate the final product of the TF and IDF scores. private fun computeTFIDF( tfMatrix : HashMap<String,Float> , idfMatrix : HashMap<String,Float> ) : HashMap<String,Float>{ val tfidfMatrix = HashMap<String,Float>() for( word in tfMatrix.keys ){ tfidfMatrix[word] = tfMatrix[ word ]!! * idfMatrix[ word ]!! } return tfidfMatrix } }
1
Kotlin
5
20
3f0f88d193ea81acc5a21d34fe19a630056a11e5
4,695
Text2Summary-Android
Apache License 2.0
day5/src/main/kotlin/App.kt
ascheja
317,918,055
false
null
package net.sinceat.aoc2020.day5 fun main() { val testCodes = listOf( "FBFBBFFRLR", "BFFFBBFRRR", "FFFBBBFRRR", "BBFFBBFRLL" ) testCodes.forEach { testCode -> println(SeatCoordinates.ofSeatCode(testCode)) } ClassLoader.getSystemResourceAsStream("input.txt")!!.bufferedReader().useLines { lines -> val maxSeatId = lines.filterNot(String::isEmpty) .map(SeatCoordinates.Companion::ofSeatCode) .map(SeatCoordinates::seatId) .maxOrNull() println("max seat id: $maxSeatId") } ClassLoader.getSystemResourceAsStream("input.txt")!!.bufferedReader().useLines { lines -> val emptySeatId = lines.filterNot(String::isEmpty) .map(SeatCoordinates.Companion::ofSeatCode) .map(SeatCoordinates::seatId) .sorted() .windowed(2, 1) .first { (a, b) -> b - a == 2 }[0] + 1 println("empty seat id: $emptySeatId") } } data class SeatCoordinates(val row: Int, val column: Int, val seatId: Int = row * 8 + column) { companion object { private fun codeToNumber(code: String, highChar: Char): Int { return code.map { c -> if (c == highChar) 1 else 0 }.reduce { a, b -> a * 2 + b } } fun ofSeatCode(code: String): SeatCoordinates { val (rowCode, columnCode) = code.chunked(7) return SeatCoordinates(codeToNumber(rowCode, 'B'), codeToNumber(columnCode, 'R')) } } }
0
Kotlin
0
0
f115063875d4d79da32cbdd44ff688f9b418d25e
1,517
aoc2020
MIT License
kotlin/src/katas/kotlin/leetcode/wildcard_matching/v4/WildcardMatching.kt
dkandalov
2,517,870
false
{"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221}
package katas.kotlin.leetcode.wildcard_matching.v4 import datsok.shouldEqual import org.junit.Test typealias Matcher = (String) -> Set<String> fun char(char: Char): Matcher = { s -> if (s.firstOrNull() == char) setOf(s.drop(1)) else emptySet() } fun anyChar(): Matcher = { s -> if (s.isNotEmpty()) setOf(s.drop(1)) else emptySet() } fun anyChars(): Matcher = { s -> (0..s.length).mapTo(HashSet()) { s.drop(it) } } fun isMatch(s: String, pattern: String): Boolean { val matchers = pattern.map { when (it) { '?' -> anyChar() '*' -> anyChars() else -> char(it) } } return matchers .fold(setOf(s)) { outputs, matcher -> outputs.flatMapTo(HashSet()) { matcher(it) } } .any { output -> output.isEmpty() } } // ✅ class WildcardMatching { @Test fun `some examples`() { isMatch("a", "a") shouldEqual true isMatch("a", "b") shouldEqual false isMatch("aa", "aa") shouldEqual true isMatch("aa", "a") shouldEqual false isMatch("a", "aa") shouldEqual false isMatch("", "*") shouldEqual true isMatch("a", "*") shouldEqual true isMatch("aa", "*") shouldEqual true isMatch("aa", "**") shouldEqual true isMatch("aa", "***") shouldEqual true isMatch("aa", "*a") shouldEqual true isMatch("aa", "a*") shouldEqual true isMatch("aa", "*aa") shouldEqual true isMatch("aa", "a*a") shouldEqual true isMatch("aa", "aa*") shouldEqual true isMatch("aa", "*b") shouldEqual false isMatch("aa", "b*") shouldEqual false isMatch("adceb", "*a*b") shouldEqual true isMatch("a", "?") shouldEqual true isMatch("cb", "?a") shouldEqual false isMatch("acdcb", "a*c?b") shouldEqual false } }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
1,830
katas
The Unlicense
2023/day04-25/src/main/kotlin/Day19.kt
CakeOrRiot
317,423,901
false
{"Kotlin": 62169, "Python": 56994, "C#": 20675, "Rust": 10417}
import java.io.File import java.math.BigInteger import kotlin.collections.Map import kotlin.math.max import kotlin.math.min class Day19 { val doubleNewLines = "(\r\n\r\n)|(\n\n)" val newLines = "(\r\n)|(\n)" fun solve1() { val input = File("inputs/19.txt").inputStream().bufferedReader().use { it.readText() }.split(doubleNewLines.toRegex()) val conditions = input[0].split(newLines.toRegex()).associate { line -> val split = line.split("[{,}]".toRegex()).filter { it.isNotBlank() } val name = split[0] val result = split.last() val conditions = split.drop(1).dropLast(1).map { cond -> val splitCondition = cond.split(':') Pair(splitCondition[0], splitCondition[1]) } name to Pair(conditions, result) } val ratings = input[1].split(newLines.toRegex()).filter { it.isNotBlank() }.map { it -> val split = it.drop(1).dropLast(1).split("[,=]".toRegex()).filter { it.isNotBlank() } val x = split[1].toInt() val m = split[3].toInt() val a = split[5].toInt() val s = split[7].toInt() Rating(x, m, a, s) } var res = 0 ratings.forEach { rating -> var curCondition = conditions.getValue("in") while (true) { val branches = curCondition.first var ratingResult = curCondition.second for (branch in branches) { val split = branch.first.split("[<>]".toRegex()).filter { it.isNotBlank() } val variable = split[0] val value = split[1].toInt() val result = branch.second val pass = when (branch.first[1]) { '>' -> rating[variable] > value '<' -> rating[variable] < value else -> throw Exception("Can't compare") } if (!pass) continue ratingResult = result break } if (ratingResult == "A") { res += rating.x + rating.m + rating.a + rating.s break } else if (ratingResult == "R") break else curCondition = conditions.getValue(ratingResult) } } println(res) } fun solve2() { val input = File("inputs/19.txt").inputStream().bufferedReader().use { it.readText() } .split(doubleNewLines.toRegex()) val conditions = input[0].split(newLines.toRegex()).associate { line -> val split = line.split("[{,}]".toRegex()).filter { it.isNotBlank() } val name = split[0] val result = split.last() val conditions = split.drop(1).dropLast(1).map { cond -> val splitCondition = cond.split(':') Pair(splitCondition[0], splitCondition[1]) } name to Pair(conditions, result) } val range = RatingRange() println(applyRange(conditions, range, "in")) } fun applyRange( conditions: Map<String, Pair<List<Pair<String, String>>, String>>, range: RatingRange, startCond: String, skipBranches: Int = 0 ): BigInteger { if (range.isEmpty()) return BigInteger.ZERO val curCondition = conditions.getValue(startCond) val branches = curCondition.first val finalResult = curCondition.second if (skipBranches >= branches.size) { val res = when (finalResult) { "A" -> (range.x.count().toBigInteger() * range.m.count().toBigInteger() * range.a.count() .toBigInteger() * range.s.count().toBigInteger()) "R" -> BigInteger.ZERO else -> applyRange(conditions, range, finalResult, 0) } return res } val branch = branches[skipBranches] val branchResult = branch.second val split = branch.first.split("[<>]".toRegex()).filter { it.isNotBlank() } val variable = split[0] val value = split[1].toInt() val cmpOperator = branch.first[1] val newRangesVar = when (cmpOperator) { '>' -> { val rangeAccept = IntRange(max(range[variable].first, value + 1), range[variable].last) val rangeDecline = IntRange(range[variable].first, rangeAccept.first - 1) Pair(rangeAccept, rangeDecline) } '<' -> { val rangeAccept = IntRange(range[variable].first, min(range[variable].last, value - 1)) val rangeDecline = IntRange(value, range[variable].last) Pair(rangeAccept, rangeDecline) } else -> throw Exception("Can't compare") } val newRangeDecline = range.clone() newRangeDecline[variable] = newRangesVar.second val resDecline = applyRange(conditions, newRangeDecline, startCond, skipBranches = skipBranches + 1) val newRangeAccept = range.clone() newRangeAccept[variable] = newRangesVar.first val resAccept = when (branchResult) { "A" -> (newRangeAccept.x.count().toBigInteger() * newRangeAccept.m.count() .toBigInteger() * newRangeAccept.a.count().toBigInteger() * newRangeAccept.s.count() .toBigInteger()) "R" -> BigInteger.ZERO else -> applyRange(conditions, newRangeAccept, branchResult, 0) } return resAccept + resDecline } class RatingRange() { var x: IntRange = IntRange(1, 4000) var m: IntRange = IntRange(1, 4000) var a: IntRange = IntRange(1, 4000) var s: IntRange = IntRange(1, 4000) constructor(x: IntRange, m: IntRange, a: IntRange, s: IntRange) : this() { this.x = x this.m = m this.a = a this.s = s } operator fun get(field: String): IntRange { return when (field) { "x" -> x "m" -> m "a" -> a "s" -> s else -> throw Exception("Unknown field") } } fun isEmpty(): Boolean { return x.isEmpty() || m.isEmpty() || a.isEmpty() || s.isEmpty() } fun clone(): RatingRange { return RatingRange( IntRange(x.first, x.last), IntRange(m.first, m.last), IntRange(a.first, a.last), IntRange(s.first, s.last) ) } operator fun set(field: String, value: IntRange) { when (field) { "x" -> this.x = value "m" -> this.m = value "a" -> this.a = value "s" -> this.s = value else -> throw Exception("Unknown field") } } } class Rating<T>(val x: T, val m: T, val a: T, val s: T) where T : Comparable<T> { operator fun get(field: String): T { return when (field) { "x" -> x "m" -> m "a" -> a "s" -> s else -> throw Exception("Unknown field") } } } }
0
Kotlin
0
0
8fda713192b6278b69816cd413de062bb2d0e400
7,416
AdventOfCode
MIT License
src/main/kotlin/before/test/problem3/OtherSolution.kt
K-Diger
642,489,846
false
{"Kotlin": 105578, "Java": 57609}
package before.test.problem3 import java.time.LocalTime import java.time.format.DateTimeFormatter import kotlin.math.abs class Solution3 { companion object { private const val SPLIT_OF_TIME = ":" private const val SPLIT_OF_TIME_RANGE = "~" private const val DAY_TO_HOUR = 24 private const val END_OF_HOUR = 23 private const val HOUR_TO_MINUTES = 60 private const val END_OF_MINUTES = 59 private const val TIME_FORMAT = "HH:mm" private const val START_HOUR = 0 private const val START_MINUTES = 0 private const val FAILED_FLAG = "impossible" } var disturbTime = Array(DAY_TO_HOUR) { BooleanArray(HOUR_TO_MINUTES) { false } } fun solution(noti_time: String, do_not_distrub: Array<String>): String { do_not_distrub.forEach { times -> val (startTime, endTime) = times.split(SPLIT_OF_TIME_RANGE) val (startHour, startMinutes) = startTime.split(SPLIT_OF_TIME).map { it.toInt() } val (endHour, endMinutes) = endTime.split(SPLIT_OF_TIME).map { it.toInt() } val startTotalMinutes = startHour * HOUR_TO_MINUTES + startMinutes val endTotalMinutes = endHour * HOUR_TO_MINUTES + endMinutes if (startTotalMinutes > endTotalMinutes) { setDisturbTime(startHour, startMinutes, END_OF_HOUR, HOUR_TO_MINUTES) setDisturbTime(START_HOUR, START_MINUTES, endHour, endMinutes) disturbTime[END_OF_HOUR][END_OF_MINUTES] = true disturbTime[START_HOUR][START_MINUTES] = true } else { setDisturbTime(startHour, startMinutes, endHour, endMinutes) } } val notiTime = noti_time.split(SPLIT_OF_TIME) val (notiHour, notiMinutes) = notiTime.map { it.toInt() } val notiTotal = notiHour * HOUR_TO_MINUTES + notiMinutes var answerHour = 0 var answerMinutes = 0 var answerTotalMin = Int.MAX_VALUE for (hour in notiHour..END_OF_HOUR) { val startMin = if (hour == notiHour) notiMinutes else 0 for (minutes in startMin..END_OF_MINUTES) { if (!disturbTime[hour][minutes]) { val totalMin = hour * HOUR_TO_MINUTES + minutes val tempTotalMin = abs(totalMin - notiTotal) if (tempTotalMin < answerTotalMin) { answerHour = hour answerMinutes = minutes answerTotalMin = tempTotalMin } } } } if (answerTotalMin != Int.MAX_VALUE) { return convertTimeFormatting(answerHour, answerMinutes) } for (hour in 0..END_OF_HOUR) { for (minutes in 0..END_OF_MINUTES) { if (!disturbTime[hour][minutes]) { answerHour = hour answerMinutes = minutes return convertTimeFormatting(answerHour, answerMinutes) } } } return FAILED_FLAG } private fun setDisturbTime(startHour: Int, startMin: Int, endHour: Int, endMinutes: Int) { for (min in startMin until if (startHour == endHour) endMinutes else HOUR_TO_MINUTES) { disturbTime[startHour][min] = true } for (hour in startHour + 1..endHour) { val end = if (hour == endHour) endMinutes else HOUR_TO_MINUTES for (min in 0 until end) { disturbTime[hour][min] = true } } } private fun convertTimeFormatting(hour: Int, min: Int): String { val dateTimeFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern(TIME_FORMAT) return dateTimeFormatter.format(LocalTime.of(hour, min)) } }
0
Kotlin
0
0
2789df5993923f7aab6e8774a7387ab65c29060a
3,850
algorithm-rehab
MIT License
src/main/kotlin/day17.kt
gautemo
572,204,209
false
{"Kotlin": 78294}
import shared.Point import shared.getText fun main() { val input = getText("day17.txt") println(day17A(input)) println(day17B(input)) } fun day17A(input: String) = heightAfter(input, 2022) fun day17B(input: String) = heightAfter(input, 1000000000000) fun heightAfter(jets: String, totalRounds: Long): Long { val history = History(totalRounds, jets) var jet = 0 var round = 0L val rocks = mutableListOf<Point>() while (round < totalRounds) { history.checkCanSkip(round, jet, rocks)?.let { round += it } val figure = nextFigure(round, rocks.maxOfOrNull { it.y } ?: -1) do { if(jets[jet % jets.length] == '>') { figure.pushRight(rocks) } else { figure.pushLeft(rocks) } val stopped = figure.down(rocks) if(stopped) { rocks.addAll(figure.points) } jet++ } while (!stopped) round++ } return rocks.maxOf { it.y } + 1 + history.addHeight } data class Figure(var points: List<Point>) { fun pushLeft(rocks: List<Point>) { if(points.minOf { it.x } == 0) return if(points.any { rocks.contains(Point(it.x-1, it.y)) }) return points = points.map { Point(it.x-1, it.y) } } fun pushRight(rocks: List<Point>) { if(points.maxOf { it.x } == 6) return if(points.any { rocks.contains(Point(it.x+1, it.y)) }) return points = points.map { Point(it.x+1, it.y) } } fun down(rocks: List<Point>): Boolean { if(points.minOf { it.y } == 0) return true if(points.any { rocks.contains(Point(it.x, it.y-1)) }) return true points = points.map { Point(it.x, it.y-1) } return false } companion object { fun init(vararg points: Point) = Figure(points.toList()) } } private fun nextFigure(round: Long, highestRock: Int): Figure { val bottomY = highestRock + 4 return when(round % 5) { 0L -> Figure.init(Point(2, bottomY), Point(3, bottomY), Point(4, bottomY), Point(5, bottomY)) 1L -> Figure.init(Point(3, bottomY+2), Point(2, bottomY+1), Point(3, bottomY+1), Point(4, bottomY+1), Point(3, bottomY)) 2L -> Figure.init(Point(4, bottomY+2), Point(4, bottomY+1), Point(2, bottomY), Point(3, bottomY), Point(4, bottomY)) 3L -> Figure.init(Point(2, bottomY+3), Point(2, bottomY+2), Point(2, bottomY+1), Point(2, bottomY)) else -> Figure.init(Point(2, bottomY+1), Point(3, bottomY+1), Point(2, bottomY), Point(3, bottomY)) } } private class History(private val totalRounds: Long, private val jets: String) { private val startConditions = mutableMapOf<Triple<Long, Int, List<Int>>, Pair<Long, Int>>() var addHeight = 0L fun checkCanSkip(round: Long, jet: Int, rocks: List<Point>): Long? { if(addHeight != 0L) return null val highestRock = rocks.maxOfOrNull { it.y } ?: 0 val landingSpot = (0..6).map { x -> rocks.maxOfOrNull { if(it.x == x) it.y - highestRock else -highestRock } ?: 0 } val state = Triple(round % 5, jet % jets.length, landingSpot) return if(startConditions.containsKey(state)) { val diffRound = round - startConditions[state]!!.first val diffHeight = highestRock - startConditions[state]!!.second val roundsLeft = totalRounds - round addHeight = diffHeight * (roundsLeft / diffRound) return roundsLeft - (roundsLeft % diffRound) } else { startConditions[state] = round to highestRock null } } }
0
Kotlin
0
0
bce9feec3923a1bac1843a6e34598c7b81679726
3,660
AdventOfCode2022
MIT License
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2023/2023-20.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2023 import com.github.ferinagy.adventOfCode.lcm import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines import java.util.LinkedList fun main() { val input = readInputLines(2023, "20-input") val test1 = readInputLines(2023, "20-test1") val test2 = readInputLines(2023, "20-test2") println("Part1:") part1(test1).println() part1(test2).println() part1(input).println() println() println("Part2:") part2(input).println() } private fun part1(input: List<String>): Int { val moduleMap = parseModules(input) var totalLow = 0 var totalHigh = 0 repeat(1000) { runCycle(moduleMap, "broadcaster", onPulseSent = { _, value -> if (value) totalHigh++ else totalLow++ }) } return totalLow * totalHigh } private fun part2(input: List<String>): Long { val moduleMap = parseModules(input) val modules = moduleMap.values.toList() val collector = modules.single { "rx" in it.out }.name val ends = modules.filter { collector in it.out }.map { it.name } val periods = ends.map { end -> val (start, visited) = findSubGraph(end, modules) val subModules = parseModules(input).filter { it.key in visited } val (period, offset) = findCycle(subModules, start) reset(subModules) val interesting = mutableListOf<Int>() repeat(period + offset) { runCycle(subModules, start, onPulseSent = { node, value -> if (node == end && !value) { interesting += it + 1 } }) } check(interesting.single() == period) period.toLong() } return periods.reduce { acc, period -> lcm(acc, period) } } private inline fun runCycle(moduleMap: Map<String, Module>, start: String, print: Boolean = false, onPulseSent: (String, Boolean) -> Unit) { val queue = LinkedList<Triple<String, String, Boolean>>() queue += Triple("button", start, false, ) while (queue.isNotEmpty()) { val (source, dest, value) = queue.removeFirst().also { if (print) it.println() } onPulseSent(dest, value) val module = moduleMap[dest] ?: continue if (print) module.println() when (module) { is Broadcaster -> module.out.forEach { queue += Triple(module.name, it, value) } is Conjunction -> { module.states[source] = value val output = module.states.values.any { !it } module.out.forEach { queue += Triple(module.name, it, output) } } is FlipFlop -> { if (!value) { module.state = !module.state module.out.forEach { queue += Triple(module.name, it, module.state) } } } } } } private fun findSubGraph(end: String, modules: List<Module>): Pair<String, Set<String>> { val queue = mutableListOf(end) val visited = mutableSetOf<String>() lateinit var start: String while (queue.isNotEmpty()) { val current = queue.removeLast() if (current in visited) continue visited += current val next = modules.filter { current in it.out }.map { it.name } if ("broadcaster" in next) { start = current } queue += next } return start to visited } private fun findCycle(moduleMap: Map<String, Module>, start: String): Pair<Int, Int> { val state = getState(moduleMap) val states = mutableMapOf(state to 0) var counter = 0 val period: Int val offset: Int while (true) { counter++ runCycle(moduleMap = moduleMap, start = start, onPulseSent = { _, _ -> }) val newState = getState(moduleMap) if (newState in states) { offset = states[newState]!! period = counter - offset break } states[newState] = counter } return period to offset } private fun getState(moduleMap: Map<String, Module>): Pair<Map<String, Boolean>, Map<String, Map<String, Boolean>>> { val flipFlops = moduleMap.values.filterIsInstance<FlipFlop>().associate { it.name to it.state } val cons = moduleMap.values.filterIsInstance<Conjunction>().associate { it.name to it.states.toMap() } return flipFlops to cons } private fun reset(moduleMap: Map<String, Module>) { moduleMap.forEach { (_, module) -> when (module) { is Broadcaster -> Unit is Conjunction -> module.states.keys.forEach { module.states[it] = false } is FlipFlop -> module.state = false } } } private fun parseModules(input: List<String>): Map<String, Module> { val modules = input.map { line -> val (source, dests) = line.split(" -> ") val out = dests.split(", ") when { source.startsWith('%') -> FlipFlop(source.drop(1), out) source.startsWith('&') -> Conjunction(source.drop(1), out) source == "broadcaster" -> Broadcaster(source, out) else -> error("unknown module: '$line'") } } modules.filterIsInstance<Conjunction>().forEach { con -> modules.filter { con.name in it.out }.map { it.name }.forEach { con.states[it] = false } } return modules.associateBy { it.name } } private sealed interface Module { val name: String val out: List<String> } private data class Broadcaster( override val name: String, override val out: List<String>, ) : Module private data class FlipFlop( override val name: String, override val out: List<String>, var state: Boolean = false ) : Module private data class Conjunction( override val name: String, override val out: List<String>, val states: MutableMap<String, Boolean> = mutableMapOf() ) : Module
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
6,029
advent-of-code
MIT License
year2017/src/main/kotlin/net/olegg/aoc/year2017/day3/Day3.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2017.day3 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.Directions.Companion.NEXT_8 import net.olegg.aoc.utils.Directions.D import net.olegg.aoc.utils.Directions.L import net.olegg.aoc.utils.Directions.R import net.olegg.aoc.utils.Directions.U import net.olegg.aoc.utils.Vector2D import net.olegg.aoc.year2017.DayOf2017 import kotlin.math.abs /** * See [Year 2017, Day 3](https://adventofcode.com/2017/day/3) */ object Day3 : DayOf2017(3) { override fun first(): Any? { val position = data.toInt() val square = (1..Int.MAX_VALUE step 2).first { it * it >= position } val relative = position - (square - 2) * (square - 2) val diff = (relative - 1) % (square - 1) return (square / 2) + abs(diff - (square / 2 - 1)) } override fun second(): Any? { val input = data.toInt() var current = Vector2D(0, 0) to 1 val visited = mutableMapOf(current) var square = 0 while (current.second < input) { val (pos, _) = current val nextPos = pos + when { pos.y == square -> R pos.x == square && pos.y > -square -> U pos.y == -square && pos.x > -square -> L pos.x == -square && pos.y < square -> D else -> R }.step if (abs(nextPos.x) > square || abs(nextPos.y) > square) { square += 1 } val value = NEXT_8.sumOf { visited[nextPos + it.step] ?: 0 } current = nextPos to value visited += current } return current.second } } fun main() = SomeDay.mainify(Day3)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,547
adventofcode
MIT License
src/main/kotlin/day1/Day1.kt
tomaszobac
726,163,227
false
{"Kotlin": 15292}
package day1 import java.io.File fun part1(file: File) { var numbers: Array<Int> = arrayOf() for (line in file.readLines()) { val firstNum = line.indexOfFirst { it.isDigit() } val lastNum = line.indexOfLast { it.isDigit() } val number = "${line[firstNum]}${line[lastNum]}" numbers += number.toInt() } println(numbers.sum()) } fun part2(file: File) { val dictionary: Map<String, Int> = mapOf( Pair("one", 1), Pair("two", 2),Pair("three", 3), Pair("four", 4), Pair("five", 5),Pair("six", 6), Pair("seven", 7), Pair("eight", 8),Pair("nine", 9), Pair("1", 1), Pair("2", 2),Pair("3", 3), Pair("4", 4), Pair("5", 5),Pair("6", 6), Pair("7", 7), Pair("8", 8),Pair("9", 9), ) var numbers: Array<Int> = arrayOf() for (line in file.readLines()) { var firstNum = 0 var lastNum = 0 var minIndex = Int.MAX_VALUE var maxIndex = 0 for (key in dictionary.keys) { val firstIndex = line.indexOf(key) if (firstIndex == -1) continue val lastIndex = line.lastIndexOf(key) if (firstIndex <= minIndex) { firstNum = dictionary[key]!! minIndex = firstIndex } if (lastIndex >= maxIndex) { lastNum = dictionary[key]!! maxIndex = lastIndex } } numbers += ((firstNum * 10) + lastNum) } println(numbers.sum()) } fun main() { val file = File("src/main/kotlin/day1/input.txt") part1(file) part2(file) }
0
Kotlin
0
0
e0ce68fcf11e126c4680cff75ba959e46c5863aa
1,625
aoc2023
MIT License
src/test/kotlin/com/igorwojda/string/issubstring/solution.kt
tmdroid
498,808,938
true
{"Kotlin": 218846}
package com.igorwojda.string.issubstring //Kotlin Idiomatic Approach private object Solution1 { private fun isSubstring(str: String, subStr: String): Boolean { return str.contains(subStr) && str.isNotEmpty() && subStr.isNotEmpty() } } // Time complexity: O(n+m) // Space complexity: O(1) // // Optimal solution using double pointer. private object Solution2 { private fun isSubstring(str: String, subStr: String): Boolean { if (str.isEmpty() || subStr.isEmpty()) return false if (str.length <= subStr.length) return false var pointer1 = 0 var pointer2 = 0 while (pointer1 <= str.lastIndex) { if (str[pointer1] == subStr[pointer2]) { pointer2++ } if (pointer2 == subStr.length) { return true } pointer1++ } return false } } // Time complexity: O(n+m) // Space complexity: ??, but more than O(1) // Number of iterations (n) is bounded by the length of the first string // and String.drop requires copying the entire remaining string (on it's own it has O(m) complexity) // First of 5 chars, needs 5 iterations at most and 15 character copied (5+4+3+2+1=15). Second is copied less often. // // Recursive solution private object Solution3 { private fun isSubstring(str: String, subStr: String): Boolean { if (subStr.length > str.length) { return false } if (str.isEmpty() || subStr.isEmpty()) { return false } return if (str.first() == subStr.first()) { val localStr = str.drop(1) val localSubStr = subStr.drop(1) if (localStr.first() == localSubStr.first()) { true } else { isSubstring(localStr, localSubStr.drop(1)) } } else { isSubstring(str.drop(1), subStr) } } } // Time complexity: O(n) // Space complexity: O(1) // This recursive solution is faster than solution with String.drop because it uses double pointer // // Recursive solution private fun isSubstring(str: String, subStr: String): Boolean { if (str.isEmpty() || subStr.isEmpty()) { return false } fun helper(first: String, second: String, firstPointer1: Int = 0, secondPointer2: Int = 0): Boolean { if (firstPointer1 > first.lastIndex) { return false } return if (first[firstPointer1] == second[secondPointer2]) { val localPointer1 = firstPointer1 + 1 val localPointer2 = secondPointer2 + 1 if (localPointer1 > first.lastIndex || localPointer2 > second.lastIndex) { return true } else { helper(first, second, localPointer1, localPointer2) } } else { val p1 = firstPointer1 + 1 if (p1 > first.lastIndex) { return false } else { helper(first, second, p1, secondPointer2) } } } return helper(str, subStr) }
1
Kotlin
2
0
f82825274ceeaf3bef81334f298e1c7abeeefc99
3,100
kotlin-puzzles
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem33/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem33 /** * LeetCode page: [33. Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/); */ class Solution { /* Complexity: * Time O(LogN) and Space O(1) where N is the size of nums; */ fun search(nums: IntArray, target: Int): Int { val (fromIndex, toIndex) = if (target > nums.last()) Pair(0, indexOfMin(nums)) else Pair(indexOfMin(nums), nums.size) return nums .binarySearch(target, fromIndex, toIndex) .let { if (it < 0) -1 else it } } /** * [nums] should be a sorted array with distinct values, and it may be rotated. * * Return the index of the minimum value in [nums]. */ private fun indexOfMin(nums: IntArray): Int { if (nums.size == 1 || nums[0] < nums.last()) { return 0 } var left = 0 var right = nums.lastIndex while (left <= right) { val mid = left + (right - left) / 2 when { nums[mid] > nums[mid + 1] -> return mid + 1 nums[mid] < nums[0] -> right = mid else -> left = mid + 1 } } throw IllegalStateException() } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,267
hj-leetcode-kotlin
Apache License 2.0
src/Day05.kt
GarrettShorr
571,769,671
false
{"Kotlin": 82669}
fun main() { fun findNumCrates(input: List<String>): Int { for(line in input) { if(line.startsWith(" 1")) { val nums = line.split(" ") return nums.last().toInt() } } return 0 } fun fillCrates(crates: MutableList<MutableList<String>>, input: List<String>) { for(line in input) { if(line.startsWith(" 1")) { return } // 3 digits then a space for(i in line.indices step 4) { val crate = line.substring(i+1, i+2) if(!crate.startsWith(" ")) { crates[i/4].add(crate) } } } } fun parseMoves(input: List<String>): MutableList<MutableList<Int>> { val moves = mutableListOf<MutableList<Int>>() for(line in input) { if(!line.startsWith("move")) { continue } val instructions = line.split(" ") as MutableList instructions.remove("move") instructions.remove("from") instructions.remove("to") val move = instructions.map { it.toInt() } as MutableList move[1]-- move[2]-- moves.add(move) } return moves } fun part1(input: List<String>): String { // find the numbers first to find out how many crates val numCrates = findNumCrates(input) val crates = mutableListOf<MutableList<String>>() for(i in 0 until numCrates) { crates.add(mutableListOf()) } // read the crates. 3 digits then space until the last 3 digits fillCrates(crates, input) println(numCrates) println(crates) // read and parse the moves val moves = parseMoves(input) println(moves) // execute instructions for(move in moves) { for(i in 1..move[0]) { crates[move[2]].add(0, crates[move[1]].removeAt(0)) } } var top = "" for(crate in crates) { top += crate[0] } return top } fun part2(input: List<String>): String { // find the numbers first to find out how many crates val numCrates = findNumCrates(input) val crates = mutableListOf<MutableList<String>>() for(i in 0 until numCrates) { crates.add(mutableListOf()) } // read the crates. 3 digits then space until the last 3 digits fillCrates(crates, input) println(numCrates) println(crates) // read and parse the moves val moves = parseMoves(input) println(moves) // execute instructions for(move in moves) { val cratesStack = mutableListOf<String>() for(i in 1..move[0]) { cratesStack.add(crates[move[1]].removeAt(0)) } for(i in cratesStack.indices) { crates[move[2]].add(i, cratesStack[i]) } } var top = "" for(crate in crates) { top += crate[0] } return top } // test if implementation meets criteria from the description, like: val testInput = readInput("Day05_test") // println(part1(testInput)) println(part2(testInput)) val input = readInput("Day05") // output(part1(input)) output(part2(input)) }
0
Kotlin
0
0
391336623968f210a19797b44d027b05f31484b5
3,001
AdventOfCode2022
Apache License 2.0
2022/src/day03/Day03.kt
scrubskip
160,313,272
false
{"Kotlin": 198319, "Python": 114888, "Dart": 86314}
package day03 import java.io.File fun main() { val input = File("src/day03/day03input.txt").readLines() println(input.sumOf { getPriority(getDuplicateItemType(it)) }) println(input.chunked(3).sumOf { getPriority(getSharedItem(it)) }) } /** * @return the bad item type. */ fun getDuplicateItemType(input: String): Char? { // Divide string in half val part1 = input.dropLast(input.length / 2) val part2 = input.drop(input.length / 2) // Find common string return part1.find { part2.contains(it) } } /** * @return the common item between the list of string */ fun getSharedItem(input: List<String>): Char? { val letterSet = mutableMapOf<Char, Int>() var foundChar: Char? = null input.map { it.toSet() }.forEach { set -> set.forEach { char -> letterSet[char] = letterSet.getOrDefault(char, 0) + 1 if (letterSet[char] == input.size) { foundChar = char } } } return foundChar } fun getPriority(type: Char?): Int { if (type == null) return -1 return when (type) { in 'a'..'z' -> type - 'a' + 1 in 'A'..'Z' -> type - 'A' + 27 else -> -1 } }
0
Kotlin
0
0
a5b7f69b43ad02b9356d19c15ce478866e6c38a1
1,211
adventofcode
Apache License 2.0
src/main/kotlin/io/github/clechasseur/adventofcode/y2015/Day9.kt
clechasseur
568,233,589
false
{"Kotlin": 242914}
package io.github.clechasseur.adventofcode.y2015 import io.github.clechasseur.adventofcode.util.permutations import io.github.clechasseur.adventofcode.y2015.data.Day9Data object Day9 { private val input = Day9Data.input private val distRegex = """^(\w+) to (\w+) = (\d+)$""".toRegex() fun part1(): Int { val distMap = input.lines().toDistMap() return permutations(distMap.keys.toList()).minOf { path -> path.zipWithNext().sumOf { (a, b) -> distMap[a]!![b]!! } } } fun part2(): Int { val distMap = input.lines().toDistMap() return permutations(distMap.keys.toList()).maxOf { path -> path.zipWithNext().sumOf { (a, b) -> distMap[a]!![b]!! } } } private fun List<String>.toDistMap(): Map<String, Map<String, Int>> { val distMap = mutableMapOf<String, MutableMap<String, Int>>() forEach { line -> val match = distRegex.matchEntire(line) ?: error("Wrong dist line: $line") val (a, b, dist) = match.destructured distMap.addDist(a, b, dist.toInt()) } return distMap } private fun MutableMap<String, MutableMap<String, Int>>.addDist(a: String, b: String, dist: Int) { computeIfAbsent(a) { mutableMapOf() }[b] = dist computeIfAbsent(b) { mutableMapOf() }[a] = dist } }
0
Kotlin
0
0
e5a83093156cd7cd4afa41c93967a5181fd6ab80
1,363
adventofcode2015
MIT License
openrndr-kartifex/src/commonMain/kotlin/utils/Combinatorics.kt
openrndr
122,222,767
false
{"Kotlin": 2343473, "ANTLR": 9333, "GLSL": 2677, "CSS": 87}
package org.openrndr.kartifex.utils object Combinatorics { val MAX_RESULTS = 32 inline fun <reified V> permutations(values: List<V>): List<List<V>> { // if exhaustive searching is out of the question, put your trust in the RNG if (values.size > 4) { List(MAX_RESULTS) { values.shuffled() } } val result: MutableList<List<V>> = mutableListOf() val ary: Array<V> = values.toTypedArray() val c = IntArray(ary.size) var i = 0 result.add(values) while (i < ary.size) { if (c[i] < i) { swap(ary, if (i % 2 == 0) 0 else c[i], i) result.add(ary.toList()) c[i]++ i = 0 } else { c[i] = 0 i++ } } return result } fun <V> swap(ary: Array<V>, i: Int, j: Int) { val tmp = ary[i] ary[i] = ary[j] ary[j] = tmp } /** * Given a list of potential values at each index in a list, returns all possible combinations of those values. */ fun <V> combinations(paths: List<List<V>>): List<List<V>> { val count = paths.map { obj -> obj.size } .fold(1) { a, b -> a * b } if (count == 0) { return emptyList() } else if (count == 1) { return listOf(paths .map { obj -> obj.first() } ) } else if (count > MAX_RESULTS) { return (0 until MAX_RESULTS) .map { _ -> paths .map { list -> list.random() } } } val indices = IntArray(paths.size) val result = mutableListOf<List<V>>() while (indices[0] < paths.first().size) { val path = mutableListOf<V>() for (i in indices.indices) { path.add(paths[i][indices[i]]) } result.add(path) for (i in indices.indices.reversed()) { if (++indices[i] < paths[i].size) { break } else if (i > 0) { indices[i] = 0 } } } return result } }
34
Kotlin
71
808
7707b957f1c32d45f2fbff6b6a95a1a2da028493
2,326
openrndr
BSD 2-Clause FreeBSD License
src/Day12.kt
Narmo
573,031,777
false
{"Kotlin": 34749}
import java.util.* fun main() { data class Point(val x: Int, val y: Int, val elevation: Int) var startPoint: Point? = null var endPoint: Point? = null fun getPoints(input: List<String>): List<List<Point>> = input.mapIndexed { y, line -> line.mapIndexed { x, char -> val elevation = when (char) { 'S' -> 'a' 'E' -> 'z' else -> char }.code - 'a'.code val p = Point(x, y, elevation) if (char == 'S') { startPoint = p } else if (char == 'E') { endPoint = p } p } } fun getAdjacentPoints(points: List<List<Point>>, row: Int, col: Int): Set<Point> { /* ------------------- | | | | | |-1,0 | | | | | | ------------------- | | | | | 0,-1| 0,0 | 0,1 | | | | | ------------------- | | | | | | 1,0 | | | | | | ------------------- */ return listOf(Pair(1, 0), Pair(0, 1), Pair(0, -1), Pair(-1, 0)).mapNotNull { if ((row + it.first) in points.indices && (col + it.second) in points[row].indices) { points[row + it.first][col + it.second] } else { null } }.toSet() } fun getNeighbors(points: List<List<Point>>, point: Point): List<Point> = getAdjacentPoints(points, point.y, point.x).filter { it.elevation - point.elevation <= 1 } // based on this discussion: https://stackoverflow.com/questions/41789767/finding-the-shortest-path-nodes-with-breadth-first-search fun bfs(points: List<List<Point>>, start: Point): Int { var point = start var pathToPoint = mutableListOf(point) val queue: Queue<MutableList<Point>> = LinkedList() val visited = mutableSetOf<Point>() fun isVisited(point: Point): Boolean { if (visited.contains(point)) { return true } visited.add(point) return false } queue.add(pathToPoint) while (!queue.isEmpty()) { pathToPoint = queue.poll() point = pathToPoint[pathToPoint.size - 1] if (point == endPoint) { return pathToPoint.size - 1 // -1 because first point is added to path at the start } val neighbors = getNeighbors(points, point) for (nextNode in neighbors) { if (!isVisited(nextNode)) { val pathToNextNode = pathToPoint.toMutableList() pathToNextNode.add(nextNode) queue.add(pathToNextNode) } } } return Int.MAX_VALUE } fun part1(input: List<String>): Int { val points = getPoints(input) return bfs(points, startPoint ?: throw IllegalStateException("Start point not found")) } fun part2(input: List<String>): Int { val points = getPoints(input) val edgePoints = mutableSetOf<Point>() edgePoints.addAll(points.first()) edgePoints.addAll(points.last()) points.forEach { edgePoints.add(it.first()) edgePoints.add(it.last()) } return edgePoints.filter { it.elevation == 0 }.minOf { bfs(points, it) } } val testInput = readInput("Day12_test") check(part1(testInput) == 31) check(part2(testInput) == 29) val input = readInput("Day12") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
335641aa0a964692c31b15a0bedeb1cc5b2318e0
3,052
advent-of-code-2022
Apache License 2.0
numeriko-complex/src/main/kotlin/tomasvolker/numeriko/complex/transforms/fft/FunctionalFFT.kt
TomasVolker
114,266,369
false
null
package tomasvolker.numeriko.complex.transforms.fft import tomasvolker.numeriko.complex.primitives.Complex import tomasvolker.numeriko.complex.primitives.toComplex import tomasvolker.numeriko.complex.transforms.mapBoth import tomasvolker.numeriko.complex.transforms.partitionByIndex import tomasvolker.numeriko.complex.primitives.unaryDoubleComplex import tomasvolker.numeriko.core.primitives.isEven import tomasvolker.numeriko.core.primitives.modulo import kotlin.math.PI import kotlin.math.sqrt fun List<Complex>.fft() = cooleyTukey2(inverse = false).map { it / sqrt(size.toDouble()) } fun List<Complex>.ifft() = cooleyTukey2(inverse = true).map { it / sqrt(size.toDouble()) } fun List<Complex>.cooleyTukey2(inverse: Boolean = false): List<Complex> = when { size < 2 -> this size % 2 != 0 -> throw IllegalArgumentException( "The Cooley Tukey Algorithm can only operate with length of a power of two" ) else -> { val (evenFft, oddFft) = this.partitionByIndex { it.isEven() }.mapBoth { it.cooleyTukey2() } val frequency = (if(inverse) -1.0 else 1.0) * 2 * PI / size val halfSize = size / 2 List(size) { k -> evenFft[k modulo halfSize] + unaryDoubleComplex(frequency * k) * oddFft[k modulo halfSize] } } } fun <T> List<List<T>>.transposed(): List<List<T>> = List(first().size) { n2 -> List(this.size) { n1 -> this[n1][n2] } } inline fun <T> List<List<T>>.deepMapIndexed(operation: (i0: Int, i1: Int, value: T)->T): List<List<T>> = mapIndexed { i0, list -> list.mapIndexed { i1, value -> operation(i0, i1, value) } } inline fun <T> List<List<T>>.deepMap(operation: (T)->T): List<List<T>> = map { it.map(operation) } fun <T> Boolean.unfold(trueVal: T, falseVal: T) = if(this) trueVal else falseVal fun twiddle(inverse: Boolean, size: Int, exponent: Int) = unaryDoubleComplex(inverse.unfold(-1.0, 1.0) * 2 * PI / size * exponent) fun List<Complex>.cooleyTukey( inverse: Boolean = false, timeDecimation: Int = 2 ): List<Complex> = when(size) { 0, 1 -> this 2 -> listOf(this[0] + this[1], this[0] - this[1]) else -> this.chunked(timeDecimation) .transposed() .map { it.cooleyTukey(inverse) } .deepMapIndexed { n1, k2, x -> x * twiddle(inverse, size, n1 * k2) } .transposed() .map { it.cooleyTukey(inverse) } .transposed() .flatten() } inline fun <T> Iterable<T>.sumByComplex(operation: (T)-> Complex) = fold(0.0.toComplex()) { acc, next -> acc + operation(next) } fun List<Complex>.dft(inverse: Boolean) = List(size) { k -> (0 until size).sumByComplex { n -> this[n] * twiddle(inverse, size, k * n) } }
8
Kotlin
1
3
1e9d64140ec70b692b1b64ecdcd8b63cf41f97af
2,891
numeriko
Apache License 2.0
src/main/kotlin/org/sjoblomj/adventofcode/day7/Day7.kt
sjoblomj
161,537,410
false
null
package org.sjoblomj.adventofcode.day7 import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import org.sjoblomj.adventofcode.day7.visualisation.visualise import org.sjoblomj.adventofcode.readFile import kotlin.system.measureTimeMillis private const val inputFile = "src/main/resources/inputs/day7.txt" private const val numberOfWorkers = 5 private const val baseTimeTakenForEachStep = 60 fun day7() { println("== DAY 7 ==") val timeTaken = measureTimeMillis { calculateAndPrintDay7() } println("Finished Day 7 in $timeTaken ms\n") } private fun calculateAndPrintDay7() { val nodes = createNodes(readFile(inputFile)) println("Resulting order is ${orderNodes(nodes)}") val parallelizedWork = parallelize(nodes, numberOfWorkers, baseTimeTakenForEachStep) println("With parallelization, it would take ${parallelizedWork.size - 1} seconds to finish") } internal fun createNodes(input: List<String>): List<Node> { return createNodesFromInput(input) } internal fun orderNodes(nodes: List<Node>): String { val orderedNodes = mutableListOf<Node>() for (firstNode in getFirstNodes(nodes)) orderNodesRecursively(firstNode, orderedNodes) val resultingOrder = orderedNodes.joinToString("") { it.id } output(orderedNodes, resultingOrder) return resultingOrder } private fun orderNodesRecursively(node: Node, orderedNodes: MutableList<Node>) { if (allDependenciesFulfilled(node, orderedNodes) && !orderedNodes.contains(node)) { orderedNodes.add(node) for (depender in node.dependers.sortedBy { it.id }) orderNodesRecursively(depender, orderedNodes) } } private fun allDependenciesFulfilled(node: Node, finishedNodes: List<Node>) = finishedNodes.containsAll(node.prerequisites) private fun getFirstNodes(nodes: List<Node>): List<Node> { val firstNodes = nodes.filter { it.prerequisites.isEmpty() }.sortedBy { it.id } if (firstNodes.isEmpty()) throw RuntimeException("Should find node that has no dependencies") return firstNodes } internal fun parallelize(nodes: List<Node>, numberOfWorkers: Int, baseTimeTakenForEachStep: Int): List<WorkOrder> { val workers = generateAvailableWorkers(numberOfWorkers, baseTimeTakenForEachStep) return parallelize(nodes.sortedBy { it.id }, 0, workers, emptyList()).reversed() } private fun parallelize(nodes: List<Node>, iteration: Int, workers: List<Worker>, result: List<Node>): List<WorkOrder> { val nodesThatWereJustFinished = workers.filter { it.isFinished(iteration) }.mapNotNull { it.node } val finishedNodes = result.plus(nodesThatWereJustFinished) if (nodes.isEmpty() && workers.all { it.isFinished(iteration) }) return listOf(WorkOrder(generateAvailableWorkers(workers.size, workers.first().baseTimeTakenForEachStep), finishedNodes)) val newWorkerList = createNewWorkerList(nodes, finishedNodes, workers, iteration) return parallelize(getNodesNotBeingWorkedOn(newWorkerList, nodes), iteration + 1, newWorkerList, finishedNodes).plus(WorkOrder(newWorkerList, finishedNodes)) } private fun createNewWorkerList(nodes: List<Node>, finishedNodes: List<Node>, workers: List<Worker>, iteration: Int): List<Worker> { val nodesReadyForProcessing = nodes.filter { allDependenciesFulfilled(it, finishedNodes) } var nodesReadyForProcessingIndex = 0 return workers.map { if (it.isFinished(iteration)) { val node = if (nodesReadyForProcessingIndex < nodesReadyForProcessing.size) nodesReadyForProcessing[nodesReadyForProcessingIndex] else null nodesReadyForProcessingIndex++ Worker(node, iteration, it.baseTimeTakenForEachStep) } else it } } private fun getNodesNotBeingWorkedOn(newWorkerList: List<Worker>, nodes: List<Node>): List<Node> { val nodesBeingWorkedOn = newWorkerList.mapNotNull { it.node } return nodes.filter { !nodesBeingWorkedOn.contains(it) } } private fun generateAvailableWorkers(numberOfWorkers: Int, baseTimeTakenForEachStep: Int) = generateSequence { Worker(null, null, baseTimeTakenForEachStep) }.take(numberOfWorkers).toList() internal data class WorkOrder(val workers: List<Worker>, val result: List<Node>) internal data class Worker(val node: Node?, val startedAt: Int?, val baseTimeTakenForEachStep: Int) { private fun delayForJob() = if (node == null) -1 else node.id[0].toInt() - 'A'.toInt() + 1 fun isFinished(currentIteration: Int) = if (startedAt == null || node == null) true else startedAt + baseTimeTakenForEachStep + delayForJob() <= currentIteration } internal fun visualiseParallelizedWork(workOrders: List<WorkOrder>): String { val numberOfWorkers = workOrders.map { it.workers.size }.max() val workerLabels = (0 until (numberOfWorkers ?: 0)).joinToString(" ") val secondLabel = "Second" val label = "$secondLabel $workerLabels Done" val lines = workOrders.mapIndexed { index, workOrder -> val formattedIndex = index.toString().padEnd(secondLabel.length) val underWork = workOrder.workers.map { it.node?.id ?: "." } "$formattedIndex ${underWork.joinToString(" ")} ${workOrder.result.joinToString("") { it.id }}" } return label + "\n" + lines.joinToString("\n") } private fun output(nodes: List<Node>, resultingOrder: String) { GlobalScope.launch { visualise(nodes, resultingOrder) } }
0
Kotlin
0
0
80db7e7029dace244a05f7e6327accb212d369cc
5,253
adventofcode2018
MIT License
src/Day20.kt
PascalHonegger
573,052,507
false
{"Kotlin": 66208}
fun main() { class Node(val value: Long) { lateinit var previous: Node lateinit var next: Node override fun toString() = value.toString() } class MutableRingBuffer(initialItems: List<Long>) : Iterable<Node> { private var head: Node private var zero: Node val size: Int init { size = initialItems.size val nodes = initialItems.map { Node(value = it) } head = nodes.first() zero = nodes.single { it.value == 0L } nodes.forEachIndexed { index, current -> current.previous = nodes.getOrElse(index - 1) { nodes.last() } current.next = nodes.getOrElse(index + 1) { head } } } fun doMixing(node: Node) { if (node.value == 0L) return val oldPrevious = node.previous var current = node if (node.value > 0) { for (i in 0 until node.value % (size - 1)) { current = current.next } } else { for (i in 0 until (-node.value) % (size - 1)) { current = current.previous } } // Unlink node link(node.previous, node.next) // Add link at correct location if (node.value > 0) { link(node, current.next) link(current, node) } else { link(current.previous, node) link(node, current) } if (node == head) { head = oldPrevious.next } } private fun link(a: Node, b: Node) { a.next = b b.previous = a } operator fun get(index: Int): Node { val optimizedIndex = index % size var current = zero repeat(optimizedIndex) { current = current.next } return current } override operator fun iterator() = iterator { var current = head repeat(size) { yield(current) current = current.next } } override fun toString(): String = joinToString() } fun part1(input: List<String>): Long { val mutableRingBuffer = MutableRingBuffer(input.map { it.toLong() }) val initialNodes = mutableRingBuffer.toList() for (node in initialNodes) { mutableRingBuffer.doMixing(node) } return mutableRingBuffer[1_000].value + mutableRingBuffer[2_000].value + mutableRingBuffer[3_000].value } fun part2(input: List<String>): Long { val mutableRingBuffer = MutableRingBuffer(input.map { it.toLong() * 811589153L }) val initialNodes = mutableRingBuffer.toList() repeat(10) { for (node in initialNodes) { mutableRingBuffer.doMixing(node) } } return mutableRingBuffer[1_000].value + mutableRingBuffer[2_000].value + mutableRingBuffer[3_000].value } val testInput = readInput("Day20_test") check(part1(testInput) == 3L) check(part2(testInput) == 1623178306L) val input = readInput("Day20") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
2215ea22a87912012cf2b3e2da600a65b2ad55fc
3,334
advent-of-code-2022
Apache License 2.0
src/main/java/leetcode/a392_isSubSequence_HARD/Solution.kt
Laomedeia
122,696,571
true
{"Java": 801075, "Kotlin": 38473, "JavaScript": 8268}
package leetcode.a392_isSubSequence_HARD /** * 判断子序列 * * 给定字符串 s 和 t ,判断 s 是否为 t 的子序列。 * 你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。 * * 字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。 * * 示例 1: * s = "abc", t = "ahbgdc" * 返回 true. * * 示例 2: * s = "axc", t = "ahbgdc" * 返回 false. * * 后续挑战 : * 如果有大量输入的 S,称作S1, S2, ... , Sk 其中 k >= 10亿,你需要依次检查它们是否为 T 的子序列。在这种情况下,你会怎样改变代码? * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/is-subsequence * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 * @author neptune * @create 2020 07 27 9:27 下午 */ class Solution { fun isSubsequence(s: String, t: String): Boolean { if (s.length == 0) return true; var indexS = 0 var indexT = 0 while (indexT < t.length) { if (t[indexT] == s[indexS]) { //指向s的指针只有在两个字符串相同时才会往右移 indexS++; if (indexS == s.length) return true; } //指向t的指针每次都会往右移一位 indexT++; } return false } }
0
Java
0
0
0dcd8438e0846493ced9c1294ce686bac34c8614
1,661
Java8InAction
MIT License
src/Day01.kt
anoniim
572,264,555
false
{"Kotlin": 8381}
fun main() { Day1().run( 24000, 45000 ) } private class Day1 : Day(1) { override fun part1(input: List<String>): Int { // Find the Elf carrying the most Calories. How many total Calories is that Elf carrying? return parseElves(input).maxOf { it.totalCalories() } } override fun part2(input: List<String>): Int { // Find the top three Elves carrying the most Calories. How many Calories are those Elves carrying in total? return parseElves(input).map { it.totalCalories() }.sorted().takeLast(3).sum() } fun parseElves(input: List<String>): List<Elf> { val elves = mutableListOf(Elf()) input.forEach { meal -> if (meal != "") { elves.last().registerMeal(meal.toInt()) } else { // Empty line, add a new Elf elves.add(Elf()) } } return elves } } private class Elf { val meals = mutableListOf<Int>() fun registerMeal(caloriesPerItem: Int) { meals.add(caloriesPerItem) } fun totalCalories(): Int { return meals.sum() } }
0
Kotlin
0
0
15284441cf14948a5ebdf98179481b34b33e5817
1,153
Advent-of-Code-2022
Apache License 2.0
src/main/kotlin/kt/kotlinalgs/app/graph/FloydWarshall.ws.kts
sjaindl
384,471,324
false
null
package kt.kotlinalgs.app.graph println("Test") /* https://www.geeksforgeeks.org/floyd-warshall-algorithm-dp-16/ relax all intermediate nodes O(V^3) 1. create adj matrix directed weighted graph 2. for each intermediate in 0 until V for each start in 0 until V for each end in 0 until V relax if matrix[i][k] + matrix[k][j] < matrix[i][j] */ data class DirectedWeightedGraphWithAdjMatrix(val matrix: Array<IntArray>) class FloydWarshall() { fun allShortestPaths(graph: DirectedWeightedGraphWithAdjMatrix): Array<IntArray> { val matrix = graph.matrix.copyOf() val size = matrix.size for (start in 0 until size) { for (intermediate in 0 until size) { for (end in 0 until size) { if (matrix[start][intermediate] != Int.MAX_VALUE && matrix[intermediate][end] != Int.MAX_VALUE) { val curPathCost = matrix[start][intermediate] + matrix[intermediate][end] if (curPathCost < matrix[start][end]) { matrix[start][end] = curPathCost } } } } } return matrix } fun printShortestPath(matrix: Array<IntArray>, from: Int, to: Int) { println("$from -> $to: Dist ${matrix[from][to]}") } } val INF = Int.MAX_VALUE val graph = DirectedWeightedGraphWithAdjMatrix( arrayOf( intArrayOf(0, 5, INF, 10), intArrayOf(INF, 0, 3, INF), intArrayOf(INF, INF, 0, 1), intArrayOf(INF, INF, INF, 0) ) ) val floyd = FloydWarshall() floyd.allShortestPaths(graph) floyd.printShortestPath(graph.matrix, 0, 1) floyd.printShortestPath(graph.matrix, 0, 2) floyd.printShortestPath(graph.matrix, 0, 3) floyd.printShortestPath(graph.matrix, 1, 0) floyd.printShortestPath(graph.matrix, 1, 2) floyd.printShortestPath(graph.matrix, 1, 3) floyd.printShortestPath(graph.matrix, 2, 0) floyd.printShortestPath(graph.matrix, 2, 1) floyd.printShortestPath(graph.matrix, 2, 2) floyd.printShortestPath(graph.matrix, 3, 0) floyd.printShortestPath(graph.matrix, 3, 1) floyd.printShortestPath(graph.matrix, 3, 2)
0
Java
0
0
e7ae2fcd1ce8dffabecfedb893cb04ccd9bf8ba0
2,223
KotlinAlgs
MIT License
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[72]编辑距离.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给你两个单词 word1 和 word2,请你计算出将 word1 转换成 word2 所使用的最少操作数 。 // // 你可以对一个单词进行如下三种操作: // // // 插入一个字符 // 删除一个字符 // 替换一个字符 // // // // // 示例 1: // // //输入:word1 = "horse", word2 = "ros" //输出:3 //解释: //horse -> rorse (将 'h' 替换为 'r') //rorse -> rose (删除 'r') //rose -> ros (删除 'e') // // // 示例 2: // // //输入:word1 = "intention", word2 = "execution" //输出:5 //解释: //intention -> inention (删除 't') //inention -> enention (将 'i' 替换为 'e') //enention -> exention (将 'n' 替换为 'x') //exention -> exection (将 'n' 替换为 'c') //exection -> execution (插入 'u') // // // // // 提示: // // // 0 <= word1.length, word2.length <= 500 // word1 和 word2 由小写英文字母组成 // // Related Topics 字符串 动态规划 // 👍 1734 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun minDistance(word1: String, word2: String): Int { //动态规划 时间复杂度 O(mn) m n 为字符串的长度 var n = word1.length var m = word2.length //如果有一个字符串为零 if(n*m == 0 ) return n+m //动态规划路径数组 val dp = Array(n+1){IntArray(m+1)} //初始化边界路径 for (i in 0 until n+1) dp[i][0] = i for (j in 0 until m+1) dp[0][j] = j //计算路径上 dp 值 for (i in 1 until n+1){ for (j in 1 until m+1){ var left = dp[i-1][j] + 1 var down = dp[i][j-1]+1 var leftDown = dp[i-1][j-1] if(word1[i-1] != word2[j-1]){ leftDown +=1 } dp[i][j] = Math.min(left,Math.min(down,leftDown)) } } return dp[n][m] } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
2,019
MyLeetCode
Apache License 2.0
src/main/kotlin/aoc2020/ShuttleSearch.kt
komu
113,825,414
false
{"Kotlin": 395919}
package komu.adventofcode.aoc2020 import komu.adventofcode.utils.lcm fun shuttleService1(time: Long, input: String): Int { val shuttles = input.split(",").filter { it != "x" }.map { it.toInt() } val (shuttle, waitTime) = shuttles.map { it to shuttleWait(it, time) }.minByOrNull { it.second }!! return shuttle * waitTime } private fun shuttleWait(shuttle: Int, time: Long): Int = ((shuttle - time % shuttle) % shuttle).toInt() private data class ShuttleConstrains(val period: Int, val offset: Int) { fun satisfies(time: Long) = shuttleWait(period, time + offset) == 0 } fun shuttleService2(input: String): Long { var constraints = input.split(",").map { it.toIntOrNull() }.withIndex() .mapNotNull { (i, v) -> v?.let { ShuttleConstrains(it, i) } } .sortedByDescending { it.period } var delta = 1L var t = 0L var steps = 0 while (true) { steps++ if (constraints.any { it.satisfies(t) }) { val (satisfied, rest) = constraints.partition { it.satisfies(t) } delta = satisfied.fold(delta) { a, c -> lcm(a, c.period.toLong()) } constraints = rest if (constraints.isEmpty()) return t } t += delta } }
0
Kotlin
0
0
8e135f80d65d15dbbee5d2749cccbe098a1bc5d8
1,257
advent-of-code
MIT License
Contest/Weekly Contest 299/Maximum Score of Spliced Array/SplicedArray.kt
xuedong
189,745,542
false
{"Kotlin": 332182, "Java": 294218, "Python": 237866, "C++": 97190, "Rust": 82753, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65}
class Solution { fun maximumsSplicedArray(nums1: IntArray, nums2: IntArray): Int { val n = nums1.size if (n == 1) return maxOf(nums1[0], nums2[0]) val prefixes1 = IntArray(n) { 0 } var prefix1 = 0 for (i in 0..n-1) { prefix1 += nums1[i] prefixes1[i] = prefix1 } val prefixes2 = IntArray(n) { 0 } var prefix2 = 0 for (i in 0..n-1) { prefix2 += nums2[i] prefixes2[i] = prefix2 } var ans1 = 0 var curr1 = 0 var j = -1 for (i in 0..n-1) { if (curr1 + nums1[i] - nums2[i] > 0) { j = i curr1 = 0 } else { if (j == -1) { ans1 = prefixes2[i] + prefixes1[n-1] - prefixes1[i] } else { ans1 = maxOf(ans1, prefixes2[i] - prefixes2[j] + prefixes1[n-1] - (prefixes1[i] - prefixes1[j])) } curr1 += nums1[i] - nums2[i] } } var ans2 = 0 var curr2 = 0 j = -1 for (i in 0..n-1) { if (curr2 + nums2[i] - nums1[i] > 0) { j = i curr2 = 0 } else { if (j == -1) { ans2 = prefixes1[i] + prefixes2[n-1] - prefixes2[i] } else { ans2 = maxOf(ans2, prefixes1[i] - prefixes1[j] + prefixes2[n-1] - (prefixes2[i] - prefixes2[j])) } curr2 += nums2[i] - nums1[i] } } return maxOf(ans1, ans2) } }
0
Kotlin
0
1
5e919965b43917eeee15e4bff12a0b6bea4fd0e7
1,635
leet-code
MIT License
src/Day01.kt
gsalinaslopez
572,839,981
false
{"Kotlin": 21439}
fun main() { fun part1(input: List<String>): Int { var currentElf = 0 var maxElf = -1 input.forEach { if (it.isEmpty()) { maxElf = maxOf(maxElf, currentElf) currentElf = 0 } else { currentElf += it.toInt() } } return maxElf } fun part2(input: List<String>): Int { val elfRations = mutableListOf<Int>() var currentElf = 0 input.forEach { if (it.isEmpty()) { elfRations.add(currentElf) currentElf = 0 } else { currentElf += it.toInt() } } return elfRations.sorted().reversed().subList(0, 3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
041c7c3716bfdfdf4cc89975937fa297ea061830
1,011
aoc-2022-in-kotlin
Apache License 2.0
solutions/qualifications/reverse-sort/src/main/kotlin/solutions.reverse.sort/ReverseSortSolution.kt
Lysoun
351,224,145
false
null
fun main(args: Array<String>) { val casesNumber = readLine()!!.toInt() for (i in 1..casesNumber) { // Ignore first line of case readLine() println("Case #$i: ${computeReverseCostToSortList(readLine()!!.split(" ").map { it.toInt() })}") } } fun computeReverseCostToSortList(numbers: List<Int>): Int { var totalCost = 0 var currentList = numbers for (i in 0 until (numbers.size - 1) ) { val result = reverseAndComputeCost(currentList, i) currentList = result.first totalCost += result.second } return totalCost } fun reverseAndComputeCost(numbers: List<Int>, startingIndex: Int): Pair<List<Int>, Int> { val smallestNumberPosition = numbers.subList(startingIndex, numbers.size) .mapIndexed { index, i -> index to i } .minByOrNull { it.second }!! .first if (smallestNumberPosition == 0) { return numbers to 1 } return ( numbers.subList(0, startingIndex) + numbers.subList(startingIndex, smallestNumberPosition + startingIndex + 1).reversed() + numbers.subList(smallestNumberPosition + startingIndex + 1, numbers.size) ) to smallestNumberPosition + 1 }
0
Kotlin
0
0
98d39fcab3c8898bfdc2c6875006edcf759feddd
1,245
google-code-jam-2021
MIT License
kotlin/src/2023/Day04_2023.kt
regob
575,917,627
false
{"Kotlin": 50757, "Python": 46520, "Shell": 430}
private fun parseItems(s: String): List<Int> { return s.trim().replace(Regex("\\s+"), " ").split(" ").map {it.toInt()} } fun main() { val input = readInput(4, 2023) val gamePat = Regex("Card\\s+([0-9]+): (.*) \\| (.*)") val games = input.trim().split("\n") .map {gamePat.matchEntire(it)!!.groupValues} .map {parseItems(it[2]).toSet() to parseItems(it[3]).toSet()} games.asSequence() .map {it.first.intersect(it.second).size} .sumOf {if (it == 0) 0 else 1 shl (it - 1)} .also {println("Part 1: $it")} val cnt = MutableList(games.size) {1} for (i in cnt.indices) { val win = games[i].first.intersect(games[i].second).size for (j in (i + 1)..(i + win)) { cnt[j] += cnt[i] } } println("Part 2: ${cnt.sum()}") }
0
Kotlin
0
0
cf49abe24c1242e23e96719cc71ed471e77b3154
826
adventofcode
Apache License 2.0
src/2022/Day03.kt
nagyjani
572,361,168
false
{"Kotlin": 369497}
package `2022` import java.io.File import java.util.* fun main() { Day03().solve() } class Day03 { val input1 = """ vJrwpWtwJgWrhcsFMMfFFhFp jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL PmmdzqPrVvPwwTWBwg wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn ttgJtRGJQctTZtZT CrZsJsPPZsGzwwsLwLmpwMDw """.trimIndent() fun prio(c: Char): Int { val p1 = c-'a'+1 val p2 = c-'A'+27 if (p1 > 0 && p1 < 27) { return p1 } return p2 } fun solve() { val f = File("src/2022/inputs/day03.in") val s = Scanner(f) // val s = Scanner(input1) val backpacks = mutableListOf<String>() while (s.hasNextLine()) { backpacks.add(s.nextLine().trim()) } val sum1 = backpacks.map { val h1 = it.subSequence(0, it.length/2) val h2 = it.subSequence(it.length/2, it.length) val intersect = h1.toSet().intersect(h2.toSet()) val prio = intersect.sumOf { prio(it) } // val prio = h1.toSet().intersect(h2.toSet()).sumOf { prio(it) } // println("'$it' ${it.length} $h1 $h2 $intersect $prio") prio }.sum() val sum2 = backpacks.windowed(3, step = 3){ val badge = it[0].toSet().intersect(it[1].toSet()).intersect(it[2].toSet()) println("$badge ${prio(badge.first())}") prio(badge.first()) }.sum() println("$backpacks\n$sum1 $sum2") } }
0
Kotlin
0
0
f0c61c787e4f0b83b69ed0cde3117aed3ae918a5
1,478
advent-of-code
Apache License 2.0
app/src/y2021/day08/Day08WithoutAnalyzingIndividualSegments.kt
henningBunk
432,858,990
false
{"Kotlin": 124495}
package y2021.day08 import common.Answers import common.AocSolution import common.annotations.AoCPuzzle import java.util.* /** * A way nicer solution. * run it by using the main method in the other class */ @AoCPuzzle(2021, 8) class Day08WithoutAnalyzingIndividualSegments : AocSolution { override val answers = Answers(samplePart1 = 26, samplePart2 = 61229, part1 = 512, part2 = 1091165) override fun solvePart1(input: List<String>): Any { TODO("Only part 2 is implemented") } override fun solvePart2(input: List<String>): Any = input.sumOf { line -> line.split(" | ").let { (left, right) -> val codes = left.split(" ").map { it.toSortedSet() }.toMutableSet() val decoded: MutableMap<Int, Set<Char>> = mutableMapOf() with(decoded) { put(1, codes.singleAndRemove(segments = 2)) put(4, codes.singleAndRemove(segments = 4)) put(7, codes.singleAndRemove(segments = 3)) put(8, codes.singleAndRemove(segments = 7)) put(9, codes.singleAndRemove(segments = 6, containsAllSegments = getValue(4))) put(0, codes.singleAndRemove(segments = 6, containsAllSegments = getValue(7))) put(6, codes.singleAndRemove(segments = 6)) put(3, codes.singleAndRemove(segments = 5, containsAllSegments = getValue(1))) put(5, codes.singleAndRemove(segments = 5, containsAllSegments = getValue(4) - getValue(1))) put(2, codes.single()) } right .split(" ") .map { digit -> decoded.filterValues { it == digit.toSortedSet() }.keys.single() } .joinToString("") .toInt() } } private fun MutableSet<SortedSet<Char>>.singleAndRemove( segments: Int, containsAllSegments: Set<Char>? = null ): Set<Char> = single { it.size == segments && it.containsAll(containsAllSegments ?: emptySet()) }.also { this.remove(it) } }
0
Kotlin
0
0
94235f97c436f434561a09272642911c5588560d
2,056
advent-of-code-2021
Apache License 2.0
src/main/kotlin/Day19.kt
Yeah69
317,335,309
false
{"Kotlin": 73241}
class Day19 : Day() { override val label: String get() = "19" private interface Rule { fun buildRegexString(): String } private class EmptyRule : Rule { override fun buildRegexString() = "" } private class CharRule(val char: Char) : Rule { override fun buildRegexString() = char.toString() } private class SpecialRuleZero(val fortyTwo: Rule, val thirtyOne: Rule) : Rule { override fun buildRegexString() = "(${fortyTwo.buildRegexString()})+(${thirtyOne.buildRegexString()})+" } private class CompositeRule(val ruleLists: List<List<Rule>>) : Rule { override fun buildRegexString(): String { val text = ruleLists .map { it.map { rule -> rule.buildRegexString() }.joinToString("") } .joinToString("|") return if(ruleLists.count() > 1) "($text)" else text } } private class RuleHolder : Rule { var innerRule: Rule = EmptyRule() override fun buildRegexString() = innerRule.buildRegexString() } private val rules by lazy { val textMap = input .lineSequence() .takeWhile { it.contains(':') } .map { val split = it.split(':') split[0].trim().toInt() to split[1].trim() } .toMap() val holderMap = textMap .map { it.key to RuleHolder() } .toMap() for(entry in textMap) { val ruleLists = entry .value .splitToSequence('|') .map { list -> list .trim() .splitToSequence(' ') .map { it.replace("\"", "") } .map { if (it.length == 1 && it[0].isLetter()) CharRule(it[0]) else holderMap[it.toInt()] ?: throw Exception() } .toList() } .toList() holderMap[entry.key]?.innerRule = CompositeRule(ruleLists) } holderMap } private val ruleZero by lazy { (rules[0]?.innerRule?.buildRegexString() ?: throw Exception()).toRegex() } private val ruleOne by lazy { Triple( SpecialRuleZero(rules[42]!!, rules[31]!!).buildRegexString().toRegex(), rules[42]?.innerRule?.buildRegexString()?.toRegex() ?: throw Exception(), rules[31]?.innerRule?.buildRegexString()?.toRegex() ?: throw Exception()) } private val messages by lazy { input .lineSequence() .dropWhile { it.contains(':') || it.isBlank() } .toList() } fun logic(regex: Regex, predicate: (MatchResult) -> Boolean): String = messages .asSequence() .mapNotNull(regex::matchEntire) .filter(predicate) .count() .toString() override fun taskZeroLogic(): String = logic(ruleZero) { true } override fun taskOneLogic(): String = logic(ruleOne.first) { fun String.getCountAndRest(regex: Regex): Pair<Int, String> { var text = this var count = 0 while (true) { val find = regex.find(text) if (find == null || find.range.first != 0) break text = text.removeRange(find.range) count++ } return count to text } val (fortyTwo, rest) = it.value.getCountAndRest(ruleOne.second) val (thirtyOne, _) = rest.getCountAndRest(ruleOne.third) fortyTwo > thirtyOne } }
0
Kotlin
0
0
23121ede8e3e8fc7aa1e8619b9ce425b9b2397ec
3,548
AdventOfCodeKotlin
The Unlicense
src/main/kotlin/dev/shtanko/algorithms/leetcode/NumberOfProvinces.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.LinkedList import java.util.Queue /** * 547. Number of Provinces * @see <a href="https://leetcode.com/problems/number-of-provinces/">Source</a> */ fun interface NumberOfProvinces { fun findCircleNum(isConnected: Array<IntArray>): Int } /** * Approach 1: Depth First Search */ class NumberOfProvincesDFS : NumberOfProvinces { override fun findCircleNum(isConnected: Array<IntArray>): Int { val n: Int = isConnected.size var numberOfComponents = 0 val visit = BooleanArray(n) for (i in 0 until n) { if (!visit[i]) { numberOfComponents++ dfs(i, isConnected, visit) } } return numberOfComponents } private fun dfs(node: Int, isConnected: Array<IntArray>, visit: BooleanArray) { visit[node] = true for (i in isConnected.indices) { if (isConnected[node][i] == 1 && !visit[i]) { dfs(i, isConnected, visit) } } } } /** * Approach 2: Breadth First Search */ class NumberOfProvincesBFS : NumberOfProvinces { override fun findCircleNum(isConnected: Array<IntArray>): Int { val n: Int = isConnected.size var numberOfComponents = 0 val visit = BooleanArray(n) for (i in 0 until n) { if (!visit[i]) { numberOfComponents++ bfs(i, isConnected, visit) } } return numberOfComponents } private fun bfs(node: Int, isConnected: Array<IntArray>, visit: BooleanArray) { var n = node val q: Queue<Int> = LinkedList() q.offer(n) visit[n] = true while (q.isNotEmpty()) { n = q.poll() for (i in isConnected.indices) { if (isConnected[n][i] == 1 && !visit[i]) { q.offer(i) visit[i] = true } } } } } /** * Approach 3: Union-find */ class NumberOfProvincesUnionFind : NumberOfProvinces { override fun findCircleNum(isConnected: Array<IntArray>): Int { val n: Int = isConnected.size val dsu = UnionFind(n) var numberOfComponents = n for (i in 0 until n) { for (j in i + 1 until n) { if (isConnected[i][j] == 1 && dsu.find(i) != dsu.find(j)) { numberOfComponents-- dsu.unionSet(i, j) } } } return numberOfComponents } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,184
kotlab
Apache License 2.0
aoc-kotlin/src/main/kotlin/day05/Day05.kt
mahpgnaohhnim
573,579,334
false
{"Kotlin": 29246, "TypeScript": 1975, "Go": 1693, "Rust": 1520, "JavaScript": 123}
package day05 import java.io.File class Day05 { companion object { fun getResultText(inputText: String, part2: Boolean = false): String { val parts = inputText.split("\n\n") val data = parseData(parts[0]) executeCommands(parts[1], data, part2) return data.map { when { it.isEmpty() -> "" else -> it.last() } }.joinToString("") } fun parseData(input: String): List<MutableList<String>> { val lines = input.lines().asReversed().toMutableList() val data = getEmptyDataByBaseLine(lines[0]) lines.removeFirst() lines.map { parseDateLine(it, data) } return data } fun parseDateLine(line: String, data: List<MutableList<String>>) { val pattern = "(\\[)|(])".toRegex() val chunks = line.chunked(4).map { it.replace(pattern, "").trim() } chunks.forEachIndexed { index, chunk -> val dataGroup = data[index] if (chunk.isNotBlank()) { dataGroup.add(chunk) } } } fun getEmptyDataByBaseLine(baseLine: String): List<MutableList<String>> { val chunks = baseLine.chunked(4) return chunks.map { mutableListOf() } } fun executeCommands(commandsPart: String, data: List<MutableList<String>>, part2: Boolean) { commandsPart.lines().forEach { line -> val match = Regex("move (\\d+) from (\\d+) to (\\d+)").find(line) if (match != null) { val (count, fromGroupId, targetGroupId) = match.destructured val fromGroup = data[fromGroupId.toInt() - 1] val targetGroup = data[targetGroupId.toInt() - 1] if (part2) { val groupData = fromGroup.takeLast(count.toInt()) targetGroup.addAll(groupData) repeat(count.toInt()) { fromGroup.removeLast() } } else { repeat(count.toInt()) { targetGroup.add(fromGroup.last()) fromGroup.removeLast() } } } } } } } fun main() { val inputFile = File(Day05::class.java.getResource("input.txt")?.path.orEmpty()) val resultPart1 = Day05.getResultText(inputFile.readText()) val resultPart2 = Day05.getResultText(inputFile.readText(), true) println( """ resultPart1: $resultPart1 resultPart2: $resultPart2 """.trimIndent() ) }
0
Kotlin
0
0
c514152e9e2f0047514383fe536f7610a66aff70
2,851
aoc-2022
MIT License
src/main/kotlin/g0501_0600/s0576_out_of_boundary_paths/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0501_0600.s0576_out_of_boundary_paths // #Medium #Dynamic_Programming #2023_01_23_Time_153_ms_(100.00%)_Space_34.7_MB_(80.00%) class Solution { private val dRowCol = arrayOf(intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(0, 1), intArrayOf(0, -1)) private fun dfs( m: Int, n: Int, remainingMoves: Int, currRow: Int, currCol: Int, cache: Array<Array<IntArray>> ): Int { if (currRow < 0 || currRow == m || currCol < 0 || currCol == n) { return 1 } if (remainingMoves == 0) { return 0 } if (cache[currRow][currCol][remainingMoves] == -1) { var paths = 0 for (i in 0..3) { val newRow = currRow + dRowCol[i][0] val newCol = currCol + dRowCol[i][1] val m1 = 1000000007 paths = (paths + dfs(m, n, remainingMoves - 1, newRow, newCol, cache)) % m1 } cache[currRow][currCol][remainingMoves] = paths } return cache[currRow][currCol][remainingMoves] } fun findPaths(m: Int, n: Int, maxMoves: Int, startRow: Int, startCol: Int): Int { val cache = Array(m) { Array(n) { IntArray( maxMoves + 1 ) } } for (c1 in cache) { for (c2 in c1) { c2.fill(-1) } } return dfs(m, n, maxMoves, startRow, startCol, cache) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,528
LeetCode-in-Kotlin
MIT License
src/main/kotlin/g1201_1300/s1300_sum_of_mutated_array_closest_to_target/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1201_1300.s1300_sum_of_mutated_array_closest_to_target // #Medium #Array #Sorting #Binary_Search #Binary_Search_II_Day_16 // #2023_06_08_Time_217_ms_(100.00%)_Space_38.8_MB_(100.00%) class Solution { fun findBestValue(arr: IntArray, target: Int): Int { arr.sort() val n = arr.size var lo = 0 var hi = arr[n - 1] var min = Int.MAX_VALUE var ans = -1 while (lo <= hi) { val mid = (lo + hi) / 2 val m = check(mid, arr, target) val l = check(mid - 1, arr, target) val r = check(mid + 1, arr, target) if (m < min || m == min && ans > mid) { min = m ans = mid } else if (l <= r) { hi = mid - 1 } else { lo = mid + 1 } } return ans } fun check(v: Int, arr: IntArray, target: Int): Int { var sum = 0 for (i in arr.indices) { sum += if (arr[i] >= v) { return Math.abs(sum + (arr.size - i) * v - target) } else { arr[i] } } return Math.abs(sum - target) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,208
LeetCode-in-Kotlin
MIT License
src/day16/d16_2.kt
svorcmar
720,683,913
false
{"Kotlin": 49110}
fun main() { val input = "" val tickerTape = mapOf( "children" to 3, "cats" to 7, "samoyeds" to 2, "pomeranians" to 3, "akitas" to 0, "vizslas" to 0, "goldfish" to 5, "trees" to 3, "cars" to 2, "perfumes" to 1 ) println(input.lines().map { parseAunt(it + ",") }.filter { it.matches(tickerTape) }.first().index) } fun parseAunt(s: String): Aunt { return s.split(" ").let { Aunt(it[1].dropLast(1).toInt(), it.drop(2).chunked(2).map { p -> p[0].dropLast(1) to p[1].dropLast(1).toInt() }.toMap()) } } data class Aunt(val index: Int, val props: Map<String, Int>) { fun matches(tickerTape: Map<String, Int>): Boolean = tickerTape.all { (k, prop) -> (props[k] ?: prop) == prop } }
0
Kotlin
0
0
cb097b59295b2ec76cc0845ee6674f1683c3c91f
800
aoc2015
MIT License
src/main/kotlin/dec8/Main.kt
dladukedev
318,188,745
false
null
package dec8 sealed class Instruction { object Noop : Instruction() data class Jump(val distance: Int) : Instruction() data class Accumulate(val amount: Int) : Instruction() } data class State( val accumulator: Int = 0, val pointer: Int = 0, val calledInstructions: List<Int> = emptyList() ) fun reduce(action: Instruction, state: State): State = when (action) { Instruction.Noop -> { state.copy(pointer = state.pointer + 1, calledInstructions = state.calledInstructions + state.pointer) } is Instruction.Jump -> { state.copy( pointer = state.pointer + action.distance, calledInstructions = state.calledInstructions + state.pointer ) } is Instruction.Accumulate -> { state.copy( pointer = state.pointer + 1, accumulator = state.accumulator + action.amount, calledInstructions = state.calledInstructions + state.pointer ) } } fun toInstruction(input: String): Instruction { val (instruction, count) = input.split(" ") return when (instruction) { "acc" -> Instruction.Accumulate(count.toInt()) "jmp" -> Instruction.Jump(count.toInt()) "nop" -> Instruction.Noop else -> throw Exception("Unknown Instruction: $instruction") } } tailrec fun evaluate(instructions: List<Instruction>, state: State = State()): Int { if (state.calledInstructions.contains(state.pointer)) { println("End Infinite Loop") return state.accumulator } if(state.pointer >= instructions.count()) { println("Pointer ${state.pointer} exceeded instruction bounds ${instructions.count() -1}") return state.accumulator } val newState = reduce(instructions[state.pointer], state) println(newState.pointer) return evaluate(instructions, newState) } fun main() { println("------------ PART 1 ------------") val instructions = input.map { toInstruction(it) } val result = evaluate(instructions) println("result: $result") println("------------ PART 2 ------------") val instructions2 = input2.map { toInstruction(it) } val result2 = evaluate(instructions2) println("result: $result2") }
0
Kotlin
0
0
d4591312ddd1586dec6acecd285ac311db176f45
2,315
advent-of-code-2020
MIT License
advent-of-code-2020/src/test/java/aoc/Day13ShuttleSearch.kt
yuriykulikov
159,951,728
false
{"Kotlin": 1666784, "Rust": 33275}
package aoc import org.assertj.core.api.Assertions.assertThat import org.junit.Test import kotlin.math.abs class Day13ShuttleSearch { @Test fun silverTest() { assertThat(calculateWaitTime(testInput)).isEqualTo(295) } @Test fun silver() { assertThat(calculateWaitTime(taskInput)).isEqualTo(259) } private fun calculateWaitTime(input: String): Int { val now = input.lines().first().toInt() val busses = input.lines() .last() .split(',') .filterNot { it == "x" } .map { it.toInt() } // What is the ID of the earliest bus you can take to the airport // multiplied by the number of minutes // you'll need to wait for that bus? return busses.map { id -> id to abs(now - ((now.div(id) + 1) * id)) } .minByOrNull { (id, wait) -> wait }!! .let { it.first * it.second } } // inputs are primes @Test fun checkUsingMaxStep() { val busses = testInput.lines() .last() .split(',') .map { it.toIntOrNull() ?: 0 } // first bus is an exact match // 1x, 2x, 3x // second is off by one, so... timestamps are: // 1y + 1, 2y + 1, 3y + 1 val (maxPer, index) = busses.mapIndexed { index, period -> period to index } .maxByOrNull { (period, index) -> period }!! val periods: List<Pair<Int, Int>> = busses.mapIndexedNotNull { index, period -> if (period == 0) null else period to index } val first = generateSequence(0L) { it + 1 } // this can be optimized, period can be increased every time next bus is added // but i don't really want to do that :) .map { iter -> (iter * maxPer - index) } .filter { ts -> periods.all { (period, index) -> (ts + index).rem(period.toLong()) == 0L } } .first { stamp -> isMagicTimestamp(stamp, busses) } assertThat(first).isEqualTo(1068781L) } @Test fun gold() { val busses = taskInput.lines() .last() .split(',') .map { it.toIntOrNull() ?: 0 } val periods: List<Pair<Int, Int>> = busses.mapIndexedNotNull { index, period -> if (period == 0) null else period to index } periods.forEach { println(it) } } @Test fun generateEquationsForWolframAlpha() { val letters = ('a'..'z').minus('e').iterator() val equations = taskInput.lines() .last() .split(',') .mapIndexedNotNull { index, period -> if (period == "x") null else "$period${letters.next()}-$index=t" } .joinToString() assertThat(equations).isEqualTo("19a-0=t, 41b-9=t, 523c-19=t, 17d-36=t, 13f-37=t, 29g-48=t, 853h-50=t, 37i-56=t, 23j-73=t") // we need the first integer solution for t // 210612924879242 well done wolfram } private fun isMagicTimestamp(timestamp: Long, busses: List<Int>): Boolean { return busses.mapIndexedNotNull { index, period -> if (period == 0) { null } else { (timestamp + index).rem(period) } }.all { it == 0L } } private val testInput = """ 939 7,13,x,x,59,x,31,19 """.trimIndent() private val taskInput = """ 1000510 19,x,x,x,x,x,x,x,x,41,x,x,x,x,x,x,x,x,x,523,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,17,13,x,x,x,x,x,x,x,x,x,x,29,x,853,x,x,x,x,x,37,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,23 """.trimIndent() }
0
Kotlin
0
1
f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3
3,715
advent-of-code
MIT License
2023/src/main/kotlin/net/daams/solutions/9a.kt
Michiel-Daams
573,040,288
false
{"Kotlin": 39925, "Nim": 34690}
package net.daams.solutions import net.daams.Solution class `9a`(input: String): Solution(input) { override fun run() { val valueHistories = input.split("\n").map { history -> history.split(" ").map { it.toInt() }.toMutableList() }.toMutableList() val valuePredictions = valueHistories.map { mutableListOf(it) }.toMutableList() valuePredictions.forEach {prediction -> while (!(prediction.any{ steps -> steps.all{ it == 0 }})){ prediction.add(getStepDistances(prediction.last())) } } var sumOfEvaluations = 0 valuePredictions.forEach { sumOfEvaluations += extend(it)[0].last() } println(sumOfEvaluations) } fun extend (prediction: MutableList<MutableList<Int>>): List<List<Int>> { var prevStep = 0 for (i in prediction.lastIndex downTo 0) { prevStep += prediction[i].last() prediction[i].add(prevStep) } return prediction } } fun getStepDistances(history: List<Int>): MutableList<Int> { val steps = mutableListOf<Int>() var prevStep = history[0] for (i in 1 .. history.lastIndex) { steps.add((history[i] - prevStep)) prevStep = history[i] } return steps }
0
Kotlin
0
0
f7b2e020f23ec0e5ecaeb97885f6521f7a903238
1,286
advent-of-code
MIT License
facebook/y2020/qual/d1.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package facebook.y2020.qual private fun solve(): Long { val (n, m) = readInts() val c = List(n) { readInt() } val a = mutableListOf(m to 0L) var low = 0 val inf = c.fold(0L, Long::plus) + 1 for (i in c.indices) { while (a[low].first < i) low++ val cost = a[low].second if (i == n - 1) return cost.takeIf { it < inf } ?: -1L val costI = if (i == 0) 0L else c[i].toLong().takeIf { it > 0 } ?: inf val new = i + m to cost + costI while ((low < a.size) && (a.last().second >= new.second)) a.pop() a.add(new) } error("") } fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") } private fun <T> MutableList<T>.pop() = removeAt(lastIndex) 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
859
competitions
The Unlicense
07/part_two.kt
ivanilos
433,620,308
false
{"Kotlin": 97993}
import java.io.File import kotlin.math.* fun readInput() : List<Int> { return File("input.txt") .readLines() .flatMap { it.split(",") } .map { it.toInt() } } fun movementCost(positions : List<Int>, finalPos : Int) : Int { var result = 0 for (position in positions) { val dist = abs(position - finalPos) result += ((1 + dist) * dist) / 2 } return result } /* The optimal real valued position is at max 0.5 away from the mean so it is sufficient to calc for floor(mean) and ceil(mean) when the mean is not an integer https://www.reddit.com/r/adventofcode/comments/rawxad/2021_day_7_part_2_i_wrote_a_paper_on_todays/ */ fun solve(positions : List<Int>) : Int { val meanFloor = positions.sum() / positions.size return min(movementCost(positions, meanFloor), movementCost(positions, meanFloor + 1)) } fun main() { val positions = readInput() val ans = solve(positions) println(ans) }
0
Kotlin
0
3
a24b6f7e8968e513767dfd7e21b935f9fdfb6d72
998
advent-of-code-2021
MIT License
day12/src/main/kotlin/Main.kt
rstockbridge
159,586,951
false
null
import java.io.File fun main() { val rawInput = readInputFile() val initialState = getInitialState(rawInput) val plantGeneratingPatterns = getPlantGeneratingPatterns(rawInput) println("Part I: the solution is ${solvePartI(initialState, plantGeneratingPatterns)}.") println("Part II: the solution is ${solvePartII(initialState, plantGeneratingPatterns)}.") } fun readInputFile(): List<String> { return File(ClassLoader.getSystemResource("input.txt").file).readLines() } fun getInitialState(input: List<String>): String { return input[0].replace("initial state: ".toRegex(), "") } fun getPlantGeneratingPatterns(input: List<String>): Set<String> { val shortenedInput = input.toMutableList() // remove first two lines shortenedInput.removeAt(0) shortenedInput.removeAt(0) val result = mutableSetOf<String>() for (line in shortenedInput) { val noteRegex = "([.#]{5}) => ([.#])".toRegex() val (noteLeft, noteRight) = noteRegex.matchEntire(line)!!.destructured if (noteRight == "#") { result.add(noteLeft) } } return result } fun solvePartI(initialState: String, plantGeneratingPatterns: Set<String>): Int { var currentState = initialState var indexOfLeftPot = 0 for (generation in 1..20) { // add only necessary "." at the front when (getFirstPlantIndex(currentState)) { 0 -> { currentState = "....$currentState" indexOfLeftPot -= 4 } 1 -> { currentState = "...$currentState" indexOfLeftPot -= 3 } 2 -> { currentState = "..$currentState" indexOfLeftPot -= 2 } 3 -> { currentState = ".$currentState" indexOfLeftPot -= 1 } } // add only necessary "." at the end when (getLastPlantIndex(currentState)) { currentState.length - 1 -> currentState = "$currentState...." currentState.length - 2 -> currentState = "$currentState..." currentState.length - 3 -> currentState = "$currentState.." currentState.length - 4 -> currentState = "$currentState." } var nextState = currentState var neighborsOfCurrentPot = currentState.substring(0, 5) for (currentPot in 2 until currentState.length - 2) { if (currentPot > 2) { neighborsOfCurrentPot = neighborsOfCurrentPot.substring(1) + currentState[currentPot + 2] } nextState = if (neighborsOfCurrentPot in plantGeneratingPatterns) { nextState.replaceRange(currentPot..currentPot, "#") } else { nextState.replaceRange(currentPot..currentPot, ".") } } currentState = nextState } return calculateSumOfPotNumbers(currentState, indexOfLeftPot) } fun solvePartII(initialState: String, plantGeneratingPatterns: Set<String>): Long { val generationsToReachSteadyState = 125 // determined by inspection var currentState = initialState var indexOfLeftPot = 0 for (generation in 1..generationsToReachSteadyState) { // add only necessary "." at the front when (getFirstPlantIndex(currentState)) { 0 -> { currentState = "....$currentState" indexOfLeftPot -= 4 } 1 -> { currentState = "...$currentState" indexOfLeftPot -= 3 } 2 -> { currentState = "..$currentState" indexOfLeftPot -= 2 } 3 -> { currentState = ".$currentState" indexOfLeftPot -= 1 } } // add only necessary "." at the end when (getLastPlantIndex(currentState)) { currentState.length - 1 -> currentState = "$currentState...." currentState.length - 2 -> currentState = "$currentState..." currentState.length - 3 -> currentState = "$currentState.." currentState.length - 4 -> currentState = "$currentState." } var nextState = currentState var neighborsOfCurrentPot = currentState.substring(0, 5) for (currentPot in 2 until currentState.length - 2) { if (currentPot > 2) { neighborsOfCurrentPot = neighborsOfCurrentPot.substring(1) + currentState[currentPot + 2] } nextState = if (plantGeneratingPatterns.contains(neighborsOfCurrentPot)) { nextState.replaceRange(currentPot..currentPot, "#") } else { nextState.replaceRange(currentPot..currentPot, ".") } } currentState = nextState } // after 125 generations, the sum of pot numbers increases by fixed amount of 109 each generation // (determined by inspection) return calculateSumOfPotNumbers(currentState, indexOfLeftPot) + (50000000000 - generationsToReachSteadyState) * 109 } fun getFirstPlantIndex(state: String): Int { var result = 0 while (state[result] != '#') { result++ } return result } fun getLastPlantIndex(state: String): Int { var result = state.length - 1 while (state[result] != '#') { result-- } return result } fun calculateSumOfPotNumbers(state: String, offset: Int): Int { var result = 0 for (pot in 0 until state.length) { if (state[pot] == '#') { result += pot + offset } } return result }
0
Kotlin
0
0
c404f1c47c9dee266b2330ecae98471e19056549
5,659
AdventOfCode2018
MIT License
src/Day11.kt
timhillgit
572,354,733
false
{"Kotlin": 69577}
import java.util.PriorityQueue fun <T> Iterable<T>.split(n: Int): Pair<List<T>, List<T>> { val iter = iterator() val head = iter.asSequence().take(n).toList() val tail = iter.asSequence().toList() return head to tail } fun <T: Comparable<T>> Iterable<T>.nLargest(n: Int): List<T> { val (head, tail) = split(n) val queue = PriorityQueue(head) tail.forEach { element -> if (element > queue.element()) { queue.poll() queue.add(element) } } return queue.toList() } tailrec fun gcd(a: Long, b: Long): Long = if (b == 0L) { a } else { gcd(b, a % b) } fun Iterable<Long>.gcd(): Long = reduceOrNull(::gcd) ?: 0 fun lcm(a: Long, b: Long): Long = a / gcd(a, b) * b fun Iterable<Long>.lcm(): Long = reduceOrNull(::lcm) ?: 0 fun Iterable<Long>.product() = fold(1L) { acc, elt -> acc * elt } fun <T> ArrayDeque<T>.exhaust( action: (T) -> Unit ) { while (isNotEmpty()) { action(removeFirst()) } } fun <T> identity(x: T): T = x class Monkey( items: List<Long>, operator: String, operand: String, val divisor: Long, val relaxFactor: Long ) { val items = ArrayDeque(items) val inspection: (Long) -> Long = when (operator) { "+" -> if (operand == "old") { { it + it } } else { { it + operand.toLong() } } "*" -> if (operand == "old") { { it * it } } else { { it * operand.toLong() } } else -> ::identity } lateinit var trueMonkey: Monkey lateinit var falseMonkey: Monkey var maximumWorry = 0L var inspections = 0L fun takeTurn() { items.exhaust { // Inspect item var item = inspection(it) inspections++ // Reduce worry if (relaxFactor > 1) { item /= relaxFactor } else if (maximumWorry > 0) { item %= maximumWorry } // Throw item val recipient = if (item % divisor == 0L) { trueMonkey } else { falseMonkey } recipient.items.addLast(item) } } companion object { val REGEX = Regex( """Monkey (\d+): Starting items:((?: \d+)(?:, \d+)*)? Operation: new = old (\+|\*) (old|\d+) Test: divisible by (\d+) If true: throw to monkey (\d+) If false: throw to monkey (\d+)""" ) } } fun createMonkeys( descriptions: List<String>, relaxFactor: Long ): List<Monkey> { val (monkeys, receivers) = descriptions.mapIndexed { index, description -> val (monkeyNumber, itemList, operator, operand, divisor, trueMonkey, falseMonkey) = Monkey.REGEX.matchEntire(description)!!.destructured assert(monkeyNumber.toInt() == index) val monkey = Monkey( itemList.trim().split(", ").map(String::toLong), operator, operand, divisor.toLong(), relaxFactor ) monkey to (trueMonkey.toInt() to falseMonkey.toInt()) }.unzip() val maximumWorry = monkeys.map(Monkey::divisor).product() receivers.forEachIndexed { index, (trueMonkey, falseMonkey) -> monkeys[index].maximumWorry = maximumWorry monkeys[index].trueMonkey = monkeys[trueMonkey] monkeys[index].falseMonkey = monkeys[falseMonkey] } return monkeys } fun List<Monkey>.rounds(rounds: Int) = repeat(rounds) { forEach(Monkey::takeTurn) } fun List<Monkey>.business() = map(Monkey::inspections).nLargest(2).product() fun main() { val monkeyDescriptions = readInputRaw("Day11").trim().split("\n\n") var monkeys = createMonkeys(monkeyDescriptions, 3) monkeys.rounds(20) println(monkeys.business()) monkeys = createMonkeys(monkeyDescriptions, 1) monkeys.rounds(10000) println(monkeys.business()) }
0
Kotlin
0
1
76c6e8dc7b206fb8bc07d8b85ff18606f5232039
3,863
advent-of-code-2022
Apache License 2.0
src/algorithms/sorting/quick_sort/QuickSort.kt
abdurakhmonoff
353,686,707
false
null
package algorithms.sorting.quick_sort /** * Implementation of the quick sort algorithm for sorting a list of integers in ascending order. */ class QuickSort { /** * Sorts an array of integers in ascending order using QuickSort algorithm. * * @param arr the array to be sorted. * @param low the starting index of the array. * @param high the ending index of the array. */ fun quickSort(arr: IntArray, low: Int, high: Int) { if (low < high) { // Find partition index val pIndex = partition(arr, low, high) // Recursively sort elements before and after partition index quickSort(arr, low, pIndex - 1) quickSort(arr, pIndex + 1, high) } } /** * Partitions the array into two sub-arrays around the pivot element. * * @param arr the array to be partitioned. * @param low the starting index of the array. * @param high the ending index of the array. * @return the index of the pivot element after partitioning. */ private fun partition(arr: IntArray, low: Int, high: Int): Int { val pivot = arr[high] var i = low - 1 // Iterate through numbers from low to high-1 for (j in low until high) { if (arr[j] <= pivot) { i++ // Swap arr[i] and arr[j] val temp = arr[i] arr[i] = arr[j] arr[j] = temp } } // Place pivot at correct position in array val temp = arr[i + 1] arr[i + 1] = arr[high] arr[high] = temp // Return partition index return i + 1 } /** * Prints the elements of the array. * * @param arr the array to be printed. */ fun printArray(arr: IntArray) { for (value in arr) print("$value ") println() } } fun main() { val numbers = intArrayOf(99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0) val quickSort = QuickSort() quickSort.quickSort(numbers, 0, numbers.size - 1) quickSort.printArray(numbers) }
0
Kotlin
40
107
cd9746d02b34b54dd0cf8c8dacc2fb91d2a3cc07
2,116
data-structures-and-algorithms-kotlin
MIT License
src/main/kotlin/year2023/day10/Problem.kt
Ddxcv98
573,823,241
false
{"Kotlin": 154634}
package year2023.day10 import IProblem import java.lang.Exception import kotlin.math.abs class Problem : IProblem { private val matrix: Array<CharArray> private val n: Int private val m: Int private val start: Pair<Int, Int> init { val lines = javaClass .getResourceAsStream("/2023/10.txt")!! .bufferedReader() .lines() .toList() matrix = Array(lines.size) { i -> lines[i].toCharArray() } n = matrix.size m = matrix[0].size start = findStart() } private fun findStart(): Pair<Int, Int> { for (i in 0 until n) { for (j in 0 until m) { if (matrix[i][j] == 'S') { return Pair(j, i) } } } throw Exception("bruh moment") } private fun walk(prev: Pair<Int, Int>, curr: Pair<Int, Int>): Pair<Int, Int> { val (px, py) = prev val (cx, cy) = curr return when (matrix[cy][cx]) { '-' -> if (px < cx) Pair(cx + 1, cy) else Pair(cx - 1, cy) '7' -> if (px < cx) Pair(cx, cy + 1) else Pair(cx - 1, cy) 'F' -> if (px > cx) Pair(cx, cy + 1) else Pair(cx + 1, cy) 'J' -> if (px < cx) Pair(cx, cy - 1) else Pair(cx - 1, cy) 'L' -> if (px > cx) Pair(cx, cy - 1) else Pair(cx + 1, cy) '|' -> if (py < cy) Pair(cx, cy + 1) else Pair(cx, cy - 1) 'S' -> { if (cx > 0 && matrix[cy][cx - 1] in "-FL") { return Pair(cx - 1, cy) } if (cy > 0 && matrix[cy - 1][cx] in "7F|") { return Pair(cx, cy - 1) } if (cx < m - 1 && matrix[cy][cx + 1] in "-7J") { return Pair(cx + 1, cy) } return Pair(cx, cy + 1) } else -> throw Exception("bruh moment") } } override fun part1(): Int { var prev = start var curr = start var steps = 0 do { val next = walk(prev, curr) prev = curr curr = next steps++ } while (curr != start) return steps / 2 } override fun part2(): Int { var prev = start var curr = start var a = 0 var b = 0 do { val next = walk(prev, curr) prev = curr curr = next a += prev.first * curr.second - curr.first * prev.second b++ } while (curr != start) return abs(a) / 2 - b / 2 + 1 } }
0
Kotlin
0
0
455bc8a69527c6c2f20362945b73bdee496ace41
2,644
advent-of-code
The Unlicense
src/main/kotlin/day14.kt
gautemo
572,204,209
false
{"Kotlin": 78294}
import shared.Point import shared.getText fun main() { val input = getText("day14.txt") println(day14A(input)) println(day14B(input)) } fun day14A(input: String) = fallingSand(input) fun day14B(input: String) = fallingSand(input, true) private fun fallingSand(input: String, hasFloor: Boolean = false): Int { val cave = createCave(input) val start = Point(500, 0) val bottom = cave.maxOf { it.key.y } + 2 while (true) { var dropping = start while (true) { when { dropping.y + 1 == bottom && hasFloor -> { cave[dropping] = '+' break } dropping.y + 1 == bottom -> { return cave.count { it.value == '+' } } cave[dropping.down()] == null -> dropping = dropping.down() cave[dropping.downLeft()] == null -> dropping = dropping.downLeft() cave[dropping.downRight()] == null -> dropping = dropping.downRight() else -> { if(dropping == start){ return cave.count { it.value == '+' } + 1 } cave[dropping] = '+' break } } } } } private fun createCave(input: String): MutableMap<Point, Char> { val cave = mutableMapOf<Point, Char>() input.lines().forEach { val points = it.split("->").map { point -> point.trim().split(",").let { (x,y) -> Point(x.toInt(), y.toInt()) } } points.windowed(2).forEach { (a,b) -> for(y in minOf(a.y, b.y) .. maxOf(a.y, b.y)) { for(x in minOf(a.x, b.x) .. maxOf(a.x, b.x)) { cave[Point(x, y)] = '#' } } } } return cave } private fun Point.down() = Point(x, y+1) private fun Point.downLeft() = Point(x-1, y+1) private fun Point.downRight() = Point(x+1, y+1)
0
Kotlin
0
0
bce9feec3923a1bac1843a6e34598c7b81679726
2,000
AdventOfCode2022
MIT License
src/Day01.kt
Oli2861
572,895,182
false
{"Kotlin": 16729}
fun main() { fun toCalorieList(input: List<String>): MutableList<Int> { val list = mutableListOf<Int>() var currAmount = 0 for ((index, str) in input.withIndex()) { if (str.matches(Regex("[0-9]+"))) { currAmount += Integer.parseInt(str) if (index == input.size - 1) list.add(currAmount) } else { list.add(currAmount) currAmount = 0 } } return list } fun part1(input: List<String>): Int = toCalorieList(input).max() fun part2(input: List<String>): Int { val topThree = toCalorieList(input).sortedDescending().slice(0..2) return topThree.sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") val result1 = part1(testInput) println(result1) check(result1 == 68442) val result2 = part2(testInput) println(result2) check(result2 == 204837) /* val input = readInput("Day") println(part1(input)) println(part2(input)) */ }
0
Kotlin
0
0
138b79001245ec221d8df2a6db0aaeb131725af2
1,115
Advent-of-Code-2022
Apache License 2.0
src/main/aoc2022/Day20.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2022 import kotlin.math.abs import kotlin.math.sign class Day20(input: List<String>) { private val parsedInput = input.map { it.toInt() } fun solvePart1(): Long { val sequence = Sequence(parsedInput, 1) sequence.mix() return sequence.coordinateSum() } fun solvePart2(): Long { val sequence = Sequence(parsedInput, 811589153) repeat(10) { sequence.mix() } return sequence.coordinateSum() } companion object { class Node(val value: Long, var prev: Node?, var next: Node?) /** * A circular sequence of nodes, implemented like a linked list. */ class Sequence(input: List<Int>, private val decryptionKey: Long) { val size = input.size private val nodesInOriginalOrder = makeSequence(input) /** * Mix the sequence once. */ fun mix() { for (current in nodesInOriginalOrder) { val stepsToMove = getMinStepsToMove(current.value) val sign = stepsToMove.sign if (stepsToMove != 0) { // detach current node current.prev!!.next = current.next current.next!!.prev = current.prev var newPos = current if (sign > 0) { // Move forward repeat(stepsToMove) { newPos = newPos.next!! } } else { // move backward, one extra step is needed since the new node is inserted after the // selected node (when moving backwards we want to insert it before) repeat(-stepsToMove + 1) { newPos = newPos.prev!! } } // Insert current node after the newPos node current.prev = newPos current.next = newPos.next newPos.next!!.prev = current newPos.next = current } } } /** * Calculate the minimum required steps to walk to the element that is 'steps' steps away. * There is no need to walk several laps around the sequence, and sometimes it's shorter to * walk the other way. */ fun getMinStepsToMove(steps: Long): Int { val numOtherElements = size - 1 var sign = steps.sign var amount = abs(steps) % numOtherElements // It's closer to go the other way if (amount > numOtherElements / 2) { amount = numOtherElements - amount sign *= -1 } return (amount * sign).toInt() } /** * The sum of the values at position 1000, 2000, and 3000 from 0. */ fun coordinateSum(): Long { var current = nodesInOriginalOrder.find { it.value == 0L }!! return listOf(1, 2, 3).sumOf { // Move forward 1000 steps and then get the value at that position repeat(1000 % size) { current = current.next!! } current.value } } /** * Make a circular sequence of nodes and return a list holding the original order * of the nodes before any mixing has taken place. */ private fun makeSequence(input: List<Int>): List<Node> { val first = Node(input.first() * decryptionKey, null, null) val originalOrder = mutableListOf(first) var current = first for (value in input.drop(1)) { val next = Node(value * decryptionKey, current, null) originalOrder.add(next) current.next = next current = next } current.next = first first.prev = current return originalOrder } } } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
4,403
aoc
MIT License
src/main/kotlin/biz/koziolek/adventofcode/year2021/day25/day25.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2021.day25 import biz.koziolek.adventofcode.* fun main() { val inputFile = findInput(object {}) val lines = inputFile.bufferedReader().readLines() val map = parseSeaCucumberMap(lines) val (stepNumber, _) = moveUntilStop(map) println("Sea cucumbers stop moving after $stepNumber steps") } fun parseSeaCucumberMap(lines: List<String>): Map<Coord, Char> = lines.parse2DMap().toMap() fun seaCucumberMapToString(seaCucumberMap: Map<Coord, Char>): String { val width = seaCucumberMap.getWidth() val height = seaCucumberMap.getHeight() return buildString { for (y in 0 until height) { for (x in 0 until width) { append(seaCucumberMap[Coord(x, y)]) } if (y < height - 1) { append("\n") } } } } fun moveUntilStop(seaCucumberMap: Map<Coord, Char>): Pair<Int, Map<Coord, Char>> { var stepNumber = 0 var currentMap = seaCucumberMap while (true) { stepNumber++ val nextMap = moveSeaCucumbers(currentMap) if (nextMap == currentMap) { break } currentMap = nextMap } return stepNumber to currentMap } fun moveSeaCucumbers(seaCucumberMap: Map<Coord, Char>): Map<Coord, Char> = moveAll(moveAll(seaCucumberMap, '>'), 'v') private fun moveAll(seaCucumberMap: Map<Coord, Char>, typeToMove: Char): Map<Coord, Char> { val width = seaCucumberMap.getWidth() val height = seaCucumberMap.getHeight() return buildMap { for (y in 0 until height) { for (x in 0 until width) { val coord = Coord(x, y) put(coord, '.') } } for (y in 0 until height) { for (x in 0 until width) { val coord = Coord(x, y) val type = seaCucumberMap[coord]!! if (type == typeToMove) { val forwardCoord = getForwardCoord(coord, type, width, height) if (seaCucumberMap[forwardCoord] == '.') { put(forwardCoord, type) } else { put(coord, type) } } else if (type != '.'){ put(coord, type) } } } } } fun getForwardCoord(coord: Coord, type: Char, width: Int, height: Int): Coord = when (type) { '>' -> coord + Coord(1, 0) 'v' -> coord + Coord(0, 1) else -> throw IllegalArgumentException("Unsupported type to move: $type") }.let { if (it.x >= width) { it.copy(x = 0) } else { it } }.let { if (it.y >= height) { it.copy(y = 0) } else { it } }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
2,840
advent-of-code
MIT License
archive/src/main/kotlin/com/grappenmaker/aoc/year23/Day05.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year23 import com.grappenmaker.aoc.* fun PuzzleSet.day5() = puzzle(day = 5) { val blocks = input.doubleLines() val seeds = blocks.first().substringAfter(": ").split(" ").map(String::toLong) val maps = blocks.drop(1).map { it.lines() }.map { p -> p.drop(1).map { it.split(" ").map(String::toLong) }.map { (a, b, c) -> b..b + c to a..a + c } } partOne = seeds.minOf { v -> maps.fold(v) { a, c -> c.find { a in it.first }?.let { it.second.first + a - it.first.first } ?: a } }.s() partTwo = maps.fold(seeds.chunked(2).map { (a, b) -> a..a + b }) { curr, m -> buildList outer@{ addAll(m.fold(curr) { c, ra -> buildList { for (r in c) { val overlap = ra.first.overlap(r) if (overlap == null) { add(r) continue } val delta = ra.second.first - ra.first.first this@outer.add((delta + overlap.first)..(delta + overlap.last)) if (r.last > ra.first.last) add(ra.first.last..r.last) if (r.first < ra.first.first) add(r.first..ra.first.first) } } }) }.simplify() }.minOf { it.first }.s() }
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
1,396
advent-of-code
The Unlicense
src/main/kotlin/sschr15/aocsolutions/Day13.kt
sschr15
317,887,086
false
{"Kotlin": 184127, "TeX": 2614, "Python": 446}
package sschr15.aocsolutions import sschr15.aocsolutions.util.* /** * AOC 2023 [Day 13](https://adventofcode.com/2023/day/13) * Challenge: Find a bunch of mirrors (so you don't run into them in such an embarrassing way) * * but wait! the mirrors actually got smudged so now you gotta make sure you can avoid them even though they're * in unexpected places */ object Day13 : Challenge { @ReflectivelyUsed override fun solve() = challenge(2023, 13) { splitBy("\n\n") // test() part1 { inputLines.sumOf { val grid = it.trim().split("\n").chars().toGrid() var toLeft = 1 outer@while (true) { var distance = 0 while (true) { // check if we're at the edge if (toLeft - 1 - distance < 0) break@outer if (toLeft + distance >= grid.width) break@outer val leftCol = grid.getColumn(toLeft - 1 - distance) val rightCol = grid.getColumn(toLeft + distance) if (leftCol != rightCol) break // reached a mismatch distance++ } toLeft++ } if (toLeft != grid.width) return@sumOf toLeft var above = 1 outer@while (true) { var distance = 0 while (true) { if (above - 1 - distance < 0) break@outer if (above + distance >= grid.height) break@outer val topRow = grid.getRow(above - 1 - distance) val bottomRow = grid.getRow(above + distance) if (topRow != bottomRow) break distance++ } above++ } above * 100 } } part2 { inputLines.sumOf { val grid = it.trim().split("\n").chars().toGrid() val columns = grid.columns() val rows = grid.rows() var toLeft = 1 while (true) { if (toLeft >= columns.size) break val (left, right) = columns.take(toLeft).asReversed() to columns.drop(toLeft) val diffs = left.zip(right).map { (l, r) -> l.zip(r).count { (a, b) -> a != b } } if (diffs.sum() == 1) { // exactly one difference is what we want return@sumOf toLeft } toLeft++ } var above = 1 while (true) { if (above >= rows.size) break val (top, bottom) = rows.take(above).asReversed() to rows.drop(above) val diffs = top.zip(bottom).map { (t, b) -> t.zip(b).count { (a, b) -> a != b } } if (diffs.sum() == 1) { return@sumOf above * 100 } above++ } error("no solution found") } } } @JvmStatic fun main(args: Array<String>) = println("Time: ${solve()}") }
0
Kotlin
0
0
e483b02037ae5f025fc34367cb477fabe54a6578
3,338
advent-of-code
MIT License
day09/src/main/kotlin/Day09.kt
bzabor
160,240,195
false
null
class Day09(private val input: List<String>) { private val circle = arrayListOf(0) private val numberOfPlayers = 439 private val marblesToPlay = 7130700 private val playerScores: MutableMap<Int, Long> = (1..numberOfPlayers).associate { it to 0L }.toMutableMap() private var currentPosition = 0 private var currentMarble = 0 private var currentPlayer = 0 private var nextMarble = 0 fun part1(): Long { for (i in 1..marblesToPlay) { playTurn() } val highScore = printScoresReturnHighest() return highScore } private fun playTurn() { var nextPosition = 0 currentMarble = ++nextMarble currentPlayer = if (currentMarble % numberOfPlayers == 0) numberOfPlayers else currentMarble % numberOfPlayers // println("currentMarble now: $currentMarble currentPosition: $currentPosition circlesize: ${circle.size} currentPlayer: $currentPlayer") if (currentMarble % 10000 == 0) { println("CurrentMarble: $currentMarble") } if (currentMarble % 100000 == 0) { printScoresReturnHighest() } if (currentMarble % 23 == 0) { var removeIdx = currentPosition - 7 if (removeIdx < 0) { removeIdx = circle.size + removeIdx // adding a negative number here to subtract println("adjusted removeIdx: $removeIdx") } val removedValue = circle.removeAt(removeIdx) playerScores[currentPlayer] = playerScores[currentPlayer] as Long + currentMarble.toLong() + removedValue.toLong() currentPosition = removeIdx if (currentPosition > circle.lastIndex) { currentPosition = 0 } } else { nextPosition = getNextInsertPosition() if (nextPosition <= circle.lastIndex) { circle.add(nextPosition, currentMarble) } else { circle.add(currentMarble) } currentPosition = nextPosition } // printCircle() } private fun getNextInsertPosition(): Int { var nextPosition = currentPosition + 1 if (nextPosition > circle.lastIndex) { nextPosition = 0 } return nextPosition + 1 } private fun printCircle() { print("[${currentPlayer}] - ") circle.mapIndexed { idx, it -> if (idx == currentPosition) print("(${it}) ") else print("${it} ") } println("") } private fun printScoresReturnHighest(): Long { println("FINAL SCORES:") val hiMap = playerScores.toList().sortedByDescending { (_, value) -> value }.take(10).toMap() hiMap.forEach{t, u -> println("$t : $u")} return hiMap.toList().first().second } fun part2(): Int { return 0 } } class Node<Int>(value: Int) { var value: Int = value var next: Node<Int>? = null var previous: Node<Int>? = null }
0
Kotlin
0
0
14382957d43a250886e264a01dd199c5b3e60edb
3,028
AdventOfCode2018
Apache License 2.0
src/main/kotlin/com/ginsberg/advent2020/Day08.kt
tginsberg
315,060,137
false
null
/* * Copyright (c) 2020 by <NAME> */ /** * Advent of Code 2020, Day 8 - Handheld Halting * Problem Description: http://adventofcode.com/2020/day/8 * Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2020/day8/ */ package com.ginsberg.advent2020 class Day08(input: List<String>) { private val instructions: List<Instruction> = input.map { Instruction.of(it) } fun solvePart1(): Int = Computer(instructions).run { runUntilTerminate() accumulator } fun solvePart2(): Int = instructions .indices .asSequence() .mapNotNull { index -> instructions.flipIndexOrNull(index) } .mapNotNull { inst -> Computer(inst).run { if (runUntilTerminate() == Computer.ExecutionState.HALTED) accumulator else null } }.first() private fun List<Instruction>.flipIndexOrNull(index: Int): List<Instruction>? = this[index].flipOrNull()?.let { flipped -> this.toMutableList().apply { this[index] = flipped } } data class Instruction(val name: String, val argument: Int) { fun flipOrNull(): Instruction? = when (name) { "jmp" -> Instruction("nop", argument) "nop" -> Instruction("jmp", argument) else -> null } companion object { fun of(input: String): Instruction = input.split(" ").run { Instruction(this.first(), this.last().toInt()) } } } data class Computer(val instructions: List<Instruction>) { enum class ExecutionState { HALTED, INFINITE_LOOP, RUNNING } private val executed = mutableSetOf<Int>() private var instructionPointer: Int = 0 var accumulator: Int = 0 fun runUntilTerminate(): ExecutionState = generateSequence { executeStep() }.first { it != ExecutionState.RUNNING } private fun executeStep(): ExecutionState { return when (instructionPointer) { in executed -> ExecutionState.INFINITE_LOOP !in instructions.indices -> ExecutionState.HALTED else -> { val current = instructions[instructionPointer] executed += instructionPointer when (current.name) { "acc" -> { accumulator += current.argument instructionPointer += 1 } "jmp" -> instructionPointer += current.argument "nop" -> instructionPointer += 1 } ExecutionState.RUNNING } } } } }
0
Kotlin
2
38
75766e961f3c18c5e392b4c32bc9a935c3e6862b
2,924
advent-2020-kotlin
Apache License 2.0
src/nativeMain/kotlin/Day17.kt
rubengees
576,436,006
false
{"Kotlin": 67428}
import kotlin.math.max class Day17 : Day { private data class Point(val x: Int, val y: Int) private data class Shape(val data: Map<Point, Unit>) { fun moveTo(x: Int, y: Int): Shape { return Shape(data.mapKeys { (point, _) -> Point(point.x + x, point.y + y) }) } fun collides(chamber: Map<Point, Unit>): Boolean { return data.keys.any { chamber.containsKey(it) || it.x < 0 || it.x > 6 } } fun collides(x: Int, y: Int, chamber: Map<Point, Unit>): Boolean { return moveTo(x, y).collides(chamber) } } private val shapes = listOf( Shape( mapOf( Point(0, 0) to Unit, Point(1, 0) to Unit, Point(2, 0) to Unit, Point(3, 0) to Unit ) ), Shape( mapOf( Point(1, 0) to Unit, Point(0, 1) to Unit, Point(1, 1) to Unit, Point(2, 1) to Unit, Point(1, 2) to Unit ) ), Shape( mapOf( Point(0, 0) to Unit, Point(1, 0) to Unit, Point(2, 0) to Unit, Point(2, 1) to Unit, Point(2, 2) to Unit ) ), Shape( mapOf( Point(0, 0) to Unit, Point(0, 1) to Unit, Point(0, 2) to Unit, Point(0, 3) to Unit ) ), Shape( mapOf( Point(0, 0) to Unit, Point(1, 0) to Unit, Point(0, 1) to Unit, Point(1, 1) to Unit ) ) ) private fun parseJet(input: Char) = when (input) { '>' -> 1 '<' -> -1 else -> error("Invalid input $input") } private fun simulate(jets: List<Int>, times: Int): Map<Point, Unit> { val chamber = (0 until 7).associate { Point(it, 0) to Unit }.toMutableMap() val jetSequence = sequence { repeat(Int.MAX_VALUE) { yieldAll(jets) } }.iterator() var top = chamber.keys.maxOf { it.y } repeat(times) { step -> var shape = shapes[step.mod(shapes.size)].moveTo(2, top + 4) while (true) { val nextJet = jetSequence.next() if (!shape.collides(nextJet, 0, chamber)) { shape = shape.moveTo(nextJet, 0) } if (!shape.collides(0, -1, chamber)) { shape = shape.moveTo(0, -1) } else { break } } chamber.putAll(shape.data) top = max(top, shape.data.keys.maxOf { it.y }) } return chamber } override suspend fun part1(input: String): String { val jets = input.map(::parseJet) val chamber = simulate(jets, 2022) return chamber.keys.maxOf { it.y }.toString() } override suspend fun part2(input: String): String { return "" } }
0
Kotlin
0
0
21f03a1c70d4273739d001dd5434f68e2cc2e6e6
3,105
advent-of-code-2022
MIT License
src/main/kotlin/days/Day01.kt
Kebaan
573,069,009
false
null
package days import utils.Day import utils.splitBy fun main() { Day01.solve() } object Day01 : Day<Int>(2022, 1) { private fun calculateSumOfNLargest(bags: List<List<String>>, n: Int) = bags.map { bagOfCalories -> bagOfCalories.sumOf { it.toInt() } }.sortedDescending().take(n).sum() override fun part1(input: List<String>): Int { val bags = input.splitBy { it.isEmpty() } return calculateSumOfNLargest(bags, 1) } override fun part2(input: List<String>): Int { val bags = input.splitBy { it.isEmpty() } return calculateSumOfNLargest(bags, 3) } override fun doSolve() { part1(input).let { println(it) check(it == 74198) } part2(input).let { println(it) check(it == 209914) } } override val testInput = """ 1000 2000 3000 4000 5000 6000 7000 8000 9000 10000""".trimIndent().lines() }
0
Kotlin
0
0
ef8bba36fedbcc93698f3335fbb5a69074b40da2
1,234
Advent-of-Code-2022
Apache License 2.0
src/main/kotlin/com/polydus/aoc18/Day7.kt
Polydus
160,193,832
false
null
package com.polydus.aoc18 class Day7: Day(7){ //https://adventofcode.com/2018/day/7 init { //partOne() partTwo() } fun partOne(){ val map = HashMap<Char, Node>() input.forEach { val type = it.toCharArray()[36] val parent = it.toCharArray()[5] if(map[type] == null) map[type] = Node(type) if(map[parent] == null) map[parent] = Node(parent) } var sequence = "" input.forEach { val type = it.toCharArray()[36] val parent = it.toCharArray()[5] map[type]!!.parents.add(map[parent]!!) map[parent]!!.children.add(map[type]!!) map[type]!!.parents.sortBy { it.id } } while(true){ val node = map.values.filter { it.canFinish() }.sortedBy { it.id }.firstOrNull() ?: break sequence += node.id node.finished = true } println(sequence) map.forEach { print("${it.value.id} has parents: ") for(p in it.value.parents) print("${p.id} ") print("\n") //print("${it.value.id} has children: ") //for(p in it.value.children) print("${p.id} ") //print("\n") //if(it.value.children.size == 0) end = it.value } } fun partTwo(){ val map = HashMap<Char, Node>() input.forEach { val type = it.toCharArray()[36] val parent = it.toCharArray()[5] if(map[type] == null) map[type] = Node(type) if(map[parent] == null) map[parent] = Node(parent) } var sequence = "" input.forEach { val type = it.toCharArray()[36] val parent = it.toCharArray()[5] map[type]!!.parents.add(map[parent]!!) map[parent]!!.children.add(map[type]!!) map[type]!!.parents.sortBy { it.id } } val workers = arrayOf(0, 0, 0, 0, 0) val workersWork = arrayOf('.', '.', '.', '.', '.') var seconds = 0 while(true){ for(w in workers.withIndex()){ if(w.value > 0) workers[w.index]-- if(workers[w.index] == 0 && workersWork[w.index] != '.'){ val n = map[workersWork[w.index]] n!!.beginWorked = false n.finished = true sequence += n.id workersWork[w.index] = '.' } } val nodes = map.values.filter { it.canStart() }.sortedBy { it.id }//.firstOrNull() if(nodes.isEmpty() && workers.filter { it == 0 }.size == workers.size){ break } if(!nodes.isEmpty() && workers.any { it == 0 }){ for(node in nodes){ if(!workers.any { it == 0 }) break for(w in workers.withIndex()){ if(w.value == 0){ node.beginWorked = true val time = node.id.toInt() - 64 + 60 //println("${node.id} has time $time") workers[w.index] = time workersWork[w.index] = node.id break } } } } /*if(node != null && !node.beginWorked && workers.any { it == 0 }){ node.beginWorked = true for(w in workers.withIndex()){ if(w.value == 0){ var time = node.id.toInt() - 64 //println("${node.id} has time $time") workers[w.index] = time workersWork[w.index] = node.id break } } }*/ if(seconds < 10){ println("0$seconds ${workersWork[0]} ${workersWork[1]} ${workersWork[2]} ${workersWork[3]} ${workersWork[4]} $sequence") } else { println("$seconds ${workersWork[0]} ${workersWork[1]} ${workersWork[2]} ${workersWork[3]} ${workersWork[4]} $sequence") } seconds++ } println("answer is ${seconds}s $sequence") } class Node(val id: Char){ val parents = ArrayList<Node>() val children = ArrayList<Node>() fun canFinish(): Boolean{ if(finished) return false for(p in parents){ if(!p.finished) return false } return true } fun canStart(): Boolean{ if(finished || beginWorked) return false for(p in parents){ if(!p.finished) return false } return true } var finished = false var beginWorked = false } }
0
Kotlin
0
0
e510e4a9801c228057cb107e3e7463d4a946bdae
4,948
advent-of-code-2018
MIT License
src/medium/_39CombinationSum.kt
ilinqh
390,190,883
false
{"Kotlin": 382147, "Java": 32712}
package medium import java.util.* class _39CombinationSum { class Solution { fun combinationSum(candidates: IntArray, target: Int): List<List<Int>> { if (candidates.isEmpty()) { return emptyList() } val result = ArrayList<List<Int>>() val cur = ArrayList<Int>() Arrays.sort(candidates) bfs(candidates, target, 0, cur, result) return result } private fun bfs( candidates: IntArray, target: Int, index: Int, cur: MutableList<Int>, result: MutableList<List<Int>> ) { if (index >= candidates.size) { return } if (target == 0) { result.add(ArrayList(cur)) return } for (i in index until candidates.size) { if (candidates[i] > target) { break } if (i > 0 && candidates[i] == candidates[i - 1]) { continue } val newTarget = target - candidates[i] cur.add(candidates[i]) bfs(candidates, newTarget, i, cur, result) cur.removeAt(cur.size - 1) } } } class BestSolution { fun combinationSum(candidates: IntArray, target: Int): List<List<Int>> { val ans: MutableList<List<Int>> = ArrayList() val combine: MutableList<Int> = ArrayList() dfs(candidates, target, ans, combine, 0) return ans } fun dfs(candidates: IntArray, target: Int, ans: MutableList<List<Int>>, combine: MutableList<Int>, idx: Int) { if (idx == candidates.size) { return } if (target == 0) { ans.add(ArrayList(combine)) return } // 直接跳过 dfs(candidates, target, ans, combine, idx + 1) // 选择当前数 if (target - candidates[idx] >= 0) { combine.add(candidates[idx]) dfs(candidates, target - candidates[idx], ans, combine, idx) combine.removeAt(combine.size - 1) } } } }
0
Kotlin
0
0
8d2060888123915d2ef2ade293e5b12c66fb3a3f
2,328
AlgorithmsProject
Apache License 2.0
ceria/04/src/main/kotlin/Solution.kt
VisionistInc
572,963,504
false
null
import java.io.File; fun main(args : Array<String>) { var input = mutableListOf<Pair<ClosedRange<Int>, ClosedRange<Int>>>() File(args.first()).readLines().forEach { var ranges = it.split(',') var firstR = ranges.get(0).split('-') var secondR = ranges.get(1).split('-') input.add(Pair<ClosedRange<Int>, ClosedRange<Int>>(firstR[0].toInt()..firstR[1].toInt(), secondR[0].toInt()..secondR[1].toInt())) } println("Solution 1: ${solution1(input)}") println("Solution 2: ${solution2(input)}") } private fun solution1(input: List<Pair<ClosedRange<Int>, ClosedRange<Int>>>) :Int { var total = 0 input.forEach { if (it.first.containedIn(it.second) || it.second.containedIn(it.first)) { total++ } } return total } private fun solution2(input: List<Pair<ClosedRange<Int>, ClosedRange<Int>>>) :Int { var total = 0 input.forEach { if (it.first.overlaps(it.second) || it.second.overlaps(it.first) ) { total++ } } return total } fun ClosedRange<Int>.containedIn(other: ClosedRange<Int>) = start >= other.start && endInclusive <= other.endInclusive fun ClosedRange<Int>.overlaps(other: ClosedRange<Int>) = (start >= other.start && start <= other.endInclusive) || (endInclusive <= other.endInclusive && endInclusive >= other.start)
0
Rust
0
0
90b348d9c8060a8e967fe1605516e9c126fc7a56
1,372
advent-of-code-2022
MIT License
src/main/kotlin/com/colinodell/advent2023/Day11.kt
colinodell
726,073,391
false
{"Kotlin": 114923}
package com.colinodell.advent2023 class Day11(input: List<String>) { private val grid = input.toGrid(ignore = '.') private fun expand(g: Grid<Char>, growthFactor: Int): Grid<Char> { val f = growthFactor - 1 val emptyRows = g.rows().filter { y -> g.none { (pos, _) -> pos.y == y } } val emptyCols = g.cols().filter { x -> g.none { (pos, _) -> pos.x == x } } return g.mapKeys { (pos, _) -> Vector2( x = pos.x + (f * emptyCols.count { it < pos.x }), y = pos.y + (f * emptyRows.count { it < pos.y }), ) } } private fun calculateAllShortestPaths(galaxies: Collection<Vector2>) = galaxies.sumOf { a -> galaxies.filter { b -> b != a }.sumOf { b -> a.manhattanDistanceTo(b).toLong() } } / 2 fun solve(growthFactor: Int) = calculateAllShortestPaths(expand(grid, growthFactor).keys) }
0
Kotlin
0
0
97e36330a24b30ef750b16f3887d30c92f3a0e83
909
advent-2023
MIT License
src/main/kotlin/nl/jhvh/sudoku/util/ListElementStringUtil.kt
JanHendrikVanHeusden
305,492,630
false
null
package nl.jhvh.sudoku.util /* 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. */ import org.apache.commons.lang3.StringUtils /** @return The length of the longest [toString] of all elements in the collection */ fun Collection<*>.maxStringLength(): Int = this.map { s -> s.toString().length } .maxOrNull()!! fun List<*>.alignRight(extraLeftPad: Int = 0, extraRightPad: Int = 0): List<String> { require(extraLeftPad >= 0, { "extraLeftPad must be non-negative or omitted (current: $extraLeftPad)" }) require(extraRightPad >= 0, { "extraRightPad must be non-negative or omitted (current: $extraRightPad)" }) val maxLength = this.maxStringLength() val padAction: (String) -> String = { it.padStart(maxLength + extraLeftPad).padEnd(maxLength + extraLeftPad + extraRightPad) } return this.map { padAction(it.toString()) } } fun List<*>.alignLeft(extraLeftPad: Int = 0, extraRightPad: Int = 0): List<String> { require(extraLeftPad >= 0, { "extraLeftPad must be non-negative or omitted (current: $extraLeftPad)" }) require(extraRightPad >= 0, { "extraRightPad must be non-negative or omitted (current: $extraRightPad)" }) val maxLength = this.maxStringLength() val padAction: (String) -> String = { it.padEnd(maxLength + extraRightPad).padStart(maxLength + extraLeftPad + extraRightPad) } return this.map { padAction(it.toString()) } } fun List<*>.alignCenter(extraLeftPad: Int = 0, extraRightPad: Int = 0): List<String> { require(extraLeftPad >= 0, { "extraLeftPad must be non-negative or omitted (current: $extraLeftPad)" }) require(extraRightPad >= 0, { "extraRightPad must be non-negative or omitted (current: $extraRightPad)" }) val maxLength = this.maxStringLength() val padAction: (String) -> String = { StringUtils.center(it, maxLength).padEnd(maxLength + extraRightPad).padStart(maxLength + extraLeftPad + extraRightPad) } return this.map { padAction(it.toString()) } } @Throws(IllegalArgumentException::class) private fun Collection<*>.validateEqualSize(other: Collection<*>) { require(other.size == this.size) { "Both collections must have equal sizes! Sizes: left=${this.size}, right=${other.size}" } } /** * Given 2 [List]s, concatenates the [toString] value of each element of the left (receiver) list with the corresponding elemeent * of the right ([other]) list * @receiver [List]`<*>` * @param other [List]`<*>`. Must have the same size as the receiver [List] * @return A new [List]`<String>` with the concatenated values. */ infix fun List<*>.concatEach(other: List<*>): List<String> { validateEqualSize(other) return this.mapIndexed { index, t -> t.toString() + other[index].toString() } } /** * Given a variable number of [List]s, concatenates the [toString] value of each element with the corresponding element * of the next [List]s * @param lists [Array]`<out [List]<*>>` A variable number of [List]s to have their elements concatenated. * All [lists] must be equal in size. * @return A new [List]`<String>` with the concatenated values. */ fun concatEach(vararg lists: List<*>): List<String> { if (lists.isEmpty()) { return emptyList() } val result = lists[0].map { "" } return lists.fold(result, {current, next -> current concatEach next}) } /** * Given 2 [List]s, concatenates the [toString] value of each element of the left (receiver) list with the corresponding element * of the right ([other]) list, values of each [List] right padded (left aligned) with respect to that [List]s values * @receiver [List]`<*>` * @param other [List]`<*>`. Must have the same size as the receiver [List] * @return A new [List]`<String>` with the concatenated and aligned values. */ infix fun List<*>.concatAlignLeft(other: List<*>): List<String> { return this.alignLeft() concatEach other.alignLeft() } /** * Given a variable number of [List]s, concatenates the [toString] value of each element with the corresponding element * of the next [List]s, values of each [List] right padded (left aligned) with respect to that [List]s values * @param lists [Array]`<out [List]<*>>` A variable number of [List]s to have their elements concatenated. * All [lists] must be equal in size. * @return A new [List]`<String>` with the concatenated and aligned values. */ fun concatAlignLeft(vararg lists: List<*>): List<String> { if (lists.isEmpty()) { return emptyList() } val result = lists[0].map { "" } return lists.fold(result, {current, next -> current concatEach next.alignLeft()}) } /** * Given 2 [List]s, concatenates the [toString] value of each element of the left (receiver) list with the corresponding element * of the right ([other]) list, values of each [List] (center aligned) with respect to that [List]s values * @receiver [List]`<*>` * @param other [List]`<*>`. Must have the same size as the receiver [List] * @return A new [List]`<String>` with the concatenated and aligned values. */ infix fun List<*>.concatAlignCenter(other: List<*>): List<String> { return this.alignCenter() concatEach other.alignCenter() } /** * Given a variable number of [List]s, concatenates the [toString] value of each element with the corresponding element * of the next [List]s, values of each [List] center aligned with respect to that [List]s values * @param lists [Array]`<out [List]<*>>` A variable number of [List]s to have their elements concatenated. * All [lists] must be equal in size. * @return A new [List]`<String>` with the concatenated and aligned values. */ fun concatAlignCenter(vararg lists: List<*>): List<String> { if (lists.isEmpty()) { return emptyList() } val result = lists[0].map { "" } return lists.fold(result, {current, next -> current concatEach next.alignCenter()}) } /** * Given 2 [List]s, concatenates the [toString] value of each element of the left (receiver) list with the corresponding element * of the right ([other]) list, values of each [List] left padded (right aligned) with respect to that [List]s values * @receiver [List]`<*>` * @param other [List]`<*>`. Must have the same size as the receiver [List] * @return A new [List]`<String>` with the concatenated and aligned values. */ infix fun List<*>.concatAlignRight(other: List<*>): List<String> { return this.alignRight() concatEach other.alignRight() } /** * Given a variable number of [List]s, concatenates the [toString] value of each element with the corresponding element * of the next [List]s, values of each [List] left padded (right aligned) with respect to that [List]s values * @param lists [Array]`<out [List]<*>>` A variable number of [List]s to have their elements concatenated. * All [lists] must be equal in size. * @return A new [List]`<String>` with the concatenated and aligned values. */ fun concatAlignRight(vararg lists: List<*>): List<String> { if (lists.isEmpty()) { return emptyList() } val result = lists[0].map { "" } return lists.fold(result, {current, next -> current concatEach next.alignRight()}) }
0
Kotlin
0
1
5a487a594600edc28b46067b12ed9a5ac610bea2
7,635
Sudoku
Apache License 2.0
src/day13/Day13.kt
crmitchelmore
576,065,911
false
{"Kotlin": 115199}
package day13 import helpers.ReadFile import java.lang.Integer.min class Day13 { val lines = ReadFile.named("src/day13/input.txt", "\n\n") val linet = ReadFile.named("src/day13/testinput.txt", "\n\n") class RecursiveArray { var children: MutableList<RecursiveArray>? = null var number: Int? = null constructor(number: Int? = null, children: MutableList<RecursiveArray>? = null) { this.number = number this.children = children } } //[[[[2]],[2,[3],[9,3],10],8],[[9,[5,7,5,5],6,8],[[],7,7,2]],[[]]] fun parseLine(line: String): Pair<RecursiveArray, String> { var remaining = line.drop(1) var ra = RecursiveArray(children = mutableListOf()) while (true) { if (remaining.startsWith(",")){ remaining = remaining.drop(1) } if (remaining.startsWith("[")) { val (el, r) = parseLine(remaining) ra.children?.add(el) remaining = r } else if (remaining.startsWith("]")) { return Pair(ra, remaining.drop(1)) } else { val number = remaining.takeWhile { it.isDigit() } val el = RecursiveArray() el.number = number.toInt() remaining = remaining.drop(number.length) ra.children?.add(el) if (remaining.startsWith(",")){ remaining = remaining.drop(1) } } } } fun aLTb(a: RecursiveArray, b: RecursiveArray): Boolean? { if (a.number != null && b.number != null && a.number != b.number) { return a.number!! < b.number!! } if (a.children != null && b.children != null) { if (a.children!!.size == 0 || b.children!!.size == 0) { if (a.children!!.size == b.children!!.size) { return null } return a.children!!.size < b.children!!.size } for (i in 0 until min(a.children!!.size, b.children!!.size)) { if (a.children!![i].children != null && b.children!![i].number != null) { val result = aLTb(a.children!![i], RecursiveArray(children = mutableListOf(b.children!![i]))) if (result != null) { return result } } else if (b.children!![i].children != null && a.children!![i].number != null) { val result = aLTb(RecursiveArray(children = mutableListOf(a.children!![i])), b.children!![i]) if (result != null) { return result } } else { val result = aLTb(a.children!![i], b.children!![i]) if (result != null) { return result } } } if (a.children!!.size != b.children!!.size) { return a.children!!.size < b.children!!.size } } return null } fun result1() { var i = 1 var sum = 0 for (block in lines) { val lines = block.split("\n") val left = parseLine(lines[0]).first val right = parseLine(lines[1]).first val compare = aLTb(left, right) if (compare == true) { sum += i } println("$i $compare") i++ } print("P1 sum: $sum") val lines = ReadFile.named("src/day13/input.txt").filter { it.isNotBlank() }.map { parseLine(it).first } val linet = ReadFile.named("src/day13/testinput.txt").filter { it.isNotBlank() }.map { parseLine(it).first } val sorted = lines.sortedWith(Comparator { o1, o2 -> val compare = aLTb(o1, o2) if (compare == true) { return@Comparator -1 } if (compare == false) { return@Comparator 1 } return@Comparator 0 }) val a = sorted.indexOfFirst { it.children?.size == 1 && it.children!![0].children?.size == 1 && it.children!![0].children!![0].number == 2 } + 1 val b = sorted.indexOfFirst { it.children?.size == 1 && it.children!![0].children?.size == 1 && it.children!![0].children!![0].number == 6 } + 1 println(a*b) } }
0
Kotlin
0
0
fd644d442b5ff0d2f05fbf6317c61ee9ce7b4470
4,474
adventofcode2022
MIT License
src/main/java/com/booknara/problem/union/NumberOfConnectedComponentsInUndirectedGraphKt.kt
booknara
226,968,158
false
{"Java": 1128390, "Kotlin": 177761}
package com.booknara.problem.union /** * 323. Number of Connected Components in an Undirected Graph (Medium) * https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/ */ class NumberOfConnectedComponentsInUndirectedGraphKt { // T:O(n with path compression), S:O(n) fun countComponents(n: Int, edges: Array<IntArray>): Int { var res = n val root = IntArray(n) { i -> i } val rank = IntArray(n) { 1 } for (i in edges.indices) { val root1 = find(root, edges[i][0]) val root2 = find(root, edges[i][1]) if (root1 != root2) { // union if (rank[root1] < rank[root2]) { root[root1] = root2 } else if (rank[root1] > rank[root2]) { root[root2] = root1 } else { root[root1] = root2 rank[root2]++ } res-- } } return res } // find fun find(root: IntArray, index: Int): Int { if (index == root[index]) { return index } root[index] = find(root, root[index]) return root[index] } }
0
Java
1
1
04dcf500ee9789cf10c488a25647f25359b37a53
1,073
playground
MIT License
src/Utils.kt
er453r
572,440,270
false
{"Kotlin": 69456}
import java.io.File import java.math.BigInteger import kotlin.math.abs import kotlin.math.max fun readInput(name: String) = File("aoc2022/src", "$name.txt") .readLines() fun <T> assertEquals(value: T, target: T) { if (value != target) check(false) { "Expected $target got $value" } } fun String.destructured(regex: Regex): MatchResult.Destructured = regex.matchEntire(this) ?.destructured ?: throw IllegalArgumentException("Incorrect line $this") val intLineRegex = """-?\d+""".toRegex() fun String.ints() = intLineRegex.findAll(this).map { it.value.toInt() }.toList() fun <T> test( day: Int, testTarget1: T, testTarget2: T, part1: (List<String>) -> T, part2: (List<String>) -> T, ) { // test if implementation meets criteria from the description, like: val dayNumber = day.toString().padStart(2, '0') val testInput = readInput("Day${dayNumber}_test") val input = readInput("Day${dayNumber}") println("[DAY $day]") println("Part 1") print(" test: $testTarget1 ") var startTime = System.currentTimeMillis() assertEquals(part1(testInput), testTarget1) println("OK (${System.currentTimeMillis() - startTime} ms)") startTime = System.currentTimeMillis() println(" answer: ${part1(input)} (${System.currentTimeMillis() - startTime} ms)") println("Part 2") print(" test: $testTarget2 ") startTime = System.currentTimeMillis() assertEquals(part2(testInput), testTarget2) println("OK (${System.currentTimeMillis() - startTime} ms)") startTime = System.currentTimeMillis() println(" answer: ${part2(input)} (${System.currentTimeMillis() - startTime} ms)") } class GridCell<T>( var value: T, val position: Vector2d, ) class Grid<T>(data: List<List<T>>) { val data = data.mapIndexed { y, line -> line.mapIndexed { x, value -> GridCell(value, Vector2d(x, y)) } } val width = data.first().size val height = data.size fun get(x: Int, y: Int) = data[y][x] operator fun get(vector2d: Vector2d) = get(vector2d.x, vector2d.y) fun contains(x: Int, y: Int) = (x in 0 until width) && (y in 0 until height) operator fun contains(vector2d: Vector2d) = contains(vector2d.x, vector2d.y) fun crossNeighbours(vector2d: Vector2d) = Vector2d.DIRECTIONS.map { vector2d + it }.filter { contains(it) }.map { get(it) } fun path( start: GridCell<T>, end: GridCell<T>, heuristic: (GridCell<T>) -> Int = { (end.position - it.position).length() }, neighbours: (GridCell<T>) -> Collection<GridCell<T>> = { crossNeighbours(it.position) }, ) = aStar(start, isEndNode = { it == end }, heuristic, neighbours) } data class Vector2d(var x: Int = 0, var y: Int = 0) { companion object { val UP = Vector2d(0, -1) val DOWN = Vector2d(0, 1) val LEFT = Vector2d(-1, -0) val RIGHT = Vector2d(1, 0) val DIRECTIONS = arrayOf(UP, DOWN, LEFT, RIGHT) } operator fun plus(vector2d: Vector2d) = Vector2d(x + vector2d.x, y + vector2d.y) operator fun minus(vector2d: Vector2d) = Vector2d(x - vector2d.x, y - vector2d.y) fun increment(vector2d: Vector2d): Vector2d { this.x += vector2d.x this.y += vector2d.y return this } fun normalized() = Vector2d(if (x != 0) x / abs(x) else 0, if (y != 0) y / abs(y) else 0) fun negative() = Vector2d(-x, -y) fun length() = max(abs(x), abs(y)) fun manhattan() = abs(x) + abs(y) fun neighbours8() = setOf( this + UP, this + UP + LEFT, this + UP + RIGHT, this + LEFT, this + RIGHT, this + DOWN, this + DOWN + LEFT, this + DOWN + RIGHT, ) } data class Vector3d(var x: Int = 0, var y: Int = 0, var z: Int = 0) { companion object { val UP = Vector3d(0, -1, 0) val DOWN = Vector3d(0, 1, 0) val LEFT = Vector3d(-1, 0, 0) val RIGHT = Vector3d(1, 0, 0) val FORWARD = Vector3d(0, 0, -1) val FRONT = Vector3d(0, 0, -1) val BACKWARD = Vector3d(0, 0, 1) val BACK = Vector3d(0, 0, 1) val DIRECTIONS = arrayOf(UP, DOWN, LEFT, RIGHT, FORWARD, BACKWARD) } operator fun plus(vector3d: Vector3d) = Vector3d(x + vector3d.x, y + vector3d.y, z + vector3d.z) operator fun minus(vector3d: Vector3d) = Vector3d(x - vector3d.x, y - vector3d.y, z - vector3d.z) operator fun times(times: Int) = Vector3d(x * times, y * times, z * times) fun increment(vector3d: Vector3d): Vector3d { this.x += vector3d.x this.y += vector3d.y this.z += vector3d.z return this } } class VectorN(val components: MutableList<Int>) { constructor(vararg ints: Int) : this(ints.toMutableList()) operator fun plus(vectorN: VectorN) = VectorN(components.mapIndexed { index, it -> it + vectorN.components[index] }.toMutableList()) operator fun minus(vectorN: VectorN) = VectorN(components.mapIndexed { index, it -> it - vectorN.components[index] }.toMutableList()) fun increment(vectorN: VectorN): VectorN { for (n in components.indices) components[n] += vectorN.components[n] return this } override fun toString(): String { return components.toString() } } fun <Node> aStar( start: Node, isEndNode: (Node) -> Boolean, heuristic: (Node) -> Int, neighbours: (Node) -> Collection<Node>, ): List<Node> { val openSet = mutableSetOf(start) val gScores = mutableMapOf(start to 0) val fScores = mutableMapOf(start to heuristic(start)) val cameFrom = mutableMapOf<Node, Node>() fun reconstructPath(cameFrom: Map<Node, Node>, end: Node): List<Node> { val path = mutableListOf(end) var current = end while (current in cameFrom) { current = cameFrom[current]!! path.add(current) } return path } while (openSet.isNotEmpty()) { val current = openSet.minBy { fScores[it]!! } if (isEndNode(current)) return reconstructPath(cameFrom, current) openSet.remove(current) for (neighbour in neighbours(current)) { val neighbourScore = gScores[current]!! + 1 if (neighbourScore < gScores.getOrDefault(neighbour, 999999)) { cameFrom[neighbour] = current gScores[neighbour] = neighbourScore fScores[neighbour] = neighbourScore + heuristic(neighbour) if (neighbour !in openSet) openSet += neighbour } } } return emptyList() } fun List<String>.separateByBlank(): List<List<String>> { val result = mutableListOf<List<String>>() var currentList = mutableListOf<String>() for (line in this) when { line.isBlank() && currentList.isEmpty() -> continue line.isBlank() -> { result.add(currentList) currentList = mutableListOf() } else -> currentList.add(line) } if (currentList.isNotEmpty()) result.add(currentList) return result } fun Int.factorial() = (1L..this).reduce(Long::times) fun <T> List<T>.findLongestSequence(): Pair<Int, Int> { val sequences = mutableListOf<Pair<Int, Int>>() for (startPos in indices) { for (sequenceLength in 1..(this.size - startPos) / 2) { var sequencesAreEqual = true for (i in 0 until sequenceLength) if (this[startPos + i] != this[startPos + sequenceLength + i]) { sequencesAreEqual = false break } if (sequencesAreEqual) sequences += Pair(startPos, sequenceLength) } } return sequences.maxBy { it.second } } fun gcd(a: Int, b: Int): Int { if (b == 0) return a return gcd(b, a % b) } fun Long.pow(exp: Int): Long { return BigInteger.valueOf(this).pow(exp).toLong() } fun Int.pow(exp: Int): Long { return BigInteger.valueOf(this.toLong()).pow(exp).toLong() }
0
Kotlin
0
0
9f98e24485cd7afda383c273ff2479ec4fa9c6dd
8,161
aoc2022
Apache License 2.0
src/main/kotlin/day8/Day8MemoryManeuver.kt
Zordid
160,908,640
false
null
package day8 import shared.extractAllPositiveInts import shared.readPuzzle data class TreeDef(val childrenSize: Int, val metadataSize: Int) { val children = mutableListOf<TreeDef>() val metadata = mutableListOf<Int>() val metadataSum: Int get() = metadata.sum() + children.sumOf { it.metadataSum } val value: Int get() = if (childrenSize == 0) metadata.sum() else metadata.sumOf { children.getOrNull(it - 1)?.value ?: 0 } } fun createTree(data: Iterator<Int>): TreeDef = TreeDef(data.next(), data.next()).also { tree -> repeat(tree.childrenSize) { tree.children.add(createTree(data)) } repeat(tree.metadataSize) { tree.metadata += data.next() } } fun part1(puzzle: String): Any { val treeData = puzzle.extractAllPositiveInts() val trees = createTree(treeData.iterator()) return trees.metadataSum } fun part2(puzzle: String): Any { val treeData = puzzle.extractAllPositiveInts() val trees = createTree(treeData.iterator()) return trees.value } fun main() { val puzzle = readPuzzle(8).single() println(part1(puzzle)) println(part2(puzzle)) }
0
Kotlin
0
0
f246234df868eabecb25387d75e9df7040fab4f7
1,156
adventofcode-kotlin-2018
Apache License 2.0
src/advent/of/code/SecondPuzzle.kt
1nco
725,911,911
false
{"Kotlin": 112713, "Shell": 103}
package advent.of.code class SecondPuzzle { companion object { private val day = "2"; private var input: MutableList<String> = arrayListOf(); private val cubes = Game(12,13,14); private var sumOfIds = 0; private var sumOfPowers = 0; fun solve() { input.addAll(Reader.readInput(day)); input.forEach { val games = getGames(it); if (areAllGamesPossible(games)) { sumOfIds += getGameId(it); } val minGame = getMinGame(games); sumOfPowers += minGame.red * minGame.green * minGame.blue; } System.out.println("sumOfIds: " + sumOfIds); System.out.println("sumOfPowers: " + sumOfPowers); } private fun getGameId(line: String): Int { return Integer.parseInt(line.split(":")[0].replace("Game ", "").trim()); } private fun getGames(line: String): List<Game> { val gamesAsString = line.split(":")[1].trim().split(";"); return gamesAsString.map { val cubes = it.trim().split(",") Game(getCubeCountByColour(cubes, "red"), getCubeCountByColour(cubes, "green"), getCubeCountByColour(cubes, "blue")) } } private fun getCubeCountByColour(cubes: List<String>, colour: String): Int { val cube = cubes.find { it.contains(colour) } return if (cube != null) { Integer.parseInt(cube.replace(colour, "").trim()) } else { 0; } } private fun areAllGamesPossible(games: List<Game>): Boolean { return !games.map { isGamePossible(it) }.contains(false); } private fun isGamePossible(game: Game): Boolean { return game.red <= cubes.red && game.green <= cubes.green && game.blue <= cubes.blue; } private fun getMinGame(games: List<Game>): Game { var minRed = 0; var minGreen = 0; var minBlue = 0; games.forEach { if (it.red > minRed) { minRed = it.red; } if (it.green > minGreen) { minGreen = it.green; } if (it.blue > minBlue) { minBlue = it.blue; } } return Game(minRed, minGreen, minBlue); } } } class Game(red: Int, green: Int, blue: Int) { var red: Int; var green: Int; var blue: Int; init { this.red = red; this.green = green; this.blue = blue; } // public fun getRed(): Int { // return this.red; // } // // public fun setRed(value: Int) { // red = value; // } // public fun getGreen(): Int { // return this.green; // } // // public fun setGreen(value: Int) { // green = value; // } // public fun getBlue(): Int { // return this.blue; // } // // public fun setBlue(value: Int) { // blue = value; // } }
0
Kotlin
0
0
0dffdeba1ebe0b44d24f94895f16f0f21ac8b7a3
3,148
advent-of-code
Apache License 2.0
src/Day04.kt
othimar
573,607,284
false
{"Kotlin": 14557}
fun main() { fun part1(input: List<String>): Int { var result = 0 val regex = "(\\d+)-(\\d+),(\\d+)-(\\d+)".toRegex() for (line in input) { val matchesResult = regex.find(line) val (a, b, c, d) = matchesResult!!.destructured if ( ((a.toInt() in c.toInt()..d.toInt()) and (b.toInt() in c.toInt()..d.toInt())) or ((c.toInt() in a.toInt()..b.toInt()) and (d.toInt() in a.toInt()..b.toInt())) ) { result++ } } return result } fun part2(input: List<String>): Int { var result = 0 val regex = "(\\d+)-(\\d+),(\\d+)-(\\d+)".toRegex() for (line in input) { val matchesResult = regex.find(line) val (a, b, c, d) = matchesResult!!.destructured if ( ((a.toInt() in c.toInt()..d.toInt()) or (b.toInt() in c.toInt()..d.toInt())) or ((c.toInt() in a.toInt()..b.toInt()) or (d.toInt() in a.toInt()..b.toInt())) ) { result++ } } return result } check(part1(readInput("Day04_test")) == 2) check(part2(readInput("Day04_test")) == 4) val input = readInput("Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ff62a00123fe817773ff6248d34f606947ffad6d
1,337
advent-of-code-2022
Apache License 2.0
advent-of-code-2022/src/main/kotlin/eu/janvdb/aoc2022/day13/Day13.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2022.day13 import eu.janvdb.aocutil.kotlin.readGroupedLines import eu.janvdb.aocutil.kotlin.readLines //const val FILENAME = "input13-test.txt" const val FILENAME = "input13.txt" fun main() { part1() part2() } private fun part1() { val pairs = readGroupedLines(2022, FILENAME) .map { Pair(it[0].toTreeNode(), it[1].toTreeNode()) } val sum = pairs .mapIndexed { index, it -> Pair(index + 1, it) } .filter { it.second.first < it.second.second } .sumOf { it.first } println(sum) } private fun part2() { val divider1 = TreeNode(listOf(TreeLeaf(2))) val divider2 = TreeNode(listOf(TreeLeaf(6))) val packets = readLines(2022, FILENAME) .filter { it.isNotBlank() } .map { it.toTreeNode() } .plus(listOf(divider1, divider2)) .sorted() val result = (1 + packets.indexOf(divider1)) * (1 + packets.indexOf(divider2)) println(result) }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
880
advent-of-code
Apache License 2.0
Problems/Algorithms/834. Sum of Distances in Tree/SumDistancesTree.kt
xuedong
189,745,542
false
{"Kotlin": 332182, "Java": 294218, "Python": 237866, "C++": 97190, "Rust": 82753, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65}
class Solution { val graph: MutableList<HashSet<Int>> init { graph = mutableListOf() } fun sumOfDistancesInTree(n: Int, edges: Array<IntArray>): IntArray { val subsum: IntArray = IntArray(n) val count: IntArray = IntArray(n) { 1 } val ans: IntArray = IntArray(n) for (i in 0..n-1) { graph.add(hashSetOf()) } for (edge in edges) { graph[edge[0]].add(edge[1]) graph[edge[1]].add(edge[0]) } dfsCount(0, -1, count, subsum) ans[0] = subsum[0] dfsSum(0, -1, n, count, ans) return ans } private fun dfsCount(node: Int, parent: Int, count: IntArray, subsum: IntArray) { for (child in graph[node]) { if (child != parent) { dfsCount(child, node, count, subsum) count[node] += count[child] subsum[node] += subsum[child] + count[child] } } } private fun dfsSum(node: Int, parent: Int, n: Int, count: IntArray, ans: IntArray) { for (child in graph[node]) { if (child != parent) { ans[child] = ans[node] - count[child] + n - count[child] dfsSum(child, node, n, count, ans) } } } }
0
Kotlin
0
1
5e919965b43917eeee15e4bff12a0b6bea4fd0e7
1,301
leet-code
MIT License
datastructures/src/main/kotlin/com/kotlinground/datastructures/arrays/maxlencontiguoussubarray/findmaxlen.kt
BrianLusina
113,182,832
false
{"Kotlin": 483489, "Shell": 7283, "Python": 1725}
package com.kotlinground.datastructures.arrays.maxlencontiguoussubarray import kotlin.math.max /** * Finds the maximum length of a contiguous sub array in a binary array. Makes use of a hashmap to store the entries in * the form of (count, index). We make an entry for a count in the map whenever the count is encountered first and * later on use the corresponding index to find the length of the largest sub array with equal number of zeros and ones * when the same count is encountered again. * Complexity Analysis: * Time complexity : O(n). The entire array is traversed only once. * Space complexity : O(n). Maximum size of the HashMap mapmap will be n, if all the elements are either 1 or 0. * @param nums: Binary Array * @return: Maximum length of contiguous sub array */ fun findMaxLength(nums: IntArray): Int { // initializing map to (0, -1) is to avoid the edge cases like [0, 1] when you only have one zero and one. val hashmap = HashMap<Int, Int>() hashmap[0] = -1 var maxLen = 0 var count = 0 for (idx in nums.indices) { count += if (nums[idx] == 1) { 1 } else { -1 } if (hashmap.containsKey(count)) { // if the count is already present in the map, then we update the maxLen with the length of the sub array maxLen = max(maxLen, idx - hashmap[count]!!) } else { hashmap[count] = idx } } return maxLen }
1
Kotlin
1
0
5e3e45b84176ea2d9eb36f4f625de89d8685e000
1,470
KotlinGround
MIT License
src/year2021/day01/Day01.kt
kingdongus
573,014,376
false
{"Kotlin": 100767}
package year2021.day01 import readInputFileByYearAndDay import readTestFileByYearAndDay fun main() { fun part1(input: List<String>): Int { var prev = input.first().toInt() var numIncreases = 0 input.drop(1) .map { it.toInt() } .forEach { if (it > prev) numIncreases++ prev = it } return numIncreases } fun part2(input: List<String>): Int { val ints = input.map { it.toInt() } var numIncreases = 0 var windowSum = ints.take(3).sum() for (i in 3 until ints.size) { val temp = ints.subList(i - 2, i + 1).sum() if (temp > windowSum) numIncreases++ windowSum = temp } return numIncreases } val testInput = readTestFileByYearAndDay(2021, 1) check(part1(testInput) == 7) check(part2(testInput) == 5) val input = readInputFileByYearAndDay(2021, 1) println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
aa8da2591310beb4a0d2eef81ad2417ff0341384
1,015
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/day2/Day2.kt
jakubgwozdz
571,298,326
false
{"Kotlin": 85100}
package day2 import execute import readAllText import wtf fun main() { val input = readAllText("local/day2_input.txt") execute(::part1, input) execute(::part2, input) } fun part1(input: String) = input.lineSequence().filterNot(String::isBlank).sumOf(::part1result) fun part2(input: String) = input.lineSequence().filterNot(String::isBlank).sumOf(::part2result) const val A = 1 const val B = 2 const val C = 3 const val LOSE = 0 const val DRAW = 3 const val WIN = 6 private fun part1result(it: String) = when (it) { "A X" -> A + DRAW "B X" -> A + LOSE "C X" -> A + WIN "A Y" -> B + WIN "B Y" -> B + DRAW "C Y" -> B + LOSE "A Z" -> C + LOSE "B Z" -> C + WIN "C Z" -> C + DRAW else -> wtf(it) } private fun part2result(it: String) = when (it) { "A X" -> C + LOSE "B X" -> A + LOSE "C X" -> B + LOSE "A Y" -> A + DRAW "B Y" -> B + DRAW "C Y" -> C + DRAW "A Z" -> B + WIN "B Z" -> C + WIN "C Z" -> A + WIN else -> wtf(it) }
0
Kotlin
0
0
7589942906f9f524018c130b0be8976c824c4c2a
1,018
advent-of-code-2022
MIT License
lib/src/main/kotlin/io/github/nathlrowe/math/distributions/Weights.kt
nathlrowe
741,153,113
false
{"Kotlin": 101522}
package io.github.nathlrowe.math.distributions import io.github.nathlrowe.random.RandomValue import io.github.nathlrowe.utils.toPercentString import kotlin.random.Random class Weights<T>(private val rawWeights: Map<T, Double>) : RandomValue<T>, Iterable<Pair<T, Double>> { val totalWeight: Double = rawWeights.values.sum() init { require(rawWeights.isNotEmpty()) { "Weights cannot be empty." } require(totalWeight > 0) { "Total weight must be positive: $totalWeight" } } private val cumulative: List<Pair<T, Double>> = buildList { var cumulativeWeight = 0.0 rawWeights.forEach { (value, weight) -> require(weight >= 0) { "Weights must be non-negative." } add(Pair(value, cumulativeWeight)) cumulativeWeight += weight } } operator fun get(value: T): Double = rawWeights[value] ?: throw NoSuchElementException() fun probability(value: T): Double = get(value) / totalWeight fun toMap(): Map<T, Double> = rawWeights fun toNormalizedMap(): Map<T, Double> = rawWeights.mapValues { it.value / totalWeight } override fun random(random: Random): T { if (cumulative.size == 1) return cumulative.first().first val r = random.nextDouble(totalWeight) val index = cumulative.binarySearchBy(r) { it.second } return (if (index >= 0) cumulative[index] else cumulative[-index-2]).first } override fun iterator(): Iterator<Pair<T, Double>> = rawWeights.asSequence().map { it.toPair() }.iterator() override fun toString(): String { return "Weights(" + rawWeights.toList().joinToString(", ") { "${it.first} = ${it.second} (${(it.second / totalWeight).toPercentString(2)})" } + ")" } } fun <T> Weights(rawWeights: Map<T, Number>): Weights<T> = Weights(rawWeights.mapValues { it.value.toDouble() }) fun <T> Weights(rawWeights: Iterable<Pair<T, Number>>): Weights<T> = Weights(rawWeights.toMap()) fun <T> weightsOf(vararg rawWeights: Pair<T, Number>): Weights<T> { return Weights(rawWeights.associate { Pair(it.first, it.second.toDouble()) }) } fun weightsOf(vararg rawWeights: Number): Weights<Int> { return rawWeights.mapIndexed { i, weight -> Pair(i, weight) }.toWeights() } fun <T> buildWeights(builderAction: WeightsBuilder<T>.() -> Unit): Weights<T> { return WeightsBuilder<T>().apply(builderAction).build() } fun <T> Iterable<T>.mapWeights(weightSelector: (T) -> Number): Weights<T> { return Weights(associateWith(weightSelector)) } fun <T> Map<T, Number>.toWeights(): Weights<T> = Weights(this) fun <T> Iterable<Pair<T, Number>>.toWeights(): Weights<T> = Weights(toMap()) class WeightsBuilder<T> internal constructor() { private val rawWeights: MutableMap<T, Double> = mutableMapOf() private val rawProbabilities: MutableMap<T, Double> = mutableMapOf() fun set(value: T, weight: Number) { val weightDouble = weight.toDouble() require(value !in rawWeights && value !in rawProbabilities) require(weightDouble >= 0) rawWeights[value] = weightDouble } fun set(weights: Weights<T>, weight: Number) { weights.forEach { (value, _) -> set(value, weight.toDouble() * weights.probability(value)) } } fun setProbability(value: T, probability: Double) { require(value !in rawWeights && value !in rawProbabilities) require(probability in 0.0..1.0) rawProbabilities[value] = probability } fun setProbability(weights: Weights<T>, probability: Double) { weights.forEach { (value, _) -> set(value, probability * weights.probability(value)) } } fun build(): Weights<T> { return when { rawWeights.isEmpty() && rawProbabilities.isEmpty() -> throw IllegalStateException("Weights and probabilities cannot both be empty.") rawProbabilities.isEmpty() -> Weights(rawWeights) rawWeights.isEmpty() -> Weights(rawProbabilities) else -> { val rawWeights = buildMap { val totalWeight = rawWeights.values.sum() val totalProbability = rawProbabilities.values.sum() rawWeights.forEach { (value, weight) -> set(value, (weight / totalWeight) * (1 - totalProbability)) } rawProbabilities.forEach { (value, probability) -> set(value, probability) } } Weights(rawWeights) } } } }
0
Kotlin
0
0
433528d09a68eb866bec73b96dc3a1537d609f03
4,642
kotlin-utils
MIT License
capitulo5/src/main/kotlin/5.23(Números palíndromos).kt
Cursos-Livros
667,537,024
false
{"Kotlin": 104564}
//5.23 (Números palíndromos) Um número inteiro positivo é um palíndromo se seu valor for o mesmo depois de inverter //a ordem dos dígitos no número. Por exemplo, 12321 é um palíndromo, mas 12563 não é. //Escreva um método que determine se um número é um palíndromo. Use este método em um aplicativo que determina se um //número digitado pelo usuário é um palíndromo ou não e imprime oresultado para o console. fun main() { println("Digite um número de até 5 dígitos:") val numero = leInput9() testaIntervaloNumero(numero) var palindromo = 0 when (testaIntervaloNumero(numero)) { true -> palindromo = verificaDigito(numero) false -> intervaloErrado() } verificaPalindromo(numero, palindromo) } fun leInput9(): Int { val input = readLine() ?: "0" return input.toInt() } fun testaIntervaloNumero(numero: Int): Boolean { val teste = numero > 0 && numero < 99999 return teste } fun verificaDigito(numero: Int): Int { var numeroDigito = numero var resultado = 0 while (numeroDigito != 0) { val digito = numeroDigito % 10 // Salva o ultimo numero resultado = resultado * 10 + digito numeroDigito /= 10 // Retira o ultimo numero } return resultado } fun intervaloErrado() { println("O numero nao esta entre 0 e 99999") } fun verificaPalindromo(numero: Int, palindromo: Int) { if (numero == palindromo) { println("É um palíndromo") } else { println("Não é palíndromo") } }
0
Kotlin
0
0
f2e005135a62b15360c2a26fb6bc2cbad18812dd
1,537
Kotlin-Como-Programar
MIT License
src/commonMain/kotlin/advent2020/day10/Day10Puzzle.kt
jakubgwozdz
312,526,719
false
null
package advent2020.day10 // Disclaimer, my solution was much uglier (although it worked in decent time complexity) // This was developed after the hint from a friend // Also, I should've looked at the puzzle name, which literally was "Adapter Array" // It is now true O(n) fun part1(input: String): String { val adapters = input.trim().lines().map(String::toInt) val array = BooleanArray(adapters.maxOrNull()!! + 1) adapters.forEach { array[it] = true } var sinceLast = 0 var ones = 0 var threes = 0 array.forEach { exists -> if (exists) { if (sinceLast == 1) ones++ if (sinceLast == 3) threes++ sinceLast = 0 } sinceLast++ } threes++ // at the end there is 3 to the device return (ones * threes).toString() } fun part2(input: String): String { val adapters = input.trim().lines().map(String::toInt) val array = BooleanArray(adapters.maxOrNull()!! + 1) adapters.forEach { array[it] = true } val variations = LongArray(array.size) variations[0] = 1L array.forEachIndexed { index, exists -> if (exists) { var v = 0L if (index > 0) v += variations[index - 1] if (index > 1) v += variations[index - 2] if (index > 2) v += variations[index - 3] variations[index] = v } } val last = variations.last() return last.toString() }
0
Kotlin
0
2
e233824109515fc4a667ad03e32de630d936838e
1,445
advent-of-code-2020
MIT License
src/main/kotlin/algorithms/Clumps.kt
jimandreas
377,843,697
false
null
@file:Suppress("UnnecessaryVariable") package algorithms /** * Returns a new character sequence that is a subsequence of this character sequence * * @param stringToSearch where to look for clumps * @param occurenceMin filter level for number of clumps in a window * @param windowLen length of window to search * @param clumpLengthMin threshold of clump length */ fun findClumps(stringToSearch: String, clumpLengthMin: Int, windowLen: Int, occurenceMin: Int ) : List<Pair<String, Int>> { val accumulationMap : MutableMap<String, Int> = HashMap() for (i in 0..stringToSearch.length-windowLen) { val substring = stringToSearch.substring(i, i+windowLen) val foundStrings = frequencyTable(substring, clumpLengthMin) // filter out any with occurence less than occurenceMin val passingStrings = foundStrings.filter { it.value >= occurenceMin } //if (passingStrings.isNotEmpty()) println(passingStrings) accumulationMap += passingStrings } val retMap = accumulationMap.toList().distinct() return retMap } /** * Returns a map of all unique substrings that are of [kmerLength] * and a frequency of the occurrence. The list is unsorted. * * @param windowString the string to scan * @param kmerLength length of the scan window * @return map of substring to occurence count */ fun frequencyTable(windowString: String, kmerLength: Int): Map<String, Int> { val map: MutableMap<String, Int> = HashMap() // var maxValue = 0 for (i in 0..windowString.length-kmerLength) { val substring = windowString.substring(i, i+kmerLength) increment(map, substring) //maxValue = Integer.max(maxValue, map[substring] ?: 0) } return map.toMap() } /** * add the [key] to the [map]. Increment the count of the key in the map. * @param map - a mutable map of type K * @param key - they key of type K to add to the map * @link https://www.techiedelight.com/increment-value-map-kotlin/ */ private fun <K> increment(map: MutableMap<K, Int>, key: K) { map.putIfAbsent(key, 0) map[key] = map[key]!! + 1 }
0
Kotlin
0
0
fa92b10ceca125dbe47e8961fa50242d33b2bb34
2,123
stepikBioinformaticsCourse
Apache License 2.0
src/day08/Day08Answer1.kt
underwindfall
573,471,357
false
{"Kotlin": 42718}
fun main() { val dayId = "08" val input = readInput("Day${dayId}") val a = input.map { s -> s.map { it.digitToInt() } } val n = a.size val m = a[0].size // part 1 val v = Array(n) { BooleanArray(m) } for (i in 0 until n) { var h = -1 for (j in 0 until m) { if (a[i][j] > h) { h = a[i][j] v[i][j] = true } } h = -1 for (j in m - 1 downTo 0) { if (a[i][j] > h) { h = a[i][j] v[i][j] = true } } } for (j in 0 until m) { var h = -1 for (i in 0 until n) { if (a[i][j] > h) { h = a[i][j] v[i][j] = true } } h = -1 for (i in n - 1 downTo 0) { if (a[i][j] > h) { h = a[i][j] v[i][j] = true } } } println(v.sumOf { it.count { it } }) // part 2 var ans2 = 0 for (i in 0 until n) { for (j in 0 until m) { var d1 = j for (k in j - 1 downTo 0) { if (a[i][k] >= a[i][j]) { d1 = j - k break } } var d2 = m - j - 1 for (k in j + 1 until m) { if (a[i][k] >= a[i][j]) { d2 = k - j break } } var d3 = i for (k in i - 1 downTo 0) { if (a[k][j] >= a[i][j]) { d3 = i - k break } } var d4 = n - i - 1 for (k in i + 1 until n) { if (a[k][j] >= a[i][j]) { d4 = k - i break } } val f = d1 * d2 * d3 * d4 if (f > ans2) ans2 = f } } println(ans2) }
0
Kotlin
0
0
967812138a7ee110a63e1950cae9a799166a6ba8
1,981
aoc-2022
Apache License 2.0
kotlin/basics/src/main/kotlin/UnionFind.kt
suzp1984
65,159,392
false
{"C++": 29471, "Java": 26106, "Kotlin": 10984, "Scala": 9694, "JavaScript": 3248, "CMake": 442, "Swift": 171}
package io.github.suzp1984.algorithms class UnionFind(size : Int) { val ids : Array<Int> init { ids = Array(size) { it } } private fun find(p : Int) : Int { if (p < 0 || p > ids.size) throw IllegalArgumentException("array out of scope") return ids[p] } fun isConnected(q : Int, p : Int) : Boolean { if (q >= 0 && q < ids.size && p >= 0 && p < ids.size) { return ids[p] == ids[q] } throw IllegalArgumentException("array out of scope") } fun unionElements(p : Int, q : Int) { val pId = find(p) val qId = find(q) if (pId == qId) { return } ids.indices .filter { ids[it] == pId } .forEach { ids[it] = qId } } } class UnionFind2(size : Int) { private val ids : Array<Int> init { ids = Array(size) { it } } private fun find(p : Int) : Int { if (p < 0 || p > ids.size) throw IllegalArgumentException("array out of scope") var i = p while (i != ids[i]) i = ids[i] return i } fun isConnected(q : Int, p : Int) : Boolean { return find(q) == find(p) } fun unionElements(p : Int, q : Int) { val pId = find(p) val qId = find(q) if (pId == qId) { return } ids[pId] = qId } }
0
C++
0
0
ea678476a4c70e5135d31fccd8383fac989cc031
1,434
Algorithms-Collection
Apache License 2.0
src/Day01.kt
Venkat-juju
572,834,602
false
{"Kotlin": 27944}
fun main() { fun part1(input: List<String>): Int { val totalCalories = mutableListOf<Int>() var currentTotal = 0 input.forEach { if (it.isBlank()) { totalCalories.add(currentTotal) currentTotal = 0 } else { currentTotal += it.toInt() } } return totalCalories.max() } fun part2(input: List<String>): Int { val totalCalories = mutableListOf<Int>() var currentTotal = 0 input.forEach { if (it.isBlank()) { totalCalories.add(currentTotal) currentTotal = 0 } else { currentTotal += it.toInt() } } return totalCalories.sorted().takeLast(3).reduce { acc, i -> acc + i } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 1) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
785a737b3dd0d2259ccdcc7de1bb705e302b298f
1,073
aoc-2022
Apache License 2.0
src/main/kotlin/year2022/day18/Problem.kt
Ddxcv98
573,823,241
false
{"Kotlin": 154634}
package year2022.day18 import IProblem class Problem : IProblem { private val points = javaClass .getResource("/2022/18.txt")!! .readText() .lines() .filter(String::isNotEmpty) .map { val split = it.split(',').map(String::toInt) Point(split[0], split[1], split[2]) } private val depth = points.maxOf(Point::x) + 2 private val height = points.maxOf(Point::y) + 2 private val width = points.maxOf(Point::z) + 2 private val map: Array<Array<BooleanArray>> = Array(depth) { Array(height) { BooleanArray(width) } } init { for ((x, y, z) in points) { map[x][y][z] = true } } private fun floodFill(visited: Array<Array<BooleanArray>>, i: Int, j: Int, k: Int): Int { if (visited[i][j][k]) { return 0 } visited[i][j][k] = true var n = 0 if (i != 0) { n += if (map[i - 1][j][k]) { 1 } else { floodFill(visited, i - 1, j, k) } } if (i != depth - 1) { n += if (map[i + 1][j][k]) { 1 } else { floodFill(visited, i + 1, j, k) } } if (j != 0) { n += if (map[i][j - 1][k]) { 1 } else { floodFill(visited, i, j - 1, k) } } if (j != height - 1) { n += if (map[i][j + 1][k]) { 1 } else { floodFill(visited, i, j + 1, k) } } if (k != 0) { n += if (map[i][j][k - 1]) { 1 } else { floodFill(visited, i, j, k - 1) } } if (k != width - 1) { n += if (map[i][j][k + 1]) { 1 } else { floodFill(visited, i, j, k + 1) } } return n } override fun part1(): Int { var count = 0 for ((x, y, z) in points) { if (!map[x - 1][y][z]) { count++ } if (!map[x + 1][y][z]) { count++ } if (!map[x][y - 1][z]) { count++ } if (!map[x][y + 1][z]) { count++ } if (!map[x][y][z - 1]) { count++ } if (!map[x][y][z + 1]) { count++ } } return count } override fun part2(): Int { val visited = Array(depth) { Array(height) { BooleanArray(width) } } return floodFill(visited, 0, 0, 0) } }
0
Kotlin
0
0
455bc8a69527c6c2f20362945b73bdee496ace41
2,756
advent-of-code
The Unlicense
codeforces/round626/b.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.round626 fun main() { readLn() var a = readInts().sorted() val powers = a.last().toString(2).length downTo 0 val ans = powers.sumBy { k -> val two = 1 shl k val res = (1..4).sumBy { countLess(a, it * two) } and 1 a = a.map { it and two - 1 }.sorted() two * res } println(ans) } private fun countLess(a: List<Int>, value: Int): Int { var j = a.lastIndex return a.indices.sumBy { i -> while (j >= 0 && a[i] + a[j] >= value) j-- minOf(i, j + 1) } } private fun readLn() = readLine()!! private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
631
competitions
The Unlicense
aoc-2020/src/commonMain/kotlin/fr/outadoc/aoc/twentytwenty/Day19.kt
outadoc
317,517,472
false
{"Kotlin": 183714}
package fr.outadoc.aoc.twentytwenty import fr.outadoc.aoc.scaffold.Day import fr.outadoc.aoc.scaffold.readDayInput class Day19 : Day<Int> { private val sections: List<String> = readDayInput().split("\n\n") private val step1Rules: Map<Int, String> = sections[0] .lines() .associate { line -> line.split(": ") .let { parts -> parts[0].toInt() to parts[1] } } private val step2Rules: Map<Int, String> = step1Rules.mapValues { (key, rule) -> when (key) { 8 -> "42 | 42 8" 11 -> "42 31 | 42 11 31" else -> rule } } private val messages: List<String> = sections[1].lines() private fun String.ruleToPattern(rules: Map<Int, String>): String = when { contains("\"") -> replace("\"", "") else -> when (this) { // Special handling for modified rule 8, fuck it: repeating pattern "42 | 42 8" -> "(${rules.getValue(42).ruleToPattern(rules)}+)" // Special handling for modified rule 11, fuck it: // right side and left side must repeat the same number of times "42 31 | 42 11 31" -> (1..4).joinToString(separator = "|") { n -> "${rules.getValue(42).ruleToPattern(rules)}{$n}" + "${rules.getValue(31).ruleToPattern(rules)}{$n}" }.let { pattern -> "($pattern)" } else -> split(" | ") .joinToString(separator = "|") { orGroup -> orGroup.split(" ") .joinToString(separator = "") { ruleIndex -> val rule = rules.getValue(ruleIndex.toInt()) rule.ruleToPattern(rules) } }.let { pattern -> "($pattern)" } } } private fun Map<Int, String>.getRule(pos: Int): Regex { val pattern = getValue(pos).ruleToPattern(this) return Regex(pattern = "^$pattern$") } override fun step1(): Int { val rule0 = step1Rules.getRule(0) return messages.count { message -> rule0.matches(message) } } override fun step2(): Int { val rule0 = step2Rules.getRule(0) return messages.count { message -> rule0.matches(message) } } override val expectedStep1: Int = 160 override val expectedStep2: Int = 357 }
0
Kotlin
0
0
54410a19b36056a976d48dc3392a4f099def5544
2,760
adventofcode
Apache License 2.0
src/main/kotlin/com/colinodell/advent2022/Day09.kt
colinodell
572,710,708
false
{"Kotlin": 105421}
package com.colinodell.advent2022 class Day09(input: List<String>) { private val directions = mapOf( "L" to Vector2(-1, 0), "R" to Vector2(1, 0), "U" to Vector2(0, -1), "D" to Vector2(0, 1), ) /** * Generate a sequence of all points the head knot passes through */ private val headKnotPositions = sequence { var pos = Vector2(0, 0) yield(pos) for (line in input) { val (dir, count) = line.split(" ") repeat(count.toInt()) { pos += directions[dir]!! yield(pos) } } } fun solvePart1() = solveFor(2) fun solvePart2() = solveFor(10) /** * Count the number of distinct points the tail knot passes through */ private fun solveFor(knotCount: Int) = createRope(knotCount).last().distinct().count() /** * Create a sequence where each subsequent knot follows the one before it */ private fun createRope(knotCount: Int) = generateSequence(headKnotPositions) { follow(it) }.take(knotCount) /** * Follow the given knot, yielding the points it passes through */ private fun follow(leadingKnot: Sequence<Vector2>) = sequence { var followerPos = Vector2(0, 0) yield(followerPos) for (leadPos in leadingKnot) { while (!followerPos.isTouching(leadPos)) { // Move towards the head position one step at a time followerPos += (leadPos - followerPos).normalize() yield(followerPos) } } } }
0
Kotlin
0
1
32da24a888ddb8e8da122fa3e3a08fc2d4829180
1,608
advent-2022
MIT License
src/Day01.kt
daletools
573,114,602
false
{"Kotlin": 8945}
fun main() { fun part1(input: List<String>): Int { val elves = IntArray(input.filter { it.isEmpty() }.size + 1) var elf = 0 for (item in input) { val cal = item.toIntOrNull() if (cal != null) { elves[elf] += cal } else { elf++ } } return elves.maxOrNull() ?: 0 } fun part2(input: List<String>): Int { val elves = IntArray(input.filter { it.isEmpty() }.size + 1) var elf = 0 for (item in input) { val cal = item.toIntOrNull() if (cal != null) { elves[elf] += cal } else { elf++ } } var cals = 0 repeat(3) { val max = elves.maxOrNull() ?: 0 elves[elves.indexOf(max)] = 0 cals += max } return cals } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") println(part2(testInput)) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c955c5d0b5e19746e12fa6a569eb2b6c3bc4b355
1,156
adventOfCode2022
Apache License 2.0
src/main/kotlin/g1701_1800/s1766_tree_of_coprimes/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1701_1800.s1766_tree_of_coprimes // #Hard #Math #Depth_First_Search #Breadth_First_Search #Tree // #2023_06_18_Time_991_ms_(100.00%)_Space_89.3_MB_(100.00%) @Suppress("kotlin:S107") class Solution { private fun dfs( v2n: IntArray, v2d: IntArray, depth: Int, parent: Int, node: Int, ans: IntArray, nums: IntArray, neighbors: Array<ArrayList<Int>> ) { var d = Int.MIN_VALUE var n = -1 val v = nums[node] for (i in 1..50) { if (v2n[i] != -1 && v2d[i] > d && gcd(i, v) == 1) { d = v2d[i] n = v2n[i] } } ans[node] = n val v2NOld = v2n[v] val v2DOld = v2d[v] v2n[v] = node v2d[v] = depth for (child in neighbors[node]) { if (child == parent) { continue } dfs(v2n, v2d, depth + 1, node, child, ans, nums, neighbors) } v2n[v] = v2NOld v2d[v] = v2DOld } private fun gcd(x: Int, y: Int): Int { return if (x == 0) y else gcd(y % x, x) } fun getCoprimes(nums: IntArray, edges: Array<IntArray>): IntArray { val n = nums.size val neighbors: Array<ArrayList<Int>> = Array(n) { ArrayList() } for (i in 0 until n) { neighbors[i] = ArrayList() } for (edge in edges) { neighbors[edge[0]].add(edge[1]) neighbors[edge[1]].add(edge[0]) } val ans = IntArray(n) val v2n = IntArray(51) val v2d = IntArray(51) v2n.fill(-1) dfs(v2n, v2d, 0, -1, 0, ans, nums, neighbors) return ans } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,723
LeetCode-in-Kotlin
MIT License
kotlin/src/com/s13g/aoc/aoc2021/Day22.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2021 import com.s13g.aoc.Result import com.s13g.aoc.Solver import kotlin.math.abs /** * --- Day 22: Reactor Reboot --- * https://adventofcode.com/2021/day/22 */ class Day22 : Solver { val regex = """(\w+)+ x=([-]*\d+)..([-]*\d+),y=([-]*\d+)..([-]*\d+),z=([-]*\d+)..([-]*\d+)""".toRegex() override fun solve(lines: List<String>): Result { val partA = run(lines, true) val partB = run(lines, false) return Result("$partA", "$partB") } fun run(lines: List<String>, partA: Boolean): Long { // Note: We always want a world where no cube intersects. // Also, all cubes are always "on". val world = mutableSetOf<Cuboid>() for (line in lines) { val (cube, on) = parseLine(line) // Only consider lines within the -50..50 space for partA. if (partA && listOf( cube.from.x, cube.from.y, cube.from.z, cube.to.x, cube.to.y, cube.to.z ).map { abs(it) }.max()!! > 50 ) continue // We cut away the overlapping pieces from all existing cubes. // This way if the new cube is on, we can add it completely. // If it's off, we don't add it and thus remove the intersection. for (existingCube in world.toList()) { if (cube.intersects(existingCube)) { world.remove(existingCube) world.addAll(existingCube.carve(cube)) } } if (on) world.add(cube) // After each step there should be no intersecting cubes. } return world.map { it.size() }.sum() } private class Cuboid(val from: XYZ, val to: XYZ) { fun carve(other: Cuboid): Set<Cuboid> { // Generate 3x3x3 - 1 (max split cubes) val xes = listOf(from.x, other.from.x, to.x, other.to.x).sorted() val yes = listOf(from.y, other.from.y, to.y, other.to.y).sorted() val zes = listOf(from.z, other.from.z, to.z, other.to.z).sorted() val allTwentySeven = mutableSetOf<Cuboid>() for (ix in 1 until xes.size) { for (iy in 1 until yes.size) { for (iz in 1 until zes.size) { allTwentySeven.add( Cuboid( XYZ(xes[ix - 1], yes[iy - 1], zes[iz - 1]), XYZ(xes[ix], yes[iy], zes[iz]) ) ) } } } // We now have 27 cuboids. First, remove all the ones that are outside // the initial cuboid or have zero size. val onlyInside = allTwentySeven.filter { this.intersects(it) && it.size() != 0L }.toSet() // Next, there should be a single cuboid that overlaps the 'other'. // Remove it from the set. return onlyInside.filter { !other.intersects(it) }.toSet() } fun intersects(other: Cuboid) = contains(other) || other.contains(this) fun contains(other: Cuboid) = (other.from.x < this.to.x && other.to.x > this.from.x) && (other.from.y < this.to.y && other.to.y > this.from.y) && (other.from.z < this.to.z && other.to.z > this.from.z) fun size(): Long = (to.x - from.x) * (to.y - from.y) * (to.z - from.z) } private fun parseLine(line: String): Pair<Cuboid, Boolean> { val (onOff, x1, x2, y1, y2, z1, z2) = regex.find(line)!!.destructured return Pair( Cuboid( XYZ(x1.toLong(), y1.toLong(), z1.toLong()), XYZ(x2.toLong() + 1, y2.toLong() + 1, z2.toLong() + 1) ), onOff == "on" ) } private data class XYZ(val x: Long, val y: Long, val z: Long) }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
3,518
euler
Apache License 2.0
src/aoc2022/Day18.kt
RobertMaged
573,140,924
false
{"Kotlin": 225650}
package aoc2022 import utils.checkEquals import utils.sendAnswer private data class Coor3D(val x: Int, val y: Int, val z: Int) fun main() { fun part1(input: List<String>): Int { val cubes = input.map { val cube = it.split(',').map { it.toInt() } Coor3D(cube[0], cube[1], cube[2]) } return cubes.sumOf { val l = listOf( it.copy(x = it.x - 1), it.copy(x = it.x + 1), it.copy(y = it.y - 1), it.copy(y = it.y + 1), it.copy(z = it.z - 1), it.copy(z = it.z + 1), ) return@sumOf 6 - (l intersect cubes).size } } fun part2(input: List<String>): Int { return input.size } // parts execution val testInput = readInput("Day18_test") val input = readInput("Day18") part1(testInput).checkEquals(64) part1(input) .sendAnswer(part = 1, day = "18", year = 2022) part2(testInput).checkEquals(TODO()) part2(input) .sendAnswer(part = 2, day = "18", year = 2022) }
0
Kotlin
0
0
e2e012d6760a37cb90d2435e8059789941e038a5
1,112
Kotlin-AOC-2023
Apache License 2.0
src/main/kotlin/com/github/freekdb/kotlin/workshop/step04/BirthdayPuzzle.kt
FreekDB
230,429,337
false
null
package com.github.freekdb.kotlin.workshop.step04 /** * A puzzle: Calvin and Hobbes are celebrating their birthdays. * * One is '44' in base a, * the other is '55' in base b, * the sum of their ages is '77' in base c and * the difference is '111' in base d. * d < a < b < c and all are natural numbers. * Hobbes is younger than Calvin. * * P.S. The names of my colleagues have been replaced by those of two famous * last century cartoon characters: * "Calvin and Hobbes follows the humorous antics of the title characters: * Calvin, a precocious, mischievous and adventurous six-year-old boy; and * Hobbes, his sardonic stuffed tiger." * https://en.wikipedia.org/wiki/Calvin_and_Hobbes */ fun main() { solveVersion1() println() solveVersion2() } private fun solveVersion1() { for (baseC in 8..16) { val sum = "77".toInt(baseC) for (baseB in 6 until baseC) { val ageCalvin = "55".toInt(baseB) for (baseA in 5 until baseB) { val ageHobbes = "44".toInt(baseA) if (sum == ageHobbes + ageCalvin) { for (baseD in 2 until baseA) { val difference = "111".toInt(baseD) if (difference == ageCalvin - ageHobbes) { println( "Found age Hobbes: $ageHobbes and age Calvin: $ageCalvin, " + "with bases a: $baseA, b: $baseB, c: $baseC, and d: $baseD." ) } } } } } } } private fun solveVersion2() { (8..16).forEach { baseC -> val sum = "77".toInt(baseC) (6 until baseC).forEach { baseB -> val ageCalvin = "55".toInt(baseB) (5 until baseB) .filter { sum == "44".toInt(it) + ageCalvin } .forEach { baseA -> val ageHobbes = "44".toInt(baseA) (2 until baseA) .filter { "111".toInt(it) == ageCalvin - ageHobbes } .forEach { baseD -> println( "Found age Hobbes: $ageHobbes and age Calvin: $ageCalvin, " + "with bases a: $baseA, b: $baseB, c: $baseC, and d: $baseD." ) } } } } }
0
Kotlin
0
2
5a9bb08a8d0bd3d68dd2274becf4758ab10caf5d
2,494
kotlin-for-kurious-koders
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindWinners.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 /** * 2225. Find Players With Zero or One Losses * @see <a href="https://leetcode.com/problems/find-players-with-zero-or-one-losses/">Source</a> */ fun interface FindWinners { operator fun invoke(matches: Array<IntArray>): List<List<Int>> } /** * Approach 1: Hash Set */ class FindWinnersHashSet : FindWinners { override operator fun invoke(matches: Array<IntArray>): List<List<Int>> { val zeroLoss: MutableSet<Int> = HashSet() val oneLoss: MutableSet<Int> = HashSet() val moreLosses: MutableSet<Int> = HashSet() for (match in matches) { val winner = match[0] val loser = match[1] // Add winner. if (!oneLoss.contains(winner) && !moreLosses.contains(winner)) { zeroLoss.add(winner) } // Add or move loser. when { zeroLoss.contains(loser) -> { zeroLoss.remove(loser) oneLoss.add(loser) } oneLoss.contains(loser) -> { oneLoss.remove(loser) moreLosses.add(loser) } moreLosses.contains(loser) -> { continue } else -> { oneLoss.add(loser) } } } val answer: List<MutableList<Int>> = listOf(ArrayList(), ArrayList()) answer[0].addAll(zeroLoss) answer[1].addAll(oneLoss) answer[0].sort() answer[1].sort() return answer } } /** * Approach 2: Hash Set + Hash Map */ class FindWinnersSetMap : FindWinners { override operator fun invoke(matches: Array<IntArray>): List<List<Int>> { val seen: MutableSet<Int> = HashSet() val lossesCount: MutableMap<Int, Int> = HashMap() for (match in matches) { val winner = match[0] val loser = match[1] seen.add(winner) seen.add(loser) lossesCount[loser] = (lossesCount[loser] ?: 0) + 1 } // Add players with 0 or 1 loss to the corresponding list. val answer: List<MutableList<Int>> = listOf(ArrayList(), ArrayList()) for (player in seen) { if (!lossesCount.containsKey(player)) { answer[0].add(player) } else if (lossesCount[player] == 1) { answer[1].add(player) } } answer[0].sort() answer[1].sort() return answer } } /** * Approach 3: Hash Map */ class FindWinnersMap : FindWinners { override operator fun invoke(matches: Array<IntArray>): List<List<Int>> { val lossesCount: MutableMap<Int, Int> = HashMap() for (match in matches) { val winner = match[0] val loser = match[1] lossesCount[winner] = lossesCount[winner] ?: 0 lossesCount[loser] = (lossesCount[loser] ?: 0) + 1 } val answer: List<MutableList<Int>> = listOf(ArrayList(), ArrayList()) for (player in lossesCount.keys) if (lossesCount[player] == 0) { answer[0].add(player) } else if (lossesCount[player] == 1) { answer[1].add(player) } answer[0].sort() answer[1].sort() return answer } } /** * Approach 4: Counting with Array */ class FindWinnersCounting : FindWinners { companion object { private const val LIMIT = 100001 } override operator fun invoke(matches: Array<IntArray>): List<List<Int>> { val lossesCount = IntArray(LIMIT) { -1 } for (match in matches) { val winner = match[0] val loser = match[1] if (lossesCount[winner] == -1) { lossesCount[winner] = 0 } if (lossesCount[loser] == -1) { lossesCount[loser] = 1 } else { lossesCount[loser]++ } } val answer: List<MutableList<Int>> = listOf(ArrayList(), ArrayList()) for (i in 1 until LIMIT) { if (lossesCount[i] == 0) { answer[0].add(i) } else if (lossesCount[i] == 1) { answer[1].add(i) } } return answer } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
4,952
kotlab
Apache License 2.0
src/main/kotlin/biz/koziolek/adventofcode/year2022/day11/day11.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2022.day11 import biz.koziolek.adventofcode.findInput fun main() { val inputFile = findInput(object {}) val monkeys = parseMonkeys(inputFile.bufferedReader().readLines()) val monkeys20 = playKeepAway(monkeys, rounds = 20) println("Monkey business after 20 rounds: ${getMonkeyBusiness(monkeys20)}") val upgradedMonkeys = upgradeItems(monkeys) val monkeys10000 = playKeepAway(upgradedMonkeys, rounds = 10000, worryDivider = 1) println("Monkey business after 10 000 rounds: ${getMonkeyBusiness(monkeys10000)}") } data class Monkey( val id: Int, val items: List<Item>, val operation: (Item) -> Item, val test: (Item) -> Boolean, val targets: Map<Boolean, Int>, val inspectedItems: Long = 0, ) { fun inspectItems(worryDivider: Int): Pair<Monkey, List<Pair<Item, Int>>> = copy( items = emptyList(), inspectedItems = inspectedItems + items.size, ) to items.map { item -> val worryLevel = operation(item) / worryDivider val testResult = test(worryLevel) val targetID = targets[testResult] ?: throw IllegalStateException("No target found for $worryLevel at $this") worryLevel to targetID } fun addItem(item: Item): Monkey = copy(items = items + item) } sealed interface Item { operator fun plus(number: Int): Item operator fun times(number: Int): Item operator fun div(number: Int): Item fun square(): Item fun isDivisible(factor: Int): Boolean } data class SimpleItem( val value: Int ) : Item { override fun plus(number: Int): Item = copy(value = value + number) override fun times(number: Int): Item = copy(value = value * number) override fun div(number: Int): Item = copy(value = value / number) override fun square(): Item = copy(value = value * value) override fun isDivisible(factor: Int): Boolean = value % factor == 0 } data class RemainderOnlyItem( val divisorsAndRemainders: Map<Int, Int> ) : Item { companion object { fun create(divisors: Set<Int>, number: Int): RemainderOnlyItem = RemainderOnlyItem( divisorsAndRemainders = divisors.associateWith { number % it }, ) } override fun plus(number: Int): Item = copy( divisorsAndRemainders = divisorsAndRemainders.mapValues { (divisor, remainder) -> (remainder + number) % divisor }, ) override fun times(number: Int): Item = copy( divisorsAndRemainders = divisorsAndRemainders.mapValues { (divisor, remainder) -> (remainder * number) % divisor }, ) override fun div(number: Int): Item = when (number) { 1 -> this else -> throw UnsupportedOperationException("Division is not supported for RemainderOnlyItem") } override fun square(): Item = copy( divisorsAndRemainders = divisorsAndRemainders.mapValues { (divisor, remainder) -> (remainder * remainder) % divisor }, ) override fun isDivisible(factor: Int): Boolean = divisorsAndRemainders[factor] == 0 } data class Multiply(val value: Int) : (Item) -> Item { override fun invoke(item: Item): Item = item * value } data class Add(val value: Int) : (Item) -> Item { override fun invoke(item: Item): Item = item + value } object Square : (Item) -> Item { override fun invoke(item: Item): Item = item.square() } data class Divisible(val value: Int) : (Item) -> Boolean { override fun invoke(item: Item): Boolean = item.isDivisible(value) } fun parseMonkeys(lines: Iterable<String>): List<Monkey> = buildList { val iterator = lines.iterator() while (iterator.hasNext()) { val firstLine = iterator.next() if (firstLine.startsWith("Monkey ")) { val id = firstLine.let { line -> Regex("Monkey ([0-9]+)") .find(line) ?.groups?.get(1)?.value ?.toInt() ?: throw IllegalStateException("Could not find monkey's ID in: '$line'") } val items = iterator.next().let { line -> Regex("Starting items: (.+)$") .find(line) ?.groups?.get(1)?.value ?.split(',') ?.map { SimpleItem(it.trim().toInt()) } ?: throw IllegalStateException("Could parse starting items in: '$line'") } val operation = iterator.next().let { line -> Regex("Operation: new = old ([+*]) ([0-9]+|old)$") .find(line) ?.let { result -> val operator = result.groups[1]?.value val operand = result.groups[2]?.value if (operator == "*" && operand == "old") { Square } else if (operator == "*") { Multiply(operand!!.toInt()) } else { Add(operand!!.toInt()) } } ?: throw IllegalStateException("Could parse operation in: '$line'") } val test = iterator.next().let { line -> Regex("Test: divisible by ([0-9]+)$") .find(line) ?.groups?.get(1)?.value ?.toInt() ?.let { Divisible(it) } ?: throw IllegalStateException("Could parse test in: '$line'") } val targets = listOf(iterator.next(), iterator.next()) .associate { line -> Regex("If (true|false): throw to monkey ([0-9]+)") .find(line) ?.let { result -> val boolean = result.groups[1]!!.value.toBoolean() val monkeyID = result.groups[2]!!.value.toInt() boolean to monkeyID } ?: throw IllegalStateException("Could not parse target in: '$line'") } add( Monkey( id = id, items = items, operation = operation, test = test, targets = targets, ) ) } } } fun playKeepAway(monkeys: List<Monkey>, rounds: Int, worryDivider: Int = 3): List<Monkey> = (1..rounds) .fold(monkeys) { currentMonkeys, _ -> playKeepAway(currentMonkeys, worryDivider) } fun playKeepAway(monkeys: List<Monkey>, worryDivider: Int = 3): List<Monkey> = monkeys.map { it.id } .sorted() .fold(monkeys) { currentMonkeys, currentID -> val currentMonkey = currentMonkeys.find { it.id == currentID }!! val (updatedMonkey, itemsToTargets) = currentMonkey.inspectItems(worryDivider) currentMonkeys .map { monkey -> when (monkey.id) { currentID -> updatedMonkey else -> monkey } } .map { monkey -> itemsToTargets.fold(monkey) { m, (item, targetID) -> when (m.id) { targetID -> m.addItem(item) else -> m } } } } fun getMonkeyBusiness(monkeys: List<Monkey>): Long = monkeys .map { it.inspectedItems } .sortedDescending() .take(2) .reduce(Long::times) fun upgradeItems(monkeys: List<Monkey>): List<Monkey> { val divisors = monkeys .map { monkey -> when (monkey.test) { is Divisible -> monkey.test.value else -> throw IllegalArgumentException("Unsupported test ${monkey.test} for $monkey") } } .toSet() return monkeys.map { monkey -> monkey.copy( items = monkey.items.map { item -> when (item) { is RemainderOnlyItem -> item is SimpleItem -> RemainderOnlyItem.create(divisors, item.value) } }, ) } }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
8,849
advent-of-code
MIT License
src/main/kotlin/leetcode/s100/Solution101.kt
IgorPerikov
134,053,571
false
{"Kotlin": 29606}
package leetcode.s100 import leetcode.other.TreeNode import java.util.* class Solution101IterativeDfs { fun isSymmetric(root: TreeNode?): Boolean { if (root == null) return true val leftNodes: Deque<TreeNode> = ArrayDeque<TreeNode>().also { it.addFirst(root.left ?: TreeNode(Int.MIN_VALUE)) } val rightNodes: Deque<TreeNode> = ArrayDeque<TreeNode>().also { it.addFirst(root.right ?: TreeNode(Int.MIN_VALUE)) } while (!leftNodes.isEmpty() && !rightNodes.isEmpty()) { val leftNode = leftNodes.poll() val rightNode = rightNodes.poll() if (leftNode.`val` != rightNode.`val`) return false if ((leftNode.left == null) != (rightNode.right == null)) return false if ((leftNode.right == null) != (rightNode.left == null)) return false if (leftNode.left != null) leftNodes.push(leftNode.left) if (leftNode.right != null) leftNodes.push(leftNode.right) if (rightNode.right != null) rightNodes.push(rightNode.right) if (rightNode.left != null) rightNodes.push(rightNode.left) } return true } } class Solution101IterativeBfs { fun isSymmetric(root: TreeNode?): Boolean { if (root == null) return true val leftNodes: Queue<TreeNode> = LinkedList<TreeNode>().apply { this.offer(root.left ?: TreeNode(Int.MAX_VALUE)) } val rightNodes: Queue<TreeNode> = LinkedList<TreeNode>().apply { this.offer(root.right ?: TreeNode(Int.MAX_VALUE)) } while (!leftNodes.isEmpty() && !rightNodes.isEmpty()) { val leftNode = leftNodes.poll() val rightNode = rightNodes.poll() if (leftNode.`val` != rightNode.`val`) return false if ((leftNode.left == null) != (rightNode.right == null)) return false if ((leftNode.right == null) != (rightNode.left == null)) return false if (leftNode.left != null) leftNodes.offer(leftNode.left) if (leftNode.right != null) leftNodes.offer(leftNode.right) if (rightNode.right != null) rightNodes.offer(rightNode.right) if (rightNode.left != null) rightNodes.offer(rightNode.left) } return true } } class Solution101Recursive { fun isSymmetric(root: TreeNode?): Boolean { if (root == null) return true return isEqual(root.left, root.right) } fun isEqual(left: TreeNode?, right: TreeNode?): Boolean { return if (left != null && right != null) { if (left.`val` != right.`val`) return false val equal1 = isEqual(left.left, right.right) val equal2 = isEqual(left.right, right.left) equal1 && equal2 } else if (left == null && right != null) { false } else if (left != null && right == null) { false } else { true } } }
0
Kotlin
0
0
b30cf179f7b7ae534ee55d432b13859b77bbc4b7
2,954
kotlin-solutions
MIT License
src/Day24.kt
RusticFlare
574,508,778
false
{"Kotlin": 78496}
import Traveling.* import java.util.* import kotlin.math.absoluteValue @JvmInline private value class Minute(val value: UInt) : Comparable<Minute> { operator fun plus(other: Minute) = Minute(value + other.value) operator fun inc() = Minute(value.inc()) operator fun dec() = Minute(value.dec()) override fun compareTo(other: Minute) = value.compareTo(other.value) companion object { val START = Minute(value = 0u) } } @JvmInline private value class X(val x: UInt) { operator fun inc() = X(x.inc()) operator fun dec() = X(x.dec()) infix fun distanceTo(other: X) = (x.toInt() - other.x.toInt()).absoluteValue.toUInt() } @JvmInline private value class Y(val y: UInt) { operator fun inc() = Y(y.inc()) operator fun dec() = Y(y.dec()) infix fun distanceTo(other: Y) = (y.toInt() - other.y.toInt()).absoluteValue.toUInt() } private data class XRange(val xRange: UIntRange) { val first = X(xRange.first) val last = X(xRange.last) operator fun contains(x: X) = x.x in xRange } private data class YRange(val yRange: UIntRange) { val first = Y(yRange.first) val last = Y(yRange.last) operator fun contains(y: Y) = y.y in yRange } private data class Valley(val xRange: XRange, val yRange: YRange) { val entrance = Location(xRange.first, yRange.first.dec()) val exit = Location(xRange.last, yRange.last.inc()) operator fun contains(location: Location) = (location.x in xRange && location.y in yRange) || location == entrance || location == exit companion object { fun parse(input: List<String>) = Valley( xRange = with(input.first().indices) { XRange(first.toUInt().inc()..last.toUInt().dec()) }, yRange = with(input.indices) { YRange(first.toUInt().inc()..last.toUInt().dec()) }, ) } } private data class Location(val x: X, val y: Y) { val up get() = copy(y = y.dec()) val down get() = copy(y = y.inc()) val left get() = copy(x = x.dec()) val right get() = copy(x = x.inc()) infix fun distanceTo(other: Location) = (x distanceTo other.x) + (y distanceTo other.y) } private enum class Traveling { UP, DOWN, LEFT, RIGHT } private data class Blizzard(val location: Location, val traveling: Traveling) { fun move(valley: Valley) = copy( location = when (traveling) { UP -> location.up.takeIf { it in valley } ?: location.copy(y = valley.yRange.last) DOWN -> location.down.takeIf { it in valley } ?: location.copy(y = valley.yRange.first) LEFT -> location.left.takeIf { it in valley } ?: location.copy(x = valley.xRange.last) RIGHT -> location.right.takeIf { it in valley } ?: location.copy(x = valley.xRange.first) } ) } private data class PartyState( val minute: Minute, val location: Location, val destinations: List<Location>, ) : Comparable<PartyState> { val bestPossibleResult = minute + Minute(location distanceTo (destinations.firstOrNull() ?: location)) + Minute(destinations.zipWithNext { a, b -> a distanceTo b }.sum()) override fun compareTo(other: PartyState) = comparator.compare(this, other) companion object { val comparator = compareBy<PartyState> { it.bestPossibleResult } } } fun main() { fun day24( input: List<String>, valley: Valley, destinations: List<Location> ): Int { val blizzardStates = mutableMapOf<Minute, Pair<Collection<Blizzard>, Set<Location>>>().apply { this[Minute.START] = input.flatMapIndexed { y, s -> s.mapIndexedNotNull { x, c -> when (c) { '>' -> RIGHT '^' -> UP 'v' -> DOWN '<' -> LEFT else -> null }?.let { traveling -> Blizzard( location = Location(X(x.toUInt()), Y(y.toUInt())), traveling = traveling, ) } } }.let { it to it.map { blizzard -> blizzard.location }.toSet() } } val queue = PriorityQueue<PartyState>().apply { add( PartyState( minute = Minute.START, location = valley.entrance, destinations = destinations, ) ) } while (queue.isNotEmpty()) { val state = queue.poll() val nextMinute = state.minute.inc() val (_, blizzardLocations) = blizzardStates.computeIfAbsent(nextMinute) { val (blizzards) = blizzardStates.getValue(state.minute) blizzards.map { blizzard -> blizzard.move(valley) } .let { newBlizzards -> newBlizzards to newBlizzards.map { blizzard -> blizzard.location }.toSet() } } queue.addAll( listOfNotNull( state.copy(minute = nextMinute), runCatching { state.copy(minute = nextMinute, location = state.location.up) }.getOrNull(), runCatching { state.copy(minute = nextMinute, location = state.location.down) }.getOrNull(), state.copy(minute = nextMinute, location = state.location.left), state.copy(minute = nextMinute, location = state.location.right), ).filter { it.location in valley && it.location !in blizzardLocations && it !in queue } .map { when (it.location) { it.destinations.first() -> it.copy(destinations = it.destinations.drop(1)) .also { state -> if (state.destinations.isEmpty()) return state.minute.value.toInt() } else -> it } } ) } error("No path found") } fun part1(input: List<String>): Int { val valley = Valley.parse(input) val destinations = listOf(valley.exit) return day24(input, valley, destinations) } fun part2(input: List<String>): Int { val valley = Valley.parse(input) val destinations = listOf(valley.exit, valley.entrance, valley.exit) return day24(input, valley, destinations) } // test if implementation meets criteria from the description, like: val testInput = readLines("Day24_test") check(part1(testInput) == 18) check(part2(testInput) == 54) val input = readLines("Day24") with(part1(input)) { check(this == 305) println(this) } with(part2(input)) { check(this == 905) println(this) } }
0
Kotlin
0
1
10df3955c4008261737f02a041fdd357756aa37f
6,875
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/com/github/michaelbull/advent2023/day12/SpringRecord.kt
michaelbull
726,012,340
false
{"Kotlin": 195941}
package com.github.michaelbull.advent2023.day12 private val CONDITION_REGEX = "[.#?]+".toRegex() private val RECORD_REGEX = "($CONDITION_REGEX) (.*)".toRegex() fun String.toSpringRecord(): SpringRecord { val result = requireNotNull(RECORD_REGEX.matchEntire(this)) { "$this must match $RECORD_REGEX" } val (conditionChars, damagedCountCsv) = result.destructured return SpringRecord( conditions = conditionChars.map(Char::toSpringCondition), contiguousDamageCounts = damagedCountCsv.split(",").map(String::toInt) ) } data class SpringRecord( val conditions: List<SpringCondition>, val contiguousDamageCounts: List<Int>, ) { fun unfoldedArrangementCount(cache: ArrangementCountCache): Long { return unfold().arrangementCount(cache) } fun arrangementCount(cache: ArrangementCountCache): Long { return when { contiguousDamageCounts.isEmpty() -> { if (Damaged in conditions) 0 else 1 } conditions.isEmpty() -> { 0 } else -> { cache.getOrPut(this) { val condition = conditions.first() val count = if (condition == Damaged) { 0 } else { dropCondition().arrangementCount(cache) } if (countingDamaged()) { count } else { count + dropDamaged().arrangementCount(cache) } } } } } private fun dropCondition(): SpringRecord { return copy( conditions = conditions.drop(1) ) } private fun dropDamaged(): SpringRecord { return copy( conditions = conditions.drop(contiguousDamageCounts.first() + 1), contiguousDamageCounts = contiguousDamageCounts.drop(1), ) } private fun countingDamaged(): Boolean { val runLength = contiguousDamageCounts.first() val runExceeded = runLength > conditions.size val runHasRemaining = runLength < conditions.size val firstCondition = conditions.first() val run = conditions.take(runLength) return when { firstCondition == Operational || Operational in run -> true runExceeded -> true runHasRemaining && conditions[runLength] == Damaged -> true else -> false } } private fun unfold(): SpringRecord { return copy( conditions = (conditions + Unknown).repeat(5).dropLast(1), contiguousDamageCounts = contiguousDamageCounts.repeat(5), ) } /** @see [CharSequence.repeat] */ private fun <T> List<T>.repeat(n: Int): List<T> { require(n >= 0) { "Count 'n' must be non-negative, but was $n." } return when (n) { 0 -> emptyList() 1 -> this else -> when (size) { 0 -> emptyList() 1 -> this[0].let { element -> List(n) { element } } else -> List(size * n) { this[it % size] } } } } }
0
Kotlin
0
1
ea0b10a9c6528d82ddb481b9cf627841f44184dd
3,243
advent-2023
ISC License
src/main/kotlin/g0101_0200/s0105_construct_binary_tree_from_preorder_and_inorder_traversal/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0101_0200.s0105_construct_binary_tree_from_preorder_and_inorder_traversal // #Medium #Top_100_Liked_Questions #Top_Interview_Questions #Array #Hash_Table #Tree #Binary_Tree // #Divide_and_Conquer #Data_Structure_II_Day_15_Tree #Big_O_Time_O(N)_Space_O(N) // #2023_07_11_Time_183_ms_(95.45%)_Space_36.9_MB_(82.73%) import com_github_leetcode.TreeNode /* * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { private var j = 0 private val map: MutableMap<Int, Int> = HashMap() fun get(key: Int): Int { return map.getValue(key) } private fun answer(preorder: IntArray, inorder: IntArray, start: Int, end: Int): TreeNode? { if (start > end || j > preorder.size) { return null } val value = preorder[j++] val index = get(value) val node = TreeNode(value) node.left = answer(preorder, inorder, start, index - 1) node.right = answer(preorder, inorder, index + 1, end) return node } fun buildTree(preorder: IntArray, inorder: IntArray): TreeNode? { j = 0 for (i in preorder.indices) { map[inorder[i]] = i } return answer(preorder, inorder, 0, preorder.size - 1) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,404
LeetCode-in-Kotlin
MIT License
src/main/kotlin/days/Day17.kt
jgrgt
433,952,606
false
{"Kotlin": 113705}
package days import util.Point class Day17 : Day(17) { override fun runPartOne(lines: List<String>): Any { //x=150..171, y=-129..-70 val minX = 150 val maxX = 171 val minY = -129 val maxY = -70 val vector = findHighestLaunch(minX, maxX, minY, maxY) return findHighest(vector, minY) } override fun runPartTwo(lines: List<String>): Any { //x=150..171, y=-129..-70 val minX = 150 val maxX = 171 val minY = -129 val maxY = -70 val vectors = findGoodLaunches(minX, maxX, minY, maxY) return vectors.size } private fun findHighest(vector: Point, minY: Int) = generate(vector) .takeWhile { probe -> probe.position.y >= minY } .map { it.position.y } .maxOrNull() ?: error("should have found a value") fun findHighestLaunch(minX: Int, maxX: Int, minY: Int, maxY: Int): Point { val highest = (1..maxX).mapNotNull { x -> val vectors = (1..1000).mapNotNull { y -> val vector = Point(x, y) val match = generate(vector) .takeWhile { probe -> probe.position.y >= minY } .filter { probe -> val p = probe.position (p.x in minX..maxX) && (p.y in minY..maxY) }.firstOrNull() if (match != null) { vector } else { null } } val highestYVector = vectors.maxByOrNull { vector -> findHighest(vector, minY) } highestYVector }.maxByOrNull { vector -> findHighest(vector, minY) } return highest!! } fun findGoodLaunches(minX: Int, maxX: Int, minY: Int, maxY: Int): List<Point> { return (1..maxX).flatMap { x -> (-1000..1000).mapNotNull { y -> val vector = Point(x, y) val match = generate(vector) .takeWhile { probe -> probe.position.y >= minY } .filter { probe -> val p = probe.position (p.x in minX..maxX) && (p.y in minY..maxY) }.firstOrNull() if (match != null) { vector } else { null } } } } fun generate(vector: Point): Sequence<Probe> { return generateSequence(Probe(Point(0, 0), vector)) { probe -> probe.next() } } data class Probe(val position: Point, val vector: Point) { fun next(): Probe { return Probe(position + vector, updatedVector()) } fun updatedVector(): Point { val x = when { vector.x < 0 -> vector.x + 1 vector.x > 0 -> vector.x - 1 else -> 0 } val y = vector.y - 1 return Point(x, y) } } }
0
Kotlin
0
0
6231e2092314ece3f993d5acf862965ba67db44f
3,040
aoc2021
Creative Commons Zero v1.0 Universal