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
core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/RequestMatching.kt
weofferservice
276,198,559
true
{"Groovy": 813668, "Java": 664815, "Kotlin": 602899, "Scala": 96238, "Clojure": 7523, "ANTLR": 7005, "Dockerfile": 582}
package au.com.dius.pact.core.matchers import au.com.dius.pact.core.model.Interaction import au.com.dius.pact.core.model.Request import au.com.dius.pact.core.model.RequestResponseInteraction import au.com.dius.pact.core.model.Response import mu.KLogging sealed class RequestMatch { /** * Take the first total match, or merge partial matches, or take the best available. */ fun merge(other: RequestMatch): RequestMatch = when { this is FullRequestMatch && other is FullRequestMatch -> this this is PartialRequestMatch && other is PartialRequestMatch -> PartialRequestMatch(this.problems + other.problems) this is FullRequestMatch -> this other is FullRequestMatch -> other this is PartialRequestMatch -> this else -> other } } data class FullRequestMatch(val interaction: Interaction) : RequestMatch() data class PartialRequestMatch(val problems: Map<Interaction, List<Mismatch>>) : RequestMatch() { fun description(): String { var s = "" for (problem in problems) { s += problem.key.description + ":\n" for (mismatch in problem.value) { s += " " + mismatch.description() + "\n" } } return s } } object RequestMismatch : RequestMatch() class RequestMatching(private val expectedInteractions: List<RequestResponseInteraction>) { fun matchInteraction(actual: Request): RequestMatch { val matches = expectedInteractions.map { compareRequest(it, actual) } return if (matches.isEmpty()) RequestMismatch else matches.reduce { acc, match -> acc.merge(match) } } fun findResponse(actual: Request): Response? { val match = matchInteraction(actual) return when (match) { is FullRequestMatch -> (match.interaction as RequestResponseInteraction).response else -> null } } companion object : KLogging() { var allowUnexpectedKeys = false private fun isPartialMatch(problems: List<Mismatch>): Boolean = !problems.any { when (it) { is PathMismatch, is MethodMismatch -> true else -> false } } private fun decideRequestMatch(expected: RequestResponseInteraction, problems: List<Mismatch>) = when { problems.isEmpty() -> FullRequestMatch(expected) isPartialMatch(problems) -> PartialRequestMatch(mapOf(expected to problems)) else -> RequestMismatch } fun compareRequest(expected: RequestResponseInteraction, actual: Request): RequestMatch { val mismatches = requestMismatches(expected.request, actual) logger.debug { "Request mismatch: $mismatches" } return decideRequestMatch(expected, mismatches) } @JvmStatic fun requestMismatches(expected: Request, actual: Request): List<Mismatch> { logger.debug { "comparing to expected request: \n$expected" } return (listOf(Matching.matchMethod(expected.method, actual.method)) + Matching.matchPath(expected, actual) + Matching.matchQuery(expected, actual) + Matching.matchCookie(expected.cookie(), actual.cookie()) + Matching.matchRequestHeaders(expected, actual) + Matching.matchBody(expected, actual, allowUnexpectedKeys) ).filterNotNull() } } }
0
Groovy
0
0
f3318bc87561b104b4fdb85dfe17b02a13481493
3,245
pact-jvm
Apache License 2.0
src/Day06.kt
Narmo
573,031,777
false
{"Kotlin": 34749}
fun main() { fun process(input: String, packetSize: Int): Int { var counter = 0 val deque = ArrayDeque<Char>() for (i in input) { deque.addLast(i) counter += 1 if (deque.size == packetSize) { if (deque.toSet().size == packetSize) { break } else { deque.removeFirst() } } } return counter } fun part1(input: String): Int = process(input, packetSize = 4) fun part2(input: String): Int = process(input, packetSize = 14) val testInput1 = readInput("Day06_test1").first() check(part1(testInput1) == 7) check(part2(testInput1) == 19) val testInput2 = readInput("Day06_test2").first() check(part1(testInput2) == 5) check(part2(testInput2) == 23) val testInput3 = readInput("Day06_test3").first() check(part1(testInput3) == 6) check(part2(testInput3) == 23) val testInput4 = readInput("Day06_test4").first() check(part1(testInput4) == 10) check(part2(testInput4) == 29) val testInput5 = readInput("Day06_test5").first() check(part1(testInput5) == 11) check(part2(testInput5) == 26) val input = readInput("Day06").first() println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
335641aa0a964692c31b15a0bedeb1cc5b2318e0
1,141
advent-of-code-2022
Apache License 2.0
src/Day25.kt
kuangbin
575,873,763
false
{"Kotlin": 8252}
fun main() { fun part1(input: List<String>): String { var sum = 0L for (s in input) { sum += getValue(s) } return getSNAFU(sum) } fun part2(input: List<String>): Int { return input.size } // test if implementation meets criteria from the description, like: val testInput = readInput("Day25_test") check(part1(testInput) == "2=-1=0") val input = readInput("Day25") println(part1(input)) println(part2(input)) } fun getValue(str: String): Long { var ret = 0L for (cc in str) { ret *= 5 if (cc == '0') { continue } else if (cc == '1') { ret += 1 } else if (cc == '2') { ret += 2 } else if (cc == '-') { ret -= 1 } else if (cc == '=') { ret -= 2 } } return ret } fun getSNAFU(value: Long): String { var ans = "" var tmp = value while (tmp > 0) { if (tmp % 5 <= 2) { ans = ('0' + (tmp%5).toInt()) + ans tmp /= 5 } else { if (tmp%5 == 3L) { ans = "=$ans" tmp /= 5 tmp++ } else { ans = "-$ans" tmp /= 5 tmp++ } } } return ans }
0
Kotlin
0
0
ea0d89065b4d3cb4f6f78f768882d5b5473624d1
1,137
advent-of-code-2022
Apache License 2.0
src/Day10.kt
jwalter
573,111,342
false
{"Kotlin": 19975}
fun main() { fun part1(input: List<String>): Int { var x = 1 val result = input.flatMap { if (it == "noop") { listOf(x) } else { val curr = x x += it.drop(5).toInt() listOf(curr, x) } } val a = result.drop(19).chunked(40) val v = a.mapIndexed { idx, c -> if (c.size == 40) { c.last() * ((idx + 1) * 40 + 20) } else { 0 } } return v.sum() + result[19] * 20 } fun updateScreen(drawIndex: Int, spritePosition: Int) { if (drawIndex % 40 in (spritePosition - 1)..(spritePosition + 1)) { print("#") } else { print(".") } if ((drawIndex + 1) % 40 == 0) { println() } } fun part2(input: List<String>): Int { var spritePosition = 1 var drawIndex = 0 input.forEach { updateScreen(drawIndex++, spritePosition) if (it != "noop") { updateScreen(drawIndex++, spritePosition) spritePosition += it.drop(5).toInt() } } return 2 } val testInput = readInput("Day10_test") check(part1(testInput) == 13140) check(part2(testInput) == 2) val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
576aeabd297a7d7ee77eca9bb405ec5d2641b441
1,452
adventofcode2022
Apache License 2.0
src/main/kotlin/aoc07/aoc07.kt
dnene
317,653,484
false
null
package aoc07 import java.io.File import java.util.regex.Pattern data class Bag(val name: String, val contained: List<Pair<Int, String>>) { fun has(map: Map<String, Bag>, otherName: String): Boolean = contained.any { it.second == otherName || map[it.second]!!.has(map, otherName)} fun contains(map: Map<String, Bag>): Int = contained.map { it.first * (map[it.second]!!.contains(map) + 1) }.sum() } fun main() { val PATTERN_1 = Pattern.compile("^(\\w* \\w*) bags contain (.*)") val PATTERN_2 = Pattern.compile("^(\\d*) (\\w* \\w*) bag.*") val bagRules = File("data/inputs/aoc07.txt") .readLines() .mapNotNull { PATTERN_1.matcher(it).let { topLevelMatcher -> if (topLevelMatcher.matches() && topLevelMatcher.groupCount() == 2) { topLevelMatcher.group(1) to if (topLevelMatcher.group(2).startsWith("no other bag")) { emptyList() } else { topLevelMatcher.group(2).split(",").map { it.trim() }.mapNotNull { val lowLevelMatcher = PATTERN_2.matcher(it) if (lowLevelMatcher.matches()) { lowLevelMatcher.group(1).toInt() to lowLevelMatcher.group(2) } else { null } } } } else null } } .map { Bag(it.first, it.second) } .map { it.name to it } .toMap() bagRules.values.filter { it.has(bagRules,"shiny gold") }.size.let { println(it)} bagRules["shiny gold"]!!.contains(bagRules).let { println(it)} }
0
Kotlin
0
0
db0a2f8b484575fc3f02dc9617a433b1d3e900f1
1,867
aoc2020
MIT License
src/nativeMain/kotlin/com.qiaoyuang.algorithm/special/Questions2.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.special fun test2() { printlnResult("1011", "10001") printlnResult("1010101001", "1001110111") } /** * Input two strings to present two unsigned binary integers, write a function to implement binary addition */ private infix fun String.addBinary(str: String): String { require(isNotEmpty() && str.isNotEmpty()) { "The Input strings are illegal" } val (bigger, smaller) = if (length > str.length) this to str else str to this var biggerIndex = bigger.lastIndex var smallerIndex = smaller.lastIndex var carry = '0' return buildString { while (smallerIndex >= 0) { val biggerDigital = bigger[biggerIndex--] val smallerDigital = smaller[smallerIndex--] require( biggerDigital == '0' || biggerDigital == '1' && (smallerDigital == '0' || smallerDigital == '1')) { "The input strings are illegal" } when { biggerDigital == '1' && smallerDigital == '0' && carry == '0' -> { insert(0, '1') carry = '0' } biggerDigital == '0' && smallerDigital == '1' && carry == '0' -> { insert(0, '1') carry = '0' } biggerDigital == '0' && smallerDigital == '0' && carry == '1' -> { insert(0, '1') carry = '0' } biggerDigital == '0' && smallerDigital == '1' && carry == '1' -> { insert(0, '0') carry = '1' } biggerDigital == '1' && smallerDigital == '0' && carry == '1' -> { insert(0, '0') carry = '1' } biggerDigital == '1' && smallerDigital == '1' && carry == '0' -> { insert(0, '0') carry = '1' } biggerDigital == '0' && smallerDigital == '0' && carry == '0' -> { insert(0, '0') carry = '0' } biggerDigital == '1' && smallerDigital == '1' && carry == '1' -> { insert(0, '1') carry = '1' } } } while (biggerIndex >= 0) { val biggerDigital = bigger[biggerIndex--] when { biggerDigital == '1' && carry == '0' -> { insert(0, '1') carry = '0' } biggerDigital == '0' && carry == '1' -> { insert(0, '1') carry = '0' } biggerDigital == '1' && carry == '1' -> { insert(0, '0') carry = '1' } biggerDigital == '0' && carry == '0' -> { insert(0, '0') carry = '0' } } } if (carry == '1') insert(0, '1') } } private fun printlnResult(num1: String, num2: String) { val result = num1 addBinary num2 println("The $num1 adds $num2, we got the result $result, the result is (${(num1.toInt(2) + num2.toInt(2)).toString(2) == result})") }
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
3,363
Algorithm
Apache License 2.0
src/test/kotlin/Problem10Test.kt
gmpalmer
319,038,590
false
null
import org.junit.jupiter.api.Test import kotlin.test.assertEquals class Problem10Test { @Test fun test_Example() { val nums = AdventUtils.getResourceAsText("/day10/example.txt").lines().map{it.toInt()} val magic = solve(nums) println("magic = ${magic}") } private fun solve(nums: List<Int>): Long { val countMap = mutableMapOf(Pair(1, 0), Pair(2, 0), Pair(3, 0)) var previous = 0 nums.sorted().forEach { val diff = it - previous!! val count = countMap[diff]!! countMap[diff] = count + 1 //println("${it}=${diff} countMap = ${countMap}") previous = it } val count = countMap[3]!! countMap[3] = count + 1 println("countMap = ${countMap}") val magic = countMap[1]!!.toLong() * countMap[3]!!.toLong() return magic } @Test fun test_input() { val nums = AdventUtils.getResourceAsText("/day10/input.txt").lines().map{it.toInt()} val magic = solve(nums) println("magic = ${magic}") } fun getValue(map:Map<Int, Long>, index: Int): Long { var result = 0L val nullableVal = map[index] if(nullableVal != null) { result = nullableVal } return result } fun countSmart(nums: List<Int>): Long { val partials:MutableMap<Int, Long> = HashMap() var partialCount = 1L val mutableList = ArrayList<Int>() mutableList.addAll(nums) mutableList.add(0) val descendingNums = mutableList.sortedDescending() descendingNums.forEachIndexed { index, i -> partialCount = countPartial(descendingNums, index, partials, i) println("${i} = ${partialCount}") partials[i] = partialCount } return partialCount } private fun countPartial(descendingNums: List<Int>, index: Int, partials: MutableMap<Int, Long>, currentVal: Int): Long { if(index == 0) { return 1L } val backOne = descendingNums[index - 1] print("${currentVal}=") var count = 0L var loopIndex = index -1 var loopVal = getPreviousValue(descendingNums, loopIndex) while(loopVal != null && IsReachable(currentVal, loopVal)) { val previous = partials[loopVal!!]!! count += previous print("${loopVal}(+${previous}) ") loopIndex-- loopVal = getPreviousValue(descendingNums, loopIndex) } print(" | ") return count } private fun getPreviousValue(nums: List<Int>, index: Int): Int? { return if(index >= 0) return nums[index] else null } private fun IsReachable(currentVal: Int, backThree: Int) = currentVal + 3 >= backThree @Test fun countIterations_small2_one() { val nums = AdventUtils.getResourceAsText("/day10/small2.txt").lines().map{it.toInt()}.sorted() val weird = countSmart(nums) println("weird = ${weird}") assertEquals(28L, weird) } @Test fun countIterations_small() { val nums = AdventUtils.getResourceAsText("/day10/small.txt").lines().map{it.toInt()}.sorted() val weird = countSmart(nums) println("weird = ${weird}") assertEquals(8L, weird) } @Test fun countIterations_example() { val nums = AdventUtils.getResourceAsText("/day10/example.txt").lines().map{it.toInt()}.sorted() val weird = countSmart(nums) println("weird = ${weird}") assertEquals(19208L, weird) } @Test fun countIterations_input() { val nums = AdventUtils.getResourceAsText("/day10/input.txt").lines().map{it.toInt()}.sorted() val weird = countSmart(nums) println("weird = ${weird}") assertEquals(19208L, weird) } }
0
Kotlin
0
0
ec8eba4c247973ac6f1d1fce2bae76c5a938cda2
3,908
advent2020
Apache License 2.0
src/y2022/Day03.kt
gaetjen
572,857,330
false
{"Kotlin": 325874, "Mermaid": 571}
package y2022 import util.readInput object Day03 { fun part1(input: List<String>): Int { return input.sumOf { wrongItem(it) } } private fun wrongItem(input: String): Int { val (c1, c2) = input.chunked(input.length / 2) { it.toSet() } val wrongItem = c1.intersect(c2).first() return itemToPriority(wrongItem) } private fun itemToPriority(item: Char) = if (item in ('a'..'z')) { (item - 'a') + 1 } else { (item - 'A') + 27 } fun part2(input: List<String>): Int { return input.chunked(3).sumOf { badge(it) } } private fun badge(items: List<String>) :Int { return items .map { it.toSet() } .reduce { acc, chars -> acc.intersect(chars) } .first() .let { itemToPriority(it) } } } fun main() { val input = readInput("resources/2022/day03") println(Day03.part1(input)) println(Day03.part2(input)) }
0
Kotlin
0
0
d0b9b5e16cf50025bd9c1ea1df02a308ac1cb66a
985
advent-of-code
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/SteppingNumbers.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.DECIMAL /** * 1215. Stepping Numbers * https://leetcode.com/problems/stepping-numbers/ */ fun interface SteppingNumbers { operator fun invoke(low: Int, high: Int): List<Int> } class SteppingNumbersBFS : SteppingNumbers { override fun invoke(low: Int, high: Int): List<Int> { val list: MutableList<Int> = ArrayList() for (i in 0..9) { dfs(low, high, i.toLong(), list) } list.sort() return list } private fun dfs(low: Int, high: Int, cur: Long, list: MutableList<Int>) { if (cur in low..high) list.add(cur.toInt()) if (cur == 0L || cur > high) return val last = cur % DECIMAL val inc = cur * DECIMAL + last + 1 val dec = cur * DECIMAL + last - 1 when (last) { 0L -> dfs(low, high, inc, list) 9L -> dfs(low, high, dec, list) else -> { dfs(low, high, inc, list) dfs(low, high, dec, list) } } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,679
kotlab
Apache License 2.0
src/main/kotlin/days/aoc2022/Day14.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2022 import days.Day import util.Array2d import util.Point2d import java.lang.Integer.max import java.lang.Integer.min class Day14 : Day(2022, 14) { override fun partOne(): Any { return calculateAmountOfSandSettled(inputList) } override fun partTwo(): Any { return calculateSandUntilBlocked(inputList) } fun calculateAmountOfSandSettled(input: List<String>): Int { val cave = Cave(input) var sandDropped = 0 while(cave.holdsDroppedSand()) { sandDropped++ } return sandDropped } fun calculateSandUntilBlocked(input: List<String>): Int { val cave = Cave(input, true) var sandDropped = 0 while(cave.holdsDroppedSand()) { sandDropped++ } return sandDropped + 1 } class Cave(input: List<String>, withFloor: Boolean = false) { val bottom: Int val topography: Array2d<Char> init { val points = input.flatMap { line -> line.split(" -> ").map { pair -> pair.split(",").let { coordinates -> Point2d(coordinates.first().toInt(), coordinates.last().toInt()) } } } bottom = points.maxOf { it.y } + if (withFloor) 2 else 0 topography = Array2d(1000 + 1, bottom + 1, ' ') input.forEach { line -> val points = line.split(" -> ").map { pair -> pair.split(",").let { coordinates -> Point2d(coordinates.first().toInt(), coordinates.last().toInt()) } } points.windowed(2).forEach { points -> val p1 = points.first() val p2 = points.last() if (p1.x == p2.x) { for (y in min(p1.y, p2.y)..max(p1.y, p2.y)) { topography[Point2d(p1.x, y)] = '#' } } else { for (x in min(p1.x, p2.x)..max(p1.x, p2.x)) { topography[Point2d(x, p1.y)] = '#' } } } } if (withFloor) { for (x in 0..1000) { topography[Point2d(x, bottom)] = '#' } } } fun holdsDroppedSand(): Boolean { var sandPosition = Point2d(500, 0) var sandMoving = true do { try { sandPosition = listOf( Point2d(sandPosition.x, sandPosition.y + 1), Point2d(sandPosition.x - 1, sandPosition.y + 1), Point2d(sandPosition.x + 1, sandPosition.y + 1) ).first { ' ' == topography[it] } } catch (e: NoSuchElementException) { sandMoving = false topography[sandPosition] = 'o' } } while (sandMoving && sandPosition.y < bottom && sandPosition.y > 0) return sandPosition.y in 1 until bottom } } }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
3,278
Advent-Of-Code
Creative Commons Zero v1.0 Universal
app/src/main/java/me/grey/picquery/common/Algorithm.kt
greyovo
676,960,803
false
{"Kotlin": 153138, "Python": 17259, "PureBasic": 181}
package me.grey.picquery.common import kotlin.math.acos import kotlin.math.asin import kotlin.math.pow import kotlin.math.sqrt fun calculateSimilarity(vectorA: FloatArray, vectorB: FloatArray): Double { var dotProduct = 0.0 var normA = 0.0 var normB = 0.0 for (i in vectorA.indices) { dotProduct += vectorA[i] * vectorB[i] normA += vectorA[i] * vectorA[i] normB += vectorB[i] * vectorB[i] } normA = sqrt(normA) normB = sqrt(normB) return dotProduct / (normA * normB) } fun calculateSphericalDistanceLoss(vector1: FloatArray, vector2: FloatArray): Double { require(vector1.size == vector2.size) { "Vector dimensions do not match" } var dotProduct = 0.0 var norm1 = 0.0 var norm2 = 0.0 for (i in vector1.indices) { dotProduct += vector1[i] * vector2[i] norm1 += vector1[i] * vector1[i] norm2 += vector2[i] * vector2[i] } norm1 = sqrt(norm1) norm2 = sqrt(norm2) val cosineSimilarity = dotProduct / (norm1 * norm2) val distanceLoss = acos(cosineSimilarity) return distanceLoss } fun sphericalDistLoss(x: FloatArray, y: FloatArray): Double { val xNormalized: DoubleArray = normalizeVector(x) val yNormalized: DoubleArray = normalizeVector(y) val difference = computeDifference(xNormalized, yNormalized) val magnitude = computeMagnitude(difference) return computeResult(magnitude) } fun normalizeVector(vector: FloatArray): DoubleArray { val norm = computeNorm(vector) return vector.map { it / norm }.toDoubleArray() } fun computeNorm(vector: FloatArray): Double { var sumOfSquares = 0.0 for (element in vector) { sumOfSquares += element.pow(2) } return sqrt(sumOfSquares) } fun computeDifference(x: DoubleArray, y: DoubleArray): DoubleArray { return x.zip(y).map { (xValue, yValue) -> xValue - yValue }.toDoubleArray() } fun computeMagnitude(diff: DoubleArray): Double { var sumOfSquares = 0.0 for (element in diff) { sumOfSquares += element.pow(2) } return sqrt(sumOfSquares) } fun computeResult(magnitude: Double): Double { return asin(magnitude / 2.0).pow(2) * 2.0 }
7
Kotlin
13
111
4c95be235837885d31961b2f4f5018c0f9c48676
2,190
PicQuery
MIT License
LeetCode/Medium/longest-palindromic-substring/Solution.kt
GregoryHo
254,657,102
false
null
class Solution { fun longestPalindrome(s: String): String { if (s.isEmpty()) { return s } val length = s.length val dp = Array(length) { BooleanArray(length) } var startIndex = 0 var endIndex = 0 val chars = s.toCharArray() for (i in length - 1 downTo 0) { for (j in i until length) { if (j - i <= 2) { dp[i][j] = chars[i] == chars[j] } else { dp[i][j] = dp[i + 1][j - 1] && chars[i] == chars[j] } if (dp[i][j] && endIndex - startIndex <= j - i) { startIndex = i endIndex = j } } } return s.substring(startIndex, endIndex + 1) } fun main(args: Array<String>) { val solution = Solution() println(solution.longestPalindrome("babad")) println(solution.longestPalindrome("cbbd")) println(solution.longestPalindrome("a")) println(solution.longestPalindrome("ac")) println(solution.longestPalindrome("ccc")) println(solution.longestPalindrome("abcda")) println(solution.longestPalindrome("abcba")) println(solution.longestPalindrome("caba")) println(solution.longestPalindrome("eabcb")) println(solution.longestPalindrome("aaabaaaa")) }
0
Kotlin
0
0
8f126ffdf75aa83a6d60689e0b6fcc966a173c70
1,202
coding-fun
MIT License
src/Day02.kt
sabercon
648,989,596
false
null
fun main() { fun isValid1(range: IntRange, letter: Char, password: String): Boolean { return password.count { it == letter } in range } fun isValid2(range: IntRange, letter: Char, password: String): Boolean { return (password[range.first - 1] == letter) xor (password[range.last - 1] == letter) } val input = readLines("Day02").map { val (start, end, letter, password) = """(\d+)-(\d+) ([a-z]): ([a-z]+)""".toRegex() .matchEntire(it)!!.destructured Triple(start.toInt()..end.toInt(), letter.single(), password) } input.count { (range, letter, password) -> isValid1(range, letter, password) }.println() input.count { (range, letter, password) -> isValid2(range, letter, password) }.println() }
0
Kotlin
0
0
81b51f3779940dde46f3811b4d8a32a5bb4534c8
773
advent-of-code-2020
MIT License
leetcode2/src/leetcode/edit-distance.kt
hewking
68,515,222
false
null
package leetcode /** * 72. 编辑距离 * https://leetcode-cn.com/problems/edit-distance/ * Created by test * Date 2020/1/29 20:39 * Description * 给定两个单词 word1 和 word2,计算出将 word1 转换成 word2 所使用的最少操作数 。 你可以对一个单词进行如下三种操作: 插入一个字符 删除一个字符 替换一个字符 示例 1: 输入: word1 = "horse", word2 = "ros" 输出: 3 解释: horse -> rorse (将 'h' 替换为 'r') rorse -> rose (删除 'r') rose -> ros (删除 'e') 示例 2: 输入: word1 = "intention", word2 = "execution" 输出: 5 解释: intention -> inention (删除 't') inention -> enention (将 'i' 替换为 'e') enention -> exention (将 'n' 替换为 'x') exention -> exection (将 'n' 替换为 'c') exection -> execution (插入 'u') 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/edit-distance 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ object EditDistance { class Solution { fun minDistance(word1: String, word2: String): Int { return -1 } } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
1,156
leetcode
MIT License
topsis-normalization-weighting/src/main/kotlin/pl/poznan/put/topsis/NormalizationWeightingCalculator.kt
sbigaret
164,424,298
true
{"Kotlin": 93061, "R": 67629, "Shell": 24899, "Groovy": 24559}
package pl.poznan.put.topsis import kotlin.math.pow import kotlin.math.sqrt class NormalizationWeightingCalculator( alternatives: List<TopsisAlternative>, criteria: List<Criterion> ) : AlternativesCalculator<WeightedNormalizedAlternatives>(alternatives, criteria) { private val weights = criteria.map { it.weight } override fun calculate(): WeightedNormalizedAlternatives { val normalized = calculateNormalizedDecisionMatrix() val weighted = calculateWeightedNormalizedDecisionMatrix(normalized) val weightedAlternatives = weighted.mapIndexed { ai, v -> val criteriaValues = criteria.zip(v.toList()).map { it.revertOriginalValueSign() }.toMap() TopsisAlternative(alternatives[ai].name, criteriaValues) } return WeightedNormalizedAlternatives(weightedAlternatives) } private fun calculateNormalizedDecisionMatrix(): Array<DoubleArray> { val normDecMat = Array(alternativeNo) { DoubleArray(criteriaNo) } (0 until criteriaNo).forEach { col -> var sumPow = 0.0 (0 until alternativeNo).forEach { row -> sumPow += decisionMatrix[row][col].pow(2) } val sumPowSqrt = sqrt(sumPow) (0 until alternativeNo).forEach { row -> normDecMat[row][col] = decisionMatrix[row][col] / sumPowSqrt } } return normDecMat } private fun calculateWeightedNormalizedDecisionMatrix(normalizedDecisionMatrix: Array<DoubleArray>): Array<DoubleArray> { val weightedNormalizedDecisionMatrix = Array(alternativeNo) { DoubleArray(criteriaNo) } (0 until criteriaNo).forEach { col -> (0 until alternativeNo).forEach { row -> weightedNormalizedDecisionMatrix[row][col] = normalizedDecisionMatrix[row][col] * weights[col] } } return weightedNormalizedDecisionMatrix } } data class WeightedNormalizedAlternatives( val alternatives: List<TopsisAlternative> )
0
Kotlin
0
0
96c182d7e37b41207dc2da6eac9f9b82bd62d6d7
2,046
DecisionDeck
MIT License
src/jvmMain/kotlin/day03/refined/Day03.kt
liusbl
726,218,737
false
{"Kotlin": 109684}
package day03.refined import java.io.File fun main() { solvePart1() // Solution: 532428, solved at 07:34 // solvePart2() // Solution: 84051670, soved at 07:59 } fun solvePart1() { // val input = File("src/jvmMain/kotlin/day03/input/input_part1_test.txt") val input = File("src/jvmMain/kotlin/day03/input/input.txt") val lines = input.readLines() var numberStarted = false var symbolAppeared = false var interimNumber = "" fun reset() { numberStarted = false symbolAppeared = false interimNumber = "" } val result = mutableListOf<Int>() lines.forEachIndexed { row, line -> line.forEachIndexed { column, char -> if (numberStarted && char == '.') { if (symbolAppeared) { result.add(interimNumber.toInt()) } reset() return@forEachIndexed } else if (numberStarted && !char.isDigit()) { result.add(interimNumber.toInt()) reset() return@forEachIndexed } if (char.isDigit()) { // Start number tracking and symbol tracking numberStarted = true interimNumber += char } // If symbol exists close, change symbol flag if (numberStarted && lines.adjacent(row, column).any { !it.char.isDigit() && it.char != '.' }) { symbolAppeared = true } } if (numberStarted && symbolAppeared) { result.add(interimNumber.toInt()) } reset() } println(result.sum()) } fun solvePart2() { val input = File("src/jvmMain/kotlin/day03/input/input.txt") // val input = File("src/jvmMain/kotlin/day03/input/input.txt") val lines = input.readLines() var numberStarted = false var gearPositionSet = emptySet<Point>() var interimNumber = "" val result = mutableListOf<Gear>() lines.forEachIndexed { row, line -> line.forEachIndexed { column, char -> if (numberStarted && char == '.') { if (gearPositionSet.isNotEmpty()) { result.add(Gear(interimNumber.toInt(), gearPositionSet)) } numberStarted = false gearPositionSet = emptySet() interimNumber = "" return@forEachIndexed } else if (numberStarted && !char.isDigit()) { result.add(Gear(interimNumber.toInt(), gearPositionSet)) numberStarted = false gearPositionSet = emptySet() interimNumber = "" return@forEachIndexed } if (char.isDigit()) { // Start number tracking and symbol tracking numberStarted = true interimNumber += char } // If symbol exists close, change symbol flag if (numberStarted) { gearPositionSet = gearPositionSet.toMutableSet().apply { addAll(lines.adjacent(row, column).filter { it.char == '*' }) } } } if (numberStarted && gearPositionSet.isNotEmpty()) { result.add(Gear(interimNumber.toInt(), gearPositionSet)) } numberStarted = false gearPositionSet = emptySet() interimNumber = "" } val gearPointList = result.flatMap { it.gearPointSet.toList() } val gearPointMap = gearPointList.associateWith { gear -> result.filter { it.gearPointSet.contains(gear) } } val sum = gearPointMap.filter { it.value.size == 2 } .toList() .sumOf { it.second[0].number * it.second[1].number } println(sum) } fun List<String>.adjacent(row: Int, column: Int): List<Point> { val lines = this return listOf( lines.safeGet(row - 1, column - 1), lines.safeGet(row - 1, column), lines.safeGet(row - 1, column + 1), lines.safeGet(row, column - 1), lines.safeGet(row, column + 1), lines.safeGet(row + 1, column - 1), lines.safeGet(row + 1, column), lines.safeGet(row + 1, column + 1) ) } fun List<String>.safeGet(row: Int, column: Int): Point { val lines = this val maxRow = lines.size - 1 val rowCoerced = row.coerceIn(0..maxRow) val line = lines[rowCoerced] val maxColumn = line.length - 1 val columnCoerced = column.coerceIn(0..maxColumn) return Point(line[columnCoerced], Position(rowCoerced, columnCoerced)) } data class Point( val char: Char, val position: Position ) data class Gear( val number: Int, val gearPointSet: Set<Point> ) data class Position( val row: Int, val column: Int ) data class Number( val row: Int, val column: Int, val value: String )
0
Kotlin
0
0
1a89bcc77ddf9bc503cf2f25fbf9da59494a61e1
4,874
advent-of-code
MIT License
src/main/kotlin/24/24.kt
Wrent
225,133,563
false
null
fun main() { val map = mutableMapOf<Coord, Eris>() val history = mutableSetOf<String>() INPUT24.split("\n") .forEachIndexed { i, row -> row.split("").filter { it != "" }.forEachIndexed { j, cell -> val coord = Coord(j, i) map[coord] = eris(cell[0]) } } var nextMap = map while (true) { val biodiversity = biodiversity(nextMap) if (history.contains(biodiversity)) { println("first result") println(biodiversity.toInt(2)) break; } history.add(biodiversity) nextMap = nextMap.mapValues { getNext(nextMap, it.key) }.toMutableMap() } val recursiveMap = mutableMapOf<Int, MutableMap<Coord, Eris>>() recursiveMap[0] = mutableMapOf() INPUT24.split("\n") .forEachIndexed { i, row -> row.split("").filter { it != "" }.forEachIndexed { j, cell -> val coord = Coord(j, i) recursiveMap[0]!![coord] = eris(cell[0]) } } var nextRecursiveMap = recursiveMap initLevels(nextRecursiveMap) for (i in 0 until 200) { val newMap = mutableMapOf<Int, MutableMap<Coord, Eris>>() nextRecursiveMap.forEach { newMap.putIfAbsent(it.key, mutableMapOf()) it.value.forEach { inner -> val next = getNext(nextRecursiveMap, inner.key, it.key) newMap[it.key]!![inner.key] = next } } initLevels(newMap) nextRecursiveMap = newMap } println("second result") println(nextRecursiveMap.values.flatMap { it.values }.filter { it == Eris.BUG }.count()) } fun initLevels(map: MutableMap<Int, MutableMap<Coord, Eris>>) { initLevel(map, map.keys.min()!! - 1) initLevel(map, map.keys.max()!! + 1) } private fun initLevel(map: MutableMap<Int, MutableMap<Coord, Eris>>, level: Int) { map[level] = mutableMapOf() for (i in 0..4) { for (j in 0..4) { map[level]!![Coord(i, j)] = Eris.EMPTY } } } fun getNext(map: MutableMap<Int, MutableMap<Coord, Eris>>, coord: Coord, level: Int): Eris { if (coord == Coord(2, 2)) { return Eris.EMPTY } // map.putIfAbsent(level - 1, mutableMapOf()) val count = (listOf( map[level]!![coord.north()] ?: map[level - 1]?.get(Coord(2, 1)) ?: Eris.EMPTY, map[level]!![coord.south()] ?: map[level - 1]?.get(Coord(2, 3)) ?: Eris.EMPTY, map[level]!![coord.east()] ?: map[level - 1]?.get(Coord(3, 2)) ?: Eris.EMPTY, map[level]!![coord.west()] ?: map[level - 1]?.get(Coord(1, 2)) ?: Eris.EMPTY ) + addSubgrid(map, coord, level)) .filter { it == Eris.BUG } .count() when (map[level]!![coord]) { Eris.BUG -> return if (count == 1) { Eris.BUG } else { Eris.EMPTY } Eris.EMPTY -> { return if (count == 1 || count == 2) { Eris.BUG } else { Eris.EMPTY } } } throw RuntimeException() } fun addSubgrid(map: MutableMap<Int, MutableMap<Coord, Eris>>, coord: Coord, level: Int): List<Eris> { // map.putIfAbsent(level + 1, mutableMapOf()) return when (coord) { Coord(2, 1) -> listOf( map[level + 1]?.get(Coord(0,0)) ?: Eris.EMPTY, map[level + 1]?.get(Coord(1,0)) ?: Eris.EMPTY, map[level + 1]?.get(Coord(2,0)) ?: Eris.EMPTY, map[level + 1]?.get(Coord(3,0)) ?: Eris.EMPTY, map[level + 1]?.get(Coord(4,0)) ?: Eris.EMPTY ) Coord(2, 3) -> listOf( map[level + 1]?.get(Coord(0,4)) ?: Eris.EMPTY, map[level + 1]?.get(Coord(1,4)) ?: Eris.EMPTY, map[level + 1]?.get(Coord(2,4)) ?: Eris.EMPTY, map[level + 1]?.get(Coord(3,4)) ?: Eris.EMPTY, map[level + 1]?.get(Coord(4,4)) ?: Eris.EMPTY ) Coord(1, 2) -> listOf( map[level + 1]?.get(Coord(0,0)) ?: Eris.EMPTY, map[level + 1]?.get(Coord(0,1)) ?: Eris.EMPTY, map[level + 1]?.get(Coord(0,2)) ?: Eris.EMPTY, map[level + 1]?.get(Coord(0,3)) ?: Eris.EMPTY, map[level + 1]?.get(Coord(0,4)) ?: Eris.EMPTY ) Coord(3, 2) -> listOf( map[level + 1]?.get(Coord(4,0)) ?: Eris.EMPTY, map[level + 1]?.get(Coord(4,1)) ?: Eris.EMPTY, map[level + 1]?.get(Coord(4,2)) ?: Eris.EMPTY, map[level + 1]?.get(Coord(4,3)) ?: Eris.EMPTY, map[level + 1]?.get(Coord(4,4)) ?: Eris.EMPTY ) else -> listOf() } } fun biodiversity(map: Map<Coord, Eris>): String { val maxX = map.keys.maxBy { it.x }!!.x val maxY = map.keys.maxBy { it.y }!!.y val minX = map.keys.minBy { it.x }!!.x val minY = map.keys.minBy { it.y }!!.y var res = "" for (i in minY..maxY) { for (j in minX..maxX) { val current = map[Coord(j, i)] if (current == Eris.BUG) { res = "1" + res } else { res = "0" + res } } } return res } fun getNext(map: Map<Coord, Eris>, coord: Coord): Eris { val count = listOf( map[coord.north()], map[coord.south()], map[coord.east()], map[coord.west()] ) .filterNotNull() .filter { it == Eris.BUG } .count() when (map[coord]) { Eris.BUG -> return if (count == 1) { Eris.BUG } else { Eris.EMPTY } Eris.EMPTY -> { return if (count == 1 || count == 2) { Eris.BUG } else { Eris.EMPTY } } } throw RuntimeException() } enum class Eris(val char: Char) { BUG('#'), EMPTY('.') } fun eris(char: Char): Eris { return Eris.values().find { it.char == char }!! } const val INPUT24 = """##### .#.#. .#..# ....# ..###""" const val TEST241 = """....# #..#. #..## ..#.. #...."""
0
Kotlin
0
0
0a783ed8b137c31cd0ce2e56e451c6777465af5d
6,274
advent-of-code-2019
MIT License
src/com/kingsleyadio/adventofcode/y2021/day06/Solution.kt
kingsleyadio
435,430,807
false
{"Kotlin": 134666, "JavaScript": 5423}
package com.kingsleyadio.adventofcode.y2021.day06 import com.kingsleyadio.adventofcode.util.readInput fun solution(input: List<Int>, timeLeft: Int): Long { val cache = hashMapOf<String, Long>() fun memo(life: Int, timeLeft: Int, func: (Int, Int) -> Long): Long { val key = "$life-$timeLeft" return cache.getOrPut(key) { func(life, timeLeft) } } fun headCount(life: Int, timeLeft: Int): Long { if (timeLeft <= life) return 1 val newTimeLeft = timeLeft - life - 1 return memo(6, newTimeLeft, ::headCount) + memo(8, newTimeLeft, ::headCount) } return input.fold(0) { acc, life -> acc + memo(life, timeLeft, ::headCount) } } fun main() { val input = readInput(2021, 6).useLines { lines -> lines.first().split(",").map { it.toInt() } } println(solution(input, 80)) println(solution(input, 256)) }
0
Kotlin
0
1
9abda490a7b4e3d9e6113a0d99d4695fcfb36422
885
adventofcode
Apache License 2.0
src/Day02.kt
sjgoebel
573,578,579
false
{"Kotlin": 21782}
fun main() { fun scissors(move: Char): Int { return when (move) { 'X' -> 1 + 6 'Y' -> 2 + 0 'Z' -> 3 + 3 else -> 0 } } fun rock(move: Char): Int { return when (move) { 'X' -> 1 + 3 'Y' -> 2 + 6 'Z' -> 3 + 0 else -> 0 } } fun paper(move: Char): Int { return when (move) { 'X' -> 1 + 0 'Y' -> 2 + 3 'Z' -> 3 + 6 else -> 0 } } fun part1(input: List<String>): Int { var total = 0 for (line in input) { when (line[0]) { 'C' -> total += scissors(line[2]) 'A' -> total += rock(line[2]) 'B' -> total += paper(line[2]) } } return total } fun win(input: Char): Int { return when (input) { 'A' -> 6 + 2 'B' -> 6 + 3 'C' -> 6 + 1 else -> 0 } } fun lose(input: Char): Int { return when (input) { 'A' -> 3 'B' -> 1 'C' -> 2 else -> 0 } } fun tie(input: Char): Int { return when (input) { 'A' -> 3 + 1 'B' -> 3 + 2 'C' -> 3 + 3 else -> 0 } } fun part2(input: List<String>): Int { var total = 0 for (line in input) { when (line[2]) { 'X' -> total += lose(line[0]) 'Y' -> total += tie(line[0]) 'Z' -> total += win(line[0]) } } return total } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
ae1588dbbb923dbcd4d19fd1495ec4ebe8f2593e
1,939
advent-of-code-2022-kotlin
Apache License 2.0
src/year2018/dec/level6/ktSolutions.kt
hasanhaja
161,559,069
true
{"Java": 17892, "Kotlin": 2291}
package year2018.dec.level6 fun ktchallenge1(s: String): Int { val expression: List<String> = s.trim().split(" ") return evaluate(expression) } private enum class Ops(val symbol: String) { ADD("+"), MINUS("-"), MULTIPLY("*"), DIVIDE("/"), } private fun evaluate(expression: List<String>): Int { var total = 0 var currentOp = Ops.ADD for (value in expression) { try { val current = value.toInt() when (currentOp) { Ops.ADD -> total += current Ops.MINUS -> total -= current Ops.MULTIPLY -> total *= current Ops.DIVIDE -> total /= current } } catch (e: Exception) { when (value) { Ops.ADD.symbol -> currentOp = Ops.ADD Ops.MINUS.symbol -> currentOp = Ops.MINUS Ops.MULTIPLY.symbol -> currentOp = Ops.MULTIPLY Ops.DIVIDE.symbol -> currentOp = Ops.DIVIDE else -> e.printStackTrace() } } } return total } fun ktchallenge2(array: IntArray, a: Int): IntArray { val result = IntArray(2) for (i in 0 until array.size) { for (j in i+1 until array.size) { when (a) { array[i] + array[j]-> { result[0] = i result[1] = j } } } } return result } fun ktchallenge3(array1: IntArray, array2: IntArray): Int = (reverseArray(array1).sum() + reverseArray(array2).sum()) private fun reverseArray(array: IntArray): IntArray { return array. map { it.toString().reversed().toInt() }. toIntArray() } fun <T> ktchallenge4(c: Class<T>, a: Double, b: Double): T? { return null } fun ktchallenge5(s: String, a: Int): Int { var text = s // replace ops with op with spaces // for this case only text = text.replace("+", " + ") // Index of "r" in return val returnIndex = text.indexOf("return") val semiIndex = text.indexOf(";") // replace i with a (this will do it for all, but it doesn't matter text = text.replace("i", a.toString()) val expression = text.slice(returnIndex+6 until semiIndex ) return ktchallenge1(expression) }
0
Java
0
0
c4c84dbfaa2bb4ca38e626a9d63cbabf81016809
2,291
UoB-Codefest
MIT License
src/chapter5/section1/ex14_ArraySort.kt
w1374720640
265,536,015
false
{"Kotlin": 1373556}
package chapter5.section1 import chapter2.swap import extensions.shuffle /** * 数组排序 * 编写一个方法,使用三向字符串快速排序处理以整型数组作为键的情况。 * * 解:字符串可以理解为字符型数组,将字符替换成整数即可 */ fun ex14_ArraySort(array: Array<IntArray>) { array.shuffle() ex14_ArraySort(array, 0, array.size - 1, 0) } private fun ex14_ArraySort(array: Array<IntArray>, low: Int, high: Int, d: Int) { // 不使用插入排序优化 if (low >= high) return var i = low + 1 var j = low var k = high while (i <= k) { // 这里和三向字符串快速排序不同,以j位置为基准点,每个位置都和基准比较 val result = compare(array, i, j, d) when { result > 0 -> array.swap(i, k--) result < 0 -> array.swap(i++, j++) else -> i++ } } ex14_ArraySort(array, low, j - 1, d) if (array[j].size > d) ex14_ArraySort(array, j, i - 1, d + 1) ex14_ArraySort(array, i, high, d) } private fun compare(array: Array<IntArray>, i: Int, j: Int, d: Int): Int { return when { d >= array[i].size && d >= array[j].size -> 0 d >= array[i].size -> -1 d >= array[j].size -> 1 else -> array[i][d].compareTo(array[j][d]) } } fun main() { val array = arrayOf( intArrayOf(1, 2, 3, 4), intArrayOf(2, 3, 4, 5), intArrayOf(2, 2, 3, 4), intArrayOf(1, 2, 3, 4), intArrayOf(5, 4, 3, 2), intArrayOf(1, 2, 3, 4), intArrayOf(1, 2), intArrayOf(2, 4, 3), intArrayOf(1, 2, 3, 4), intArrayOf(2, 4, 3) ) ex14_ArraySort(array) println(array.joinToString(separator = "\n") { it.joinToString() }) }
0
Kotlin
1
6
879885b82ef51d58efe578c9391f04bc54c2531d
1,833
Algorithms-4th-Edition-in-Kotlin
MIT License
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[978]最长湍流子数组.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//当 A 的子数组 A[i], A[i+1], ..., A[j] 满足下列条件时,我们称其为湍流子数组: // // // 若 i <= k < j,当 k 为奇数时, A[k] > A[k+1],且当 k 为偶数时,A[k] < A[k+1]; // 或 若 i <= k < j,当 k 为偶数时,A[k] > A[k+1] ,且当 k 为奇数时, A[k] < A[k+1]。 // // // 也就是说,如果比较符号在子数组中的每个相邻元素对之间翻转,则该子数组是湍流子数组。 // // 返回 A 的最大湍流子数组的长度。 // // // // 示例 1: // // 输入:[9,4,2,10,7,8,8,1,9] //输出:5 //解释:(A[1] > A[2] < A[3] > A[4] < A[5]) // // // 示例 2: // // 输入:[4,8,12,16] //输出:2 // // // 示例 3: // // 输入:[100] //输出:1 // // // // // 提示: // // // 1 <= A.length <= 40000 // 0 <= A[i] <= 10^9 // // Related Topics 数组 动态规划 Sliding Window // 👍 142 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun maxTurbulenceSize(arr: IntArray): Int { //时间复杂度 O(n) var inc = 1 //递增长度 var dec = 1 //递减长度 var res = 1 for (i in 1 until arr.size){ if(arr[i] < arr[i-1]){ //递减 dec = inc +1 inc = 1 }else if(arr[i] > arr[i-1]){ //递增 inc = dec +1 dec = 1 }else{ inc = 1 dec = 1 } res = Math.max(res,Math.max(inc,dec)) } return res } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,666
MyLeetCode
Apache License 2.0
src/Day07.kt
joshpierce
573,265,121
false
{"Kotlin": 46425}
import java.io.File // I'm not proud of this, but it works. fun main() { var lines: List<String> = File("Day07.txt").readLines() var fileSystem: MutableList<Obj> = mutableListOf() fileSystem.add(Obj("/", ObjectType.Directory, 0)) var currentObj: Obj = fileSystem[0] for (i in 0..lines.size - 1) { //println("Current Line: " + lines[i]) //currentObj.children.forEach { println("Object under " + currentObj.objName + " | " + it.objName + " | " +it.objType.toString() + " | " + it.parent!!.objName) } var parts = lines[i].split(" ") when (parts[0]) { "$" -> { when (parts[1]) { "cd" -> { when (parts[2]) { "/" -> { // Go to root //println("Changing current obj to root") currentObj = fileSystem[0] } ".." -> { //println("Changing current obj to parent " + currentObj.parent!!.objName) currentObj = currentObj.parent!! } else -> { var target = currentObj.children.filter { it.objName == parts[2] }.first() //println("Changing current obj to " + target.objName) currentObj = target } } } "ls" -> { //println("Listing directory: " + currentObj.objName) var nextCommandLine = lines.slice(i+1..lines.size - 1).indexOfFirst { it.split(" ")[0] == "$" } + i + 1 if (i == nextCommandLine) { nextCommandLine = lines.size } //println("nextCommandLine is " + nextCommandLine.toString()) //println("i is " + i.toString()) for (idx in i+1..nextCommandLine - 1) { var lsParts = lines[idx].split(" ") when (lsParts[0]) { "dir" -> { if (currentObj.children.filter { it.objName == lsParts[1] && it.objType == ObjectType.Directory }.count() == 0) { //println("Adding directory: " + lsParts[1] + " to " + currentObj.objName) currentObj.children.add(Obj(lsParts[1], ObjectType.Directory, 0, currentObj)) } } else -> { if (currentObj.children.filter { it.objName == lsParts[1] && it.objType == ObjectType.File }.count() == 0) { //println("Adding file: " + lsParts[1] + " to " + currentObj.objName) currentObj.children.add(Obj(lsParts[1], ObjectType.File, lsParts[0].toInt(), currentObj)) } } } } } } } else -> { // This is a file print("") } } } println("------------") printStructure(fileSystem[0], 0) var sizes = getDirectoriesWithSizes(fileSystem[0]) sizes.sortByDescending { it.size } sizes.forEach { println(it.path + " | " + it.size.toString()) } println("Part 1 size: " + sizes.filter { it.size < 100000 }.sumOf { it.size }.toString()) var freeSpace = 70000000 - sizes[0].size println("Total Free Space is " + freeSpace.toString()) var validSizes = sizes.filter { it.size + freeSpace > 30000000 }.toMutableList() validSizes.sortBy { it.size } validSizes.forEach { println("Valid Size: " + it.path + " | " + it.size.toString()) } println("Smallest Directory To Achieve Goal is " + validSizes[0].path.toString() + " | " + validSizes[0].size.toString()) } fun printStructure(obj: Obj, level: Int) { var indent = "" for (i in 0..level) { indent += " " } indent += "- " if (obj.objType == ObjectType.Directory) { println(indent + obj.objName) } else { println(indent + obj.objName + " | " + obj.objSize.toString()) } obj.children.forEach { printStructure(it, level + 1) } } fun getDirectoriesWithSizes(obj: Obj): MutableList<DirectoryInfo> { var directorySizes: MutableList<DirectoryInfo> = mutableListOf() if (obj.objType == ObjectType.Directory) { directorySizes.add(DirectoryInfo(obj.objName, 0)) } obj.children.forEach { if (it.objType == ObjectType.Directory) { directorySizes.add(DirectoryInfo(it.objName, 0)) } else { directorySizes[0].size += it.objSize } } obj.children.forEach { if (it.objType == ObjectType.Directory) { var childSizes = getDirectoriesWithSizes(it) directorySizes[0].size += childSizes[0].size directorySizes.addAll(childSizes) } } return directorySizes.filter { it.size > 0 }.toMutableList() } enum class ObjectType { Directory, File } class DirectoryInfo(path: String, size: Int) { var path: String = path var size: Int = size } class Obj(objName: String, objType: ObjectType, objSize: Int, parent: Obj? = null) { var objName: String = objName var objType: ObjectType = objType var objSize: Int = objSize var children: MutableList<Obj> = mutableListOf() var parent: Obj? = parent }
0
Kotlin
0
1
fd5414c3ab919913ed0cd961348c8644db0330f4
6,344
advent-of-code-22
Apache License 2.0
src/main/kotlin/com/github/davio/aoc/y2020/Day19.kt
Davio
317,510,947
false
{"Kotlin": 405939}
package com.github.davio.aoc.y2020 import com.github.davio.aoc.general.Day import com.github.davio.aoc.general.call import com.github.davio.aoc.general.getInputAsSequence import kotlin.system.measureTimeMillis fun main() { measureTimeMillis { Day19.getResult() }.call { println("$it ms") } } object Day19 : Day() { /* * --- Day 19: Monster Messages --- You land in an airport surrounded by dense forest. As you walk to your high-speed train, * the Elves at the Mythical Information Bureau contact you again. * They think their satellite has collected an image of a sea monster! * Unfortunately, the connection to the satellite is having problems, * and many of the messages sent back from the satellite have been corrupted. They sent you a list of the rules valid messages should obey and a list of received messages they've collected so far (your puzzle input). The rules for valid messages (the top part of your puzzle input) are numbered and build upon each other. For example: 0: 1 2 1: "a" 2: 1 3 | 3 1 3: "b" Some rules, like 3: "b", simply match a single character (in this case, b). The remaining rules list the sub-rules that must be followed; for example, the rule 0: 1 2 means that to match rule 0, * the text being checked must match rule 1, and the text after the part that matched rule 1 must then match rule 2. Some of the rules have multiple lists of sub-rules separated by a pipe (|). This means that at least one list of sub-rules must match. * (The ones that match might be different each time the rule is encountered.) For example, the rule 2: 1 3 | 3 1 means that to match rule 2, * the text being checked must match rule 1 followed by rule 3 or it must match rule 3 followed by rule 1. Fortunately, there are no loops in the rules, so the list of possible matches will be finite. Since rule 1 matches a and rule 3 matches b, * rule 2 matches either ab or ba. Therefore, rule 0 matches aab or aba. Here's a more interesting example: 0: 4 1 5 1: 2 3 | 3 2 2: 4 4 | 5 5 3: 4 5 | 5 4 4: "a" 5: "b" Here, because rule 4 matches a and rule 5 matches b, rule 2 matches two letters that are the same (aa or bb), * and rule 3 matches two letters that are different (ab or ba). Since rule 1 matches rules 2 and 3 once each in either order, it must match two pairs of letters, * one pair with matching letters and one pair with different letters. * This leaves eight possibilities: aaab, aaba, bbab, bbba, abaa, abbb, baaa, or babb. Rule 0, therefore, matches a (rule 4), then any of the eight options from rule 1, then b (rule 5): * aaaabb, aaabab, abbabb, abbbab, aabaab, aabbbb, abaaab, or ababbb. The received messages (the bottom part of your puzzle input) need to be checked against the rules so you can determine which are valid * and which are corrupted. Including the rules and the messages together, this might look like: 0: 4 1 5 1: 2 3 | 3 2 2: 4 4 | 5 5 3: 4 5 | 5 4 4: "a" 5: "b" ababbb bababa abbbab aaabbb aaaabbb Your goal is to determine the number of messages that completely match rule 0. In the above example, ababbb and abbbab match, * but bababa, aaabbb, and aaaabbb do not, producing the answer 2. * The whole message must match all of rule 0; there can't be extra unmatched characters in the message. * (For example, aaaabbb might appear to match rule 0 above, but it has an extra unmatched b on the end.) How many messages completely match rule 0? * * --- Part Two --- As you look over the list of messages, you realize your matching rules aren't quite right. * To fix them, completely replace rules 8: 42 and 11: 42 31 with the following: 8: 42 | 42 8 11: 42 31 | 42 11 31 This small change has a big impact: now, the rules do contain loops, and the list of messages they could hypothetically match is infinite. * You'll need to determine how these changes affect which messages are valid. Fortunately, many of the rules are unaffected by this change; * it might help to start by looking at which rules always match the same set of values and how those rules * (especially rules 42 and 31) are used by the new versions of rules 8 and 11. (Remember, you only need to handle the rules you have; * building a solution that could handle any hypothetical combination of rules would be significantly more difficult.) For example: 42: 9 14 | 10 1 9: 14 27 | 1 26 10: 23 14 | 28 1 1: "a" 11: 42 31 5: 1 14 | 15 1 19: 14 1 | 14 14 12: 24 14 | 19 1 16: 15 1 | 14 14 31: 14 17 | 1 13 6: 14 14 | 1 14 2: 1 24 | 14 4 0: 8 11 13: 14 3 | 1 12 15: 1 | 14 17: 14 2 | 1 7 23: 25 1 | 22 14 28: 16 1 4: 1 1 20: 14 14 | 1 15 3: 5 14 | 16 1 27: 1 6 | 14 18 14: "b" 21: 14 1 | 1 14 25: 1 1 | 1 14 22: 14 14 8: 42 26: 14 22 | 1 20 18: 15 15 7: 14 5 | 1 21 24: 14 1 abbbbbabbbaaaababbaabbbbabababbbabbbbbbabaaaa bbabbbbaabaabba babbbbaabbbbbabbbbbbaabaaabaaa aaabbbbbbaaaabaababaabababbabaaabbababababaaa bbbbbbbaaaabbbbaaabbabaaa bbbababbbbaaaaaaaabbababaaababaabab ababaaaaaabaaab ababaaaaabbbaba baabbaaaabbaaaababbaababb abbbbabbbbaaaababbbbbbaaaababb aaaaabbaabaaaaababaa aaaabbaaaabbaaa aaaabbaabbaaaaaaabbbabbbaaabbaabaaa babaaabbbaaabaababbaabababaaab aabbbbbaabbbaaaaaabbbbbababaaaaabbaaabba Without updating rules 8 and 11, these rules only match three messages: bbabbbbaabaabba, ababaaaaaabaaab, and ababaaaaabbbaba. However, after updating rules 8 and 11, a total of 12 messages match: bbabbbbaabaabba babbbbaabbbbbabbbbbbaabaaabaaa aaabbbbbbaaaabaababaabababbabaaabbababababaaa bbbbbbbaaaabbbbaaabbabaaa bbbababbbbaaaaaaaabbababaaababaabab ababaaaaaabaaab ababaaaaabbbaba baabbaaaabbaaaababbaababb abbbbabbbbaaaababbbbbbaaaababb aaaaabbaabaaaaababaa aaaabbaabbaaaaaaabbbabbbaaabbaabaaa aabbbbbaabbbaaaaaabbbbbababaaaaabbaaabba After updating rules 8 and 11, how many messages completely match rule 0? */ private val input = getInputAsSequence() private val rules = hashMapOf<Int, Rule>() private val characterRegex = Regex("\"([a-z])\"") private const val maxRecursionDepth = 20 fun getResult() { input.count { line -> if (line.isNotBlank() && line[0].isDigit()) { when (line) { "8: 42" -> { parseRule("8: 42 | 42 8") } "11: 42 31" -> { parseRule("11: 42 31 | 42 11 31") } else -> { parseRule(line) } } false } else if (line.isNotBlank() && line[0].isLetter()) { rules[0]!!.toRegex().matches(line) } else { false } }.call { println(it) } } private fun parseRule(line: String) { val lineParts = line.split(":") val ruleNumber = lineParts[0].toInt() val rulePart = lineParts[1].trim() val characterMatcher = characterRegex.matchEntire(rulePart) val rule = rules.computeIfAbsent(ruleNumber) { Rule(ruleNumber) } if (characterMatcher != null) { rule.char = characterMatcher.groupValues[1][0] } else { val ruleParts = rulePart.split("|") ruleParts.forEachIndexed { index, rulesAtSide -> val otherRuleNumbers = rulesAtSide.trim().split(" ") otherRuleNumbers.forEach { otherRuleNumber -> rule.addRule(rules.computeIfAbsent(otherRuleNumber.toInt()) { Rule(ruleNumber) }, index) } } } } private class Rule(val number: Int) { var subRules = ArrayList<MutableList<Rule>>(2) var char: Char? = null var regex: Regex? = null init { subRules.add(arrayListOf()) subRules.add(arrayListOf()) } fun addRule(rule: Rule, index: Int) { subRules[index].add(rule) } fun toRegex(recursionDepth: Int = 0): Regex { if (regex != null) { return regex!! } regex = when { char != null -> Regex("$char") else -> { val leftHandSide = subRules[0].map { it.toRegex(recursionDepth + 1) }.joinToString("") if (subRules[1].isEmpty()) { Regex(leftHandSide) } else { val rightHandSide = subRules[1].map { if (it.number != number || recursionDepth < maxRecursionDepth) { it.toRegex(recursionDepth + 1) } else { "" } }.joinToString("") Regex("(?:$leftHandSide|$rightHandSide)") } } } return regex!! } } }
1
Kotlin
0
0
4fafd2b0a88f2f54aa478570301ed55f9649d8f3
8,968
advent-of-code
MIT License
2021/src/main/kotlin/de/skyrising/aoc2021/day8/solution.kt
skyrising
317,830,992
false
{"Kotlin": 411565}
package de.skyrising.aoc2021.day8 import de.skyrising.aoc.* val test = TestInput(""" be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef | cg cg fdcagb cbg fbegcd cbd adcefb dageb afcb bc aefdc ecdab fgdeca fcdbega | efabcd cedba gadfec cb aecbfdg fbg gf bafeg dbefa fcge gcbea fcaegb dgceab fcbdga | gecf egdcabf bgf bfgea fgeab ca afcebg bdacfeg cfaedg gcfdb baec bfadeg bafgc acf | gebdcfa ecba ca fadegcb dbcfg fgd bdegcaf fgec aegbdf ecdfab fbedc dacgb gdcebf gf | cefg dcbef fcge gbcadfe bdfegc cbegaf gecbf dfcage bdacg ed bedf ced adcbefg gebcd | ed bcgafe cdgba cbgef egadfb cdbfeg cegd fecab cgb gbdefca cg fgcdab egfdb bfceg | gbdfcae bgc cg cgb gcafb gcf dcaebfg ecagb gf abcdeg gaef cafbge fdbac fegbdc | fgae cfgab fg bagc """) @PuzzleName("Seven Segment Search") fun PuzzleInput.part1(): Any { var count = 0 for (line in lines) { val (_, output) = line.split(" | ", limit=2) val outputs = output.split(' ') for (o in outputs) { when (o.length) { 2, 3, 4, 7 -> count++ } } } return count } fun PuzzleInput.part2(): Any { var sum = 0 for (line in lines) { val signalToNumber = mutableMapOf<String, Int>() val numberToSignal = Array<String?>(10) { null } val (signal, output) = line.split(" | ", limit=2) val signals = signal.split(' ').map(String::sort) val segmentCount = IntArray(7) for (s in signals) { when (s.length) { // 1, 4, 7, 8 2 -> { signalToNumber[s] = 1 numberToSignal[1] = s } 3 -> { signalToNumber[s] = 7 numberToSignal[7] = s } 4 -> { signalToNumber[s] = 4 numberToSignal[4] = s } 7 -> { signalToNumber[s] = 8 numberToSignal[8] = s } } for (seg in s) { segmentCount[seg - 'a']++ } } val f = 'a' + segmentCount.findIndex { _, n -> n == 9 }!! val e = 'a' + segmentCount.findIndex { _, n -> n == 4 }!! val d = 'a' + segmentCount.findIndex { idx, n -> n == 7 && ('a' + idx) in numberToSignal[4]!! }!! for (s in signals) { if (s in signalToNumber) continue when (s.length) { 5 -> { // 2, 3, 5 var contains7 = true for (seg in numberToSignal[7]!!) { if (seg !in s) { contains7 = false break } } if (contains7) { signalToNumber[s] = 3 numberToSignal[3] = s } else if (f in s) { signalToNumber[s] = 5 numberToSignal[5] = s } else { signalToNumber[s] = 2 numberToSignal[2] = s } } 6 -> { // 0, 6, 9 if (d !in s) { signalToNumber[s] = 0 numberToSignal[0] = s } else if (e in s) { signalToNumber[s] = 6 numberToSignal[6] = s } else { signalToNumber[s] = 9 numberToSignal[9] = s } } } } val outputs = output.split(' ') sum += (signalToNumber[outputs[0].sort()] ?: 0) * 1000 sum += (signalToNumber[outputs[1].sort()] ?: 0) * 100 sum += (signalToNumber[outputs[2].sort()] ?: 0) * 10 sum += (signalToNumber[outputs[3].sort()] ?: 0) * 1 } return sum } fun String.sort(): String { val chars = this.toCharArray() chars.sort() return chars.concatToString() } fun IntArray.findIndex(predicate: (Int, Int) -> Boolean): Int? { for (i in this.indices) { if (predicate(i, this[i])) return i } return null }
0
Kotlin
0
0
19599c1204f6994226d31bce27d8f01440322f39
4,471
aoc
MIT License
src/main/kotlin/g1301_1400/s1397_find_all_good_strings/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g1301_1400.s1397_find_all_good_strings // #Hard #String #Dynamic_Programming #String_Matching // #2023_06_06_Time_273_ms_(100.00%)_Space_36.3_MB_(100.00%) @Suppress("NAME_SHADOWING", "UNUSED_PARAMETER") class Solution { private val mod = 1000000007 private lateinit var next: IntArray fun findGoodStrings(n: Int, s1: String, s2: String, evil: String): Int { var s1 = s1 val s1arr = s1.toCharArray() for (i in s1.length - 1 downTo 0) { if (s1arr[i] > 'a') { s1arr[i] = (s1arr[i].code - 1).toChar() break } else { s1arr[i] = 'z' } } s1 = String(s1arr) next = getNext(evil) return if (s1.compareTo(s2) > 0) { lessOrEqualThan(s2, evil) } else (lessOrEqualThan(s2, evil) - lessOrEqualThan(s1, evil) + mod) % mod } private fun lessOrEqualThan(s: String, e: String): Int { val dp = Array(s.length + 1) { Array(e.length + 1) { LongArray(2) } } dp[0][0][1] = 1 var res: Long = 0 for (i in 0 until s.length) { for (state in 0 until e.length) { run { var c = 'a' while (c <= 'z') { val nextstate = getNextState(state, c, e) dp[i + 1][nextstate][0] = (dp[i + 1][nextstate][0] + dp[i][state][0]) % mod c++ } } var c = 'a' while (c < s[i]) { val nextstate = getNextState(state, c, e) dp[i + 1][nextstate][0] = (dp[i + 1][nextstate][0] + dp[i][state][1]) % mod c++ } val nextstate = getNextState(state, s[i], e) dp[i + 1][nextstate][1] = (dp[i + 1][nextstate][1] + dp[i][state][1]) % mod } } for (i in 0 until e.length) { res = (res + dp[s.length][i][0]) % mod res = (res + dp[s.length][i][1]) % mod } return res.toInt() } private fun getNextState(prevState: Int, nextChar: Char, evil: String): Int { var idx = prevState while (idx != -1 && evil[idx] != nextChar) { idx = next[idx] } return idx + 1 } private fun getNext(e: String): IntArray { val len = e.length val localNext = IntArray(len) localNext[0] = -1 var last = -1 var i = 0 while (i < len - 1) { if (last == -1 || e[i] == e[last]) { i++ last++ localNext[i] = last } else { last = localNext[last] } } return localNext } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,805
LeetCode-in-Kotlin
MIT License
src/main/kotlin/net/maizegenetics/phgv2/pathing/MostLikelyParents.kt
maize-genetics
696,835,682
false
{"Kotlin": 766953, "Shell": 262}
package net.maizegenetics.phgv2.pathing import net.maizegenetics.phgv2.api.HaplotypeGraph import net.maizegenetics.phgv2.api.ReferenceRange import net.maizegenetics.phgv2.api.SampleGamete /** * Given a set of read mappings, finds the most likely parents in a stepwise fashion. The parent with the most reads * is selected as a likely parent. Then, the subset of reads not mapping to that parent is created. * The parent with the most reads from that subset is then added to the list of likely parents. * The process is repeated until the number of likely parents = maxParents, coverage is equal to or greater than minCoverage, * or until all parents have been added to the list, whichever occurs first. Coverage is calculated as the number * of reads mapping to any of the likely parents divided by the total number of reads. */ class MostLikelyParents(val hapGraph: HaplotypeGraph) { //list of parents, which are the sampleGametes present in the HaplotypeGraph private val myParentList: List<SampleGamete> = hapGraph.sampleGametesInGraph().toList() data class ParentStats(val parent: SampleGamete, val readCount: Int, val coverage: Double) /** * Finds the most likely parents for a set of hapid counts from read mappings. */ fun findMostLikelyParents(refRangeToHapIdListCounts: Map<ReferenceRange, Map<List<String>, Int>>, maxParents: Int, minCoverage: Double) : List<ParentStats> { //convert refRangeToHapIdSetCounts to a Map<ReferenceRange,List<HapIdSetCount>> //use only the counts for ranges that are present in myParentToHapidMap val rangesInGraph = hapGraph.ranges() var filteredCounts = refRangeToHapIdListCounts.filter { (refrange, _) -> rangesInGraph.contains(refrange) } val bestParentList = mutableListOf<ParentStats>() var iteration = 0 var coverage = 0.0 //total Count of reads, which is the sum of the read counts for each reference range (outer sum) val totalCount = filteredCounts.map {(_,setCounts) -> setCounts.values }.flatten().sum() var cumulativeCount = 0 while (iteration < maxParents && coverage < minCoverage) { iteration++ var bestParent = SampleGamete("none", 0) var highestCount = 0 for (parent in myParentList) { //get count for this parent val parentCount = filteredCounts.keys.sumOf { refrange -> val hapid = hapGraph.sampleToHapId(refrange, parent) if (hapid == null) 0 else filteredCounts[refrange]!!.filter { it.key.contains(hapid) }.entries.sumOf { it.value } } if (parentCount > highestCount) { highestCount = parentCount bestParent = parent } } cumulativeCount += highestCount coverage = cumulativeCount / totalCount.toDouble() bestParentList.add(ParentStats(bestParent, highestCount, coverage)) //rebuild the filteredList using only hapIdSetCounts that do not contain the best parent //this will be used for the next round filteredCounts = filteredCounts.keys.map { refrange -> //for each refrange count parent use val hapid = hapGraph.sampleToHapId(refrange, bestParent) val filteredList = filteredCounts[refrange]!!.filter { !it.key.contains(hapid) } Pair(refrange, filteredList) }.filter { it.second.isNotEmpty() }.toMap() } return bestParentList } }
1
Kotlin
0
3
4a97577424042322de5ed9f1e40b43116679f14f
3,689
phg_v2
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/DesignHashSet.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.BitSet import kotlin.math.abs interface DesignHashSet { fun add(key: Int) fun remove(key: Int) fun contains(key: Int): Boolean } class DesignHashSetBitSet : DesignHashSet { private val bitSet = BitSet(BITS + 1) override fun add(key: Int) { bitSet[key] = true } override fun remove(key: Int) { bitSet[key] = false } override fun contains(key: Int): Boolean { return bitSet[key] } companion object { private const val BITS = 1_000_000 } } class DesignHashSetSimple : DesignHashSet { private var buckets = Array<MutableList<Int>>(INITIAL_CAPACITY) { mutableListOf() } private var threshold = INITIAL_CAPACITY * LOAD_FACTOR private var count = 0 override fun add(key: Int) { if (!contains(key)) { buckets[index(key)].add(key) count++ if (count >= threshold) { rebalanced() } } } override fun remove(key: Int) { buckets[index(key)].remove(key) count-- } override fun contains(key: Int): Boolean { return buckets[index(key)].contains(key) } private fun index(key: Int): Int { return abs(key.hashCode()) % buckets.size } private fun rebalanced() { val newBuckets = Array<MutableList<Int>>(buckets.size * 2) { mutableListOf() } buckets.forEach { list -> list.forEach { key -> newBuckets[key.hashCode() % newBuckets.size].add(key) } } buckets = newBuckets threshold = buckets.size * LOAD_FACTOR } companion object { private const val INITIAL_CAPACITY = 16 private const val LOAD_FACTOR = 0.75 } } class DesignHashSetImpl : DesignHashSet { private var capacity = DEFAULT_CAPACITY private var cnt = 0 var list = arrayOfNulls<DesignList>(capacity) init { for (i in 0 until capacity) { list[i] = DesignList() } } override fun add(key: Int) { if (contains(key)) return if (cnt < capacity) { addTail(key) } else { // rehash capacity *= 2 val copy = list val newList = arrayOfNulls<DesignList>(capacity) for (i in 0 until capacity) { newList[i] = DesignList() } list = newList for (i in copy.indices) { var head: DesignListNode? = copy[i]!!.head while (head!!.next != null && head.next?.value != null) { addTail(head.next?.value!!) head = head.next } } addTail(key) } cnt++ } override fun remove(key: Int) { if (!contains(key)) return cnt-- val idx = key % capacity var head: DesignListNode? = list[idx]!!.head while (head!!.next != null && head.next?.value != null) { if (head.next?.value == key) { val next = head.next next!!.next?.pre = head head.next = next.next next.pre = null next.next = null break } head = head.next } } override fun contains(key: Int): Boolean { val idx = key % capacity var head: DesignListNode? = list[idx]!!.head while (head!!.next != null && head.next?.value != null) { if (head.next?.value == key) return true head = head.next } return false } private fun addTail(key: Int) { val idx = key % capacity val tail = list[idx]!!.tail val pre: DesignListNode = tail.pre ?: return val cur = DesignListNode(key) pre.next = cur cur.pre = pre cur.next = tail tail.pre = cur } companion object { private const val DEFAULT_CAPACITY = 32 } } class DesignList { var head = DesignListNode() var tail = DesignListNode() init { head.next = tail tail.pre = head } } data class DesignListNode(var value: Int? = null) { var next: DesignListNode? = null var pre: DesignListNode? = null }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
4,924
kotlab
Apache License 2.0
kotlin/src/com/s13g/aoc/aoc2023/Day2.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2023 import com.s13g.aoc.Result import com.s13g.aoc.Solver import kotlin.math.max import com.s13g.aoc.mul import com.s13g.aoc.resultFrom /** * --- Day 2: Cube Conundrum --- * https://adventofcode.com/2023/day/2 */ class Day2 : Solver { override fun solve(lines: List<String>): Result { val solutions = lines.mapIndexed { idx, line -> calculate(line, idx + 1) } return resultFrom( solutions.sumOf { it.first }, solutions.sumOf { it.second }) } private fun calculate(line: String, game: Int): Pair<Int, Int> { var partA = game val maxN = mutableMapOf("red" to 0, "green" to 0, "blue" to 0) val sets = line.split(": ")[1].split("; ").map { it.split(", ") } for (set in sets) { for (pair in set) { val split = pair.split(" ") val num = split[0].toInt() val color = split[1] maxN[color] = max(maxN[color]!!, num) if (color == "red" && num > 12) partA = 0 if (color == "green" && num > 13) partA = 0 if (color == "blue" && num > 14) partA = 0 } } return Pair(partA, maxN.values.toList().mul()) } }
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
1,141
euler
Apache License 2.0
archive/2022/Day02.kt
mathijs81
572,837,783
false
{"Kotlin": 167658, "Python": 725, "Shell": 57}
package aoc2022 private const val EXPECTED_1 = 15 private const val EXPECTED_2 = 12 private val SCORES = listOf( 3, 0, 6, 6, 3, 0, 0, 6, 3, ) private class Day02(isTest: Boolean) : Solver(isTest) { fun part1(): Any { var sum = 0 for (line in readAsLines()) { val player2 = line[0] - 'A' val player1 = line[2] - 'X' sum += player1 + 1 + SCORES[player1 * 3 + player2] } return sum } fun part2(): Any { var sum = 0 for (line in readAsLines()) { val player2 = line[0] - 'A' val outcome = line[2] - 'X' val intendedScore = outcome * 3 var playSymbol = 0 var index = player2 while (SCORES[index] != intendedScore) { index += 3 playSymbol ++ } sum += playSymbol + 1 + intendedScore } return sum } } fun main() { val testInstance = Day02(true) val instance = Day02(false) testInstance.part1().let { check(it == EXPECTED_1) { "part1: $it != $EXPECTED_1" } } println(instance.part1()) testInstance.part2().let { check(it == EXPECTED_2) { "part2: $it != $EXPECTED_1" } } println(instance.part2()) }
0
Kotlin
0
2
92f2e803b83c3d9303d853b6c68291ac1568a2ba
1,286
advent-of-code-2022
Apache License 2.0
src/main/kotlin/g2501_2600/s2584_split_the_array_to_make_coprime_products/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2501_2600.s2584_split_the_array_to_make_coprime_products // #Hard #Array #Hash_Table #Math #Number_Theory // #2023_07_11_Time_341_ms_(100.00%)_Space_45.6_MB_(100.00%) class Solution { private fun fillDivideArray() { for (i in 1 until divideTo.size) { divideTo[i] = i } var i = 2 while (i * i < divideTo.size) { if (divideTo[i] != i) { i++ continue } var j = i + i while (j < divideTo.size) { if (divideTo[j] == j) { divideTo[j] = i } j += i } i++ } } fun findValidSplit(nums: IntArray): Int { if (divideTo[1] == 0) { fillDivideArray() } val dMap: MutableMap<Int, Int> = HashMap() val dividers: Array<MutableList<Int>?> = arrayOfNulls(nums.size) for (i in nums.indices) { dividers[i] = ArrayList() while (nums[i] != 1) { dividers[i]?.add(divideTo[nums[i]]) dMap.put(divideTo[nums[i]], i) nums[i] = nums[i] / divideTo[nums[i]] } } var nextEnd = 0 var i = 0 while (i <= nextEnd) { for (j in dividers[i]!!.indices) { nextEnd = nextEnd.coerceAtLeast(dMap[dividers[i]!![j]]!!) } i++ } return if (i == nums.size) -1 else i - 1 } companion object { var divideTo = IntArray(1e6.toInt() + 1) } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,592
LeetCode-in-Kotlin
MIT License
src/main/kotlin/com/jaspervanmerle/aoc2021/day/Day10.kt
jmerle
434,010,865
false
{"Kotlin": 60581}
package com.jaspervanmerle.aoc2021.day class Day10 : Day("390993", "2391385187") { private val lines = input.lines() private val openCharacterByClosing = mapOf( ')' to '(', ']' to '[', '}' to '{', '>' to '<' ) private val errorScoreByCharacter = mapOf( ')' to 3L, ']' to 57L, '}' to 1197L, '>' to 25137L ) private val incompleteScoreByCharacter = mapOf( '(' to 1L, '[' to 2L, '{' to 3L, '<' to 4L ) override fun solvePartOne(): Any { return lines .map { getScore(it) } .filter { !it.first } .sumOf { it.second } } override fun solvePartTwo(): Any { val incompleteScores = lines .map { getScore(it) } .filter { it.first } .map { it.second } .sorted() return incompleteScores[incompleteScores.size / 2] } private fun getScore(line: String): Pair<Boolean, Long> { val stack = ArrayDeque<Char>() for (char in line) { if (char in openCharacterByClosing.keys) { val last = stack.removeLast() if (last != openCharacterByClosing[char]) { return false to errorScoreByCharacter[char]!! } } else { stack.add(char) } } var incompleteScore = 0L while (!stack.isEmpty()) { incompleteScore *= 5L incompleteScore += incompleteScoreByCharacter[stack.removeLast()]!! } return true to incompleteScore } }
0
Kotlin
0
0
dcac2ac9121f9bfacf07b160e8bd03a7c6732e4e
1,654
advent-of-code-2021
MIT License
src/main/kotlin/com/nibado/projects/advent/y2016/Day17.kt
nielsutrecht
47,550,570
false
null
package com.nibado.projects.advent.y2016 import com.nibado.projects.advent.Day import com.nibado.projects.advent.Direction import com.nibado.projects.advent.Hash import com.nibado.projects.advent.Point object Day17 : Day { private val dirMap = mapOf("D" to Direction.SOUTH, "U" to Direction.NORTH, "R" to Direction.EAST, "L" to Direction.WEST) private val input = "hhhxzeay" private val solution : Pair<String, String> by lazy { solve() } override fun part1() = solution.first override fun part2() = solution.second.length.toString() private fun solve() : Pair<String, String> { val solutions = mutableListOf<String>() search("", Point(0, 0), solutions) return solutions.minByOrNull { it.length }!! to solutions.maxByOrNull { it.length }!! } private fun search(path: String, current: Point, solutions: MutableList<String>) { if(current == Point(3, 3)) { solutions += path return } val md5 = Hash.md5(input + path) val next = directions(md5) .map { it.first to current.plus(it.second) } .filter { it.second.inBound(3,3) } next.forEach { search(path + it.first, it.second, solutions) } } private fun directions(md5: String) = listOf("U", "D", "L", "R").filterIndexed { i, _ -> md5[i] in 'b' .. 'f'}.map { it to dirMap[it]!! } }
1
Kotlin
0
15
b4221cdd75e07b2860abf6cdc27c165b979aa1c7
1,415
adventofcode
MIT License
advent-of-code-2020/src/test/java/aoc/Day21AllergenAssessment.kt
yuriykulikov
159,951,728
false
{"Kotlin": 1666784, "Rust": 33275}
package aoc import org.assertj.core.api.Assertions.assertThat import org.junit.Test inline class Ingredient(val value: String) inline class Allergen(val value: String) class Day21AllergenAssessment { /** * * Each allergen is found in exactly one ingredient. * Each ingredient contains **zero** or one allergen. * * Allergens aren't always marked; when they're listed (as in (contains nuts, shellfish) after an ingredients list), * the ingredient that contains each listed allergen will be somewhere in the corresponding ingredients list. * However, even if an allergen isn't listed, the ingredient that contains that allergen could still be present. * * The first food in the list has four ingredients (written in a language you don't understand): mxmxvkd, kfcds, sqjhc, and nhms. * While the food might contain other allergens, a few allergens the food definitely contains are listed afterward: dairy and fish. * * The first step is to determine which ingredients can't possibly contain any of the allergens in any food in your list. 0000000000000000000000000000000000000000 * In the above example, none of the ingredients kfcds, nhms, sbzzf, or trh can contain an allergen. * Counting the number of times any of these ingredients appear in any ingredients list produces 5: * they all appear once each except sbzzf, which appears twice. * * Determine which ingredients cannot possibly contain any of the allergens in your list. How many times do any of those ingredients appear? */ @Test fun silverTest() { assertThat(countAllergenFreeIngredients(testInput)).isEqualTo(5) } @Test fun silver() { assertThat(countAllergenFreeIngredients(taskInput)).isEqualTo(1882) } @Test fun goldTest() { assertThat(canonicalDangerousIngredientList(testInput)).isEqualTo("mxmxvkd,sqjhc,fvjkl") } @Test fun gold() { assertThat(canonicalDangerousIngredientList(taskInput)).isEqualTo("xgtj,ztdctgq,bdnrnx,cdvjp,jdggtft,mdbq,rmd,lgllb") } private fun countAllergenFreeIngredients(input: String): Int { val ingredientsAndAllergens: List<Pair<List<Ingredient>, List<Allergen>>> = parse(input) val allergenToIngredient = findMatches(ingredientsAndAllergens) val allergic = allergenToIngredient.values.toSet() return ingredientsAndAllergens.flatMap { it.first } .count { it !in allergic } } private fun canonicalDangerousIngredientList(input: String): String { val ingredientsAndAllergens: List<Pair<List<Ingredient>, List<Allergen>>> = parse(input) return findMatches(ingredientsAndAllergens) .entries .sortedBy { (allergen, ingredient) -> allergen.value } .joinToString(",") { (allergen, ingredient) -> ingredient.value } } private fun findMatches(ingredientsAndAllergens: List<Pair<List<Ingredient>, List<Allergen>>>) = ingredientsAndAllergens .flatMap { (ingredients, allergens) -> allergens.map { allergen -> allergen to ingredients } } .groupBy( keySelector = { (allergen, ingredients) -> allergen }, valueTransform = { (allergen: Allergen, ingredients: List<Ingredient>) -> ingredients.toSet() } ) .mapValues { (allergen, ingredientsCandidates) -> ingredientsCandidates.reduce { l, r -> l.intersect(r) } } .entries .sortedBy { (allergen, possibleIngredients) -> possibleIngredients.size } .onEach { println(it) } .fold(setOf()) { confirmed: Set<Pair<Allergen, Ingredient>>, (allergen, ingredients) -> val possibleIngredients = ingredients.minus(confirmed.map { it.second }) possibleIngredients.firstOrNull() // found match ?.let { confirmed.plus(allergen to it) } ?: confirmed }.toMap() private fun parse(input: String) = input.lines().map { line -> require(line.contains("(contains")) val ingredients: List<Ingredient> = line.substringBefore(" (").split(" ").map { Ingredient(it) } val allergens: List<Allergen> = line.substringAfter("(contains ").removeSuffix(")").split(", ").map { Allergen(it) } ingredients to allergens } private val testInput = """ mxmxvkd kfcds sqjhc nhms (contains dairy, fish) trh fvjkl sbzzf mxmxvkd (contains dairy) sqjhc fvjkl (contains soy) sqjhc mxmxvkd sbzzf (contains fish) """.trimIndent() private val taskInput = """ dkgkc qxsgkzt zsqn mhlm lzxpk rmd bhxx gbzczpn jbxvkvf gqsj qpdb bdjxjvj rkcngr ztdctgq lgllb jlmlz qcrf vmz fllmxc krg rltc djsvj gxml prgh kcfjnr pjzqbc rqccts sgqj zclh xsfpzncj qqttxln mpqtc hzkdqz hxbl fgjxhf xlknfh mdbq dggmkht cdvjp dlgsd jbdqm xgtj lpts cz qrmvtk nhnsh jfddkg bdnrnx (contains nuts, shellfish, dairy) rjrn jzjhcm rtcdm pzcgr gvfsv bdnrnx djsvj ztdctgq dnrgnnr ffqndb gpmvkrt dzhf sndrz vmnfpd bzxvd xlknfh xtzqb jdggtft ckbsg fjndlnv qsqcjd vhsp jqhzc mdpql qdqfl dggmkht vgfknzx sjpcmz spqqb qpdb dkgkc lsnj bchsc rkcngr jfddkg ppb pzh lflv tzqxpq rglpnc zclh hcsmg qxsgkzt cdvjp dqxvmx vlsprc qhgg ztpvmk lgllb dfzbpz s<KEY> sjpx lvmm j<KEY> g<KEY> rqccts kjsll xgtj lzxz pllnld mxkfs mdbq nprb mbnr drpn dfvkm hxbl dzqvbsq kfft ccqf lcbbcb jtmlcg zsqn rltc cz dlgsd qddlv (contains fish, eggs, soy) fllmxc xsfpzncj jsqng tzzfktn jdggtft jfrkn cmzlkx dnrgnnr vtbdr qqttxln drpn jtmlcg rjrn rqccts rmd h<KEY> pzcgr ckbsg kspzjr l<KEY> jp<KEY> s<KEY> vl<KEY> x<KEY> jhcr cdvjp tpgm mvhlr xvbdz vgfknzx bdjxjvj kjsqxp jrkbs bzxvd fd<KEY> ztpvmk zclh hbxq rglpnc fgjxhf vsns dfvkm pjzqbc mnptn dkgkc qhkq cqlpzd kjsll (contains shellfish, nuts, dairy) fllmxc nhnsh rglpnc gqpdph lvmm dlgsd jsqng pjzqbc hbxq xsfpzncj fbllk qhkq hfmkj rmd xvmsx cglt jzppz qcrf cdvjp kkcz ckbsg cmzlkx mdms vrhrt xjgv zclh lsnj qddlv lmrbfm jqhzc jrkbs gzzb qxsgkzt jdggtft bdnrnx vpqxh rltc rjrn ztdctgq lgllb ppb rkcngr dzhf xqdl sbbkvr pkknn sjpx skhxhp kcfjnr jlhpkg xvbdz bhxx cz nbkdh djsvj vhsp dkgkc ghshq pzcgr xgtj kmkcksz jbxvkvf jpztz dzqvbsq cmrlm gmzjtc vgfknzx gqsj drrvln (contains eggs) gbzczpn tzhq kkcz ztdctgq rkcngr cglt jfrkn jtmlcg vpqxh xvbdz fdndh pzvbfr dfvkm vbxnml rglpnc gbv hxbl dfzbpz tpgm chbpkvt qhgg bdnrnx sjpcmz dnrgnnr qsqcjd sbbkvr jndts qxsgkzt mhlm zclh dkplsn zbqhtv fsmhfr kht vgsxs djsvj mxkfs bhxx mdbq jknscx jdggtft pzh mvhlr drrvln kcfjnr cmzlkx rdkvvnb vlsprc mxnjztb sjpx lgllb lzxz bdjxjvj dkgkc tjsvdhn jzppz fllmxc jrkbs xgtj hzrzc gqsj rqccts kspzjr sndrz cdvjp sgqj (contains peanuts, dairy) vtbdr qhgg bzxvd zbqhtv gsdm jknscx cglt fnr xtzqb rjrn lvmm ztdctgq lzxpk sjpx qglnp qpdb fdndh dggmkht jbxvkvf vsns nvdlxkc ggmcmz gzzb qcrf pllnld jbdqm pzvbfr lxhpmc jzjhcm sjfht jtmlcg sjxlr pbfzgfx xlknfh zsqn vbdnhp prgh dzqvbsq chbpkvt cdvjp qdqfl rmd rtcdm mdpql bdjxjvj gbzczpn kcfjnr vrhrt xgtj tzqxpq jrkbs dfzbpz jzppz mdbq bdnrnx lcbbcb pkknn lflv rglpnc dnrgnnr vmz jdggtft rkcngr sndrz ppb ffjb rqccts jqhzc mbnr lgdv vbxnml sdgjxm xmpqj cz (contains dairy, fish) jbxvkvf spqqb bzxvd mxkfs lvmm kjsll jlmlz ztdctgq dkgkc pzh xmpqj tzzfktn prgh jtmlcg lzxpk sjpcmz mkv vpqxh jqhzc rtcdm djsvj sjpx lgllb ghshq mdms lcbbcb jfrkn rjrn ggmcmz zzlfrts xtzqb mbnr jdggtft kspzjr tjxrc kmkcksz hcsmg jlhpkg cdvjp bdnrnx kjsqxp dlgsd tzhq xvmsx jzjhcm pjzqbc qdqfl skhxhp ktgf nsndth jdrlzk ngmk gqpdph dfvkm mhlm rmd jbdqm mdbq gqsj mvhlr (contains peanuts, soy, fish) qrmvtk hfmkj kkcz rmd qxsgkzt mdbq rhjhmvj cz pkknn jdrlzk nsndth ggmgdv tzhq xqdl gpmvkrt mpcsjs xvmsx xgtj mbnr mhlm xxzjz qdqfl zclh rjrn tjsvdhn vbxnml jjnd bmqvll ggmcmz kcfjnr jdggtft bchsc bdnrnx drrvln zsqn ckbsg tzzfktn pzh lgdv mkv gmzjtc jlmlz pzvbfr ztdctgq jfddkg fxbxj xlknfh lcbbcb nvdlxkc lpts fgjxhf lxhpmc cqlpzd tjxrc rdkvvnb xqsn dzhf qtsq qglnp bzxvd sjpcmz vpqxh zlqcps ppb lgllb vlsprc mvhlr jhcr (contains soy, fish) gpmvkrt vmz mnptn pbfzgfx bxv vbdnhp fllmxc tgtzx dkgkc cdvjp xmpqj jhcr mdms cqlpzd jpztz xlknfh kjsll xgtj bchsc bhxx rmd pjzqbc xsfpzncj mdbq mpcsjs kht dfvkm cmzlkx vrhrt jzppz sjpx rkcngr mhlm kspzjr prgh zbqhtv lgllb jdggtft pzh qglnp jlhpkg vpqxh bdnrnx mbnr (contains fish) gqsj vbdnhp xgtj ztdctgq gvfsv xxzjz jsqng gmzjtc hbxq spqqb fdndh mxkfs kjsll mvhlr lcbbcb sgqj pzh dggmkht bdnrnx jlhpkg zjj lgdv jhcr qtsq sjpcmz nbkdh mdpql rdkvvnb gsdm dzhf lgllb vbxnml jdggtft mpqtc ckbsg cdvjp mdbq kht hcsmg sjxlr chbpkvt pfmnx cmzlkx ppb mpcsjs jzjhcm qglnp gbv hzkdqz rtcdm zlqcps pjzqbc vmz dkgkc fxbxj xqdl kspzjr qhkq rqccts qpdb gqpdph zbqhtv djsvj xlknfh ggmcmz qrmvtk dkplsn vgfknzx bmqvll (contains nuts, eggs, fish) dzqvbsq vhsp kmkcksz vsns pzh mpqtc sndrz gzzb xtzqb vpqxh mdms bdnrnx tzhq ktgf djsvj lgdv tzzfktn qhkq qtsq jbdqm jndts rtcdm xxzjz vbdnhp lmrbfm mxnjztb sjfht bchsc sjxlr vmz drpn spqqb mdbq gbzczpn dnrgnnr gbv pllnld cdvjp qhgg ggmcmz cmrlm qddlv lvmm kfft tzqxpq gsdm vlsprc jdggtft xgtj zsqn kjsll pzcgr kjsqxp fxbxj dkplsn ffjb gmzjtc xqdl mdpql dqxvmx fnr jhcr cglt gqsj gbcsmlr tjxrc dkgkc lflv bxv xqsn hxbl jjnd sjpcmz qcrf jzjhcm pjzqbc jlhpkg vtbdr qdqfl chbpkvt mpcsjs lxhpmc gqpdph rmd kspzjr ztdctgq prgh jsqng vgfknzx fgfl bdjxjvj nxc lcbbcb (contains fish) fgfl kcfjnr fdndh fjndlnv gbv ktgf kht skhxhp chbpkvt qpdb mdbq vrhrt nvdlxkc mxnjztb jdggtft lgdv rltc bdnrnx vpqxh hzkdqz ztdctgq sdgjxm jjnd dlgsd spqqb sjpx rmd nprb vmz bhxx cqlpzd pjzqbc mkv qxsgkzt xgtj fllmxc zjj jzppz tjxrc gxml fbllk rqccts hxbl qhgg lgllb mdms gpmvkrt ggmgdv tgtzx ghshq nbkdh pgdb bxv drrvln rglpnc jknscx dzqvbsq (contains peanuts, eggs, fish) lgdv nbkdh dggmkht qcrf kspzjr qpdb lpts drrvln jhcr fllmxc xjgv rdkvvnb xxzjz jbxvkvf pgdb mxnjztb xmpqj pjzqbc jfrkn rtcdm dkplsn bdnrnx vbdnhp rqccts vgsxs hcsmg dfvkm xtzqb mpqtc kjsll ktgf cqlpzd kmkcksz jdggtft lflv lcbbcb bchsc rhjhmvj ffqndb xvmsx tzzfktn gbzczpn jfddkg kfft cmrlm rmd nhnsh hxbl vmnfpd dqxvmx jknscx pkknn vmz dnrgnnr lgllb mdbq gvfsv zbqhtv xlknfh fsmhfr jndts mkv fdndh qqttxln xgtj fgfl nprb mdms sjxlr fxbxj sbbkvr lzxz rglpnc cdvjp lsnj kkcz hbxq gmzjtc sgqj qrmvtk (contains fish, peanuts) cdvjp kjsll cmzlkx bdnrnx jdggtft gbcsmlr kjsqxp rglpnc jtmlcg dfzbpz bhxx xvmsx tzhq nsndth tgtzx xvbdz lflv djsvj pzcgr ztdctgq pfmnx jdrlzk zlqcps xgtj pjzqbc dnrgnnr qddlv vrhrt ckbsg lmrbfm lzxz dkplsn dlgsd fbllk rmd ggmgdv tzzfktn pzh dkgkc qtsq vgfknzx mdbq jsqng gxml lsnj (contains sesame, peanuts, shellfish) cdvjp xgtj mvhlr tzzfktn qddlv vgsxs bhxx tgtzx vgfknzx xqdl gsdm xvbdz mxnjztb mdbq fdndh vtbdr chbpkvt tzhq kkcz vrhrt mnptn pfmnx mkv xxzjz pzcgr ztdctgq bdnrnx pgdb nhnsh fnr hbxq lgllb prgh cglt rmd ppb jdrlzk gbzczpn vsns gzzb jlhpkg lpts vbxnml gjvhr ztpvmk ffqndb kmkcksz krg lzxz pbfzgfx jzppz mxkfs djsvj ghshq dkgkc rglpnc jlmlz (contains fish) cqlpzd ztdctgq pzvbfr dkplsn zclh djsvj lzxpk kjsll tjxrc zlqcps prgh kjsqxp gzzb vmnfpd nhnsh sjxlr bdjxjvj sgqj kht xgtj mpqtc vbxnml jbdqm gmzjtc jlmlz chbpkvt dzqvbsq pzh spqqb pbfzgfx rjrn zbqhtv jknscx lgllb sjpx drrvln qglnp dlgsd sjpcmz rdkvvnb cglt bdnrnx vbdnhp nsndth dggmkht hbxq mxnjztb cdvjp xvbdz jbxvkvf zzlfrts jzjhcm fgfl hzrzc gqpdph nprb skhxhp hfmkj dzhf vsns bzxvd pjzqbc dqxvmx jtmlcg pllnld ckbsg jdggtft ffjb fnr lxhpmc vtbdr mpcsjs ktgf mdbq (contains sesame) tzqxpq sjfht ffqndb jpztz jlmlz lgdv ppb sndrz qtsq rkcngr jtmlcg nbkdh dnrgnnr ztdctgq hbxq gzzb vbdnhp cdvjp cz nhnsh fjndlnv ngmk tzzfktn sjxlr zsqn xgtj hcsmg cqlpzd ffjb sjpcmz bdjxjvj xvmsx drpn mpqtc sgqj gxml xqdl mdbq pzvbfr bdnrnx sjpx jrkbs gsdm vrhrt chbpkvt kcfjnr sdgjxm tjsvdhn xsfpzncj djsvj rmd fgjxhf vpqxh ckbsg tjxrc jjnd kfft vlsprc pzcgr pfmnx jknscx vhsp jdggtft jfrkn hfmkj kjsll drrvln gbzczpn xmpqj lcbbcb lzxz mkv kjsqxp tgtzx jdrlzk (contains eggs, dairy, sesame) spqqb qtsq cmrlm nhnsh mkv rtcdm cmzlkx bxv zjj lmrbfm mhlm fjndlnv gqsj kfft xgtj zzlfrts xlknfh lzxz cglt hzkdqz nvdlxkc lvmm gxml qqttxln dkplsn vgfknzx fxbxj hcsmg jbxvkvf jdggtft dqxvmx ghshq zlqcps jndts bchsc cqlpzd djsvj cdvjp mdbq pzvbfr jlhpkg qpdb rjrn dzqvbsq ztpvmk tpgm lgllb rmd kcfjnr xxzjz jlmlz bdnrnx (contains peanuts, dairy) ckbsg jdggtft sjpcmz nhnsh dnrgnnr bmqvll ztdctgq qsqcjd rqccts cdvjp fdndh sndrz lflv mdbq dzqvbsq jlmlz qcrf fnr vlsprc qpdb cz jbxvkvf jfddkg bdnrnx jsqng vrhrt dzhf skhxhp nvdlxkc mhlm ccqf jknscx lgllb kkcz xmpqj spqqb tjsvdhn jqhzc ggmgdv mxkfs rmd tgtzx kht jlhpkg vbxnml lvmm vtbdr (contains soy, eggs, fish) bdnrnx lxhpmc qhgg vbxnml ggmgdv zbqhtv qpdb kht vlsprc jdrlzk dnrgnnr zjj mnptn zclh xtzqb ccqf bdjxjvj pgdb jdggtft fnr xsfpzncj fgjxhf qglnp kspzjr rltc hfmkj pkknn mdbq mvhlr ffqndb ckbsg hzrzc kfft lgdv gpmvkrt ztdctgq vsns dfzbpz pjzqbc rmd mdms hxbl gxml mdpql xmpqj gqsj ghshq xlknfh dzhf lcbbcb bxv sbbkvr dzqvbsq dkplsn qqttxln mhlm rkcngr lzxpk chbpkvt vrhrt vgfknzx ztpvmk sgqj cdvjp vmz bchsc pzcgr zzlfrts sjpcmz vgsxs lgllb jzjhcm kmkcksz gvfsv (contains sesame, eggs, shellfish) jdggtft sbbkvr ppb lsnj mxnjztb kfft kht kmkcksz cqlpzd ztdctgq mpqtc bdnrnx jbdqm vpqxh dggmkht vgfknzx qdqfl bzxvd bxv rmd kcfjnr nxc pjzqbc lmrbfm zsqn rkcngr tzqxpq bmqvll pbfzgfx vtbdr ghshq pzcgr prgh zzlfrts lgllb cdvjp mdbq hzrzc (contains soy, sesame, fish) zbqhtv mpqtc fbllk jdggtft xsfpzncj rhjhmvj hzrzc xqdl zclh sdgjxm bhxx jsqng vgsxs dlgsd ppb xmpqj tjxrc fsmhfr mdbq ccqf jzjhcm tjsvdhn jbdqm cdvjp lzxz lgllb qsqcjd jrkbs bdnrnx sjfht mdpql vmz pzcgr jlhpkg jdrlzk mdms drpn nvdlxkc jbxvkvf sjpx sndrz jtmlcg xgtj nxc kspzjr mhlm mpcsjs dnrgnnr mvhlr ztpvmk mxkfs rglpnc gqpdph ffjb rdkvvnb qpdb mxnjztb gsdm xlknfh sjpcmz rmd jjnd qhgg djsvj dggmkht cmzlkx tzzfktn (contains shellfish) xgtj hfmkj ppb hcsmg rglpnc vbxnml mdbq jqhzc jrkbs rdkvvnb prgh bxv gbzczpn qglnp vsns jdggtft vlsprc gxml nbkdh mkv gvfsv zbqhtv zzlfrts pbfzgfx vmz lgllb gzzb xqsn cmzlkx fsmhfr cmrlm cglt kspzjr fdndh chbpkvt rkcngr qpdb hzkdqz kjsqxp bdjxjvj ztdctgq kmkcksz rltc kht qhgg xjgv bdnrnx zlqcps rjrn kcfjnr bhxx nhnsh mpcsjs tjxrc lzxz rmd (contains peanuts, dairy, sesame) ckbsg jjnd mdbq xvbdz kjsqxp drpn vmnfpd lzxpk ffjb drrvln dlgsd zclh pjzqbc mvhlr vsns dkplsn mpqtc jhcr gzzb mkv rdkvvnb zzlfrts jsqng lgllb tzzfktn zbqhtv djsvj xqsn hxbl gqpdph qglnp hfmkj rmd xjgv sjxlr qhgg jrkbs kkcz fdndh kspzjr bhxx tjxrc vpqxh xxzjz jdggtft jlhpkg lcbbcb pllnld qtsq rhjhmvj rkcngr nbkdh tpgm nvdlxkc jzppz zsqn cdvjp lgdv dzhf xqdl gqsj fsmhfr jzjhcm gxml pfmnx lxhpmc vhsp jlmlz gbcsmlr ztdctgq bdnrnx (contains sesame) xsfpzncj hfmkj rhjhmvj lmrbfm sbbkvr ggmgdv jdggtft xgtj mpqtc rkcngr rtcdm ztpvmk cdvjp zbqhtv zjj lvmm cmzlkx gxml mdbq sjpcmz fsmhfr jzppz bmqvll ktgf vbxnml gbzczpn bdnrnx cmrlm kspzjr gsdm qxsgkzt ztdctgq vtbdr jdrlzk gpmvkrt rmd tzzfktn gqsj jtmlcg dfzbpz skhxhp dkplsn (contains shellfish, nuts, dairy) cdvjp sndrz cqlpzd pjzqbc xqsn bdnrnx mxkfs sjpx pfmnx jknscx mdbq kjsll rkcngr jndts qrmvtk lgdv nhnsh xsfpzncj hxbl xgtj qpdb qddlv lcbbcb vmz tjsvdhn prgh fjndlnv fdndh vpqxh dfzbpz zlqcps rmd nbkdh zclh dfvkm hbxq gsdm lzxz jlmlz vhsp zzlfrts mxnjztb rltc ghshq qhgg gpmvkrt qhkq tjxrc mpqtc rtcdm dkgkc xtzqb pzcgr bdjxjvj xvbdz sgqj xvmsx dzhf ffqndb vbdnhp vsns gbcsmlr jdggtft fbllk lgllb dggmkht gmzjtc vgsxs lzxpk nsndth ztpvmk nvdlxkc bhxx drrvln lflv tpgm hzkdqz vtbdr (contains fish, sesame, shellfish) djsvj xtzqb tzqxpq jzjhcm kmkcksz bmqvll zjj jknscx lgllb sbbkvr pzvbfr krg kfft xvmsx xgtj tgtzx xqsn sjpcmz xqdl zclh bzxvd rtcdm nsndth vmz rmd lgdv qcrf ggmgdv pfmnx jdggtft fnr tjsvdhn kcfjnr rglpnc pjzqbc nxc jfrkn nvdlxkc xvbdz zbqhtv zsqn lzxz dfvkm spqqb fllmxc ztdctgq bdnrnx lvmm pbfzgfx lzxpk gvfsv fxbxj vgsxs mdms cglt dfzbpz qrmvtk mdbq (contains eggs, soy) rmd vtbdr dnrgnnr mpqtc qhkq hbxq jtmlcg tzhq rkcngr gsdm qqttxln hfmkj jhcr lzxz lgllb pzcgr dqxvmx lxhpmc mvhlr vlsprc mdpql gpmvkrt gqpdph gmzjtc fxbxj cmrlm jzjhcm xgtj zclh vbdnhp vmz bmqvll kcfjnr ztdctgq fnr bdjxjvj sjpcmz cz dzqvbsq drrvln gzzb gxml prgh bdnrnx qtsq jbxvkvf bchsc ghshq pbfzgfx drpn rdkvvnb sjfht sndrz krg pzh dfvkm jqhzc mdbq zzlfrts sbbkvr pllnld ggmcmz dzhf tpgm tzqxpq vmnfpd lpts kspzjr vbxnml ngmk tjxrc hzkdqz xsfpzncj jsqng qhgg qdqfl bxv pfmnx qglnp nsndth ppb ztpvmk spqqb dggmkht cdvjp lsnj zjj dkgkc mnptn vsns dkplsn (contains sesame, dairy) jfrkn gpmvkrt lgllb pfmnx ktgf kmkcksz zclh lzxz sjxlr xvmsx lxhpmc gmzjtc qhgg lflv dggmkht rkcngr tjxrc xtzqb gbzczpn mdbq krg ffjb xgtj bxv hcsmg pzh vbdnhp ngmk vsns gjvhr jdrlzk mxnjztb ccqf drpn ztdctgq kfft kjsll jdggtft drrvln nprb qglnp ppb jbxvkvf pzvbfr kspzjr spqqb bdnrnx jhcr ghshq qrmvtk mxkfs gzzb ffqndb skhxhp sbbkvr chbpkvt mbnr rdkvvnb rmd fnr vtbdr tjsvdhn ggmgdv lpts prgh zjj xqdl (contains dairy, peanuts) bzxvd xgtj kmkcksz fjndlnv qhkq qtsq dggmkht jpztz vpqxh kfft djsvj jjnd cdvjp rqccts qsqcjd qddlv mdbq lmrbfm zbqhtv xlknfh vmz qglnp xjgv rmd vgsxs ccqf gbcsmlr ckbsg jqhzc nsndth gjvhr gsdm mdms ngmk fdndh tgtzx sndrz krg jtmlcg ffjb xtzqb dzqvbsq pbfzgfx skhxhp mkv xmpqj tjxrc hxbl lgllb gvfsv kcfjnr mpqtc pkknn sdgjxm zlqcps dfzbpz vhsp sjpx pllnld tpgm jdggtft jdrlzk tzhq fxbxj qpdb ztdctgq bdjxjvj tjsvdhn pjzqbc xqdl (contains sesame, soy) jpztz ggmgdv mhlm fbllk pzcgr vpqxh dkgkc fjndlnv qrmvtk kkcz xgtj qqttxln jtmlcg nsndth s<KEY> rjrn nvdlxkc bdjxjvj ckbsg mdbq nhnsh bxv xmpqj ztdctgq qtsq qpdb rmd pjzqbc (contains sesame, soy) bdnrnx sbbkvr k<KEY> z<KEY> l<KEY> z<KEY> kjsll xqsn tzhq hcsmg tzqxpq zjj sjxlr mdbq xtzqb kkcz rmd gjvhr vgsxs cdvjp xvbdz prgh xqdl qhkq vbxnml (contains soy, shellfish) qpdb chbpkvt hcsmg ztpvmk tjxrc hfmkj ffjb qdqfl prgh vmz mnptn nvdlxkc kkcz gbcsmlr xmpqj xqsn drpn gmzjtc gbv s<KEY> x<KEY> jzppz jpztz sjxlr dfvkm rmd ghshq kspzjr rltc vmnfpd ztdctgq lzxpk jbdqm ffqndb fgfl nxc rkcngr gvfsv bdnrnx pgdb mdbq vlsprc sgqj cdvjp lflv drrvln zbqhtv jdrlzk qddlv qqttxln (contains fish, eggs, sesame) """.trimIndent() }
0
Kotlin
0
1
f5efe2f0b6b09b0e41045dc7fda3a7565cb21db3
18,923
advent-of-code
MIT License
advent-of-code2015/src/main/kotlin/day23/Advent23.kt
REDNBLACK
128,669,137
false
null
package day23 import day23.Operation.Type.* import parseInput import splitToLines import java.util.* /** --- Day 23: Opening the Turing Lock --- <NAME> just got her very first computer for Christmas from some unknown benefactor. It comes with instructions and an example program, but the computer itself seems to be malfunctioning. She's curious what the program does, and would like you to help her run it. The manual explains that the computer supports two registers and six instructions (truly, it goes on to remind the reader, a state-of-the-art technology). The registers are named a and b, can hold any non-negative integer, and begin with a value of 0. The instructions are as follows: hlf r sets register r to half its current value, then continues with the next instruction. tpl r sets register r to triple its current value, then continues with the next instruction. inc r increments register r, adding 1 to it, then continues with the next instruction. jmp offset is a jump; it continues with the instruction offset away relative to itself. jie r, offset is like jmp, but only jumps if register r is even ("jump if even"). jio r, offset is like jmp, but only jumps if register r is 1 ("jump if one", not odd). All three jump instructions work with an offset relative to that instruction. The offset is always written with a prefix + or - to indicate the direction of the jump (forward or backward, respectively). For example, jmp +1 would simply continue with the next instruction, while jmp +0 would continuously jump back to itself forever. The program exits when it tries to run an instruction beyond the ones defined. For example, this program sets a to 2, because the jio instruction causes it to skip the tpl instruction: inc a jio a, +2 tpl a inc a What is the value in register b when the program in your puzzle input is finished executing? --- Part Two --- The unknown benefactor is very thankful for releasi-- er, helping little <NAME> with her computer. Definitely not to distract you, what is the value in register b after the program is finished executing if register a starts as 1 instead? */ fun main(args: Array<String>) { val test = """inc a |jio a, +2 |tpl a |inc a""".trimMargin() val input = parseInput("day23-input.txt") println(executeOperations(test, hashMapOf())) println(executeOperations(input, hashMapOf())) println(executeOperations(input, hashMapOf("a" to 1L))) } data class Operation(val type: Operation.Type, val args: List<String>) { enum class Type { HLF, TPL, INC, JMP, JIE, JIO } } fun executeOperations(input: String, registers: HashMap<String, Long>): Map<String, Long> { val operations = parseOperations(input) fun getRegisterValue(key: String) = registers.getOrElse(key, { 0 }) var index = 0 while (index < operations.size) { val operation = operations[index] when (operation.type) { HLF -> { val register = operation.args[0] registers.computeIfPresent(register, { k, v -> v / 2 }) } TPL -> { val register = operation.args[0] registers.computeIfPresent(register, { k, v -> v * 3 }) } INC -> { val register = operation.args[0] registers.put(register, registers.getOrElse(register, { 0 }) + 1) } JMP -> { index += operation.args[0].toInt() - 1 } JIE -> { val (register, value) = operation.args if (getRegisterValue(register) % 2 == 0L) { index += value.toInt() - 1 } } JIO -> { val (register, value) = operation.args if (getRegisterValue(register) == 1L) { index += value.toInt() - 1 } } } index++ } return registers } private fun parseOperations(input: String) = input.splitToLines() .map { val args = it.split(" ") val type = Operation.Type.valueOf(args[0].toUpperCase()) Operation(type, args.drop(1).map { it.replace(",", "").replace("+", "") }) }
0
Kotlin
0
0
e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7
4,318
courses
MIT License
year2022/src/main/kotlin/net/olegg/aoc/year2022/day20/Day20.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2022.day20 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.year2022.DayOf2022 /** * See [Year 2022, Day 20](https://adventofcode.com/2022/day/20) */ object Day20 : DayOf2022(20) { override fun first(): Any? { val numbers = lines .mapIndexed { index, line -> line.toInt() to index } .toMutableList() val mod = numbers.size - 1 numbers.indices.forEach { index -> val positionBefore = numbers.indexOfFirst { it.second == index } val value = numbers[positionBefore] val positionAfter = (((positionBefore + value.first) % mod) + mod) % mod numbers.removeAt(positionBefore) numbers.add(positionAfter, value) } val position = numbers.indexOfFirst { it.first == 0 } return numbers[(position + 1000) % numbers.size].first + numbers[(position + 2000) % numbers.size].first + numbers[(position + 3000) % numbers.size].first } override fun second(): Any? { val numbers = lines .mapIndexed { index, line -> line.toLong() * 811589153L to index } .toMutableList() val mod = numbers.size - 1 repeat(10) { numbers.indices.forEach { index -> val positionBefore = numbers.indexOfFirst { it.second == index } val value = numbers[positionBefore] val positionAfter = ((((positionBefore + value.first) % mod) + mod) % mod).toInt() numbers.removeAt(positionBefore) numbers.add(positionAfter, value) } } val position = numbers.indexOfFirst { it.first == 0L } return numbers[(position + 1000) % numbers.size].first + numbers[(position + 2000) % numbers.size].first + numbers[(position + 3000) % numbers.size].first } } fun main() = SomeDay.mainify(Day20)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,763
adventofcode
MIT License
2016/07/Solution.kt
AdrianMiozga
588,519,359
false
{"Kotlin": 110785, "Python": 11275, "Assembly": 3369, "C": 2378, "Pawn": 1390, "Dart": 732}
import java.io.File private const val FILENAME = "2016/07/input.txt" fun main() { partOne() partTwo() } private fun partOne() { val file = File(FILENAME).readLines() var valid = 0 for (ip in file) { val inBrackets = Regex("""\[\w+]""") .findAll(ip) .flatMap { it.groupValues } .map { it.removeSurrounding("[", "]") } .toList() val outsideBrackets = Regex("""\w+""") .findAll(ip) .flatMap { it.groupValues }.toList() .minus(inBrackets.toSet()) val outsideRule = containsAbba(outsideBrackets) val insideRule = !containsAbba(inBrackets) if (outsideRule && insideRule) { valid++ } } println(valid) } private fun containsAbba(strings: List<String>): Boolean { for (string in strings) { for (i in 0 until (string.length - 3)) { if (string[i] == string[i + 1]) { continue } val firstPair = "${string[i]}${string[i + 1]}" val secondPair = "${string[i + 2]}${string[i + 3]}" if (firstPair == secondPair.reversed()) { return true } } } return false } private fun partTwo() { val file = File(FILENAME).readLines() var valid = 0 ip@for (ip in file) { val inBrackets = Regex("""\[\w+]""") .findAll(ip) .flatMap { it.groupValues } .map { it.removeSurrounding("[", "]") } .toList() val outsideBrackets = Regex("""\w+""") .findAll(ip) .flatMap { it.groupValues }.toList() .minus(inBrackets.toSet()) val sequences = HashSet<String>() for (element in outsideBrackets) { for (index in 0 until element.length - 2) { if (element[index] == element[index + 2]) { if (element[index + 1] != element[index]) { sequences.add(element.substring(index..(index + 2))) } } } } for (element in inBrackets) { for (index in 0 until element.length - 2) { for (sequence in sequences) { if (element[index] == sequence[1] && element[index + 2] == sequence[1]) { if (element[index + 1] == sequence[0]) { valid++ continue@ip } } } } } } println(valid) }
0
Kotlin
0
0
c9cba875089d8d4fb145932c45c2d487ccc7e8e5
2,722
Advent-of-Code
MIT License
src/main/kotlin/io/queue/TagValidator.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.queue import java.util.* // https://leetcode.com/problems/tag-validator/ class TagValidator { private val tagRegex = "<[/|A-Z]+>".toRegex() private val cDataRegex = "<!\\[CDATA\\[.*]]>".toRegex() fun isValid(code: String): Boolean = execute(code) fun execute(input: String): Boolean { when { input.length < 5 || input.first() != '<' || input[1] == '!' -> return false } val stack = LinkedList<String>() var index = 0 while (index < input.length) { when (input[index]) { '<' -> { if (index + 1 == input.length) return false when (input[index + 1]) { ' ' -> { stack.push(input[index].toString()) index += 2 } '!' -> { val lastCDataContentIndex = input.lastCDataContextIndex(index) val cData = input.substring(index, lastCDataContentIndex) if (!cData.isCDataValid()) return false index = lastCDataContentIndex } else -> { val lastTagIndex = input.lastTagIndex(index) val tag = input.substring(index, lastTagIndex) when { tag.isTagInvalid() || tag.isClosingTag() && (stack.isEmpty() || stack.pop().areInvalidTags(tag))-> return false tag.isOpenTag() -> stack.push(tag) } index = lastTagIndex } } } '>' -> { when{ stack.isNotEmpty() && stack.peek() == "<" -> { stack.pop() } } index++ } else -> { index = input.moveUntilNextValue(index) } } } return stack.isEmpty() } private fun String.moveUntilNextValue(currentIndex:Int):Int{ var index = currentIndex loop@ while(index < length){ when (this[index]){ '<', '>' -> break@loop else -> index++ } } return index } private fun String.lastTagIndex(index: Int): Int { var currentIndex = index while (currentIndex < length && this[currentIndex] != '>') currentIndex++ return if (currentIndex == length) currentIndex else currentIndex+1 } private fun String.isTagValid() = length < 13 && tagRegex.matchEntire(this) != null private fun String.isTagInvalid() = !isTagValid() private fun String.isClosingTag() = this[1] == '/' private fun String.isOpenTag() = !isClosingTag() private fun String.areValidTags(closingTag: String) = this.length + 1 == closingTag.length && this.substring(1, this.length - 1) == closingTag.substring(2, closingTag.length-1) private fun String.areInvalidTags(closingTag: String) = !areValidTags(closingTag) private fun String.isCDataValid() = cDataRegex.matchEntire(this) != null private fun String.lastCDataContextIndex(startIndex: Int): Int { var index = startIndex while (index + 3 < length && this.substring(index, index + 3) != "]]>") index++ return index + 3 } } fun main(){ val tagValidator = TagValidator() listOf( "<DIV>This is the first line <![CDATA[<div>]]></DIV>" to true, "<DIV>>> ![cdata[]] <![CDATA[<div>]>]]>]]>>]</DIV>" to true, "<A> <B> </A> </B>" to false, "<DIV> div tag is not closed <DIV>" to false, "<DIV> unmatched < </DIV>" to false, "<DIV> closed tags with invalid tag name <b>123</b> </DIV>" to false, "<DIV> unmatched tags with invalid tag name </1234567890> and <CDATA[[]]> </DIV>" to false, "<DIV> unmatched start tag <B> and unmatched end tag </C> </DIV>" to false, "<![CDATA[wahaha]]]><![CDATA[]> wahaha]]>" to false, "<TRUE><![CDATA[wahaha]]]><![CDATA[]> wahaha]]></TRUE>" to true ).forEachIndexed { index, (input,value) -> val output = tagValidator.execute(input) val isValid = output == value if (isValid) println("index $index $output is valid") else println("index $index Except $value but instead got $output") } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
4,054
coding
MIT License
2015/src/main/kotlin/com/koenv/adventofcode/Day2.kt
koesie10
47,333,954
false
null
package com.koenv.adventofcode object Day2 { public fun getSquareFeetOfWrappingPaper(input: String): Int { val (l, w, h) = getDimensions(input) val areas = arrayOf(l * w, w * h, h * l) val minArea = areas.min()!! return areas.map { it * 2 }.sum() + minArea } public fun getTotalSquareFeetOfWrappingPaper(input: String): Int { return input.lines().map { getSquareFeetOfWrappingPaper(it) }.sum() } public fun getSquareFeetOfRibbon(input: String): Int { val (l, w, h) = getDimensions(input) val dimensions = listOf(l, w, h) val shortest = dimensions.min()!! val noShortestDimensions = dimensions.minus(shortest) val minShortest = noShortestDimensions.min()!! return shortest * 2 + minShortest * 2 + l * w * h } public fun getTotalSquareFeetOfRibbon(input: String): Int { return input.lines().map { getSquareFeetOfRibbon(it) }.sum() } private fun getDimensions(input: String): Day2Dimensions { val dimensions = input.split('x') val l = dimensions[0].toInt() val w = dimensions[1].toInt() val h = dimensions[2].toInt() return Day2Dimensions(l, w, h) } data class Day2Dimensions(val l: Int, val w: Int, val h: Int) }
0
Kotlin
0
0
29f3d426cfceaa131371df09785fa6598405a55f
1,336
AdventOfCode-Solutions-Kotlin
MIT License
year2017/src/main/kotlin/net/olegg/aoc/year2017/day22/Day22.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2017.day22 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.Directions import net.olegg.aoc.utils.Directions.Companion.CCW import net.olegg.aoc.utils.Directions.Companion.CW import net.olegg.aoc.utils.Directions.Companion.REV import net.olegg.aoc.utils.Vector2D import net.olegg.aoc.year2017.DayOf2017 /** * See [Year 2017, Day 22](https://adventofcode.com/2017/day/22) */ object Day22 : DayOf2017(22) { override fun first(): Any? { val map = mutableMapOf<Vector2D, Boolean>().apply { val raw = lines.map { line -> line.map { it == '#' } } raw.forEachIndexed { y, row -> row.forEachIndexed { x, value -> put(Vector2D(x - raw.size / 2, y - raw.size / 2), value) } } } return (0..<10000).fold(Triple(Vector2D(), Directions.U, 0)) { (pos, dir, state), _ -> val curr = map.getOrDefault(pos, false) val newDir = (if (curr) CW[dir] else CCW[dir]) ?: dir map[pos] = !curr return@fold Triple( pos + newDir.step, newDir, if (curr) state else state + 1, ) }.third } override fun second(): Any? { val map = mutableMapOf<Vector2D, Int>().apply { val raw = lines.map { line -> line.map { ".W#F".indexOf(it) } } raw.forEachIndexed { y, row -> row.forEachIndexed { x, value -> put(Vector2D(x - raw.size / 2, y - raw.size / 2), value) } } } return (0..<10000000).fold(Triple(Vector2D(), Directions.U, 0)) { (pos, dir, state), _ -> val curr = map.getOrDefault(pos, 0) val newDir = when (curr) { 0 -> CCW[dir] 1 -> dir 2 -> CW[dir] 3 -> REV[dir] else -> dir } ?: dir map[pos] = (curr + 1) % 4 return@fold Triple( pos + newDir.step, newDir, if (curr == 1) state + 1 else state, ) }.third } } fun main() = SomeDay.mainify(Day22)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,940
adventofcode
MIT License
src/main/kotlin/days/Day10.kt
tpepper0408
317,612,203
false
null
package days import java.util.* class Day10() : Day<Long>(10) { override fun partOne(): Long { var values = inputList.map { it.toInt() }.plus(0) values = values.sorted() var numberOf1Diffs = 0L var numberOf3Diffs = 0L var previousValue = -1 for (value in values) { if (previousValue == -1) { previousValue = value continue } when (value - previousValue) { 1 -> numberOf1Diffs++ 3 -> numberOf3Diffs++ else -> { } } previousValue = value } numberOf3Diffs++ println("1diffs $numberOf1Diffs: 3diffs $numberOf3Diffs") return numberOf1Diffs * numberOf3Diffs } override fun partTwo(): Long { var fullList = inputList.map { it.toInt() }.plus(0) fullList.plus(fullList.last() + 3) fullList = fullList.sorted() val gaps: MutableList<Int> = ArrayList() for (i in 1 until fullList.size) { val thisEntry = fullList[i] val previousEntry = fullList[i - 1] val difference = thisEntry - previousEntry gaps.add(difference) } val differenceString = StringBuilder() for (i in gaps.indices) { differenceString.append(gaps[i]) } var diff = differenceString.toString() diff = diff.replace("111111", "E") diff = diff.replace("11111", "D") diff = diff.replace("1111", "C") diff = diff.replace("111", "B") diff = diff.replace("11", "A") var count: Long = 1 for (element in diff) { when (element) { 'A' -> count *= 2 'B' -> count *= 4 'C' -> count *= 7 'D' -> count *= 13 'E' -> count *= 24 } } return count } // override fun partTwo(): Int { // var values = inputList.map { // it.toInt() // }.sorted() // // val jumps = HashSet<Pair<Int,Int>>() // for (value in values) { // if (values.contains(value+1)) jumps.add(Pair(value, value+1)) // if (values.contains(value+2)) jumps.add(Pair(value, value+2)) // if (values.contains(value+3)) jumps.add(Pair(value, value+3)) // } // val jumpList = jumps.sortedBy { it.first } // return jumpList.size // } // // private fun successfulPath(values: List<Int>, successfulPaths: ArrayList<List<Int>>): ArrayList<Int> { // val currentPath = arrayListOf(0) // var previousValue = 0 // var localIndex = 0 // for (index in values.indices) { // val nextValue = values[index] // if (!validMove(nextValue, previousValue)) { // continue // } // if (alreadyMadeMove(successfulPaths, previousValue, nextValue, localIndex)) { // previousValue = nextValue // localIndex++ // continue // } // previousValue = nextValue // currentPath.add(nextValue) // } // return currentPath // } // // private fun alreadyMadeMove(successfulPaths: ArrayList<List<Int>>, // previousValue: Int, // nextValue: Int, // index: Int): Boolean { // for (path in successfulPaths) { // val previousValueInPath = path[index] // if (path.size < index+1) { // return false // } // val nextValueInPath = path[index+1] // if (previousValue == previousValueInPath // && nextValue == nextValueInPath) { // return true // } // } // return false // } // // private fun validMove(value: Int, previousValue: Int): Boolean { // return when (value - previousValue) { // in 1..3 -> true // else -> false // } // } }
0
Kotlin
0
0
67c65a9e93e85eeb56b57d2588844e43241d9319
4,153
aoc2020
Creative Commons Zero v1.0 Universal
2021/src/day01/Day01.kt
Bridouille
433,940,923
false
{"Kotlin": 171124, "Go": 37047}
package day01 import readInput fun part1(input: List<String>) = input.windowed(2).map { it[0] < it[1] }.count { it } const val SLIDING_WINDOW_SIZE = 3 fun part2(input: List<String>): Int { val sliding1: MutableList<Int> = mutableListOf<Int>() val sliding2: MutableList<Int> = mutableListOf<Int>() var increase = 0 input.forEach { if (!sliding1.isEmpty()) { sliding2.add(0, it.toInt()) } if (sliding1.size > SLIDING_WINDOW_SIZE) { sliding1.removeLast() } if (sliding2.size > SLIDING_WINDOW_SIZE) { sliding2.removeLast() } if (sliding1.size == SLIDING_WINDOW_SIZE && sliding2.size == SLIDING_WINDOW_SIZE) { if (sliding2.sum() > sliding1.sum()) { increase++ } } sliding1.add(0, it.toInt()) } return increase } fun main() { val testInput = readInput("day01/test") println(part1(testInput)) println(part2(testInput)) val input = readInput("day01/input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
8ccdcce24cecca6e1d90c500423607d411c9fee2
1,099
advent-of-code
Apache License 2.0
src/main/kotlin/co/csadev/advent2022/Day16.kt
gtcompscientist
577,439,489
false
{"Kotlin": 252918}
/** * Copyright (c) 2022 by <NAME> * Advent of Code 2022, Day 16 * Problem Description: http://adventofcode.com/2021/day/16 */ package co.csadev.advent2022 import co.csadev.adventOfCode.BaseDay import co.csadev.adventOfCode.Resources.resourceAsList import kotlin.math.max class Day16(override val input: List<String> = resourceAsList("22day16.txt")) : BaseDay<List<String>, Int, Int> { private val flowArr: Array<Int> private val valveArr: Array<List<Int>> private val openArr: Array<Boolean> private val aaIdx: Int init { val flows = mutableMapOf<String, Int>() val valves = mutableMapOf<String, List<String>>() val open = mutableMapOf<String, Boolean>() @Suppress("DestructuringDeclarationWithTooManyEntries") input.map { val (v, t) = it.split("; ") val (_, name, _, _, rate) = v.replace("rate=", "").split(" ") flows[name] = rate.toInt() val currV = t.split("valve")[1].replace("s ", "").trim().split(", ") valves[name] = currV open[name] = false } val nameMap = flows.keys.sorted().mapIndexed { index, s -> s to index }.toMap() aaIdx = nameMap["AA"]!! flowArr = flows.keys.sortedBy { nameMap[it]!! }.map { flows[it]!! }.toTypedArray() valveArr = valves.keys.sortedBy { nameMap[it]!! }.map { valves[it]!!.map { l -> nameMap[l]!! } }.toTypedArray() openArr = open.keys.sortedBy { nameMap[it]!! }.map { open[it]!! }.toTypedArray() } private val seen = mutableMapOf<String, Int>() private var max = 0 private var maxTime = 30 override fun solvePart1(): Int { listOf(0).findPath(1, arrayOf(aaIdx)) return max } override fun solvePart2(): Int { seen.clear() max = 0 maxTime = 26 listOf(0).findPath(1, arrayOf(aaIdx, aaIdx)) return max } private val currFlow: Int get() = openArr.mapIndexed { index, b -> if (b) flowArr[index] else 0 }.sum() private fun List<Int>.findPath(time: Int, pos: Array<Int>) { val key = "$time${pos.contentDeepHashCode()}" val currSum = sum() if (seen.getOrDefault(key, -1) >= currSum) { return } seen[key] = currSum if (time == maxTime) { max = max(max, currSum) } else if (openArr.all { it }) { (this + currFlow).findPath(time + 1, pos) } else { searchPath(time, 0, pos) } } private fun List<Int>.searchPath(time: Int, offset: Int, pos: Array<Int>) { val opening = pos.getOrNull(offset) ?: return if (!openArr[opening] && flowArr[opening] > 0) { openArr[opening] = true addDepth(currFlow, time, offset + 1, pos) openArr[opening] = false } val currentFlow = currFlow valveArr[opening].forEach { p -> val temp = pos[offset] pos[offset] = p addDepth(currentFlow, time, offset + 1, pos) pos[offset] = temp } } private fun List<Int>.addDepth(startFlow: Int, time: Int, offset: Int, pos: Array<Int>) { val pos2 = pos.getOrNull(offset) if (pos2 != null && offset > 0) { searchPath(time, offset, pos) } else { (this + startFlow).findPath(time + 1, pos) } } }
0
Kotlin
0
1
43cbaac4e8b0a53e8aaae0f67dfc4395080e1383
3,438
advent-of-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/LoudAndRich.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * 851. Loud and Rich * @see <a href="https://leetcode.com/problems/loud-and-rich/">Source</a> */ fun interface LoudAndRich { operator fun invoke(richer: Array<IntArray>, quiet: IntArray): IntArray } class LoudAndRichDFS : LoudAndRich { override operator fun invoke(richer: Array<IntArray>, quiet: IntArray): IntArray { val n = quiet.size val res = IntArray(n) { -1 } val adj: Array<MutableList<Int>> = Array(n) { ArrayList() } for (i in 0 until n) { adj[i] = ArrayList() } for (r in richer) { adj[r[1]].add(r[0]) // build graph } for (i in 0 until n) { dfs(adj, i, quiet, res) // dfs for every node } return res } private fun dfs(adj: Array<MutableList<Int>>, src: Int, quiet: IntArray, res: IntArray): IntArray { if (res[src] > -1) return intArrayOf(quiet[res[src]], res[src]) var ret = intArrayOf(quiet[src], src) for (n in adj[src]) { val temp = dfs(adj, n, quiet, res) if (temp[0] < ret[0]) { ret = temp // if any richer node is quieter } } res[src] = ret[1] // update the index in res return ret } } class LoudAndRichMap : LoudAndRich { private var richer2: HashMap<Int, MutableList<Int>> = HashMap() private lateinit var res: IntArray override operator fun invoke(richer: Array<IntArray>, quiet: IntArray): IntArray { val n = quiet.size for (i in 0 until n) { richer2[i] = ArrayList() } for (v in richer) { richer2[v[1]]?.add(v[0]) } res = IntArray(n) { -1 } for (i in 0 until n) dfs(i, quiet) return res } private fun dfs(i: Int, quiet: IntArray): Int { if (res[i] >= 0) return res[i] res[i] = i for (j in richer2.getOrDefault(i, emptyList())) { if (quiet[res[i]] > quiet[dfs(j, quiet)]) res[i] = res[j] } return res[i] } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,686
kotlab
Apache License 2.0
src/Day24.kt
frungl
573,598,286
false
{"Kotlin": 86423}
data class Blizzard(val pos: Pair<Int, Int>, val move: Pair<Int, Int>) @OptIn(ExperimentalStdlibApi::class) fun main() { fun parseInput(input: List<String>): List<Blizzard> { val tiles = mapOf( '>' to Pair(0, 1), '<' to Pair(0, -1), '^' to Pair(-1, 0), 'v' to Pair(1, 0) ) val blizzards = mutableListOf<Blizzard>() input.forEachIndexed { x, str -> str.forEachIndexed { y, c -> if (c in tiles) blizzards.add(Blizzard(x to y, tiles[c]!!)) } } return blizzards } fun part1(input: List<String>): Int { val n = input.size - 2 val m = input[0].length - 2 val time = n * m / n.toBigInteger().gcd(m.toBigInteger()).toInt() var blizzards = parseInput(input) val positions = MutableList(time) { mutableSetOf<Pair<Int, Int>>() } positions[0] = blizzards.map { it.pos }.toMutableSet() for(i in 1 ..< time) { val newBlizzards = mutableListOf<Blizzard>() for((pos, dir) in blizzards) { var newPos = pos.first + dir.first to pos.second + dir.second if (newPos.first == n + 1) newPos = 1 to newPos.second if (newPos.first == 0) newPos = n to newPos.second if (newPos.second == m + 1) newPos = newPos.first to 1 if (newPos.second == 0) newPos = newPos.first to m newBlizzards.add(Blizzard(newPos, dir)) } blizzards = newBlizzards; positions[i] = blizzards.map { it.pos }.toMutableSet() } val possible = mutableSetOf<Pair<Int, Int>> () possible.addAll((1..n).flatMap { x -> (1..m).map { y -> x to y } }) possible.add(0 to 1) possible.add(n + 1 to m) var dp = MutableList(n + 2) { MutableList(m + 2) { false } } var count = 0 dp[0][1] = true while (true) { val ind = count % positions.size val newDp = MutableList(n + 2) { MutableList(m + 2) { false } } for(x in 0 .. n+1) { for(y in 0 .. m+1) { if (!dp[x][y]) continue for((dx, dy) in listOf(Pair(0, 0), Pair(0, 1), Pair(0, -1), Pair(1, 0), Pair(-1, 0))) { val nx = x + dx val ny = y + dy if (nx to ny in possible && nx to ny !in positions[ind]) newDp[nx][ny] = true } } } if (newDp[n + 1][m]) { return count } count++ dp = newDp } } fun part2(input: List<String>): Int { val n = input.size - 2 val m = input[0].length - 2 val time = n * m / n.toBigInteger().gcd(m.toBigInteger()).toInt() var blizzards = parseInput(input) val positions = MutableList(time) { mutableSetOf<Pair<Int, Int>>() } positions[0] = blizzards.map { it.pos }.toMutableSet() for(i in 1 ..< time) { val newBlizzards = mutableListOf<Blizzard>() for((pos, dir) in blizzards) { var newPos = pos.first + dir.first to pos.second + dir.second if (newPos.first == n + 1) newPos = 1 to newPos.second if (newPos.first == 0) newPos = n to newPos.second if (newPos.second == m + 1) newPos = newPos.first to 1 if (newPos.second == 0) newPos = newPos.first to m newBlizzards.add(Blizzard(newPos, dir)) } blizzards = newBlizzards; positions[i] = blizzards.map { it.pos }.toMutableSet() } val possible = mutableSetOf<Pair<Int, Int>> () possible.addAll((1..n).flatMap { x -> (1..m).map { y -> x to y } }) possible.add(0 to 1) possible.add(n + 1 to m) var dp = MutableList(n + 2) { MutableList(m + 2) { false } } var count = 0 dp[0][1] = true var state = 0 while (true) { val ind = count % positions.size var newDp = MutableList(n + 2) { MutableList(m + 2) { false } } for(x in 0 .. n+1) { for(y in 0 .. m+1) { if (!dp[x][y]) continue for((dx, dy) in listOf(Pair(0, 0), Pair(0, 1), Pair(0, -1), Pair(1, 0), Pair(-1, 0))) { val nx = x + dx val ny = y + dy if (nx to ny in possible && nx to ny !in positions[ind]) newDp[nx][ny] = true } } } if (newDp[n + 1][m]) { if (state == 0){ state = 1 newDp = MutableList(n + 2) { MutableList(m + 2) { false } } newDp[n + 1][m] = true } else if (state == 2) return count } if (newDp[0][1] && state == 1) { state = 2 newDp = MutableList(n + 2) { MutableList(m + 2) { false } } newDp[0][1] = true } count++ dp = newDp } } val testInput = readInput("Day24_test") check(part1(testInput) == 18) check(part2(testInput) == 54) val input = readInput("Day24") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d4cecfd5ee13de95f143407735e00c02baac7d5c
5,563
aoc2022
Apache License 2.0
src/main/kotlin/ch/uzh/ifi/seal/bencher/prioritization/search/Greedy.kt
chrstphlbr
227,602,878
false
{"Kotlin": 918163, "Java": 29153}
package ch.uzh.ifi.seal.bencher.prioritization.search import org.uma.jmetal.algorithm.Algorithm import org.uma.jmetal.problem.permutationproblem.PermutationProblem import org.uma.jmetal.solution.permutationsolution.PermutationSolution import org.uma.jmetal.solution.permutationsolution.impl.IntegerPermutationSolution class Greedy( private val problem: PermutationProblem<PermutationSolution<Int>>, private val benchmarkIdMap: BenchmarkIdMap, private val objectives: List<Objective>, private val aggregation: Aggregation?, ) : Algorithm<PermutationSolution<Int>> { private lateinit var result: PermutationSolution<Int> init { if (problem.numberOfVariables() != benchmarkIdMap.size) { throw IllegalArgumentException("problem.numberOfVariables (${problem.numberOfVariables()}) != benchmarkIdMap.size (${benchmarkIdMap.size})") } if (objectives.isEmpty()) { throw IllegalArgumentException("no objectives specified") } if (objectives.size == 1 && aggregation != null) { throw IllegalArgumentException("aggregation not null although objectives.size == 1") } if (objectives.size > 1 && aggregation == null) { throw IllegalArgumentException("objectives.size > 1 but aggregation == null") } } override fun run() { val greedySolution = greedySolution() result = problem.evaluate(greedySolution) } private fun greedySolution(): PermutationSolution<Int> { val idsSingleObjectives = (0 until benchmarkIdMap.size) .map { id -> val b = benchmarkIdMap[id] ?: throw IllegalStateException("expected benchmark with id $id") val objectiveValues = objectives.map { o -> Objective.toMinimization(o.type, o.compute(b)) } val objectiveValue = aggregation?.compute(objectiveValues.toDoubleArray()) ?: objectiveValues[0] Pair(id, objectiveValue) } .sortedBy { it.second } assert(idsSingleObjectives.size == benchmarkIdMap.size) val solution = IntegerPermutationSolution(benchmarkIdMap.size, problem.numberOfObjectives(), problem.numberOfConstraints()) assert(idsSingleObjectives.size == solution.variables().size) idsSingleObjectives.forEachIndexed { i, (v, _) -> solution.variables()[i] = v } return solution } override fun result(): PermutationSolution<Int> = result override fun name(): String = "Greedy" override fun description(): String = "Greedy" }
0
Kotlin
2
4
06601fb4dda3b2996c2ba9b2cd612e667420006f
2,580
bencher
Apache License 2.0
src/Day01.kt
timhillgit
572,354,733
false
{"Kotlin": 69577}
fun <T> Iterable<T>.split( predicate: (T) -> Boolean ): List<List<T>> = fold(listOf(listOf())) { result, element -> if (predicate(element)) { result + listOf(listOf()) } else { result.dropLast(1) + listOf(result.last() + element) } } fun <T> Iterable<T?>.splitOnNull( predicate: (T) -> Boolean = { false } ): List<List<T>> = fold(listOf(listOf())) { result, element -> if ((element == null) || predicate(element)) { result + listOf(listOf()) } else { result.dropLast(1) + listOf(result.last() + element) } } fun main() { val elves = readInts("Day01") .splitOnNull() .map(List<Int>::sum) .sortedDescending() println(elves.first()) println(elves.take(3).sum()) }
0
Kotlin
0
1
76c6e8dc7b206fb8bc07d8b85ff18606f5232039
764
advent-of-code-2022
Apache License 2.0
hackerrank/journey-to-the-moon/Solution.kt
shengmin
5,972,157
false
null
import java.io.* import java.math.* import java.security.* import java.text.* import java.util.* import java.util.concurrent.* import java.util.function.* import java.util.regex.* import java.util.stream.* import kotlin.collections.* import kotlin.comparisons.* import kotlin.io.* import kotlin.jvm.* import kotlin.jvm.functions.* import kotlin.jvm.internal.* import kotlin.ranges.* import kotlin.sequences.* import kotlin.text.* // Complete the journeyToMoon function below. fun journeyToMoon(n: Int, pairs: Array<Array<Int>>): Long { val nodeEdges = kotlin.arrayOfNulls<MutableList<Int>>(n) for (pair in pairs) { val (a, b) = pair val aNodeEdges = nodeEdges[a] ?: mutableListOf<Int>() val bNodeEdges = nodeEdges[b] ?: mutableListOf<Int>() aNodeEdges.add(b) bNodeEdges.add(a) nodeEdges[a] = aNodeEdges nodeEdges[b] = bNodeEdges } val visitedNodes = BooleanArray(n) fun countNodes(node: Int): Int { if (visitedNodes[node]) { return 0 } visitedNodes[node] = true var nodeCount = 1 val nextNodes = nodeEdges[node] if (nextNodes == null) { return 1 } for (nextNode in nextNodes) { nodeCount += countNodes(nextNode) } return nodeCount } val countries = mutableListOf<Int>() var countryWithSingleNodeCount = 0 for (node in 0 until n) { val nodeCount = countNodes(node) if (nodeCount == 0) { continue } if (nodeCount == 1) { countryWithSingleNodeCount++ } else { countries.add(nodeCount) } } var totalCount = 0L for (i in 0 until countries.size) { for (j in i + 1 until countries.size) { totalCount += countries[i].toLong() * countries[j].toLong() } } // pair single node with multiple nodes for (countryCount in countries) { totalCount += countryCount * countryWithSingleNodeCount.toLong() } // pair single node with single node totalCount += (countryWithSingleNodeCount) * (countryWithSingleNodeCount.toLong() - 1) / 2 return totalCount } fun main(args: Array<String>) { val scan = Scanner(System.`in`) val np = scan.nextLine().split(" ") val n = np[0].trim().toInt() val p = np[1].trim().toInt() val astronaut = Array<Array<Int>>(p, { Array<Int>(2, { 0 }) }) for (i in 0 until p) { astronaut[i] = scan.nextLine().split(" ").map { it.trim().toInt() }.toTypedArray() } val result = journeyToMoon(n, astronaut) println(result) }
0
Java
18
20
08e65546527436f4bd2a2014350b2f97ac1367e7
2,448
coding-problem
MIT License
src/main/kotlin/Solution1.kt
AndreySmirdin
170,665,827
false
null
import org.apache.commons.lang3.StringUtils import java.util.* import kotlin.collections.ArrayList object Solution1 { @JvmStatic fun main(args: Array<String>) { val reader = Scanner(System.`in`) val n = reader.nextInt() val names = ArrayList<String>() for (i in 0..n) { names.add(reader.nextLine()) } val result = solve(names) if (result.isEmpty()) { println("Impossible") } else { println(result.joinToString(" ")) } } /** * Finds the correct order of letters. * @return correct order if possible, empty list otherwise */ fun solve(names: ArrayList<String>): List<Char> { val graph = ArrayList<Node>() for (char in 'a'..'z') { graph.add(Node(char)) } for (i in 1 until names.size) { val diff_position = StringUtils.indexOfDifference(names[i - 1], names[i]) if (diff_position == names[i].length) { return emptyList() } else if (diff_position == -1 || diff_position == names[i - 1].length) { continue } else { val edge_to = graph[getIndexFromChar(names[i - 1][diff_position])] val edge_from = graph[getIndexFromChar(names[i][diff_position])] edge_from.edges.add(edge_to) } } for (node in graph) { if (!node.visited && !checkNoCycles(node)) { return emptyList() } } for (node in graph) { node.visited = false } val result = ArrayList<Node>() for (node in graph) { if (!node.visited) doTopSort(node, result) } return result.map { node -> node.symbol } } private fun checkNoCycles(node: Node): Boolean { if (node.repeated) return false if (node.visited) return true node.repeated = true node.visited = true for (e in node.edges) { if (!checkNoCycles(e)) return false } node.repeated = false return true } /** * Finds top sort of the graph. * @param node node to start search from * @param result topologically ordered nodes */ private fun doTopSort(node: Node, result: MutableList<Node>) { node.visited = true for (e in node.edges) { if (!e.visited) { doTopSort(e, result) } } result.add(node) } private class Node(val symbol: Char) { // We dont need to store one edge twice. val edges = TreeSet<Node>(Comparator<Node> { o1, o2 -> Character.compare(o1.symbol, o2.symbol) }) var visited = false var repeated = false } private fun getIndexFromChar(char: Char): Int = char - 'a' }
0
Kotlin
0
0
27465d19f5413a06948fc32d789ac7c35a80682f
2,943
Task_for_Groovy_project
MIT License
src/Day03.kt
DevHexs
573,262,501
false
{"Kotlin": 11452}
fun main(){ fun getPriorityValue(): MutableMap<Char,Int> { val mapPriority = mutableMapOf<Char,Int>() for (i in 'a'..'z'){ mapPriority.put(i,26 - ('z'.code - i.code)) } for (i in 'A'..'Z'){ mapPriority.put(i,52 - ('Z'.code - i.code)) } return mapPriority } fun part1(){ val input = readInput("Day03") val elementRepeat = mutableListOf<Char>() val priorityValue = getPriorityValue() for (i in input){ val value = i.chunked(i.count() / 2) val set1 = value[0].toSet() val set2 = value[1].toSet() for (j in set1) { if (set2.contains(j)) { elementRepeat.add(j) break } } } var sumValuePriority = 0 for (i in elementRepeat){ sumValuePriority += priorityValue[i]!! } println(sumValuePriority) } fun part2(){ val input = readInput("Day03") val elementRepeat = mutableListOf<Char>() val priorityValue = getPriorityValue() val sizeInput = input.count() for (i in 2..sizeInput step 3) { val set1 = input[i-2].toSet() val set2 = input[i-1].toSet() val set3 = input[i-0].toSet() for (j in set1) { if (set2.contains(j)) { if (set3.contains(j)) { elementRepeat.add(j) break } } } } var sumValuePriority = 0 for (i in elementRepeat){ sumValuePriority += priorityValue[i]!! } println(sumValuePriority) } part1() part2() }
0
Kotlin
0
0
df0ff2ed7c1ebde9327cd1a102499ac5467b73be
1,817
AdventOfCode-2022-Kotlin
Apache License 2.0
puzzles/src/main/kotlin/com/kotlinground/puzzles/arrays/meetingrooms/meetingRooms.kt
BrianLusina
113,182,832
false
{"Kotlin": 483489, "Shell": 7283, "Python": 1725}
package com.kotlinground.puzzles.arrays.meetingrooms import java.util.* /** * Uses 2 lists to find the minimum number of meeting rooms required * * Complexity: * Time Complexity: O(n*log(n)) as we sort the 2 lists * Space Complexity: O(n) we store the meetings in a list * * @param meetings: start and end times of meetings * @return: minimum number of meeting rooms to allocated */ fun findMinimumMeetingRooms(meetings: Array<IntArray>): Int { if (meetings.isEmpty()) { return 0 } val startTimes = arrayListOf<Int>() val endTimes = arrayListOf<Int>() for (meeting in meetings) { startTimes.add(meeting[0]) endTimes.add(meeting[1]) } startTimes.sort() endTimes.sort() var j = 0 var numRooms = 0 for (i in 0 until startTimes.size) { if (startTimes[i] < endTimes[j]) { numRooms++ } else { j++ } } return numRooms } /** * Uses a priority queue to find minimum number of meetings * * Complexity: * Time Complexity: O(log(n)) as we sort the list * Space Complexity: O(n) we store the meetings in a list * * @param meetings: start and end times of meetings * @return: minimum number of meeting rooms to allocated */ fun findMinimumMeetingRoomsPriorityQueue(meetings: Array<IntArray>): Int { if (meetings.isEmpty()) { return 0 } Arrays.sort(meetings) { a, b -> a[0] - b[0] } val rooms = PriorityQueue<Int>() rooms.add(meetings[0][1]) for (i in 1 until meetings.size) { val start = meetings[i][0] val end = meetings[i][1] // if earliest ending meeting ends before the next meeting starts, remove it from the heap if (rooms.peek() <= start) { rooms.poll() } rooms.add(end) } return rooms.size }
1
Kotlin
1
0
5e3e45b84176ea2d9eb36f4f625de89d8685e000
1,849
KotlinGround
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/SortColors.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode private const val RED = 0 private const val WHITE = 1 private const val BLUE = 2 fun interface SortColorsStrategy { operator fun invoke(nums: IntArray) } class SortColorsOnePass : SortColorsStrategy { override operator fun invoke(nums: IntArray) { var p1 = 0 var p2 = nums.size - 1 var index = 0 while (index <= p2) { if (nums[index] == RED) { nums[index] = nums[p1] nums[p1] = RED p1++ } if (nums[index] == BLUE) { nums[index] = nums[p2] nums[p2] = BLUE p2-- index-- } index++ } } } class SortColorsTwoPass : SortColorsStrategy { override operator fun invoke(nums: IntArray) { var red = 0 var white = 0 var blue = 0 for (num in nums) { when (num) { RED -> red++ WHITE -> white++ BLUE -> blue++ } } for (i in nums.indices) { when { i < red -> nums[i] = RED i < red + white -> nums[i] = WHITE else -> nums[i] = BLUE } } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,900
kotlab
Apache License 2.0
src/main/aoc2022/Day25.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2022 import kotlin.math.pow class Day25(input: List<String>) { val numbers = input.map { snafuToDecimal(it) } private fun Char.value(): Double = when (this) { '1' -> 1.0 '2' -> 2.0 '0' -> 0.0 '-' -> -1.0 '=' -> -2.0 else -> error("Invalid digit") } private fun snafuToDecimal(snafu: String): Double { var ret = 0.0 var power = 0 for (digit in snafu.reversed()) { ret += digit.value() * 5.0.pow(power++) } return ret } /** * Converts one decimal digit to the snafu version of it. Does not include the carry, that * is 4 ==> 1-. This is handle separately by the caller of this function. * @param target The digit to convert * @param smaller The decimal value that the snafu digit 0 represent at the current position. So if target is 26 * this would be 25. In other words, the largest power of 5 that is smaller than target. */ private fun convertDecimalDigitToSnafu(target: Double, smaller: Double) = when (target) { 0.0 -> "0" in smaller..<smaller * 2 -> "1" in smaller * 2..<smaller * 3 -> "2" in smaller * 3..<smaller * 4 -> "=" in smaller * 4..<smaller * 5 -> "-" else -> error("should never happen") } /*** * The result of adding one to a snafu digit (carry is not included) */ private fun String.plusOne() = when (this) { "0" -> "1" "1" -> "2" "2" -> "=" "=" -> "-" "-" -> "0" else -> error("should not happen") } /** * Convert a decimal digit to a Snafu digit. */ private fun decimalToSnafu(dec: Double): String { var ret = "" var power = 0 var carry = false var processed = 0.0 do { // Get the least significant, unprocessed digit by getting the remainder when dividing by the next digit. val target = (dec - processed) % 5.0.pow(power + 1) val result = convertDecimalDigitToSnafu(target, 5.0.pow(power++)) // If the previous digit subtracts from this one (carry set) then this digit needs to be increased. val toAdd = if (carry) result.plusOne() else result // If this digit subtracts from the next one, we need to remember that when processing the next digit. carry = if (carry) toAdd in listOf("0", "-", "=") else toAdd in listOf("-", "=") ret = toAdd + ret processed += target } while (processed < dec) return if (carry) "1$ret" else ret } fun solvePart1(): String { return decimalToSnafu(numbers.sum()) } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
2,738
aoc
MIT License
src/Day05.kt
TheGreatJakester
573,222,328
false
{"Kotlin": 47612}
import utils.string.asLines import utils.string.asParts import java.lang.Exception private data class Move(val count: Int, val from: Int, val to: Int) private typealias Tower = ArrayDeque<Char> fun main() { fun readInTowers(input: List<String>, towerCount: Int): List<Tower> { val towers = List(towerCount) { ArrayDeque<Char>() } input.forEach { line -> for (towerIndex in 0 until towerCount) { val letterIndex = towerIndex * 4 + 1 if (letterIndex > line.length) break val letter = line[letterIndex] if (letter != ' ') { towers[towerIndex].add(letter) } } } return towers } fun readInMoves(input: List<String>): List<Move> { return input.map { val broken = it.split(" ") Move(broken[1].toInt(), broken[3].toInt() - 1, broken[5].toInt() - 1) } } fun moveSingle(from: Tower, to: Tower, count: Int) { repeat(count) { from.removeFirst().let(to::addFirst) } } fun moveMultiple(from: Tower, to: Tower, count: Int) { val top = from.take(count) repeat(count) { from.removeFirst() } to.addAll(0, top) } object : Challenge<String>("Day05", "CMZ", "MCD") { fun Context.asTowersAndMoves(): Pair<List<Tower>, List<Move>> { val (towerInput, moveInput) = fileContents.asParts() val towerLines = towerInput.asLines().dropLast(1) val towerCount = towerLines.last().length / 4 + 1 val towers = readInTowers(towerLines, towerCount) val moves = readInMoves(moveInput.asLines()) return towers to moves } override fun Context.part1(): String { val (towers, moves) = asTowersAndMoves() moves.forEach { moveSingle(towers[it.from], towers[it.to], it.count) } return towers.joinToString(separator = "") { it.first().toString() } } override fun Context.part2(): String { val (towers, moves) = asTowersAndMoves() moves.forEach { moveMultiple(towers[it.from], towers[it.to], it.count) } return towers.joinToString(separator = "") { it.first().toString() } } }.trySolve() }
0
Kotlin
0
0
c76c213006eb8dfb44b26822a44324b66600f933
2,413
2022-AOC-Kotlin
Apache License 2.0
src/main/kotlin/days/Day13.kt
andilau
429,557,457
false
{"Kotlin": 103829}
package days @AdventOfCodePuzzle( name = "Knights of the Dinner Table", url = "https://adventofcode.com/2015/day/13", date = Date(day = 13, year = 2015) ) class Day13(happinessStatements: List<String>) : Puzzle { private val happinessMap = happinessStatements.parseStatements() override fun partOne(): Int = happinessMap .guests() .arrangements() .maxOf { arrangement -> arrangement.totalHappiness(happinessMap) } override fun partTwo(): Int = happinessMap.toMutableMap() .apply { happinessMap.guests().forEach { guest -> this[Guest("Me") to guest] = 0 this[guest to Guest("Me")] = 0 } }.let { it .guests() .arrangements() .maxOf { arrangement -> arrangement.totalHappiness(it) } } private fun Map<Pair<Guest, Guest>, Int>.guests() = keys.map { it.first }.toSet() private fun List<Guest>.totalHappiness(mutableMap: Map<Pair<Guest, Guest>, Int>): Int { return this.sumOf { person -> val leftNeighbor = this[(indexOf(person) - 1 + size) % size] val rightNeighbor = this[(indexOf(person) + 1) % size] mutableMap[person to leftNeighbor]!! + mutableMap[person to rightNeighbor]!! } } private fun List<String>.parseStatements() = associate { line -> val (guest, gainLose, happiness, neighbor) = STATEMENT_PATTERN.matchEntire(line)!!.destructured Pair(Guest(guest), Guest(neighbor)) to if (gainLose == "gain") happiness.toInt() else -happiness.toInt() }.toMap() companion object { private val STATEMENT_PATTERN = Regex("""^(\w+) would (gain|lose) (\d+) happiness units by sitting next to (\w+).$""") } data class Guest(val name: String) }
0
Kotlin
0
0
55932fb63d6a13a1aa8c8df127593d38b760a34c
1,947
advent-of-code-2015
Creative Commons Zero v1.0 Universal
src/Day10.kt
Sasikuttan2163
647,296,570
false
null
fun main() { var cycleCount = 1 val keyframes = mutableListOf(20, 60, 100, 140, 180, 220) var x = 1 val instructionQueue = mutableListOf<Pair<Int, Int>>() readInput("Day10").forEach { line -> cycleCount += if (line.startsWith("addx")) { instructionQueue.add(Pair(cycleCount + 2, line.substringAfter(" ").toInt())) 2 } else { 1 } } val part1 = (2..220).toList().sumOf { cycle -> x += instructionQueue.firstOrNull { it.first == cycle }?.second ?: 0 if (keyframes.contains(cycle)) { x * cycle } else { 0 } } part1.println() x = 1 val part2 = (1..240).fold("") { crt, cycle -> x += instructionQueue.firstOrNull { it.first == cycle }?.second ?: 0 crt + if ((x - 1..x + 1).toList().contains((cycle - 1) % 40)) { "#" } else { "." } }.chunked(40).joinToString(separator = "\n") part2.println() }
0
Kotlin
0
0
fb2ade48707c2df7b0ace27250d5ee240b01a4d6
1,012
AoC-2022-Solutions-In-Kotlin
MIT License
year2018/src/main/kotlin/net/olegg/aoc/year2018/day10/Day10.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2018.day10 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.Vector2D import net.olegg.aoc.year2018.DayOf2018 /** * See [Year 2018, Day 10](https://adventofcode.com/2018/day/10) */ object Day10 : DayOf2018(10) { private val PATTERN = "position=<\\s*(-?\\d+),\\s*(-?\\d+)> velocity=<\\s*(-?\\d+),\\s*(-?\\d+)>".toRegex() private const val HEIGHT = 16 override fun first(): Any? { val points = lines .mapNotNull { line -> PATTERN.find(line)?.let { match -> val (x, y, vx, vy) = match.destructured.toList().map { it.toInt() } return@let Vector2D(x, y) to Vector2D(vx, vy) } } val final = generateSequence(points) { curr -> curr.map { it.copy(first = it.first + it.second) } } .first { curr -> curr.map { it.first.y }.let { it.max() - it.min() } <= HEIGHT } val coords = final.map { it.first } val xmin = coords.minOf { it.x } val xmax = coords.maxOf { it.x } val ymin = coords.minOf { it.y } val ymax = coords.maxOf { it.y } return buildString { append('\n') (ymin..ymax).forEach { y -> (xmin..xmax).forEach { x -> append(if (Vector2D(x, y) in coords) "██" else "..") } append('\n') } } } override fun second(): Any? { val points = lines .mapNotNull { line -> PATTERN.find(line)?.let { match -> val (x, y, vx, vy) = match.destructured.toList().map { it.toInt() } return@let Vector2D(x, y) to Vector2D(vx, vy) } } val final = generateSequence(points) { curr -> curr.map { it.copy(first = it.first + it.second) } } .indexOfFirst { curr -> curr.map { it.first.y }.let { it.max() - it.min() } <= HEIGHT } return final } } fun main() = SomeDay.mainify(Day10)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
1,876
adventofcode
MIT License
exercises/practice/binary-search/.meta/src/reference/kotlin/BinarySearch.kt
exercism
47,675,865
false
{"Kotlin": 382097, "Shell": 14600}
object BinarySearch { fun <T: Comparable<T>> search(list: List<T>, item: T) : Int { require(list.isSorted()) {"The provided list must be sorted in ascending order"} if(list.isEmpty()) { throw NoSuchElementException("value $item is not in array $list") } return searchRec(list, item, 0) } private tailrec fun <T: Comparable<T>> searchRec(list: List<T>, item: T, accumulatedOffset: Int) : Int { if(1 == list.size) { return if(list.first() == item) accumulatedOffset else throw NoSuchElementException("value $item is not in array $list") } val midIndex = list.size / 2 val midValue = list[midIndex] if(item < midValue) { return searchRec(list.subList(0, midIndex), item, accumulatedOffset) } return searchRec(list.subList(midIndex, list.size), item, midIndex + accumulatedOffset) } /** * The following extension methods are more general, in a project they would probably not be private */ /** * Uses a sequence of Pair objects in order to avoid calculating all the pairs beforehand in cases * where the list is not sorted */ private fun <T: Comparable<T>> List<T>.isSorted(): Boolean { if(this.isEmpty()) { return true } return this.pairsSequence().all { it.first <= it.second } } /** * Returns a sequence of Pair objects containing all each object of the list plus it's following object */ private fun <T> List<T>.pairsSequence() : Sequence<Pair<T, T>> { if(this.size < 2) { return emptySequence() } val list = this return object : Sequence<Pair<T, T>> { override fun iterator(): Iterator<Pair<T, T>> { return object: AbstractIterator<Pair<T, T>>() { var index = 0 override fun computeNext() { if(index >= (list.size-1)) { done() } else { setNext(Pair(list[index], list[index+1])) index += 1 } } } } } } }
51
Kotlin
190
199
7f1c7a11cfe84499cfef4ea2ecbc6c6bf34a6ab9
2,309
kotlin
MIT License
BayesClassifier.kt
khqnn
296,738,545
false
null
class BayesClassifier{ private var vocabSize = 0 private var positiveSum = 0 private var negativeSum = 0 private var positiveClassProbability = 0.0 private var negativeClassProbability = 0.0 private val positiveCorpus = mutableMapOf<String, Int>() private val negativeCorpus = mutableMapOf<String, Int>() private fun calculateParams(){ positiveSum = positiveCorpus.values.sum() negativeSum = negativeCorpus.values.sum() positiveClassProbability = positiveSum.toDouble()/(positiveSum+negativeSum) negativeClassProbability = negativeSum.toDouble()/(positiveSum+negativeSum) vocabSize = positiveCorpus.size + negativeCorpus.size } fun getCorpus(selectedClass: Int): Map<String, Int>{ when(selectedClass){ CLASS_POSITIVE-> return positiveCorpus CLASS_NEGATIVE-> return negativeCorpus else-> return mapOf() } } fun getWordsFrequency(text: String): Map<String, Int>{ val words = text.toLowerCase().split(" ").map { Regex("[^a-zA-Z]").replace( it , "") } as MutableList<String> words.removeAll(englishStopWords) val corpus = words.groupingBy{ it } .eachCount() return corpus } private fun addIntoCorpus(wf: Map<String, Int>, selectedClass:Int){ wf.forEach{ val word = it.key val frequency = it.value when(selectedClass){ CLASS_POSITIVE->{ positiveCorpus[word] = positiveCorpus.getOrPut(word){0} + frequency } CLASS_NEGATIVE->{ negativeCorpus[word] = negativeCorpus.getOrPut(word){0} + frequency } } } calculateParams() } fun updateCorpus(wf: Map<String, Int>, selectedClass: Int){ addIntoCorpus(wf, selectedClass) } fun updateCorpus(text: String, selectedClass: Int){ val wf = getWordsFrequency(text) addIntoCorpus(wf, selectedClass) } fun probabilityOfWordByClass(word: String, selectedClass: Int): Double{ when(selectedClass){ CLASS_POSITIVE-> return (1.0+positiveCorpus.getOrPut(word){0})/(positiveSum+vocabSize) CLASS_NEGATIVE-> return (1.0+negativeCorpus.getOrPut(word){0})/(negativeSum+vocabSize) else-> return 0.0 } } fun liklyhoodEstimation(wf: Map<String, Int>, selectedClass: Int): Double{ var LE = 1.0 wf.forEach{ val word = it.key val frequency = it.value val pr_of_word = Math.pow(probabilityOfWordByClass(word, selectedClass), frequency.toDouble()) LE *= pr_of_word } when(selectedClass){ CLASS_POSITIVE-> LE *= positiveClassProbability CLASS_NEGATIVE-> LE *= negativeClassProbability } return LE } fun predictClass(text: String): Int{ val wf = getWordsFrequency(text) val POSITIVE_LIKLYHOOD = liklyhoodEstimation(wf, CLASS_POSITIVE) val NEGATIVE_LIKLYHOOD = liklyhoodEstimation(wf, CLASS_NEGATIVE) if(POSITIVE_LIKLYHOOD>NEGATIVE_LIKLYHOOD) return CLASS_POSITIVE return CLASS_NEGATIVE } fun getTokens( text : String ) : Array<String> { val tokens = text.toLowerCase().split( " " ) val filteredTokens = ArrayList<String>() for ( i in 0 until tokens.count() ) { if ( !tokens[i].trim().isBlank() ) { filteredTokens.add( tokens[ i ] ) } } val stopWordRemovedTokens = tokens.map { Regex("[^a-zA-Z]").replace( it , "") } as ArrayList<String> stopWordRemovedTokens.removeAll { englishStopWords.contains( it ) or it.trim().isBlank() } return stopWordRemovedTokens.distinct().toTypedArray() } companion object { val CLASS_POSITIVE = 0 // Spam val CLASS_NEGATIVE = 1 // Ham val englishStopWords = arrayOf( "i", "me", "my", "myself", "we", "our", "ours", "ourselves", "you", "your", "yours", "yourself", "yourselves", "he", "him", "his", "himself", "she", "her", "hers", "herself", "it", "its", "itself", "they", "them", "their", "theirs", "themselves", "what", "which", "who", "whom", "this", "that", "these", "those", "am", "is", "are", "was", "were", "be", "been", "being", "have", "has", "had", "having", "do", "does", "did", "doing", "a", "an", "the", "and", "but", "if", "or", "because", "as", "until", "while", "of", "at", "by", "for", "with", "about", "against", "between", "into", "through", "during", "before", "after", "above", "below", "to", "from", "up", "down", "in", "out", "on", "off", "over", "under", "again", "further", "then", "once", "here", "there", "when", "where", "why", "how", "all", "any", "both", "each", "few", "more", "most", "other", "some", "such", "no", "nor", "not", "only", "own", "same", "so", "than", "too", "very", "s", "t", "can", "will", "just", "don", "should", "now" , "hello" , "hi" , "dear" , "respected" , "thank" ) } }
0
Kotlin
0
0
1f0278d680648b0191297ec546f8db9941e53d4b
5,279
Naive-Bayes-Classifier
MIT License
src/Java/LeetcodeSolutions/src/main/java/leetcode/solutions/concrete/kotlin/Solution_12_Integer_to_Roman.kt
v43d3rm4k4r
515,553,024
false
{"Kotlin": 40113, "Java": 25728}
package leetcode.solutions.concrete.kotlin import leetcode.solutions.* import leetcode.solutions.ProblemDifficulty.* import leetcode.solutions.validation.SolutionValidator.* import leetcode.solutions.annotations.ProblemInputData import leetcode.solutions.annotations.ProblemSolution import leetcode.solutions.annotations.ProblemSolutionData import kotlin.math.log10 /** * __Problem:__ Given an integer, convert it to a roman numeral. * * __Constraints:__ * - 1 <= _num_ <= 3999 * __Solution 1:__ * - Iterate over the provided integer, checking each number. * - Checking the following situations: * * 1) I can be placed before V (5) and X (10) to make 4 and 9. * 2) X can be placed before L (50) and C (100) to make 40 and 90. * 3) C can be placed before D (500) and M (1000) to make 400 and 900. * * __Time:__ O(N) * * __Space:__ O(1) * * __Solution 2:__ This solution is more elegant in terms of code quality, but requires additional memory overhead. * * __Time:__ O(N) * * __Space:__ O(1) * * @see Solution_13_Roman_to_Integer * @author <NAME> */ class Solution_12_Integer_to_Roman : LeetcodeSolution(MEDIUM) { @ProblemSolution(timeComplexity = "O(N)", spaceComplexity = "O(1)") private fun intToRoman1(num: Int): String { var numCopy = num var digit: Int var result = "" for (i in 0..log10(num.toFloat()).toInt()) { digit = numCopy % 10 when (digit) { in 0..3 -> { result = when (i) { 0 -> "I".repeat(digit) + result 1 -> "X".repeat(digit) + result 2 -> "C".repeat(digit) + result 3 -> "M".repeat(digit) + result else -> result } } 4 -> { result = when (i) { 0 -> "IV$result" 1 -> "XL$result" 2 -> "CD$result" else -> result } } 5 -> { result = when (i) { 0 -> "V$result" 1 -> "L$result" 2 -> "D$result" else -> result } } in 6..8 -> { result = when (i) { 0 -> "V" + "I".repeat(digit - 5) + result 1 -> "L" + "X".repeat(digit - 5) + result 2 -> "D" + "C".repeat(digit - 5) + result else -> result } } 9 -> { result = when (i) { 0 -> "IX$result" 1 -> "XC$result" 2 -> "CM$result" else -> result } } } numCopy /= 10 } return result } @ProblemSolution(timeComplexity = "O(N)", spaceComplexity = "O(1)") private fun intToRoman2(num: Int): String { var number = num var position = 0 var result = "" while (number > 0) { val digit = number % 10 result += ROMANS[position][digit] number /= 10 ++position } return result } companion object { @ProblemSolutionData(solution = 2) val ROMANS = arrayOf( arrayOf("", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"), arrayOf("", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"), arrayOf("", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"), arrayOf("", "M", "MM", "MMM"), ) } @ProblemInputData override fun run() { ASSERT_STREQ("III", intToRoman1(3)) ASSERT_STREQ("LVIII", intToRoman1(58)) ASSERT_STREQ("MCMXCIV", intToRoman1(1994)) ASSERT_STREQ("III", intToRoman2(3)) ASSERT_STREQ("LVIII", intToRoman2(58)) ASSERT_STREQ("MCMXCIV", intToRoman2(1994)) } }
0
Kotlin
0
1
c5a7e389c943c85a90594315ff99e4aef87bff65
4,191
LeetcodeSolutions
Apache License 2.0
src/Day15.kt
jrmacgill
573,065,109
false
{"Kotlin": 76362}
import utils.* import java.lang.Math.max import java.lang.Math.min class Day15 { fun go() { var lines =readInput("day15_test") //var lines =readInput("day15") val row = 2000000 //val row = 10 val data = mutableListOf<List<Int>>() val sensors = mutableMapOf<Point, Point>() println("sizing") lines.forEach{ var values = it.extractAllIntegers() data.add(values) sensors[Point(values[0], values[1])] = Point(values[2], values[3]) } var minx = data.minOf { i -> min(i[0], i[2])} var miny = data.minOf { i -> min(i[1], i[3])} var maxx = data.maxOf { i -> max(i[0], i[2])} var maxy = data.maxOf { i -> max(i[1], i[3])} //val row = 2000000 var count = 0 for (x in minx-100000000 .. maxx+10000000) { var test = Point(x, row) var found = false sensors.forEach{p -> if (p.value != test && p.key != test) { var dist = test.manhattanDistanceTo(p.key) var range = p.key.manhattanDistanceTo(p.value) if (dist <= range) { found = true //return@forEach } } else { // found = false // } } if (found) {count++} } println("answer is") println(count) /* println(data) println(minx) println(miny) println("make grid") var grid = MutableGrid(maxx-minx+1,maxy-miny+1) { _ -> '.' } var sensor = Point(0,0) var beacon = Point(0,0) println("process") data.forEach{it -> run { sensor = Point(it[0] - minx, it[1] - miny) beacon = Point(it[2] - minx, it[3] - miny) grid.forAreaIndexed { p, v -> if (sensor.manhattanDistanceTo(p) <= sensor.manhattanDistanceTo(beacon)) { grid.set(p, '#') } } //grid= grid.mapValuesIndexed { pair, c -> if (sensor.manhattanDistanceTo(pair) <= dist) '#' else c }.toMutableGrid() // println() // println(temp.formatted()) grid.set(Point(it[0] - minx, it[1] - miny), 'S') grid.set(Point(it[2] - minx, it[3] - miny), 'B') } } // println(grid.formatted()) println("done") println(grid[2000000-miny].count{ it -> it != '.' && it != 'B'}) */ } } fun main() { Day15().go() }
0
Kotlin
0
1
3dcd590f971b6e9c064b444139d6442df034355b
2,692
aoc-2022-kotlin
Apache License 2.0
src/main/kotlin/day5/Day5.kt
errob37
573,508,650
false
{"Kotlin": 18301}
package day5 import ResourceFileReader class Day5 { companion object { private val stacks = mapOf<Int, MutableList<String>>( 1 to mutableListOf(), 2 to mutableListOf(), 3 to mutableListOf(), 4 to mutableListOf(), 5 to mutableListOf(), 6 to mutableListOf(), 7 to mutableListOf(), 8 to mutableListOf(), 9 to mutableListOf() ) private val stackCharacterPosition = mapOf( 1 to 1, 2 to 5, 3 to 9, 4 to 13, 5 to 17, 6 to 21, 7 to 25, 8 to 29, 9 to 33 ) fun problem1() = getTopCrates(CrateMoverModel.MODEL_9000) fun problem2() = getTopCrates(CrateMoverModel.MODEL_9001) private fun getTopCrates(crateMover: CrateMoverModel): String { val (rawStacks, movesToDo) = getInput() val moves = movesToDo .split("\n") .filter { it.isNotBlank() } .map(String::toMove) fillStacks(rawStacks) moves.forEach { val toMoved = mutableListOf<String>() for (i in 1..it.howMany) { if (crateMover == CrateMoverModel.MODEL_9000) { stacks[it.to]!!.add(stacks[it.from]!!.removeLast()) } else if (crateMover == CrateMoverModel.MODEL_9001) { toMoved.add(stacks[it.from]!!.removeLast()) } } if (crateMover == CrateMoverModel.MODEL_9001) { stacks[it.to]!!.addAll(toMoved.reversed()) } } return stacks.values .filter { it.isNotEmpty() } .joinToString("") { it.last() } } private fun getInput(): List<String> { return ResourceFileReader .readAocFile(5) .split("\n\n") .filter { it.isNotBlank() } } private fun fillStacks(rawStacks: String) { rawStacks .split("\n") .filter { it.isNotBlank() } .dropLast(1) .reversed() .forEach { val s = it.padEnd(34).toCharArray() stackCharacterPosition.forEach { (k, v) -> stacks[k]!!.addIfNotBlank(s[v].toString()) } } } } } fun String.toMove(): Move { val (howManyRaw, fromToRaw) = this.split(" from ") val fromTo = fromToRaw.split(" to ") return Move( fromTo.first().toInt(), fromTo[1].toInt(), howManyRaw.removePrefix("move ").toInt() ) } fun MutableList<String>.addIfNotBlank(element: String): Boolean = if (element.isNotBlank()) this.add(element) else false class Move(val from: Int, val to: Int, val howMany: Int) enum class CrateMoverModel { MODEL_9000, MODEL_9001; }
0
Kotlin
0
0
7e84babb58eabbdb636f8cca87fdcf4314fb2af0
3,019
adventofcode-2022
Apache License 2.0
tools/recipe/src/main/kotlin/top/bettercode/summer/tools/recipe/result/RecipeExt.kt
top-bettercode
387,652,015
false
{"Kotlin": 2939064, "Java": 24119, "JavaScript": 22541, "CSS": 22336, "HTML": 15833}
package top.bettercode.summer.tools.recipe.result import top.bettercode.summer.tools.recipe.criteria.DoubleRange import top.bettercode.summer.tools.recipe.criteria.RecipeRelation import top.bettercode.summer.tools.recipe.material.MaterialIDs.Companion.toMaterialIDs import top.bettercode.summer.tools.recipe.material.RecipeMaterialValue /** * * @author <NAME> */ class RecipeExt(private val recipe: Recipe) { val RecipeMaterialValue.range: DoubleRange? get() { return recipe.requirement.materialRangeConstraints.filter { it.key.contains(this.id) }.values.firstOrNull() } val RecipeMaterialValue.double: Boolean get() { val relationMap = recipe.requirement.materialRelationConstraints.values.find { it.keys.any { m -> m.contains(this.id) } } ?: return false val iDs = relationMap.keys.first { it.contains(this.id) } val recipeRelation = relationMap[iDs] return recipeRelation?.overdose != null || recipeRelation?.overdoseMaterial != null } val RecipeMaterialValue.relationName: String? get() { val materialRelationConstraints = recipe.requirement.materialRelationConstraints.filter { it.value.keys.any { m -> m.contains(this.id) } } val ids = materialRelationConstraints.keys.firstOrNull() ?: return null val materials = recipe.materials val usedIds = materials.filter { ids.contains(it.id) }.map { it.id }.toMaterialIDs() return usedIds.toString() } private val RecipeMaterialValue.replaceRate: Double get() { val materialRelationConstraints = recipe.requirement.materialRelationConstraints.filter { it.value.keys.any { m -> m.contains(this.id) } } val ids = materialRelationConstraints.keys.firstOrNull() ?: return 1.0 val materials = recipe.materials val usedIds = materials.filter { ids.contains(it.id) }.map { it.id }.toMaterialIDs() return if (ids.replaceIds == usedIds) ids.replaceRate ?: 1.0 else 1.0 } val RecipeMaterialValue.relationRate: RecipeRelation? get() { val relationMap = recipe.requirement.materialRelationConstraints.values.find { it.keys.any { m -> m.contains(this.id) } } ?: return null val iDs = relationMap.keys.first { it.contains(this.id) } val recipeRelation = relationMap[iDs] return recipeRelation?.replaceRate(replaceRate) } val RecipeMaterialValue.relationValue: Pair<DoubleRange, DoubleRange>? get() { val relationRate = relationRate if (relationRate == null) { val materialRelationConstraints = recipe.requirement.materialRelationConstraints.filter { it.key.contains(this.id) } val entry = materialRelationConstraints.entries.firstOrNull() ?: return null recipe.apply { return entry.relationValue } } else { var usedMinNormalWeight = 0.0 var usedMaxNormalWeight = 0.0 var usedMinOverdoseWeight = 0.0 var usedMaxOverdoseWeight = 0.0 val normal = relationRate.normal val overdose = relationRate.overdose if (normalWeight > 0) { usedMinNormalWeight += normalWeight * normal.min * replaceRate usedMaxNormalWeight += normalWeight * normal.max * replaceRate if (overdose != null) { usedMinOverdoseWeight += normalWeight * overdose.min * replaceRate usedMaxOverdoseWeight += normalWeight * overdose.max * replaceRate } } else { usedMinNormalWeight += weight * normal.min * replaceRate usedMaxNormalWeight += weight * normal.max * replaceRate if (overdose != null) { usedMinOverdoseWeight += weight * overdose.min * replaceRate usedMaxOverdoseWeight += weight * overdose.max * replaceRate } } //过量物料 var usedMinOverdoseMaterialWeight = 0.0 var usedMaxOverdoseMaterialWeight = 0.0 val overdoseMaterial = relationRate.overdoseMaterial if (overdoseMaterial != null && overdoseWeight > 0) { val overdoseMaterialNormal = overdoseMaterial.normal val overdoseMaterialOverdose = overdoseMaterial.overdose usedMinOverdoseMaterialWeight += overdoseWeight * overdoseMaterialNormal.min * replaceRate usedMaxOverdoseMaterialWeight += overdoseWeight * overdoseMaterialNormal.max * replaceRate if (overdoseMaterialOverdose != null) { usedMinOverdoseMaterialWeight += overdoseWeight * overdoseMaterialOverdose.min * replaceRate usedMaxOverdoseMaterialWeight += overdoseWeight * overdoseMaterialOverdose.max * replaceRate } } if (usedMinOverdoseWeight == 0.0) { usedMinOverdoseWeight = usedMinOverdoseMaterialWeight } if (usedMaxOverdoseWeight == 0.0) { usedMaxOverdoseWeight = usedMaxOverdoseMaterialWeight } return DoubleRange(usedMinNormalWeight, usedMaxNormalWeight) to DoubleRange(usedMinOverdoseWeight, usedMaxOverdoseWeight) } } }
0
Kotlin
0
1
d07ed7250e6dcdbcce51f27f5f22602e9c222b3c
5,678
summer
Apache License 2.0
src/main/kotlin/Day06.kt
brigham
573,127,412
false
{"Kotlin": 59675}
fun main() { fun part1(input: List<String>): Int { val line = input[0] return line .windowedSequence(4, 1) .mapIndexed { index, s -> if (s.toSet().size == 4) index + 4 else null } .filterNotNull().first() } fun part2(input: List<String>): Int { val line = input[0] return line .windowedSequence(14, 1) .mapIndexed { index, s -> if (s.toSet().size == 14) index + 14 else null } .filterNotNull().first() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") check(part1(testInput) == 5) // check(part2(testInput) == 1) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
b87ffc772e5bd9fd721d552913cf79c575062f19
802
advent-of-code-2022
Apache License 2.0
kotlin/0212-word-search-ii.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}
class Solution { private companion object{ const val IMPOSSIBLE: Char = '#' val DIRS = intArrayOf(0, -1, 0, 1, 0) } fun findWords(board: Array<CharArray>, words: Array<String>): List<String> { val nRows = board.size val nCols = board[0].size val root = buildTrie(words) val ans = mutableListOf<String>() for(row in 0 until nRows){ for(col in 0 until nCols){ backtrack(row, col, board, root, ans) } } return ans } private fun backtrack(row: Int, col: Int, board: Array<CharArray>, node: TrieNode, res: MutableList<String>){ val nRows = board.size val nCols = board[0].size if(row < 0 || row >= nRows || col < 0 || col >= nCols) return val hold = board[row][col] val idx = hold.toInt() - 'a'.toInt(); if(hold == IMPOSSIBLE || node.children[idx] == null){ return } var cur: TrieNode? = node cur = cur!!.children[idx] if(cur!!.word != null){ res.add(cur.word!!) cur.word = null } board[row][col] = IMPOSSIBLE for(d in 0 until 4){ val r = row + DIRS[d] val c = col + DIRS[d + 1] backtrack(r, c, board, cur, res) } board[row][col] = hold } private fun buildTrie(words: Array<String>): TrieNode{ val root = TrieNode() for(word in words){ var cur: TrieNode? = root for(ch in word){ val idx = ch.toInt() - 'a'.toInt() if(cur!!.children[idx] == null) cur.children[idx] = TrieNode() cur = cur.children[idx] } cur!!.word = word } return root } private data class TrieNode(var word: String? = null){ val children: Array<TrieNode?> = Array(26){ null } } }
337
JavaScript
2,004
4,367
0cf38f0d05cd76f9e96f08da22e063353af86224
1,962
leetcode
MIT License
src/main/kotlin/nl/jackploeg/aoc/_2023/calendar/day13/Day13.kt
jackploeg
736,755,380
false
{"Kotlin": 318734}
package nl.jackploeg.aoc._2023.calendar.day13 import nl.jackploeg.aoc.generators.InputGenerator.InputGeneratorFactory import nl.jackploeg.aoc.utilities.readStringFile import javax.inject.Inject import kotlin.math.min typealias Pattern = MutableList<MutableList<Char>> class Day13 @Inject constructor( private val generatorFactory: InputGeneratorFactory, ) { // find reflections fun partOne(fileName: String): Int { val patterns: MutableList<MutableList<String>> = mutableListOf() var pattern: MutableList<String> = mutableListOf() readStringFile(fileName).forEach { line -> if (line == "") { patterns.add(pattern) pattern = mutableListOf() } else { pattern.add(line) } } patterns.add(pattern) return patterns.sumOf { findReflection(it) } } // find reflections after clearing smudges fun partTwo(fileName: String): Int { val patterns: MutableList<MutableList<String>> = mutableListOf() var pattern: MutableList<String> = mutableListOf() readStringFile(fileName).forEach { line -> if (line == "") { patterns.add(pattern) pattern = mutableListOf() } else { pattern.add(line) } } patterns.add(pattern) return patterns.sumOf { findSmudgeClearedSolution(it) } } fun findSmudgeClearedSolution(pattern: MutableList<String>): Int { val oldScore = findReflection(pattern) for (i in 0 until pattern.size) { val lineToClear = pattern[i] for (j in 0 until pattern[i].length) { val newline = lineToClear.substring(0, j) + (if (lineToClear[j] == '.') '#' else '.') + lineToClear.substring(j + 1) val newPattern = pattern.subList(0, i).plus(newline).plus(pattern.subList(i + 1, pattern.size)) val score = findReflection(newPattern, oldScore) if (score != 0 && score != oldScore) return score } } return 0 } fun findReflection(pattern: List<String>, scoreToSkip: Int = 0): Int { // try to find reflection row for (row in 1 until pattern.size) { val rowsToCompare = min(row, pattern.size - row) if (pattern.subList(row - rowsToCompare, row).reversed() == pattern.subList(row, row + rowsToCompare)) { // found mirror row if (row * 100 != scoreToSkip) return row * 100 } } // no reflection row, try to find reflection column val patternWidth = pattern[0].length for (column in 1 until patternWidth) { val columnsToCompare = min(column, patternWidth - column) val columnsUptoX = (column - columnsToCompare until column).map { col -> pattern.map { it[col] }.joinToString("") } val columnsFromtoX = (column until column + columnsToCompare).map { col -> pattern.map { it[col] }.joinToString("") } if (columnsUptoX.reversed() == columnsFromtoX) { // found mirror column if (column != scoreToSkip) return column } } return 0 } }
0
Kotlin
0
0
f2b873b6cf24bf95a4ba3d0e4f6e007b96423b76
2,970
advent-of-code
MIT License
src/main/kotlin/year2021/day-18.kt
ppichler94
653,105,004
false
{"Kotlin": 182859}
package year2021 import lib.aoc.Day import lib.aoc.Part import lib.math.product import kotlin.math.roundToInt fun main() { Day(18, 2021, PartA18(), PartB18()).run() } open class PartA18 : Part() { protected lateinit var numbers: MutableList<String> override fun parse(text: String) { numbers = text.split("\n").toMutableList() } override fun compute(): String { var number = numbers.removeFirst() while (numbers.isNotEmpty()) { val nextNumber = numbers.removeFirst() number = "[${number},${nextNumber}]" number = reduce(number) } return magnitude(number).toString() } protected fun reduce(number: String): String { val exploded = explode(number) if (exploded != number) { return reduce(exploded) } else { val splitted = split(number) if (splitted != number) { return reduce(splitted) } return splitted } } private fun explode(number: String): String { var offset = 0 for (num in """\[\d+,\d+]""".toRegex().findAll(number)) { val pair = num.value.toRegex(RegexOption.LITERAL).find(number.drop(offset))!! val leftBracketsCount = number.take(pair.range.first + offset).count { it == '[' } val rightBracketsCount = number.take(pair.range.first + offset).count { it == ']' } if (leftBracketsCount - rightBracketsCount >= 4) { val (left, right) = pair.value.drop(1).dropLast(1).split(",") var leftPart = number.take(pair.range.first + offset).reversed() var rightPart = number.drop(pair.range.last + offset + 1) """\d+""".toRegex().find(leftPart)?.let { val x = (leftPart.slice(it.range).reversed().toInt() + left.toInt()).toString().reversed() leftPart = "${leftPart.take(it.range.first)}$x${leftPart.drop(it.range.last + 1)}" } """\d+""".toRegex().find(rightPart)?.let { val x = rightPart.slice(it.range).toInt() + right.toInt() rightPart = "${rightPart.take(it.range.first)}$x${rightPart.drop(it.range.last + 1)}" } return "${leftPart.reversed()}0$rightPart" } else { offset += pair.range.last + 1 } } return number } private fun split(number: String): String { """\d\d""".toRegex().find(number)?.let { val leftPart = number.take(it.range.first) val rightPart = number.drop(it.range.last + 1) val newLeftDigit = it.value.toInt() / 2 val newRightDigit = (it.value.toInt() / 2f).roundToInt() return "$leftPart[$newLeftDigit,$newRightDigit]$rightPart" } return number } protected fun magnitude(data: String): Int { var number = data while (number.count { it == ',' } > 1) { for (num in """\[\d+,\d+]""".toRegex().findAll(number)) { val pair = num.value.toRegex(RegexOption.LITERAL).find(number)!! val (left, right) = pair.value.drop(1).dropLast(1).split(",") val newNumber = left.toInt() * 3 + right.toInt() * 2 number = "${number.take(pair.range.first)}$newNumber${number.drop(pair.range.last + 1)}" } } val (left, right) = number.drop(1).dropLast(1).split(",") return left.toInt() * 3 + right.toInt() * 2 } override val exampleAnswer: String get() = "4230" } class PartB18 : PartA18() { override fun compute(): String { val pairs = numbers.permutations() return pairs.maxOf { pair -> magnitudeOfPair(pair) }.toString() } private fun <T> Iterable<T>.permutations(): List<Pair<T, T>> { return this.product(this).filter { it.first != it.second } } private fun magnitudeOfPair(pair: Pair<String, String>): Int { var number = "[${pair.first},${pair.second}]" number = reduce(number) return magnitude(number) } override val exampleAnswer: String get() = "4647" }
0
Kotlin
0
0
49dc6eb7aa2a68c45c716587427353567d7ea313
4,358
Advent-Of-Code-Kotlin
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinDistance.kt
ashtanko
515,874,521
false
{"Kotlin": 235302, "Shell": 755, "Makefile": 591}
/* * MIT License * Copyright (c) 2022 <NAME> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max import kotlin.math.min /** * 583. Delete Operation for Two Strings * @link https://leetcode.com/problems/delete-operation-for-two-strings/ */ fun interface MinDistance { operator fun invoke( word1: String, word2: String, ): Int } /** * Approach #1 Using Longest Common Subsequence * Time complexity : O(2^{max(m,n)}). * Space complexity : O(max (m,n))). */ val minDistanceLcs = MinDistance { word1: String, word2: String -> fun lcs( s1: String, s2: String, m: Int, n: Int, ): Int { if (m == 0 || n == 0) { return 0 } return if (s1[m - 1] == s2[n - 1]) { 1 + lcs(s1, s2, m - 1, n - 1) } else { max(lcs(s1, s2, m, n - 1), lcs(s1, s2, m - 1, n)) } } return@MinDistance word1.length + word2.length - 2 * lcs(word1, word2, word1.length, word2.length) } /** * Approach #2 Longest Common Subsequence with Memoization * Time complexity : O(m*n). * Space complexity : O(m*n). */ val minDistanceLcsMemo = MinDistance { word1: String, word2: String -> fun lcs( s1: String, s2: String, m: Int, n: Int, memo: Array<IntArray>, ): Int { if (m == 0 || n == 0) { return 0 } if (memo[m][n] > 0) { return memo[m][n] } if (s1[m - 1] == s2[n - 1]) { memo[m][n] = 1 + lcs(s1, s2, m - 1, n - 1, memo) } else { memo[m][n] = max(lcs(s1, s2, m, n - 1, memo), lcs(s1, s2, m - 1, n, memo)) } return memo[m][n] } val memo = Array(word1.length + 1) { IntArray( word2.length + 1, ) } return@MinDistance word1.length + word2.length - 2 * lcs(word1, word2, word1.length, word2.length, memo) } /** * Approach #3 Using Longest Common Subsequence- Dynamic Programming * Time complexity : O(m*n). * Space complexity : O(m*n). */ val minDistanceLcsDp = MinDistance { word1: String, word2: String -> val dp = Array(word1.length + 1) { IntArray(word2.length + 1) } for (i in 0..word1.length) { for (j in 0..word2.length) { if (i == 0 || j == 0) { continue } if (word1[i - 1] == word2[j - 1]) { dp[i][j] = 1 + dp[i - 1][j - 1] } else { dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) } } } word1.length + word2.length - 2 * dp[word1.length][word2.length] } /** * Approach #4 Without using LCS Dynamic Programming * Time complexity : O(m*n). * Space complexity : O(m*n). */ val minDistanceDp = MinDistance { word1: String, word2: String -> val dp = Array(word1.length + 1) { IntArray( word2.length + 1, ) } for (i in 0..word1.length) { for (j in 0..word2.length) { if (i == 0 || j == 0) { dp[i][j] = i + j } else if (word1[i - 1] == word2[j - 1]) { dp[i][j] = dp[i - 1][j - 1] } else { dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1]) } } } dp[word1.length][word2.length] } /** * Approach #5 1-D Dynamic Programming * Time complexity : O(m*n). * Space complexity : O(n). */ val minDistance1Ddp = MinDistance { word1: String, word2: String -> var dp = IntArray(word2.length + 1) for (i in 0..word1.length) { val temp = IntArray(word2.length + 1) for (j in 0..word2.length) { if (i == 0 || j == 0) { temp[j] = i + j } else if (word1[i - 1] == word2[j - 1]) { temp[j] = dp[j - 1] } else { temp[j] = 1 + min(dp[j], temp[j - 1]) } } dp = temp } dp[word2.length] }
2
Kotlin
1
9
6a2d7ed76e2d88a3446f6558109809c318780e2c
5,100
the-algorithms
MIT License
src/main/kotlin/Day17.kt
cbrentharris
712,962,396
false
{"Kotlin": 171464}
import java.util.* import kotlin.String import kotlin.collections.List import kotlin.math.min object Day17 { enum class Direction { UP, DOWN, LEFT, RIGHT } data class CurrentStepInformation( val currentCoordinate: Coordinate, val currentDirection: Direction, val consecutiveDirectionSteps: Int, val heatLoss: Int ) { } data class Coordinate(val x: Int, val y: Int) fun part1(input: List<String>): String { val endCoordinate = Coordinate(input[0].length - 1, input.size - 1) return minimumHeatLoss(input, endCoordinate, maxConsecutiveSteps = 3).toString() } private fun minimumHeatLoss( grid: List<String>, endCoordinate: Coordinate, maxConsecutiveSteps: Int, minConsecutiveSteps: Int = 0 ): Int { val heap = PriorityQueue<CurrentStepInformation> { o1, o2 -> o1.heatLoss.compareTo(o2.heatLoss) } heap.add( CurrentStepInformation( Coordinate(1, 0), Direction.RIGHT, 1, 0 ) ) heap.add( CurrentStepInformation( Coordinate(0, 1), Direction.DOWN, 1, 0 ) ) var minValue = Int.MAX_VALUE val memo = mutableMapOf<CurrentStepInformation, Int>() while (heap.isNotEmpty()) { val currentStepInformation = heap.poll() val currentCoordinate = currentStepInformation.currentCoordinate val heatLoss = grid[currentCoordinate.y][currentCoordinate.x].digitToInt() val memoKey = currentStepInformation.copy(heatLoss = 0) // If we have already been here with less heat loss, we can skip this // Especially if we have already been here with the same heat loss but less consecutive steps, because // if a path had more possibilites and a smaller heat loss it makes no sense to search the space val tooExpensive = (minConsecutiveSteps..memoKey.consecutiveDirectionSteps - 1).map { memoKey.copy( consecutiveDirectionSteps = it ) } .any { memo.containsKey(it) && memo[it]!! <= currentStepInformation.heatLoss + heatLoss } || (memo[memoKey] ?: Int.MAX_VALUE) <= currentStepInformation.heatLoss + heatLoss if (tooExpensive) { continue } memo.put(memoKey, currentStepInformation.heatLoss + heatLoss) if (currentCoordinate == endCoordinate) { if (currentStepInformation.consecutiveDirectionSteps < minConsecutiveSteps) { continue } minValue = min(minValue, currentStepInformation.heatLoss + heatLoss) continue } val nextCoordinates = listOf( currentCoordinate.copy(x = currentCoordinate.x + 1) to Direction.RIGHT, currentCoordinate.copy(y = currentCoordinate.y + 1) to Direction.DOWN, currentCoordinate.copy(x = currentCoordinate.x - 1) to Direction.LEFT, currentCoordinate.copy(y = currentCoordinate.y - 1) to Direction.UP ).filter { (_, direction) -> // We cannot reverse directions when (direction) { Direction.UP -> currentStepInformation.currentDirection != Direction.DOWN Direction.DOWN -> currentStepInformation.currentDirection != Direction.UP Direction.LEFT -> currentStepInformation.currentDirection != Direction.RIGHT Direction.RIGHT -> currentStepInformation.currentDirection != Direction.LEFT } }.map { (coordinate, direction) -> CurrentStepInformation( coordinate, direction, if (direction == currentStepInformation.currentDirection) currentStepInformation.consecutiveDirectionSteps + 1 else 1, currentStepInformation.heatLoss + heatLoss ) }.filter { // We must move a minimum number of steps in the same direction it.currentDirection == currentStepInformation.currentDirection || currentStepInformation.consecutiveDirectionSteps >= minConsecutiveSteps }.filter { // We cannot move in the same direction more than maxConsecutiveSteps it.consecutiveDirectionSteps <= maxConsecutiveSteps }.filter { // We cannot move out of bounds it.currentCoordinate.x >= 0 && it.currentCoordinate.y >= 0 && it.currentCoordinate.y < grid.size && it.currentCoordinate.x < grid[it.currentCoordinate.y].length } heap.addAll(nextCoordinates) } return minValue } fun part2(input: List<String>): String { val endCoordinate = Coordinate(input[0].length - 1, input.size - 1) return minimumHeatLoss( input, endCoordinate, maxConsecutiveSteps = 10, minConsecutiveSteps = 4 ).toString() } }
0
Kotlin
0
1
f689f8bbbf1a63fecf66e5e03b382becac5d0025
5,358
kotlin-kringle
Apache License 2.0
src/main/kotlin/day1/Day01.kt
Avataw
572,709,044
false
{"Kotlin": 99761}
package day1 fun solveA(input: List<String>): Int = input .chunkByEmptyLine() .reduceToSum() .getSumOfNHighestSums(1) fun solveB(input: List<String>): Int = input .chunkByEmptyLine() .reduceToSum() .getSumOfNHighestSums(3) fun List<String>.chunkByEmptyLine() = this .joinToString(" ") { it.ifEmpty { "," } } .split(" , ") .map { it.split(" ") } fun List<String>.mapToInt() = this.map { it.toInt() } fun List<List<String>>.reduceToSum() = this.map { it.mapToInt().sum() } fun List<Int>.getSumOfNHighestSums(n: Int) = this.sortedDescending().take(n).sum()
0
Kotlin
2
0
769c4bf06ee5b9ad3220e92067d617f07519d2b7
598
advent-of-code-2022
Apache License 2.0
code/numeric/LinEqSolver.kt
hakiobo
397,069,173
false
null
private class LinEqSolver(val matrix: Array<DoubleArray>) { var status: Status? = null private set private fun swap(r1: Int, r2: Int) { val tmp = matrix[r1] matrix[r1] = matrix[r2] matrix[r2] = tmp } private fun multiplyRow(row: Int, mult: Double) { for (x in matrix[row].indices) { matrix[row][x] *= mult } } private fun divideRow(row: Int, mult: Double) { for (x in matrix[row].indices) { matrix[row][x] /= mult } } private fun multiplyAddRow(row: Int, row2: Int, mult: Double) { for (x in matrix[row].indices) { matrix[row2][x] += matrix[row][x] * mult } } private fun examineCol(col: Int, idealRow: Int): Boolean { var good = false if (matrix[idealRow][col].absoluteValue < EPSILON) { for (row in idealRow + 1 until matrix.size) { if (matrix[row][col].absoluteValue >= EPSILON) { good = true swap(row, idealRow) break } } } else { good = true } if (good) { divideRow( idealRow, matrix[idealRow][col] ) for (row in matrix.indices) { if (row == idealRow) continue if (matrix[row][col].absoluteValue >= EPSILON) { multiplyAddRow( idealRow, row, -matrix[row][col] ) } } } return good } fun solve() { var idealRow = 0 var col = 0 while (idealRow < matrix.size && col < matrix[0].lastIndex) { if (examineCol(col++, idealRow)) idealRow++ } status = if (col != matrix[0].lastIndex) { Status.MULTIPLE } else if (idealRow != matrix.size && examineCol(col, idealRow)) { Status.INCONSISTENT } else if (idealRow == col) { Status.SINGLE } else { Status.MULTIPLE } } companion object { private const val EPSILON = 1e-7 } enum class Status { INCONSISTENT, SINGLE, MULTIPLE } }
0
Kotlin
1
2
f862cc5e7fb6a81715d6ea8ccf7fb08833a58173
2,330
Kotlinaughts
MIT License
src/main/kotlin/de/hermes/technicalcasekotlin/models/Line.kt
Accessory
718,200,550
false
{"Kotlin": 15522, "Dockerfile": 471}
package de.hermes.technicalcasekotlin.models import kotlin.math.max import kotlin.math.min data class Line(val start: Position, val end: Position) { fun intersections(other: Line): Int { val selfIsHorizontal = this.isHorizontal() val otherIsHorizontal = other.isHorizontal() return when { selfIsHorizontal && otherIsHorizontal -> if (start.y == other.start.y) other.getHorizontalOverlap(this) else 0 !selfIsHorizontal && !otherIsHorizontal -> if (start.x == other.start.x) getVerticalOverlap(other) else 0 selfIsHorizontal && !otherIsHorizontal -> if (hasIntersection(other)) 1 else 0 else -> if (other.hasIntersection(this)) 1 else 0 } } private fun hasIntersection(other: Line): Boolean { val thisStartX = min(start.x, end.x) val thisEndX = max(start.x, end.x) if (thisStartX > other.start.x || thisEndX < other.start.x) { return false } val otherStartY = min(other.start.y, other.end.y) val otherEndY = max(other.start.y, other.end.y) return start.y in (otherStartY + 1) until otherEndY } private fun getVerticalOverlap(other: Line): Int { val start = min(this.start.y, this.end.y) val end = max(this.start.y, this.end.y) val otherStart = min(other.start.y, other.end.y) val otherEnd = max(other.start.y, other.end.y) return overlapping(start, end, otherStart, otherEnd) } private fun getHorizontalOverlap(other: Line): Int { val start = min(this.start.x, this.end.x) val end = max(this.start.x, this.end.x) val otherStart = min(other.start.x, other.end.x) val otherEnd = max(other.start.x, other.end.x) return overlapping(start, end, otherStart, otherEnd) } private fun overlapping(start: Int, end: Int, otherStart: Int, otherEnd: Int): Int { val startMax = max(otherStart, start) val endMin = min(otherEnd, end) val overlap = endMin - startMax return if (overlap == 0) 1 else max(0, overlap + 1) } private fun isHorizontal(): Boolean { return start.y == end.y } }
0
Kotlin
0
0
257552ae89688c2c3de2623769586f1a95a69b5c
2,198
technical-case-kotlin
Apache License 2.0
src/day16/Code.kt
fcolasuonno
225,219,560
false
null
package day16 import isDebug import java.io.File import kotlin.math.abs fun main() { val name = if (isDebug()) "test.txt" else "input.txt" System.err.println(name) val dir = ::main::class.java.`package`.name val input = File("src/$dir/$name").readLines() val parsed = parse(input) println("Part 1 = ${part1(parsed)}") println("Part 2 = ${part2(parsed)}") } fun parse(input: List<String>) = input.map { it.toList().map { it - '0' } }.requireNoNulls().first() fun part1(input: List<Int>) = generateSequence(input) { signal -> signal.indices.map { index -> val step = 4 * (index + 1) abs((index until signal.size step step).sumBy { o -> (0..index).sumBy { signal.getOrNull(it + o) ?: 0 } } - ((index + (2 * (index + 1))) until signal.size step step).sumBy { o -> (0..index).sumBy { signal.getOrNull(it + o) ?: 0 } }) % 10 } }.take(100 + 1).last().take(8).joinToString("") fun part2(input: List<Int>): Any? { val offset = input.take(7).joinToString("").toInt() return generateSequence(List(input.size * 10000 - offset) { input[(offset + it) % input.size] }) { signal -> var last = 0 signal.indices.reversed().map { last += signal[it] last }.map { it % 10 }.reversed() }.take(100 + 1).last().take(8).joinToString("") }
0
Kotlin
0
0
d1a5bfbbc85716d0a331792b59cdd75389cf379f
1,375
AOC2019
MIT License
src/day02/Day02.kt
JakubMosakowski
572,993,890
false
{"Kotlin": 66633}
package day02 import readInput /** * The Elves begin to set up camp on the beach. * To decide whose tent gets to be closest to the snack storage, a giant Rock Paper Scissors tournament is already in progress. * * Rock Paper Scissors is a game between two players. * Each game contains many rounds; in each round, the players each simultaneously choose one of Rock, Paper, or Scissors using a hand shape. * Then, a winner for that round is selected: Rock defeats Scissors, Scissors defeats Paper, and Paper defeats Rock. If both players choose the same shape, the round instead ends in a draw. * * Appreciative of your help yesterday, one Elf gives you an encrypted strategy guide (your puzzle input) that they say will be sure to help you win. * "The first column is what your opponent is going to play: A for Rock, B for Paper, and C for Scissors. The second column--" Suddenly, the Elf is called away to help with someone's tent. * * The second column, you reason, must be what you should play in response: X for Rock, Y for Paper, and Z for Scissors. * Winning every time would be suspicious, so the responses must have been carefully chosen. * * The winner of the whole tournament is the player with the highest score. Your total score is the sum of your scores for each round. * The score for a single round is the score for the shape you selected (1 for Rock, 2 for Paper, and 3 for Scissors) plus the score for the outcome of the round (0 if you lost, 3 if the round was a draw, and 6 if you won). * * Since you can't be sure if the Elf is trying to help you or trick you, you should calculate the score you would get if you were to follow the strategy guide. * * For example, suppose you were given the following strategy guide: * * A Y * B X * C Z * This strategy guide predicts and recommends the following: * * In the first round, your opponent will choose Rock (A), and you should choose Paper (Y). This ends in a win for you with a score of 8 (2 because you chose Paper + 6 because you won). * In the second round, your opponent will choose Paper (B), and you should choose Rock (X). This ends in a loss for you with a score of 1 (1 + 0). * The third round is a draw with both players choosing Scissors, giving you a score of 3 + 3 = 6. * In this example, if you were to follow the strategy guide, you would get a total score of 15 (8 + 1 + 6). * * What would your total score be if everything goes exactly according to your strategy guide? * * PART 2: * The Elf finishes helping with the tent and sneaks back over to you. "Anyway, the second column says how the round needs to end: X means you need to lose, Y means you need to end the round in a draw, and Z means you need to win. Good luck!" * * The total score is still calculated in the same way, but now you need to figure out what shape to choose so the round ends as indicated. The example above now goes like this: * * In the first round, your opponent will choose Rock (A), and you need the round to end in a draw (Y), so you also choose Rock. This gives you a score of 1 + 3 = 4. * In the second round, your opponent will choose Paper (B), and you choose Rock so you lose (X) with a score of 1 + 0 = 1. * In the third round, you will defeat your opponent's Scissors with Rock for a score of 1 + 6 = 7. * Now that you're correctly decrypting the ultra top secret strategy guide, you would get a total score of 12. * * Following the Elf's instructions for the second column, what would your total score be if everything goes exactly according to your strategy guide? */ private fun main() { fun getPair(line: String): Pair<String, String> = line.split(" ").let { it[0] to it[1] } fun part1(input: List<String>): Int = input.sumOf { line -> val (opponent, response) = getPair(line) when { opponent == ROCK && response == ROCK_RESPONSE -> DRAW + ROCK_SCORE opponent == ROCK && response == PAPER_RESPONSE -> WON + PAPER_SCORE opponent == ROCK && response == SCISSORS_RESPONSE -> LOOSE + SCISSORS_SCORE opponent == PAPER && response == ROCK_RESPONSE -> LOOSE + ROCK_SCORE opponent == PAPER && response == PAPER_RESPONSE -> DRAW + PAPER_SCORE opponent == PAPER && response == SCISSORS_RESPONSE -> WON + SCISSORS_SCORE opponent == SCISSORS && response == ROCK_RESPONSE -> WON + ROCK_SCORE opponent == SCISSORS && response == PAPER_RESPONSE -> LOOSE + PAPER_SCORE else -> DRAW + SCISSORS_SCORE } } fun part2(input: List<String>): Int = input.sumOf { line -> val (opponent, response) = getPair(line) when { opponent == ROCK && response == SHOULD_LOOSE -> LOOSE + SCISSORS_SCORE opponent == ROCK && response == SHOULD_DRAW -> DRAW + ROCK_SCORE opponent == ROCK && response == SHOULD_WIN -> WON + PAPER_SCORE opponent == PAPER && response == SHOULD_LOOSE -> LOOSE + ROCK_SCORE opponent == PAPER && response == SHOULD_DRAW -> DRAW + PAPER_SCORE opponent == PAPER && response == SHOULD_WIN -> WON + SCISSORS_SCORE opponent == SCISSORS && response == SHOULD_LOOSE -> LOOSE + PAPER_SCORE opponent == SCISSORS && response == SHOULD_DRAW -> DRAW + SCISSORS_SCORE else -> WON + ROCK_SCORE } } val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) } private const val LOOSE = 0 private const val DRAW = 3 private const val WON = 6 private const val ROCK = "A" private const val PAPER = "B" private const val SCISSORS = "C" private const val ROCK_RESPONSE = "X" private const val PAPER_RESPONSE = "Y" private const val SCISSORS_RESPONSE = "Z" private const val SHOULD_LOOSE = "X" private const val SHOULD_DRAW = "Y" private const val SHOULD_WIN = "Z" private const val ROCK_SCORE = 1 private const val PAPER_SCORE = 2 private const val SCISSORS_SCORE = 3
0
Kotlin
0
0
f6e9a0b6c2b66c28f052d461c79ad4f427dbdfc8
6,122
advent-of-code-2022
Apache License 2.0
src/Day02.kt
phoenixli
574,035,552
false
{"Kotlin": 29419}
fun main() { fun part1(input: List<String>): Int { var totalScore = 0 input.forEach { totalScore += score(it[0], mapXyzToAbc(it[2])) } return totalScore } fun part2(input: List<String>): Int { var totalScore = 0 input.forEach { totalScore += newStrat(it[0], it[2]) } return totalScore } val input = readInput("Day02") println(part1(input)) println(part2(input)) } fun mapXyzToAbc(myPlay: Char): Char? { return when (myPlay) { 'X' -> 'A' 'Y' -> 'B' 'Z' -> 'C' else -> null } } fun mapPlayToScore(play: Char): Int { return when (play) { 'A' -> 1 'B' -> 2 'C' -> 3 else -> 0 } } fun rockA(otherPlay: Char): Int { return when (otherPlay) { 'A' -> 3 'B' -> 6 'C' -> 0 else -> 0 } } fun paperB(otherPlay: Char): Int { return when (otherPlay) { 'A' -> 0 'B' -> 3 'C' -> 6 else -> 0 } } fun scissorsC(otherPlay: Char): Int { return when (otherPlay) { 'A' -> 6 'B' -> 0 'C' -> 3 else -> 0 } } fun score(firstPlayer: Char, secondPlayer: Char?): Int { if (secondPlayer == null) return 0 val score = when (firstPlayer) { 'A' -> rockA(secondPlayer) 'B' -> paperB(secondPlayer) 'C' -> scissorsC(secondPlayer) else -> 0 } return score + mapPlayToScore(secondPlayer) } fun lose(play: Char): Char? { return when (play) { 'A' -> 'C' 'B' -> 'A' 'C' -> 'B' else -> null } } fun win(play: Char): Char? { return when (play) { 'A' -> 'B' 'B' -> 'C' 'C' -> 'A' else -> null } } fun newStrat(firstPlayer: Char, strat: Char): Int { val secondPlayer = when (strat) { 'X' -> lose(firstPlayer) 'Y' -> firstPlayer 'Z' -> win(firstPlayer) else -> firstPlayer } if (secondPlayer == null) return 0 return score(firstPlayer, secondPlayer) }
0
Kotlin
0
0
5f993c7b3c3f518d4ea926a792767a1381349d75
2,113
Advent-of-Code-2022
Apache License 2.0
app/src/main/java/com/aesean/twentyfour/CalculateImpl.kt
aesean
63,247,450
false
{"Java": 14199, "Kotlin": 7326, "Dart": 4268, "Swift": 3770}
package com.aesean.twentyfour import java.math.BigDecimal import java.util.* interface CalculateRule { fun size(): Int fun calculate(a: String, index: Int, b: String): String fun symbol(index: Int): String fun deviation(): String } fun main(args: Array<String>) { test("8,8,3,3") test("5,5,5,1") } private fun String.format(): String { return String.format("%2.1f", this.toFloat()) } private fun test(s: String) { val numbers = s.split(",") val nodes = MutableList(numbers.size) { Node(numbers[it]) } val tree = Tree(nodes, CalculateRuleByBigDecimal()) tree.find { if (Math.abs(it.number.toDouble() - 24) < 0.0000000001) { println("${it.desc} = ${it.number.format()}") } } println("**********") tree.find { if (Math.abs(it.number.toDouble()) <= 10) { println("${it.desc} = ${it.number.format()}") } } } class CalculateRuleNormal : CalculateRule { companion object { val SYMBOLS = arrayOf("+", "-", "×", "÷") const val DEVIATION = "0.00001" } override fun symbol(index: Int): String { return SYMBOLS[index] } override fun calculate(a: String, index: Int, b: String): String { val numA = a.toDouble() val numB = b.toDouble() when (index) { 0 -> { return (numA + numB).toString() } 1 -> { return (numA - numB).toString() } 2 -> { return (numA * numB).toString() } 3 -> { if (numB == 0.0) { throw RuntimeException("Can't multiply 0") } return (numA / numB).toString() } else -> { throw RuntimeException("Unknown index") } } } override fun size(): Int { return SYMBOLS.size } override fun deviation(): String { return DEVIATION } override fun toString(): String { return "CalculateRuleNormal{SYMBOLS = ${Arrays.toString(SYMBOLS)}, deviation = ${deviation()}}" } } class CalculateRuleByBigDecimal : CalculateRule { companion object { val SYMBOLS = arrayOf("+", "-", "×", "÷") const val DEVIATION = "0.00000000001" } override fun symbol(index: Int): String { return SYMBOLS[index] } override fun calculate(a: String, index: Int, b: String): String { val numA = BigDecimal(a) val numB = BigDecimal(b) when (index) { 0 -> { return numA.add(numB).toString() } 1 -> { return numA.subtract(numB).toString() } 2 -> { return numA.multiply(numB).toString() } 3 -> { return numA.divide(numB, 16, BigDecimal.ROUND_HALF_UP).toString() } else -> { throw RuntimeException("Unknown index") } } } override fun size(): Int { return SYMBOLS.size } override fun deviation(): String { return DEVIATION } override fun toString(): String { return "CalculateRuleByBigDecimal{SYMBOLS = ${Arrays.toString(SYMBOLS)}, deviation = ${deviation()}}" } } class Tree(private val nodes: MutableList<Node>, private val calculateRule: CalculateRule) { private val nodeArrangement = Arrangement(nodes.size) fun find(filter: (result: Node) -> Unit) { nodeArrangement.traversal { left: Int, right: Int -> val leftNode = nodes[left] val rightNode = nodes[right] for (symbolIndex in 0 until calculateRule.size()) { val nextNodes: MutableList<Node> = ArrayList(nodes.size - 2) nodes.forEachIndexed { index, value -> if ((index != left) and (index != right)) { nextNodes.add(value) } } val number: String try { number = calculateRule.calculate(leftNode.number, symbolIndex, rightNode.number) } catch (e: Exception) { continue } val node = Node(number) node.desc = "(${leftNode.desc}${calculateRule.symbol(symbolIndex)}${rightNode.desc})" nextNodes.add(node) if (nextNodes.size > 1) { Tree(nextNodes, calculateRule).find(filter) } else { val n = nextNodes[0] filter.invoke(n) } } } } fun size(): Int { return nodes.size } } class Node(var number: String) { var desc: String = number override fun toString(): String { return desc } } class Arrangement(val size: Int) { private var mainIndex: Int = -1 private var childIndex: Int = -1 init { if (size < 2) { throw RuntimeException("size should be >= 2. ") } } private fun next(): Boolean { if ((mainIndex == -1) and (childIndex == -1)) { mainIndex = 0 childIndex = 1 return true } childIndex++ var check = false if (childIndex < size) { check = true } else { childIndex = 0 mainIndex++ if (mainIndex < size) { check = true } } if (check) { return if (mainIndex == childIndex) { next() } else { true } } return false } fun traversal(result: (left: Int, right: Int) -> Unit) { mainIndex = -1 childIndex = -1 while (next()) { result.invoke(mainIndex, childIndex) } } }
0
Java
2
3
666ae03f418cd54819b6d4a671985a0310bc928b
5,987
TwentyFour
Apache License 2.0
Generics/Generic functions/src/Task.kt
feczkob
638,839,822
false
null
import java.util.* fun <K, C : MutableCollection<K>> Collection<K>.partitionTo( one: C, two: C, pred: Collection<K>.(K) -> Boolean, ): Pair<MutableCollection<K>, MutableCollection<K>> { // * solution 1 // this.forEach { // if (pred(it)) { // one += it // } else { // two += it // } // } // * solution 2 val (a, b) = this.partition { pred(it) } one.addAll(a) two.addAll(b) return Pair(one, two) } fun partitionWordsAndLines() { val (words, lines) = listOf("a", "a b", "c", "d e") .partitionTo(ArrayList(), ArrayList()) { s -> !s.contains(" ") } check(words == listOf("a", "c")) check(lines == listOf("a b", "d e")) } fun partitionLettersAndOtherSymbols() { val (letters, other) = setOf('a', '%', 'r', '}') .partitionTo(HashSet(), HashSet()) { c -> c in 'a'..'z' || c in 'A'..'Z' } check(letters == setOf('a', 'r')) check(other == setOf('%', '}')) }
0
Kotlin
0
0
b954a54b8f34bddbee3c2d116eb60b0ffa9ac855
979
Kotlin-Koans
MIT License
src/main/kotlin/d22_ReactorReboot/ReactorReboot.kt
aormsby
425,644,961
false
{"Kotlin": 68415}
package d22_ReactorReboot import util.Input import util.Output fun main() { Output.day(22, "Reactor Reboot") val startTime = Output.startTime() val instructions = Input.parseLines(filename = "/input/d22_reboot_steps.txt") .map { Cuboid.of(it) } as MutableList val initializationLimits = Cuboid(true, -50..50, -50..50, -50..50) var cuboids = mutableListOf<Cuboid>() instructions.filter { it.intersectsWith(initializationLimits) }.forEach { c -> cuboids.addAll(cuboids.mapNotNull { it.intersectOf(c) }) if (c.isOn) cuboids.add(c) } Output.part(1, "Initialization: Active Cubes", cuboids.sumOf { it.volume() }) cuboids = mutableListOf<Cuboid>() instructions.forEach { c -> cuboids.addAll(cuboids.mapNotNull { it.intersectOf(c) }) if (c.isOn) cuboids.add(c) } Output.part(2, "Reboot: Active Cubes", cuboids.sumOf { it.volume() }) Output.executionTime(startTime) } class Cuboid( val isOn: Boolean, private val x: IntRange, private val y: IntRange, private val z: IntRange ) { companion object { private val pattern = """^(on|off) x=(-?\d+)\.\.(-?\d+),y=(-?\d+)\.\.(-?\d+),z=(-?\d+)\.\.(-?\d+)$""".toRegex() fun of(input: String): Cuboid { val (on, x1, x2, y1, y2, z1, z2) = pattern.matchEntire(input)?.destructured ?: error("Cannot parse input: $input") return Cuboid( on == "on", x1.toInt()..x2.toInt(), y1.toInt()..y2.toInt(), z1.toInt()..z2.toInt() ) } } fun intersectsWith(other: Cuboid): Boolean = x.intersectsWith(other.x) && y.intersectsWith(other.y) && z.intersectsWith(other.z) fun intersectOf(other: Cuboid): Cuboid? = if (!intersectsWith(other)) null else Cuboid(!isOn, x.intersectOf(other.x), y.intersectOf(other.y), z.intersectOf(other.z)) fun volume(): Long = (x.size().toLong() * y.size().toLong() * z.size().toLong()) * if (isOn) 1 else -1 } fun IntRange.intersectsWith(other: IntRange): Boolean = first <= other.last && last >= other.first fun IntRange.intersectOf(other: IntRange): IntRange = maxOf(first, other.first)..minOf(last, other.last) fun IntRange.size(): Int = last - first + 1
0
Kotlin
1
1
193d7b47085c3e84a1f24b11177206e82110bfad
2,339
advent-of-code-2021
MIT License
kotlin/src/com/codeforces/round736/D_not_completed.kt
programmerr47
248,502,040
false
null
package com.codeforces.round736 import java.util.* import kotlin.math.abs import kotlin.math.max fun main() { val reader = Scanner(System.`in`) task(reader) } private fun task(input: Scanner) { repeat(input.nextInt()) { val a = LongArray(input.nextInt()) { input.nextLong() } val diffs = LongArray(a.size - 1) { abs(a[it] - a[it + 1]) } println(findGcdCount(diffs) + 1) } } private fun findGcdCount(diffs: LongArray): Int { val divisors = LongArray(diffs.size) var maxSequence = 0 for (i in divisors.indices) { var gcdCount = 1 for (j in i..divisors.lastIndex) { if (j == i) { divisors[j] = diffs[j] maxSequence = max(maxSequence, gcdCount) } else { val gcd = divisors[j - 1].gcd(diffs[j]) divisors[j] = gcd if (gcd <= 1) { maxSequence = max(maxSequence, gcdCount) break } else { gcdCount += 1 if (j == divisors.lastIndex) { // // println(divisors.joinToString { it.joinToString() + "\n" }) return max(maxSequence, gcdCount) } } } } } // // println(divisors.joinToString { it.joinToString() + "\n" }) return maxSequence } private fun Long.gcd(with: Long): Long { var a = this var b = with while (b != 0L) { val temp = a a = b b = temp % b } return a }
0
Kotlin
0
0
0b5fbb3143ece02bb60d7c61fea56021fcc0f069
1,584
problemsolving
Apache License 2.0
src/main/kotlin/Day01.kt
robfletcher
724,814,488
false
{"Kotlin": 18682}
class Day01 : Puzzle { override fun test() { val testInput1 = """ 1abc2 pqr3stu8vwx a1b2c3d4e5f treb7uchet""".trimIndent() assert(part1(testInput1.lineSequence()) == 142) val testInput2 = """ two1nine eightwothree abcone2threexyz xtwone3four 4nineeightseven2 zoneight234 7pqrstsixteen""".trimIndent() assert(part2(testInput2.lineSequence()) == 281) } fun value(line: String) = "${line.first(Char::isDigit)}${line.last(Char::isDigit)}".toInt() override fun part1(input: Sequence<String>): Int = input.sumOf(::value) val digits = (1..9).toList().map(Int::toString) val words = listOf("one", "two", "three", "four", "five", "six", "seven", "eight", "nine") val parse = { digit: String -> when { digit in words -> "${words.indexOf(digit) + 1}" else -> digit } } fun firstDigit(line: String) = checkNotNull(line.findAnyOf(digits + words)).second fun lastDigit(line: String) = checkNotNull(line.findLastAnyOf(digits + words)).second override fun part2(input: Sequence<String>) = input.sumOf { line -> "${firstDigit(line).let(parse)}${lastDigit(line).let(parse)}".toInt() } }
0
Kotlin
0
0
cf10b596c00322ea004712e34e6a0793ba1029ed
1,197
aoc2023
The Unlicense
src/Day02.kt
Oktosha
573,139,677
false
{"Kotlin": 110908}
fun main() { class Game(val player: Int, val opponent: Int) fun getMovesPart1(description: String): Game { val opponent = description[0].code - 'A'.code val player = description[2].code - 'X'.code return Game(player, opponent) } fun getGameScore(game: Game): Int { val moveScore = game.player + 1 if ((game.opponent + 1) % 3 == game.player) { return moveScore + 6 } if (game.opponent == game.player) { return moveScore + 3 } return moveScore } fun part1EntryResolver(entry: String): Int { return getGameScore(getMovesPart1(entry)) } fun part1(input: List<String>): Int { return input.map(::part1EntryResolver).sum() } fun getMovesPart2(description: String): Game { val opponent = description[0].code - 'A'.code val outcome = description[2].code - 'Y'.code val player = (3 + opponent + outcome) % 3 return Game(player, opponent) } fun part2EntryResolver(entry: String): Int { return getGameScore(getMovesPart2(entry)) } fun part2(input: List<String>): Int { return input.map(::part2EntryResolver).sum() } val input = readInput("Day02") println("Day 2") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e53eea61440f7de4f2284eb811d355f2f4a25f8c
1,341
aoc-2022
Apache License 2.0
src/main/kotlin/days/aoc2015/Day14.kt
bjdupuis
435,570,912
false
{"Kotlin": 537037}
package days.aoc2015 import days.Day class Day14: Day(2015, 14) { // Comet can fly 14 km/s for 10 seconds, but then must rest for 127 seconds override fun partOne(): Any { val reindeer = parseReindeer(inputList) return reindeer.map { it.calculateDistanceForTime(2503) }.maxOrNull() ?: 0 } fun parseReindeer(list: List<String>): List<Reindeer> { return list.map { Regex("(\\w+) can fly (\\d+) km/s for (\\d+) seconds, but then must rest for (\\d+) seconds.").matchEntire(it)?.destructured?.let { (name, speed, flightTime, restTime) -> Reindeer(name, speed.toInt(), flightTime.toInt(), restTime.toInt()) }!! } } override fun partTwo(): Any { val reindeer = parseReindeer(inputList) return calculateWinningScore(reindeer, 2503) } fun calculateWinningScore(reindeer: List<Reindeer>, time: Int): Int { for (i in 1..time) { val max = reindeer.map { reindeer -> reindeer.calculateDistanceForTime(i) }.maxOrNull() reindeer.filter { reindeer -> reindeer.calculateDistanceForTime(i) == max }.forEach { reindeer -> reindeer.score++ } } return reindeer.maxByOrNull { reindeer -> reindeer.score }!!.score } class Reindeer(val name: String, private val speed: Int, private val flightTime: Int, private val restTime: Int) { var score = 0 fun calculateDistanceForTime(seconds: Int): Int { return ((seconds / (flightTime + restTime)) * (speed * flightTime)) + (minOf(flightTime, (seconds % ( flightTime + restTime ))) * speed) } } }
0
Kotlin
0
1
c692fb71811055c79d53f9b510fe58a6153a1397
1,643
Advent-Of-Code
Creative Commons Zero v1.0 Universal
2022/Day09.kt
amelentev
573,120,350
false
{"Kotlin": 87839}
import kotlin.math.abs fun main() { val input = readInput("Day09") data class Point(val x: Int, val y: Int) operator fun Point.plus(p: Point) = Point(x + p.x, y + p.y) operator fun Point.minus(p: Point) = Point(x - p.x, y - p.y) val dirs = mapOf( 'R' to Point(1, 0), 'U' to Point(0, 1), 'L' to Point(-1, 0), 'D' to Point(0, -1), ) val rope = Array(10) { Point(0, 0)} val res1 = mutableSetOf(rope[0]) val res2 = mutableSetOf(rope[0]) for (s in input) { val (dir, c) = s.split(' ') repeat(c.toInt()) { rope[0] += dirs[dir[0]]!! for (i in 1 until rope.size) { var d = rope[i-1] - rope[i] if (abs(d.x) > 1 || abs(d.y) > 1) { if (abs(d.x) > 1) d = d.copy(x = d.x / abs(d.x)) if (abs(d.y) > 1) d = d.copy(y = d.y / abs(d.y)) rope[i] += d } } res1.add(rope[1]) res2.add(rope[9]) } } println(res1.size) println(res2.size) }
0
Kotlin
0
0
a137d895472379f0f8cdea136f62c106e28747d5
1,093
advent-of-code-kotlin
Apache License 2.0
src/main/kotlin/g2001_2100/s2019_the_score_of_students_solving_math_expression/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2001_2100.s2019_the_score_of_students_solving_math_expression // #Hard #Array #String #Dynamic_Programming #Math #Stack #Memoization // #2023_06_23_Time_1497_ms_(100.00%)_Space_48.2_MB_(100.00%) import java.util.ArrayDeque class Solution { private lateinit var dp: Array<Array<HashSet<Int>?>> fun scoreOfStudents(s: String, answers: IntArray): Int { val st = ArrayDeque<Int>() val n = s.length var i = 0 dp = Array(n) { arrayOfNulls<HashSet<Int>?>(n) } while (i < n) { if (s[i].code - '0'.code >= 0 && s[i].code - '9'.code <= 0) { st.push(s[i].code - '0'.code) i++ } else if (s[i] == '*') { val cur = st.pop() * (s[i + 1].code - '0'.code) i += 2 st.push(cur) } else { i++ } } var res = 0 var ret = 0 while (st.isNotEmpty()) { res += st.pop() } val wrong = opts(0, n - 1, s) for (ans in answers) { if (ans == res) { ret += 5 } else if (wrong!!.contains(ans)) { ret += 2 } } return ret } private fun opts(i: Int, j: Int, s: String): HashSet<Int>? { if (dp[i][j] != null) { return dp[i][j] } if (i == j) { val res = HashSet<Int>() res.add(s[i].code - '0'.code) dp[i][j] = res return res } val res = HashSet<Int>() var x = i + 1 while (x < j) { val op = s[x] val left = opts(i, x - 1, s) val right = opts(x + 1, j, s) if (op == '*') { for (l in left!!) { for (r in right!!) { if (l * r <= 1000) { res.add(l * r) } } } } else { for (l in left!!) { for (r in right!!) { if (l + r <= 1000) { res.add(l + r) } } } } x += 2 } dp[i][j] = res return res } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
2,337
LeetCode-in-Kotlin
MIT License
Retos/Reto #19 - ANÁLISIS DE TEXTO [Media]/kotlin/jaimefere.kt
mouredev
581,049,695
false
{"Python": 3866914, "JavaScript": 1514237, "Java": 1272062, "C#": 770734, "Kotlin": 533094, "TypeScript": 457043, "Rust": 356917, "PHP": 281430, "Go": 243918, "Jupyter Notebook": 221090, "Swift": 216751, "C": 210761, "C++": 164758, "Dart": 159755, "Ruby": 70259, "Perl": 52923, "VBScript": 49663, "HTML": 45912, "Raku": 44139, "Scala": 30892, "Shell": 27625, "R": 19771, "Lua": 16625, "COBOL": 15467, "PowerShell": 14611, "Common Lisp": 12715, "F#": 12710, "Pascal": 12673, "Haskell": 11051, "Assembly": 10368, "Elixir": 9033, "Visual Basic .NET": 7350, "Groovy": 7331, "PLpgSQL": 6742, "Clojure": 6227, "TSQL": 5744, "Zig": 5594, "Objective-C": 5413, "Apex": 4662, "ActionScript": 3778, "Batchfile": 3608, "OCaml": 3407, "Ada": 3349, "ABAP": 2631, "Erlang": 2460, "BASIC": 2340, "D": 2243, "Awk": 2203, "CoffeeScript": 2199, "Vim Script": 2158, "Brainfuck": 1550, "Prolog": 1342, "Crystal": 783, "Fortran": 778, "Solidity": 560, "Standard ML": 525, "Scheme": 457, "Vala": 454, "Limbo": 356, "xBase": 346, "Jasmin": 285, "Eiffel": 256, "GDScript": 252, "Witcher Script": 228, "Julia": 224, "MATLAB": 193, "Forth": 177, "Mercury": 175, "Befunge": 173, "Ballerina": 160, "Smalltalk": 130, "Modula-2": 129, "Rebol": 127, "NewLisp": 124, "Haxe": 112, "HolyC": 110, "GLSL": 106, "CWeb": 105, "AL": 102, "Fantom": 97, "Alloy": 93, "Cool": 93, "AppleScript": 85, "Ceylon": 81, "Idris": 80, "Dylan": 70, "Agda": 69, "Pony": 69, "Pawn": 65, "Elm": 61, "Red": 61, "Grace": 59, "Mathematica": 58, "Lasso": 57, "Genie": 42, "LOLCODE": 40, "Nim": 38, "V": 38, "Chapel": 34, "Ioke": 32, "Racket": 28, "LiveScript": 25, "Self": 24, "Hy": 22, "Arc": 21, "Nit": 21, "Boo": 19, "Tcl": 17, "Turing": 17}
fun analyzeText(text: String) { val symbols = arrayOf(' ', '.', ',', ':', ';', '-', '¡', '!', '¿', '?', '(', ')', '[', ']', '"', '\t', '\n') var wordLengths = arrayOf<Int>() var pointsCounter = 0 var largestWord = "" var currentWord = "" text.forEach { char -> if(symbols.contains(char)) { if(char == '.') { pointsCounter++ } if(currentWord.isNotEmpty()) { if(currentWord.length > wordLengths.maxOrNull() ?: 0) { largestWord = currentWord } wordLengths += currentWord.length currentWord = "" } } else { currentWord += char } } println("Número de palabras: ${wordLengths.size}") println("Longitud media de las palabras: ${wordLengths.average().toInt()}") println("Número de oraciones: $pointsCounter") println("Palabra más larga: $largestWord") } fun main() { analyzeText("En un lugar de la Mancha, de cuyo nombre no quiero acordarme, no ha mucho tiempo que vivía un hidalgo de los de lanza en astillero, adarga antigua, rocín flaco y galgo corredor. Una olla de algo más vaca que carnero, salpicón las más noches, duelos y quebrantos los sábados, lantejas los viernes, algún palomino de añadidura los domingos, consumían las tres partes de su hacienda.") analyzeText("Find out exactly how many sentences are in your text content using this online sentence counter. This sentence counting tool will also give you basic information on the number of words and characters in your text.\nThis tool will automatically figure out the number of sentences, words, and characters that you have in most any type of text content. The text information you want to analyze can be many formats. This sentence counter can handle anything from a single string of text or to very long content composed of numerous text paragraphs separated by multiple line breaks.\nThe text box may look small but it can handle text content with thousands upon thousands of words very easily and quickly. It's a ideal sentence calculator for short stories, long articles, and even some books.") }
4
Python
2,929
4,661
adcec568ef7944fae3dcbb40c79dbfb8ef1f633c
2,215
retos-programacion-2023
Apache License 2.0
src/com/wd/algorithm/leetcode/ALGO0009.kt
WalkerDenial
327,944,547
false
null
package com.wd.algorithm.leetcode import com.wd.algorithm.test /** * 9. 回文数 * * 给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。 * 回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文,而 123 不是。 * */ class ALGO0009 { fun isPalindrome1(x: Int): Boolean { if (x < 0 || x > Int.MAX_VALUE) return false if (x < 10) return true var num = x var curr = 0 while (curr < num) { val end = num % 10 if (curr == 0 && curr == end) break num /= 10 if (curr == num) return true curr = curr * 10 + end if (curr == num) return true else if (num < 10) break } return false } fun isPalindrome2(x: Int): Boolean { if (x < 0 || x > Int.MAX_VALUE) return false val str = "$x" val reverseStr = str.reversed() return str == reverseStr } fun isPalindrome3(x: Int): Boolean { if (x < 0 || x > Int.MAX_VALUE) return false if (x < 10) return true if (x % 10 == 0) return false val str = "$x" val length = str.length val lastIndex = length - 1 for (i in 0 until length / 2) { if (str[i] != str[lastIndex - i]) return false } return true } } fun main() { val clazz = ALGO0009() val num = 21120 (clazz::isPalindrome1).test(num) (clazz::isPalindrome2).test(num) (clazz::isPalindrome3).test(num) }
0
Kotlin
0
0
245ab89bd8bf467625901034dc1139f0a626887b
1,604
AlgorithmAnalyze
Apache License 2.0
src/main/kotlin/com/mckernant1/leetcode/ThreeSum.kt
mckernant1
494,952,749
false
{"Kotlin": 33093}
package com.mckernant1.leetcode fun main() { // println(threeSum(intArrayOf(-1, 0, 1, 2, -1, -4))) // println(threeSum(intArrayOf(0, 1, 1))) println(threeSum(intArrayOf(-1, 0, 1, 2, -1, -4))) } private fun threeSum(nums: IntArray): List<List<Int>> { val nums = nums.sorted() var middle = nums.size / 2 var l = middle - 1 var r = middle + 1 var alt = true val triples = mutableListOf<List<Int>>() while (l >= 0 && r <= nums.size - 1) { println("Round") while (middle > l && middle < r) { println("$l $middle $r => ${nums[l] + nums[middle] + nums[r]}") if (nums[l] + nums[middle] + nums[r] == 0) { triples.add(listOf(nums[l], nums[middle], nums[r])) } ++middle } if (alt) { ++r } else { --l } alt = !alt middle = l + 1 } return triples.distinct() }
0
Kotlin
0
0
5aaa96588925b1b8d77d7dd98dd54738deeab7f1
948
kotlin-random
Apache License 2.0
src/year2022/Day10.kt
Maetthu24
572,844,320
false
{"Kotlin": 41016}
package year2022 import kotlin.math.abs fun main() { fun part1(input: List<String>): Int { var register = 1 var cycle = 1 return buildList { for (op in input) { when (op) { "noop" -> cycle += 1 else -> { cycle += 1 if ((cycle - 20) % 40 == 0) { add(register * cycle) } cycle += 1 register += op.split(" ").last().toInt() } } if ((cycle - 20) % 40 == 0) { add(register * cycle) } } }.sum() } fun draw(image: List<Char>) { for (line in image.windowed(40, 40)) { println(line.joinToString("")) } println() } fun part2(input: List<String>) { var register = 1 var cycle = 0 val image = MutableList(240) { '.' } for (op in input) { if (abs(register - cycle % 40) <= 1) { image[cycle] = '#' } when (op) { "noop" -> cycle += 1 else -> { cycle += 1 if (abs(register - cycle % 40) <= 1) { image[cycle] = '#' } cycle += 1 register += op.split(" ").last().toInt() } } if (abs(register - cycle % 40) <= 1) { image[cycle] = '#' } } draw(image) } val day = "10" // Read inputs val testInput = readInput("Day${day}_test") val input = readInput("Day${day}") // Test & run part 1 val testResult = part1(testInput) val testExpected = 13140 check(testResult == testExpected) { "testResult should be $testExpected, but is $testResult" } println(part1(input)) // Test & run part 2 println("Test image:") part2(testInput) println("\n---------------------------------\nActual image:") part2(input) }
0
Kotlin
0
1
3b3b2984ab718899fbba591c14c991d76c34f28c
2,172
adventofcode-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/SearchInsertPosition.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 /** * 35. Search Insert Position * @see <a href="https://leetcode.com/problems/search-insert-position">Source</a> */ fun interface SearchInsertPosition { fun searchInsert(nums: IntArray, target: Int): Int } class SearchInsertPositionIterative : SearchInsertPosition { override fun searchInsert(nums: IntArray, target: Int): Int { var low = 0 var high = nums.size - 1 while (low <= high) { val mid = (low + high) / 2 when { nums[mid] == target -> { return mid } nums[mid] > target -> { high = mid - 1 } else -> { low = mid + 1 } } } return low } } class SearchInsertPositionFast : SearchInsertPosition { override fun searchInsert(nums: IntArray, target: Int): Int { var start = 0 var end: Int = nums.size - 1 while (start <= end) { val mid = start + (end - start) / 2 if (nums[mid] == target) return mid else if (nums[mid] > target) end = mid - 1 else start = mid + 1 } return start } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,853
kotlab
Apache License 2.0
src/Day08.kt
jvmusin
572,685,421
false
{"Kotlin": 86453}
fun main() { val dx = intArrayOf(-1, 0, 1, 0) val dy = intArrayOf(0, 1, 0, -1) fun part1(input: List<String>): Int { val n = input.size val m = input[0].length val a = input.map { s -> s.map { it.digitToInt() } } fun check(x: Int, y: Int): Boolean { fun check(d: Int): Boolean { var x1 = x var y1 = y while (x1 in 0 until n && y1 in 0 until m) { val nx = x1 + dx[d] val ny = y1 + dy[d] if (nx in 0 until n && ny in 0 until m) { val cur = a[x][y] val next = a[nx][ny] if (next >= cur) return false } x1 = nx y1 = ny } return true } for (d in 0 until 4) if (check(d)) return true return false } var cnt = 0 for (i in 0 until n) { for (j in 0 until m) { if (check(i, j)) { cnt++ } } } return cnt } fun part2(input: List<String>): Int { val n = input.size val m = input[0].length val a = input.map { s -> s.map { it.digitToInt() } } fun check(x: Int, y: Int): Int { fun check(d: Int): Int { var x1 = x var y1 = y var steps = 0 while (true) { val nx = x1 + dx[d] val ny = y1 + dy[d] if (nx in 0 until n && ny in 0 until m) { steps++ val cur = a[x][y] val next = a[nx][ny] if (next >= cur) break } else break x1 = nx y1 = ny } return steps } var r = 1 for (d in 0 until 4) r *= check(d) return r } var mx = 0 for (i in 0 until n) { for (j in 0 until m) { mx = maxOf(mx, check(i, j)) } } return mx } @Suppress("DuplicatedCode") run { val day = String.format("%02d", 8) val testInput = readInput("Day${day}_test") val input = readInput("Day$day") println("Part 1 test - " + part1(testInput)) println("Part 1 real - " + part1(input)) println("---") println("Part 2 test - " + part2(testInput)) println("Part 2 real - " + part2(input)) } }
1
Kotlin
0
0
4dd83724103617aa0e77eb145744bc3e8c988959
2,693
advent-of-code-2022
Apache License 2.0
src/test/kotlin/ch/ranil/aoc/aoc2022/Day23.kt
stravag
572,872,641
false
{"Kotlin": 234222}
package ch.ranil.aoc.aoc2022 import ch.ranil.aoc.AbstractDay import org.junit.jupiter.api.Test import kotlin.test.assertEquals class Day23 : AbstractDay() { @Test fun part1Test() { assertEquals(110, compute1(testInput)) } @Test fun part1Puzzle() { assertEquals(4091, compute1(puzzleInput)) } @Test fun part2Test() { assertEquals(20, compute2(testInput)) } @Test fun part2Puzzle() { assertEquals(1036, compute2(puzzleInput)) } private fun compute1(input: List<String>): Int { val elves = parse(input) repeat(10) { elves.round() } elves.print() return elves.result1 } private fun compute2(input: List<String>): Int { val elves = parse(input) do { val moved = elves.round() } while (moved) return elves.result2 } class Elves( private var currentPositions: LinkedHashSet<Elf>, private var roundCount: Int = 0, ) { constructor(positions: List<Elf>) : this(LinkedHashSet(positions)) fun round(): Boolean { val moveSuggestions = moveSuggestions() .sortedBy { it.current } val groupedSuggestions = moveSuggestions .groupBy { it.suggested } val newPositions = groupedSuggestions .flatMap { (_, elvesWithSameSuggestion) -> if (elvesWithSameSuggestion.size > 1) { elvesWithSameSuggestion.map { it.current } // don't move } else { elvesWithSameSuggestion.map { it.suggested } // move to suggestion } } require(newPositions.size == currentPositions.size) val hasMoved = !currentPositions.containsAll(newPositions) currentPositions = LinkedHashSet(newPositions) roundCount++ return hasMoved } val result1: Int get() { val minX = currentPositions.minOf { it.x } val maxX = currentPositions.maxOf { it.x } val minY = currentPositions.minOf { it.y } val maxY = currentPositions.maxOf { it.y } val width = maxX - minX + 1 val height = maxY - minY + 1 return width * height - currentPositions.size } val result2: Int get() = roundCount fun print() { val minX = currentPositions.minOf { it.x } val maxX = currentPositions.maxOf { it.x } val minY = currentPositions.minOf { it.y } val maxY = currentPositions.maxOf { it.y } for (y in minY - 1..maxY + 1) { for (x in minX - 1..maxX + 1) { if (currentPositions.contains(Elf(x, y))) print('#') else print('.') } println() } } private fun moveSuggestions(): List<MoveSuggestion> { fun List<Elf>.allFree(): Boolean = none { currentPositions.contains(it) } fun Elf.suggestion(): MoveSuggestion? { val checks: List<Pair<DirectionCheck, MoveSuggester>> = listOf( DirectionCheck { it.n.allFree() } to MoveSuggester { MoveSuggestion(it.north, it) }, DirectionCheck { it.s.allFree() } to MoveSuggester { MoveSuggestion(it.south, it) }, DirectionCheck { it.w.allFree() } to MoveSuggester { MoveSuggestion(it.west, it) }, DirectionCheck { it.e.allFree() } to MoveSuggester { MoveSuggestion(it.east, it) }, ) val checkOffset = roundCount % checks.size return (checks.indices).map { i -> val checkIdx = (i + checkOffset) % checks.size val (check, suggester) = checks[checkIdx] if (check.check(this)) suggester.suggest(this) else null }.firstOrNull { it != null } } return currentPositions.map { elf -> val elfSuggestion = elf.suggestion() when { elf.allAdjacent.allFree() -> MoveSuggestion(elf, elf) // stay elfSuggestion != null -> elfSuggestion else -> MoveSuggestion(elf, elf) // stay } } } } fun interface DirectionCheck { fun check(elf: Elf): Boolean } fun interface MoveSuggester { fun suggest(elf: Elf): MoveSuggestion } data class MoveSuggestion( val suggested: Elf, val current: Elf, ) data class Elf( val x: Int, val y: Int, ) : Comparable<Elf> { val allAdjacent: List<Elf> get() = listOf( north, northEast, northWest, south, southEast, southWest, east, west, ) val n: List<Elf> get() = listOf(north, northEast, northWest) val s: List<Elf> get() = listOf(south, southEast, southWest) val w: List<Elf> get() = listOf(west, northWest, southWest) val e: List<Elf> get() = listOf(east, northEast, southEast) val north: Elf get() = Elf(x, y - 1) val northEast: Elf get() = Elf(x + 1, y - 1) val northWest: Elf get() = Elf(x - 1, y - 1) val south: Elf get() = Elf(x, y + 1) val southEast: Elf get() = Elf(x + 1, y + 1) val southWest: Elf get() = Elf(x - 1, y + 1) val east: Elf get() = Elf(x + 1, y) val west: Elf get() = Elf(x - 1, y) override fun compareTo(other: Elf): Int { if (y != other.y) return y.compareTo(other.y) return x.compareTo(other.x) } } private fun parse(input: List<String>): Elves { val positions = input.flatMapIndexed { y: Int, row: String -> row .mapIndexedNotNull { x, char -> if (char == '#') Elf(x, y) else null } } return Elves(positions) } }
0
Kotlin
1
0
dbd25877071cbb015f8da161afb30cf1968249a8
6,234
aoc
Apache License 2.0
src/Day04.kt
AlaricLightin
572,897,551
false
{"Kotlin": 87366}
fun main() { fun getRanges(string: String): Pair<IntRange, IntRange> { val stringList = string.split(",") if (stringList.size < 2) throw IllegalArgumentException() val s0List = stringList[0].split("-") val s1List = stringList[1].split("-") return Pair(IntRange(s0List[0].toInt(), s0List[1].toInt()), IntRange(s1List[0].toInt(), s1List[1].toInt())) } fun part1(inputFilename: String): Int { var result = 0 getInputFile(inputFilename).forEachLine { val (range1, range2) = getRanges(it) if ((range1.contains(range2.first) && (range1.contains(range2.last)) || (range2.contains(range1.first) && range2.contains(range1.last)))) result++ } return result } fun part2(inputFilename: String): Int { var result = 0 getInputFile(inputFilename).forEachLine { val (range1, range2) = getRanges(it) val intersect = range1.intersect(range2) if (intersect.isNotEmpty()) result++ } return result } check(part1("Day04_test") == 2) check(part2("Day04_test") == 4) println(part1("Day04")) println(part2("Day04")) }
0
Kotlin
0
0
ee991f6932b038ce5e96739855df7807c6e06258
1,282
AdventOfCode2022
Apache License 2.0
src/main/kotlin/Main.kt
BapaLruH
245,823,915
false
null
fun max(first: Int, second: Int) = if (first > second) first else second fun max(first: Int, second: Int, third: Int) = if (max(first, second) > third) max(first, second) else third fun fitness(ivan: Int, nik: Int): Int { var month = 0 var powerIvan = ivan var powerNikolay = nik while (powerIvan < powerNikolay) { powerIvan *= 3 powerNikolay *= 2 month++ } return month } fun sum(start: Int, finish: Int): Int { var rsl = 0 for (value in start..finish) { rsl += value } return rsl } fun sumUntilFinish(start: Int, finish: Int): Int { var rsl = 0 for (value in start until finish) { rsl += value } return rsl } fun sumByStep2(start: Int, finish: Int): Int { var rsl = 0 for (value in start..finish step 2) { rsl += value } return rsl } fun sumDownTo(start: Int, finish: Int): Int { var rsl = 0 for (value in finish downTo start step 2) { rsl += value } return rsl } fun draw(size: Int) { if (size > 0 && size % 2 != 0) { for (value in 0..size step 2) { print("X") } println() } } fun createArray() { val names = arrayOfNulls<String>(10) names[0] = "<NAME>" for ((index, name) in names.withIndex()) { println("$index " + name?.length) } } fun createArrayList() { val names = ArrayList<String>() names.add("<NAME>") for (name in names) { println(name) } } fun sortArray(array: Array<String?>) : Array<String?>{ for ((index, value) in array.withIndex()) { if (value != null) { continue } for (i in index + 1 until array.size) { if (array[i] != null) { array[index] = array[i] array[i] = null break } else { continue } } } return array } fun main() { val age = 18 val last = "Ivanov" val name = "Ivan" val size = 65 println("Age : $age, last : $last, name : $name, size : $size") println("result : ${add(1, 2)}") println("result : ${subtract(1, 2)}") println("result : ${multiple(1, 2)}") println("result : ${divide(1, 2)}") println("max from 1 and 2 is ${max(1, 2)}") println("max from 1 and 2 and 3 is ${max(1, 3, 2)}") println("Month : ${fitness(50, 90)}") println("Sum : ${sum(1, 5)}") println("Sum : ${sumUntilFinish(1, 5)}") println("Sum : ${sumByStep2(1, 5)}") println("Sum : ${sumDownTo(1, 5)}") draw(51) createArray() createArrayList() }
0
Kotlin
0
0
d934ce3f5f282cd236f1285c7a398a55ccdb5ca6
2,633
job4j-kt
Apache License 2.0
kotlin/329.Longest Increasing Path in a Matrix(矩阵中的最长递增路径).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 integer matrix, find the length of the longest increasing path.</p> <p>From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).</p> <p><b>Example 1:</b></p> <pre> <strong>Input: </strong>nums = [ [<font color="red">9</font>,9,4], [<font color="red">6</font>,6,8], [<font color="red">2</font>,<font color="red">1</font>,1] ] <strong>Output:</strong> 4 <strong>Explanation:</strong> The longest increasing path is <code>[1, 2, 6, 9]</code>. </pre> <p><b>Example 2:</b></p> <pre> <strong>Input:</strong> nums = [ [<font color="red">3</font>,<font color="red">4</font>,<font color="red">5</font>], [3,2,<font color="red">6</font>], [2,2,1] ] <strong>Output: </strong>4 <strong>Explanation: </strong>The longest increasing path is <code>[3, 4, 5, 6]</code>. Moving diagonally is not allowed. </pre> <p>给定一个整数矩阵,找出最长递增路径的长度。</p> <p>对于每个单元格,你可以往上,下,左,右四个方向移动。 你不能在对角线方向上移动或移动到边界外(即不允许环绕)。</p> <p><strong>示例 1:</strong></p> <pre><strong>输入: </strong>nums = [ [<strong>9</strong>,9,4], [<strong>6</strong>,6,8], [<strong>2</strong>,<strong>1</strong>,1] ] <strong>输出:</strong> 4 <strong>解释:</strong> 最长递增路径为&nbsp;<code>[1, 2, 6, 9]</code>。</pre> <p><strong>示例 2:</strong></p> <pre><strong>输入:</strong> nums = [ [<strong>3</strong>,<strong>4</strong>,<strong>5</strong>], [3,2,<strong>6</strong>], [2,2,1] ] <strong>输出: </strong>4 <strong>解释: </strong>最长递增路径是&nbsp;<code>[3, 4, 5, 6]</code>。注意不允许在对角线方向上移动。 </pre> <p>给定一个整数矩阵,找出最长递增路径的长度。</p> <p>对于每个单元格,你可以往上,下,左,右四个方向移动。 你不能在对角线方向上移动或移动到边界外(即不允许环绕)。</p> <p><strong>示例 1:</strong></p> <pre><strong>输入: </strong>nums = [ [<strong>9</strong>,9,4], [<strong>6</strong>,6,8], [<strong>2</strong>,<strong>1</strong>,1] ] <strong>输出:</strong> 4 <strong>解释:</strong> 最长递增路径为&nbsp;<code>[1, 2, 6, 9]</code>。</pre> <p><strong>示例 2:</strong></p> <pre><strong>输入:</strong> nums = [ [<strong>3</strong>,<strong>4</strong>,<strong>5</strong>], [3,2,<strong>6</strong>], [2,2,1] ] <strong>输出: </strong>4 <strong>解释: </strong>最长递增路径是&nbsp;<code>[3, 4, 5, 6]</code>。注意不允许在对角线方向上移动。 </pre> **/ class Solution { fun longestIncreasingPath(matrix: Array<IntArray>): Int { } }
0
Python
1
3
6731e128be0fd3c0bdfe885c1a409ac54b929597
2,807
leetcode
MIT License
src/leetcode/aprilChallenge2020/weekfour/MaximalSquare.kt
adnaan1703
268,060,522
false
null
package leetcode.aprilChallenge2020.weekfour import kotlin.math.max import kotlin.math.min fun main() { var matrix = arrayOf( charArrayOf('1', '0', '1', '0', '0'), charArrayOf('1', '0', '1', '1', '1'), charArrayOf('1', '1', '1', '1', '1'), charArrayOf('1', '0', '0', '1', '0') ) println(maximalSquare(matrix)) // ans: 4 matrix = arrayOf( charArrayOf('0', '1', '1', '0', '1'), charArrayOf('1', '1', '0', '1', '0'), charArrayOf('0', '1', '1', '1', '0'), charArrayOf('1', '1', '1', '1', '0'), charArrayOf('1', '1', '1', '1', '1'), charArrayOf('0', '0', '0', '0', '0') ) println(maximalSquare(matrix)) // ans: 9 matrix = arrayOf(charArrayOf()) println(maximalSquare(matrix)) matrix = arrayOf() println(maximalSquare(matrix)) } fun maximalSquare(matrix: Array<CharArray>): Int { var ans = 0 if (matrix.isEmpty() || matrix[0].isEmpty()) return 0 val dp: Array<IntArray> = Array(matrix.size) { IntArray(matrix[0].size) } for (i in 0..matrix[0].lastIndex) { dp[0][i] = matrix[0][i].getBinaryValue() if (dp[0][i] == 1) ans = 1 } for (i in 0..matrix.lastIndex) { dp[i][0] = matrix[i][0].getBinaryValue() if (dp[i][0] == 1) ans = 1 } for (i in 1..matrix.lastIndex) { for (j in 1..matrix[i].lastIndex) { val num = matrix[i][j].getBinaryValue() if (num == 1) { dp[i][j] = min(dp[i - 1][j], min(dp[i][j - 1], dp[i - 1][j - 1])) + 1 ans = max(ans, dp[i][j]) } else { dp[i][j] = 0 } } } return ans * ans } fun Char.getBinaryValue(): Int { return if (this == '1') 1 else 0 }
0
Kotlin
0
0
e81915db469551342e78e4b3f431859157471229
1,797
KotlinCodes
The Unlicense
src/main/kotlin/dev/shtanko/algorithms/leetcode/AddTwoNumbers.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 dev.shtanko.algorithms.DECIMAL /** * 2. Add Two Numbers * @see <a href="https://leetcode.com/problems/add-two-numbers">Source</a> */ fun interface AddTwoNumbers { operator fun invoke(l1: ListNode?, l2: ListNode?): ListNode? } class AddTwoNumbersMath : AddTwoNumbers { override fun invoke(l1: ListNode?, l2: ListNode?): ListNode? { val dummy = ListNode(0) // creating a dummy list var curr: ListNode? = dummy // initialising a pointer var carry = 0 // initialising our carry with 0 initial // while loop will run, until l1 OR l2 not reaches null OR if they both reaches null. // But our carry has some value in it. We will add that as well into our list var l10 = l1 var l20 = l2 while (l10 != null || l20 != null || carry == 1) { var sum = 0 // initialising our sum if (l10 != null) { // adding l1 to our sum & moving l1 sum += l10.value l10 = l10.next } if (l20 != null) { // adding l2 to our sum & moving l2 sum += l20.value l20 = l20.next } sum += carry // if we have carry then add it into our sum carry = sum / DECIMAL // if we get carry, then divide it by 10 to get the carry val node = ListNode(sum % DECIMAL) // the value we'll get by modulating it, // will become as new node so. add it to our list curr?.next = node // curr will point to that new node if we get curr = curr?.next // update the current every time } return dummy.next // return dummy.next bcz, we don't want the value we have considered in it initially } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,374
kotlab
Apache License 2.0
src/Day01.kt
nguyendanv
573,066,311
false
{"Kotlin": 18026}
fun main() { fun part1(input: List<String>): Int { return input .joinToString("\n") .split("\n\n") .maxOfOrNull { it.split("\n").sumOf(String::toInt) }!! } fun part2(input: List<String>): Int { return input .joinToString("\n") .split("\n\n") .map { it.split("\n").sumOf(String::toInt) } .sortedDescending() .subList(0, 3) .sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
376512583af723b4035b170db1fa890eb32f2f0f
717
advent2022
Apache License 2.0
src/main/kotlin/Exercise4.kt
US-ADDA
521,923,956
false
{"Kotlin": 17265}
import java.util.stream.Stream import kotlin.math.absoluteValue import kotlin.math.pow class Exercise4 { companion object { fun functional(n: Double, e: Double): Double { val pair = Stream.iterate( Pair(0.0, n) // Definimos el comienzo como 0 (nos dicen que se calcula la raíz cúbica de un número positivo) y el valor del que queremos saber la raíz cúbica. ) { val middle = it.first.plus(it.second).div(2) // Calculamos el valor medio. // Analizamos donde puede estar aplicando búsqueda binaria (de inicio a medio y de medio a fin). if (middle.pow(3) > n && it.first.pow(3) < n) Pair(it.first, middle) else if (middle.pow(3) < n && it.second.pow(3) > n) Pair(middle, it.second) else it }.filter { it.first.plus(it.second).div(2).pow(3).minus(n).absoluteValue < e.pow(3) }.findFirst() // Indicamos que termine cuando el error al cubo sea mayor que la resta del medio al cubo con el valor del que qeremos saber su rai´z cúbica .orElse(Pair(0.0, 0.0)) return pair.first.plus(pair.second).div(2) } fun iterativeWhile(n: Double, e: Double): Double { var current = Pair(0.0, n) var middle = n.div(2) while (middle.pow(3).minus(n).absoluteValue > e.pow(3)) { current = if (middle.pow(3) > n && current.first.pow(3) < n) Pair(current.first, middle) else if (middle.pow(3) < n && current.second.pow(3) > n) Pair(middle, current.second) else current middle = current.first.plus(current.second).div(2) } return middle } fun recursiveFinal(n: Double, e: Double): Double { return recursiveFinal(n, e, Pair(0.0, n), n.div(2)) } private fun recursiveFinal(n: Double, e: Double, current: Pair<Double, Double>, middle: Double): Double { return if (middle.pow(3).minus(n).absoluteValue <= e.pow(3)) middle else { val auxCurrent = if (middle.pow(3) > n && current.first.pow(3) < n) Pair(current.first, middle) else if (middle.pow(3) < n && current.second.pow(3) > n) Pair(middle, current.second) else current val auxMiddle = auxCurrent.first.plus(auxCurrent.second).div(2) recursiveFinal(n, e, auxCurrent, auxMiddle) } } } }
0
Kotlin
0
0
b83e4fd0e457bda0b026df3a94f538d4dab715cf
2,505
PI1_kotlin
Apache License 2.0
src/Day23.kt
greg-burgoon
573,074,283
false
{"Kotlin": 120556}
enum class Direction { NORTH, SOUTH, EAST, WEST } fun main() { data class Coord(val y: Int, val x: Int) { fun N(): Coord{ return Coord(y-1, x) } fun S(): Coord{ return Coord(y+1, x) } fun E(): Coord{ return Coord(y, x+1) } fun W(): Coord{ return Coord(y, x-1) } fun NW(): Coord{ return Coord(y-1, x-1) } fun NE(): Coord{ return Coord(y-1, x+1) } fun SW(): Coord{ return Coord(y+1, x-1) } fun SE(): Coord{ return Coord(y+1, x+1) } override fun toString(): String { return "Coord(y=$y, x=$x)" } } fun printGrid(coordMap: MutableMap<Coord, Boolean>) { var minX = coordMap.filter { it.value }.keys.minOf { it.x } var maxX = coordMap.filter { it.value }.keys.maxOf { it.x } var minY = coordMap.filter { it.value }.keys.minOf { it.y } var maxY = coordMap.filter { it.value }.keys.maxOf { it.y } for (y in minY .. maxY) { for (x in minX .. maxX) { if (coordMap.getOrDefault(Coord(y,x), false)) { print("#") } else { print(".") } } println("") } } fun part1(input: String): Int { var coordMap = mutableMapOf<Coord, Boolean>() input.split("\n").forEachIndexed { y, s -> s.forEachIndexed { x, c -> if (c == '#') { coordMap[Coord(y,x)] = true } } } var numberOfElves = coordMap.keys.size var moved = true var directionSequence = ArrayDeque<Direction>() directionSequence.add(Direction.NORTH) directionSequence.add(Direction.SOUTH) directionSequence.add(Direction.WEST) directionSequence.add(Direction.EAST) var round = 0 println("Round: "+round) printGrid(coordMap) repeat (10) { var proposedMoves = mutableMapOf<Coord, Int>() var transitions = mutableMapOf<Coord, Coord>() coordMap.filter { it.value == true }.keys.forEach { coord -> var nextCoord: Coord? = null var moveMap = mutableMapOf<Direction,Int>() directionSequence.forEach { when(it) { Direction.NORTH -> { var canMove = !coordMap.getOrDefault(coord.NW(), false) && !coordMap.getOrDefault(coord.N(), false) && !coordMap.getOrDefault(coord.NE(), false) if (nextCoord == null && canMove) { nextCoord = coord.N() } if (canMove) { moveMap[Direction.NORTH] = 1 } } Direction.SOUTH -> { var canMove = !coordMap.getOrDefault(coord.SW(), false) && !coordMap.getOrDefault(coord.S(), false) && !coordMap.getOrDefault(coord.SE(), false) if (nextCoord == null && canMove) { nextCoord = coord.S() } if (canMove) { moveMap[Direction.SOUTH] = 1 } } Direction.WEST -> { var canMove = !coordMap.getOrDefault(coord.NW(), false) && !coordMap.getOrDefault(coord.W(), false) && !coordMap.getOrDefault(coord.SW(), false) if (nextCoord == null && canMove) { nextCoord = coord.W() } if (canMove) { moveMap[Direction.WEST] = 1 } } else -> { var canMove = !coordMap.getOrDefault(coord.NE(), false) && !coordMap.getOrDefault(coord.E(), false) && !coordMap.getOrDefault(coord.SE(), false) if (nextCoord == null && canMove) { nextCoord = coord.E() } if (canMove) { moveMap[Direction.EAST] = 1 } } } } if (moveMap.values.sum() == 4) { //noop } else if (nextCoord != null) { // println("Proposing moving "+coord+" to "+nextCoord!!) proposedMoves[nextCoord!!] = proposedMoves.getOrDefault(nextCoord!!, 0) + 1 transitions[nextCoord!!] = coord } } var newMoves = proposedMoves.filter { it.value == 1 } newMoves.keys.forEach { // println("Moved "+transitions[it]!!+" to "+it) coordMap[transitions[it]!!] = false coordMap[it] = true } moved = newMoves.isNotEmpty() directionSequence.addLast(directionSequence.removeFirst()) round++ println("Round: "+round) printGrid(coordMap) } var minX = coordMap.filter { it.value }.keys.minOf { it.x } var maxX = coordMap.filter { it.value }.keys.maxOf { it.x } var minY = coordMap.filter { it.value }.keys.minOf { it.y } var maxY = coordMap.filter { it.value }.keys.maxOf { it.y } var length = maxX - minX + 1 var width = maxY - minY + 1 var emptyTiles = (length*width) - numberOfElves return emptyTiles } fun part2(input: String): Int { var coordMap = mutableMapOf<Coord, Boolean>() input.split("\n").forEachIndexed { y, s -> s.forEachIndexed { x, c -> if (c == '#') { coordMap[Coord(y,x)] = true } } } var numberOfElves = coordMap.keys.size var moved = true var directionSequence = ArrayDeque<Direction>() directionSequence.add(Direction.NORTH) directionSequence.add(Direction.SOUTH) directionSequence.add(Direction.WEST) directionSequence.add(Direction.EAST) var round = 0 while (moved) { var proposedMoves = mutableMapOf<Coord, Int>() var transitions = mutableMapOf<Coord, Coord>() coordMap.filter { it.value == true }.keys.forEach { coord -> var nextCoord: Coord? = null var moveMap = mutableMapOf<Direction,Int>() directionSequence.forEach { when(it) { Direction.NORTH -> { var canMove = !coordMap.getOrDefault(coord.NW(), false) && !coordMap.getOrDefault(coord.N(), false) && !coordMap.getOrDefault(coord.NE(), false) if (nextCoord == null && canMove) { nextCoord = coord.N() } if (canMove) { moveMap[Direction.NORTH] = 1 } } Direction.SOUTH -> { var canMove = !coordMap.getOrDefault(coord.SW(), false) && !coordMap.getOrDefault(coord.S(), false) && !coordMap.getOrDefault(coord.SE(), false) if (nextCoord == null && canMove) { nextCoord = coord.S() } if (canMove) { moveMap[Direction.SOUTH] = 1 } } Direction.WEST -> { var canMove = !coordMap.getOrDefault(coord.NW(), false) && !coordMap.getOrDefault(coord.W(), false) && !coordMap.getOrDefault(coord.SW(), false) if (nextCoord == null && canMove) { nextCoord = coord.W() } if (canMove) { moveMap[Direction.WEST] = 1 } } else -> { var canMove = !coordMap.getOrDefault(coord.NE(), false) && !coordMap.getOrDefault(coord.E(), false) && !coordMap.getOrDefault(coord.SE(), false) if (nextCoord == null && canMove) { nextCoord = coord.E() } if (canMove) { moveMap[Direction.EAST] = 1 } } } } if (moveMap.values.sum() == 4) { //noop } else if (nextCoord != null) { proposedMoves[nextCoord!!] = proposedMoves.getOrDefault(nextCoord!!, 0) + 1 transitions[nextCoord!!] = coord } } var newMoves = proposedMoves.filter { it.value == 1 } newMoves.keys.forEach { coordMap[transitions[it]!!] = false coordMap[it] = true } moved = newMoves.isNotEmpty() directionSequence.addLast(directionSequence.removeFirst()) round++ } return round } val testInput = readInput("Day23_test") val output = part1(testInput) check(output == 110) val outputTwo = part2(testInput) check(outputTwo == 20) val input = readInput("Day23") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
74f10b93d3bad72fa0fc276b503bfa9f01ac0e35
10,647
aoc-kotlin
Apache License 2.0
src/deselby/std/extensions/collections.kt
deselby-research
166,023,166
false
null
package deselby.std.extensions import kotlin.math.pow import kotlin.math.sqrt data class Statistics(val mean: Double, val variance: Double, val SD: Double) fun Iterable<Number>.statistics() = this.asSequence().statistics() fun Sequence<Number>.statistics() : Statistics { var sum = 0.0 var sumOfSquares = 0.0 var n = 0 this.forEach { sum += it.toDouble() sumOfSquares += it.toDouble().pow(2) ++n } val mean = sum/n val variance = sumOfSquares/n - mean*mean return Statistics(mean, variance, sqrt(variance)) } fun Iterable<Number>.variance() = this.asSequence().variance() fun Sequence<Number>.variance() : Double { var sum = 0.0 var sumOfSquares = 0.0 var n = 0 this.forEach { sum += it.toDouble() sumOfSquares += it.toDouble().pow(2) ++n } val mean = sum/n return sumOfSquares/n - mean*mean } fun Iterable<Number>.standardDeviation() = sqrt(this.asSequence().variance()) fun Sequence<Number>.standardDeviation() = sqrt(this.variance()) inline fun<T: Number> Iterable<T>.expectationValue(f : (T) -> Double) = this.asSequence().expectationValue(f) inline fun<T: Number> Sequence<T>.expectationValue(f : (T) -> Double) : Double { var n = 0 var sum = 0.0 this.forEach { sum += f(it) ++n } return sum/n }
0
Kotlin
1
8
6c76a9a18e2caafc1ff00ab970d0df4d703f0119
1,353
ProbabilisticABM
MIT License