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
app/src/main/java/dev/patrickgold/florisboard/ime/nlp/FlorisLanguageModel.kt
stefan-misik
357,279,068
true
{"Kotlin": 793069, "HTML": 58856, "Python": 429}
/* * Copyright (C) 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.patrickgold.florisboard.ime.nlp /** * Represents the root node to a n-gram tree. */ open class NgramTree( sameOrderChildren: MutableList<NgramNode> = mutableListOf(), higherOrderChildren: MutableList<NgramNode> = mutableListOf() ) : NgramNode(0, '?', -1, sameOrderChildren, higherOrderChildren) /** * A node of a n-gram tree, which holds the character it represents, the corresponding frequency, * a pre-computed string representing all parent characters and the current one as well as child * nodes, one for the same order n-gram nodes and one for the higher order n-gram nodes. */ open class NgramNode( val order: Int, val char: Char, val freq: Int, val sameOrderChildren: MutableList<NgramNode> = mutableListOf(), val higherOrderChildren: MutableList<NgramNode> = mutableListOf() ) { companion object { const val FREQ_CHARACTER = -1 const val FREQ_WORD_MIN = 0 const val FREQ_WORD_MAX = 255 const val FREQ_WORD_FILLER = -2 const val FREQ_IS_POSSIBLY_OFFENSIVE = 0 } val isCharacter: Boolean get() = freq == FREQ_CHARACTER val isWord: Boolean get() = freq in FREQ_WORD_MIN..FREQ_WORD_MAX val isWordFiller: Boolean get() = freq == FREQ_WORD_FILLER val isPossiblyOffensive: Boolean get() = freq == FREQ_IS_POSSIBLY_OFFENSIVE fun findWord(word: String): NgramNode? { var currentNode = this for ((pos, char) in word.withIndex()) { val childNode = if (pos == 0) { currentNode.higherOrderChildren.find { it.char == char } } else { currentNode.sameOrderChildren.find { it.char == char } } if (childNode != null) { currentNode = childNode } else { return null } } return if (currentNode.isWord || currentNode.isWordFiller) { currentNode } else { null } } /** * This function allows to search for a given [input] word with a given [maxEditDistance] and * adds all matches in the trie to the [list]. */ fun listSimilarWords( input: String, list: StagedSuggestionList<String, Int>, word: StringBuilder, allowPossiblyOffensive: Boolean, maxEditDistance: Int, deletionCost: Int = 0, insertionCost: Int = 0, substitutionCost: Int = 0, pos: Int = -1 ) { if (pos > -1) { word.append(char) } val costSum = deletionCost + insertionCost + substitutionCost if (pos > -1 && (pos + 1 == input.length) && isWord && ((isPossiblyOffensive && allowPossiblyOffensive) || !isPossiblyOffensive)) { // Using shift right instead of divide by 2^(costSum) as it is mathematically the // same but faster. if (list.canAdd(freq shr costSum)) { list.add(word.toString(), freq shr costSum) } } if (pos <= -1) { for (childNode in higherOrderChildren) { childNode.listSimilarWords( input, list, word, allowPossiblyOffensive, maxEditDistance, 0, 0, 0, 0 ) } } else if (maxEditDistance == costSum) { if (pos + 1 < input.length) { sameOrderChildren.find { it.char == input[pos + 1] }?.listSimilarWords( input, list, word, allowPossiblyOffensive, maxEditDistance, deletionCost, insertionCost, substitutionCost, pos + 1 ) } } else { // Delete if (pos + 2 < input.length) { sameOrderChildren.find { it.char == input[pos + 2] }?.listSimilarWords( input, list, word, allowPossiblyOffensive, maxEditDistance, deletionCost + 1, insertionCost, substitutionCost, pos + 2 ) } for (childNode in sameOrderChildren) { if (pos + 1 < input.length && childNode.char == input[pos + 1]) { childNode.listSimilarWords( input, list, word, allowPossiblyOffensive, maxEditDistance, deletionCost, insertionCost, substitutionCost, pos + 1 ) } else { // Insert childNode.listSimilarWords( input, list, word, allowPossiblyOffensive, maxEditDistance, deletionCost, insertionCost + 1, substitutionCost, pos ) if (pos + 1 < input.length) { // Substitute childNode.listSimilarWords( input, list, word, allowPossiblyOffensive, maxEditDistance, deletionCost, insertionCost, substitutionCost + 1, pos + 1 ) } } } } if (pos > -1) { word.deleteAt(word.lastIndex) } } fun listAllSameOrderWords(list: StagedSuggestionList<String, Int>, word: StringBuilder, allowPossiblyOffensive: Boolean) { word.append(char) if (isWord && ((isPossiblyOffensive && allowPossiblyOffensive) || !isPossiblyOffensive)) { if (list.canAdd(freq)) { list.add(word.toString(), freq) } } for (childNode in sameOrderChildren) { childNode.listAllSameOrderWords(list, word, allowPossiblyOffensive) } word.deleteAt(word.lastIndex) } } open class FlorisLanguageModel( initTreeObj: NgramTree? = null ) : LanguageModel<String, Int> { protected val ngramTree: NgramTree = initTreeObj ?: NgramTree() override fun getNgram(vararg tokens: String): Ngram<String, Int> { val ngramOut = getNgramOrNull(*tokens) if (ngramOut != null) { return ngramOut } else { throw NullPointerException("No n-gram found matching the given tokens: $tokens") } } override fun getNgram(ngram: Ngram<String, Int>): Ngram<String, Int> { val ngramOut = getNgramOrNull(ngram) if (ngramOut != null) { return ngramOut } else { throw NullPointerException("No n-gram found matching the given ngram: $ngram") } } override fun getNgramOrNull(vararg tokens: String): Ngram<String, Int>? { var currentNode: NgramNode = ngramTree for (token in tokens) { val childNode = currentNode.findWord(token) if (childNode != null) { currentNode = childNode } else { return null } } return Ngram(tokens.toList().map { Token(it) }, currentNode.freq) } override fun getNgramOrNull(ngram: Ngram<String, Int>): Ngram<String, Int>? { return getNgramOrNull(*ngram.tokens.toStringList().toTypedArray()) } override fun hasNgram(ngram: Ngram<String, Int>, doMatchFreq: Boolean): Boolean { val result = getNgramOrNull(ngram) return if (result != null) { if (doMatchFreq) { ngram.freq == result.freq } else { true } } else { false } } override fun matchAllNgrams( ngram: Ngram<String, Int>, maxEditDistance: Int, maxTokenCount: Int, allowPossiblyOffensive: Boolean ): List<WeightedToken<String, Int>> { val ngramList = mutableListOf<WeightedToken<String, Int>>() var currentNode: NgramNode = ngramTree for ((t, token) in ngram.tokens.withIndex()) { val word = token.data if (t + 1 >= ngram.tokens.size) { if (word.isNotEmpty()) { // The last word is not complete, so find all possible words and sort val splitWord = mutableListOf<Char>() var splitNode: NgramNode? = currentNode for ((pos, char) in word.withIndex()) { val node = if (pos == 0) { splitNode?.higherOrderChildren?.find { it.char == char } } else { splitNode?.sameOrderChildren?.find { it.char == char } } splitWord.add(char) splitNode = node if (node == null) { break } } if (splitNode != null) { // Input thus far is valid val wordNodes = StagedSuggestionList<String, Int>(maxTokenCount) val strBuilder = StringBuilder().append(word.substring(0, word.length - 1)) splitNode.listAllSameOrderWords(wordNodes, strBuilder, allowPossiblyOffensive) ngramList.addAll(wordNodes) } if (ngramList.size < maxTokenCount) { val wordNodes = StagedSuggestionList<String, Int>(maxTokenCount) val strBuilder = StringBuilder() currentNode.listSimilarWords(word, wordNodes, strBuilder, allowPossiblyOffensive, maxEditDistance) ngramList.addAll(wordNodes) } } } else { val node = currentNode.findWord(word) if (node == null) { return ngramList } else { currentNode = node } } } return ngramList } fun toFlorisMutableLanguageModel(): FlorisMutableLanguageModel = FlorisMutableLanguageModel(ngramTree) } open class FlorisMutableLanguageModel( initTreeObj: NgramTree? = null ) : MutableLanguageModel<String, Int>, FlorisLanguageModel(initTreeObj) { override fun deleteNgram(ngram: Ngram<String, Int>) { TODO("Not yet implemented") } override fun insertNgram(ngram: Ngram<String, Int>) { TODO("Not yet implemented") } override fun updateNgram(ngram: Ngram<String, Int>) { TODO("Not yet implemented") } fun toFlorisLanguageModel(): FlorisLanguageModel = FlorisLanguageModel(ngramTree) }
0
Kotlin
0
0
e9fc3246d834d626b073563c175a4a1445b739f1
11,118
florisboard
Apache License 2.0
src/main/kotlin/com/leetcode/P720.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package com.leetcode // https://github.com/antop-dev/algorithm/issues/267 class P720 { fun longestWord(words: Array<String>): String { val root = TrieNode() var answer = "" words.sortWith( Comparator<String> { o1, o2 -> o1.length - o2.length } .then(Comparator { o1, o2 -> if (o1 < o2) -1 else 1 }) ) word@ for (word in words) { var node = root for (i in word.indices) { val idx = word[i] - 'a' if (node.children[idx] != null) { node = node.children[idx]!! continue } if (i < word.lastIndex) continue@word if (i == word.lastIndex) { if (word.length > answer.length) answer = word val newNode = TrieNode(word[i]) node.children[idx] = newNode node = newNode } } } return answer } class TrieNode(val char: Char? = null) { val children = Array<TrieNode?>(26) { null } } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
1,136
algorithm
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/AdvantageCount.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.Deque import java.util.LinkedList /** * Approach 1: Greedy * Time Complexity: O(N log N), where N is the length of a and b. * Space Complexity: O(N). */ fun advantageCount(a: IntArray, b: IntArray): IntArray { val sortedA: IntArray = a.clone(); sortedA.sort() val sortedB: IntArray = b.clone(); sortedB.sort() val assigned: MutableMap<Int, Deque<Int>> = HashMap() for (bb in b) assigned[bb] = LinkedList() val remaining: Deque<Int> = LinkedList() var j = 0 for (aa in sortedA) { if (aa > sortedB[j]) { assigned[sortedB[j++]]?.add(aa) } else { remaining.add(aa) } } val ans = IntArray(b.size) for (i in b.indices) { val bDeque = assigned.getOrDefault(b[i], LinkedList()) if (bDeque.isNotEmpty()) { ans[i] = bDeque.pop() } else { ans[i] = remaining.pop() } } return ans }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,590
kotlab
Apache License 2.0
deprecated/fn-mmg-validator/src/main/kotlin/gov/cdc/dex/hl7/model/ValidationIssue.kt
CDCgov
510,836,864
false
{"Kotlin": 746627, "Scala": 208820, "Python": 44391, "Java": 18075, "Batchfile": 11894, "Go": 8661, "JavaScript": 7609, "Groovy": 4230, "HTML": 2177, "Shell": 1362, "CSS": 979}
package gov.cdc.dex.hl7.model enum class ValidationIssueCategoryType(val message: String) { ERROR("Error"), WARNING("Warning"); } enum class ValidationIssueType(val message: String) { DATA_TYPE("data_type"), CARDINALITY("cardinality"), VOCAB("vocabulary"), SEGMENT_NOT_IN_MMG("segment_not_in_mmg"), OBSERVATION_SUB_ID_VIOLATION("observation_sub_id_violation"), DATE_CONTENT("date_content"), MMWR_WEEK("mmwr_week_violation") } enum class ValidationErrorMessage(val message: String) { DATA_TYPE_NOT_FOUND("Element data type not found"), DATA_TYPE_MISMATCH("Element data type is not matching the MMG data type"), CARDINALITY_UNDER("Element has less repeats than allowed by MMG cardinality"), CARDINALITY_OVER("Element has more repeats than allowed by MMG cardinality"), VOCAB_NOT_AVAILABLE("Vocabulary not available for code system code"), VOCAB_ISSUE("Vocabulary code system code and code concept not found in vocabulary entries"), SEGMENT_NOT_IN_MMG("HL7 segment found in the message that is not part of the MMG definitions"), OBSERVATION_SUB_ID_MISSING("Observation Sub-Id must be populated for data elements in a repeating group."), OBSERVATION_SUB_ID_NOT_UNIQUE("The combination of the data element identifier (OBX-3) and the observation sub-id (OBX-4) must be unique."), DATE_INVALID("Date/time provided is not a valid date/time"), WEEK_INVALID("Week provided is not a valid week") } data class ValidationIssue( val classification: ValidationIssueCategoryType, // ERROR (for required fields) or WARNING val category: ValidationIssueType, // DATA_TYPE, CARDINALITY, VOCAB val fieldName: String, // mmg field Name val path: String, // HL7 path to extract value val line: Int, val errorMessage: ValidationErrorMessage, // error message val description: String, // custom message to add value in question ) // .ValidationIssue
118
Kotlin
14
9
e859ed7c4d5feb3a97acd6e3faef1382487a689f
2,055
data-exchange-hl7
Apache License 2.0
src/main/kotlin/se/saidaspen/aoc/aoc2015/Day23.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2015 import se.saidaspen.aoc.util.Day import se.saidaspen.aoc.util.words fun main() { Day23.run() } object Day23 : Day(2015, 23) { class Computer { var registers = mutableMapOf<String, Int>() private var pc = 0 fun run(program: List<Op>) { while (pc < program.size) { val op = program[pc] when (op.type) { "hlf" -> { registers[op.arg1] = registers[op.arg1]!! / 2 pc++ } "tpl" -> { registers[op.arg1] = registers[op.arg1]!! * 3 pc++ } "inc" -> { registers[op.arg1] = registers[op.arg1]!! + 1 pc++ } "jmp" -> { if (op.arg1[0] == '+') pc += op.arg1.drop(1).toInt() else pc -= op.arg1.drop(1).toInt() } "jie" -> { if (registers[op.arg1]!! % 2 == 0) { if (op.arg2[0] == '+') pc += op.arg2.drop(1).toInt() else pc -= op.arg2.drop(1).toInt() } else { pc++ } } "jio" -> { if (registers[op.arg1]!! == 1) { if (op.arg2[0] == '+') pc += op.arg2.drop(1).toInt() else pc -= op.arg2.drop(1).toInt() } else { pc++ } } } } } } data class Op(val type: String, val arg1: String, val arg2: String) override fun part1(): Any { val program = input.lines().map { it.replace(",", "") }.map { words(it) } .map { Op(it[0], it[1], if (it.size > 2) it[2] else "") }.toList() val cpu = Computer() cpu.registers["a"] = 0 cpu.registers["b"] = 0 cpu.run(program) return cpu.registers["b"]!! } override fun part2(): Any { val program = input.lines().map { it.replace(",", "") }.map { words(it) } .map { Op(it[0], it[1], if (it.size > 2) it[2] else "") }.toList() val cpu = Computer() cpu.registers["a"] = 1 cpu.registers["b"] = 0 cpu.run(program) return cpu.registers["b"]!! } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
2,585
adventofkotlin
MIT License
src/2020/Day16_1.kts
Ozsie
318,802,874
false
{"Kotlin": 99344, "Python": 1723, "Shell": 975}
/** * As you're walking to yet another connecting flight, you realize that one of the legs of your * re-routed trip coming up is on a high-speed train. However, the train ticket you were given is * in a language you don't understand. You should probably figure out what it says before you get * to the train station after the next flight. * * Unfortunately, you can't actually read the words on the ticket. You can, however, read the * numbers, and so you figure out the fields these tickets must have and the valid ranges for * values in those fields. * * You collect the rules for ticket fields, the numbers on your ticket, and the numbers on other * nearby tickets for the same train service (via the airport security cameras) together into a * single document you can reference (your puzzle input). * * The rules for ticket fields specify a list of fields that exist somewhere on the ticket and * the valid ranges of values for each field. For example, a rule like class: 1-3 or 5-7 means * that one of the fields in every ticket is named class and can be any value in the ranges 1-3 * or 5-7 (inclusive, such that 3 and 5 are both valid in this field, but 4 is not). * * Each ticket is represented by a single line of comma-separated values. The values are the * numbers on the ticket in the order they appear; every ticket has the same format. For * example, consider this ticket: * * ``` * .--------------------------------------------------------. * | ????: 101 ?????: 102 ??????????: 103 ???: 104 | * | | * | ??: 301 ??: 302 ???????: 303 ??????? | * | ??: 401 ??: 402 ???? ????: 403 ????????? | * '--------------------------------------------------------' * ``` * * Here, ? represents text in a language you don't understand. This ticket might be represented * as 101,102,103,104,301,302,303,401,402,403; of course, the actual train tickets you're looking * at are much more complicated. In any case, you've extracted just the numbers in such a way * that the first number is always the same specific field, the second number is always a * different specific field, and so on - you just don't know what each position actually means! * * Start by determining which tickets are completely invalid; these are tickets that contain * values which aren't valid for any field. Ignore your ticket for now. * * For example, suppose you have the following notes: * * ``` * class: 1-3 or 5-7 * row: 6-11 or 33-44 * seat: 13-40 or 45-50 * * your ticket: * 7,1,14 * * nearby tickets: * 7,3,47 * 40,4,50 * 55,2,20 * 38,6,12 * ``` * * It doesn't matter which position corresponds to which field; you can identify invalid nearby * tickets by considering only whether tickets contain values that are not valid for any field. * In this example, the values on the first nearby ticket are all valid for at least one field. * This is not true of the other three nearby tickets: the values 4, 55, and 12 are are not valid * for any field. Adding together all of the invalid values produces your ticket scanning error * rate: 4 + 55 + 12 = 71. * * Consider the validity of the nearby tickets you scanned. What is your ticket scanning error * rate? */ import java.io.File import java.math.BigInteger import java.util.* import kotlin.collections.HashMap import kotlin.collections.component1 import kotlin.collections.component2 data class Rule(val name: String, val lowerRange: IntRange, val upperRange: IntRange) fun Rule.matches(num: Int) = num in lowerRange || num in upperRange val f = File("input/2020/day16").readLines() val rules = ArrayList<Rule>() val ticket = ArrayList<Int>() val nearby = ArrayList<List<Int>>() var i = 0 while (i < f.size) { val line = f[i++] if (line.isEmpty()) continue when (line) { "your ticket:" -> { val x = f[i++] val t = x.split(",").map { it.toInt() } ticket.addAll(t) } "nearby tickets:" -> { while (i < f.size) { val t = f[i++].split(",").map { it.toInt() } nearby.add(t) } } else -> { val (name,ranges) = line.split(":") val (a,b) = ranges.trim().split(" or ") val (lA,hA) = a.split("-") val (lB,hB) = b.split("-") rules.add(Rule(name.trim(), (lA.toInt())..(hA.toInt()), (lB.toInt())..(hB.toInt()))) } } } var sum = 0 nearby.forEach { t -> sum += t.filter { num -> val matchingRules = rules.filter { it.matches(num) } matchingRules.isEmpty() }.sum() } println(sum)
0
Kotlin
0
0
d938da57785d35fdaba62269cffc7487de67ac0a
4,715
adventofcode
MIT License
src/main/kotlin/ru/nrcki/biokotlin/tetra.kt
laxeye
164,879,760
false
null
package ru.nrcki.biokotlin import ru.nrcki.biokotlin.io.Fasta class Tetra(){ fun makeTetraList(redundant: Boolean = false): List<String>{ val dinucs = mutableListOf<String>() val tetranucs = mutableListOf<String>() val nucs = listOf("A","C","G","T") for(n in nucs){ nucs.map{dinucs.add(n + it)} } if(redundant){ for(n in dinucs){ dinucs.map{tetranucs.add(n + it)} } }else{ for(n in dinucs){ dinucs.map{ if(! tetranucs.contains((n+it).revComp())) tetranucs.add(n + it)} } } return tetranucs.toList().sorted() } fun calcTetra(seq: String): Map<String,Int>{ val tetraList = makeTetraList() val tMap = tetraList.associateWith { 0 }.toMutableMap<String,Int>() val lastIdx = seq.length - 4 for(i in 0..lastIdx){ var piece = seq.substring(i,i+4) if(piece in tetraList) tMap[piece] = (tMap[piece] ?: 0) + 1 piece = piece.revComp() if(piece in tetraList) tMap[piece] = (tMap[piece] ?: 0) + 1 } return tMap } fun calcAllTetra(seq: String): Map<String,Int>{ val tMap = makeTetraList(true).associateWith { 0 }.toMutableMap<String,Int>() val lastIdx = seq.length - 4 for(i in 0..lastIdx){ val piece = seq.substring(i,i+4) tMap[piece] = (tMap[piece] ?: 0) + 1 } return tMap } fun genomeTetraStats(filename: String, redundant: Boolean = false){ val seqs = Fasta().read(filename) val allTetra = makeTetraList(redundant) if(redundant) { for (seq in seqs) { val tMap = calcAllTetra(seq.sequence) print(seq.id) allTetra.forEach(){ print("\t${tMap.getOrElse(it,{0}).toDouble().times(100.0).div(seq.length-3)}") // More time consumption if format() used // print("\t%.5f".format(tMap.getOrElse(it,{0}).toDouble().div(seq.length-3))) } print("\n") } } else { for (seq in seqs){ val tMap = calcTetra(seq.sequence) print(seq.id) allTetra.forEach() { print("\t${tMap.getOrElse(it,{0}).toDouble().times(100.0).div(seq.length-3)}") // More time consumption if format() used // print("\t%.5f".format(tMap.getOrElse(it,{0}).toDouble().div(seq.length-3))) } print("\n") } } } }
7
Kotlin
0
0
fb86e738ee31a082bb71e2c8a73d34e65197f2eb
2,149
BioKotlin
MIT License
src/main/kotlin/day16/Day16.kt
alxgarcia
435,549,527
false
{"Kotlin": 91398}
package day16 import java.io.File import java.util.Optional sealed interface Packet { val version: Int val value: Long } data class Literal(override val version: Int, override val value: Long) : Packet data class Op(override val version: Int, private val type: Int, val packets: List<Packet>) : Packet { override val value: Long get() = when (type) { 0 -> packets.sumOf { it.value } 1 -> packets.fold(1L) { acc, packet -> acc * packet.value } 2 -> packets.minOf { it.value } 3 -> packets.maxOf { it.value } 5 -> if (packets[0].value > packets[1].value) 1 else 0 6 -> if (packets[0].value < packets[1].value) 1 else 0 7 -> if (packets[0].value == packets[1].value) 1 else 0 else -> TODO("Operation $type is not supported") } } private val hexBinMap2 = (0..0xF).associate { n -> n.toString(16).first().uppercaseChar() to n.toString(2).padStart(4, '0') } fun hexToBits(input: String): Iterator<Char> = input.flatMap { hexBinMap2[it]!!.asIterable() }.iterator() // Syntax sugar methods that will carelessly throw exception if there aren't enough bits private fun Iterator<Char>.take(bits: Int): String = (1..bits).map { next() }.joinToString("") private fun Iterator<Char>.takeInt(bits: Int): Int = take(bits).toInt(2) fun decodePackets(input: Iterator<Char>): List<Packet> = sequence { while (input.hasNext()) { val next = decodeNextPacket(input) if (next.isPresent) yield(next.get()) } }.toList() fun decodeNPackets(input: Iterator<Char>, number: Int) = (1..number).map { decodeNextPacket(input).get() } fun decodeNextPacket(input: Iterator<Char>): Optional<Packet> = runCatching { val version = input.takeInt(3) val typeId = input.takeInt(3) return Optional.ofNullable( when (typeId) { 4 -> Literal(version, decodeLiteralPayload(input)) else -> Op(version, typeId, decodeOperatorPayload(input)) } ) }.getOrElse { Optional.empty() } private fun decodeLiteralPayload(input: Iterator<Char>): Long { tailrec fun rec(input: Iterator<Char>, number: Long): Long { val controlBit = input.next() val n = number.shl(4) + input.takeInt(4) return if (controlBit == '0') n else rec(input, n) } return rec(input, 0) } private fun decodeOperatorPayload(input: Iterator<Char>): List<Packet> = runCatching { when (input.next()) { '0' -> { // takes 15 bits to parse the size of the payload in bits decodePackets(boundedIteratorWrap(input, input.takeInt(15))) } '1' -> { // takes 11 bits to parse the number of packets in its payload decodeNPackets(input, input.takeInt(11)) } else -> TODO("Should never happen") } }.getOrElse { emptyList() } private fun boundedIteratorWrap(iterator: Iterator<Char>, limit: Int) = object : Iterator<Char> { private var counter = 0 override fun hasNext(): Boolean = iterator.hasNext() && counter < limit override fun next(): Char = if (hasNext()) { counter += 1 iterator.next() } else throw NoSuchElementException("End of bounded iterator") } fun sumAllVersionsOfTheTransmission(input: Iterator<Char>): Long { fun sumVersions(p: Packet): Long = when (p) { is Literal -> p.version.toLong() is Op -> p.packets.fold(p.version.toLong()) { acc, packet -> acc + sumVersions(packet) } } return decodePackets(input).fold(0L) { acc, packet -> acc + sumVersions(packet) } } fun evaluateTransmission(input: Iterator<Char>): Long = decodeNextPacket(input).get().value fun main() { File("./input/day16.txt").useLines { lines -> val transmission = lines.first() println(sumAllVersionsOfTheTransmission(hexToBits(transmission))) println(evaluateTransmission(hexToBits(transmission))) } }
0
Kotlin
0
0
d6b10093dc6f4a5fc21254f42146af04709f6e30
3,715
advent-of-code-2021
MIT License
src/main/kotlin/com/tradeshift/suggest/Model.kt
liufuyang
140,750,099
false
{"Kotlin": 21637, "Python": 1174}
package com.tradeshift.suggest import com.tradeshift.suggest.features.Inputs import com.tradeshift.suggest.features.Update import com.tradeshift.suggest.features.WordCounter import com.tradeshift.suggest.storage.ModelTableStorage import com.tradeshift.suggest.storage.Storage import kotlin.math.ln class Model( private val storage: Storage = ModelTableStorage(), private val pseudoCount: Double = 1.0 // reference: https://www.wikiwand.com/en/Naive_Bayes_classifier ) { private fun logProbability(count: Int, cFC: Int, cC: Int, numOfUniqueFeature: Int): Double { return count.toDouble() * (ln(cFC + pseudoCount) - ln(cC + numOfUniqueFeature * pseudoCount)) } /** * Predicts using naive bayes, e.g. p(y|x) = p(x|y)p(y)/p(x) * * @return predicted outcomes and their un-normalized log-probability, e.g. {"positive": -4.566621, "negative": -2.324455} */ fun predict(inputs: Inputs): Map<String, Double> { val result = hashMapOf<String, Double>() for (outcome in storage.getAllClasses()) { val priorsCountOfClass = storage.getPriorsCountOfClass(outcome) val totalDataCount = storage.getTotalDataCount() var lp = 0.0 for ((featureName, featureValue) in inputs.text) { val knownFeaturesInTable = storage.getKnownWords(featureName) val countOfUniqueWord = knownFeaturesInTable.size val countOfAllWordInClass = storage.getCountOfAllWordInClass(featureName, outcome) val wordCountsForCurrentFeature = WordCounter.countWords(featureValue) val knownFeatures = wordCountsForCurrentFeature.keys.intersect(knownFeaturesInTable) for (entry in wordCountsForCurrentFeature.entries) { if (knownFeatures.contains(entry.key)) { lp += calculateLogProbability(featureName, outcome, countOfUniqueWord, countOfAllWordInClass, entry.value, entry.key) } } } for ((featureName, featureValue) in inputs.category) { val knownFeaturesInTable = storage.getKnownWords(featureName) val countOfUniqueWord = knownFeaturesInTable.size val countOfAllWordInClass = storage.getCountOfAllWordInClass(featureName, outcome) if (featureValue in knownFeaturesInTable) { lp += calculateLogProbability(featureName, outcome, countOfUniqueWord, countOfAllWordInClass, 1, featureValue) } } val finalLogP = ln(priorsCountOfClass.toDouble()) - ln(totalDataCount.toDouble()) + lp result.put(outcome, finalLogP) } return normalize(result) } private fun calculateLogProbability(featureName: String, outcome: String, countOfUniqueWord: Int, countOfAllWordInClass: Int, countOfWord: Int, word: String): Double { val countOfWordInClass = storage.getCountOfWordInClass(featureName, outcome, word) return logProbability(countOfWord, countOfWordInClass, countOfAllWordInClass, countOfUniqueWord) } private fun normalize(suggestions: Map<String, Double>): Map<String, Double> { val max: Double = suggestions.maxBy({ it.value })?.value ?: 0.0 val vals = suggestions.mapValues { Math.exp(it.value - max) } val norm = vals.values.sum() return vals.mapValues { it.value / norm } } /** * Creates a new model with the counts added */ fun add(update: Update) { return batchAdd(listOf(update)) } /** * @param updates List of observed Updates */ fun batchAdd(updates: List<Update>) { for (update in updates) { val outcome = update.outcome val input = update.inputs for ((featureName, featureValue) in input.text) { // multinomial situation storage.addOneToPriorsCountOfClass(outcome) storage.addOneToTotalDataCount() val wordCountsForCurrentFeature = WordCounter.countWords(featureValue) for ((word, count) in wordCountsForCurrentFeature) { storage.addToCountOfWordInClass(featureName, outcome, word, count) storage.addOneToCountOfAllWordInClass(featureName, outcome, count) } } for ((featureName, featureValue) in input.category) { // category situation storage.addOneToPriorsCountOfClass(outcome) storage.addOneToTotalDataCount() storage.addToCountOfWordInClass(featureName, outcome, featureValue, 1) storage.addOneToCountOfAllWordInClass(featureName, outcome, 1) } } } }
0
Kotlin
0
0
dce2136e35abeb7729f3ce9639d5ac1163116dbb
4,961
pblayze
MIT License
rtron-math/src/main/kotlin/io/rtron/math/range/RangeExtensions.kt
tum-gis
258,142,903
false
{"Kotlin": 1425220, "C": 12590, "Dockerfile": 511, "CMake": 399, "Shell": 99}
package io.rtron.math.range /** * Returns the intersecting [Range] of a provided set of ranges. * * @receiver provided set of ranges for which the intersecting range shall be found * @return maximum range that intersects all ranges within the set */ fun <T : Comparable<*>> Set<Range<T>>.intersectingRange(): Range<T> = reduce { acc, element -> acc.intersection(element) } /** * Union operation of a set of [Range] to a [RangeSet]. */ fun <T : Comparable<*>> Set<Range<T>>.unionRanges(): RangeSet<T> = map { RangeSet.of(it) }.toSet().unionRangeSets() /** * Returns true, if the set of ranges contains intersecting [Range]. */ fun <T : Comparable<*>> Set<Range<T>>.containsIntersectingRanges(): Boolean { val rangeSetsList = this.map { RangeSet.of(it) } return rangeSetsList.toSet().containsIntersectingRangeSets() } /** * Returns true, if the list of ranges contains consecutively following ranges that intersect. */ fun <T : Comparable<*>> List<Range<T>>.containsConsecutivelyIntersectingRanges(): Boolean = map { it.toRangeSet() }.zipWithNext().any { it.first.intersects(it.second) }
4
Kotlin
12
38
27969aee5a0c8115cb5eaf085ca7d4c964e1f033
1,121
rtron
Apache License 2.0
src/main/kotlin/days/Day16.kt
hughjdavey
725,972,063
false
{"Kotlin": 76988}
package days import days.Day14.Direction.EAST import days.Day14.Direction.NORTH import days.Day14.Direction.SOUTH import days.Day14.Direction.WEST import xyz.hughjd.aocutils.Coords.Coord class Day16 : Day(16) { private val grid = BeamGrid(inputList) override fun partOne(): Any { return grid.getEnergy() } // todo takes 40 seconds override fun partTwo(): Any { val startingBeams = grid.getEdgeTiles().flatMap { when { it.y == 0 -> when (it.x) { 0 -> listOf(Beam(it, SOUTH), Beam(it, EAST)) grid.lastX -> listOf(Beam(it, SOUTH), Beam(it, WEST)) else -> listOf(Beam(it, SOUTH)) } it.y == grid.lastY -> when (it.x) { 0 -> listOf(Beam(it, NORTH), Beam(it, EAST)) grid.lastX -> listOf(Beam(it, NORTH), Beam(it, WEST)) else -> listOf(Beam(it, NORTH)) } it.x == 0 -> listOf(Beam(it, EAST)) it.x == grid.lastX -> listOf(Beam(it, WEST)) else -> emptyList() } } return startingBeams.maxOf { grid.getEnergy(it) } } class BeamGrid(private val input: List<String>) { val lastX = input.first().lastIndex val lastY = input.lastIndex fun getEnergy(startingBeam: Beam = Beam(Coord(0, 0), EAST)): Int { var beams = listOf(startingBeam) val tiles = mutableListOf<Beam>() while (beams.isNotEmpty()) { tiles.addAll(beams) beams = beams .flatMap { it.advance(getTile(it.position)) } .filterNot { isOutsideGrid(it.position) } .filterNot { tiles.contains(it) } } return tiles.map { it.position }.distinct().map { getTile(it) }.size } fun getEdgeTiles(): List<Coord> { return input.first().mapIndexed { x, _ -> Coord(x, 0) } + input.last().mapIndexed { x, _ -> Coord(x, lastY) } + (0..lastY).map { y -> Coord(0, y) } + (0..lastY).map { y -> Coord(lastX, y) } } private fun isOutsideGrid(coord: Coord) = coord.x < 0 || coord.y < 0 || coord.x > lastX || coord.y > lastY private fun getTile(coord: Coord): Char { return input[coord.y][coord.x] } } data class Beam(val position: Coord, val direction: Day14.Direction) { fun advance(tile: Char): List<Beam> { return when (tile) { '.' -> listOf(onEmptySpace()) '/','\\' -> listOf(onMirror(tile)) '-','|' -> onSplitter(tile) else -> emptyList() } } private fun onEmptySpace(): Beam { return when (direction) { NORTH -> copy(position = position.minusY(1)) EAST -> copy(position = position.plusX(1)) SOUTH -> copy(position = position.plusY(1)) WEST -> copy(position = position.minusX(1)) } } private fun onMirror(mirror: Char): Beam { return when (direction) { NORTH -> if (mirror == '/') Beam(position.plusX(1), EAST) else Beam(position.minusX(1), WEST) EAST -> if (mirror == '/') Beam(position.minusY(1), NORTH) else Beam(position.plusY(1), SOUTH) SOUTH -> if (mirror == '/') Beam(position.minusX(1), WEST) else Beam(position.plusX(1), EAST) WEST -> if (mirror == '/') Beam(position.plusY(1), SOUTH) else Beam(position.minusY(1), NORTH) } } private fun onSplitter(splitter: Char): List<Beam> { return when (direction) { NORTH, SOUTH -> if (splitter == '-') listOf(Beam(position.minusX(1), WEST), Beam(position.plusX(1), EAST)) else listOf(onEmptySpace()) EAST, WEST -> if (splitter == '|') listOf(Beam(position.minusY(1), NORTH), Beam(position.plusY(1), SOUTH)) else listOf(onEmptySpace()) } } } }
0
Kotlin
0
0
330f13d57ef8108f5c605f54b23d04621ed2b3de
4,232
aoc-2023
Creative Commons Zero v1.0 Universal
src/main/kotlin/Problem20.kt
jimmymorales
496,703,114
false
{"Kotlin": 67323}
import java.math.BigInteger /** * Factorial digit sum * * n! means n × (n − 1) × ... × 3 × 2 × 1 * * For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, * and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. * * Find the sum of the digits in the number 100! * * https://projecteuler.net/problem=20 */ fun main() { println(factorialDigitSum(10)) println(factorialDigitSum(100)) } private fun factorialDigitSum(n: Int): Int { val result = mutableListOf<Int>().apply { var num = n while (num != 0) { add(num % 10) num /= 10 } } for (factor in (n - 1) downTo 2) { var acc = 0 for ((i, num) in result.withIndex()) { val res = (num * factor) + acc result[i] = res % 10 acc = res / 10 } while (acc != 0) { result.add(acc % 10) acc /= 10 } } return result.sum() }
0
Kotlin
0
0
e881cadf85377374e544af0a75cb073c6b496998
988
project-euler
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/GetWinner.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 import kotlin.math.max /** * 1535. Find the Winner of an Array Game * @see <a href="https://leetcode.com/problems/find-the-winner-of-an-array-game">Source</a> */ fun interface GetWinner { operator fun invoke(arr: IntArray, k: Int): Int } sealed interface GetWinnerStrategy { data object QueueSolution : GetWinner, GetWinnerStrategy { override fun invoke(arr: IntArray, k: Int): Int { var maxElement = arr[0] val queue: Queue<Int> = LinkedList() for (i in 1 until arr.size) { maxElement = max(maxElement, arr[i]) queue.offer(arr[i]) } var curr = arr[0] var winstreak = 0 while (queue.isNotEmpty()) { val opponent: Int = queue.poll() if (curr > opponent) { queue.offer(opponent) winstreak++ } else { queue.offer(curr) curr = opponent winstreak = 1 } if (winstreak == k || curr == maxElement) { return curr } } return -1 } } data object NoQueueSolution : GetWinner, GetWinnerStrategy { override fun invoke(arr: IntArray, k: Int): Int { var maxElement = arr[0] for (i in 1 until arr.size) { maxElement = max(maxElement, arr[i]) } var curr = arr[0] var winstreak = 0 for (i in 1 until arr.size) { val opponent = arr[i] if (curr > opponent) { winstreak++ } else { curr = opponent winstreak = 1 } if (winstreak == k || curr == maxElement) { return curr } } return -1 } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,667
kotlab
Apache License 2.0
demo-plural-sight-gradle/src/main/kotlin/demo/objects/House.kt
antoniolazaro
257,624,848
false
null
package demo.objects /* Given a program that reads two numbers from input each in a new line: The first one represents a number of rooms of a house. It helps define and create an instance of a class depending on that number according to the following rules: 1 – Cabin, 2-3 – Bungalow, 4 – Cottage, 5-7 – Mansion, 8-10 – Palace. If the number is lower than 1, it's a Cabin if the number is greater than 10, it's a Palace; The second one is the base price of this house. If this price is lower than 0, this house costs 0, if the number is greater than 1_000_000, the base price is 1_000_000; There is also a coefficient per each class: 1 – Cabin, 1.2 – Bungalow, 1.25 – Cottage, 1.4 – Mansion, 1.6 – Palace. The program is to define which house to build and to calculate the final price of this house according to the next rule: base price * coefficient. Fix the program below and implement the given logic. Don't forget to print the integer, not a floating-point number! */ fun main() { val rooms = readLine()!!.toInt() val price = readLine()!!.toInt() val house = createHouse(rooms, price) println(totalPrice(house)) } fun createHouse(rooms: Int,price: Int): House{ return when{ rooms <= 1 -> Cabin(rooms,price) rooms in 2..3 -> Bungalow(rooms,price) rooms == 4 -> Cottage(rooms,price) rooms in 5..7 -> Mansion(rooms,price) else -> Palace(rooms,price) } } fun totalPrice(house: House): Int{ return (house.price * house.coefficient).toInt() } open class House(val rooms: Int) { var price: Int = 0 set(price){ field = when { price < 0 -> 0 price > 1_000_000 -> 1_000_000 else -> { price } } } open val coefficient = 0.0 val finalPrice: Int get(){ return (price * coefficient).toInt() } } class Cabin(rooms: Int): House(rooms) { override val coefficient: Double = 1.0 constructor(rooms: Int, price: Int): this(rooms){ super.price = price } } class Bungalow(rooms: Int) : House(rooms) { override val coefficient = 1.2 constructor(rooms: Int, price: Int) : this(rooms){ super.price = price } } class Cottage(rooms: Int) : House(rooms) { override val coefficient = 1.25 constructor(rooms: Int, price: Int) : this(rooms){ super.price = price } } class Mansion(rooms: Int) : House(rooms) { override val coefficient = 1.4 constructor(rooms: Int, price: Int) : this(rooms){ super.price = price } } class Palace(rooms: Int) : House(rooms) { override val coefficient = 1.6 constructor(rooms: Int, price: Int) : this(rooms){ super.price = price } }
0
Kotlin
0
0
9e673057c3255be66fd67479b8198fa129463d95
2,807
kotlin-lab
Apache License 2.0
src/main/kotlin/day20/part1/Part1.kt
bagguley
329,976,670
false
null
package day20.part1 import day20.data fun main() { val tiles = load(data) val corners = findCorners(tiles) corners.forEach { println(it.number) } println(corners.map { it.number }.fold(1L, {a,i -> a * i} )) } fun load(data: List<String>): List<Tile> { return data.map { loadTile(it) } } fun loadTile(data: String): Tile { val lines = data.split("\n").filter { it.isNotEmpty() }.toMutableList() val first = lines.removeFirst() val tileNum = first.substring(5, 9).toInt() return Tile(tileNum, lines) } fun findCorners(tiles: List<Tile>): List<Tile> { val result:MutableList<Tile> = mutableListOf() for (tile in tiles) { val otherTiles = tiles.filter { it != tile } val otherEdges = otherTiles.flatMap { it.edges() } val edges = tile.edges() val matchingEdges = edges.filterNot { otherEdges.contains(it) || otherEdges.contains(it.reversed()) } if (matchingEdges.size == 2) { result.add(tile) } } return result }
0
Kotlin
0
0
6afa1b890924e9459f37c604b4b67a8f2e95c6f2
1,030
adventofcode2020
MIT License
2016/src/main/kotlin/day2.kt
madisp
434,510,913
false
{"Kotlin": 388138}
import utils.Grid import utils.Parser import utils.Solution import utils.Vec2i import utils.mapItems fun main() { Day2.run() } object Day2 : Solution<List<String>>() { override val name = "day2" override val parser = Parser.lines val pad = Parser.charGrid("123\n456\n789") val pad2 = Parser.charGrid("00100\n02340\n56789\n0ABC0\n00D00") val dirs = mapOf( 'U' to Vec2i.UP, 'L' to Vec2i.LEFT, 'R' to Vec2i.RIGHT, 'D' to Vec2i.DOWN, ) override fun part1(): String { return solve(pad) } override fun part2(): String { return solve(pad2) } private fun solve(pad: Grid<Char>): String { var location = pad.cells.first { (_, c) -> c == '5' }.first val out = StringBuilder() input.forEach { line -> line.forEach { c -> location = dirs[c]?.let { location + it }?.takeIf { it in pad && pad[it] != '0' } ?: location } out.append(pad[location]) } return out.toString() } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
965
aoc_kotlin
MIT License
src/day5/Day5.kt
davidcurrie
579,636,994
false
{"Kotlin": 52697}
package day5 import java.io.File fun main() { val parts = File("src/day5/input.txt").readText(Charsets.UTF_8).split("\n\n") val lines = parts[0].split("\n") val length = (lines.last().length + 1) / 4 val columns = List(length) { mutableListOf<Char>() } lines.dropLast(1).forEach { line -> for (i in 0 until length) { val char = line[(i * 4) + 1] if (char != ' ') { columns[i].add(char) } } } val pattern = "move (\\d*) from (\\d*) to (\\d*)".toRegex() val partOne = columns.map { column -> column.map { it }.toMutableList() } parts[1].split("\n").dropLast(1).forEach { line -> val numbers = pattern.find(line)!!.groupValues.drop(1).map(String::toInt) for (i in 0 until numbers[0]) { partOne[numbers[2]-1].add(0, partOne[numbers[1]-1].removeAt(0)) } } println(partOne.map { column -> column.first() }.joinToString("")) val partTwo = columns.map { column -> column.map { it }.toMutableList() } parts[1].split("\n").dropLast(1).forEach { line -> val numbers = pattern.find(line)!!.groupValues.drop(1).map(String::toInt) for (i in 0 until numbers[0]) { partTwo[numbers[2]-1].add(0, partTwo[numbers[1]-1].removeAt(numbers[0] - i - 1)) } } println(partTwo.map { column -> column.first() }.joinToString("")) }
0
Kotlin
0
0
0e0cae3b9a97c6019c219563621b43b0eb0fc9db
1,407
advent-of-code-2022
MIT License
classroom/src/main/kotlin/com/radix2/algorithms/week3/TraditionalMergeSort.kt
rupeshsasne
190,130,318
false
{"Java": 66279, "Kotlin": 50290}
package com.radix2.algorithms.week3 object TraditionalMergeSort { fun sort(array: IntArray) { val aux = IntArray(array.size) sort(array, aux, 0, array.size - 1) } fun sort(array: IntArray, aux: IntArray, lo: Int, hi: Int) { if (lo >= hi) return val mid = lo + (hi - lo) / 2 sort(array, aux, lo, mid) sort(array, aux, mid + 1, hi) merge(array, aux, lo, mid, hi) } fun merge(array: IntArray, aux: IntArray, lo: Int, mid: Int, hi: Int) { System.arraycopy(array, lo, aux, lo, (hi - lo) + 1) var i = lo var j = mid + 1 for (k in lo..hi) { when { i > mid -> array[k] = aux[j++] j > hi -> array[k] = aux[i++] aux[i] > aux[j] -> { array[k] = aux[j++] } else -> array[k] = aux[i++] } } } } fun main(args: Array<String>) { val array = intArrayOf(6, 2, 1, 0, 13, 89, 72, 4, 22, 28) TraditionalMergeSort.sort(array) println(array.joinToString()) }
0
Java
0
1
341634c0da22e578d36f6b5c5f87443ba6e6b7bc
1,099
coursera-algorithms-part1
Apache License 2.0
src/commonMain/kotlin/eu/yeger/cyk/parser/ProductionRuleParser.kt
DerYeger
302,742,119
false
null
package eu.yeger.cyk.parser import eu.yeger.cyk.* import eu.yeger.cyk.model.* public fun parseProductionRules( startSymbol: String, includeEmptyProductionRule: Boolean = false, productionRules: String, ): Result<ProductionRuleSet> { return startSymbol .parseStartSymbol() .andThen { validatedStartSymbol -> productionRules .trimIndent() .lines() .filter(String::isNotBlank) .parseLines(validatedStartSymbol) } .map { productionRuleSet -> when (includeEmptyProductionRule) { true -> productionRuleSet.copy( terminatingRules = productionRuleSet.terminatingRules + TerminatingRule( StartSymbol(startSymbol), TerminalSymbol("") ) ) false -> productionRuleSet } } } private fun List<String>.parseLines(startSymbol: StartSymbol): Result<ProductionRuleSet> { return mapAsResult { parseLine(startSymbol) } .map(::productionRuleSet) } private fun String.parseLine(startSymbol: StartSymbol): Result<ProductionRule> { return trim() .splitIntoComponents() .andThen { components -> components.asProductionRule(startSymbol) } } private fun String.splitIntoComponents(): Result<List<String>> { return when { this matches productionRuleRegex -> split("->", " ").filter(String::isNotBlank).asSuccess() else -> fail("Invalid production rule. ($this)") } } private fun List<String>.asProductionRule(startSymbol: StartSymbol): Result<ProductionRule> { return when (val inputString = get(0)) { startSymbol.symbol -> startSymbol.asSuccess() else -> inputString.parseNonTerminalSymbol() }.andThen { inputSymbol -> when (size) { 3 -> asNonTerminatingProductionRule(inputSymbol) 2 -> asTerminatingProductionRule(inputSymbol) else -> fail("Invalid amount of symbols on the right side! Must be 1 for terminal or 2 for non terminal production rules. ($lastIndex)") } } } private fun List<String>.asNonTerminatingProductionRule(inputSymbol: NonTerminalSymbol): Result<NonTerminatingRule> { return get(1) .parseNonTerminalSymbol() .with(get(2).parseNonTerminalSymbol()) { firstRight, secondRight -> NonTerminatingRule( left = inputSymbol, right = firstRight to secondRight ) } } private fun List<String>.asTerminatingProductionRule(inputSymbol: NonTerminalSymbol): Result<TerminatingRule> { return get(1) .parseTerminalSymbol() .map { terminalSymbol -> TerminatingRule(inputSymbol, terminalSymbol) } }
0
Kotlin
0
2
76b895e3e8ea6b696b3ad6595493fda9ee3da067
2,812
cyk-algorithm
MIT License
src/Day06.kt
dmstocking
575,012,721
false
{"Kotlin": 40350}
fun main() { fun part1(input: List<String>): Int { var i = 0 input.first() .asSequence() .windowed(4) { it.toSet().size } .onEach { i += 1 } .dropWhile { it != 4 } .take(1) .first() return i + 3 } fun part2(input: List<String>): Int { var i = 0 input.first() .asSequence() .windowed(14) { it.toSet().size } .onEach { i += 1 } .dropWhile { it != 14 } .take(1) .first() return i + 13 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") check(part1(testInput) == 7) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e49d9247340037e4e70f55b0c201b3a39edd0a0f
834
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/g1101_1200/s1162_as_far_from_land_as_possible/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1101_1200.s1162_as_far_from_land_as_possible // #Medium #Array #Dynamic_Programming #Breadth_First_Search #Matrix // #Graph_Theory_I_Day_4_Matrix_Related_Problems // #2023_05_25_Time_362_ms_(81.25%)_Space_86_MB_(31.25%) import java.util.LinkedList import java.util.Objects import java.util.Queue class Solution { fun maxDistance(grid: Array<IntArray>): Int { val q: Queue<IntArray> = LinkedList() val n = grid.size val m = grid[0].size val vis = Array(n) { BooleanArray(m) } for (i in 0 until n) { for (j in 0 until m) { if (grid[i][j] == 1) { q.add(intArrayOf(i, j)) vis[i][j] = true } } } if (q.isEmpty() || q.size == n * m) { return -1 } val dir = intArrayOf(-1, 0, 1, 0, -1) var maxDistance = 0 var level = 1 while (q.isNotEmpty()) { val size = q.size for (i in 0 until size) { val top = q.poll() val currX = Objects.requireNonNull(top)[0] val currY = top[1] for (j in 0 until dir.size - 1) { val x = currX + dir[j] val y = currY + dir[j + 1] if (x >= 0 && x != n && y >= 0 && y != n && !vis[x][y]) { maxDistance = Math.max(maxDistance, level) vis[x][y] = true q.add(intArrayOf(x, y)) } } } level++ } return maxDistance } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,648
LeetCode-in-Kotlin
MIT License
src/main/kotlin/day02/Round.kt
jankase
573,187,696
false
{"Kotlin": 70242}
package day02 internal data class Round(val opponentPlay: Play, val yourPlay: Play, val result: RoundResult) { companion object { fun fromOpponentAndYourPlay(input: String): Round { val playInputs = inputStrings(input).map { Play.valueOf(it) } val opponentPlay = playInputs[0] val yourPlay = playInputs[1] return Round(opponentPlay, yourPlay, roundResult(opponentPlay, yourPlay)) } fun fromOpponentPlayAndDesiredResult(input: String): Round { val playInputs = inputStrings(input) val opponentPlay = Play.valueOf(playInputs[0]) val result = RoundResult.valueOf(playInputs[1]) return Round(opponentPlay, yourPlay(opponentPlay, result), result) } private fun inputStrings(input: String): Array<String> { val playInputs = input.split(" ").toTypedArray() if (playInputs.size != 2) error("Expected two plays per round") return playInputs } private fun roundResult(opponentPlay: Play, yourPlay: Play): RoundResult { return when { opponentPlay == yourPlay -> RoundResult.DRAW opponentPlay == Play.ROCK && yourPlay == Play.PAPER || opponentPlay == Play.PAPER && yourPlay == Play.SCISSORS || opponentPlay == Play.SCISSORS && yourPlay == Play.ROCK -> RoundResult.WIN else -> RoundResult.LOST } } private fun yourPlay(opponentPlay: Play, desiredResult: RoundResult): Play { return when (desiredResult) { RoundResult.DRAW -> opponentPlay RoundResult.WIN -> when (opponentPlay) { Play.ROCK -> Play.PAPER Play.PAPER -> Play.SCISSORS Play.SCISSORS -> Play.ROCK } RoundResult.LOST -> when (opponentPlay) { Play.ROCK -> Play.SCISSORS Play.PAPER -> Play.ROCK Play.SCISSORS -> Play.PAPER } } } } }
0
Kotlin
0
0
0dac4ec92c82a5ebb2179988fb91fccaed8f800a
2,141
adventofcode2022
Apache License 2.0
libraries/core-converter/src/main/kotlin/dev/marlonlom/apps/glucoreo/converter/measurement.kt
marlonlom
690,744,248
false
{"Kotlin": 77324}
/* * Copyright 2023 Marlonlom * SPDX-License-Identifier: Apache-2.0 */ package dev.marlonlom.apps.glucoreo.converter /** * Measurement units enum class. * * @author marlonlom * * @property unitText text for measurement unit. */ enum class MeasurementUnits( private val unitText: String ) { MGDL("mg/dl"), MMOLL("mmol/l") } /** * Measurement status check interface definition. * * @author marlonlom * */ interface MeasurementStatusChecker { /** * Checks for measurement status using a numeric value in mg/dl. * * @param mgdl value for comparison. * * @return true/false */ fun isInStatus(mgdl: Double): Boolean } /** * Measurement status enum class. * * @author marlonlom * */ enum class MeasurementStatus : MeasurementStatusChecker { /** * Hypoglycemia status enum entry. */ HYPOGLYCEMIA { override fun isInStatus(mgdl: Double): Boolean = mgdl < 70 }, /** * Lower status enum entry. */ LOWER { override fun isInStatus(mgdl: Double): Boolean = mgdl <= 80 }, /** * Normal status enum entry. */ NORMAL { override fun isInStatus(mgdl: Double): Boolean = between(mgdl, 80.0, 130.0) }, /** * Higher status enum entry. */ HIGHER { override fun isInStatus(mgdl: Double): Boolean = between(mgdl, 130.0, 180.0) }, /** * Hyperglycemia status enum entry. */ HYPERGLYCEMIA { override fun isInStatus(mgdl: Double): Boolean = between(mgdl, 180.0, 600.0) }, /** * Hyperosmolar hyperglycemic status enum entry. */ HYPEROSMOLAR_HYPERGLYCEMIC { override fun isInStatus(mgdl: Double): Boolean = mgdl > 600 }; companion object { /** * Finds a single enum entry for measurement status. * * @param mgdl Numeric value for finding status. */ fun single(mgdl: Double) = when { mgdl >= 0 -> values().find { it.isInStatus(mgdl) }?.name ?: "ERROR" else -> "ERROR" } } } /** * Checks if a number is between min and max values. * * @param num Selected number for checks if inside range. * @param min Minimum value for range. * @param max Maximum value for range. */ internal fun between( num: Double, min: Double, max: Double ) = (num > min).and(num <= max)
0
Kotlin
0
0
25dcb40a4f84251b01538309189a73ed7f1b63b0
2,245
glucoreo
Apache License 2.0
buildSrc/src/main/kotlin/utils/CommonUtils.kt
AlexRogalskiy
331,076,596
false
null
/* * Copyright (C) 2021. <NAME>. All Rights Reserved. * * 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 utils import java.util.* object CommonUtils { init { // To hide annoying warning on Windows System.setProperty("idea.use.native.fs.for.win", "false") } /** A state machine for classifying qualified names. */ private enum class TyParseState(val isSingleUnit: Boolean) { /** The start state. */ START(false) { override fun next(n: JavaCaseFormat): TyParseState { return when (n) { JavaCaseFormat.UPPERCASE -> // if we see an UpperCamel later, assume this was a class // e.g. com.google.FOO.Bar AMBIGUOUS JavaCaseFormat.LOWER_CAMEL -> REJECT JavaCaseFormat.LOWERCASE -> // could be a package START JavaCaseFormat.UPPER_CAMEL -> TYPE } } }, /** The current prefix is a type. */ TYPE(true) { override fun next(n: JavaCaseFormat): TyParseState { return when (n) { JavaCaseFormat.UPPERCASE, JavaCaseFormat.LOWER_CAMEL, JavaCaseFormat.LOWERCASE -> FIRST_STATIC_MEMBER JavaCaseFormat.UPPER_CAMEL -> TYPE } } }, /** The current prefix is a type, followed by a single static member access. */ FIRST_STATIC_MEMBER(true) { override fun next(n: JavaCaseFormat): TyParseState { return REJECT } }, /** Anything not represented by one of the other states. */ REJECT(false) { override fun next(n: JavaCaseFormat): TyParseState { return REJECT } }, /** An ambiguous type prefix. */ AMBIGUOUS(false) { override fun next(n: JavaCaseFormat): TyParseState { return when (n) { JavaCaseFormat.UPPERCASE -> AMBIGUOUS JavaCaseFormat.LOWER_CAMEL, JavaCaseFormat.LOWERCASE -> REJECT JavaCaseFormat.UPPER_CAMEL -> TYPE } } }; /** Transition function. */ abstract fun next(n: JavaCaseFormat): TyParseState } /** * Returns the end index (inclusive) of the longest prefix that matches the naming conventions of * a type or static field access, or -1 if no such prefix was found. * * Examples: * * * ClassName * * ClassName.staticMemberName * * com.google.ClassName.InnerClass.staticMemberName */ internal fun typePrefixLength(nameParts: List<String>): Optional<Int> { var state = TyParseState.START var typeLength = Optional.empty<Int>() for (i in nameParts.indices) { state = state.next(JavaCaseFormat.from(nameParts[i])) if (state === TyParseState.REJECT) { break } if (state.isSingleUnit) { typeLength = Optional.of(i) } } return typeLength } /** Case formats used in Java identifiers. */ enum class JavaCaseFormat { UPPERCASE, LOWERCASE, UPPER_CAMEL, LOWER_CAMEL; companion object { /** Classifies an identifier's case format. */ internal fun from(name: String): JavaCaseFormat { var firstUppercase = false var hasUppercase = false var hasLowercase = false var first = true for (element in name) { if (!Character.isAlphabetic(element.toInt())) { continue } if (first) { firstUppercase = Character.isUpperCase(element) first = false } hasUppercase = hasUppercase or Character.isUpperCase(element) hasLowercase = hasLowercase or Character.isLowerCase(element) } return if (firstUppercase) { if (hasLowercase) UPPER_CAMEL else UPPERCASE } else { if (hasUppercase) LOWER_CAMEL else LOWERCASE } } } } }
13
Kotlin
2
2
d7173ec1d9ef227308d926e71335b530c43c92a8
5,026
gradle-kotlin-sample
Apache License 2.0
atcoder.jp/abc264/abc264_c/Main.kt
akkinoc
520,873,415
false
{"Kotlin": 24773}
fun main() { val (h1, w1) = readLine()!!.split(" ").map { it.toInt() } val a = List(h1) { readLine()!!.split(" ") } val (h2, w2) = readLine()!!.split(" ").map { it.toInt() } val b = List(h2) { readLine()!!.split(" ") } for (r in (0 until h1).combinations(h1 - h2)) { val w = a.filterIndexed { i, _ -> i !in r } for (c in (0 until w1).combinations(w1 - w2)) if (w.map { it.filterIndexed { i, _ -> i !in c } } == b) return print("Yes") } print("No") } fun <T> Iterable<T>.combinations(r: Int): Sequence<List<T>> = sequence { if (r < 1) yield(emptyList()) else forEachIndexed { i, e -> drop(i + 1).combinations(r - 1).forEach { yield(listOf(e) + it) } } }
1
Kotlin
0
1
e650a9c2e73d26a8f037b4f9f0dfe960171a604a
718
atcoder-workspace
MIT License
src/Day02.kt
ElenaRgC
572,898,962
false
null
fun main() { fun part1(input: List<String>): Int { var valorJugada = 0 var valorRonda = 0 var valorTotal = 0 for (i in input) { valorRonda = 3 when (i[0]) { 'A' -> when (i[2]) { 'Y' -> valorRonda = 6 'Z' -> valorRonda = 0 } 'B' -> when (i[2]) { 'X' -> valorRonda = 0 'Z' -> valorRonda = 6 } 'C' -> when (i[2]) { 'X' -> valorRonda = 6 'Y' -> valorRonda = 0 } } when (i[2]) { 'X' -> valorJugada = 1 'Y' -> valorJugada = 2 'Z' -> valorJugada = 3 } //println("$valorJugada, $valorRonda") valorTotal += valorJugada + valorRonda } return valorTotal } fun part2(input: List<String>): Int { var valorJugada = 0 var valorRonda = 0 var valorTotal = 0 for (i in input) { valorRonda = 3 when (i[0]) { 'A' -> when (i[2]) { 'X' -> { valorRonda = 0 valorJugada = 3 } 'Z' -> { valorRonda = 6 valorJugada = 2 } else -> valorJugada = 1 } 'B' -> when (i[2]) { 'X' -> { valorRonda = 0 valorJugada = 1 } 'Z' -> { valorRonda = 6 valorJugada = 3 } else -> valorJugada = 2 } 'C' -> when (i[2]) { 'X' -> { valorRonda = 0 valorJugada = 2 } 'Z' -> { valorRonda = 6 valorJugada = 1 } else -> valorJugada = 3 } } //println("$valorJugada, $valorRonda") valorTotal += valorJugada + valorRonda } return valorTotal } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b7505e891429970c377f7b45bfa8b5157f85c457
2,643
advent-of-code-2022
Apache License 2.0
src/Day04.kt
mdtausifahmad
573,116,146
false
{"Kotlin": 5783}
import java.io.File fun main(){ val numberOfCommonPairs = File("src/Day04.txt") .readText() .split("\n") .flatMap { it.lines() } .sumOf { val split = it.split(",") overLappingAssignmentPair(split[0].split("-"), split[1].split("-")) } println(numberOfCommonPairs) } fun pairsInRangeOfEachOther(firstPair: List<String>,secondPair: List<String>) : Int{ val firstPairInsideSecond = firstPair[0].toInt() >= secondPair[0].toInt() && firstPair[1].toInt() <= secondPair[1].toInt() val secondPairInsideFirst = secondPair[0].toInt() >= firstPair[0].toInt() && secondPair[1].toInt() <= firstPair[1].toInt() return if (firstPairInsideSecond.or(secondPairInsideFirst)) 1 else 0 } fun overLappingAssignmentPair(firstPair: List<String>,secondPair: List<String>) : Int{ val firstPairOverlappingSecond = firstPair[0].toInt() in secondPair[0].toInt()..secondPair[1].toInt() || firstPair[1].toInt() in secondPair[0].toInt()..secondPair[1].toInt() val secondPairOverlappingFirst = secondPair[0].toInt() in firstPair[0].toInt()..firstPair[1].toInt() || secondPair[1].toInt() in firstPair[0].toInt()..firstPair[1].toInt() return if (firstPairOverlappingSecond.or(secondPairOverlappingFirst)) 1 else 0 }
0
Kotlin
0
0
13295fd5f5391028822243bb6880a98c70475ee2
1,322
adventofcode2022
Apache License 2.0
src/commonMain/kotlin/edu/unito/probability/ConditionalProbabilityDistribution.kt
lamba92
150,039,952
false
null
package edu.unito.probability import edu.unito.probability.bayes.AssignmentProposition interface ConditionalProbabilityDistribution { /** * @return the Random Variable this conditional probability distribution is * on. */ fun getOn(): RandomVariable /** * @return a consistent ordered Set (e.g. LinkedHashSet) of the parent * Random Variables for this conditional distribution. */ fun getParents(): Set<RandomVariable> /** * A convenience method for merging the elements of getParents() and getOn() * into a consistent ordered set (i.e. getOn() should always be the last * Random Variable returned when iterating over the set). * * @return a consistent ordered Set (e.g. LinkedHashSet) of the random * variables this conditional probability distribution is for. */ fun getFor() = LinkedHashSet(getParents()).apply { add(getOn()) } /** * * @param rv * the Random Variable to be checked. * @return true if the conditional distribution is for the passed in Random * Variable, false otherwise. */ operator fun contains(rv: RandomVariable): Boolean /** * Get the value for the provided set of AssignmentPropositions for the * random variables comprising the Conditional Distribution (size of each * must equal and their random variables must match). * * @param eventValues * the assignment propositions for the random variables * comprising the Conditional Distribution * @return the value for the possible worlds associated with the assignments * for the random variables comprising the Conditional Distribution. */ fun getValue(vararg eventValues: AssignmentProposition): Double /** * A conditioning case is just a possible combination of values for the * parent nodes - a miniature possible world, if you like. The returned * distribution must sum to 1, because the entries represent an exhaustive * set of cases for the random variable. * * @param parentValues * for the conditioning case. The size of parentValues must equal * getParents() and their Random Variables must match. * @return the Probability Distribution for the Random Variable the * Conditional Probability Distribution is On. * @see ConditionalProbabilityDistribution.getOn * @see ConditionalProbabilityDistribution.getParents */ fun getConditioningCase(vararg parentValues: AssignmentProposition): ProbabilityDistribution /** * Retrieve a specific example for the Random Variable this conditional * distribution is on. * * @param probabilityChoice * a double value, from the range [0.0d, 1.0d), i.e. 0.0d * (inclusive) to 1.0d (exclusive). * @param parentValues * for the conditioning case. The size of parentValues must equal * getParents() and their Random Variables must match. * @return a sample value from the domain of the Random Variable this * distribution is on, based on the probability argument passed in. * @see ConditionalProbabilityDistribution.getOn */ abstract fun getSample(probabilityChoice: Double, vararg parentValues: AssignmentProposition): Any }
0
Kotlin
0
0
acbae0d12d9501ca531b8e619b49ce38793a7697
3,287
bayes-net-project-multiplatform
MIT License
src/main/kotlin/xyz/prpht/distributeamountbetweenslots/Distributor.kt
ilyawaisman
203,545,826
false
null
package xyz.prpht.distributeamountbetweenslots import kotlin.math.floor import kotlin.random.Random fun main() { repeat(0x10) { println(distribute(100, 5, 1, Random).joinToString(" ") { "%2d".format(it) }) } } fun distribute(amount: Int, slots: Int, rollsNum: Int, random: Random): List<Int> { var leftAmount = amount return (slots downTo 1).map { leftSlots -> val slotAmount = random.generateSlotAmount(leftAmount, leftSlots, rollsNum) leftAmount -= slotAmount slotAmount } } private fun Random.generateSlotAmount(leftAmount: Int, leftSlots: Int, rollsNum: Int): Int { check(leftSlots > 0) { "Non-positive slots count: $leftSlots" } check(leftAmount > 0) { "Non-positive amount: $leftAmount" } check(leftAmount >= leftSlots) { "leftAmount ($leftAmount) is less than leftSlots ($leftSlots)" } if (leftSlots <= 1) return leftAmount if (leftAmount == leftSlots) return 1 /** * Magic formula ensures: * 1. Values distributed in `[1..(leftAmount-lestSlots+1)]` to guarantee that next `leftAmount >= next slotsAmount`. * 2. Estimation is `leftAmount/leftSlots`. * 3. Values are centered: those near `leftAmount/leftSlots` are more probable than values at the boundaries. * Bigger `rollsNum` leads to more centered result. */ val rollsSum = (0 until rollsNum).map { nextInt(1, leftAmount - leftSlots + 2) }.sum() return stochasticRound(2.0 * rollsSum / (rollsNum * leftSlots) + (leftSlots - 2.0) / leftSlots) } fun Random.stochasticRound(x: Double): Int { val floor = floor(x) var result = floor if (nextFloat() < (x - floor)) result += 1 return result.toInt() }
0
Kotlin
0
0
aa5c75ba801ad4c3a0e370913bbecce661dee98a
1,728
distribute-amount-between-slots
MIT License
leetcode/src/main/kotlin/com/artemkaxboy/leetcode/p00/Leet14.kt
artemkaxboy
513,636,701
false
{"Kotlin": 547181, "Java": 13948}
package com.artemkaxboy.leetcode.p00 /** * Optimizations * Runtime 140ms Beats 97.72% * Memory 35.5MB Beats 78.27% */ class Leet14 { class Solution { fun longestCommonPrefix(strs: Array<String>): String { val lastElement = strs.size - 1 val commonPrefixLength = intArrayOf(strs[0].length) var i = 1 while (i <= lastElement) { val l = strs[i].length if (l < commonPrefixLength[0]) commonPrefixLength[0] = l if (l == 0) break i++ } i = 1 while (i <= lastElement) { var j = 0 while (j < commonPrefixLength[0]) { if (strs[0][j] != strs[i][j]) { commonPrefixLength[0] = j break } j++ } i++ } return strs[0].subSequence(0, commonPrefixLength[0]).toString() } } companion object { @JvmStatic fun main(args: Array<String>) { val testCase1 = arrayOf("floa", "floa", "flolll") doWork(testCase1) } private fun doWork(data: Array<String>) { val solution = Solution() val result = solution.longestCommonPrefix(data) println("Data: $data") println("Result: $result\n") } } }
0
Kotlin
0
0
516a8a05112e57eb922b9a272f8fd5209b7d0727
1,495
playground
MIT License
src/main/kotlin/biz/koziolek/adventofcode/year2021/day01/day1.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2021.day01 import biz.koziolek.adventofcode.findInput fun main() { val inputFile = findInput(object {}) println("Simple increases: ${countIncreases(inputFile.bufferedReader().lineSequence())}") println("Windowed increases: ${countIncreasesSlidingWindow(inputFile.bufferedReader().lineSequence(), windowSize = 3)}") } fun countIncreases(lines: Sequence<String>): Int = lines .map { it.toInt() } .fold(Pair<Int, Int?>(0, null)) { acc, currentHeight -> val previousHeight = acc.second if (previousHeight != null && currentHeight > previousHeight) { acc.copy(first = acc.first.inc(), second = currentHeight) } else { acc.copy(second = currentHeight) } }.first fun countIncreasesSlidingWindow(lines: Sequence<String>, windowSize: Int = 3): Int = lines .map { it.toInt() } .windowed(windowSize) .map { it.sum() } .map { it.toString() } .let { countIncreases(it) }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
1,185
advent-of-code
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem907/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem907 /** * LeetCode page: [907. Sum of Subarray Minimums](https://leetcode.com/problems/sum-of-subarray-minimums/); */ class Solution { /* Complexity: * Time O(|arr|) and Space O(|arr|); */ fun sumSubarrayMins(arr: IntArray): Int { val module = 1_000_000_007 val indexStack = mutableListOf<Int>() // stack for searching nearest previous index with smaller value val prefixDp = IntArray(arr.size) // prefixDp[i] is the sum of min of all sub arrays ending at index i for (index in prefixDp.indices) { while (indexStack.isNotEmpty() && arr[index] < arr[indexStack.last()]) { indexStack.apply { removeAt(lastIndex) } } val indexOfPrevSmaller = indexStack.lastOrNull() ?: -1 indexStack.add(index) prefixDp[index] = ((index - indexOfPrevSmaller) * arr[index] + prefixDp.getOrElse(indexOfPrevSmaller) { 0 }) % module } return prefixDp.reduce { acc, i -> (acc + i) % module } } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,075
hj-leetcode-kotlin
Apache License 2.0
untitled/src/main/kotlin/Day2tginsberg.kt
jlacar
572,845,298
false
{"Kotlin": 41161}
/* Exercise to go through the thought process for coming up with solution shared by tginsberg */ class Day2tginsberg(private val fileName: String) : AocSolution { override val description: String get() = "Day 2 - RPS tginsberg approach ($fileName)" private val rounds = InputReader(fileName).lines override fun part1() = score( mapOf( "A X" to 1 + 3, // r vs R -> Draw "B X" to 1 + 0, // p vs R -> Lose "C X" to 1 + 6, // s vs R -> Win "A Y" to 2 + 6, // r vs P -> W "B Y" to 2 + 3, // p vs P -> D "C Y" to 2 + 0, // s vs P -> L "A Z" to 3 + 0, // r vs S -> L "B Z" to 3 + 6, // p vs S -> W "C Z" to 3 + 3, // s vs S -> D ) ) override fun part2() = score( mapOf( "A X" to 0 + 3, // (L) r vs Scissors "B X" to 0 + 1, // (L) p vs Rock "C X" to 0 + 2, // (L) s vs Paper "A Y" to 3 + 1, // (D) r vs R "B Y" to 3 + 2, // (D) p vs P "C Y" to 3 + 3, // (D) s vs S "A Z" to 6 + 2, // (W) r vs P "B Z" to 6 + 3, // (W) p vs S "C Z" to 6 + 1, // (W) s vs R ) ) private fun score(result: Map<String, Int>) = rounds.sumOf { result[it] ?: 0 } } fun main() { Day2tginsberg("Day2-sample.txt") solution { part1() shouldBe 15 part2() shouldBe 12 } Day2tginsberg("Day2.txt") solution { part1() shouldBe 14264 part2() shouldBe 12382 } Day2tginsberg("Day2-alt.txt") solution { part1() shouldBe 13268 part2() shouldBe 15508 } }
0
Kotlin
0
2
dbdefda9a354589de31bc27e0690f7c61c1dc7c9
1,659
adventofcode2022-kotlin
The Unlicense
2019/src/test/kotlin/Day10.kt
jp7677
318,523,414
false
{"Kotlin": 171284, "C++": 87930, "Rust": 59366, "C#": 1731, "Shell": 354, "CMake": 338}
import kotlin.math.atan2 import kotlin.math.hypot import kotlin.test.Test import kotlin.test.assertEquals class Day10 { data class Coord(val x: Int, val y: Int) @Test fun runPart01() { val coords = getInputAsCoords() val detected = coords.maxOf { coords .filter { other -> it != other } .groupBy { other -> it.angleTo(other) } .count() } assertEquals(274, detected) } @Test fun runPart02() { val coords = getInputAsCoords() val laser = coords.maxByOrNull { coords .filter { other -> it != other } .groupBy { other -> it.angleTo(other) } .count() } ?: throw IllegalStateException() val asteroids = coords .filter { it != laser } .sortedBy { laser.angleTo(it) } .toMutableList() val hits = mutableListOf<Coord>() while (asteroids.isNotEmpty()) { asteroids.onEach { if (it.isVisibleFor(laser, asteroids)) hits.add(it) } asteroids.removeAll(hits) } val result = hits[200 - 1] .let { it.x * 100 + it.y } .toInt() assertEquals(305, result) } private fun getInputAsCoords() = Util.getInputAsListOfString("day10-input.txt") .flatMapIndexed { indexY, line -> line.mapIndexed { indexX, char -> Triple(indexX, indexY, char) } } .filter { it.third == '#' } .map { Coord(it.first, it.second) } private fun Coord.isVisibleFor(other: Coord, coords: List<Coord>) = coords.none { other.angleTo(this) == other.angleTo(it) && other.distanceTo(it) < other.distanceTo(this) } private fun Coord.angleTo(other: Coord) = Math.toDegrees(atan2((other.y - this.y).toDouble(), (other.x - this.x).toDouble())) .plus(90) .let { if (it < 0) it + 360 else it } private fun Coord.distanceTo(other: Coord) = hypot((this.x - other.x).toDouble(), (this.y - other.y).toDouble()) }
0
Kotlin
1
2
8bc5e92ce961440e011688319e07ca9a4a86d9c9
2,122
adventofcode
MIT License
src/main/kotlin/biz/koziolek/adventofcode/coords2dLong.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode import kotlin.math.abs import kotlin.math.pow import kotlin.math.sqrt data class LongCoord(val x: Long, val y: Long) { constructor(x: Int, y: Int) : this(x.toLong(), y.toLong()) operator fun plus(other: LongCoord) = LongCoord(x + other.x, y + other.y) operator fun minus(other: LongCoord) = LongCoord(x - other.x, y - other.y) operator fun unaryMinus() = LongCoord(-x, -y) override fun toString() = "$x,$y" fun distanceTo(other: LongCoord) = sqrt( (x - other.x).toDouble().pow(2) + (y - other.y).toDouble().pow(2) ) infix fun manhattanDistanceTo(other: LongCoord): Long = abs(x - other.x) + abs(y - other.y) fun getAdjacentCoords(includeDiagonal: Boolean = false): Set<LongCoord> = if (includeDiagonal) { setOf( this + LongCoord(-1, 0), this + LongCoord(0, -1), this + LongCoord(1, 0), this + LongCoord(0, 1), this + LongCoord(-1, -1), this + LongCoord(1, -1), this + LongCoord(-1, 1), this + LongCoord(1, 1), ) } else { setOf( this + LongCoord(-1, 0), this + LongCoord(0, -1), this + LongCoord(1, 0), this + LongCoord(0, 1), ) } fun move(direction: Direction, count: Long = 1): LongCoord = when (direction) { Direction.NORTH -> copy(y = y - count) Direction.SOUTH -> copy(y = y + count) Direction.WEST -> copy(x = x - count) Direction.EAST -> copy(x = x + count) } companion object { val yComparator: Comparator<LongCoord> = Comparator.comparing { it.y } val xComparator: Comparator<LongCoord> = Comparator.comparing { it.x } fun fromString(str: String): LongCoord = str.split(',') .map { it.trim().toInt() } .let { LongCoord(x = it[0], y = it[1]) } } } fun LongProgression.zipAsCoord(ys: LongProgression) = zip(ys) { x, y -> LongCoord(x, y) } fun <T> Map<LongCoord, T>.getWidth() = keys.maxOfOrNull { it.x }?.plus(1) ?: 0 fun <T> Map<LongCoord, T>.getHeight() = keys.maxOfOrNull { it.y }?.plus(1) ?: 0 fun Iterable<LongCoord>.sortByYX() = sortedWith( LongCoord.yComparator.thenComparing(LongCoord.xComparator) ) fun Map<LongCoord, Char>.to2DString(default: Char): String = to2DString { _, c -> c ?: default } fun <T> Map<LongCoord, T>.to2DString(formatter: (LongCoord, T?) -> Char): String = to2DStringOfStrings { coord, t -> formatter(coord, t).toString() } fun <T> Map<LongCoord, T>.to2DStringOfStrings(formatter: (LongCoord, T?) -> String): String = buildString { val (minX, maxX) = keys.minAndMaxOrNull { it.x }!! val (minY, maxY) = keys.minAndMaxOrNull { it.y }!! for (y in minY..maxY) { for (x in minX..maxX) { val coord = LongCoord(x, y) val value = get(coord) append(formatter(coord, value)) } if (y != maxY) { append('\n') } } } fun <T> Map<LongCoord, T>.getAdjacentCoords(coord: LongCoord, includeDiagonal: Boolean): Set<LongCoord> = keys.getAdjacentCoords(coord, includeDiagonal) fun Iterable<LongCoord>.getAdjacentCoords(coord: LongCoord, includeDiagonal: Boolean): Set<LongCoord> { return sequence { yield(LongCoord(-1, 0)) yield(LongCoord(0, -1)) yield(LongCoord(1, 0)) yield(LongCoord(0, 1)) if (includeDiagonal) { yield(LongCoord(-1, -1)) yield(LongCoord(1, -1)) yield(LongCoord(-1, 1)) yield(LongCoord(1, 1)) } } .map { coord + it } .filter { contains(it) } .toSet() } fun Map<LongCoord, Int>.toGraph(includeDiagonal: Boolean): Graph<LongCoordNode, UniDirectionalGraphEdge<LongCoordNode>> = buildGraph { this@toGraph.forEach { (coord, value) -> val node2 = coord.toGraphNode() getAdjacentCoords(coord, includeDiagonal) .forEach { adjCoord -> add(UniDirectionalGraphEdge( node1 = adjCoord.toGraphNode(), node2 = node2, weight = value, )) } } } fun LongCoord.toGraphNode() = LongCoordNode(this) data class LongCoordNode(val coord: LongCoord) : GraphNode { override val id = "x${coord.x}_y${coord.y}" override fun toGraphvizString(exactXYPosition: Boolean, xyPositionScale: Float) = id }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
4,746
advent-of-code
MIT License
src/main/kotlin/org/example/adventofcode/puzzle/Day05.kt
nikos-ds
573,046,617
false
null
package org.example.adventofcode.puzzle import org.apache.commons.lang3.StringUtils import org.apache.commons.lang3.StringUtils.isBlank import org.example.adventofcode.util.FileLoader object Day05 { private const val FILE_PATH = "/day-05-input.txt" fun printSolution() { println("- part 1: ${getTopOfEachStack(Day05::part1CraneOperator)}") println("- part 2: ${getTopOfEachStack(Day05::part2CraneOperator)}") } private fun getTopOfEachStack(craneOperator: (ArrayList<ArrayDeque<Char>>, Int, Int, Int) -> Unit): List<Char> { val allLines = FileLoader.loadFromFile<String>(FILE_PATH) var stackHeaderLine = 0 for (i in 0..allLines.size) { if (StringUtils.startsWith(allLines[i], " 1")) { stackHeaderLine = i break } } val numberOfStacks = allLines[stackHeaderLine].split("""\s+""".toRegex()).last().toInt() val stacks = ArrayList<ArrayDeque<Char>>() for (i in 1..numberOfStacks) { stacks.add(ArrayDeque()) } for (lineNumber in stackHeaderLine - 1 downTo 0) { val currentLine = allLines[lineNumber] for (characterIndex in currentLine.indices) { if (!listOf('[', ']', ' ').contains(currentLine[characterIndex])) { stacks[(characterIndex - 1) / 4].add(currentLine[characterIndex]) } } } val rearrangementCommand = """move (\d+) from (\d+) to (\d+)""".toRegex() for (line in allLines) { if (isBlank(line)) { continue } if (rearrangementCommand.matches(line)) { val (howMany, fromStack, toStack) = rearrangementCommand.find(line)!!.destructured craneOperator(stacks, fromStack.toInt() - 1, toStack.toInt() - 1, howMany.toInt()) } } val topOfEachStack = stacks.stream().map { stack -> stack.removeLast() }.toList() return topOfEachStack } private fun part1CraneOperator( stacks: ArrayList<ArrayDeque<Char>>, fromStack: Int, toStack: Int, howMany: Int ) { for (i in 1..howMany) { stacks[toStack].addLast(stacks[fromStack].removeLast()) } } private fun part2CraneOperator( stacks: ArrayList<ArrayDeque<Char>>, fromStack: Int, toStack: Int, howMany: Int ) { val toIndex = stacks[fromStack].size val fromIndex = toIndex - howMany val cratesToBeMoved = stacks[fromStack].subList(fromIndex, toIndex) stacks[toStack].addAll(cratesToBeMoved) stacks[fromStack].subList(fromIndex, toIndex).clear() } }
0
Kotlin
0
0
3f97096ebcd19f971653762fe29ddec1e379d09a
2,758
advent-of-code-2022-kotlin
MIT License
src/cn/leetcode/codes/simple155/Simple155.kt
shishoufengwise1234
258,793,407
false
{"Java": 771296, "Kotlin": 68641}
package cn.leetcode.codes.simple155 import cn.leetcode.codes.out import java.util.* import kotlin.math.min fun main() { val minStack = MinStack() minStack.push(-2) minStack.push(0) minStack.push(-3) out(minStack.getMin())// --> 返回 -3. minStack.pop() out(minStack.top()) // --> 返回 0. out(minStack.getMin()) // --> 返回 -2. } /* 155. 最小栈 设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。 push(x) —— 将元素 x 推入栈中。 pop() —— 删除栈顶的元素。 top() —— 获取栈顶元素。 getMin() —— 检索栈中的最小元素。 示例: 输入: ["MinStack","push","push","push","getMin","pop","top","getMin"] [[],[-2],[0],[-3],[],[],[],[]] 输出: [null,null,null,null,-3,null,0,-2] 解释: MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> 返回 -3. minStack.pop(); minStack.top(); --> 返回 0. minStack.getMin(); --> 返回 -2. 提示: pop、top 和 getMin 操作总是在 非空栈 上调用。 */ class MinStack() { private val minStack = LinkedList<Int>().also { it.push(Int.MAX_VALUE) } private val numStack = LinkedList<Int>() fun push(x: Int) { numStack.push(x) minStack.push(min(minStack.peek(), x)) } fun pop() { numStack.pop() minStack.pop() } fun top(): Int { return numStack.peek() } fun getMin(): Int { return minStack.peek() } }
0
Java
0
0
f917a262bcfae8cd973be83c427944deb5352575
1,582
LeetCodeSimple
Apache License 2.0
src/main/kotlin/problems/S05c05p10DPchangeDynamicProgramming.kt
jimandreas
377,843,697
false
null
@file:Suppress("SameParameterValue", "UnnecessaryVariable", "UNUSED_VARIABLE", "ReplaceManualRangeWithIndicesCalls") package problems /** * stepik: @link: https://stepik.org/lesson/240300/step/10?unit=212646 * rosalind: @link: http://rosalind.info/problems/ba5a/ * Code Challenge: Solve the Change Problem. Input: An integer money and an array Coins = (coin1, ..., coind). Output: The minimum number of coins with denominations Coins that changes money. */ fun main() { val coins = listOf(5, 3, 1) val money = 18662 val result = dpChange(money, coins) println(result) // val coins2 = listOf(5, 4, 1) // val money2 = 22 // val result2 = problems.dpChange(money2, coins2) // println(result2) } /** * [money] An integer money * [coins] array Coins = (coin1, ..., coin d) coins sizes available for change sorted high to low * @return The minimum number of coins with denominations Coins that changes money. */ fun dpChange(money: Int, coins: List<Int>): Int { val minNumCoinsMap: MutableMap<Int, Int> = mutableMapOf() minNumCoinsMap[0] = 0 for (m in 1..money) { minNumCoinsMap[m] = Int.MAX_VALUE for (i in 0 until coins.size) { if (m >= coins[i]) { if (minNumCoinsMap[m - coins[i]]!! + 1 < minNumCoinsMap[m]!!) { minNumCoinsMap[m] = minNumCoinsMap[m - coins[i]]!! +1 } } } } return minNumCoinsMap[money]!! }
0
Kotlin
0
0
fa92b10ceca125dbe47e8961fa50242d33b2bb34
1,476
stepikBioinformaticsCourse
Apache License 2.0
src/main/kotlin/dayfourteen/DayFourteen.kt
pauliancu97
619,525,509
false
null
package dayfourteen import getLines import kotlin.math.max import kotlin.math.min private typealias Matrix = List<MutableList<Boolean>> private val Matrix.rows: Int get() = this.size private val Matrix.cols: Int get() = this.first().size private operator fun Matrix.get(row: Int, col: Int): Boolean = this[row][col] private operator fun Matrix.set(row: Int, col: Int, value: Boolean) { this[row][col] = value } private fun Matrix(rows: Int, cols: Int): Matrix = List(rows) { MutableList(cols) { false } } private fun Matrix.isInbounds(row: Int, col: Int) = row in 0 until this.rows && col in 0 until this.cols private data class InfiniteMatrix( val matrix: MutableMap<Coordinate, Boolean>, val rows: Int ) { operator fun get(row: Int, col: Int): Boolean = if (row == rows - 1) true else this.matrix[Coordinate(row, col)] ?: false operator fun set(row: Int, col: Int, value: Boolean) { this.matrix[Coordinate(row, col)] = value } } private fun InfiniteMatrix(rows: Int, cols: Int): InfiniteMatrix { val matrix: MutableMap<Coordinate, Boolean> = mutableMapOf() for (row in 0 until (rows - 1)) { for (col in 0 until cols) { matrix[Coordinate(row, col)] = false } } for (col in 0 until cols) { matrix[Coordinate(row = rows - 1, col = col)] = true } return InfiniteMatrix(matrix, rows) } private data class CaveCoordinate(val x: Int, val y: Int) private data class Coordinate(val row: Int, val col: Int) private typealias CavePath = List<CaveCoordinate> private typealias Path = List<Coordinate> private fun String.toCaveCoordinate(): CaveCoordinate { val (xString, yString) = this.split(",") val x = xString.toInt() val y = yString.toInt() return CaveCoordinate(x, y) } private fun getCoordinate(caveCoordinate: CaveCoordinate, offsetX: Int, offsetY: Int): Coordinate = Coordinate(row = caveCoordinate.y - offsetY, col = caveCoordinate.x - offsetX) private fun getPath(cavePath: CavePath, offsetX: Int, offsetY: Int): Path = cavePath.map { getCoordinate(it, offsetX, offsetY) } private fun String.toCavePath(): CavePath = this.split(" -> ") .map { it.toCaveCoordinate() } private fun placePath(matrix: Matrix, path: Path) { for ((first, second) in path.zipWithNext()) { if (first.row == second.row) { val row = first.row val startCol = min(first.col, second.col) val endCol = max(first.col, second.col) for (col in startCol..endCol) { matrix[row, col] = true } } else if (first.col == second.col) { val col = first.col val startRow = min(first.row, second.row) val endRow = max(first.row, second.row) for (row in startRow..endRow) { matrix[row, col] = true } } } } private fun placePath(matrix: InfiniteMatrix, path: Path) { for ((first, second) in path.zipWithNext()) { if (first.row == second.row) { val row = first.row val startCol = min(first.col, second.col) val endCol = max(first.col, second.col) for (col in startCol..endCol) { matrix[row, col] = true } } else if (first.col == second.col) { val col = first.col val startRow = min(first.row, second.row) val endRow = max(first.row, second.row) for (row in startRow..endRow) { matrix[row, col] = true } } } } private fun getCave(path: String): Pair<Matrix, Coordinate> { val strings = getLines(path) val cavePaths = strings.map { it.toCavePath() } val minX = cavePaths.flatMap { cavePath -> cavePath.map { it.x } }.min() val minY = 0 val maxX = cavePaths.flatMap { cavePath -> cavePath.map { it.x } }.max() val maxY = cavePaths.flatMap { cavePath -> cavePath.map { it.y } }.max() val rows = maxY - minY + 1 val cols = maxX - minX + 1 val matrix = Matrix(rows, cols) val paths = cavePaths.map { cavePath -> getPath(cavePath, minX, minY) } paths.forEach { placePath(matrix, it) } val coordinate = Coordinate(row = 0, col = 500 - minX) return matrix to coordinate } private fun getCaveInfinite(path: String): Pair<InfiniteMatrix, Coordinate> { val strings = getLines(path) val cavePaths = strings.map { it.toCavePath() } val minX = cavePaths.flatMap { cavePath -> cavePath.map { it.x } }.min() val minY = 0 val maxX = cavePaths.flatMap { cavePath -> cavePath.map { it.x } }.max() val maxY = cavePaths.flatMap { cavePath -> cavePath.map { it.y } }.max() val rows = maxY - minY + 3 val cols = maxX - minX + 1 val matrix = InfiniteMatrix(rows, cols) val paths = cavePaths.map { cavePath -> getPath(cavePath, minX, minY) } paths.forEach { placePath(matrix, it) } val coordinate = Coordinate(row = 0, col = 500 - minX) return matrix to coordinate } private fun updateSand(matrix: Matrix, row: Int, col: Int): Boolean { var currentRow = row var currentCol = col var shouldContinue = true while (shouldContinue) { if (currentRow + 1 < matrix.rows) { if (!matrix[currentRow + 1, currentCol]) { currentRow += 1 continue } } else { shouldContinue = false currentRow += 1 continue } if (currentCol - 1 >= 0) { if (!matrix[currentRow + 1, currentCol - 1]) { currentRow += 1 currentCol -= 1 continue } } else { shouldContinue = false currentRow += 1 currentCol -= 1 continue } if (currentCol + 1 < matrix.cols) { if (!matrix[currentRow + 1, currentCol + 1]) { currentRow += 1 currentCol += 1 continue } } else { shouldContinue = false currentRow += 1 currentCol += 1 continue } shouldContinue = false } val shouldPlace = matrix.isInbounds(currentRow, currentCol) if (shouldPlace) { matrix[currentRow, currentCol] = true } return shouldPlace } private fun updateSandInfiniteMatrix(matrix: InfiniteMatrix, row: Int, col: Int): Boolean { var currentRow = row var currentCol = col var shouldContinue = true while (shouldContinue) { if (!matrix[currentRow + 1, currentCol]) { currentRow += 1 continue } if (!matrix[currentRow + 1, currentCol - 1]) { currentRow += 1 currentCol -= 1 continue } if (!matrix[currentRow + 1, currentCol + 1]) { currentRow += 1 currentCol += 1 continue } shouldContinue = false } val shouldPlace = !(currentRow == row && currentCol == col) if (shouldPlace) { matrix[currentRow, currentCol] = true } return shouldPlace } private fun getNumOfSandParticles(matrix: Matrix, row: Int, col: Int): Int { var numOfSandParticles = 0 var shouldContinue = true while (shouldContinue) { shouldContinue = updateSand(matrix, row, col) if (shouldContinue) { numOfSandParticles++ } } return numOfSandParticles } private fun getNumOfSandParticlesInfiniteMatrix(matrix: InfiniteMatrix, row: Int, col: Int): Int { var numOfSandParticles = 0 var shouldContinue = true while (shouldContinue) { shouldContinue = updateSandInfiniteMatrix(matrix, row, col) numOfSandParticles++ } return numOfSandParticles } private fun Matrix.getRepresentation(): String { var string = "" for (row in 0 until this.rows) { for (col in 0 until this.cols) { string += if (this[row, col]) "#" else "." } string += "\n" } return string } private fun solvePartOne() { val (matrix, coordinate) = getCave("day_14.txt") val answer = getNumOfSandParticles(matrix, coordinate.row, coordinate.col) println(answer) } private fun solvePartTwo() { val (matrix, coordinate) = getCaveInfinite("day_14.txt") val answer = getNumOfSandParticlesInfiniteMatrix(matrix, coordinate.row, coordinate.col) println(answer) } fun main() { //solvePartOne() solvePartTwo() }
0
Kotlin
0
0
78af929252f094a34fe7989984a30724fdb81498
8,546
advent-of-code-2022
MIT License
src/main/kotlin/com/sk/set29/2981. Find Longest Special Substring That Occurs Thrice I.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package com.sk.set29 import java.util.PriorityQueue class Solution2981 { fun maximumLength(s: String): Int { val map = mutableMapOf<Char, MutableList<Int>>() for (i in s.indices) { val ch = s[i] val list = map.getOrDefault(ch, mutableListOf<Int>()) list.add(i) map[ch] = list } var ans = -1 for (entry in map) { // total max 26 val pq = PriorityQueue<Int>(4) val list = entry.value if (list.size < 3) continue // no 3 items var i = 0 while (i < list.size) { val first = i pq.offer(1) if (pq.size > 3) pq.poll() while (i < list.size - 1 && list[i] + 1 == list[i + 1]) i++ pq.offer(i - first + 1) if (pq.size > 3) pq.poll() i++ } val segment = pq.asIterable().sorted().reversed() val a1 = if (segment.size >= 3) segment[2] else 0 val a2 = if (segment.size >=2) if (segment[0] == segment[1]) segment[0]-1 else segment [1] else 0 val a3 = segment[0] - 3 + 1 ans = maxOf(ans, a1, a2, a3) } return ans } }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
1,258
leetcode-kotlin
Apache License 2.0
src/main/kotlin/g2301_2400/s2397_maximum_rows_covered_by_columns/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2301_2400.s2397_maximum_rows_covered_by_columns // #Medium #Array #Matrix #Bit_Manipulation #Backtracking #Enumeration // #2023_07_02_Time_154_ms_(100.00%)_Space_32.3_MB_(100.00%) class Solution { private var ans = 0 fun maximumRows(matrix: Array<IntArray>, numSelect: Int): Int { dfs(matrix, /*colIndex=*/0, numSelect, /*mask=*/0) return ans } private fun dfs(matrix: Array<IntArray>, colIndex: Int, leftColsCount: Int, mask: Int) { if (leftColsCount == 0) { ans = Math.max(ans, getAllZerosRowCount(matrix, mask)) return } if (colIndex == matrix[0].size) { return } // choose this column dfs(matrix, colIndex + 1, leftColsCount - 1, mask or (1 shl colIndex)) // not choose this column dfs(matrix, colIndex + 1, leftColsCount, mask) } private fun getAllZerosRowCount(matrix: Array<IntArray>, mask: Int): Int { var count = 0 for (row in matrix) { var isAllZeros = true for (i in row.indices) { if (row[i] == 1 && mask shr i and 1 == 0) { isAllZeros = false break } } if (isAllZeros) { ++count } } return count } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,350
LeetCode-in-Kotlin
MIT License
src/pl/shockah/aoc/y2017/Day24.kt
Shockah
159,919,224
false
null
package pl.shockah.aoc.y2017 import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import pl.shockah.aoc.AdventTask import pl.shockah.aoc.UnorderedPair class Day24: AdventTask<List<UnorderedPair<Int>>, Int, Int>(2017, 24) { override fun parseInput(rawInput: String): List<UnorderedPair<Int>> { return rawInput.trim().lines().map { val split = it.split("/") return@map UnorderedPair(split[0].toInt(), split[1].toInt()) } } override fun part1(input: List<UnorderedPair<Int>>): Int { fun calculateMaxStrength(tail: Int, currentStrength: Int, elementsLeft: Set<UnorderedPair<Int>>): Int { return elementsLeft .filter { it.first == tail || it.second == tail } .maxOfOrNull { element -> val newTail = if (element.first == tail) element.second else element.first return@maxOfOrNull calculateMaxStrength( newTail, currentStrength + element.first + element.second, elementsLeft - element ) } ?: currentStrength } return calculateMaxStrength(0, 0, input.toSet()) } override fun part2(input: List<UnorderedPair<Int>>): Int { data class Result( val length: Int, val strength: Int ): Comparable<Result> { override fun compareTo(other: Result): Int { if (length != other.length) return length.compareTo(other.length) return strength.compareTo(other.strength) } } fun calculateMaxStrengthOfLongestBridge(tail: Int, currentStrength: Int, currentLength: Int, elementsLeft: Set<UnorderedPair<Int>>): Result { return elementsLeft .filter { it.first == tail || it.second == tail } .maxOfOrNull { element -> val newTail = if (element.first == tail) element.second else element.first return@maxOfOrNull calculateMaxStrengthOfLongestBridge( newTail, currentStrength + element.first + element.second, currentLength + 1, elementsLeft - element ) } ?: Result(currentLength, currentStrength) } return calculateMaxStrengthOfLongestBridge(0, 0, 0, input.toSet()).strength } class Tests { private val task = Day24() private val rawInput = """ 0/2 2/2 2/3 3/4 3/5 0/1 10/1 9/10 """.trimIndent() @Test fun part1() { val input = task.parseInput(rawInput) Assertions.assertEquals(31, task.part1(input)) } @Test fun part2() { val input = task.parseInput(rawInput) Assertions.assertEquals(19, task.part2(input)) } } }
0
Kotlin
0
0
9abb1e3db1cad329cfe1e3d6deae2d6b7456c785
2,429
Advent-of-Code
Apache License 2.0
src/Day01.kt
rxptr
572,717,765
false
{"Kotlin": 9737}
fun main() { val emptyLine = "\n\n" fun sliceInputToListOfInts(input: String): List<List<Int>> = input.split(emptyLine) .map { lines -> lines.lines().filter { it.isNotBlank() }.map { it.toInt() } } fun sumOfCalories(input: String): List<Int> = sliceInputToListOfInts(input).map { it.sum() }.sortedDescending() fun part1(input: String): Int = sumOfCalories(input).max() fun part2(input: String): Int = sumOfCalories(input).take(3).sum() val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
989ae08dd20e1018ef7fe5bf121008fa1c708f09
690
aoc2022
Apache License 2.0
Collections/Associate/src/TaskExtensionAssociate.kt
Rosietesting
373,564,502
false
{"HTML": 178715, "JavaScript": 147056, "Kotlin": 113135, "CSS": 105840}
fun main () { /* associateWith() creates a Map in which the elements of the original collection are keys, and values are produced from them by the given transformation function. */ val number1 = listOf("one", "two", "three", "four") println(number1.associateWith { it.length }) /* associateBy() creates a Map in which the elements of the original collection are the values, and keys are produced from them by the given transformation function. */ val number2 = listOf("one", "two", "three", "four") println(number2.associateBy { it.first().toUpperCase()}) val numbers3 = listOf("one", "two", "three", "four") // Calling associatedBy in a transformation function println(numbers3.associateBy(keySelector = { it.first().toUpperCase() }, valueTransform = { it.length })) /* Each count */ val numbers4 = listOf("one", "two", "three", "four", "five", "six") println(numbers4.groupingBy { it.first() }.eachCount()) /* fold() This function helps to accumulate value starting with initial value, then apply operation from left to right to current accumulator value and each element. */ val numbers5 = listOf("one", "two", "three", "four", "five", "six") //println(numbers5.groupingBy { it.first() }.fold(0){ total, item -> total + item}) println(listOf(1, 2, 3, 4, 5).fold(0) { total, item -> total + item }) println(listOf(1, 2, 3, 4, 5).fold(1) { mul, item -> mul * item }) //Associated val names = listOf("<NAME>", "<NAME>", "<NAME>") val byLastName = names.associate { it.split(" ") .let { (firstName, lastName) -> lastName to firstName } } println(byLastName) //Shop val city1 = City ("Bogota") val city2 = City ("London") val product1 = Product("Bread", 10.50) val product2 = Product("Rice", 4.23) val product3 = Product("potatoes", 1.23) val product4 = Product("brocoli", 12.60) val order1 = Order(listOf(product1,product3, product4), true) val order2 = Order(listOf(product2), true) val order3 = Order(listOf(product1, product2), true) val order4 = Order(listOf(product3, product4), true) val customer1 = Customer("<NAME>", city1, listOf(order1, order2, order3)) val customer2 = Customer("<NAME>", city2, listOf(order1)) val customer3 = Customer("Santi", city2, listOf(order1, order4)) val shop = Shop("Roxipan", listOf(customer2,customer3, customer1)) // This build a map from the customer name to the customer shop.customers.associateBy { it.name } shop.customers.associateBy(Customer::name) shop.customers.associateWith { it.city } shop.customers.associateWith{ Customer::city } shop.customers.associateBy {Customer::name} }
0
HTML
0
0
b0aa518d220bb43c9398dacc8a6d9b6c602912d5
2,816
KotlinKoans
MIT License
solutions/src/trainings/2017/day 07.kt
Kroppeb
225,582,260
false
null
package trainings.`2017` import helpers.* private fun part1(data: List<List<Any?>>){ val ps = data.map{it[0]}.toSet() val pps = data.flatMap { it.drop(2) }.toSet() println(ps - pps) } private fun part2(data:List<List<Any?>>){ val w = data.map { it[0].toString() to it[1] as Int }.toMap() val c = data.map { it[0].toString() to it.drop(3).map{it.toString()} }.toMap() fun check(cur:String) : Int{ if (c[cur]!!.isEmpty()) return w[cur]!! val childs = c[cur]!!.groupBy{check(it)} if(childs.size == 1) { //println(childs.toList()[0].let { (f, s) -> s.size * f } + w[cur]!!) return childs.toList()[0].let { (f, s) -> s.size * f } + w[cur]!! }else{ var (a,b) = childs.toList() if (a.second.size > 1){ val x = a a = b b = x } error("${a.second[0]}: ${b.first - a.first + w[a.second[0]]!!}") } } check("dtacyn") } fun main(){ val data = getWSV(2017_07).map2{it.getWord()?:it.getInt()} part1(data) }
0
Kotlin
0
1
744b02b4acd5c6799654be998a98c9baeaa25a79
984
AdventOfCodeSolutions
MIT License
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[31]下一个排列.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//实现获取 下一个排列 的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。 // // 如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。 // // 必须 原地 修改,只允许使用额外常数空间。 // // // // 示例 1: // // //输入:nums = [1,2,3] //输出:[1,3,2] // // // 示例 2: // // //输入:nums = [3,2,1] //输出:[1,2,3] // // // 示例 3: // // //输入:nums = [1,1,5] //输出:[1,5,1] // // // 示例 4: // // //输入:nums = [1] //输出:[1] // // // // // 提示: // // // 1 <= nums.length <= 100 // 0 <= nums[i] <= 100 // // Related Topics 数组 // 👍 1154 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun nextPermutation(nums: IntArray): Unit { // 时间复杂度 O(n) 题意为寻找较小的 调整位置 //较小数 index var index = nums.size - 2 while (index >= 0 && nums[index] >= nums[index + 1]){ index -- } //寻找比 index 较小的 if (index >= 0){ var j = nums.size -1 while (j >= 0 && nums[index] >= nums[j]){ j-- } //替换位置 swapNum(nums,index,j) } //翻转数组 reverseNums(nums,index+1) } //翻转数组 private fun reverseNums(nums: IntArray, startIndex: Int) { var left = startIndex var right = nums.size - 1 while (left < right){ swapNum(nums,left,right) left++ right-- } } //交换位置 private fun swapNum(nums: IntArray, i: Int, j: Int) { var temp = nums[i] nums[i] = nums[j] nums[j] = temp } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,927
MyLeetCode
Apache License 2.0
src/main/kotlin/com/staricka/adventofcode2023/days/Day11.kt
mathstar
719,656,133
false
{"Kotlin": 107115}
package com.staricka.adventofcode2023.days import com.staricka.adventofcode2023.framework.Day import com.staricka.adventofcode2023.util.GridCell import com.staricka.adventofcode2023.util.StandardGrid import kotlin.math.abs class Day11(val oldMultiplier: Long = 1000000): Day { enum class Galaxy: GridCell { `#`; override val symbol = name[0] } private fun calculateDistances(grid: StandardGrid<Galaxy>, multiplier: Long): Long { val emptyRows = (grid.minX..grid.maxX).filter { grid.row(it).isEmpty() }.toSortedSet() val emptyCols = (grid.minY..grid.maxY).filter { grid.col(it).isEmpty() }.toSortedSet() val galaxies = grid.cells() var total = 0L for (i in galaxies.indices) { for (j in (i+1 until galaxies.size)) { val (x1,y1,_) = galaxies[i] val (x2,y2,_) = galaxies[j] val x1l = x1 + emptyRows.headSet(x1).size * (multiplier - 1) val y1l = y1 + emptyCols.headSet(y1).size * (multiplier - 1) val x2l = x2 + emptyRows.headSet(x2).size * (multiplier - 1) val y2l = y2 + emptyCols.headSet(y2).size * (multiplier - 1) total += abs(x1l - x2l) + abs(y1l - y2l) } } return total } override fun part1(input: String): Long { val grid = StandardGrid.buildWithStrings(input) {Galaxy.valueOf(it)} return calculateDistances(grid, 2) } override fun part2(input: String): Long { val grid = StandardGrid.buildWithStrings(input) {Galaxy.valueOf(it)} return calculateDistances(grid, oldMultiplier) } }
0
Kotlin
0
0
8c1e3424bb5d58f6f590bf96335e4d8d89ae9ffa
1,666
adventOfCode2023
MIT License
src/Day01.kt
nmrsmn
574,578,675
false
{"Kotlin": 1364}
fun main() { fun part1(input: String): Int { return input.split("\n\n").maxOf { elf -> elf.lines().sumOf { it.toInt() } } } fun part2(input: String): Int { return input.split("\n\n") .map { elf -> elf.lines().sumOf { it.toInt() } } .sortedDescending() .subList(0, 3) .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24_000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5455d1fcc567bf63a16534b3d82ae2f407b1d41c
623
advent-of-code-2022
Apache License 2.0
src/iii_conventions/MyDate.kt
LeeReindeer
99,133,549
false
null
package iii_conventions data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int):Comparable<MyDate> { override fun compareTo(other: MyDate): Int { /* val diffYear=this.year-other.year val diffMonth=this.month-other.month val diffDay=this.dayOfMonth-other.dayOfMonth if(diffYear == 0) { if(diffMonth == 0) { return diffDay } return diffMonth } return diffYear*/ return when { year != other.year -> year - other.year month != other.month -> month - other.month else -> dayOfMonth - other.dayOfMonth } } } operator fun MyDate.rangeTo(other: MyDate): DateRange = DateRange(this, other) class RepeatedTime(val time: TimeInterval, val number: Int) operator fun MyDate.plus(timeInterval: TimeInterval): MyDate = this.addTimeIntervals(timeInterval, 1) operator fun MyDate.plus(timeInterval: RepeatedTime): MyDate = this.addTimeIntervals(timeInterval.time, timeInterval.number) enum class TimeInterval { DAY, WEEK, YEAR } operator fun TimeInterval.times(time: Int) = RepeatedTime(this, time) class DateRange(override val start: MyDate, override val endInclusive: MyDate) : ClosedRange<MyDate>, Iterable<MyDate>{ override fun iterator(): Iterator<MyDate> { return DateIterator(this) } //operator fun contains(value: MyDate): Boolean =((endInclusive>=start)&&(start<=value)&&(endInclusive>=value)) override fun contains(value: MyDate): Boolean =((endInclusive>=start)&&(start<=value)&&(endInclusive>=value)) } class DateIterator(private val dateRange: DateRange) : Iterator<MyDate> { var current: MyDate = dateRange.start override fun next(): MyDate { val result = current current = current.nextDay() return result } override fun hasNext(): Boolean = current <= dateRange.endInclusive }
0
Kotlin
0
0
6633226ec2264bc8725ea69267bbeea3b04b8e90
1,948
kotlin-koans-solved
MIT License
src/main/kotlin/divine/brothers/pizza/Setup.kt
AarjavP
450,892,849
false
{"Kotlin": 28300}
package divine.brothers.pizza import com.google.common.collect.BiMap import com.google.common.collect.HashBiMap import java.util.* import java.util.stream.Collectors @JvmInline value class Ingredient(val id: Int) { override fun toString(): String = id.toString() } @JvmInline value class CustomerId(val id: Int) data class Customer( val id: CustomerId, val likes: BitSet, val dislikes: BitSet, ) { fun isCompatibleWith(other: Customer): Boolean { return !(likes.intersects(other.dislikes) || other.likes.intersects(dislikes)) } } abstract class PizzaApproach(input: Sequence<String>) { interface PizzaSolution { val ingredients: BitSet } val ingredientAliases: BiMap<String, Ingredient> = HashBiMap.create() val customers: List<Customer> init { var aliasCounter = 0 fun registerIngredient(original: String): Ingredient { return ingredientAliases.computeIfAbsent(original) { Ingredient(aliasCounter++) } } fun String.parseIngredients(): BitSet { return substring(2).splitToSequence(' ').fold(BitSet()) { set, ingredient -> set.set(registerIngredient(ingredient).id) set } } val customers = mutableListOf<Customer>() for ((index, customerPrefs) in input.drop(1).chunked(2).withIndex()) { val likes = customerPrefs[0].parseIngredients() val dislikes = customerPrefs[1].takeIf { it != "0" }?.parseIngredients() ?: BitSet(0) customers += Customer(id = CustomerId(index), likes = likes, dislikes = dislikes) } this.customers = customers } fun BitSet.toIngredients(): Set<Ingredient> = stream().mapToObj { Ingredient(it) }.collect(Collectors.toSet()) fun BitSet.toCustomers(): List<Customer> = mutableListOf<Customer>().also { for (i in stream()) it.add(customers[i]) } abstract fun findIngredients(): PizzaSolution }
0
Kotlin
0
0
3aaaefc04d55b1e286dde0895fa32f9c34f5c945
1,974
google-hash-code-2022
MIT License
src/day03/Day03.kt
Sardorbekcyber
573,890,266
false
{"Kotlin": 6613}
package day03 import java.io.File fun main() { val letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" fun part1(input: String) : Int { val data = input.split("\n") var sum = 0 for (line in data) { val secondHalf = line.substring(line.length/2) for (char in line){ if (secondHalf.contains(char, false)){ sum += letters.indexOf(char) + 1 break } } } return sum } fun part2(input: String) : Int { val data = input.split("\n").chunked(3) var sum = 0 for (group in data){ val firstSet = mutableSetOf<Char>() val secondSet = mutableSetOf<Char>() val thirdSet = mutableSetOf<Char>() var setNum = 1 val groupAll = group.joinToString(",") for (char in groupAll){ if (char == ','){ setNum++ continue } when (setNum) { 1 -> firstSet.add(char) 2 -> secondSet.add(char) else -> thirdSet.add(char) } } for (char in firstSet){ if (secondSet.contains(char) && thirdSet.contains(char)){ sum += letters.indexOf(char) + 1 break } } } return sum } val testInput = File("src/day03/Day03_test.txt").readText() println(part1(testInput)) println(part2(testInput)) check(part1(testInput) == 157) check(part2(testInput) == 70) val input = File("src/day03/Day03.txt").readText() println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
56f29c8322663720bc83e7b1c6b0a362de292b12
1,801
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/nl/jackploeg/aoc/utilities/utilities.kt
jackploeg
736,755,380
false
{"Kotlin": 318734}
package nl.jackploeg.aoc.utilities import java.io.File import java.math.BigInteger fun readNumbersFile(fileName: String): List<Int> { return File(fileName) .readLines() .map { it.toInt() } } fun readStringFile(fileName: String): List<String> { return File(fileName) .readLines() } fun repeatString(input: String, repeat: Int, separator: Char) : String { if (repeat==1) return input val result= StringBuilder(input) repeat(( 2..repeat).count()) { result.append(separator) result.append(input) } return result.toString() } fun printList(list: List<*>) { list.forEach { println(it) } } fun leastCommonMultiple(first: BigInteger, second: BigInteger): BigInteger { val larger = if (first > second) first else second val maxLcm = first * second var lcm = larger while (lcm <= maxLcm) { if (lcm.mod(first) == BigInteger.ZERO && lcm.mod(second) == BigInteger.ZERO ) { return lcm } lcm += larger } return maxLcm } enum class Direction { UP, RIGHT, DOWN, LEFT; fun reversed() = when (this) { UP->DOWN DOWN->UP LEFT->RIGHT RIGHT->LEFT } }
0
Kotlin
0
0
f2b873b6cf24bf95a4ba3d0e4f6e007b96423b76
1,249
advent-of-code
MIT License
Circular_primes/Kotlin/src/CircularPrimes.kt
ncoe
108,064,933
false
{"D": 425100, "Java": 399306, "Visual Basic .NET": 343987, "C++": 328611, "C#": 289790, "C": 216950, "Kotlin": 162468, "Modula-2": 148295, "Groovy": 146721, "Lua": 139015, "Ruby": 84703, "LLVM": 58530, "Python": 46744, "Scala": 43213, "F#": 21133, "Perl": 13407, "JavaScript": 6729, "CSS": 453, "HTML": 409}
import java.math.BigInteger val SMALL_PRIMES = listOf( 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997 ) fun isPrime(n: BigInteger): Boolean { if (n < 2.toBigInteger()) { return false } for (sp in SMALL_PRIMES) { val spb = sp.toBigInteger() if (n == spb) { return true } if (n % spb == BigInteger.ZERO) { return false } if (n < spb * spb) { //if (n > SMALL_PRIMES.last().toBigInteger()) { // println("Next: $n") //} return true } } return n.isProbablePrime(10) } fun cycle(n: BigInteger): BigInteger { var m = n var p = 1 while (m >= BigInteger.TEN) { p *= 10 m /= BigInteger.TEN } return m + BigInteger.TEN * (n % p.toBigInteger()) } fun isCircularPrime(p: BigInteger): Boolean { if (!isPrime(p)) { return false } var p2 = cycle(p) while (p2 != p) { if (p2 < p || !isPrime(p2)) { return false } p2 = cycle(p2) } return true } fun testRepUnit(digits: Int) { var repUnit = BigInteger.ONE var count = digits - 1 while (count > 0) { repUnit = BigInteger.TEN * repUnit + BigInteger.ONE count-- } if (isPrime(repUnit)) { println("R($digits) is probably prime.") } else { println("R($digits) is not prime.") } } fun main() { println("First 19 circular primes:") var p = 2 var count = 0 while (count < 19) { if (isCircularPrime(p.toBigInteger())) { if (count > 0) { print(", ") } print(p) count++ } p++ } println() println("Next 4 circular primes:") var repUnit = BigInteger.ONE var digits = 1 count = 0 while (repUnit < p.toBigInteger()) { repUnit = BigInteger.TEN * repUnit + BigInteger.ONE digits++ } while (count < 4) { if (isPrime(repUnit)) { print("R($digits) ") count++ } repUnit = BigInteger.TEN * repUnit + BigInteger.ONE digits++ } println() testRepUnit(5003) testRepUnit(9887) testRepUnit(15073) testRepUnit(25031) testRepUnit(35317) testRepUnit(49081) }
0
D
0
4
c2a9f154a5ae77eea2b34bbe5e0cc2248333e421
3,138
rosetta
MIT License
kotlin/src/katas/kotlin/hackerrank/NewYearChaos.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.hackerrank import datsok.shouldEqual import org.junit.Test import java.util.* /** * https://www.hackerrank.com/challenges/new-year-chaos */ fun main() { val scanner = Scanner(System.`in`) main(generateSequence { scanner.nextLine() }) } private fun main(input: Sequence<String>, output: (Any?) -> Unit = { println(it) }) { val i = input.iterator() val t = i.next().trim().toInt() (1..t).forEach { i.next().trim().toInt() // skip number of items because it can be inferred from the line itself val q = i.next().split(" ").map { token -> token.trim().toInt() }.toTypedArray() val bribes = minimumBribes(q) output(bribes?.toString() ?: "Too chaotic") } } fun minimumBribes(q: Array<Int>): Int? { if (q.size <= 1) return 0 var result = 0 var i = q.size - 2 while (i >= 0) { val bribes = q.moveForward(i) if (bribes == null) return null else result += bribes i-- } return result } fun Array<Int>.moveForward(i: Int): Int? { if (this[i] <= this[i + 1]) return 0 swap(i, i + 1) if (i + 2 == size || this[i + 1] <= this[i + 2]) return 1 swap(i + 1, i + 2) if (i + 3 == size || this[i + 2] <= this[i + 3]) return 2 return null } private fun <T> Array<T>.swap(i1: Int, i2: Int) { val tmp = this[i1] this[i1] = this[i2] this[i2] = tmp } class NewYearChaosTests { @Test fun `testcase 0`() { """|2 |5 |2 1 5 3 4 |5 |2 5 1 3 4 """ shouldProduce """ |3 |Too chaotic """ } @Test fun `testcase 1`() { """|2 |8 |5 1 2 3 7 8 6 4 |8 |1 2 5 3 7 8 6 4 """ shouldProduce """ |Too chaotic |7 """ } @Test fun `testcase 2`() { """|1 |8 |1 2 5 3 4 7 8 6 """ shouldProduce """ |4 """ } private infix fun String.shouldProduce(expectedOutput: String) { val outputRecorder = OutputRecorder() main(trimToLineSequence(), outputRecorder) outputRecorder.text shouldEqual expectedOutput.trimMargin() + "\n" } }
7
Roff
3
5
0f169804fae2984b1a78fc25da2d7157a8c7a7be
2,241
katas
The Unlicense
src/main/kotlin/org/hildan/minecraft/mining/optimizer/geometry/Range3D.kt
joffrey-bion
48,772,914
false
null
package org.hildan.minecraft.mining.optimizer.geometry /** * Represents a 3D range. * * The min and max methods give the interval of variation of each variable. These intervals of variation are just bounds * for enumeration. They are not sufficient to tell if a point in space is in this range. For that purpose, use the * [inRange] method. */ interface Range3D { /** * Returns the maximum value Y can take in this range. * * @return the maximum value Y can take in this range. */ fun maxY(): Int /** * Returns the minimum value Y can take in this range. * * By default, the interval is symmetric and this is equivalent to [`-maxY()`][maxY]. * * @return the minimum value Y can take in this range. */ fun minY(): Int = -maxY() /** * Returns the maximum value X can take when Z varies, at the given Y distance of the center. * * @param distanceY the distance from the center on the Y axis * @return the maximum value X can take when Z varies, at the given Y distance of the center. */ fun maxX(distanceY: Int): Int /** * Returns the minimum value X can take when Z varies, at the given Y distance of the center. * * By default, the interval is symmetric and this is equivalent to [`-maxX()`][maxX]. * * @param distanceY the distance from the center on the Y axis * @return the minimum value X can take when Z varies, at the given Y distance of the center. */ fun minX(distanceY: Int): Int = -maxX(distanceY) /** * Returns the maximum value Z can take when X varies, at the given Y distance of the center. * * By default the range behaves symmetrically for X and Z, and this is equivalent to [maxX]. * * @param distanceY the distance from the center on the Y axis * @return the maximum value Z can take when X varies, at the given Y distance of the center. */ fun maxZ(distanceY: Int): Int = maxX(distanceY) /** * Returns the minimum value Z can take when X varies, at the given Y distance of the center. * * By default, the interval is symmetric and this is equivalent to [`-maxZ(distanceY)`][maxZ]. * * @param distanceY the distance from the center on the Y axis * @return the minimum value Z can take when X varies, at the given Y distance of the center. */ fun minZ(distanceY: Int): Int = -maxZ(distanceY) /** * Returns whether the given point is in range. * * @param distanceX the X distance from the center * @param distanceY the Y distance from the center * @param distanceZ the Z distance from the center * @return true if the given point is in range */ fun inRange(distanceX: Int, distanceY: Int, distanceZ: Int): Boolean fun allDistancesInRange(): Sequence<Distance3D> = sequence { for (dY in minY()..maxY()) { for (dX in minX(dY)..maxX(dY)) { for (dZ in minZ(dY)..maxZ(dY)) { if (inRange(dX, dY, dZ)) { yield(Distance3D.of(dX, dY, dZ)) } } } } } }
1
Kotlin
0
0
065ea1c3068d88d6b5abe39150f7866b100b0384
3,187
mc-mining-optimizer
MIT License
distributed-systems/consistent-hashing/src/Storage.kt
Lascor22
331,294,681
false
{"Java": 1706475, "HTML": 436528, "CSS": 371563, "C++": 342426, "Jupyter Notebook": 274491, "Kotlin": 248153, "Haskell": 189045, "Shell": 186916, "JavaScript": 159132, "Vue": 45665, "Python": 25957, "PLpgSQL": 23402, "Clojure": 11410, "Batchfile": 9677, "FreeMarker": 7201, "Yacc": 7148, "ANTLR": 6303, "Scala": 3020, "Lex": 1136, "Makefile": 473, "Grammatical Framework": 113}
class Storage { private val arr = ArrayList<Entry>(0) fun addToStorage(hash: Int, shard: Shard) { arr.add(Entry(hash, shard)) arr.sortBy { entry -> entry.hash } } fun isEmpty(): Boolean { return arr.isEmpty() } fun findAllHashes(shard: Shard): List<Int> { return arr.filter { entry -> entry.shard == shard } .map { entry -> entry.hash } } fun remove(shard: Shard) { arr.filter { entry -> entry.shard == shard } .forEach { entry -> arr.remove(entry) } } fun searchShard(hash: Int): Shard { return upperBound(hash).shard } fun searchAddBounds(hash: Int): Pair<Shard, HashRange> { val right = upperBound(hash) val left = lowerBound(hash) return Pair(right.shard, HashRange(left.hash + 1, hash)) } fun searchRemoveBounds(hash: Int, shard: Shard): Pair<Shard, HashRange> { var right = upperBound(hash + 1) while (right.shard == shard) { right = upperBound(right.hash + 1) } var left = lowerBound(hash) while (left.shard == shard) { left = lowerBound(left.hash) } return Pair(right.shard, HashRange(left.hash + 1, hash)) } private fun upperBound(hash: Int): Entry { val right = generalBinary(hash).second if (right == arr.size) { return upperBound(Int.MIN_VALUE) } return arr[right] } private fun lowerBound(hash: Int): Entry { val left = generalBinary(hash).first if (left == -1) { return lowerBound(Int.MAX_VALUE) } return arr[left] } private fun generalBinary(hash: Int): Pair<Int, Int> { var left = -1 var right = arr.size while (left < right - 1) { val mid = (right + left) / 2 if (arr[mid].hash < hash) { left = mid } else { right = mid } } return Pair(left, right) } } data class Entry(val hash: Int, val shard: Shard)
0
Java
0
0
c41dfeb404ce995abdeb18fc93502027e54239ee
2,101
ITMO-university
MIT License
src/main/kotlin/dev/bogwalk/batch9/Problem91.kt
bog-walk
381,459,475
false
null
package dev.bogwalk.batch9 import dev.bogwalk.util.maths.gcd /** * Problem 91: Right Triangles with Integer Coordinates * * https://projecteuler.net/problem=91 * * Goal: Given that 0 <= x_1, y_1, x_2, y_2 <= N, count how many right triangles can be formed that * fulfill the requirements detailed below. * * Constraints: 2 <= N <= 2500 * * A right-angled triangle is formed with a point at origin O (0,0), and 2 others: P (x_1, y_1) and * Q (x_2, y_2). Both points are plotted at integer coordinates. * * e.g.: N = 2 * count = 14 * 4 triangles with right angle at O * 4 triangles with right angle on x-axis * 4 triangles with right angle on y-axis * 2 triangles with right angle internal (along center bisecting line) */ class RightTrianglesIntegerCoordinates { /** * Accumulates count based on a pattern of 5 positions observed for the right-angles: * - at origin (0,0) * - on the x-axis * - on the y-axis * - mirrored on both sides of the line y=x that bisects the [n]x[n] grid along the centre * - mirrored between line y=x and each axis (pattern not yet finalised) * * Note that the line y=x creates right-angled triangles with the following pyramidal sequence * of counts: * 2 -> 1 * 3 -> 1 1 * 4 -> 1 2 1 * 5 -> 1 2 2 1 * 6 -> 1 2 3 2 1 * 7 -> 1 2 3 3 2 1 * 8 -> 1 2 3 4 3 2 1 * The equation used in the code below is Gauss's summation method (provided [n]/2) * multiplied by 4 and then adjusted based on [n]'s parity to mimic this sequence. */ fun countRightTriangles(n: Int): Int { // right angles at origin and on both axes var count = (n * n) * 3 // right angles along centre line y = x count += 2 * (n / 2) * (n / 2) if (n % 2 != 0) count += 2 * (n / 2) // internal right angles between x-axis and centre line y = x for (pX in 2L..1L * n) { for (pY in 1L until pX) { val factor = gcd(pX, pY) val (deltaX, deltaY) = pX / factor to pY / factor // most Q occur to the left of point P var qX = pX - deltaY var qY = pY + deltaX while (qX >= 0 && qY <= n) { count += 2 qX -= deltaY qY += deltaX } // Q occasionally occurs to the right of P qX = pX + deltaY qY = pY - deltaX while (qY >= 0 && qX <= n) { count += 2 qX += deltaY qY -= deltaX } } } return count } }
0
Kotlin
0
0
62b33367e3d1e15f7ea872d151c3512f8c606ce7
2,796
project-euler-kotlin
MIT License
Kotlin/problems/0064_coin_change.kt
oxone-999
243,366,951
true
{"C++": 961697, "Kotlin": 99948, "Java": 17927, "Python": 9476, "Shell": 999, "Makefile": 187}
//Problem statement // You are given coins of different denominations and a total amount of money amount. // Write a function to compute the fewest number of coins that you need to make up that amount. // If that amount of money cannot be made up by any combination of the coins, return -1. class Solution constructor () { fun coinChange(coins: IntArray, amount: Int): Int { coins.sort() var dp:IntArray = IntArray(amount+1) {i->-1} dp[0]=0; for(value in 1..amount){ var index:Int = 0 var minQuantChange:Int = -1 while(index<coins.size && coins[index]<=value){ if(dp[value-coins[index]]!=-1){ if(minQuantChange==-1) minQuantChange = dp[value-coins[index]]+1 else minQuantChange = minOf(minQuantChange,dp[value-coins[index]]+1) } index++ } dp[value]=minQuantChange } return dp.last(); } } fun main(args:Array<String>){ val coins:IntArray = intArrayOf(1,2,5) val target:Int = 11 val sol = Solution() println(sol.coinChange(coins,target)) }
0
null
0
0
52dc527111e7422923a0e25684d8f4837e81a09b
1,205
algorithms
MIT License
src/iii_conventions/MyDate.kt
hotdrop
96,165,435
false
null
package iii_conventions class MyDate(val year: Int, val month: Int, val dayOfMonth: Int): Comparable<MyDate> { override fun compareTo(other: MyDate): Int = if(this.toInt() > other.toInt()) 1 else -1 override fun equals(other: Any?): Boolean = sameDate(other as MyDate) || super.equals(other) private fun sameDate(d: MyDate): Boolean { return (year == d.year) && (month == d.month) && (dayOfMonth == d.dayOfMonth) } private fun toInt(): Int = (year * 10000) + (month * 100) + dayOfMonth } class RepeatedTimeInterval(val timeInterval: TimeInterval, val number: Int) operator fun TimeInterval.times(number: Int) = RepeatedTimeInterval(this, number) operator fun MyDate.rangeTo(other: MyDate): DateRange = DateRange(this, other) operator fun MyDate.plus(timeInterval: TimeInterval): MyDate = this.addTimeIntervals(timeInterval, 1) operator fun MyDate.plus(rti: RepeatedTimeInterval): MyDate = addTimeIntervals(rti.timeInterval, rti.number) enum class TimeInterval { DAY, WEEK, YEAR } class DateRange(val start: MyDate, val endInclusive: MyDate): Iterable<MyDate> { override fun iterator(): Iterator<MyDate> = DateIterator(this) operator fun contains(d: MyDate): Boolean = (start <= d && d <= endInclusive) } class DateIterator(range: DateRange): Iterator<MyDate> { var currentDate = range.start val endDate = range.endInclusive override fun next(): MyDate { val result = currentDate currentDate = currentDate.nextDay() return result } override fun hasNext(): Boolean = (currentDate <= endDate) }
0
Kotlin
0
0
a6959d5758284b48e1135860933912e0bbb5dbe2
1,608
kotlin-koans
MIT License
kotlin/0116-populating-next-right-pointers-in-each-node.kt
neetcode-gh
331,360,188
false
{"JavaScript": 473974, "Kotlin": 418778, "Java": 372274, "C++": 353616, "C": 254169, "Python": 207536, "C#": 188620, "Rust": 155910, "TypeScript": 144641, "Go": 131749, "Swift": 111061, "Ruby": 44099, "Scala": 26287, "Dart": 9750}
// Time complexity O(n) and space complexity O(1) with Follow-up constraints, without using recursion class Solution { fun connect(root: Node?): Node? { var cur = root var next = cur?.left while (cur != null && next != null) { cur?.left?.next = cur?.right if (cur?.next != null) cur?.right?.next = cur?.next?.left cur = cur?.next if (cur == null) { cur = next next = cur?.left } } return root } } // Time complexity O(n) and space complexity O(1) with Follow-up constraints using recursion class Solution { fun connect(root: Node?): Node? { root?: return null root.left?.let { it.next = root.right root.right?.let { it.next = root.next?.left } connect(root.left) connect(root.right) } return root } } // Time complexity O(n) and space complexity O(logn) class Solution { fun connect(root: Node?): Node? { with (LinkedList<Pair<Node?, Int>>()) { addLast(root to 0) while (isNotEmpty()) { repeat (size) { val (curNode, curLevel) = removeFirst() peekFirst()?.let { (nextNode, nextLevel) -> if (nextLevel == curLevel) curNode?.next = nextNode } curNode?.left?.let { addLast(it to (curLevel + 1)) } curNode?.right?.let { addLast(it to (curLevel + 1)) } } } } return root } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
1,711
leetcode
MIT License
src/main/kotlin/com/kishor/kotlin/algo/search/ClimbingLeaderBoard.kt
kishorsutar
276,212,164
false
null
package com.kishor.kotlin.algo.search fun climbingLeaderboard(scores: IntArray, player: IntArray): IntArray? { val scoreSize = scores.size val playerScoresSize = player.size val ranking = IntArray(playerScoresSize) val rank = IntArray(scoreSize) rank[0] = 1 for (i in 1 until scoreSize) { if (scores[i] == scores[i - 1]) { rank[i] = rank[i - 1] } else { rank[i] = rank[i - 1] + 1 } } for (i in 0 until playerScoresSize) { val aliceScore = player[i] if (aliceScore > scores[0]) { ranking[i] = 1 } else if (aliceScore < scores[scoreSize - 1]) { ranking[i] = rank[scoreSize - 1] + 1 } else { val index = binarySearch(scores, aliceScore) ranking[i] = rank[index] } } return ranking } private fun binarySearch(a: IntArray, key: Int): Int { var lo = 0 var hi = a.size - 1 while (lo <= hi) { val mid = lo + (hi - lo) / 2 if (a[mid] == key) { return mid } else if (a[mid] < key && key < a[mid - 1]) { return mid } else if (a[mid] > key && key >= a[mid + 1]) { return mid + 1 } else if (a[mid] < key) { hi = mid - 1 } else if (a[mid] > key) { lo = mid + 1 } } return -1 }
0
Kotlin
0
0
6672d7738b035202ece6f148fde05867f6d4d94c
1,376
DS_Algo_Kotlin
MIT License
kotlin/src/com/daily/algothrim/leetcode/OddEvenList.kt
idisfkj
291,855,545
false
null
package com.daily.algothrim.leetcode /** * 328. 奇偶链表 * * 给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。 * * 请尝试使用原地算法完成。你的算法的空间复杂度应为 O(1),时间复杂度应为 O(nodes),nodes 为节点总数。 * * 示例 1: * * 输入: 1->2->3->4->5->NULL * 输出: 1->3->5->2->4->NULL * 示例 2: * * 输入: 2->1->3->5->6->4->7->NULL * 输出: 2->3->6->7->1->5->4->NULL * */ class OddEvenList { // 输入: 1->2->3->4->5->NULL =>1->3->2->4->5->NULL // 输出: 1->3->5->2->4->NULL companion object { @JvmStatic fun main(args: Array<String>) { OddEvenList().solution( (ListNode(1).apply { next = ListNode(2).apply { next = ListNode(3).apply { next = ListNode(4).apply { next = ListNode(5) } } } }) )?.printAll() } } fun solution(head: ListNode?): ListNode? { var odd = head val firstEven = head?.next // 第一个偶数节点 var endOdd = head // 最后一个奇数节点 // 寻找下一个奇数节点 while (odd?.next != null && odd.next?.next != null) { val curr = odd.next?.next val preCurr = odd.next val nextCurr = curr?.next endOdd?.next = curr endOdd = curr curr?.next = firstEven preCurr?.next = nextCurr odd = preCurr } return head } } class ListNode(var `val`: Int) { var next: ListNode? = null fun printAll() { println("$`val`") var temp = next while (temp != null) { println(temp.`val`) temp = temp.next } } }
0
Kotlin
9
59
9de2b21d3bcd41cd03f0f7dd19136db93824a0fa
2,084
daily_algorithm
Apache License 2.0
2021/src/main/kotlin/de/skyrising/aoc2021/day7/solution.kt
skyrising
317,830,992
false
{"Kotlin": 411565}
package de.skyrising.aoc2021.day7 import de.skyrising.aoc.* import kotlin.math.abs val test = TestInput("16,1,2,0,4,2,7,1,2,14") @PuzzleName("The Treachery of Whales") fun PuzzleInput.part1(): Any { val crabs = chars.trim().split(',').map(String::toInt).sorted() var minFuel = Int.MAX_VALUE for (pos in crabs.first()..crabs.last()) { var fuel = 0 for (c in crabs) { fuel += abs(c - pos) } minFuel = minOf(minFuel, fuel) } return minFuel } fun PuzzleInput.part2(): Any { val crabs = chars.trim().split(',').map(String::toInt).sorted() var minFuel = Int.MAX_VALUE for (pos in crabs.first()..crabs.last()) { var fuel = 0 for (c in crabs) { val dist = abs(c - pos) val cost = (dist * (dist + 1)) / 2 fuel += cost } minFuel = minOf(minFuel, fuel) } return minFuel }
0
Kotlin
0
0
19599c1204f6994226d31bce27d8f01440322f39
917
aoc
MIT License
core-kotlin-modules/core-kotlin-datastructures/src/test/kotlin/com/baeldung/lexicographicalsort/LexicographicalSortUnitTest.kt
Baeldung
260,481,121
false
{"Kotlin": 1476024, "Java": 43013, "HTML": 4883}
package com.baeldung.lexicographicalsort import org.junit.Test import kotlin.test.assertContentEquals class LexicographicalSortUnitTest { @Test fun `sort using sortedWith() method`(){ val words = arrayOf("banana", "apple", "cherry", "date", "A", "Result", "Union") val sortedWords = words.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it }) assertContentEquals(listOf("A", "apple", "banana", "cherry", "date", "Result", "Union"), sortedWords) } @Test fun `sort using sortedBy() method`(){ val words = arrayOf("banana", "apple", "cherry", "date", "A", "Result", "Union") val sortedWords = words.sortedBy { it.lowercase() } assertContentEquals(listOf("A", "apple", "banana", "cherry", "date", "Result", "Union"), sortedWords) } @Test fun `sort using custom method`(){ val words = arrayOf("banana", "apple", "cherry", "date", "A", "Result", "Union") sortWithCustomMethod(words) assertContentEquals(arrayOf("A", "apple", "banana", "cherry", "date", "Result", "Union"), words) } @Test fun `sort using forEachIndexed method`(){ val words = listOf("banana", "apple", "cherry", "date", "A", "Result", "Union") val sortedWords = sortStringsIgnoreCaseForEach(words) assertContentEquals(listOf("A", "apple", "banana", "cherry", "date", "Result", "Union"), sortedWords) } fun sortWithCustomMethod(words: Array<String>){ for (i in 0..words.size - 2) { for (j in i + 1 until words.size) { if (words[i].lowercase() > words[j].lowercase()) { val temp = words[i] words[i] = words[j] words[j] = temp } } } } fun sortStringsIgnoreCaseForEach(words: List<String>): List<String> { val sortedWords = words.toMutableList() sortedWords.forEachIndexed { i, word -> (i until sortedWords.size).forEach { j -> if (word.lowercase().compareTo( sortedWords[j].lowercase()) > 0) { sortedWords[i] = sortedWords[j].also { sortedWords[j] = sortedWords[i] } } } } return sortedWords } }
10
Kotlin
273
410
2b718f002ce5ea1cb09217937dc630ff31757693
2,271
kotlin-tutorials
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinOpToMakeArrayEmpty.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2024 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.ceil /** * 2870. Minimum Number of Operations to Make Array Empty * @see <a href="https://leetcode.com/problems/minimum-number-of-operations-to-make-array-empty">Source</a> */ fun interface MinOpToMakeArrayEmpty { operator fun invoke(nums: IntArray): Int } val minOpToMakeArrayEmptyCounting = MinOpToMakeArrayEmpty { nums -> val counter = mutableMapOf<Int, Int>() for (num in nums) { counter[num] = counter.getOrDefault(num, 0) + 1 } var ans = 0 for ((_, count) in counter) { if (count == 1) { return@MinOpToMakeArrayEmpty -1 } ans += ceil(count.toDouble() / 3).toInt() } return@MinOpToMakeArrayEmpty ans }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,349
kotlab
Apache License 2.0
src/iii_conventions/MyDate.kt
RawToast
98,023,160
false
null
package iii_conventions data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int): Comparable<MyDate> { override fun compareTo(other: MyDate): Int { return if (year < other.year) -1 else if(year > other.year) 1 else if(year >= other.year && month > other.month) 1 else if (month < other.month) -1 else dayOfMonth.compareTo(other.dayOfMonth) } } operator fun MyDate.rangeTo(other: MyDate): DateRange = DateRange(this, other) enum class TimeInterval { DAY, WEEK, YEAR } class DateRange(override val start: MyDate, override val endInclusive: MyDate): Iterable<MyDate>, ClosedRange<MyDate> { override fun iterator(): Iterator<MyDate> = DateIterator(this) class DateIterator(val dateRange: DateRange) : Iterator<MyDate> { var current: MyDate = dateRange.start override fun next(): MyDate { val result = current current = current.nextDay() return result } override fun hasNext(): Boolean = current <= dateRange.endInclusive } override fun contains(d: MyDate): Boolean = (d >= start && d <= endInclusive) } //Add an extension function 'times' to 'TimeInterval', constructing the value of this class. //Add an extension function 'plus' to 'MyDate', taking a 'RepeatedTimeInterval' as an argument. data class RepeatedTimeInterval(val ti: TimeInterval, val n: Int) fun TimeInterval.times(i: Int) = RepeatedTimeInterval(this, i) fun MyDate.plus(rti: RepeatedTimeInterval): MyDate = addTimeIntervals(rti.ti, rti.n)
0
Kotlin
0
0
d8dd239d294545fedfeab8d6bb89d4b261966c0e
1,586
kotlin-koans
MIT License
src/main/kotlin/be/twofold/aoc2021/Day02.kt
jandk
433,510,612
false
{"Kotlin": 10227}
package be.twofold.aoc2021 object Day02 { fun part1(input: List<Pair<String, Int>>): Int { var depth = 0 var position = 0 input.forEach { when (it.first) { "forward" -> position += it.second "down" -> depth += it.second "up" -> depth -= it.second } } return depth * position } fun part2(input: List<Pair<String, Int>>): Int { var aim = 0 var depth = 0 var position = 0 input.forEach { when (it.first) { "forward" -> { position += it.second depth += aim * it.second } "down" -> aim += it.second "up" -> aim -= it.second } } return depth * position } } fun main() { val input = Util.readFile("/day02.txt") .map { s -> s.split(' ').let { it[0] to it[1].toInt() } } println("Part 1: ${Day02.part1(input)}") println("Part 2: ${Day02.part2(input)}") }
0
Kotlin
0
0
2408fb594d6ce7eeb2098bc2e38d8fa2b90f39c3
1,078
aoc2021
MIT License
src/Java/LeetcodeSolutions/src/main/java/leetcode/solutions/concrete/kotlin/Solution_21_Merge_Two_Sorted_Lists.kt
v43d3rm4k4r
515,553,024
false
{"Kotlin": 40113, "Java": 25728}
package leetcode.solutions.concrete.kotlin import leetcode.solutions.LeetcodeSolution import leetcode.solutions.ProblemDifficulty.* import leetcode.solutions.annotations.ProblemInputData import leetcode.solutions.annotations.ProblemSolution import leetcode.solutions.utils.ListNode import leetcode.solutions.utils.createList import leetcode.solutions.validation.SolutionValidator.ASSERT_EQ /** * __Problem:__ You are given the heads of two sorted linked lists `list1` and `list2`. * Merge the two lists into one __sorted__ list. The list should be made by splicing together the nodes of the * first two lists. * * Return _the head of the merged linked list_. * * __Constraints:__ * - The number of nodes in both lists is in the range [[0, 50]] * - `[-100 <= ListNode.val <= 100]` * - Both `list1` and `list2` are sorted in __non-decreasing__ order * * __Solution:__ Create iterators for lists. Compare the values of the elements: if the value of the current iterator * of the first list is less than the value of the iterator of the second list, we add it to the new list. Otherwise, * we add a node from the second list. At the end, you need to add the last node to the list, which is not null, * since it was not added in the loop. * * __Time:__ O(N) * * __Space:__ O(1) * * @author <NAME> */ class Solution_21_Merge_Two_Sorted_Lists : LeetcodeSolution(EASY) { @ProblemSolution(timeComplexity = "O(N)", spaceComplexity = "O(1)") private fun mergeTwoLists(list1: ListNode?, list2: ListNode?): ListNode? { var currentNode1 = list1 var currentNode2 = list2 val result = ListNode(0) var currentResult = result while (currentNode1 != null && currentNode2 != null) { if (currentNode1.`val` < currentNode2.`val`) { currentResult.next = currentNode1 currentNode1 = currentNode1.next } else { currentResult.next = currentNode2 currentNode2 = currentNode2.next } currentResult = currentResult.next!! } currentNode1?.let { currentResult.next = currentNode1 } currentNode2?.let { currentResult.next = currentNode2 } return result.next } @ProblemInputData override fun run() { ASSERT_EQ(createList(1, 1, 2, 3, 4, 4), mergeTwoLists(createList(1, 2, 4), createList(1, 3, 4))) ASSERT_EQ(createList(), mergeTwoLists(createList(), createList())) ASSERT_EQ(createList(0), mergeTwoLists(createList(), createList(0))) } }
0
Kotlin
0
1
c5a7e389c943c85a90594315ff99e4aef87bff65
2,577
LeetcodeSolutions
Apache License 2.0
src/main/kotlin/year2023/Day10.kt
forketyfork
572,832,465
false
{"Kotlin": 142196}
package year2023 import utils.Direction class Day10 { val stepMap = buildMap { put(Direction.DOWN to '|', Direction.DOWN) put(Direction.UP to '|', Direction.UP) put(Direction.LEFT to '-', Direction.LEFT) put(Direction.RIGHT to '-', Direction.RIGHT) put(Direction.DOWN to 'L', Direction.RIGHT) put(Direction.LEFT to 'L', Direction.UP) put(Direction.DOWN to 'J', Direction.LEFT) put(Direction.RIGHT to 'J', Direction.UP) put(Direction.RIGHT to '7', Direction.DOWN) put(Direction.UP to '7', Direction.LEFT) put(Direction.UP to 'F', Direction.RIGHT) put(Direction.LEFT to 'F', Direction.DOWN) } fun part1(input: String): Int { val cells = input.lines().map { it.toCharArray() }.toTypedArray() val sRow = cells.indexOfFirst { it.contains('S') } val sCol = cells[sRow].indexOf('S') var sDirection = if (sRow > 0 && cells[sRow - 1][sCol] in setOf('|', '7', 'F')) { Direction.UP } else if (sCol > 0 && cells[sRow][sCol - 1] in setOf('-', 'F', 'L')) { Direction.LEFT } else if (sCol < cells[sRow].size - 1 && cells[sRow][sCol + 1] in setOf('-', 'J', '7')) { Direction.RIGHT } else { Direction.DOWN } return generateSequence(Triple(sDirection, sRow, sCol)) { (direction, row, col) -> val nextRow = row + direction.dy val nextCol = col + direction.dx if (cells[nextRow][nextCol] == 'S') { null } else { Triple(stepMap[direction to cells[nextRow][nextCol]]!!, nextRow, nextCol) } }.count() / 2 } fun part2(input: String): Int { return 0 } }
0
Kotlin
0
0
5c5e6304b1758e04a119716b8de50a7525668112
1,786
aoc-2022
Apache License 2.0
app/src/main/java/com/klamerek/fantasyrealms/game/Game.kt
NicolaiRuckel
439,810,244
true
{"Kotlin": 203429}
package com.klamerek.fantasyrealms.game import android.content.Context import com.klamerek.fantasyrealms.toInt import com.klamerek.fantasyrealms.util.Constants import com.klamerek.fantasyrealms.util.Preferences import java.lang.Integer.max /** * List of cards (player hand) wth scoring calculation * */ class Game { private val handCards = ArrayList<Card>() private val tableCards = ArrayList<Card>() private val bonusScoreByCard = HashMap<CardDefinition, Int>() private val penaltyScoreByCard = HashMap<CardDefinition, Int>() private val selections = listOf( DoppelgangerSelection(), IslandSelection(), ShapeShifterSelection(), ShapeShifterV2Selection(), MirageSelection(), MirageV2Selection(), AngelSelection(), BookOfChangesSelection() ).map { selection -> selection.source to selection }.toMap() fun cards(): Collection<Card> { return handCards.plus(tableCards) } fun handCards(): Collection<Card> { return ArrayList(handCards) } fun handCardsNotBlanked(): Collection<Card> { return handCards.filter { card -> !card.blanked } } fun add(cardDefinition: CardDefinition) { val list = if (cardDefinition.position() == CardPosition.HAND) handCards else tableCards if (!list.map { card -> card.definition }.contains(cardDefinition)) { list.add(Card(cardDefinition, AllRules.instance[cardDefinition].orEmpty())) } } fun remove(cardDefinition: CardDefinition) { val list = if (cardDefinition.position() == CardPosition.HAND) handCards else tableCards list.removeIf { it.definition == cardDefinition } selections.values.forEach { it.clear(cardDefinition) } } fun update(cardDefinitions: List<CardDefinition>) { cardDefinitions.forEach { definition -> add(definition) } handCards.plus(tableCards).map { card -> card.definition } .filter { definition -> !cardDefinitions.contains(definition) } .forEach { definition -> remove(definition) } } fun clear() { selections.values.forEach { it.clear() } handCards.forEach { it.clear() } handCards.clear() tableCards.clear() } fun countOddHandCards() = handCardsNotBlanked().count { it.isOdd() } fun isAllHandCardsOdd() = handCardsNotBlanked().all { it.isOdd() } fun countHandCards(vararg suit: Suit) = handCardsNotBlanked().count { it.isOneOf(*suit) } fun countHandCardsExcept(suit: Suit, cardDefinition: CardDefinition) = handCardsNotBlanked().filter { it.definition != cardDefinition }.count { it.isOneOf(suit) } fun countTableCards(vararg suit: Suit) = tableCards.count { it.isOneOf(*suit) } fun noHandCardsOf(suit: Suit) = countHandCards(suit) == 0 fun atLeastOneHandCardOf(suit: Suit) = countHandCards(suit) > 0 /** * Remark : this method uses comparison by name to handle when a wild card simulate another card. * * @param cardExpected list of cards expected in the game */ fun containsHandCards(vararg cardExpected: CardDefinition) = handCardsNotBlanked() .map { it.name() }.containsAll(cardExpected.toList().map { it.name() }) fun longestSuite(): Int { val sorted = handCardsNotBlanked().sortedBy { card -> card.value() } var maxCount = 1 var count = 1 var previousValue = Int.MIN_VALUE for (card in sorted) { if (card.value() == (previousValue + 1)) { count += 1 } else if (card.value() != previousValue) { count = 1 } maxCount = max(count, maxCount) previousValue = card.value() } return maxCount } fun largestSuit(): Int { return groupNotBlankedCardsBySuit().map { entry -> entry.value.size }.maxOrNull() ?: 0 } fun calculate() { handCards.forEach { card -> card.clear() } applySpecificCardEffects() handCards.map { card -> identifyClearedRules(card) }.flatten() .forEach { ruleToDeactivate -> handCards.forEach { card -> card.rules() .filter { rule -> rule == ruleToDeactivate } .forEach { rule -> card.deactivate(rule) } } } handCards.map { card -> identifyUnblankableCards(card) }.flatten() .forEach { card -> card.addTemporaryRule(unblankable) } applyBlankingRules() bonusScoreByCard.clear() penaltyScoreByCard.clear() bonusScoreByCard.putAll(cardsForScoring().map { card -> card.definition to card.rules() .asSequence() .filter { rule -> card.isActivated(rule) } .map { rule -> rule as? RuleAboutScore } .filter { rule -> rule?.tags?.contains(Effect.BONUS) ?: false } .map { rule -> rule?.logic?.invoke(this) } .sumOf { any -> if (any is Int) any else 0 } }.toMap()) penaltyScoreByCard.putAll(cardsForScoring().map { card -> card.definition to card.rules() .asSequence() .filter { rule -> card.isActivated(rule) } .map { rule -> rule as? RuleAboutScore } .filter { rule -> rule?.tags?.contains(Effect.PENALTY) ?: false } .map { rule -> rule?.logic?.invoke(this) } .sumOf { any -> if (any is Int) any else 0 } }.toMap()) } private fun applySpecificCardEffects() { selections.values.forEach { it.apply(this) } } fun score(): Int = bonusScoreByCard.entries.sumOf { it.value } + penaltyScoreByCard.entries.sumOf { it.value } + cardsForScoring().sumOf { it.value() } fun score(card: CardDefinition): Int = bonusScore(card) + penaltyScore(card) + cardsForScoring().filter { it.definition == card }.sumOf { it.value() } private fun cardsForScoring() = handCardsNotBlanked().plus(tableCards) fun bonusScore(card: CardDefinition): Int = bonusScoreByCard.getOrDefault(card, 0) fun penaltyScore(card: CardDefinition): Int = penaltyScoreByCard.getOrDefault(card, 0) /** * Sensitive method. Apply BLANK rules on cards<br> * - We apply each BLANK rule by priority order (introduced with Demon card)<br> * - We take attention before applying the rule that the card is still active.<br> * - Some cards are UNBLANKABLE (like Angel).<br> */ private fun applyBlankingRules() { handCards.map { card -> card.rules() .filter { rule -> card.isActivated(rule) } .filter { rule -> rule.tags.contains(Effect.BLANK) } .map { rule -> rule as? RuleAboutCard } .map { rule -> Pair(card, rule) } }.flatten() .sortedByDescending { pair -> pair.second?.priority } .forEach() { applyBlankingRules(it) } } private fun applyBlankingRules(pair: Pair<Card, RuleAboutCard?>) { if (!pair.first.blanked) { pair.second?.logic?.invoke(this) ?.filter { potentialCard -> !potentialCard.rules().contains(unblankable) } .orEmpty().forEach { cardToBlank -> cardToBlank.blanked = true } } } private fun identifyClearedRules(card: Card): List<Rule<out Any>> = card.rules().filter { rule -> card.isActivated(rule) } .filter { rule -> rule.tags.contains(Effect.CLEAR) } .map { rule -> rule as? RuleAboutRule } .flatMap { rule -> rule?.logic?.invoke(this).orEmpty() } private fun identifyUnblankableCards(card: Card): List<Card> = card.rules().filter { rule -> card.isActivated(rule) } .filter { rule -> rule.tags.contains(Effect.UNBLANKABLE) } .map { rule -> rule as? RuleAboutCard } .flatMap { rule -> rule?.logic?.invoke(this).orEmpty() } fun filterNotBlankedHandCards(scope: (Card) -> Boolean): List<Card> { return this.handCardsNotBlanked().filter(scope) } fun identifyClearedPenalty(scope: (Card) -> Boolean): List<Rule<out Any>> { return identifyRule(scope, Effect.PENALTY) } fun identifyArmyClearedPenalty(scope: (Card) -> Boolean): List<Rule<out Any>> { return identifyRule(scope, Effect.PENALTY, Suit.ARMY) } private fun identifyRule(scope: (Card) -> Boolean, vararg tags: Tag): List<Rule<out Any>> { return handCardsNotBlanked().filter(scope) .flatMap { card -> card.rules() } .filter { rule -> rule.tags.containsAll(tags.asList()) } } fun handSizeExpected(context: Context): Int { return Constants.DEFAULT_HAND_SIZE + Preferences.getBuildingsOutsidersUndead(context).toInt() + handCards.any { card -> card.definition == necromancer || card.definition == necromancerV2 }.toInt() + handCards.any { card -> card.definition == genie }.toInt() + handCards.any { card -> card.definition == leprechaun }.toInt() } fun actualHandSize(): Int { return handCards.size } fun ruleEffectCardSelectionAbout(cardDefinition: CardDefinition?): List<CardDefinition> = listOfNotNull(selections[cardDefinition]?.cardSelected) fun ruleEffectSuitSelectionAbout(cardDefinition: CardDefinition?): List<Suit> = listOfNotNull((selections[cardDefinition] as? CardAndSuitSelection)?.suitSelected) fun ruleEffectCandidateAbout(cardDefinition: CardDefinition?): List<CardDefinition> = selections[cardDefinition]?.candidates(this) ?: emptyList() fun ruleEffectSelectionMode(cardDefinition: CardDefinition?): Int = selections[cardDefinition]?.selectionMode() ?: Constants.CARD_LIST_SELECTION_MODE_DEFAULT fun hasManualEffect(definition: CardDefinition): Boolean = selections.keys.contains(definition) fun countCardWithAtLeastOnePenaltyNotCleared(): Int { return handCardsNotBlanked().count { card -> card.rules() .any { rule -> rule.tags.contains(Effect.PENALTY) && card.isActivated(rule) } } } fun groupNotBlankedCardsBySuit(): Map<Suit, List<Card>> { return handCardsNotBlanked().groupBy { card -> card.suit() } } fun applySelection( cardDefinition: CardDefinition?, cardSelected: CardDefinition?, ) { selections[cardDefinition]?.cardSelected = cardSelected } fun applySelection( cardDefinition: CardDefinition?, cardSelected: CardDefinition?, suitSelected: Suit? ) { applySelection(cardDefinition, cardSelected) (selections[cardDefinition] as? CardAndSuitSelection)?.suitSelected = suitSelected } }
0
Kotlin
0
0
345578a6d4be9eb50788be9550ff28b3fd395db9
10,968
fantasy-realm-scoring
MIT License
src/main/kotlin/18/18.kt
Wrent
225,133,563
false
null
fun main() { val underground = mutableMapOf<Coord, Underground>() INPUT18.split("\n") .forEachIndexed { i, row -> row.split("").filter { it != "" }.forEachIndexed { j, cell -> val coord = Coord(i, j) underground[coord] = Underground(coord, undergroundBlock(cell[0]), Int.MAX_VALUE, listOf()) } } underground.values.forEach { val validNeighbours = mutableListOf<Underground>() processNeighbour(it.coord.north(), underground, validNeighbours) processNeighbour(it.coord.south(), underground, validNeighbours) processNeighbour(it.coord.east(), underground, validNeighbours) processNeighbour(it.coord.west(), underground, validNeighbours) it.validNeighbors = validNeighbours } val keyPairs = mutableMapOf<Pair<Coord, Coord>, Pair<Int, MutableSet<Char>>>() val keys = underground.values .filter { it.block is Key || it.block is Entrance } keys.forEach { first -> keys.forEach { second -> if (first !== second) { if (keyPairs[Pair(second.coord, first.coord)] == null) { keyPairs[Pair(first.coord, second.coord)] = getDistanceWithRequiredKeys(first, second) } } } } val entrance = underground.values.first { it.block is Entrance } val pickedKeys = mutableSetOf<Char>('@') val results = mutableListOf<Int>() //// val closedDoors = mutableSetOf<Char>() println("first result") start(entrance, pickedKeys, keyPairs, underground, results, 0) // val current = entrance // // process(current, pickedKeys, underground, 0, results) // println(results.min()) // while (true) { // val keys = findAvailableKeys(current, pickedKeys, mutableSetOf<Coord>(), 0) // keys.forEach { // // move to this key // current = underground[it.first]!! // // pick this key // val pickedKeysCopy = HashSet(pickedKeys) // pickedKeysCopy.add(current.block.char) // // find available keys for this key and do the same // findAvailableKeys(current, pickedKeysCopy, mutableSetOf(), it.second) // } // } // enter(underground, entrance, pickedKeys, closedDoors, 0) // probe(underground, entrance.coord, 0, mutableSetOf()) } fun start(current: Underground, pickedKeys: MutableSet<Char>, keyPairs: MutableMap<Pair<Coord, Coord>, Pair<Int, MutableSet<Char>>>, underground: MutableMap<Coord, Underground>, results: MutableList<Int>, steps: Int) { val availableKeys = keyPairs .filter { it.key.first == current.coord || it.key.second == current.coord } .filter { pickedKeys.containsAll(it.value.second) } .filter { val next = if (it.key.first == current.coord) { underground[it.key.second]!! } else { underground[it.key.first]!! } !pickedKeys.contains(next.block.char) } // .entries.toList() // .sortedBy { it.value.first } // .take(3) println(availableKeys) availableKeys.forEach lambda@{ // move to this key val next = if (it.key.first == current.coord) { underground[it.key.second]!! } else { underground[it.key.first]!! } if (pickedKeys.contains(next.block.char)) { return@lambda } val distance = keyPairs[it.key]!!.first val min = results.min() ?: 2974 println("${steps + distance} $next $pickedKeys $min") if (steps + distance >= min) { return@lambda } // pick this key val pickedKeysCopy = HashSet(pickedKeys) pickedKeysCopy.add(next.block.char) //check results if (!underground.hasKeys(pickedKeysCopy)) { // println("adding ${it.second}") results.add(steps + distance) return@lambda } // find available keys for this key and do the same start(next, pickedKeysCopy, keyPairs, underground, results, steps + distance) } } val cache = mutableMapOf<Coord, MutableMap<Set<Char>, List<Pair<Coord, Int>>>>() fun process(current: Underground, pickedKeys: MutableSet<Char>, underground: MutableMap<Coord, Underground>, steps: Int, results: MutableList<Int>) { val keys = cache[current.coord]?.get(pickedKeys.toSortedSet())?.apply { println("cache hit") } ?: run { val tmp = findAvailableKeys(current, pickedKeys, mutableSetOf(), 0) cache.putIfAbsent(current.coord, mutableMapOf()) cache[currentCoord]?.put(pickedKeys.toSortedSet(), tmp) tmp } // println(keys) // println(current) val minA = results.min() ?: Int.MAX_VALUE if (steps >= minA) { return } keys.forEach { // move to this key val next = underground[it.first]!! val min = results.min() ?: Int.MAX_VALUE println("${steps + it.second} $next $pickedKeys $min") if (pickedKeys.contains(next.block.char) || steps + it.second >= min) { return } // pick this key val pickedKeysCopy = HashSet(pickedKeys) pickedKeysCopy.add(next.block.char) //check results if (!underground.hasKeys(pickedKeysCopy)) { // println("adding ${it.second}") results.add(steps + it.second) return } // cache.putIfAbsent(next.coord, mutableMapOf()) // cache[next.coord]!![pickedKeysCopy] = it.second // find available keys for this key and do the same process(next, pickedKeysCopy, underground, steps + it.second, results) } // println("exiting") } fun getDistanceWithRequiredKeys(first: Underground, second: Underground): Pair<Int, MutableSet<Char>> { val requiredKeys = mutableSetOf<Char>() val visited = mutableSetOf<Coord>() return find(first, second, requiredKeys, visited, 0) .minBy { it.first }!! } fun find(current: Underground, second: Underground, requiredKeys: MutableSet<Char>, visited: MutableSet<Coord>, steps: Int): List<Pair<Int, MutableSet<Char>>> { if (current == second) { return listOf(Pair(steps, requiredKeys)) } val newKeys = HashSet(requiredKeys) if (current.block is Door) { newKeys.add(current.block.key()) } visited.add(current.coord) return current.validNeighbors .filter { !visited.contains(it.coord) } .flatMap { find(it, second, newKeys, visited, steps + 1) } } fun findAvailableKeys(current: Underground, pickedKeys: MutableSet<Char>, visited: MutableSet<Coord>, steps: Int): List<Pair<Coord, Int>> { val resultList = mutableListOf<Pair<Coord, Int>>() if (current.block is Key && !pickedKeys.contains(current.block.char)) { resultList.add(Pair(current.coord, steps)) } visited.add(current.coord) val list = current.validNeighbors .filter { !visited.contains(it.coord) } .filter { canBeOpened(it, pickedKeys) } .flatMap { findAvailableKeys(it, pickedKeys, HashSet(visited), steps + 1) } + resultList return list.shuffled() } fun canBeOpened(it: Underground, pickedKeys: MutableSet<Char>): Boolean { return when (it.block) { is Door -> return pickedKeys.contains(it.block.key()) else -> true } } //fun enter(underground: MutableMap<Coord, Underground>, block: Underground, pickedKeys: MutableSet<Char>, closedDoors: MutableSet<Char>, steps: Int) { // if (!underground.hasKeys()) { // throw RuntimeException("${steps - 1}") // } // block.validNeighbors // .filter { it.block is Door && !pickedKeys.contains(it.block.key()) } // .forEach { closedDoors.add(it.block.char) } // block.steps = steps // block.validNeighbors.forEach { // if (it.steps < steps && closedDoors.isEmpty()) { // return // } // if (it.block is Door) { // if (!pickedKeys.contains(it.block.key())) { // return // } else { // underground[it.coord] = Underground(it.coord, Empty(), block.steps, it.validNeighbors) // pickedKeys.remove(it.block.key()) // } // } // if (it.block is Key) { // pickedKeys.add(block.block.char) // underground[it.coord] = Underground(it.coord, Empty(), block.steps, it.validNeighbors) // } // enter(underground, it, HashSet(pickedKeys), HashSet(closedDoors), steps + 1) // } //} fun processNeighbour(coord: Coord, underground: MutableMap<Coord, Underground>, validNeighbors: MutableList<Underground>) { val block = underground[coord] ?: return when (block.block) { is Wall -> return } validNeighbors.add(block) } //fun probe(underground: MutableMap<Coord, Underground>, coord: Coord, steps: Int, pickedKeys: MutableSet<Char>, unopenedDoors: MutableSet<Char>, seenCoords: MutableSet<Coord>) { // val block = underground[coord]!! // // if (seenCoords.contains(coord) && unopenedDoors.isEmpty()) { // return // } // // seenCoords.add(coord) // when (block.block) { // is Wall -> return // is Empty -> { // } // is Entrance -> { // } // is Key -> { // pickedKeys.add(block.block.char) // underground[coord] = Underground(coord, Empty(), block.steps) // } // is Door -> { // if (pickedKeys.contains(block.block.key())) { // underground[coord] = Underground(coord, Empty(), block.steps) // pickedKeys.remove(block.block.key()) // } else { // // return // } // } // } // if (!underground.hasKeys()) { // println(steps) // return // } // // block.steps = steps // probe(underground, coord.north(), steps + 1, HashSet(pickedKeys)) // probe(underground, coord.south(), steps + 1, HashSet(pickedKeys)) // probe(underground, coord.west(), steps + 1, HashSet(pickedKeys)) // probe(underground, coord.east(), steps + 1, HashSet(pickedKeys)) //} private fun MutableMap<Coord, Underground>.hasKeys(): Boolean { return this.values.filter { it.block is Key }.count() > 0 } private fun MutableMap<Coord, Underground>.hasKeys(pickedKeys: MutableSet<Char>): Boolean { return !pickedKeys.containsAll(this.values.filter { it.block is Key }.map { it.block.char }.toSet()) } data class Underground(val coord: Coord, val block: UndergroundBlock, var steps: Int, var validNeighbors: List<Underground>) { override fun toString(): String { return "Underground(coord=$coord, block=$block)" } } fun undergroundBlock(char: Char): UndergroundBlock { return when (char) { '#' -> Wall() '.' -> Empty() '@' -> Entrance() else -> { if (char.toUpperCase() == char) { Door(char) } else { Key(char) } } } } sealed class UndergroundBlock(val char: Char) class Wall : UndergroundBlock('#') class Empty : UndergroundBlock('.') class Entrance : UndergroundBlock('@') class Door(char: Char) : UndergroundBlock(char) { fun key(): Char = this.char.toLowerCase() } class Key(char: Char) : UndergroundBlock(char) { fun door(): Char = this.char.toUpperCase() override fun toString(): String { return "Key($char)" } } const val TEST181 = """######### #b.A.@.a# #########""" const val TEST182 = """######################## #f.D.E.e.C.b.A.@.a.B.c.# ######################.# #d.....................# ########################""" const val TEST183 = """######################## #...............b.C.D.f# #.###################### #.....@.a.B.c.d.A.e.F.g# ########################""" const val TEST184 = """################# #i.G..c...e..H.p# ########.######## #j.A..b...f..D.o# ########@######## #k.E..a...g..B.n# ########.######## #l.F..d...h..C.m# #################""" const val TEST185 = """######################## #@..............ac.GI.b# ###d#e#f################ ###A#B#C################ ###g#h#i################ ########################""" const val INPUT18 = """################################################################################# #.#...#.........#i........U.........#...#.........#.......#.............#.....E.# #.#.#.#.###.###Q#########.#########I#X#####.#####.#####.#.#.#######.###.#.#####.# #...#..u..#...#.#.........#l#...D.#.#...#...#...#.......#.#.#.......#.#.#.#...#.# #############.#.#.#########.#.###.#.###.#.###.#.#.#######.###.#######.#.#.#B#.#.# #...A.......#.#...#.#.....#...#...#...#.#.#.#.#...#...#......p#.......#.#.#.#.#.# #.#########.#.#####.#.#.#S#.###.#####.#.#.#.#.#####.#.#########.###.###.###.#.#.# #.#.........#...#...#.#.#.#...#.....#.#.#.#...#.#...#.......#.....#.#...#...#...# #.#########.#.#.###.#.#.#####.###.#.#.#.#.#.###.#.#########.#####.#.#.###.#####.# #.#.......#.#q#...#...#.#.....#.#.#.#...#.#.....#.#.....#.#.K.#...#.......#...#.# #.#.#####.#.#.###W#####.#.#####.#.#.###.#.#######.###.#.#.###.#.###########.#.#.# #...#...#.#y#...#.....#.#...L...#.#d#...#.....#...#...#.....#.#.#...#...#...#...# #####.#.#.#.#########.#.#######.#.###.#######.#.###.#########.###.#.#.#.#.####### #.....#...#.#.........#.N.....#n#...#x#.#.....#.#.....#.......#...#.#.#.#f#..o..# #.#########.#.#########.###.###.###.#.#.#.###.#.#.###.#.#######.###.#.###.#.###.# #...#.#.....#...#.....#.#.#...#.#.#.....#..t#.#.#...#.#...#...#...#.#.#...#...#.# ###O#.#.#####.#.#.#.###.#.###.#.#.#####.###.###.#####.###.#.#.#.###.#.#.#####.#.# #...#...#.....#.#.#.#..s#...#.....#..v#.#...#...........#.#.#...#...#.......#.#.# #.###.#########.#.#.#.###.#.#####.#.#.###.###.###########.#.#####.#########.###.# #.#..g..........#.#.......#.#...#.#.#...#.#...#.#.......#.......#.#...#.....#...# #.#.#############.#########.#.#.###.###.#.#.###.#.#####.#.#######.#.#.#.#####.#.# #.#.#...........#.#.#.#....z#.#.....#...#.#.....#...#.#.#.#.#...#.#.#.#.#.....#.# #.###.#########.#.#.#.#######.#######.###.#####.###.#.#.#.#.###.#.#.#.#.#####.#.# #.....#...#.....#...#.........#.....#...#.....#...#...#.#.....#.#...#.#.#.....#.# #.#####.#.#.#######.###########.#######.#.#######.###.#.###.###.#####.#.#.#####.# #.....#.#.#...#.Z.#.#....j..#.........#.#...#.......#.#.#...#...#.....#.#.#...#.# #######.#.###.#.###.#.#####.#.#####.###.#.#.#.#######.#.#####.###.#####.#.###.#.# #.......#.#...#.....#.#...#.#...#.#.....#.#.#.#.#.....#...#...#...#.....#...#.#.# #.#######.#.#.#####.#.###.#.###.#.#######.#.#.#.#.#######.#.###.#.###.#####.#.#.# #.#.#.....#.#.#...#.#...#.#...#...#.#...#.#...#.#.....#.#...#...#...#.......#...# #.#.#.#####.#.#.#.#####.#.###.###.#.#.#.#.#####.#####.#.#####.#####.#########.### #.#...#.....#.#.#.#...#...#.#.#...#...#.#.#...#.....#...#.#...#...#.....#...#.#.# #.###.###.#.###.#.#.#.###.#.#.#.#######.#.#.#.#####.###.#.#.###.#.#####.###.#.#.# #...#...#.#.#...#.#.#...#.#.#.#.#.......#...#.........#.#...#...#.#...#...#.#...# #.#.###.#.#.#.###.#.###.#.#.#.#.###.###.###########.###.#.###.###.###.###.#.###.# #.#...#.#.#.#...#...#...#.#.#.#.....#...#...#.....#.#...#.....#.....#.#...#..h#.# #.###.#.#.#####.#####.#.#.#.#.#######.###.#.#####.#.#.#############.#.#.###.#.#.# #...#.#.F.#...#.....#.#.#.#.#.#...#...#.#.#.......#.#.#...#...#...#...#.#.#.#...# ###.#.#####.#.#####.#.###.#.#.#.#.#.###.#.#########.#.#.#.#.#.#.#.#####.#.#.##### #...#.......#.......#.......#...#..................r#...#...#...#.......#.......# #######################################.@.####################################### #...........#.............#.#.....#...........#...........#...#.....#.....#.....# #########.#.#.###########.#.#.#.###.#.#.#.#.###.#####.#####.#.#####.#.###.#.#.### #...#.....#.#...#.......#.#.#.#.....#.#.#.#.....#.....#.....#.#...#....w#...#...# #.#.#.#####.###.#####.#.#.#.#.#####.#.###.#######.###.#.#####.#.#.#####.#######.# #.#.H.#...#...#.#...#.#.#.#...#...#.#...#.#.....#.#...#.....#...#...#...#.....#.# #.#.###.#.#####.#.#.#.###.#.###.#.###.#.#.###.#.#.#####.#######.###.#####.###.#.# #.#.#...#.......#.#...#...#.#...#...#.#.#...#.#.#.......#.....#.#...#.....#.#a#.# #.#.#.###########.#####.###R#.#####.###.###.###.#########.###.#.#.###.#####.#.#.# #.#.#.#.....#.....#...#.#...#.#...#...#.#.#...#.....#.....#...#.#.#.......#...#.# #.#.#.#.###.#.#.###.#.#.#####.#.#####.#.#.###.#.#.#.#.#####.#####.#.#####.#.###.# #.#.#.#...#...#.....#.#...#...#.....#...#.#...#.#.#.#.#...........#.#.....#...#.# #.#.#.###.###########.###.#.###.###.###.#.#.###.#.###.#############.#.#######.#Y# #.#.#.#.#.#.........#...#.#...#.#.#...#.#.#...#.#.#...#...#.#.....#.#.....#...#.# #.#.#.#.#.#########.#.###.###.#.#.#.#.#.#.###.###.#.###.#.#.#.#.###.#####.#.###.# #.#.#.#...#.........#.........#...#.#.#.#...#.....#.....#.#...#.........#.#.#...# #.###.#.###.#.#######.###########.#.###.#.#######.#######.#.#############.#.#.#.# #...#.#.#...#.#.....#.#.....#...J.#.....#...#...#...#.....#.#...#...#.....#...#.# ###.#.#.###.#.#.###.###.###.#.###########.#.#.#.###.#.#####.#.#.###.#.#########.# #...#.#.....#.#...#.....#...#.#...#.....#.#.#.#.....#.#.......#.....#.....#.....# #.###.###.#######.#######.###.#.###.#.#####.#.#######.###.#########.#####.#.##### #...#.#.#.#.......#.#.....#.#.#.....#...#.V.#.....#.#...#...#.#...#...#...#.....# ###.#.#.#.#.#######.#######.#.#########.#.#######.#.###.###.#.#.#####.#.#######.# #...#.#...#.#.......#.......#.......#...#.......#.#...#...#.#.#...#...#.#...#...# #.###.#####.#.#####.#.#.###.#######.#.#.#.#.###.#.#.#.###.###.###.#.###.#.#G#.### #...#.....#...#...#.#.#.#.#.#.....#...#.#.#.#...#.#.#b..#...#...#.#.#c..#.#.....# #.#.#####.#####.#.#.#.#.#.#.###.#######.#.#.#####.#####.###.###.#.#.#.########### #.#.C...#.......#...#.#.#.......#...#...#.#.#...#.#.....#.#.#...#...#...#......m# #.#####.#############.#.###.#####.#.#.###.#.#.#T#.#.###.#.#.#.#####.###.#.#####.# #...#.#.......#.....#.#...#.#.....#...#.#.#.#.#...#.#...#.#.#.....#...#.....#...# ###.#.#####.###.#.#.#.###.#.#.#########.#.#.#.#####.#.###.#.#####.###.#######.#.# #.#...#...#.#...#.#.#.#...#.#.....#.....#.#...#.....#.#...#.....#.#...#.#...#.#.# #.###.#.###M#.###.###.#.#########.###.#.#.#####.#.###.#.#.#.#####.###.#.#.#.#.#.# #.....#...#...#...#...#...#.......#...#.#.#...#.#...#.#.#.#.....#...#...#.#...#.# #.#######.#####.#.#.#####.#.#######.###.#.#.#.#####.#.#.#######.###.#####.#####.# #.#.........#...#.#.#.#...#.#.......#...#k#.#.......#.#.....#...#...#.....#.....# #.#.#######.#.###.#.#.#.###.###.#####.###.#.#########.#####.#.###.###.#####.##### #...#...#...#...#.#...#...#...#...#.#.#.#...#.#.....#.#e....#.....#...#...#.#...# #####.#.#.#####.#####.###P###.###.#.#.#.#####.#.#.###.#.###.#######.###.###.#.#.# #.....#.......#.........#.........#.....#.......#.......#...........#.........#.# #################################################################################"""
0
Kotlin
0
0
0a783ed8b137c31cd0ce2e56e451c6777465af5d
18,997
advent-of-code-2019
MIT License
Kotlinlang/src/examples/longerExamples/Maze.kt
why168
118,225,102
false
null
package examples.longerExamples import java.util.* /** * Let's Walk Through a Maze. * * Imagine there is a maze whose walls are the big 'O' letters. * Now, I stand where a big 'I' stands and some cool prize lies * somewhere marked with a '$' sign. Like this: * * OOOOOOOOOOOOOOOOO * O O * O$ O O * OOOOO O * O O * O OOOOOOOOOOOOOO * O O I O * O O * OOOOOOOOOOOOOOOOO * * I want to get the prize, and this program helps me do so as soon * as I possibly can by finding a shortest path through the maze. * * @author Edwin.Wu * @version 2018/2/3 下午7:10 * @since JDK1.8 */ /** * Declare a point class. */ data class Point(val i: Int, val j: Int) /** * This function looks for a path from max.start to maze.end through * free space (a path does not go through walls). One can move only * straight up, down, left or right, no diagonal moves allowed. */ fun findPath(maze: Maze): List<Point>? { val previous = hashMapOf<Point, Point>() val queue = LinkedList<Point>() val visited = hashSetOf<Point>() queue.offer(maze.start) visited.add(maze.start) while (!queue.isEmpty()) { val cell = queue.poll() if (cell == maze.end) break for (newCell in maze.neighbors(cell.i, cell.j)) { if (newCell in visited) continue previous.put(newCell, cell) queue.offer(newCell) visited.add(cell) } } if (previous[maze.end] == null) return null val path = arrayListOf<Point>() var current = previous[maze.end]!! while (current != maze.start) { path.add(0, current) current = previous[current]!! } return path } /** * Find neighbors of the (i, j) cell that are not walls */ fun Maze.neighbors(i: Int, j: Int): List<Point> { val result = arrayListOf<Point>() addIfFree(i - 1, j, result) addIfFree(i, j - 1, result) addIfFree(i + 1, j, result) addIfFree(i, j + 1, result) return result } fun Maze.addIfFree(i: Int, j: Int, result: MutableList<Point>) { if (i !in 0..height - 1) return if (j !in 0..width - 1) return if (walls[i][j]) return result.add(Point(i, j)) } /** * A data class that represents a maze */ class Maze( // Number or columns val width: Int, // Number of rows val height: Int, // true for a wall, false for free space val walls: Array<BooleanArray>, // The starting point (must not be a wall) val start: Point, // The target point (must not be a wall) val end: Point ) { } /** A few maze examples here */ fun main(args: Array<String>) { walkThroughMaze("I $") walkThroughMaze("I O $") walkThroughMaze(""" O $ O O O O I """) walkThroughMaze(""" OOOOOOOOOOO O $ O OOOOOOO OOO O O OOOOO OOOOO O O O OOOOOOOOO O OO OOOOOO IO """) walkThroughMaze(""" OOOOOOOOOOOOOOOOO O O O$ O O OOOOO O O O O OOOOOOOOOOOOOO O O I O O O OOOOOOOOOOOOOOOOO """) } // UTILITIES fun walkThroughMaze(str: String) { val maze = makeMaze(str) println("Maze:") val path = findPath(maze) for (i in 0..maze.height - 1) { for (j in 0..maze.width - 1) { val cell = Point(i, j) print( if (maze.walls[i][j]) "O" else if (cell == maze.start) "I" else if (cell == maze.end) "$" else if (path != null && path.contains(cell)) "~" else " " ) } println("") } println("Result: " + if (path == null) "No path" else "Path found") println("") } /** * A maze is encoded in the string s: the big 'O' letters are walls. * I stand where a big 'I' stands and the prize is marked with * a '$' sign. * * Example: * * OOOOOOOOOOOOOOOOO * O O * O$ O O * OOOOO O * O O * O OOOOOOOOOOOOOO * O O I O * O O * OOOOOOOOOOOOOOOOO */ fun makeMaze(s: String): Maze { val lines = s.split('\n') val longestLine = lines.toList().maxBy { it.length } ?: "" val data = Array(lines.size) { BooleanArray(longestLine.length) } var start: Point? = null var end: Point? = null for (line in lines.indices) { for (x in lines[line].indices) { val c = lines[line][x] when (c) { 'O' -> data[line][x] = true 'I' -> start = Point(line, x) '$' -> end = Point(line, x) } } } return Maze(longestLine.length, lines.size, data, start ?: throw IllegalArgumentException("No starting point in the maze (should be indicated with 'I')"), end ?: throw IllegalArgumentException("No goal point in the maze (should be indicated with a '$' sign)")) }
0
Kotlin
1
4
c642d97a605ef09355b86c39c1c522e3181d65e2
5,167
JavaProjects
Apache License 2.0
src/test/kotlin/amb/aoc2020/day2.kt
andreasmuellerbluemlein
318,221,589
false
null
package amb.aoc2020 import org.junit.jupiter.api.Test class Day2 : TestBase() { class Tree( val branches: String ) class Panda( val name: Char, val favouriteBranch1: Int, val favouriteBranch2: Int, ) class Input( val tree: Tree, val panda: Panda ) @Test fun findPandasInBambooForest() { var foundPandasOnTheirFavouriteBranchesInForest = 0 for (treesAndPandas in exploreBambooForest()) { val tree = treesAndPandas.tree val panda = treesAndPandas.panda val pandaSitsOnFavouriteBranch1 = tree.branches.length >= panda.favouriteBranch1 && tree.branches[panda.favouriteBranch1 - 1] == panda.name val pandaSitsOnFavouriteBranch2 = tree.branches.length >= panda.favouriteBranch2 && tree.branches[panda.favouriteBranch2 - 1] == panda.name if (pandaSitsOnFavouriteBranch1.xor(pandaSitsOnFavouriteBranch2)) foundPandasOnTheirFavouriteBranchesInForest++ } logger.info { "Congratulation, you found $foundPandasOnTheirFavouriteBranchesInForest Pandas in the Forest" } } private fun readInput(): List<Input> { return getTestData("input2").map { line -> var regex = """(\d+)-(\d+) (\w): (\w*)""".toRegex() var match = regex.find(line) if (match != null) { val (min, max, char, pw) = match!!.destructured Input(Tree( pw ),Panda(char.first(),min.toInt(),max.toInt())) } else { null } }.filterNotNull() } private fun exploreBambooForest(): List<Input> { return readInput() } }
1
Kotlin
0
0
dad1fa57c2b11bf05a51e5fa183775206cf055cf
1,814
aoc2020
MIT License
src/exercises/Day01.kt
Njko
572,917,534
false
{"Kotlin": 53729}
// ktlint-disable filename package exercises import readInput import kotlin.math.max fun main() { fun part1(input: List<String>, excluding: List<Int> = emptyList()): Int { var weight = 0 var maxWeight = 0 input.forEach { line -> if (line.isNotEmpty()) { // last empty line in original input was ignored weight += line.toInt() } else { if (!excluding.contains(weight) && max(weight, maxWeight) == weight) { maxWeight = weight } weight = 0 } } return maxWeight } fun part2(input: List<String>): Int { val firstMaxWeight = part1(input) val secondMaxWeight = part1(input, listOf(firstMaxWeight)) val thirdMaxWeight = part1(input, listOf(firstMaxWeight, secondMaxWeight)) return firstMaxWeight + secondMaxWeight + thirdMaxWeight } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") println("Test results:") println(part1(testInput)) check(part1(testInput) == 24000) println(part2(testInput)) check(part2(testInput) == 45000) val input = readInput("Day01") println("Final results:") println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
68d0c8d0bcfb81c183786dfd7e02e6745024e396
1,338
advent-of-code-2022
Apache License 2.0
src/main/kotlin/Models.kt
akunowski
166,451,736
false
{"Kotlin": 6214}
import kotlin.math.roundToInt data class Gene(val x: Int, val y: Int) { companion object { fun fitnessScore(g1: Gene, g2: Gene): Int { val xSq = Math.pow((g1.x - g2.x).toDouble(), 2.0) val ySq = Math.pow((g1.y - g2.y).toDouble(), 2.0) return Math.sqrt(Math.abs(xSq + ySq)).roundToInt() } } } class Individual(val chromosome: List<Gene>) { var score: Int = 0 get() { if (field != 0) { return field } field = fitnessScore() return field } private fun fitnessScore(): Int { var score = 0 (0 until this.chromosome.lastIndex).forEach { geneIndex -> score += Gene.fitnessScore(chromosome[geneIndex], chromosome[geneIndex.inc()]) } score += Gene.fitnessScore(chromosome.first(), chromosome.last()) return score } override fun toString(): String { return score.toString() } } class Population(private val individuals: MutableList<Individual>) { fun selectParent(): Pair<Individual, Individual> { individuals.sortBy { it.score } return Pair(individuals[0], individuals[1]) } fun populationSize() = individuals.size }
0
Kotlin
0
0
2aaecdf83840dba48ab11b5c0245e81d29d6c0c4
1,268
tsp_genetic
MIT License
src/main/kotlin/day16.kt
Gitvert
725,292,325
false
{"Kotlin": 97000}
import kotlin.math.max fun day16 (lines: List<String>) { val beams = if (lines[0][0] == '\\') { mutableListOf(Beam(0, 0, 0, 1)) } else { mutableListOf(Beam(0, 0, 1, 0)) } val part1 = findVisitedPositions(lines, beams, Pos(0, 0)) println("Day 16 part 1: $part1") val part2 = max(max(max(enterFromLeft(lines), enterFromRight(lines)), enterFromTop(lines)), enterFromBottom(lines)) println("Day 16 part 2: $part2") println() } fun enterFromLeft(lines: List<String>): Int { var highestVisited = Int.MIN_VALUE for (y in lines.indices) { val beams = mutableListOf<Beam>() when (lines[y][0]) { '\\' -> beams.add(Beam(0, y, 0, 1)) '/' -> beams.add(Beam(0, y, 0, -1)) '|' -> { beams.add(Beam(0, y, 0, 1)) beams.add(Beam(0, y, 0, -1)) } else -> beams.add(Beam(0, y, 1, 0)) } val visited = findVisitedPositions(lines, beams, Pos(0, y)) if (visited > highestVisited) { highestVisited = visited } } return highestVisited } fun enterFromRight(lines: List<String>): Int { var highestVisited = Int.MIN_VALUE for (y in lines.indices) { val beams = mutableListOf<Beam>() when (lines[y][lines[0].indices.last]) { '\\' -> beams.add(Beam(lines[0].indices.last, y, 0, -1)) '/' -> beams.add(Beam(lines[0].indices.last, y, 0, 1)) '|' -> { beams.add(Beam(lines[0].indices.last, y, 0, 1)) beams.add(Beam(lines[0].indices.last, y, 0, -1)) } else -> beams.add(Beam(lines[0].indices.last, y, -1, 0)) } val visited = findVisitedPositions(lines, beams, Pos(lines[0].indices.last, y)) if (visited > highestVisited) { highestVisited = visited } } return highestVisited } fun enterFromTop(lines: List<String>): Int { var highestVisited = Int.MIN_VALUE for (x in lines[0].indices) { val beams = mutableListOf<Beam>() when (lines[0][x]) { '\\' -> beams.add(Beam(x, 0, 1, 0)) '/' -> beams.add(Beam(x, 0, -1, 0)) '-' -> { beams.add(Beam(x, 0, 1, 0)) beams.add(Beam(x, 0, -1, 0)) } else -> beams.add(Beam(x, 0, 0, 1)) } val visited = findVisitedPositions(lines, beams, Pos(x, 0)) if (visited > highestVisited) { highestVisited = visited } } return highestVisited } fun enterFromBottom(lines: List<String>): Int { var highestVisited = Int.MIN_VALUE for (x in lines[0].indices) { val beams = mutableListOf<Beam>() when (lines[lines.indices.last][x]) { '\\' -> beams.add(Beam(x, lines.indices.last, -1, 0)) '/' -> beams.add(Beam(x, lines.indices.last, 1, 0)) '-' -> { beams.add(Beam(x, lines.indices.last, 1, 0)) beams.add(Beam(x, lines.indices.last, -1, 0)) } else -> beams.add(Beam(x, lines.indices.last, 0, -1)) } val visited = findVisitedPositions(lines, beams, Pos(x, lines.indices.last)) if (visited > highestVisited) { highestVisited = visited } } return highestVisited } fun findVisitedPositions(lines: List<String>, beams: MutableList<Beam>, startPos: Pos): Int { val visitedPositions = mutableSetOf(startPos) var stepsWithoutNewVisitedPositions = 0 while (stepsWithoutNewVisitedPositions < 10) { val visitedBefore = visitedPositions.size step(lines, beams, visitedPositions) val visitedAfter = visitedPositions.size if (visitedBefore == visitedAfter) { stepsWithoutNewVisitedPositions++ } else { stepsWithoutNewVisitedPositions = 0 } } return visitedPositions.filter { it.x >= 0 && it.y >= 0 && it.x < lines[0].length && it.y < lines.size }.size } fun step(lines: List<String>, beams: MutableList<Beam>, visitedPositions: MutableSet<Pos>) { val newBeams = mutableListOf<Beam>() val removedBeams = mutableListOf<Beam>() beams.forEach { it.xPos += it.xDir it.yPos += it.yDir if (stillInContraption(it, lines)) { val cell = lines[it.yPos][it.xPos] when (cell) { '.' -> {} '\\' -> { if (it.xDir == 1) { it.xDir = 0 it.yDir = 1 } else if (it.xDir == -1) { it.xDir = 0 it.yDir = -1 } else if (it.yDir == 1) { it.yDir = 0 it.xDir = 1 } else if (it.yDir == -1) { it.yDir = 0 it.xDir = -1 } } '/' -> { if (it.xDir == 1) { it.xDir = 0 it.yDir = -1 } else if (it.xDir == -1) { it.xDir = 0 it.yDir = 1 } else if (it.yDir == 1) { it.yDir = 0 it.xDir = -1 } else if (it.yDir == -1) { it.yDir = 0 it.xDir = 1 } } '-' -> { if (it.xDir == 0) { it.yDir = 0 it.xDir = 1 newBeams.add(Beam(it.xPos, it.yPos, -1, 0)) } } '|' -> { if (it.yDir == 0) { it.xDir = 0 it.yDir = 1 newBeams.add(Beam(it.xPos, it.yPos, 0, -1)) } } } } else { removedBeams.add(it) } } beams.removeAll(removedBeams) beams.addAll(newBeams.filter { !beams.contains(it) }) beams.forEach { visitedPositions.add(Pos(it.xPos, it.yPos)) } } fun stillInContraption(beam: Beam, lines: List<String>): Boolean { val xRange = lines[0].indices val yRange = lines.indices return xRange.contains(beam.xPos) && yRange.contains(beam.yPos) } data class Beam(var xPos: Int, var yPos: Int, var xDir: Int, var yDir: Int)
0
Kotlin
0
0
f204f09c94528f5cd83ce0149a254c4b0ca3bc91
6,619
advent_of_code_2023
MIT License
src/cn/ancono/math/discrete/Graphs.kt
140378476
105,762,795
false
{"Java": 1912158, "Kotlin": 1243514}
package cn.ancono.math.discrete import java.lang.Double.min import java.util.* //Created by lyc at 2021-03-15 interface GraphBuilder<G> { infix fun Int.to(y: Int): Int fun build(): G } /** * Builds an undirected graph. */ fun buildGraph(n: Int, builderAction: GraphBuilder<UndirectedGraph>.() -> Unit): UndirectedGraph { val builder = MatrixUndirectedGraphBuilder(n) builderAction(builder) return builder.build() } enum class VisitState { UNDISCOVERED, VISITING, VISITED } open class SearchResult( val source: Node, val target: Node, val visitStates: Array<VisitState>, val parents: IntArray ) { /** * Gets the path from the source to the target basing on this search result. * Caller should check `targetReached` first to ensure such a path do exist. */ fun getPath(): List<Node> { return Graphs.buildPath(source, target, parents) } val targetReached: Boolean get() = visitStates[target] == VisitState.VISITED } /** * A (prioritized) work bag for general priority search. */ interface WorkBag { fun init(start: Node) /** * Adds the node `y` to the working bag with priority computed according to the * current edge `x-y`. * */ fun add(x: Node, y: Node) /** * Returns and removes the item with lowest priority. */ fun pop(): Node /** * Updates the priority of node `y` according to priority computed according to the * current edge `x-y`. * * @return `true` if the new priority is lower than */ fun update(x: Node, y: Node): Boolean fun isEmpty(): Boolean } class StackWorkBag : WorkBag { private val stack: Queue<Int> = Collections.asLifoQueue(ArrayDeque()) override fun init(start: Node) { stack.offer(start) } override fun add(x: Node, y: Node) { stack.offer(y) } override fun pop(): Node { return stack.poll() } override fun update(x: Node, y: Node): Boolean { return false } override fun isEmpty(): Boolean { return stack.isEmpty() } } class QueueWorkBag : WorkBag { private val queue: Queue<Int> = ArrayDeque() override fun init(start: Node) { queue.offer(start) } override fun add(x: Node, y: Node) { queue.offer(y) } override fun pop(): Node { return queue.poll() } override fun update(x: Node, y: Node): Boolean { return false } override fun isEmpty(): Boolean { return queue.isEmpty() } } class PriorityQueueWorkBag( graph: Graph, private val weight: (Node, Node) -> Double = { _, _ -> 1.0 }, private val heuristic: (Node) -> Double = { 0.0 } ) : WorkBag { private val distances = DoubleArray(graph.n) { Double.POSITIVE_INFINITY } private val pq = PriorityQueue<Pair<Node, Double>>(compareBy { it.second }) override fun init(start: Node) { distances[start] = 0.0 pq.add(start to 0.0) } override fun add(x: Node, y: Node) { val w = distances[x] + weight(x, y) + heuristic(y) pq.add(y to w) distances[y] = w } override fun pop(): Node { return pq.remove().first } override fun update(x: Node, y: Node): Boolean { val w = distances[x] + weight(x, y) + heuristic(y) return if (w < distances[y]) { pq.remove(y to distances[y]) pq.add(y to w) distances[y] true } else { false } } override fun isEmpty(): Boolean { return pq.isEmpty() } } class CollectiveWorkBag(val bag: WorkBag) : WorkBag { val visited = hashSetOf<Node>() override fun init(start: Node) { bag.init(start) visited.add(start) } override fun add(x: Node, y: Node) { bag.add(x, y) visited.add(y) } override fun pop(): Node { return bag.pop() } override fun update(x: Node, y: Node): Boolean { return bag.update(x, y) } override fun isEmpty(): Boolean { return bag.isEmpty() } } /** * Provides methods related to graphs. */ object Graphs { /** * Creates an undirected graph from an adjacent matrix. */ fun fromAdjMatrix(matrix: Array<IntArray>): UndirectedGraph { val n = matrix.size require(matrix.all { it.size == n }) for (i in 0 until n) { for (j in 0 until n) { require(matrix[i, j] == 0 || matrix[i, j] == 1) } } return UndirectedGraphInMatrix(matrix) } /** * Returns a copy of the given graph in matrix representation. */ fun toMatrixRep(graph: UndirectedGraph): UndirectedGraph { return UndirectedGraphInMatrix(graph.adjacentMatrix()) } /** * Gets the complete graph `K_n`. */ fun completeGraph(n: Int): UndirectedGraph { require(n > 0) val mat = Array(n) { IntArray(n) { 1 } } for (i in 0 until n) { mat[i][i] = 0 } return fromAdjMatrix(mat) } fun shortestPath(graph: GraphWithData<*, out Number>, src: Node, dest: Node): Pair<Double, List<Node>>? { return shortestPath(graph, src, dest) { i, j -> graph.getEdge(i, j)?.toDouble() ?: Double.POSITIVE_INFINITY } } internal fun buildPath(src: Node, target: Node, prev: IntArray): List<Node> { val path = arrayListOf<Int>() var x = target while (x != src) { path.add(x) x = prev[x] } return path.reversed() } /** * Finds the shortest path from source `src` to destination `dest`, using the given edge weight function `weight`. * * @return a pair of minimal cost and a list of nodes indicating the path. */ fun shortestPath(graph: Graph, src: Node, dest: Node, weight: (Node, Node) -> Double): Pair<Double, List<Node>>? { // use Dijkstra algorithm val n = graph.n val prev = IntArray(n) { -1 } // val dist = DoubleArray(n) { Double.POSITIVE_INFINITY } // dist[src] = 0.0 val queue = PriorityQueue<Triple<Int, Int, Double>>(compareBy { it.third }) val state = Array(n) { VisitState.UNDISCOVERED } queue.add(Triple(src, -1, 0.0)) var cost = Double.POSITIVE_INFINITY while (queue.isNotEmpty()) { val (x, from, d) = queue.remove() if (state[x] == VisitState.VISITED) { continue } state[x] = VisitState.VISITED prev[x] = from if (x == dest) { cost = d break } for (y in graph.nodesOut(x)) { if (state[y] == VisitState.VISITED) { continue } val w = weight(x, y) queue.add(Triple(y, x, w + d)) } } if (prev[dest] < 0) { return null } val path = buildPath(src, dest, prev) return cost to path } /** * The most general version of priority search, the method starts from the given starting node and * visits the nodes in the graph according to the order given by the prioritized work bag. * This method will not visit the explored nodes that are marked by [state]. * * @param target the searching target, it can be set to `-1` if the method should fully explore the graph. * @param bag an instance of WorkBag, it must be empty and ready for use. * @param state the visit state of each node in the graph, explored nodes should be set to `VISITED`. * @param prev the ancestor for each node, which will be computed. The value should be set to be `-1` for * unexplored nodes. */ fun generalPrioritySearch( graph: Graph, start: Node, target: Node, bag: WorkBag, state: Array<VisitState>, prev: IntArray, ): SearchResult { bag.init(start) outer@ while (!bag.isEmpty()) { val x = bag.pop() state[x] = VisitState.VISITED if (x == target) { break } for (y in graph.nodesOut(x)) { when (state[y]) { VisitState.VISITED -> continue VisitState.UNDISCOVERED -> { state[y] = VisitState.VISITING bag.add(x, y) prev[y] = x } VisitState.VISITING -> { if (bag.update(x, y)) { prev[y] = x } } } } } return SearchResult(start, target, state, prev) } /** * A general version of priority search, the method starts from the given starting node and * visits the nodes in the graph according to the order given by the prioritized work bag. */ fun generalPrioritySearch( graph: Graph, start: Node, dest: Node, bag: WorkBag ): SearchResult { val n = graph.n val state = Array(n) { VisitState.UNDISCOVERED } val prev = IntArray(n) { -1 } return generalPrioritySearch(graph, start, dest, bag, state, prev) } /** * Performs deep-first search on the given graph with the given starting node. * * @param target the target to search for, it can be `-1` to let the algorithm go over the whole connected component. */ fun dfs(graph: Graph, start: Node, target: Node): SearchResult { return generalPrioritySearch( graph, start, target, StackWorkBag() ) } /** * Performs breath-first search on the given graph with the given starting node. * * @param target the target to search for, it can be `-1` to let the algorithm go over the whole connected component. */ fun bfs(graph: Graph, start: Node, target: Node): SearchResult { return generalPrioritySearch( graph, start, target, QueueWorkBag() ) } /** * Performs uniform cost search on the given graph with the given starting node and the given edge weight. * * @param target the target to search for, it can be `-1` to let the algorithm go over the whole connected component. */ fun ucs(graph: Graph, start: Node, target: Node, weight: (Node, Node) -> Double): SearchResult { return generalPrioritySearch( graph, start, target, PriorityQueueWorkBag(graph, weight) ) } /** * The A* search algorithm. * * @param weight the non-negative weight of each edge * @param heuristic the heuristic function, it must be consistent */ fun aStarSearch( graph: Graph, start: Int, dest: Int, weight: (Int, Int) -> Double, heuristic: (Int) -> Double ): SearchResult { return generalPrioritySearch( graph, start, dest, PriorityQueueWorkBag(graph, weight, heuristic) ) } /** * Computes the pairwise shortest path for the given graph. This method provides time complexity of * `O(n^3)`. */ fun pairwiseShortestPath(graph: Graph, weight: (Node, Node) -> Double): Array<DoubleArray> { val dists = Array(graph.n) { DoubleArray(graph.n) { Double.MAX_VALUE } } for (i in graph.nodes) { dists[i][i] = 0.0 for (j in graph.nodesOut(i)) { dists[i][j] = weight(i, j) } } for (k in graph.nodes) { for (i in graph.nodes) { for (j in graph.nodes) { dists[i][j] = min(dists[i][j], dists[i][k] + dists[k][j]) } } } return dists } //TODO: Euler cycle }
0
Java
0
6
02c2984c10a95fcf60adcb510b4bf111c3a773bc
12,046
Ancono
MIT License
kotlin/674.Longest Continuous Increasing Subsequence(最长连续递增序列).kt
learningtheory
141,790,045
false
{"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944}
/** <p> Given an unsorted array of integers, find the length of longest <code>continuous</code> increasing subsequence (subarray). </p> <p><b>Example 1:</b><br /> <pre> <b>Input:</b> [1,3,5,4,7] <b>Output:</b> 3 <b>Explanation:</b> The longest continuous increasing subsequence is [1,3,5], its length is 3. Even though [1,3,5,7] is also an increasing subsequence, it's not a continuous one where 5 and 7 are separated by 4. </pre> </p> <p><b>Example 2:</b><br /> <pre> <b>Input:</b> [2,2,2,2,2] <b>Output:</b> 1 <b>Explanation:</b> The longest continuous increasing subsequence is [2], its length is 1. </pre> </p> <p><b>Note:</b> Length of the array will not exceed 10,000. </p><p>给定一个未经排序的整数数组,找到最长且<strong>连续</strong>的的递增序列。</p> <p><strong>示例 1:</strong></p> <pre> <strong>输入:</strong> [1,3,5,4,7] <strong>输出:</strong> 3 <strong>解释:</strong> 最长连续递增序列是 [1,3,5], 长度为3。 尽管 [1,3,5,7] 也是升序的子序列, 但它不是连续的,因为5和7在原数组里被4隔开。 </pre> <p><strong>示例 2:</strong></p> <pre> <strong>输入:</strong> [2,2,2,2,2] <strong>输出:</strong> 1 <strong>解释:</strong> 最长连续递增序列是 [2], 长度为1。 </pre> <p><strong>注意:</strong>数组长度不会超过10000。</p> <p>给定一个未经排序的整数数组,找到最长且<strong>连续</strong>的的递增序列。</p> <p><strong>示例 1:</strong></p> <pre> <strong>输入:</strong> [1,3,5,4,7] <strong>输出:</strong> 3 <strong>解释:</strong> 最长连续递增序列是 [1,3,5], 长度为3。 尽管 [1,3,5,7] 也是升序的子序列, 但它不是连续的,因为5和7在原数组里被4隔开。 </pre> <p><strong>示例 2:</strong></p> <pre> <strong>输入:</strong> [2,2,2,2,2] <strong>输出:</strong> 1 <strong>解释:</strong> 最长连续递增序列是 [2], 长度为1。 </pre> <p><strong>注意:</strong>数组长度不会超过10000。</p> **/ class Solution { fun findLengthOfLCIS(nums: IntArray): Int { } }
0
Python
1
3
6731e128be0fd3c0bdfe885c1a409ac54b929597
2,088
leetcode
MIT License
14.kts
pin2t
725,922,444
false
{"Kotlin": 48856, "Go": 48364, "Shell": 54}
val platform = System.`in`.bufferedReader().lines().map { it.toCharArray() }.toList() fun north() { for (c in 0..<platform[0].size) { for (r in 0..<platform.size) { if (platform[r][c] == 'O') { platform[r][c] = '.' var i = r - 1; while (i >= 0 && platform[i][c] == '.') i-- platform[i + 1][c] = 'O' } } } } fun west() { for (r in 0..<platform.size) { for (c in 0..<platform[0].size) { if (platform[r][c] == 'O') { platform[r][c] = '.' var i = c - 1; while (i >= 0 && platform[r][i] == '.') i-- platform[r][i + 1] = 'O' } } } } fun south() { for (c in 0..<platform[0].size) { for (r in (platform.size-1) downTo 0) { if (platform[r][c] == 'O') { platform[r][c] = '.' var i = r + 1; while (i < platform.size && platform[i][c] == '.') i++ platform[i - 1][c] = 'O' } } } } fun east() { for (r in 0..<platform.size) { for (c in (platform[0].size - 1) downTo 0) { if (platform[r][c] == 'O') { platform[r][c] = '.' var i = c + 1; while (i < platform[0].size && platform[r][i] == '.') i++ platform[r][i - 1] = 'O' } } } } fun state(): List<Int> { val result = ArrayList<Int>() platform.forEachIndexed { row, chars -> chars.forEachIndexed { col, c -> if (c == 'O') result.add(platform.size - row) } } return result } north() var load1 = state().sum() var cycle: Long = 0 val states = HashMap<List<Int>, Long>() while (cycle < 1000000000) { north(); west(); south(); east() cycle++ val s = state() if (states.contains(s)) { val len = cycle - states[s]!! while (cycle < 1000000000 - len) cycle += len states.clear() } else { states[s] = cycle } } println(listOf(load1, state().sum()))
0
Kotlin
1
0
7575ab03cdadcd581acabd0b603a6f999119bbb6
2,025
aoc2023
MIT License
src/net/sheltem/aoc/y2022/Day09.kt
jtheegarten
572,901,679
false
{"Kotlin": 178521}
package net.sheltem.aoc.y2022 import kotlin.math.absoluteValue suspend fun main() { Day09().run() } class Day09 : Day<Int>(88, 36) { override suspend fun part1(input: List<String>): Int = input.toInstructions().moveMatrix(2).flatMap { it.toList() }.filter { it != 0 }.size override suspend fun part2(input: List<String>): Int = input.toInstructions().moveMatrix(10).flatMap { it.toList() }.filter { it != 0 }.size private fun List<String>.moveMatrix(pieces: Int): Array<IntArray> { val ropeList = List(pieces) { Rope(500, 500) } val moveMatrix = Array(1000) { IntArray(1000) } moveMatrix[500][500] = 1 val iterator = this.iterator() while (iterator.hasNext()) { val start = ropeList[0] when (iterator.next()) { "R" -> start.x++ "L" -> start.x-- "U" -> start.y++ "D" -> start.y-- } var moved = true var position = 0 while (moved && position < pieces - 1) { val head = ropeList[position] val tail = ropeList[position + 1] position++ if (tail.needsToMove(head)) { tail.moveAdjacent(head) } else { moved = false } } if (position == pieces - 1 && moved) { ropeList[pieces - 1].let { moveMatrix[it.x][it.y]++ } } } return moveMatrix } } private fun List<String>.toInstructions() = map { it.split(" ") }.flatMap { (dir, rep) -> List(rep.toInt()) { dir } } private class Rope(var x: Int, var y: Int) { fun needsToMove(other: Rope) = distance(other) > 2 || (distance(other) > 1 && (x == other.x || y == other.y)) fun distance(other: Rope) = (x - other.x).absoluteValue + (y - other.y).absoluteValue fun moveAdjacent(other: Rope) { y = when { other.y > y -> y + 1 other.y < y -> y - 1 else -> y } x = when { other.x > x -> x + 1 other.x < x -> x - 1 else -> x } } }
0
Kotlin
0
0
ac280f156c284c23565fba5810483dd1cd8a931f
2,189
aoc
Apache License 2.0
src/main/kotlin/g0001_0100/s0098_validate_binary_search_tree/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0001_0100.s0098_validate_binary_search_tree // #Medium #Top_100_Liked_Questions #Top_Interview_Questions #Depth_First_Search #Tree #Binary_Tree // #Binary_Search_Tree #Data_Structure_I_Day_14_Tree #Level_1_Day_8_Binary_Search_Tree // #Udemy_Tree_Stack_Queue #Big_O_Time_O(N)_Space_O(log(N)) // #2023_07_10_Time_190_ms_(61.62%)_Space_37.6_MB_(48.48%) import com_github_leetcode.TreeNode /* * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { fun isValidBST(root: TreeNode?): Boolean { return solve(root, Long.MIN_VALUE, Long.MAX_VALUE) } // we will send a valid range and check whether the root lies in the range // and update the range for the subtrees private fun solve(root: TreeNode?, left: Long, right: Long): Boolean { if (root == null) { return true } return if (root.`val` <= left || root.`val` >= right) { false } else solve(root.left, left, root.`val`.toLong()) && solve(root.right, root.`val`.toLong(), right) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,198
LeetCode-in-Kotlin
MIT License
core-bandit/src/main/kotlin/org/rsultan/bandit/algorithms/BanditAlgorithm.kt
remisultan
241,215,006
false
{"Jupyter Notebook": 26270, "Kotlin": 9773}
package org.rsultan.bandit.algorithms import java.security.SecureRandom interface BanditAlgorithm { fun selectArm(): Int fun update(chosenArm: Int, reward: Float) } abstract class AbstractBanditAlgorithm(nbArms: Int) : BanditAlgorithm { protected val random = SecureRandom() protected val counts = (1..nbArms).map { 0 }.toTypedArray() protected val values = (1..nbArms).map { 0.0f }.toTypedArray() override fun update(chosenArm: Int, reward: Float) { val armCount = ++counts[chosenArm] val armValue = values[chosenArm] values[chosenArm] = ((armCount - 1) / armCount.toFloat()) * armValue + (1 / armCount.toFloat()) * reward } } abstract class AbstractSoftmaxAlgorithm(nbArms: Int) : AbstractBanditAlgorithm(nbArms) { fun categoricalDraw(probabilities: List<Float>): Int { val rand = random.nextFloat() var cumulativeProbability = 0.0f for (i in probabilities.indices) { cumulativeProbability += probabilities[i] if (cumulativeProbability > rand) { return i } } return probabilities.lastIndex } }
2
Jupyter Notebook
0
0
ead934d89e552d2daa1b8dc63e63d68fcc2610c4
1,158
multiarm-bandit-algorithm-kotlin
Do What The F*ck You Want To Public License
src/Day01.kt
kprow
573,685,824
false
{"Kotlin": 23005}
fun main() { var maxCalories = 0 var currentCalories = 0 var caloriesPerElf = arrayOf<Int>() fun part1(input: List<String>): Int { for (cal in input) { if (cal == "") { if (currentCalories > maxCalories) { maxCalories = currentCalories } caloriesPerElf += currentCalories currentCalories = 0 } else { currentCalories += cal.toInt() } } caloriesPerElf += currentCalories return maxCalories } fun part2(input: List<String>): Int { caloriesPerElf.sort() return caloriesPerElf.takeLast(3).sum() } val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
9a1f48d2a49aeac71fa948656ae8c0a32862334c
880
AdventOfCode2022
Apache License 2.0
kotlin-math/src/main/kotlin/com/baeldung/math/checkfibonacci/Fibonacci.kt
Baeldung
260,481,121
false
{"Kotlin": 1476024, "Java": 43013, "HTML": 4883}
package com.baeldung.math.checkfibonacci var currentLimit = 0 var currentFibonacciHashSet: HashSet<Int> = hashSetOf(0, 1) fun checkIfFibonacciUsingIteration(n: Int): Boolean { var first = 0 var second = 1 while (first < n) { val temp = first first = second second = temp + second } return n == first } fun isPerfectSquare(x: Int): Boolean { val s = Math.sqrt(x.toDouble()).toInt() return s * s == x } fun checkIfFibonacciUsingPerfectSquareProperty(n: Int): Boolean { return isPerfectSquare(5 * n * n + 4) || isPerfectSquare(5 * n * n - 4) } fun getNthFibonacci(n: Int, cache: HashMap<Int, Int>): Int { if (n == 0) return 0 if (n == 1) return 1 cache[n]?.let { return it } val result = getNthFibonacci(n - 1, cache) + getNthFibonacci(n - 2, cache) cache[n] = result return result } fun checkIfFibonacciUsingRecursion(num: Int): Boolean { var n = 0 var cache: HashMap<Int, Int> = HashMap<Int, Int>() while (getNthFibonacci(n, cache) <= num) { if (getNthFibonacci(n, cache) == num) return true n++ } return false } fun generateFibonacciNumberHashSet(limit: Int): HashSet<Int> { val fibonacciNumberSet = HashSet<Int>() var first = 0 var second = 1 while (first <= limit) { fibonacciNumberSet.add(first) val temp = first first = second second = temp + second } return fibonacciNumberSet } fun checkIfFibonacciUsingHashSet(n: Int): Boolean { if (n > currentLimit) { currentFibonacciHashSet.addAll(generateFibonacciNumberHashSet(n)) currentLimit = n } return currentFibonacciHashSet.contains(n) }
10
Kotlin
273
410
2b718f002ce5ea1cb09217937dc630ff31757693
1,711
kotlin-tutorials
MIT License
leetcode-75-kotlin/src/main/kotlin/ReverseVowelsOfAString.kt
Codextor
751,507,040
false
{"Kotlin": 49566}
/** * Given a string s, reverse only all the vowels in the string and return it. * * The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more than once. * * * * Example 1: * * Input: s = "hello" * Output: "holle" * Example 2: * * Input: s = "leetcode" * Output: "leotcede" * * * Constraints: * * 1 <= s.length <= 3 * 10^5 * s consist of printable ASCII characters. * @see <a href="https://leetcode.com/problems/reverse-vowels-of-a-string/">LeetCode</a> */ fun reverseVowels(s: String): String { val stringAsArray = s.toCharArray() val setOfVowels = hashSetOf<Char>('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U') var startPointer = 0 var endPointer = stringAsArray.lastIndex while (startPointer < endPointer) { while (startPointer <= stringAsArray.lastIndex && !setOfVowels.contains(stringAsArray[startPointer])) { startPointer++ } while (endPointer >= 0 && !setOfVowels.contains(stringAsArray[endPointer])) { endPointer-- } if (startPointer < endPointer) { val temp = stringAsArray[startPointer] stringAsArray[startPointer] = stringAsArray[endPointer] stringAsArray[endPointer] = temp startPointer++ endPointer-- } } return stringAsArray.concatToString() }
0
Kotlin
0
0
0511a831aeee96e1bed3b18550be87a9110c36cb
1,385
leetcode-75
Apache License 2.0
year2021/day06/lanternfish/src/main/kotlin/com/curtislb/adventofcode/year2021/day06/lanternfish/School.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
package com.curtislb.adventofcode.year2021.day06.lanternfish import com.curtislb.adventofcode.common.collection.Counter /** * A school of lanternfish, which create more fish over time according to a population growth model. * * @param initialTimers The internal reproduction timer (in days) of each lanternfish. * @param cycleDays The number of days required for a mature lanternfish to create a new fish. * @param maturationDays The number of days required for a new lanternfish to become mature. * * @throws IllegalArgumentException If any timer in `initialTimers` is negative. */ class School(initialTimers: List<Int>, cycleDays: Int, maturationDays: Int) { /** * The value (in days) to which a fish's internal timer should be set after creating a new fish. */ private val oldTimerStart: Int = cycleDays - 1 /** * The value (in days) to which a newly created fish's internal timer should be set. */ private val newTimerStart: Int = oldTimerStart + maturationDays /** * An upper bound on the current internal timer for any fish. */ private var timerMax: Int = newTimerStart /** * A counter of the current number of fish for each internal timer value. */ private val fishCounts: Counter<Int> = Counter() init { for (timer in initialTimers) { require(timer >= 0) { "Timer starting value must be non-negative: $timer" } timerMax = maxOf(timerMax, timer) fishCounts[timer]++ } } /** * Returns the current number of fish with the given internal [timer] value. */ operator fun get(timer: Int): Long = fishCounts[timer] /** * Returns the current total number of fish. */ fun countFish(): Long = fishCounts.entries.sumOf { (_, count) -> count } /** * Simulates population growth for [dayCount] days, starting from the current state. * * Each day, lanternfish population growth is simulated as follows: * * - A fish with a timer of 0 updates its timer to [oldTimerStart] and creates one new fish with * a timer of [newTimerStart]. * - A fish with a timer of any other value decreases its timer by 1. */ fun update(dayCount: Int = 1) { repeat(dayCount) { // Decrement timer counts, keeping track of new fish val newFishCount = fishCounts[0] for (timer in 0..timerMax) { fishCounts[timer] = fishCounts[timer + 1] } // Check if the upper bound for timer values can be reduced if (timerMax > newTimerStart) { timerMax-- } // Add new fish and update all parents' timers fishCounts[oldTimerStart] += newFishCount fishCounts[newTimerStart] += newFishCount } } }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
2,857
AdventOfCode
MIT License
src/main/kotlin/easy/merge-sorted-array.kt
shevtsiv
286,838,200
false
null
package easy class MergeSortedArraySolution { /** * Time Complexity: O(n) * Space Complexity: O(1) */ fun mergeUsingThreePointers(nums1: IntArray, m: Int, nums2: IntArray, n: Int) { var i = m - 1 var j = n - 1 var endPointer = m + n - 1 while (i >= 0 && j >= 0) { if (nums1[i] > nums2[j]) { nums1[endPointer--] = nums1[i--] } else { nums1[endPointer--] = nums2[j--] } } while (j >= 0) { nums1[endPointer--] = nums2[j--] } } /** * Time Complexity: O((n^2)log(n)) * Space Complexity: O(1) */ fun mergeUsingBinarySearch(nums1: IntArray, mInitial: Int, nums2: IntArray, _n: Int) { var m = mInitial - 1 for (x in nums2) { insertIntoAt(x, nums1, findInsertPosition(nums1, m++, x)) } } /** * Time Complexity: O(log(n)) * Space Complexity: O(1) */ private fun findInsertPosition(array: IntArray, size: Int, element: Int): Int { var lo = 0 var hi = size while (lo <= hi) { val mid = (lo + hi) / 2 when { array[mid] == element -> { return mid } array[mid] < element -> { lo = mid + 1 } else -> { hi = mid - 1 } } } return lo } /** * Time Complexity: O(n) * Space Complexity: O(1) */ private fun insertIntoAt(element: Int, array: IntArray, position: Int) { for (i in array.size - 1 downTo position + 1) { array[i] = array[i - 1] } array[position] = element } }
0
Kotlin
0
0
95d5f74069098beddf2aee14465f069302a51b77
1,803
leet
MIT License
src/main/kotlin/com/leetcode/P539.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package com.leetcode // https://github.com/antop-dev/algorithm/issues/514 class P539 { fun findMinDifference(timePoints: List<String>): Int { // 문자열을 분으로 변경 val times = mutableListOf<Int>() for (s in timePoints) { val time = time(s) times += time // 다음날 시간 if (time < 13 * 60) times += (24 * 60) + time } // 오름차순 정렬 times.sort() // 가장 작은 시간 차이 구하기 var minDiff = 24 * 60 for (i in 1 until times.size) { val diff = times[i] - times[i - 1] if (diff < minDiff) minDiff = diff } return minDiff } /** * time string to int */ private fun time(s: String) = s.split(":") .map { it.toInt() } .let { val (hh, mm) = it (hh * 60) + mm } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
953
algorithm
MIT License
src/Day08.kt
IvanChadin
576,061,081
false
{"Kotlin": 26282}
import kotlin.math.max fun main() { val inputName = "Day08" val a = readInput(inputName).map { s -> s.map { it.digitToInt() } } fun calc1(i: Int, j: Int): Int { var res = 1 for (ii in i + 1 until a.size) { if (a[ii][j] >= a[i][j]) { res = 0 break } } if (res == 1) return 1 res = 1 for (ii in i - 1 downTo 0) { if (a[ii][j] >= a[i][j]) { res = 0 break } } if (res == 1) return 1 res = 1 for (jj in j + 1 until a[i].size) { if (a[i][jj] >= a[i][j]) { res = 0 break } } if (res == 1) return 1 res = 1 for (jj in j - 1 downTo 0) { if (a[i][jj] >= a[i][j]) { res = 0 break } } return res } fun part1(a: List<List<Int>>): Int { var ans = 0 for (i in a.indices) { for (j in a[i].indices) { ans += calc1(i, j) } } return ans } fun calc2(i: Int, j: Int): Int { var res = 1 var cur = 0 for (ii in i + 1 until a.size) { cur++ if (a[ii][j] >= a[i][j]) { break } } res *= cur cur = 0 for (ii in i - 1 downTo 0) { cur++ if (a[ii][j] >= a[i][j]) { break } } res *= cur cur = 0 for (jj in j + 1 until a[i].size) { cur++ if (a[i][jj] >= a[i][j]) { break } } res *= cur cur = 0 for (jj in j - 1 downTo 0) { cur++ if (a[i][jj] >= a[i][j]) { break } } res *= cur return res } fun part2(a: List<List<Int>>): Int { var maxx = -1 for (i in a.indices) { for (j in a[i].indices) { maxx = max(maxx, calc2(i, j)) } } return maxx } check(part1(a) == 21) check(part2(a) == 8) }
0
Kotlin
0
0
2241437e6c3a20de70306a0cb37b6fe2ed8f9e3a
2,251
aoc-2022
Apache License 2.0
plugins/evaluation-plugin/core/src/com/intellij/cce/metric/LatencyMetrics.kt
jbakermalone
267,440,120
true
null
package com.intellij.cce.metric import com.intellij.cce.core.Lookup import com.intellij.cce.core.Session import com.intellij.cce.metric.util.Bootstrap abstract class LatencyMetric(override val name: String) : Metric { private val sample = mutableListOf<Double>() override val value: Double get() = compute(sample) override fun confidenceInterval(): Pair<Double, Double>? = Bootstrap.computeInterval(sample) { compute(it) } override fun evaluate(sessions: List<Session>, comparator: SuggestionsComparator): Double { val fileSample = mutableListOf<Double>() sessions .flatMap { session -> session.lookups } .filter(::shouldInclude) .forEach { this.sample.add(it.latency.toDouble()) fileSample.add(it.latency.toDouble()) } return compute(fileSample) } abstract fun compute(sample: List<Double>): Double open fun shouldInclude(lookup: Lookup) = true } class MaxLatencyMetric : LatencyMetric(NAME) { override val valueType = MetricValueType.INT override fun compute(sample: List<Double>): Double = sample.maxOrNull() ?: Double.NaN companion object { const val NAME = "Max Latency" } } class TotalLatencyMetric : LatencyMetric(NAME) { override val valueType = MetricValueType.DOUBLE override val showByDefault = false override fun compute(sample: List<Double>): Double = sample.sum() companion object { const val NAME = "Total Latency" } } class MeanLatencyMetric(private val filterZeroes: Boolean = false) : LatencyMetric(NAME) { override val valueType = MetricValueType.DOUBLE override fun compute(sample: List<Double>): Double = sample.average() override fun shouldInclude(lookup: Lookup) = if (filterZeroes) lookup.latency > 0 else true companion object { const val NAME = "Mean Latency" } }
0
null
0
0
08c3a7658b320448efdbdfa75692c8449ee975bd
1,816
intellij-community
Apache License 2.0
src/main/kotlin/com/sk/leetcode/kotlin/122. Best Time to Buy and Sell Stock II.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package com.sk.leetcode.kotlin class Solution122 { /** * Consider each greater element compared to previous and keep accumulating delta profit. */ fun maxProfit(prices: IntArray): Int { var res = 0 for (i in 1 until prices.size) { if (prices[i] > prices[i - 1]) { res += (prices[i] - prices[i - 1]) } } return res } /** * Traverse from left to right, find every peak followed by valley, and * book profit. Keep accumulating the profit and return it. */ fun maxProfit2(prices: IntArray): Int { var valley = 0 var peak = 0 var profit = 0 var i = 0 while (i < prices.size - 1) { // going down till we find a valley while (i < prices.size - 1 && prices[i + 1] <= prices[i]) i++ valley = prices[i] // going up till we find a peak while (i < prices.size - 1 && prices[i + 1] >= prices[i]) i++ peak = prices[i] // time to book profit profit += peak - valley } return profit } }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
1,151
leetcode-kotlin
Apache License 2.0
src/main/java/io/github/lunarwatcher/aoc/day9/Day9.kt
LunarWatcher
160,042,659
false
null
package io.github.lunarwatcher.aoc.day9 import io.github.lunarwatcher.aoc.commons.CircleDeque import io.github.lunarwatcher.aoc.commons.readFile /* Rules: - Marbles start at 0 - Increase by 1 until all have a value > 0 - Lowest-numbered marble is replaced between 1 and 2-marbles - Exception on first turn. - Eventually it adds between the current marble and the one that was just placed) - 23 adds to the score - Also removes the marble that's 7 marbles counter-clockwise from the current marble - The current marble is the recently placed one. */ private fun parseInput(raw: List<String>) : Pair<Int, Long> = raw.first() .split(" ") .filter { it.toLongOrNull() != null } .let { it[0].toInt() to it[1].toLong() } private fun unifiedProcessor(raw: List<String>, part2: Boolean) : Long { val data = parseInput(raw); val players = data.first val highestValue = (data.second + 1) * if(part2) 100 else 1 val circle = CircleDeque(0L) val scores = Array(players) { 0L } for(marbleValue in 1..highestValue){ if(marbleValue % 23 == 0L){ circle.rotate(-7) // marbleValue % players makes it wrap around. scores[(marbleValue % players).toInt()] += marbleValue + circle.pop() }else { circle.rotate(2) circle.addLast(marbleValue) } } return scores.sortedDescending().first() } fun day9part1processor(raw: List<String>) = unifiedProcessor(raw, false) fun day9part2processor(raw: List<String>) = unifiedProcessor(raw, true) fun day9(part: Boolean){ val data = readFile("day9.txt"); val res = if(!part) day9part1processor(data) else day9part2processor(data) println(res); }
0
Kotlin
0
1
99f9b05521b270366c2f5ace2e28aa4d263594e4
1,755
AoC-2018
MIT License
src/main/kotlin/me/peckb/aoc/_2021/calendar/day08/Day08.kt
peckb1
433,943,215
false
{"Kotlin": 956135}
package me.peckb.aoc._2021.calendar.day08 import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory import javax.inject.Inject class Day08 @Inject constructor(private val generatorFactory: InputGeneratorFactory) { companion object { private const val ALL_LETTERS = "abcdefg" private val NUMBER_TO_SIGNAL_CODE = mapOf( '0' to "abcefg", '1' to "cf", '2' to "acdeg", '3' to "acdfg", '4' to "bcdf", '5' to "abdfg", '6' to "abdefg", '7' to "acf", '8' to "abcdefg", '9' to "abcdfg" ) private val SIGNAL_CODE_TO_NUMBER = NUMBER_TO_SIGNAL_CODE.entries.associate { (k, v) -> v to k } } fun findUniqueNumbers(fileName: String) = generatorFactory.forFile(fileName).readAs(::measurement) { input -> val wantedValues = listOf(2, 3, 4, 7) input.sumOf { (_, outputValue) -> outputValue.count { wantedValues.contains(it.length) } } } fun sumAllOutputs(fileName: String) = generatorFactory.forFile(fileName).readAs(::measurement) { input -> val outputResult = input.map { (patterns, outputValues) -> val wirePossibilities = ALL_LETTERS.associateWith { ALL_LETTERS.toMutableList() } fun String.hasEveryPossibilityFor(possibility: Char) = wirePossibilities[possibility]?.all { this.contains(it) } == true patterns.sortedBy { it.length }.forEach { encoding -> when(encoding.length) { 2 -> wirePossibilities.removeValuesFor('1', encoding) 3 -> wirePossibilities.removeValuesFor('7', encoding) 4 -> wirePossibilities.removeValuesFor('4', encoding) 5 -> if (encoding.hasEveryPossibilityFor('c') && encoding.hasEveryPossibilityFor('f')) { // The "c" and "f" encodings fully matching can only happen in a #3 // as in a #2 you would have no 'f' and in a #5 you would have no 'c' wirePossibilities.removeValuesFor('3', encoding) } 6 -> if (!(encoding.hasEveryPossibilityFor('c') && encoding.hasEveryPossibilityFor('f'))) { // The 'c' and 'f' encodings NOT fully matching can only happen in a #6 wirePossibilities.removeValuesFor('6', encoding) } } } val mappings = wirePossibilities.entries.associate { (k, v) -> v.first() to k } outputValues .map { mappings.decode(it) } .map { SIGNAL_CODE_TO_NUMBER[it]!! } .joinToString("").toInt() } outputResult.sum() } private fun Map<Char, MutableList<Char>>.removeValuesFor(number: Char, encoding: String) { // we start by ensuring only values in our encoding show up for a given number // for example if we were looking for the number "2" we would have two signal characters // and for 'c' and 'f' we remove any value as a possibility that isn't inside our encoding NUMBER_TO_SIGNAL_CODE[number]?.forEach { signalCharacter -> this[signalCharacter]?.removeAll { !encoding.contains(it) } } // we also do the inverse, by clearing our encodings from anything that our number doesn't fill // so if we have the number "2" again, we remove these two encoded values from a possibility // to have encoded 'a', 'b', 'd', 'e', 'g' NUMBER_TO_SIGNAL_CODE[number] ?.let { signal -> signal.fold(ALL_LETTERS) { letters, letterToRemove -> letters.filterNot { it == letterToRemove } } } ?.forEach { signalCharacter -> this[signalCharacter]?.removeAll { encoding.contains(it) } } } private fun Map<Char, Char>.decode(outputValue: String) = outputValue .toCharArray() .map { this[it]!! } .sorted() .joinToString("") private fun measurement(line: String): Measurement { val (patterns, output) = line.split("|").map { it.trim().split(" ") } return Measurement(patterns, output) } private data class Measurement(val patterns: List<String>, val outputValues: List<String>) }
0
Kotlin
1
3
2625719b657eb22c83af95abfb25eb275dbfee6a
3,912
advent-of-code
MIT License
src/Day06.kt
pavlo-dh
572,882,309
false
{"Kotlin": 39999}
fun main() { fun findMarkerEnd(signal: String, markerLength: Int): Int { var markerEnd = 0 outer@ for (i in markerLength - 1 until signal.length) { val markerChars = mutableSetOf<Char>() for (j in i downTo i - (markerLength - 1)) { markerChars.add(signal[j]) } if (markerChars.size == markerLength) { markerEnd = i + 1 break@outer } } return markerEnd } fun part1(input: List<String>): Int = findMarkerEnd(input[0], 4) fun part2(input: List<String>): Int = findMarkerEnd(input[0], 14) // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") check(part1(testInput) == 7) check(part2(testInput) == 19) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
c10b0e1ce2c7c04fbb1ad34cbada104e3b99c992
918
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/com/chriswk/aoc/advent2022/Day5.kt
chriswk
317,863,220
false
{"Kotlin": 481061}
package com.chriswk.aoc.advent2022 import com.chriswk.aoc.AdventDay import com.chriswk.aoc.util.reportableString import java.util.* class Day5: AdventDay(2022, 5) { companion object { @JvmStatic fun main(args: Array<String>) { val day = Day5() reportableString { day.part1() } reportableString { day.part2() } } val operationRegEx = """move (\d+) from (\d+) to (\d+)""".toRegex() } fun parseInput(input: List<String>): Pair<List<ArrayDeque<Char>>, List<Operation>> { val stackCount = (input.first().length + 1) / 4 val stacks = List(stackCount) { ArrayDeque<Char>() } val ops = mutableListOf<Operation>() input.forEach { line -> when { line.contains('[') -> { for (idx in 1 until line.length step 4){ if (line[idx].isLetter()) { stacks[(idx - 1) / 4].addLast(line[idx]) } } } line.startsWith("move") -> { ops.add(Operation(line)) } } } return stacks to ops } fun applyOps(stacks: List<ArrayDeque<Char>>, operations: List<Operation>): List<ArrayDeque<Char>> { operations.forEach { op -> repeat(op.cratesToMove) { stacks[op.toStack].addFirst(stacks[op.fromStack].removeFirst()) } } return stacks } fun crateMover9001(stacks: List<ArrayDeque<Char>>, operations: List<Operation>): List<ArrayDeque<Char>> { operations.forEach { op -> val top = mutableListOf<Char>() repeat(op.cratesToMove) { top.add(stacks[op.fromStack].removeFirst()) } top.reversed().forEach { stacks[op.toStack].push(it) } } return stacks } fun getStacksAndOps(): Pair<List<ArrayDeque<Char>>, List<Operation>> { return parseInput(inputAsLines) } fun part1(): String { val (stacks, ops) = getStacksAndOps() val endResult = applyOps(stacks, ops) return endResult.joinToString(separator = "") { it.first().toString() } } fun part2(): String { val (stacks, ops) = getStacksAndOps() val endResult = crateMover9001(stacks, ops) return endResult.joinToString(separator = "") { it.first().toString() } } data class Operation(val cratesToMove: Int, val fromStack: Int, val toStack: Int) { constructor(line: String, match: MatchResult.Destructured = operationRegEx.find(line)!!.destructured): this( cratesToMove = match.component1().toInt(), fromStack = match.component2().toInt() - 1, // To get correct index toStack = match.component3().toInt() - 1 // To get correct index ) } }
116
Kotlin
0
0
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
2,993
adventofcode
MIT License
src/main/kotlin/g2101_2200/s2196_create_binary_tree_from_descriptions/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2101_2200.s2196_create_binary_tree_from_descriptions // #Medium #Array #Hash_Table #Depth_First_Search #Breadth_First_Search #Tree #Binary_Tree // #2023_06_26_Time_933_ms_(100.00%)_Space_58.3_MB_(100.00%) import com_github_leetcode.TreeNode /* * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { fun createBinaryTree(descriptions: Array<IntArray>): TreeNode? { val map: MutableMap<Int, Data> = HashMap() for (description in descriptions) { var data = map[description[0]] if (data == null) { data = Data() data.node = TreeNode(description[0]) data.isHead = true map[description[0]] = data } var childData = map[description[1]] if (childData == null) { childData = Data() childData.node = TreeNode(description[1]) map[childData.node!!.`val`] = childData } childData.isHead = false if (description[2] == 1) { data.node!!.left = childData.node } else { data.node!!.right = childData.node } } for ((_, value) in map) { if (value.isHead) { return value.node } } return null } private class Data { var node: TreeNode? = null var isHead = false } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,611
LeetCode-in-Kotlin
MIT License
problems/2861/kotlin/Solution.kt
misut
678,196,869
false
{"Kotlin": 32683}
class Solution { fun maxNumberOfAlloys( n: Int, k: Int, budget: Int, composition: List<List<Int>>, stock: List<Int>, cost: List<Int> ): Int = composition.maxOf { it.findCount(budget, stock, cost) } } fun List<Int>.isAvailable(count: Int, budget: Int, stock: List<Int>, cost: List<Int>): Boolean = mapIndexed { idx, num -> maxOf(0, (num.toLong() * count - stock[idx])) * cost[idx] }.sum() <= budget fun List<Int>.findCount(budget: Int, stock: List<Int>, cost: List<Int>): Int { var lo = 0 var hi = Int.MAX_VALUE while (lo <= hi) { val mi = (lo + hi) / 2 if (isAvailable(mi, budget, stock, cost)) { lo = mi + 1 } else { hi = mi - 1 } } return lo - 1 }
0
Kotlin
0
0
52fac3038dd29cb8eefebbf4df04ccf1dda1e332
796
ps-leetcode
MIT License
AdventOfCodeDay07/src/nativeMain/kotlin/Day07.kt
bdlepla
451,523,596
false
{"Kotlin": 153773}
class Day07(lines:List<String>) { private val bags = parseLines(lines) fun solvePart1() = findParents().count() - 1 fun solvePart2() = baggageCost() - 1 private fun parseLines(lines: List<String>): Set<Rule> = lines.filterNot { it.contains("no other") } .flatMap { row -> val parts = row.replace(unusedText, "").split(whitespace) val parent = parts.take(2).joinToString(" ") parts.drop(2) .windowed(3, 3, false) .map { child -> Rule( parent, child.first().toInt(), child.drop(1).joinToString(" ") ) } } .toSet() private fun findParents(bag: String = "shiny gold"): Set<String> = bags .filter { it.child == bag } .flatMap { findParents(it.parentName) }.toSet() + bag private fun baggageCost(bag: String = "shiny gold"): Int = bags .filter { it.parentName == bag } .sumOf { it.quantity * baggageCost(it.child) } + 1 companion object { private val unusedText = """bags|bag|contain|,|\.""".toRegex() private val whitespace = """\s+""".toRegex() } }
0
Kotlin
0
0
043d0cfe3971c83921a489ded3bd45048f02ce83
1,345
AdventOfCode2020
The Unlicense
src/day8/fr/Day08_1.fr.kt
BrunoKrantzy
433,844,189
false
{"Kotlin": 63580}
package day8.fr import java.io.File private fun readChars(): CharArray = readLn().toCharArray() private fun readLn() = readLine()!! // string line private fun readSb() = StringBuilder(readLn()) private fun readInt() = readLn().toInt() // single int private fun readLong() = readLn().toLong() // single long private fun readDouble() = readLn().toDouble() // single double private fun readStrings() = readLn().split(" ") // list of strings private fun readInts() = readStrings().map { it.toInt() } // list of ints private fun readLongs() = readStrings().map { it.toLong() } // list of longs private fun readDoubles() = readStrings().map { it.toDouble() } // list of doubles private fun readIntArray() = readStrings().map { it.toInt() }.toIntArray() // Array of ints private fun readLongArray() = readStrings().map { it.toLong() }.toLongArray() // Array of longs fun readInput(name: String) = File("src", "$name.txt").readLines() fun main() { var rep = 0L //val vIn = readInput("test8") val vIn = readInput("input8") // val regex = "^([a-g]{1,7})\\s([a-g]{1,7})\\s([a-g]{1,7})\\s([a-g]{1,7})\\s([a-g]{1,7})\\s([a-g]{1,7}) // \\s([a-g]{1,7})\\s([a-g]{1,7})\\s([a-g]{1,7})\\s([a-g]{1,7})\\s\\|\\s([a-g]{1,7})\\s([a-g]{1,7})\\s // ([a-g]{1,7})\\s([a-g]{1,7})\$".toRegex() val regex = "^\\s|([a-g]{1,7})\\s([a-g]{1,7})\\s([a-g]{1,7})\\s([a-g]{1,7})\$".toRegex() var lstP = mutableListOf<String>() vIn.forEach { val match = regex.find(it) val s1 = match!!.groups[1]!!.value lstP.add(s1) val s2 = match.groups[2]!!.value lstP.add(s2) val s3 = match.groups[3]!!.value lstP.add(s3) val s4 = match.groups[4]!!.value lstP.add(s4) lstP.forEach { item -> when (item.length) { 2 -> rep++ 4 -> rep++ 3 -> rep++ 7 -> rep++ } } lstP.clear() } println(rep) }
0
Kotlin
0
0
0d460afc81fddb9875e6634ee08165e63c76cf3a
1,982
Advent-of-Code-2021
Apache License 2.0
cx-test/src/main/kotlin/io/nuvalence/cx/tools/cxtest/orchestrator/TestOrchestrator.kt
Nuvalence
641,553,939
false
{"Kotlin": 237698, "FreeMarker": 11464}
package io.nuvalence.cx.tools.cxtest.orchestrator import io.nuvalence.cx.tools.cxtest.model.test.TestScenario import io.nuvalence.cx.tools.cxtest.util.Properties data class ExecutionPath(val path: List<Int>) { operator fun get(index: Int): Int { return path[index] } } enum class TestOrchestrationMode(val value: String) { SIMPLE("simple") { override fun generateExecutionPaths(testScenarios: List<TestScenario>): Map<TestScenario, List<ExecutionPath>> { return testScenarios.associateWith { testScenario -> listOf(ExecutionPath(List(testScenario.testSteps.size) { 0 })) } } }, COMPREHENSIVE("comprehensive") { override fun generateExecutionPaths(testScenarios: List<TestScenario>): Map<TestScenario, List<ExecutionPath>> { return testScenarios.associateWith { testScenario -> val modelPath = List(testScenario.testSteps.size) { 0 } val counts = testScenario.testSteps.map { testStep -> testStep.input.size } var isFirstMultimessageNode = true val pathList = counts.foldIndexed(mutableListOf<ExecutionPath>()) { index, acc, count -> if (count > 1) { for (i in (if (isFirstMultimessageNode) 0 else 1) until count) { val path = modelPath.toMutableList() path[index] = i acc.add(ExecutionPath(path)) } isFirstMultimessageNode = false } acc } pathList } } }; /** * Generates a map of test scenarios to execution paths. The execution paths are generated based on the test * orchestration mode, in the order that the test scenarios are provided. Each execution path is a list of integers * representing a permutation of the test steps in the test scenario based on possible inputs. * * @param testScenarios the list of test scenarios to generate execution paths for * @return a map of test scenarios to execution paths */ abstract fun generateExecutionPaths(testScenarios: List<TestScenario>): Map<TestScenario, List<ExecutionPath>> companion object { infix fun from(value: String?): TestOrchestrationMode = TestOrchestrationMode.values().firstOrNull { testOrchestrationMode -> testOrchestrationMode.value == value } ?: SIMPLE } } class OrchestratedTestMap(private val testMap: Map<TestScenario, List<ExecutionPath>>) { constructor(testScenarios: List<TestScenario>) : this( TestOrchestrationMode.from(Properties.ORCHESTRATION_MODE).generateExecutionPaths(testScenarios) ) constructor(testScenarios: List<TestScenario>, orchestrationMode: String) : this( TestOrchestrationMode.from(orchestrationMode).generateExecutionPaths(testScenarios) ) /** * Pairs up test scenarios with possible execution paths. * * @return a list of pairs of test scenarios and execution paths * @see TestOrchestrationMode.generateExecutionPaths */ fun generatePairs(): List<Pair<TestScenario, ExecutionPath>> { return testMap.entries.map { (testScenario, executionPaths) -> executionPaths.map { executionPath -> Pair(testScenario, executionPath) } }.flatten() } }
2
Kotlin
0
0
52ceacb32a2f64d9f23f995904ab5822cb7456c7
3,502
dialogflow-cx-tools
MIT License