path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/main/kotlin/dev/shtanko/algorithms/leetcode/DailyTemperatures.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 import java.util.Deque import java.util.LinkedList import java.util.Stack /** * 739. Daily Temperatures * @see <a href="https://leetcode.com/problems/daily-temperatures">Source</a> */ fun interface DailyTemperatures { operator fun invoke(temperatures: IntArray): IntArray } class DailyTemperaturesStack : DailyTemperatures { override operator fun invoke(temperatures: IntArray): IntArray { val stack: Stack<Int> = Stack() val ret = IntArray(temperatures.size) for (i in temperatures.indices) { while (stack.isNotEmpty() && temperatures[i] > temperatures[stack.peek()]) { val idx: Int = stack.pop() ret[idx] = i - idx } stack.push(i) } return ret } } class DailyTemperaturesArr : DailyTemperatures { override operator fun invoke(temperatures: IntArray): IntArray { val stack = IntArray(temperatures.size) var top = -1 val ret = IntArray(temperatures.size) for (i in temperatures.indices) { while (top > -1 && temperatures[i] > temperatures[stack[top]]) { val idx = stack[top--] ret[idx] = i - idx } stack[++top] = i } return ret } } class DailyTemperaturesDeque : DailyTemperatures { override operator fun invoke(temperatures: IntArray): IntArray { if (temperatures.isEmpty()) { return intArrayOf() } val stack: Deque<Int> = LinkedList() val res = IntArray(temperatures.size) // the idea is to keep all element in ascending order! for (i in temperatures.indices) { if (stack.isEmpty()) { // case1 : stack is empty, feel free to push stack.offerFirst(i) } else if (stack.isNotEmpty() && temperatures[i] > temperatures[stack.peekFirst()]) { // case2 : descending order happens: // pop all the smaller element out, then push the current element while (stack.isNotEmpty() && temperatures[i] > temperatures[stack.peekFirst()]) { res[stack.peekFirst()] = i - stack.peekFirst() stack.pollFirst() } stack.offerFirst(i) // push current element to keep ascending order } else { // case3 : push current element to keep ascending order stack.offerFirst(i) } } return res } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,171
kotlab
Apache License 2.0
src/main/kotlin/days/Day4.kt
hughjdavey
317,575,435
false
null
package days import isIntAndInRange class Day4 : Day(4) { private val passports = inputString.split(Regex("\\W\\n", RegexOption.MULTILINE)).map { Passport(it) } // 213 override fun partOne(): Any { return passports.count { it.hasValidKeys() } } // 147 override fun partTwo(): Any { return passports.count { it.hasValidKeysAndValues() } } class Passport(str: String) { private val passport = Regex("([\\w]+:[\\w\\d#]+)").findAll(str).toList() .map { it.value } .map { val x = it.split(":"); x[0] to x[1] }.toMap() fun hasValidKeys(): Boolean { return passport.keys.containsAll(FIELDS) } // the !! assertions are safe below as we know the keys exist from the first predicate fun hasValidKeysAndValues(): Boolean { return hasValidKeys() && validBirthYear() && validIssueYear() && validExpiryYear() && validHeight() && validHairColour() && validEyeColour() && validPassportId() } fun validBirthYear() = passport["byr"]!!.isIntAndInRange(1920, 2002) fun validIssueYear() = passport["iyr"]!!.isIntAndInRange(2010, 2020) fun validExpiryYear() = passport["eyr"]!!.isIntAndInRange(2020, 2030) fun validHairColour() = passport["hcl"]!!.matches(Regex("#[a-f|0-9]{6}")) fun validEyeColour() = passport["ecl"]!!.matches(Regex("amb|blu|brn|gry|grn|hzl|oth")) fun validPassportId() = passport["pid"]!!.matches(Regex("[0-9]{9}")) fun validHeight(): Boolean { val r = Regex("^(\\d+)(cm|in)\$").matchEntire(passport["hgt"]!!) ?: return false val (n, unit) = r.groupValues[1] to r.groupValues[2] return (unit == "cm" || unit == "in") && if (unit == "cm") n.isIntAndInRange(150, 193) else n.isIntAndInRange(59, 76) } companion object { val FIELDS = listOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid") } } }
0
Kotlin
0
1
63c677854083fcce2d7cb30ed012d6acf38f3169
2,003
aoc-2020
Creative Commons Zero v1.0 Universal
src/main/kotlin/dev/shtanko/algorithms/leetcode/WiggleSort.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 dev.shtanko.algorithms.extensions.swap fun interface WiggleSort { operator fun invoke(nums: IntArray) } /** * Approach #1 (Sorting) */ class WiggleSortBruteForce : WiggleSort { override operator fun invoke(nums: IntArray) { for (i in 1 until nums.size) { val a = nums[i - 1] if (i % 2 == 1 == a > nums[i]) { nums[i - 1] = nums[i] nums[i] = a } } } } /** * Approach #2 (One-pass Swap) */ class WiggleSortOnePassSwap : WiggleSort { override operator fun invoke(nums: IntArray) { var less = true for (i in 0 until nums.size - 1) { if (less) { if (nums[i] > nums[i + 1]) { nums.swap(i, i + 1) } } else { if (nums[i] < nums[i + 1]) { nums.swap(i, i + 1) } } less = !less } } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,608
kotlab
Apache License 2.0
kotlin/src/main/kotlin/adventofcode/day9/Day9_1.kt
thelastnode
160,586,229
false
null
package adventofcode.day8 import java.util.* object Day9_1 { fun process(playerCount: Int, marbleCount: Int): Int { val marbles = ArrayList<Int>(marbleCount + 1) marbles.add(0) val scores = (0 until playerCount).map { 0 }.toMutableList() var currentMarbleIndex = 0 var currentPlayer = 0 for (nextMarble in 1..marbleCount) { if (nextMarble % 23 == 0) { val removalIndex = (currentMarbleIndex - 7 + marbles.size) % marbles.size val removed = marbles.removeAt(removalIndex) scores[currentPlayer] += nextMarble + removed currentMarbleIndex = (removalIndex + marbles.size) % marbles.size } else { val nextMarbleIndex = (currentMarbleIndex + 2) % marbles.size if (nextMarbleIndex == marbles.size) { marbles.add(nextMarble) } else { marbles.add(nextMarbleIndex, nextMarble) } currentMarbleIndex = nextMarbleIndex } currentPlayer = (currentPlayer + 1) % playerCount } return scores.max()!! } } fun main(args: Array<String>) { println(Day9_1.process(playerCount = 10, marbleCount = 1618)) println(Day9_1.process(playerCount = 13, marbleCount = 7999)) println(Day9_1.process(playerCount = 17, marbleCount = 1104)) println(Day9_1.process(playerCount = 21, marbleCount = 6111)) println(Day9_1.process(playerCount = 30, marbleCount = 5807)) println(Day9_1.process(playerCount = 491, marbleCount = 71058)) }
0
Kotlin
0
0
8c9a3e5a9c8b9dd49eedf274075c28d1ebe9f6fa
1,628
adventofcode
MIT License
src/main/kotlin/com/colinodell/advent2022/Day17.kt
colinodell
572,710,708
false
{"Kotlin": 105421}
package com.colinodell.advent2022 import kotlin.math.min class Day17(input: String) { private val jetPattern = input.map { when (it) { '<' -> Vector2(-1, 0) '>' -> Vector2(1, 0) else -> error("Invalid jet pattern") } } private val shapes = listOf( listOf(Vector2(0, 0), Vector2(1, 0), Vector2(2, 0), Vector2(3, 0)), listOf(Vector2(0, 1), Vector2(1, 0), Vector2(1, 1), Vector2(2, 1), Vector2(1, 2)), listOf(Vector2(0, 0), Vector2(1, 0), Vector2(2, 0), Vector2(2, 1), Vector2(2, 2)), listOf(Vector2(0, 0), Vector2(0, 1), Vector2(0, 2), Vector2(0, 3)), listOf(Vector2(0, 0), Vector2(0, 1), Vector2(1, 0), Vector2(1, 1)), ) fun solvePart1() = simulate(2022) fun solvePart2() = simulate(1000000000000) private fun simulate(rocksToDrop: Long): Long { val fallenRocks = mutableSetOf<Vector2>() var rocksDropped = 0 var jetIndex = -1 var highestPoint = 0 val seenCycles = mutableSetOf<Int>() var cycle: Cycle? = null val heightAfterNDroppedRocks = mutableListOf<Int>() // A cycle should be detected after (shape size * jet pattern size) iterations val repetitions = min( rocksToDrop, (shapes.size * jetPattern.size).toLong() ) repeat(repetitions.toInt()) { // The bottom edge should start three units above the highest rock in the room (or the floor, if there isn't one). var shape = shapes[rocksDropped % shapes.size].map { it + Vector2(2, highestPoint + 4) } while (true) { // Move left/right with the jet pattern jetIndex = (jetIndex + 1) % jetPattern.size var candidatePosition = shape.map { it + jetPattern[jetIndex] } // Only move if there's no collision if (!hasCollision(candidatePosition, fallenRocks)) { shape = candidatePosition } // Move downwards candidatePosition = shape.map { it + Vector2(0, -1) } // Only move if there's no collision if (!hasCollision(candidatePosition, fallenRocks)) { shape = candidatePosition } else { break // We've hit something, so we're done with this rock } } // Add this rock to our list of fallen rocks rocksDropped++ fallenRocks.addAll(shape) highestPoint = fallenRocks.maxOf { it.y } // Try to detect a cycle // A cycle occurs when we continue seeing the same jet pattern index after dropping all five shapes if (rocksDropped % shapes.size == 0) { if (cycle == null) { // We have not yet seen a cycle, so record the current jet pattern index for next time if (!seenCycles.add(jetIndex)) { cycle = Cycle(jetIndex, shape[0].y, rocksDropped) } } else if (cycle!!.index == jetIndex) { // The cycle is repeating! val cycleHeight = shape[0].y - cycle!!.yPosition val cycleSize = rocksDropped - cycle!!.rocksDropped val rocksToJumpOver = rocksToDrop - cycle!!.rocksDropped val cycleCount = rocksToJumpOver / cycleSize val extraRocks = (rocksToJumpOver % cycleSize).toInt() return (cycleCount * cycleHeight) + heightAfterNDroppedRocks[extraRocks] } } // Record the height of the rocks after this rock was dropped // We'll use this later when we detect a cycle if (cycle != null) { heightAfterNDroppedRocks.add(highestPoint) } } return highestPoint.toLong() } private fun hasCollision(shape: List<Vector2>, grid: Set<Vector2>): Boolean { return shape.any { it.x !in 0..6 || it.y <= 0 || it in grid } } private data class Cycle(val index: Int, val yPosition: Int, val rocksDropped: Int) }
0
Kotlin
0
1
32da24a888ddb8e8da122fa3e3a08fc2d4829180
4,240
advent-2022
MIT License
year2021/src/main/kotlin/net/olegg/aoc/year2021/day19/Day19.kt
0legg
110,665,187
false
{"Kotlin": 511989}
package net.olegg.aoc.year2021.day19 import net.olegg.aoc.someday.SomeDay import net.olegg.aoc.utils.Vector3D import net.olegg.aoc.utils.pairs import net.olegg.aoc.utils.parseInts import net.olegg.aoc.year2021.DayOf2021 /** * See [Year 2021, Day 19](https://adventofcode.com/2021/day/19) */ object Day19 : DayOf2021(19) { override fun first(): Any? { return findAllData().first.size } override fun second(): Any? { return findAllData() .second .toList() .pairs() .maxOf { (a, b) -> (a - b).manhattan() } } private fun findAllData(): Pair<Set<Vector3D>, Set<Vector3D>> { val visibleBeacons = data .split("\n\n") .map { block -> block.lines() .drop(1) .map { it.parseInts(",") } .map { Vector3D(it[0], it[1], it[2]) } } val dists = visibleBeacons .map { beacons -> beacons.flatMapIndexed { index, first -> beacons.drop(index + 1).map { second -> (second - first).length2() } }.toSet() } val possiblePairs = visibleBeacons.indices .toList() .pairs() .filter { (indexA, indexB) -> dists[indexA].intersect(dists[indexB]).size >= 66 } .flatMap { listOf(it, it.second to it.first) } .groupBy { it.first } val oriented = mutableSetOf(0) val beacons = visibleBeacons[0].toMutableSet() val scanners = mutableSetOf(Vector3D()) val queue = ArrayDeque(possiblePairs[0].orEmpty()) val orientedBeacons = visibleBeacons.toMutableList() while (queue.isNotEmpty()) { val curr = queue.removeFirst() val (base, new) = when { curr.first in oriented && curr.second in oriented -> continue curr.first in oriented -> curr.first to curr.second curr.second in oriented -> curr.second to curr.first else -> error("One of points should be already oriented") } val baseDists = orientedBeacons[base] .indices .toList() .pairs() .map { (a, b) -> val beaconA = orientedBeacons[base][a] val beaconB = orientedBeacons[base][b] Triple(a, b, (beaconB - beaconA).length2()) } .toList() val newDists = visibleBeacons[new] .indices .toList() .pairs() .map { (a, b) -> val beaconA = visibleBeacons[new][a] val beaconB = visibleBeacons[new][b] Triple(a, b, (beaconB - beaconA).length2()) } .toList() val matchCount = mutableMapOf<Pair<Int, Int>, Int>() baseDists.forEach { baseTriple -> newDists.forEach { newTriple -> if (baseTriple.third == newTriple.third) { matchCount[baseTriple.first to newTriple.first] = matchCount.getOrDefault(baseTriple.first to newTriple.first, 0) + 1 matchCount[baseTriple.first to newTriple.second] = matchCount.getOrDefault(baseTriple.first to newTriple.second, 0) + 1 matchCount[baseTriple.second to newTriple.first] = matchCount.getOrDefault(baseTriple.second to newTriple.first, 0) + 1 matchCount[baseTriple.second to newTriple.second] = matchCount.getOrDefault(baseTriple.second to newTriple.second, 0) + 1 } } } val matches = matchCount.filterValues { it == 11 }.keys val rotation = ALL_ROTATIONS.first { currRotation -> matches .map { (baseIndex, newIndex) -> val baseA = orientedBeacons[base][baseIndex] val newA = visibleBeacons[new][newIndex] val convertedA = currRotation(newA) baseA - convertedA } .distinct() .size == 1 } val delta = matches.first().let { (baseIndex, newIndex) -> val baseA = orientedBeacons[base][baseIndex] val newA = visibleBeacons[new][newIndex] val convertedA = rotation(newA) baseA - convertedA } val rotatedPoints = visibleBeacons[new] .map { point -> rotation(point) + delta } beacons += rotatedPoints scanners += rotation(Vector3D()) + delta orientedBeacons[new] = rotatedPoints oriented += new queue += possiblePairs[new].orEmpty() } return beacons to scanners } private val ALL_ROTATIONS: List<Vector3D.() -> Vector3D> = listOf( { Vector3D(x, y, z) }, { Vector3D(x, y, -z) }, { Vector3D(x, -y, z) }, { Vector3D(x, -y, -z) }, { Vector3D(-x, y, z) }, { Vector3D(-x, y, -z) }, { Vector3D(-x, -y, z) }, { Vector3D(-x, -y, -z) }, { Vector3D(x, z, y) }, { Vector3D(x, z, -y) }, { Vector3D(x, -z, y) }, { Vector3D(x, -z, -y) }, { Vector3D(-x, z, y) }, { Vector3D(-x, z, -y) }, { Vector3D(-x, -z, y) }, { Vector3D(-x, -z, -y) }, { Vector3D(y, x, z) }, { Vector3D(y, x, -z) }, { Vector3D(y, -x, z) }, { Vector3D(y, -x, -z) }, { Vector3D(-y, x, z) }, { Vector3D(-y, x, -z) }, { Vector3D(-y, -x, z) }, { Vector3D(-y, -x, -z) }, { Vector3D(y, z, x) }, { Vector3D(y, z, -x) }, { Vector3D(y, -z, x) }, { Vector3D(y, -z, -x) }, { Vector3D(-y, z, x) }, { Vector3D(-y, z, -x) }, { Vector3D(-y, -z, x) }, { Vector3D(-y, -z, -x) }, { Vector3D(z, y, x) }, { Vector3D(z, y, -x) }, { Vector3D(z, -y, x) }, { Vector3D(z, -y, -x) }, { Vector3D(-z, y, x) }, { Vector3D(-z, y, -x) }, { Vector3D(-z, -y, x) }, { Vector3D(-z, -y, -x) }, { Vector3D(z, x, y) }, { Vector3D(z, x, -y) }, { Vector3D(z, -x, y) }, { Vector3D(z, -x, -y) }, { Vector3D(-z, x, y) }, { Vector3D(-z, x, -y) }, { Vector3D(-z, -x, y) }, { Vector3D(-z, -x, -y) }, ) } fun main() = SomeDay.mainify(Day19)
0
Kotlin
1
7
e4a356079eb3a7f616f4c710fe1dfe781fc78b1a
5,836
adventofcode
MIT License
src/Day21.kt
felldo
572,233,925
false
{"Kotlin": 76496}
import java.lang.Exception import java.lang.Long.max data class Monkeyy(val name: String, val monkey1: String, val monkey2: String, val operation: Char, var output: Long = Long.MIN_VALUE) fun main() { fun recurseMonkeys(monkeyys: MutableList<Monkeyy>, current: String, target: Long): Long { if (current == "humn") { return target } val monkey = monkeyys.find { it.name == current }!! val monkey1 = monkeyys.find{ it.name == monkey.monkey1 }!! val monkey2 = monkeyys.find{ it.name == monkey.monkey2 }!! if (monkey1.output == Long.MIN_VALUE) { val newTarget = when (monkey.operation) { '+' -> target - monkey2.output '-' -> target + monkey2.output '*' -> target / monkey2.output '/' -> target * monkey2.output '=' -> monkey2.output else -> throw Exception() } monkey1.output = newTarget return recurseMonkeys(monkeyys, monkey1.name, newTarget) } else { val newTarget = when (monkey.operation) { '+' -> target - monkey1.output '-' -> monkey1.output - target '*' -> target / monkey1.output '/' -> monkey1.output / target '=' -> monkey1.output else -> throw Exception() } monkey2.output = newTarget return recurseMonkeys(monkeyys, monkey2.name, newTarget) } } fun part1(input: List<String>): Long { val monkeyys = mutableListOf<Monkeyy>() for (line in input) { // root: pppw + sjmn val name = line.substring(0, 4) var output = Long.MIN_VALUE var monkey1 = "" var monkey2 = "" var operation = ' ' if (line.length < 15) { output = line.substringAfter(" ").toLong() } else { monkey1 = line.substring(6, 10) monkey2 = line.substring(13, 17) operation = line[11] } monkeyys.add(Monkeyy(name, monkey1, monkey2, operation, output)) } while (monkeyys.find { it.name == "root"}!!.output == Long.MIN_VALUE) { for (monkey in monkeyys) { if (monkey.output == Long.MIN_VALUE) { val monkey1 = monkeyys.find{ it.name == monkey.monkey1 }!!.output val monkey2 = monkeyys.find{ it.name == monkey.monkey2 }!!.output if (monkey1 != Long.MIN_VALUE && monkey2 != Long.MIN_VALUE) { monkey.output = when (monkey.operation) { '+' -> monkey1 + monkey2 '-' -> monkey1 - monkey2 '*' -> monkey1 * monkey2 '/' -> monkey1 / monkey2 else -> throw Exception() } if (monkey.output < 0 && monkey1 > 0 && monkey2 > 0) { println("Woo") } } } } } return monkeyys.find { it.name == "root"}!!.output } fun part2(input: List<String>): Long { val monkeyys = mutableListOf<Monkeyy>() for (line in input) { // root: pppw + sjmn val name = line.substring(0, 4) var output = Long.MIN_VALUE var monkey1 = "" var monkey2 = "" var operation = ' ' if (line.length < 15) { output = line.substringAfter(" ").toLong() } else { monkey1 = line.substring(6, 10) monkey2 = line.substring(13, 17) operation = line[11] } // Change human's output to impossible if (name == "humn") { output = Long.MIN_VALUE monkey1 = "humn" monkey2 = "humn" } // Change root's operation if (name == "root") { operation = '=' } monkeyys.add(Monkeyy(name, monkey1, monkey2, operation, output)) } var changed = true while (changed) { changed = false for (monkey in monkeyys) { if (monkey.output == Long.MIN_VALUE) { val monkey1 = monkeyys.find{ it.name == monkey.monkey1 }!!.output val monkey2 = monkeyys.find{ it.name == monkey.monkey2 }!!.output if (monkey1 != Long.MIN_VALUE && monkey2 != Long.MIN_VALUE) { monkey.output = when (monkey.operation) { '+' -> monkey1 + monkey2 '-' -> monkey1 - monkey2 '*' -> monkey1 * monkey2 '/' -> monkey1 / monkey2 else -> throw Exception() } changed = true } } } } val root = monkeyys.find { it.name == "root"}!! val root1 = monkeyys.find{ it.name == root.monkey1 }!!.output val root2 = monkeyys.find{ it.name == root.monkey2 }!!.output root.output = max(root1, root2) return recurseMonkeys(monkeyys, "root", root.output) } val input = readInput("Day21") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0ef7ac4f160f484106b19632cd87ee7594cf3d38
5,572
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/adventOfCode2023/Day03.kt
TetraTsunami
726,140,343
false
{"Kotlin": 80024}
package adventOfCode2023 import util.* @Suppress("unused") class Day03(input: String, context: RunContext = RunContext.PROD) : Day(input, context) { override fun solve() { var s1 = 0 var s2 = 0 for ((i, line) in lines.withIndex()) { val symbolsAbove = findSymbols(lines[maxOf(i - 1, 0)]) val symbolsBelow = findSymbols(lines[minOf(i + 1, lines.size - 1)]) val symbols = findSymbols(line) // if number is adjacent to a symbol, add to sum var j = 0 while (j < line.length) { val c = line[j] if (Character.isDigit(c) && (trueAround(j, symbolsAbove) || trueAround(j, symbolsBelow) || trueAround(j, symbols))) { val (res, upper) = restOfNumber(line, j) s1 += res j = upper } j++ } val gears = findGears(line) for (gear in gears) { val adjacent = mutableListOf<Int>() var lineNo = i - 1 while (lineNo <= i + 1) { var charIndex = gear - 1 while (charIndex <= gear + 1) { if (charIndex == gear && lineNo == i) { charIndex++ continue } if (charIndex < 0 || charIndex >= line.length || lineNo < 0 || lineNo >= lines.size) { charIndex++ continue } plt(lineNo, charIndex, line[lineNo], line[charIndex]) if (lines[lineNo][charIndex].isDigit()) { val (res, index) = restOfNumber(lines[lineNo], charIndex) adjacent.add(res) charIndex = index } charIndex++ } lineNo++ } if (adjacent.size == 2) { s2 += adjacent.reduce { acc, e -> acc * e } } } } a(s1, s2) } fun findSymbols(line: String): BooleanArray { return line.map { c -> !c.isDigit() && c != '.' }.toBooleanArray() } fun findGears(line: String): List<Int> { return line.mapIndexed { i, c -> if (c == '*') i else -1 }.filter { it != -1 } } fun trueAround(index: Int, bools: BooleanArray): Boolean { return bools[maxOf(index - 1, 0)] || bools[index] || bools[minOf(index + 1, bools.size - 1)] } fun restOfNumber(line: String, index: Int): Pair<Int, Int> { var lower = index var upper = index for (i in index downTo 0) { if (!Character.isDigit(line[i])) { break } lower = i } for (i in index until line.length) { if (!Character.isDigit(line[i])) { break } upper = i } return Pair(line.substring(lower, upper + 1).toInt(), upper + 1) } }
0
Kotlin
0
0
78d1b5d1c17122fed4f4e0a25fdacf1e62c17bfd
3,168
AdventOfCode2023
Apache License 2.0
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[372]超级次方.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//你的任务是计算 ab 对 1337 取模,a 是一个正整数,b 是一个非常大的正整数且会以数组形式给出。 // // // // 示例 1: // // //输入:a = 2, b = [3] //输出:8 // // // 示例 2: // // //输入:a = 2, b = [1,0] //输出:1024 // // // 示例 3: // // //输入:a = 1, b = [4,3,3,8,5,2] //输出:1 // // // 示例 4: // // //输入:a = 2147483647, b = [2,0,0] //输出:1198 // // // // // 提示: // // // 1 <= a <= 231 - 1 // 1 <= b.length <= 2000 // 0 <= b[i] <= 9 // b 不含前导 0 // // Related Topics 数学 分治 // 👍 194 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { var Mod = 1337 fun superPow(a: Int, b: IntArray): Int { return dfs(a,b,b.size-1) } private fun dfs(a: Int, b: IntArray, i: Int): Int { //递归结束条件 if (i == -1) return 1 //逻辑处理 进入下层循环 return pow(dfs(a,b,i-1),10) * pow(a,b[i])%Mod } fun pow(a: Int, b: Int): Int { var a = a var b = b var res = 1 a %= Mod while (b-- > 0) res = res * a % Mod return res } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,278
MyLeetCode
Apache License 2.0
src/aoc22/Day05_Simple.kt
mihassan
575,356,150
false
{"Kotlin": 123343}
@file:Suppress("PackageDirectoryMismatch") package aoc22.day05_simple import lib.Collections.headTail import lib.Solution import lib.Strings.ints import lib.Strings.words data class Step(val quantity: Int, val from: Int, val to: Int) data class Input(val cargo: List<ArrayDeque<Char>>, val procedure: List<Step>) typealias Output = List<ArrayDeque<Char>> private val solution = object : Solution<Input, Output>(2022, "Day05") { override fun parse(input: String): Input { val (cargoLines, procedureLines) = input.split("\n\n").map { it.lines() } val (stackIndexLine, stackLines) = cargoLines.reversed().headTail() val stackCount = checkNotNull(stackIndexLine).ints().max() val steps = procedureLines.map { line -> val (quantity, from, to) = line.words().mapNotNull(String::toIntOrNull) Step(quantity, from - 1, to - 1) } val cargo = List(stackCount) { ArrayDeque<Char>() } stackLines.forEach { line -> line.chunked(4).forEachIndexed { idx, ch -> ch[1].takeIf { it.isUpperCase() }?.let { cargo[idx].addLast(it) } } } return Input(cargo, steps) } override fun format(output: Output): String = output.joinToString("") { "${it.last()}" } override fun part1(input: Input): Output { val cargo = input.cargo.map { ArrayDeque(it) } input.procedure.forEach { (quantity, from, to) -> repeat(quantity) { val crate = cargo[from].removeLast() cargo[to].addLast(crate) } } return cargo } override fun part2(input: Input): Output { val cargo = input.cargo.map { ArrayDeque(it) } input.procedure.forEach { (quantity, from, to) -> val crates = cargo[from].takeLast(quantity) repeat(quantity) { cargo[from].removeLast() } cargo[to].addAll(crates) } return cargo } } fun main() = solution.run()
0
Kotlin
0
0
698316da8c38311366ee6990dd5b3e68b486b62d
1,870
aoc-kotlin
Apache License 2.0
src/aoc2022/Day06.kt
miknatr
576,275,740
false
{"Kotlin": 413403}
package aoc2022 fun main() { fun part1(input: List<String>) = input .filter { it != "" } .map { line -> var lastFour = line.substring(0..3) for (i in 4 until line.length) { if (lastFour.toList().distinct().size == 4) { return@map i } lastFour = lastFour.substring(1) lastFour += line[i] } } fun part2(input: List<String>) = input .filter { it != "" } .map { line -> var lastFour = line.substring(0..13) for (i in 14 until line.length) { if (lastFour.toList().distinct().size == 14) { return@map i } lastFour = lastFour.substring(1) lastFour += line[i] } } val testInput = readInput("Day06_test") part1(testInput).println() part2(testInput).println() val input = readInput("Day06") part1(input).println() part2(input).println() }
0
Kotlin
0
0
400038ce53ff46dc1ff72c92765ed4afdf860e52
1,053
aoc-in-kotlin
Apache License 2.0
src/main/kotlin/com/chriswk/aoc/advent2017/Day1.kt
chriswk
317,863,220
false
{"Kotlin": 481061}
package com.chriswk.aoc.advent2017 import com.chriswk.aoc.util.asInt object Day1 { fun partOne(str: String): Int { val sum = str.fold(Pair('a', 0)) { (lastChar, count), c -> when (lastChar) { c -> Pair(c, count + c.asInt()) else -> Pair(c, count) } }.second return if (str.first() == str.last()) { sum + str.last().asInt() } else { sum } } fun partTwo(str: String): Int { return str.toList().foldInHalf().filter { (first, second) -> first == second }.sumOf { (first, _) -> first.asInt() * 2 } } } fun <T> List<T>.foldInHalf(): List<Pair<T, T>> { val (first, second) = this.chunked(this.size / 2) return first.zip(second) }
116
Kotlin
0
0
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
823
adventofcode
MIT License
aoc-2017/src/main/kotlin/nl/jstege/adventofcode/aoc2017/days/Day25.kt
JStege1206
92,714,900
false
null
package nl.jstege.adventofcode.aoc2017.days import nl.jstege.adventofcode.aoccommon.days.Day import nl.jstege.adventofcode.aoccommon.utils.extensions.extractValue /** * * @author <NAME> */ class Day25 : Day(title = "The Halting Problem") { companion object Configuration { private val BEGIN_REGEX = """Begin in state ([A-Z]).""".toRegex() private val ITERATIONS_REGEX = """Perform a diagnostic checksum after ([0-9]+) steps.""".toRegex() private val STATE_INIT_REGEX = """In state ([A-Z]):""".toRegex() private val STATE_WRITE_REGEX = """- Write the value ([0-1]).""".toRegex() private val STATE_MOVE_REGEX = """- Move one slot to the (right|left).""".toRegex() private val STATE_NEXT_REGEX = """- Continue with state ([A-Z]).""".toRegex() } override fun first(input: Sequence<String>): Any { return input .map { it.trim() } .filter { it.isNotEmpty() } .toList() .parseAndCalculateChecksum() } override fun second(input: Sequence<String>): Any { return "-" } private fun List<String>.parseAndCalculateChecksum(): Int { val beginState = this[0].extractValue(BEGIN_REGEX, 1) val iterations = this[1].extractValue(ITERATIONS_REGEX, 1).toInt() val states = this .drop(2) //Drop the 2 starting lines: "Begin in state.." and "Perform a diagnostic..." .chunked(9) //Split input into groups of 9 lines, which indicate a state. .associateBy( { it[0].extractValue(STATE_INIT_REGEX, 1) }, { State( Instruction.parse(it.subList(2, 5)), Instruction.parse(it.subList(6, 9)) ) } ) return TuringMachine(states[beginState]!!, states) .apply { this.run(iterations) } .checksum } private data class Instruction( val value: Int, val direction: RelativeDirection, val next: String ) { companion object { fun parse(raw: List<String>) = Instruction( raw[0].extractValue(STATE_WRITE_REGEX, 1).toInt(), raw[1].extractValue(STATE_MOVE_REGEX, 1).toRelativeDirection(), raw[2].extractValue(STATE_NEXT_REGEX, 1) ) private fun String.toRelativeDirection() = RelativeDirection.valueOf(this.toUpperCase()) } enum class RelativeDirection(val transformTape: Tape.() -> Unit) { LEFT(Tape::moveLeft), RIGHT(Tape::moveRight) } } private data class State(val onZero: Instruction, val onOne: Instruction) { inline fun withValue(value: Int, action: Instruction.() -> Unit) = when (value) { 0 -> action(onZero) 1 -> action(onOne) else -> throw IllegalArgumentException("Illegal value") } } private class TuringMachine( var state: State, val states: Map<String, State> ) { private val tape = Tape() fun run(iterations: Int) = (0 until iterations).forEach { _ -> tick() } fun tick() = state.withValue(tape.currentValue) { tape.currentValue = this.value this.direction.transformTape(tape) state = states[this.next]!! } val checksum get() = tape.count { it == 1 } } private class Tape : Iterable<Int> { private var current = Node(value = 0) private var first = current private var last = current var currentValue: Int get() = current.value set(value) { current.value = value } fun moveLeft() { current = current.left ?: Node(right = current).apply { current.left = this first = this } } fun moveRight() { current = current.right ?: Node(left = current).apply { current.right = this last = this } } override fun iterator(): Iterator<Int> = object : Iterator<Int> { var iteratorValue: Node? = first override fun hasNext(): Boolean = iteratorValue != null override fun next(): Int = iteratorValue!!.value.also { iteratorValue = iteratorValue!!.right } } private data class Node( var value: Int = 0, var left: Node? = null, var right: Node? = null ) } }
0
Kotlin
0
0
d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025
4,691
AdventOfCode
MIT License
advent-of-code/src/main/kotlin/com/akikanellis/adventofcode/year2022/Day04.kt
akikanellis
600,872,090
false
{"Kotlin": 142932, "Just": 977}
package com.akikanellis.adventofcode.year2022 object Day04 { fun numberOfFullyOverlappingPairs(input: String) = firstToSecondSectionRange(input) .count { (firstSectionRange, secondSectionRange) -> firstSectionRange.containsFully(secondSectionRange) || secondSectionRange.containsFully(firstSectionRange) } fun numberOfPartiallyOverlappingPairs(input: String) = firstToSecondSectionRange(input) .count { (firstSectionRange, secondSectionRange) -> firstSectionRange.containsPartially(secondSectionRange) || secondSectionRange.containsPartially(firstSectionRange) } private fun firstToSecondSectionRange(input: String) = input .lines() .filter { it.isNotBlank() } .map { Pair(it.substringBefore(","), it.substringAfter(",")) } .map { (firstSectionRange, secondSectionRange) -> Pair( IntRange( firstSectionRange.substringBefore("-").toInt(), firstSectionRange.substringAfter("-").toInt() ), IntRange( secondSectionRange.substringBefore("-").toInt(), secondSectionRange.substringAfter("-").toInt() ) ) } private fun IntRange.containsFully(other: IntRange) = contains(other.first) && contains(other.last) private fun IntRange.containsPartially(other: IntRange) = contains(other.first) }
8
Kotlin
0
0
036cbcb79d4dac96df2e478938de862a20549dce
1,510
advent-of-code
MIT License
src/Day18.kt
underwindfall
573,471,357
false
{"Kotlin": 42718}
fun main() { val dayId = "18" val input = readInput("Day${dayId}") val cs = input.map { s -> s.split(",").map { it.toInt() }}.toHashSet() var ans = 0 val mins = List(3) { i -> cs.map { it[i] }.min() } val maxs = List(3) { i -> cs.map { it[i] }.max() } val v = HashMap<List<Int>, Boolean>() fun scan(c: List<Int>, vv: HashSet<List<Int>>): Boolean { v[c]?.let { return it } for (i in 0..2) { if (c[i] !in mins[i]..maxs[i]) return true } v[c] = false vv += c for (i in 0..2) for (jj in 0..1) { val j = jj * 2 - 1 val t = c.toMutableList() t[i] += j if (t in cs) continue if (scan(t, vv)) { return true } } return false } for (c in cs) { for (i in 0..2) for (jj in 0..1) { val j = jj * 2 - 1 val t = c.toMutableList() t[i] += j if (t !in cs) { val vv: HashSet<List<Int>> = HashSet() if (scan(t, vv)) { for (cc in vv) v[cc] = true ans++ } } } } println(ans) }
0
Kotlin
0
0
0e7caf00319ce99c6772add017c6dd3c933b96f0
1,231
aoc-2022
Apache License 2.0
AdventOfCode/Challenge2023Day05.kt
MartinWie
702,541,017
false
{"Kotlin": 90565}
import org.junit.Test import java.io.File import kotlin.test.assertEquals class Challenge2023Day05 { private fun solve1(lines: List<String>): Long { val seedsLine = lines.first() val seeds = seedsLine.split(":")[1].trim().split(" ").map { it.toLong() to 0 }.toMutableList() var currentMappingCounter = 0 val mappingLines = lines.subList(1, lines.lastIndex + 1) mappingLines.forEach { line -> when { // Lines that indicate the start of a new mapping line.contains(":") -> currentMappingCounter++ // Empty lines indicate that the mapping is over line.trim().isEmpty() -> { val tmpSeeds = mutableListOf<Pair<Long, Int>>() currentMappingCounter++ seeds.forEach { if (it.second < currentMappingCounter) { tmpSeeds.add(it.first to currentMappingCounter) } else { tmpSeeds.add(it) } } seeds.clear() seeds.addAll(tmpSeeds) } // Lines that contain the actual mapping else -> { val mappingsRaw = line.split(" ").map { it.toLong() } val targetStart = mappingsRaw.first() val sourceStart = mappingsRaw[1] val range = mappingsRaw.last() val tmpSeeds = mutableListOf<Pair<Long, Int>>() seeds.forEach { seed -> if ( seed.second < currentMappingCounter && (seed.first in sourceStart..<(sourceStart + range)) ) { val newValue = (seed.first - sourceStart) + targetStart tmpSeeds.add(newValue to currentMappingCounter) } else { tmpSeeds.add(seed) } } seeds.clear() seeds.addAll(tmpSeeds) } } } var currentLowestDistance = seeds.first().first seeds.forEach { if (it.first < currentLowestDistance) currentLowestDistance = it.first } return currentLowestDistance } @Test fun test() { val lines = File("./AdventOfCode/Data/Day05-1-Test-Data.txt").bufferedReader().readLines() val exampleSolution1 = solve1(lines) println("Example solution 1: $exampleSolution1") assertEquals(35, exampleSolution1) val realLines = File("./AdventOfCode/Data/Day05-1-Data.txt").bufferedReader().readLines() val solution1 = solve1(realLines) println("Solution 1: $solution1") assertEquals(107430936, solution1) val realLines2 = File("./AdventOfCode/Data/Day05-1-Data.txt").bufferedReader().readLines() val solution2 = solve2(realLines2) println("Solution 1: $solution2") assertEquals(107430936, solution2) } private fun solve2(lines: List<String>): Long { val seedsLine = lines.first() val seedsLineRaw = seedsLine.split(":")[1].trim().split(" ") val rawSeedStart = mutableListOf<String>() val rawSeedRange = mutableListOf<String>() seedsLineRaw.forEachIndexed { index, s -> if (index % 2 == 0) { rawSeedStart.add(s) } else { rawSeedRange.add(s) } } val seeds = mutableListOf<Pair<Long, Int>>() rawSeedRange.mapIndexed { index, s -> var seedRange = rawSeedRange[index].toInt() for (num in 0..<seedRange) { seeds.add((s.toInt() + num).toLong() to 0) } } var currentMappingCounter = 0 val mappingLines = lines.subList(1, lines.lastIndex + 1) mappingLines.forEach { line -> when { // Lines that indicate the start of a new mapping line.contains(":") -> currentMappingCounter++ // Empty lines indicate that the mapping is over line.trim().isEmpty() -> { val tmpSeeds = mutableListOf<Pair<Long, Int>>() currentMappingCounter++ seeds.forEach { if (it.second < currentMappingCounter) { tmpSeeds.add(it.first to currentMappingCounter) } else { tmpSeeds.add(it) } } seeds.clear() seeds.addAll(tmpSeeds) } // Lines that contain the actual mapping else -> { val mappingsRaw = line.split(" ").map { it.toLong() } val targetStart = mappingsRaw.first() val sourceStart = mappingsRaw[1] val range = mappingsRaw.last() val tmpSeeds = mutableListOf<Pair<Long, Int>>() seeds.forEach { seed -> if ( seed.second < currentMappingCounter && (seed.first in sourceStart..<(sourceStart + range)) ) { val newValue = (seed.first - sourceStart) + targetStart tmpSeeds.add(newValue to currentMappingCounter) } else { tmpSeeds.add(seed) } } seeds.clear() seeds.addAll(tmpSeeds) } } } var currentLowestDistance = seeds.first().first seeds.forEach { if (it.first < currentLowestDistance) currentLowestDistance = it.first } return currentLowestDistance } }
0
Kotlin
0
0
47cdda484fabd0add83848e6000c16d52ab68cb0
6,056
KotlinCodeJourney
MIT License
src/main/kotlin/g2101_2200/s2179_count_good_triplets_in_an_array/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2101_2200.s2179_count_good_triplets_in_an_array // #Hard #Array #Binary_Search #Ordered_Set #Divide_and_Conquer #Segment_Tree #Binary_Indexed_Tree // #Merge_Sort #2023_06_26_Time_563_ms_(100.00%)_Space_62.1_MB_(100.00%) @Suppress("NAME_SHADOWING") class Solution { fun goodTriplets(nums1: IntArray, nums2: IntArray): Long { val n = nums1.size val idx = IntArray(n) val arr = IntArray(n) for (i in 0 until n) { idx[nums2[i]] = i } for (i in 0 until n) { arr[i] = idx[nums1[i]] } val tree = Tree(n) var res = 0L for (i in 0 until n) { val smaller = tree.query(arr[i]) val bigger = n - (arr[i] + 1) - (i - smaller) res += smaller.toLong() * bigger tree.update(arr[i] + 1, 1) } return res } private class Tree(var n: Int) { var array: IntArray init { array = IntArray(n + 1) } fun lowbit(x: Int): Int { return x and -x } fun update(i: Int, delta: Int) { var i = i while (i <= n) { array[i] += delta i += lowbit(i) } } fun query(k: Int): Int { var k = k var ans = 0 while (k > 0) { ans += array[k] k -= lowbit(k) } return ans } } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,483
LeetCode-in-Kotlin
MIT License
src/main/kotlin/01-sep.kt
aladine
276,334,792
false
{"C++": 70308, "Kotlin": 53152, "Java": 10020, "Makefile": 511}
class Solution01Sep { private fun isValid(A: IntArray): Boolean { val hour = 10 * A[0] + A[1] val mins = 10 * A[2] + A[3] return hour < 24 && mins < 60 } fun largestTimeFromDigits(A: IntArray): String { // sort asc A.sort() if (!isValid(A)) return "" val lm = listOf( intArrayOf(A[3], A[2], A[1], A[0]), intArrayOf(A[3], A[2], A[0], A[1]), intArrayOf(A[3], A[1], A[2], A[0]), intArrayOf(A[3], A[1], A[0], A[2]), intArrayOf(A[3], A[0], A[2], A[1]), intArrayOf(A[3], A[0], A[1], A[2]), intArrayOf(A[2], A[3], A[1], A[0]), intArrayOf(A[2], A[3], A[0], A[1]), intArrayOf(A[2], A[1], A[3], A[0]), intArrayOf(A[2], A[1], A[0], A[3]), intArrayOf(A[2], A[0], A[3], A[1]), intArrayOf(A[2], A[0], A[1], A[3]), intArrayOf(A[1], A[3], A[2], A[0]), intArrayOf(A[1], A[3], A[0], A[2]), intArrayOf(A[1], A[2], A[3], A[0]), intArrayOf(A[1], A[2], A[0], A[3]), intArrayOf(A[1], A[0], A[3], A[2]), intArrayOf(A[1], A[0], A[2], A[3]), intArrayOf(A[0], A[3], A[2], A[1]), intArrayOf(A[0], A[3], A[1], A[2]), intArrayOf(A[0], A[2], A[3], A[1]), intArrayOf(A[0], A[2], A[1], A[3]), intArrayOf(A[0], A[1], A[3], A[2]), intArrayOf(A[0], A[1], A[2], A[3]) ) for (l in lm) { if (isValid(l)) return "${l[0]}${l[1]}:${l[2]}${l[3]}" } return "" } } /* class Solution { private int max_time = -1; public String largestTimeFromDigits(int[] A) { this.max_time = -1; permutate(A, 0); if (this.max_time == -1) return ""; else return String.format("%02d:%02d", max_time / 60, max_time % 60); } protected void permutate(int[] array, int start) { if (start == array.length) { this.build_time(array); return; } for (int i = start; i < array.length; ++i) { this.swap(array, i, start); this.permutate(array, start + 1); this.swap(array, i, start); } } protected void build_time(int[] perm) { int hour = perm[0] * 10 + perm[1]; int minute = perm[2] * 10 + perm[3]; if (hour < 24 && minute < 60) this.max_time = Math.max(this.max_time, hour * 60 + minute); } protected void swap(int[] array, int i, int j) { if (i != j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } } }*/
0
C++
1
1
54b7f625f6c4828a72629068d78204514937b2a9
2,738
awesome-leetcode
Apache License 2.0
src/main/kotlin/days/Day18.kt
jgrgt
433,952,606
false
{"Kotlin": 113705}
package days class Day18 : Day(18) { override fun runPartOne(lines: List<String>): Any { val numbers = lines.map { SnailFishNumber.parse(it) } return numbers.reduce { acc, n -> val new = acc.add(n) new.reduce() }.magnitude() } override fun runPartTwo(lines: List<String>): Any { val numbers = lines.map { SnailFishNumber.parse(it) } val pairs = generateAllPairs(numbers) return pairs.maxOf { (l, r) -> l.add(r).reduce().magnitude() } } fun generateAllPairs(numbers: List<SnailFishNumber>): Sequence<Pair<SnailFishNumber, SnailFishNumber>> { return sequence { numbers.forEachIndexed { i, left -> val others = numbers.drop(i + 1) others.forEach { right -> yield(left to right) yield(right to left) } } } } sealed class SnailFishNumber { companion object { fun parse(s: String): SnailFishNumber { val (n, leftOver) = when (s[0]) { '[' -> NumberPair.parse(s.substring(1)) else -> Leaf(s[0].digitToInt()) to s.substring(1) } check(leftOver.isEmpty()) { "Leftover string should be empty but was ${leftOver}" } return n } val EXPLODED = Leaf(0) } fun add(other: SnailFishNumber): SnailFishNumber { return NumberPair(this, other) } abstract fun findAndDoExplode(level: Int): ExplodeResult fun reduce(): SnailFishNumber { val result = findAndDoExplode(0) if (result.newNode != null) { return result.newNode.reduce() } val splitResult = split() return if (splitResult == this) { this } else { splitResult.reduce() } } abstract fun split(): SnailFishNumber abstract fun addLeft(other: Int?): SnailFishNumber abstract fun addRight(other: Int?): SnailFishNumber abstract fun magnitude(): Int } data class ExplodeResult(val leftCarryOver: Int?, val newNode: SnailFishNumber?, val rightCarryOver: Int?) data class NumberPair(val left: SnailFishNumber, val right: SnailFishNumber) : SnailFishNumber() { companion object { fun parse(s: String): Pair<SnailFishNumber, String> { val (left, leftOver) = when (s[0]) { '[' -> parse(s.substring(1)) else -> Leaf(s[0].digitToInt()) to s.substring(1) } check(leftOver[0] == ',') { "Expected a , at the beginning of $leftOver" } val (right, other) = when (leftOver[1]) { '[' -> parse(leftOver.substring(2)) else -> Leaf(leftOver[1].digitToInt()) to leftOver.substring(2) } return NumberPair(left, right) to other.substring(1) // skip ] } } override fun addLeft(other: Int?): SnailFishNumber { if (other == null) { return this } return NumberPair(left, right.addLeft(other)) } override fun addRight(other: Int?): SnailFishNumber { if (other == null) { return this } return NumberPair(left.addRight(other), right) } override fun magnitude(): Int { return 3 * left.magnitude() + 2 * right.magnitude() } override fun findAndDoExplode(level: Int): ExplodeResult { if (level == 4) { return explode() } val leftResult = left.findAndDoExplode(level + 1) if (leftResult.newNode != null) { return ExplodeResult( leftResult.leftCarryOver, NumberPair(leftResult.newNode, right.addRight(leftResult.rightCarryOver)), null ) } val rightResult = right.findAndDoExplode(level + 1) if (rightResult.newNode != null) { return ExplodeResult( null, NumberPair(left.addLeft(rightResult.leftCarryOver), rightResult.newNode), rightResult.rightCarryOver ) } return ExplodeResult(null, null, null) } override fun split(): SnailFishNumber { val leftResult = left.split() if (left != leftResult) { return NumberPair(leftResult, right) } val rightResult = right.split() if (right != rightResult) { return NumberPair(left, rightResult) } return this } private fun explode(): ExplodeResult { return ExplodeResult((left as Leaf).n, EXPLODED, (right as Leaf).n) } } data class Leaf(val n: Int) : SnailFishNumber() { companion object { } override fun addLeft(other: Int?): SnailFishNumber { if (other == null) { return this } return Leaf(n + other) } override fun addRight(other: Int?): SnailFishNumber { if (other == null) { return this } return Leaf(n + other) } override fun findAndDoExplode(level: Int): ExplodeResult { return ExplodeResult(null, null, null) } override fun split(): SnailFishNumber { if (n >= 10) { val left = n / 2 val right = n - left return NumberPair(Leaf(left), Leaf(right)) } return this } override fun magnitude(): Int { return n } } }
0
Kotlin
0
0
6231e2092314ece3f993d5acf862965ba67db44f
5,981
aoc2021
Creative Commons Zero v1.0 Universal
2022/src/main/kotlin/Day20.kt
dlew
498,498,097
false
{"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262}
import kotlin.math.abs object Day20 { fun part1(input: String): Long { val order = input.splitNewlines().mapIndexed { index, s -> Number(index, s.toLong()) } val file = order.toMutableList() mix(order, file) return groveCoordinates(file) } fun part2(input: String): Long { val order = input.splitNewlines().mapIndexed { index, s -> Number(index, s.toLong() * 811589153L) } val file = order.toMutableList() repeat(10) { mix(order, file) } return groveCoordinates(file) } private fun groveCoordinates(file: List<Number>): Long { val zero = file.indexOfFirst { it.value == 0L } return (1000..3000 step 1000).sumOf { file[(zero + it) % file.size].value } } private fun mix(order: List<Number>, file: MutableList<Number>) { val shiftSize = file.size - 1 // When we shift a number around, the file is a wee bit smaller for (number in order) { val position = file.indexOf(number) val shiftMultiplier = if (number.value >= 0) 0 else 1 + (abs(number.value) / shiftSize) val newPosition = (position + number.value + (shiftMultiplier * shiftSize)) % shiftSize file.removeAt(position) file.add(newPosition.toInt(), number) } } // Using this just to avoid duplicate numbers getting mixed up in the order private data class Number(val index: Int, val value: Long) }
0
Kotlin
0
0
6972f6e3addae03ec1090b64fa1dcecac3bc275c
1,361
advent-of-code
MIT License
src/Day01/Day01.kt
martin3398
436,014,815
false
{"Kotlin": 63436, "Python": 5921}
fun main() { fun part1(input: List<Int>): Int { var res = 0 var last = input[0] for (e in input) { if (e > last) res++ last = e } return res } fun part2(input: List<Int>): Int { var res = 0 for (i in 0 until input.size - 3) { if (input.slice(i until i + 3).sum() < input.slice(i + 1 until i + 4).sum()) res++ } return res } val testInput = readInput(1, true).map { it.toInt() } check(part1(testInput) == 7) check(part2(testInput) == 5) val input = readInput(1).map { it.toInt() } println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
085b1f2995e13233ade9cbde9cd506cafe64e1b5
709
advent-of-code-2021
Apache License 2.0
2021/src/day08/Day8KtTest.kt
scrubskip
160,313,272
false
{"Kotlin": 198319, "Python": 114888, "Dart": 86314}
package day08 import org.junit.jupiter.api.Assertions.* import kotlin.test.Test internal class Day8KtTest { @Test fun testParse() { val input = "be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | " + "fdgacbe cefdb cefbgd gcbe" val parsed = parseLine(input) assertEquals( listOf("be", "cfbegad", "cbdgef", "fgaecd", "cgeb", "fdcge", "agebfd", "fecdb", "fabcd", "edb"), parsed.first ) assertEquals(listOf("fdgacbe", "cefdb", "cefbgd", "gcbe"), parsed.second) } @Test fun testExample() { val input = listOf( "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 bagce" ) assertEquals(26, getUniqueSegments(input.map { parseLine(it) }.map { it.second }).size) var digitMap = analyzeInput("acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab".split(" ")) assertEquals(5353, parseOutput("cdfeb fcadb cdfeb cdbaf".split(" "), digitMap)) val outputSum = input.map { parseLine(it) }.sumOf { val digitMap = analyzeInput(it.first) println(parseOutput(it.second, digitMap)) parseOutput(it.second, digitMap) } assertEquals(61229, outputSum) } @Test fun testCharFind() { assertEquals(listOf('a'), findUniqueChars("abc", "bc")) assertEquals(listOf('d'), findUniqueChars("dab", "ab")) assertTrue(containsAll("abcd", "ab")) assertFalse(containsAll("acd", "ab")) } @Test fun testDigitMaker() { val segmentMap: Map<Int, Char> = buildMap { put(0, 'd') put(1, 'e') put(2, 'a') put(3, 'f') put(4, 'g') put(5, 'b') put(6, 'c') } val digitMap = makeDigitMapFromSegmentMap(segmentMap) assertEquals(sortString("abcdeg"), sortString("cagedb")) assertEquals(digitMap[sortString("cagedb")], 0) assertEquals(digitMap[sortString("ab")], 1) } @Test fun testSearch() { val input = "acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab".split(" ") val segmentMap = analyzeInput(input) } }
0
Kotlin
0
0
a5b7f69b43ad02b9356d19c15ce478866e6c38a1
3,129
adventofcode
Apache License 2.0
Yellowstone_sequence/Kotlin/src/main/kotlin/YellowstoneSequence.kt
ncoe
108,064,933
false
{"D": 425100, "Java": 399306, "Visual Basic .NET": 343987, "C++": 328611, "C#": 289790, "C": 216950, "Kotlin": 162468, "Modula-2": 148295, "Groovy": 146721, "Lua": 139015, "Ruby": 84703, "LLVM": 58530, "Python": 46744, "Scala": 43213, "F#": 21133, "Perl": 13407, "JavaScript": 6729, "CSS": 453, "HTML": 409}
fun main() { println("First 30 values in the yellowstone sequence:") println(yellowstoneSequence(30)) } private fun yellowstoneSequence(sequenceCount: Int): List<Int> { val yellowstoneList = mutableListOf(1, 2, 3) var num = 4 val notYellowstoneList = mutableListOf<Int>() var yellowSize = 3 while (yellowSize < sequenceCount) { var found = -1 for (index in notYellowstoneList.indices) { val test = notYellowstoneList[index] if (gcd(yellowstoneList[yellowSize - 2], test) > 1 && gcd( yellowstoneList[yellowSize - 1], test ) == 1 ) { found = index break } } if (found >= 0) { yellowstoneList.add(notYellowstoneList.removeAt(found)) yellowSize++ } else { while (true) { if (gcd(yellowstoneList[yellowSize - 2], num) > 1 && gcd( yellowstoneList[yellowSize - 1], num ) == 1 ) { yellowstoneList.add(num) yellowSize++ num++ break } notYellowstoneList.add(num) num++ } } } return yellowstoneList } private fun gcd(a: Int, b: Int): Int { return if (b == 0) { a } else gcd(b, a % b) }
0
D
0
4
c2a9f154a5ae77eea2b34bbe5e0cc2248333e421
1,445
rosetta
MIT License
app/src/main/kotlin/com/bloidonia/advent2020/Day_13.kt
timyates
317,965,519
false
null
package com.bloidonia.advent2020 import com.bloidonia.linesFromResource class Day_13(val now: Long, val busses: String) { companion object { // Lowest common multiple calculations (thanks to Google) fun gcd(x: Long, y: Long): Long = if (y == 0L) x else gcd(y, x % y) fun lcm(x: Long, y: Long): Long = x * (y / gcd(x, y)) fun lcm(input: List<Long>): Long = input.fold(1, this::lcm) } fun part1(): Long { val busNumbers = busses.split(",").filter { it != "x" }.map { it.toLong() } for (curr in now until now + busNumbers.maxOrNull()!!) { val find = busNumbers.find { curr.rem(it) == 0L } if (find != null) return (curr - now) * find } return -1; } fun part2(): Long { // Get list of bus pairs, where `first` is the bus line (time), and `second` is the offset due to the position // of the bus val busNumbers = busses.split(",") .mapIndexed { index, offset -> if (offset == "x") null else Pair(offset.toLong(), index) } .filterNotNull() val lowestCommonMultiple = lcm(busNumbers.map { it.first }) // Start at the offset of the first bus var timeStamp = busNumbers[0].first for (i in busNumbers.indices.drop(1)) { // we can jump the lcm of the busses up to here (means we keep the previous busses lined up) val jump = busNumbers.take(i).fold(1L) { acc, bus -> lcm(acc, bus.first) } // Find the point where the next bus lines up (don't forget the positional offset) timeStamp = (timeStamp..lowestCommonMultiple step jump) .first { (it + busNumbers[i].second) % busNumbers[i].first == 0L } } return timeStamp } } fun main() { linesFromResource("/13.txt").apply { println(Day_13(this[0].toLong(), this[1]).part1()) } linesFromResource("/13.txt").apply { println(Day_13(this[0].toLong(), this[1]).part2()) } }
0
Kotlin
0
0
cab3c65ac33ac61aab63a1081c31a16ac54e4fcd
2,016
advent-of-code-2020-kotlin
Apache License 2.0
src/main/resources/CucumberFeatureReport.kt
joshdur
120,290,788
false
null
package {OUTPUT_PACKAGE} private const val PASSED = "passed" private const val FAILED = "failed" private const val IGNORED = "ignored" private const val FEATURE = "Feature" private const val SCENARIO = "Scenario" private const val DEFAULT_LOCATION = "location" private const val DEFAULT_LINE = 0 private const val DEFAULT_DURATION = 100L fun defaultMatch() = Match(DEFAULT_LOCATION) data class CucumberFeatureReport(val description: String, val comment: List<Comment>, val id: String, val keyword: String = FEATURE, val name: String, val line: Int, val tags: List<Tag>, val uri: String, val elements: List<Element>) data class Comment(val value: String, val line: Int) data class Tag(val name: String, val line: Int) data class Element(val id: String, val keyword: String = SCENARIO, val type: String = SCENARIO.toLowerCase(), val name: String, val description: String, val line: Int, val before: List<Before>, val after: List<After>, val steps: List<Step> ) data class Before(val result: Result, val match: Match = defaultMatch()) data class After(val result: Result, val match: Match = defaultMatch()) data class Step(val name: String, val keyword: String?, val line: Int = DEFAULT_LINE, val result: Result, val match: Match = defaultMatch()) data class Result(val status: String, val duration: Long = DEFAULT_DURATION, val error_message: String? = null) data class Match(val location: String) fun transformToCucumberReport(featureReports: Collection<FeatureReport>): List<CucumberFeatureReport> { return featureReports.map { val elements = it.scenarioReports.map { mapElement(it, emptyList()) } mapFeatureReport(it, elements) } } private fun mapElement(scenario: ScenarioReport, steps: List<Step>): Element { return Element(id = scenario.scenarioName, name = scenario.scenarioName, description = scenario.scenarioName, after = listOf(After(result(scenario))), before = listOf(Before(Result(PASSED))), line = 0, steps = steps) } private fun mapFeatureReport(feature: FeatureReport, elements: List<Element>): CucumberFeatureReport { return CucumberFeatureReport(id = feature.featureName, description = feature.featureName, name = feature.featureName, uri = feature.featureName, elements = elements, line = 0, tags = emptyList(), comment = emptyList() ) } private fun result(scenario: ScenarioReport): Result { return when (scenario.testStatus) { ScenarioTestStatus.PASSED -> Result(PASSED) ScenarioTestStatus.ERROR -> Result(FAILED, error_message = scenario.throwable?.message ?: "No message") ScenarioTestStatus.IGNORED -> Result(IGNORED) } }
0
Kotlin
0
1
139edd1f0492dc880b448e00d63d193d19b2eda1
3,201
GherkPlugin
Apache License 2.0
src/main/kotlin/g0801_0900/s0862_shortest_subarray_with_sum_at_least_k/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0801_0900.s0862_shortest_subarray_with_sum_at_least_k // #Hard #Array #Binary_Search #Heap_Priority_Queue #Prefix_Sum #Sliding_Window #Queue // #Monotonic_Queue #2023_04_04_Time_563_ms_(84.62%)_Space_51.6_MB_(38.46%) import java.util.Deque import java.util.LinkedList class Solution { internal class Pair(var index: Int, var value: Long) fun shortestSubarray(nums: IntArray, k: Int): Int { val n = nums.size val dq: Deque<Pair> = LinkedList() var ans = Int.MAX_VALUE var sum: Long = 0 for (i in 0 until n) { sum += nums[i].toLong() // Keep dq in incrementing order while (dq.isNotEmpty() && sum <= dq.peekLast().value) dq.removeLast() // Add current sum and index dq.add(Pair(i, sum)) // Calculate your answer here if (sum >= k) ans = Math.min(ans, i + 1) // Check if Contraction is possible or not while (dq.isNotEmpty() && sum - dq.peekFirst().value >= k) { ans = ans.coerceAtMost(i - dq.peekFirst().index) dq.removeFirst() } } return if (ans == Int.MAX_VALUE) -1 else ans } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,213
LeetCode-in-Kotlin
MIT License
LeetCode/Easy/intersection-of-two-arrays/Solution.kt
GregoryHo
254,657,102
false
null
class Solution { fun intersection(nums1: IntArray, nums2: IntArray): IntArray { val answer = mutableListOf<Int>() val set1 = nums1.toHashSet().sortedWith(Comparator { o1, o2 -> when { o1 < o2 -> -1 o1 == o2 -> 0 else -> 1 } }) val set2 = nums2.toHashSet().sortedWith(Comparator { o1, o2 -> when { o1 < o2 -> -1 o1 == o2 -> 0 else -> 1 } }) var i = 0 var j = 0 while (i < set1.size && j < set2.size) { if (set1[i] == set2[j]) { answer.add(set1[i]) i++ j++ } else if (set1[i] < set2[j]) { i++ } else { j++ } } return answer.toTypedArray().toIntArray() } } fun main(args: Array<String>) { val solution = Solution() println(solution.intersection(intArrayOf(1, 2, 2, 1), intArrayOf(2, 2)).contentToString()) println(solution.intersection(intArrayOf(4, 9, 5), intArrayOf(9, 4, 9, 8, 4)).contentToString()) }
0
Kotlin
0
0
8f126ffdf75aa83a6d60689e0b6fcc966a173c70
994
coding-fun
MIT License
src/main/kotlin/day17/Day17.kt
cyril265
433,772,262
false
{"Kotlin": 39445, "Java": 4273}
package day17 private val target = Area(60..94, -171..-136) fun main() { var globalMax = 0 var velocitiesCount = 0 for (x in 0..100) { for (y in -200..200) { val maxY = findMaxY(Velocity(Point(x, y))) if (maxY != null) { if (maxY > globalMax) globalMax = maxY velocitiesCount++ } } } println("p1 $globalMax") println("p2 $velocitiesCount") } private fun findMaxY(velocity: Velocity): Int? { var position = Point(0, 0) var maxY = 0 for (step in 1..500) { position = position.move(velocity) if (position.y > maxY) maxY = position.y if (target.contains(position)) { return maxY } velocity.step() } return null } private data class Area(val x: IntRange, val y: IntRange) { fun contains(point: Point) = x.contains(point.x) && y.contains(point.y) } private data class Point(var x: Int, var y: Int) { fun move(velocity: Velocity) = Point(x + velocity.point.x, y + velocity.point.y) } private data class Velocity(val point: Point) { fun step() { val (x, y) = point this.point.x = when { x > 0 -> x - 1 x < 0 -> x + 1 else -> 0 } this.point.y = y - 1 } }
0
Kotlin
0
0
1ceda91b8ef57b45ce4ac61541f7bc9d2eb17f7b
1,326
aoc2021
Apache License 2.0
src/main/kotlin/g2901_3000/s2935_maximum_strong_pair_xor_ii/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2901_3000.s2935_maximum_strong_pair_xor_ii // #Hard #Array #Hash_Table #Bit_Manipulation #Sliding_Window #Trie // #2024_01_03_Time_748_ms_(84.38%)_Space_63.6_MB_(59.38%) import java.util.BitSet class Solution { private val map = IntArray(1 shl 20) fun maximumStrongPairXor(nums: IntArray): Int { nums.sort() val n = nums.size val max = nums[n - 1] var ans = 0 var mask: Int var masks = 0 var highBit = 20 while (--highBit >= 0) { if (((max shr highBit) and 1) == 1) { break } } val m = 1 shl highBit + 1 var seen = BitSet(m) for (i in highBit downTo 0) { mask = 1 shl i masks = masks or mask if (check(nums, masks, ans or mask, seen)) { ans = ans or mask } seen = BitSet(m) } return ans } private fun check(nums: IntArray, masks: Int, ans: Int, seen: BitSet): Boolean { for (x in nums) { val mask = x and masks if (seen[mask xor ans] && x <= 2 * map[mask xor ans]) { return true } seen.set(mask) map[mask] = x } return false } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,291
LeetCode-in-Kotlin
MIT License
src/main/kotlin/io/tree/ConvertSortedArrayIntoBinaryTreeSearch.kt
jffiorillo
138,075,067
false
{"Kotlin": 434399, "Java": 14529, "Shell": 465}
package io.tree import io.models.TreeNode import io.utils.runTests // https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ class ConvertSortedArrayIntoBinaryTreeSearch { fun execute( input: IntArray, leftBoundary: Int = 0, rightBoundary: Int = input.lastIndex): TreeNode? = when { input.isEmpty() -> null leftBoundary == rightBoundary -> TreeNode(input[leftBoundary]) leftBoundary + 1 == rightBoundary -> TreeNode(input[leftBoundary]).apply { this.right = TreeNode(input[rightBoundary]) } else -> (leftBoundary + (rightBoundary - leftBoundary) / 2).let { index -> TreeNode(input[index]).apply { left = execute(input, leftBoundary, index - 1) right = execute(input, index + 1, rightBoundary) } } } } fun main() { runTests(listOf( intArrayOf(-10, -3, 0, 5, 9) to TreeNode(0, TreeNode(-10, right = TreeNode(-3)), TreeNode(5, right = TreeNode(9))), intArrayOf(0, 1) to TreeNode(0, right = TreeNode(1)), intArrayOf(0, 1, 2) to TreeNode(1, TreeNode(0), TreeNode(2)), intArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8) to TreeNode(4, left = TreeNode(1, TreeNode(0), TreeNode(2, right = TreeNode(3))), right = TreeNode(6, TreeNode(5), TreeNode(7, right = TreeNode(8)))), intArrayOf(0, 1, 2, 3, 4, 5, 6, 7) to TreeNode(3, left = TreeNode(1, TreeNode(0), TreeNode(2)), right = TreeNode(5, TreeNode(4), TreeNode(6, right = TreeNode(7)))) )) { (input, value) -> value to ConvertSortedArrayIntoBinaryTreeSearch().execute(input) } }
0
Kotlin
0
0
f093c2c19cd76c85fab87605ae4a3ea157325d43
1,610
coding
MIT License
src/Day06.kt
jamesrobert
573,249,440
false
{"Kotlin": 13069}
fun main() { fun String.hasUniqueChars(): Boolean { for (i in indices) if (substring(i + 1).contains(this[i])) return false return true } fun String.indexAfterFirstNUnique(n: Int): Int { for (i in indices) if (substring(i, i + n).hasUniqueChars()) return i + n error("No unique sequence.") } fun part1(input: String): Int { return input.indexAfterFirstNUnique(4) } fun part2(input: String): Int { return input.indexAfterFirstNUnique(14) } // test if implementation meets criteria from the description, like: check(part1("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 7) check(part1("bvwbjplbgvbhsrlpgdmjqwftvncz") == 5) check(part1("nppdvjthqldpwncqszvftbrmjlhg") == 6) check(part1("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 10) check(part1("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 11) check(part2("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 19) check(part2("bvwbjplbgvbhsrlpgdmjqwftvncz") == 23) check(part2("nppdvjthqldpwncqszvftbrmjlhg") == 23) check(part2("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 29) check(part2("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 26) val input = readInput("Day06") println(part1(input.first())) println(part2(input.first())) }
0
Kotlin
0
0
d0b49770fc313ae42d802489ec757717033a8fda
1,295
advent-of-code-2022
Apache License 2.0
src/main/kotlin/day16_packet_decoder/PacketDecoder.kt
barneyb
425,532,798
false
{"Kotlin": 238776, "Shell": 3825, "Java": 567}
package day16_packet_decoder import util.CountingIterator import util.countingIterator /** * Binary things again! "One or more sub-packets" means recursion. Lots of * bookkeeping. But a simple question: find all the version numbers and sum. * Nailing the parsing is key, since the input data looks like an optimized wire * packet with its non-byte-aligned fields. "Make an int from these three bits." * Keeping track of your position in the stream is also needed, both number of * packets _and_ number of bits. * * It's super-simple IntCode, all in one day! Recurse through the packet, * interpreting the type IDs, just like any other expression evaluator. Like * the tiles for part two of Chiton Risk (#15), a good `Packet` interface makes * this a breeze. */ fun main() { util.solve(960, ::partOne) util.solve(12301926782560, ::partTwo) // 197445829014 is too low } interface Packet { val version: Int val type: Int val versionSum: Int fun evaluate(): Long } data class Literal( override val version: Int, override val type: Int, val value: Long ) : Packet { override val versionSum get() = version override fun evaluate() = value } data class Operator( override val version: Int, override val type: Int, val operands: List<Packet> ) : Packet { override val versionSum get() = version + operands.sumOf(Packet::versionSum) override fun evaluate(): Long = when (type) { 0 -> operands.sumOf(Packet::evaluate) 1 -> operands.map(Packet::evaluate).reduce(Long::times) 2 -> operands.minOf(Packet::evaluate) 3 -> operands.maxOf(Packet::evaluate) 5 -> { val (a, b) = operands.map(Packet::evaluate) if (a > b) 1 else 0 } 6 -> { val (a, b) = operands.map(Packet::evaluate) if (a < b) 1 else 0 } 7 -> { val (a, b) = operands.map(Packet::evaluate) if (a == b) 1 else 0 } else -> throw IllegalStateException("Unknown '$type' operator type") } } fun String.asHexBitSequence(): CountingIterator<Boolean> { val hexDigits = iterator() var buffer = 0 var bitIdx = -1 // sorta silly... return generateSequence { if (bitIdx < 0) { if (!hexDigits.hasNext()) return@generateSequence null bitIdx = 3 buffer = hexDigits.next().digitToInt(16) } buffer and (1 shl bitIdx--) != 0 }.countingIterator() } fun Iterator<Boolean>.readInt(bits: Int): Int = (0 until bits).fold(0) { incoming, _ -> (incoming shl 1) + if (next()) 1 else 0 } fun CountingIterator<Boolean>.readPacket(): Packet { val version = readInt(3) val typeId = readInt(3) if (typeId == 4) { return Literal(version, typeId, readLiteral()) } else if (next()) { // packet-length operator val len = readInt(11) return Operator( version, typeId, (0 until len).map { readPacket() }, ) } else { // bit-length operator val operands = mutableListOf<Packet>() val len = readInt(15) val end = count + len while (count < end) operands.add(readPacket()) return Operator(version, typeId, operands) } } private fun Iterator<Boolean>.readLiteral(): Long { var v = 0L do { val segment = readInt(5) v = (v shl 4) + (segment and 0b01111) } while (segment and 0b10000 > 1) return v } fun String.toPacket(): Packet = asHexBitSequence().readPacket() fun partOne(input: String) = input.toPacket().versionSum fun partTwo(input: String) = input.toPacket().evaluate()
0
Kotlin
0
0
a8d52412772750c5e7d2e2e018f3a82354e8b1c3
3,842
aoc-2021
MIT License
LeetCode/Kotlin/src/main/kotlin/org/redquark/tutorials/leetcode/FourSum.kt
ani03sha
297,402,125
false
null
package org.redquark.tutorials.leetcode import java.util.* import kotlin.collections.ArrayList fun fourSum(nums: IntArray, target: Int): List<List<Int>> { // Resultant list val quadruplets: MutableList<List<Int>> = ArrayList() // Base condition if (nums.size < 4) { return quadruplets } // Sort the array Arrays.sort(nums) // Length of the array val n = nums.size // Loop for each element in the array for (i in 0 until n - 3) { // Check for skipping duplicates if (i > 0 && nums[i] == nums[i - 1]) { continue } // Reducing problem to 3Sum problem for (j in i + 1 until n - 2) { // Check for skipping duplicates if (j != i + 1 && nums[j] == nums[j - 1]) { continue } // Left and right pointers var k = j + 1 var l = n - 1 // Reducing to two sum problem while (k < l) { val currentSum = nums[i] + nums[j] + nums[k] + nums[l] when { currentSum < target -> { k++ } currentSum > target -> { l-- } else -> { quadruplets.add(listOf(nums[i], nums[j], nums[k], nums[l])) k++ l-- // Check for skipping duplicates while (k < l && nums[k] == nums[k - 1]) { k++ } while (k < l && nums[l] == nums[l + 1]) { l-- } } } } } } return quadruplets } fun main() { println(fourSum(intArrayOf(1, 0, -1, 0, -2, 2), 0)) println(fourSum(intArrayOf(), 0)) println(fourSum(intArrayOf(1, 2, 3, 4), 10)) println(fourSum(intArrayOf(0, 0, 0, 0), 0)) }
2
Java
40
64
67b6ebaf56ec1878289f22a0324c28b077bcd59c
2,048
RedQuarkTutorials
MIT License
src/Day01.kt
k3vonk
573,555,443
false
{"Kotlin": 17347}
fun main() { fun part1(input: List<String>): Int { var highestCalories = 0 var currentCalories = 0 for (row in input) { if (row.isEmpty()) { if (currentCalories > highestCalories) highestCalories = currentCalories currentCalories = 0 continue } currentCalories += row.toInt() } return highestCalories } fun part2(input: List<String>): Int { val elfBaggage = mutableListOf<Int>() var currentCalories = 0 for (row in input) { if (row.isEmpty()) { elfBaggage.add(currentCalories) currentCalories = 0 continue } currentCalories += row.toInt() } elfBaggage.sort() return elfBaggage.takeLast(3).sum() } val input = readInput("Day01_test") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
68a42c5b8d67442524b40c0ce2e132898683da61
989
AOC-2022-in-Kotlin
Apache License 2.0
src/main/kotlin/Main.kt
snikiforov4
485,917,499
false
{"Kotlin": 9895}
package processor import java.text.DecimalFormat private val regexp = "\\s+".toRegex() var decimalFormat = DecimalFormat("#0.##") fun main() { while (true) { printMenu() print("Your choice: ") when (readln().toInt()) { 0 -> break 1 -> { val m1 = readMatrix("first") val m2 = readMatrix("second") if (isAdditionAllowed(m1, m2)) { printMatrix(addMatrices(m1, m2)) } else { println("The operation cannot be performed.") } } 2 -> { val m1 = readMatrix() print("Enter constant: ") val constant = readln().toDouble() printMatrix(multiplyMatrixByConstant(m1, constant)) } 3 -> { val m1 = readMatrix("first") val m2 = readMatrix("second") if (isMultiplicationAllowed(m1, m2)) { printMatrix(multiplyMatrices(m1, m2)) } else { println("The operation cannot be performed.") } } 4 -> { printTransposeMatrixMenu() print("Your choice: ") val strategy = TransposeStrategy.byNumber(readln().toInt()) val m = readMatrix() strategy.transpose(m) printMatrix(m) } 5 -> { val m = readMatrix() if (m.isSquare()) { println("The result is:") println(m.determinant()) } else { println("The operation cannot be performed.") } } 6 -> { val m = readMatrix() if (m.isSquare()) { val inverse = findMatrixInverse(m) if (inverse == null) { println("This matrix doesn't have an inverse.") } else { printMatrix(inverse) } } else { println("The operation cannot be performed.") } } else -> println("Wrong choice!") } } } private fun printMenu() { println("1. Add matrices") println("2. Multiply matrix by a constant") println("3. Multiply matrices") println("4. Transpose matrix") println("5. Calculate a determinant") println("6. Inverse matrix") println("0. Exit") } private fun readMatrix(matrixName: String = ""): Matrix { val matrixNamePlaceholder = if (matrixName.isNotBlank()) " " else "" + matrixName.trim() print("Enter size of$matrixNamePlaceholder matrix: ") val (n, m) = readln().split(regexp).map { it.toInt() } val result = Matrix.empty(n, m) println("Enter$matrixNamePlaceholder matrix:") repeat(n) { x -> val row = readln().split(regexp).map { it.toDouble() } check(row.size == m) row.forEachIndexed { y, e -> result[x, y] = e } } return result } private fun isAdditionAllowed(m1: Matrix, m2: Matrix) = m1.sizesOfDimensions.contentEquals(m2.sizesOfDimensions) private fun addMatrices(m1: Matrix, m2: Matrix): Matrix { val (n, m) = m1.sizesOfDimensions val result = Matrix.empty(n, m) repeat(n) { x -> repeat(m) { y -> result[x, y] = m1[x, y] + m2[x, y] } } return result } private fun multiplyMatrixByConstant(matrix: Matrix, c: Double): Matrix { val (n, m) = matrix.sizesOfDimensions val result = Matrix.empty(n, m) repeat(n) { x -> repeat(m) { y -> result[x, y] = matrix[x, y] * c } } return result } private fun isMultiplicationAllowed(m1: Matrix, m2: Matrix): Boolean { val (_, m1d2) = m1.sizesOfDimensions val (m2d1, _) = m2.sizesOfDimensions return m1d2 == m2d1 } private fun multiplyMatrices(m1: Matrix, m2: Matrix): Matrix { val (n, m) = m1.sizesOfDimensions val (_, k) = m2.sizesOfDimensions val result = Matrix.empty(n, k) repeat(n) { x -> repeat(k) { y -> val dotProduct = (0 until m).sumOf { idx -> m1[x, idx] * m2[idx, y] } result[x, y] = dotProduct } } return result } private fun printMatrix(matrix: Matrix) { val (n, m) = matrix.sizesOfDimensions println("The result is:") repeat(n) { x -> repeat(m) { y -> print("${decimalFormat.format(matrix[x, y])} ") } println() } } private fun printTransposeMatrixMenu() { println("1. Main diagonal") println("2. Side diagonal") println("3. Vertical line") println("4. Horizontal line") } fun findMatrixInverse(matrix: Matrix): Matrix? { val determinant = matrix.determinant() if (determinant == 0.0) { return null } val cofactorMatrix = matrix.toCofactorMatrix() MainDiagonalTransposeStrategy.transpose(cofactorMatrix) return multiplyMatrixByConstant(cofactorMatrix, 1.0 / determinant) }
0
Kotlin
0
0
ace36ad30c0a2024966744792a45e98b3358e10d
5,143
numeric-matrix-processor
Apache License 2.0
aoc_2023/src/main/kotlin/problems/day19/part1/PartsSorter.kt
Cavitedev
725,682,393
false
{"Kotlin": 228779}
package problems.day19.part1 class PartsSorter(lines: List<String>) { val workflows: Map<String, PartWorkflow> val parts: List<Part> init { val workflowLines = lines.takeWhile { it.isNotEmpty() } val workflowRegex = Regex("""(\w+)\{(.*)\}""") val innerWorkflowRegex = Regex("""(\w+)([<>])(\d+):(\w+)""") this.workflows = workflowLines.map { line -> val matches = workflowRegex.findAll(line).first().groupValues val key = matches[1] val content = matches[2] val workflowStepsStr = content.split(",") val workflowSteps = workflowStepsStr.map { val condMatches = innerWorkflowRegex.findAll(it).firstOrNull() if (condMatches == null) { WorkflowStep(it) } else { val groupValues = condMatches.groupValues WorkflowStepCondition( groupValues[1].toCharArray().first(), groupValues[2].toCharArray().first(), groupValues[3].toInt(), groupValues[4] ) } } return@map key to PartWorkflow(workflowSteps) }.toMap() val partsLines = lines.takeLastWhile { it.isNotEmpty() } val partsRegex = Regex("""=(\d+)""") this.parts = partsLines.map { line -> val values = line.split(",").map { partsRegex.find(it)!!.groupValues[1].toInt() } return@map Part(values[0], values[1], values[2], values[3]) } } fun totalRatingNumber(): Long { val acceptedParts = acceptedParts() return acceptedParts.fold(0L) { acc, part -> acc + part.totalAmount() } } fun acceptedParts(): List<Part> { return this.parts.filter { part -> var key = "in" while (key != "A" && key != "R") { key = workflows[key]!!.resultFromPart(part) } key == "A" } } }
0
Kotlin
0
1
aa7af2d5aa0eb30df4563c513956ed41f18791d5
2,087
advent-of-code-2023
MIT License
src/main/kotlin/abc/229-e.kt
kirimin
197,707,422
false
null
package abc import java.util.* fun main(args: Array<String>) { val sc = Scanner(System.`in`) val n = sc.nextInt() val m = sc.nextInt() val ab = (0 until m).map { sc.next().toInt() to sc.next().toInt() } println(problem229e(n, m, ab)) } fun problem229e(n: Int, m: Int, ab: List<Pair<Int, Int>>): String { class UnionFind(n: Int) { private val parent = IntArray(n) { -1 } fun root(x: Int): Int { if (parent[x] < 0) return x parent[x] = root(parent[x]) return parent[x] } fun isSameRoot(x: Int, y: Int) = root(x) == root(y) fun merge(x: Int, y: Int) { var xRoot = root(x) var yRoot = root(y) if (xRoot == yRoot) return if (parent[xRoot] > parent[yRoot]) { val tmp = xRoot xRoot = yRoot yRoot = tmp } parent[xRoot] += parent[yRoot] parent[yRoot] = xRoot } fun groupSize(x: Int) = -parent[root(x)] override fun toString(): String { return parent.toString() } } val graph = Array(n) { mutableListOf<Int>() } for (i in 0 until m) { val (a, b) = ab[i] graph[a - 1].add(b - 1) } val uf = UnionFind(n) val ans = mutableListOf<Int>() ans.add(0) var count = 0 for (i in n - 1 downTo 1) { count++ for (j in graph[i]) { if (!uf.isSameRoot(i, j)) { uf.merge(i, j) count-- } } ans.add(count) } return ans.reversed().joinToString("\n") }
0
Kotlin
1
5
23c9b35da486d98ab80cc56fad9adf609c41a446
1,656
AtCoderLog
The Unlicense
Shortest_Unsorted_Continuous_Subarray_v2.kt
xiekch
166,329,519
false
{"C++": 165148, "Java": 103273, "Kotlin": 97031, "Go": 40017, "Python": 22302, "TypeScript": 17514, "Swift": 6748, "Rust": 6579, "JavaScript": 4244, "Makefile": 349}
import java.util.* // https://leetcode.com/problems/shortest-unsorted-continuous-subarray/solution/#approach-4-using-stack // We need to determine the correct position of the minimum and the maximum element // in the unsorted subarray to determine the boundaries of the required unsorted subarray. class Solution { fun findUnsortedSubarray(nums: IntArray): Int { if (nums.isEmpty()) return 0 val st = Stack<Int>() var right = -1 var left = nums.size for (i in nums.indices) { while (!st.isEmpty() && nums[st.peek()] > nums[i]) { left = Math.min(left, st.pop()) } st.push(i) } // println("left " + left) st.clear() for (i in nums.size - 1 downTo 0) { while (!st.isEmpty() && nums[st.peek()] < nums[i]) { right = Math.max(right, st.pop()) } st.push(i) } // println("right " + right) return if (right - left + 1 > 0) right - left + 1 else 0 } } fun main(args: Array<String>) { val solution = Solution() val testset = arrayOf( intArrayOf(), intArrayOf(1), intArrayOf(1, 2), intArrayOf(2, 1), intArrayOf(2, 6, 4, 8, 10, 9, 15), intArrayOf(10, 8, 10, 9, 15, 7), intArrayOf(2, 1, 10, 0, 3) ); for (nums in testset) { println(solution.findUnsortedSubarray(nums)) } }
0
C++
0
0
eb5b6814e8ba0847f0b36aec9ab63bcf1bbbc134
1,467
leetcode
MIT License
src/aoc2022/Day03.kt
nguyen-anthony
572,781,123
false
null
package aoc2022 import utils.readInputAsList import utils.alphaToInt fun main() { fun part1(input : List<String>) : Int { var sum = 0 for(rucksack in input) { val first = rucksack.substring(0, rucksack.length / 2) val second = rucksack.substring(rucksack.length / 2) //just initializes character as a non-empty value var commonChar = 'a' for(char in first){ if(second.contains(char)){ commonChar = char } } sum += alphaToInt(commonChar)!! } return sum } fun part2(input : List<String>) : Int { var sum = 0 for(group in input.windowed(3,3)){ //just initializes character as a non-empty value var commonChar = 'a' for(char in group[0]){ if(group[1].contains(char) && group[2].contains(char)){ commonChar = char } } sum += alphaToInt(commonChar)!! } return sum } val input = readInputAsList("Day03", "2022") println(part1(input)) println(part2(input)) // test if implementation meets criteria from the description, like: val testInput = readInputAsList("Day03_test", "2022") check(part1(testInput) == 77) check(part2(testInput) == 16) }
0
Kotlin
0
0
9336088f904e92d801d95abeb53396a2ff01166f
1,397
AOC-2022-Kotlin
Apache License 2.0
src/main/kotlin/math/Vec3.kt
spookyGh0st
197,557,690
false
null
package math import kotlin.math.sqrt data class Vec3(var x: Double = 0.0, var y: Double = 0.0, var z: Double = 0.0){ constructor(x: Number, y: Number, z: Number): this(x.toDouble(), y.toDouble(), z.toDouble()) val length get() = sqrt(x * x + y * y + z * z) /** * Normalise the vector to length 1 */ fun normalize(){ val l = 1.0/ sqrt(x * x + y * y + z * z) x*=l; y*= l; z*=l } fun toVec2(): Vec2 { return Vec2(x,y) } operator fun plus(vec3: Vec3): Vec3 { return Vec3(x + vec3.x, y + vec3.y, z + vec3.z) } operator fun minus(vec3: Vec3): Vec3 { return Vec3(x - vec3.x, y - vec3.y, z - vec3.z) } operator fun times(fac: Double): Vec3 { return Vec3(x * fac, y * fac, z * fac) } operator fun times(fac: Int): Vec3 { return Vec3(x * fac, y * fac, z * fac) } operator fun div(fact: Double): Vec3 { val xfact = 1.0/ fact return Vec3(x * xfact, y * xfact, z * xfact) } operator fun div(fact: Int): Vec3 { val xfact = 1.0/ fact return Vec3(x * xfact, y * xfact, z * xfact) } operator fun get(index: Int) = when(index){ 0 -> x; 1 -> y; 2 -> z else -> throw IndexOutOfBoundsException() } operator fun times(mat3: Mat3): Vec3 = Vec3( x*mat3.x.x + y*mat3.y.x + z*mat3.z.x, x*mat3.x.y + y*mat3.y.y + z*mat3.z.y, x*mat3.x.z + y*mat3.y.z + z*mat3.z.z, ) fun toList(): List<Double> = listOf(x,y,z) operator fun times(vec3: Vec3): Vec3 { return Vec3( vec3.x * x, vec3.y * y, vec3.z * z, ) } fun toVec4(w: Double): Vec4 = Vec4(x,y,z,w) fun dot(v: Vec3): Double = x*v.x + y*v.y + z*v.z fun cross(b:Vec3): Vec3 { val v = Vec3() v.x = y * b.z - z * b.y v.y = z * b.x - x * b.z v.z = x * b.y - y * b.x return v } }
3
Kotlin
9
19
0ba55cb3d9abb3a9e57e8cef6c7eb0234c4f116a
2,011
beatwalls
MIT License
src/day3.kt
SerggioC
573,171,085
false
{"Kotlin": 8824}
fun main() { val input: List<String> = readInput("day3") var total = 0 input.forEach { val input2: List<String> = it.chunked(it.length / 2) val left = input2.get(0) val right = input2.get(1) val result: Char = left.first { right.contains(it) } println("common in $it: $result") total += totalFromChar(result) } println("total is $total") // part 2 total = 0 val groups: List<List<String>> = input.chunked(3) groups.forEach { group: List<String> -> val elf1 = group.get(0) val elf2 = group.get(1) val elf3 = group.get(2) val result = elf1.first { elf2.contains(it) && elf3.contains(it) } total += totalFromChar(result) } println("total part 2 is $total") } private fun totalFromChar(result: Char) = if (result.isLowerCase()) { result.code - 96 } else { (result.code - 64) + 26 }
0
Kotlin
0
0
d56fb119196e2617868c248ae48dcde315e5a0b3
962
aoc-2022
Apache License 2.0
src/commonMain/kotlin/ai/hypergraph/kaliningraph/CommonUtils.kt
breandan
245,074,037
false
{"Kotlin": 1482924, "Haskell": 744, "OCaml": 200}
package ai.hypergraph.kaliningraph import ai.hypergraph.kaliningraph.sampling.randomVector import ai.hypergraph.kaliningraph.tensor.* import ai.hypergraph.kaliningraph.types.* import kotlin.math.* import kotlin.random.* import kotlin.reflect.KClass fun <T, R : Ring<T>, M : Matrix<T, R, M>> Matrix<T, R, M>.elwise(op: (T) -> T): M = new(data = data.map { op(it) }) operator fun <T, R : Ring<T>, M : Matrix<T, R, M>> T.times(m: Matrix<T, R, M>): M = with(m.algebra) { m.elwise { this@times * it } } operator fun <T, R : Ring<T>, M : Matrix<T, R, M>> Matrix<T, R, M>.times(t: T): M = with(algebra) { elwise { it * t } } fun <T, R : Ring<T>, M : Matrix<T, R, M>> Matrix<T, R, M>.pow(i: Int): M = (0..i).fold(this) { a, _ -> a * this as M } as M fun DoubleMatrix.norm() = data.sumOf { it * it }.pow(0.5) fun DoubleMatrix.companionMatrix(): DoubleMatrix = if (numRows != 1) throw Exception("Companion matrix requires scalar coefficients") else DoubleMatrix(numCols) { r, c -> if (r + 1 == c) 1.0 else if (r == numCols - 1) -this[0, c] else 0.0 } fun DoubleMatrix.eigen(tolerance: Double = 0.00001): Π2<DoubleMatrix, Double> { val init = this * DoubleMatrix(numCols, 1, List(numCols) { 1.0 }) val eigVec = init.seekFixpoint( stop = { i, t, tt -> (t - tt).norm() < tolerance }, succ = { (this * it).let { it * (1.0 / it.norm()) } } ) val eigVal = ((this * eigVec) * eigVec.transpose)[0, 0] / (eigVec * eigVec.transpose)[0, 0] return eigVec to eigVal } infix fun <T, R : Ring<T>, M : Matrix<T, R, M>> List<T>.dot(m: Matrix<T, R, M>): List<T> = m.cols.map { col -> with(m.algebra) { zip(col).fold(nil) { c, (a, b) -> c + a * b } } } val ACT_TANH: (DoubleMatrix) -> DoubleMatrix = { it.elwise { tanh(it) } } val NORM_AVG: (DoubleMatrix) -> DoubleMatrix = { it.meanNorm() } fun DoubleMatrix.minMaxNorm() = data.fold(0.0 cc 0.0) { (a, b), e -> min(a, e) cc max(b, e) }.let { (min, max) -> elwise { e -> (e - min) / (max - min) } } fun DoubleMatrix.meanNorm() = data.fold(VT(0.0, 0.0, 0.0)) { (a, b, c), e -> VT(a + e / data.size.toDouble(), min(b, e), max(c, e)) }.let { (μ, min, max) -> elwise { e -> (e - μ) / (max - min) } } infix fun Int.choose(k: Int): Int { require(0 <= k && 0 <= this) { "Bad (k, n) = ($k, $this)!" } if (k > this || k < 0) return 0 if (k > this / 2) return this choose this - k var result = 1 for (i in 1..k) result = result * (this - i + 1) / i return result } tailrec fun fact(n: Int, t: Int = 1): Int = if (n == 1) t else fact(n - 1, t * n) fun DoubleMatrix.exp(max: Int = 10): DoubleMatrix = (1..max).fold(DoubleMatrix.one(numRows) to this) { (acc, an), i -> (acc + an * (1.0 / fact(i).toDouble())) to (an * this) }.first fun <T, Y> joinToScalar( m1: Matrix<T, *, *>, m2: Matrix<T, *, *>, filter: (Int, Int) -> Boolean = { _, _ -> true }, join: (T, T) -> Y, reduce: (Y, Y) -> Y ): Y = if (m1.shape() != m2.shape()) throw Exception("Shape mismatch: ${m1.shape()} != ${m2.shape()}") else m1.data.zip(m2.data) .filterIndexed { i, _ -> filter(i / m1.numCols, i % m1.numCols) } .map { (a, b) -> join(a, b) } .reduce { a, b -> reduce(a, b) } fun Array<DoubleArray>.toDoubleMatrix() = DoubleMatrix(size, this[0].size) { i, j -> this[i][j] } fun kroneckerDelta(i: Int, j: Int) = if (i == j) 1.0 else 0.0 const val DEFAULT_FEATURE_LEN = 20 fun String.vectorize(len: Int = DEFAULT_FEATURE_LEN) = Random(hashCode()).let { randomVector(len) { it.nextDouble() } } tailrec fun <T> closure( toVisit: Set<T> = emptySet(), visited: Set<T> = emptySet(), successors: Set<T>.() -> Set<T> ): Set<T> = if (toVisit.isEmpty()) visited else closure( toVisit = toVisit.successors() - visited, visited = visited + toVisit, successors = successors ) // Maybe we can hack reification using super type tokens? infix fun Any.isA(that: Any) = when { this !is KClass<out Any> && that !is KClass<out Any> -> this::class.isInstance(that) this !is KClass<out Any> && that is KClass<out Any> -> this::class.isInstance(that) this is KClass<out Any> && that is KClass<out Any> -> this.isInstance(that) this is KClass<out Any> && that !is KClass<out Any> -> this.isInstance(that) else -> TODO() } infix fun Collection<Any>.allAre(that: Any) = all { it isA that } infix fun Collection<Any>.anyAre(that: Any) = any { it isA that }
0
Kotlin
8
100
c755dc4858ed2c202c71e12b083ab0518d113714
4,389
galoisenne
Apache License 2.0
src/Day02.kt
ixtryl
575,312,836
false
null
import java.lang.IllegalArgumentException import java.lang.RuntimeException enum class TOKEN(val value: Int) { ROCK(1), SCISSORS(2), PAPER(3) } fun matchPoints(player: TOKEN, opponent: TOKEN): Int { when { player == TOKEN.ROCK && opponent == TOKEN.SCISSORS || player == TOKEN.PAPER && opponent == TOKEN.ROCK || player == TOKEN.SCISSORS && opponent == TOKEN.PAPER -> { print("WIN ") return 6 } player == opponent -> { print("DRAW ") return 3 } else -> { print("LOOSE ") return 0 } } } fun String.convertToToken(): TOKEN { return when (this) { "A", "X" -> TOKEN.ROCK "B", "Y" -> TOKEN.PAPER "C", "Z" -> TOKEN.SCISSORS else -> throw IllegalArgumentException("Bad input $this") } } fun getPoints(fileName: String): Int { val lines = readInput(fileName) var points = 0 for (line in lines) { val parts = line.split(" ") val opponent = parts[0].convertToToken() val player = parts[1].convertToToken() val currentMatchPoints = player.value + matchPoints(player, opponent) points += currentMatchPoints println("$line -> $opponent $player $currentMatchPoints $points") } println("File $fileName -> Points: $points") return points } fun main() { if (getPoints("Day02_test2") != (18 + 27)) { throw RuntimeException("Failed...") } if (getPoints("Day02_test") != 15) { throw RuntimeException("Failed...") } getPoints("Day02") }
0
Kotlin
0
0
78fa5f6f85bebe085a26333e3f4d0888e510689c
1,633
advent-of-code-kotlin-2022
Apache License 2.0
src/main/kotlin/co/csadev/advent2022/Day19.kt
gtcompscientist
577,439,489
false
{"Kotlin": 252918}
/** * Copyright (c) 2022 by <NAME> * Advent of Code 2022, Day 19 * Problem Description: http://adventofcode.com/2021/day/19 */ package co.csadev.advent2022 import co.csadev.adventOfCode.BaseDay import co.csadev.adventOfCode.Resources.resourceAsList import co.csadev.adventOfCode.product import kotlin.math.max class Day19(override val input: List<String> = resourceAsList("22day19.txt")) : BaseDay<List<String>, Int, Int> { data class Cost(val id: Int, val oO: Int, val cO: Int, val obO: Int, val obC: Int, val gO: Int, val gOb: Int) private val costs = input.map { it.replace(":", "").split(" ").mapNotNull { v -> v.toIntOrNull() } }.map { l -> Cost(l[0], l[1], l[2], l[3], l[4], l[5], l[6]) } private val maxLowend = costs.maxOf { max(it.oO, it.cO) } private val maxClay = costs.maxOf { it.obC } private val maxOb = costs.maxOf { it.gOb } override fun solvePart1(): Int { return costs.sumOf { it.runSim(24, 1, 0, 0, 0, 0, 0, 0, 0) * it.id } } override fun solvePart2(): Int { return costs.take(3).map { it.runSim(32, 1, 0, 0, 0, 0, 0, 0, 0) }.product() } @Suppress("LongParameterList") // 80% runtime reduction in using [Int]s over [List]s private fun Cost.runSim(time: Int, bOre: Int, bClay: Int, bOb: Int, bGeo: Int, rOre: Int, rClay: Int, rOb: Int, rGeo: Int): Int { val (nOre, nClay, nOb, nGeo) = listOf(rOre + bOre, rClay + bClay, rOb + bOb, rGeo + bGeo) val nextTime = time - 1 // Build as many Geode bots as you can return if (nextTime == 0) { nGeo } else if (rOre >= gO && rOb >= gOb) { runSim(nextTime, bOre, bClay, bOb, bGeo + 1, nOre - gO, nClay, nOb - gOb, nGeo) } else if (bOb < maxOb && rOre >= obO && rClay >= obC) { // Then build as many obsidian robots as you can runSim(nextTime, bOre, bClay, bOb + 1, bGeo, nOre - obO, nClay - obC, nOb, nGeo) } else { // Past here we need to see what makes sense to build of the 3 options val options = mutableListOf<Int>() // Option 1: Build nothing if (rOre < maxLowend) { options += runSim(nextTime, bOre, bClay, bOb, bGeo, nOre, nClay, nOb, nGeo) } // Option 2: Build an Ore robot if (bClay < maxClay && rOre >= oO) { options += runSim(nextTime, bOre + 1, bClay, bOb, bGeo, nOre - oO, nClay, nOb, nGeo) } // Option 3: Build a Clay robot if (rOre >= cO) { options += runSim(nextTime, bOre, bClay + 1, bOb, bGeo, nOre - cO, nClay, nOb, nGeo) } options.maxOf { it } } } }
0
Kotlin
0
1
43cbaac4e8b0a53e8aaae0f67dfc4395080e1383
2,747
advent-of-kotlin
Apache License 2.0
src/Day03.kt
calindumitru
574,154,951
false
{"Kotlin": 20625}
fun main() { val part1 = Implementation("Find the item type that appears in both compartments of each rucksack. What is the sum of the priorities of those item types?", 157) { lines -> val sum = lines.map { it.chunked(it.length / 2) } .map { twoChunks -> (twoChunks.get(0).toCharSet() to twoChunks.get(1).toCharSet()) } .map { (a, b) -> (a.intersect(b)) } .flatten().sumOf { calculatePriority(it) } return@Implementation sum } val part2 = Implementation("Find the item type that corresponds to the badges of each three-Elf group. What is the sum of the priorities of those item types?", 70) { lines -> val sum = lines.chunked(3) .map { it.get(0).toCharSet().intersect(it.get(1).toCharSet()).intersect(it.get(2).toCharSet()) } .flatten().sumOf { calculatePriority(it) } return@Implementation sum } OhHappyDay(3, part1, part2).checkResults() } fun calculatePriority(it: Char): Int { return if (it.isLowerCase()) { pos(it) } else { pos(it.lowercaseChar()) + 26 } } private fun pos(it: Char) = (it.code - 97 + 1) private fun String.toCharSet() = this.toCharArray().toSet()
0
Kotlin
0
0
d3cd7ff5badd1dca2fe4db293da33856832e7e83
1,228
advent-of-code-2022
Apache License 2.0
src/main/aoc2018/Day25.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2018 import kotlin.math.abs class Day25(input: List<String>) { data class Point(val coord: List<Int>) { fun distanceTo(other: Point): Int { return coord.zip(other.coord).sumOf { abs(it.first - it.second) } } } private val points = parseInput(input) private fun parseInput(input: List<String>): Set<Point> { val ret = mutableSetOf<Point>() input.forEach { line -> ret.add(Point(line.split(",").map { it.toInt() })) } return ret } private fun makeConstellations(points: Set<Point>): List<Set<Point>> { val constellations = mutableListOf<MutableSet<Point>>() points.forEach { point -> val partOf = constellations.filter {constellation -> constellation.map { it.distanceTo(point) }.any { it <= 3 } } when { partOf.isEmpty() -> constellations.add(mutableSetOf(point)) partOf.size == 1 -> partOf.first().add(point) else -> { constellations.removeAll(partOf.toSet()) constellations.add(partOf.flatten().toMutableSet().apply { add(point) }) } } } return constellations.toList() } fun solvePart1(): Int { return makeConstellations(points).size } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
1,373
aoc
MIT License
src/Day01.kt
acrab
573,191,416
false
{"Kotlin": 52968}
import com.google.common.truth.Truth.assertThat fun main() { fun part1(input: List<String>): Int { var max = 0 var current = 0 for (line in input) { if (line.isEmpty()) { if (current > max) { max = current } current = 0 } else { current += line.toInt() } } if (current > max) { max = current } return max } fun part2(input: List<String>): Int { val groups = mutableListOf<Int>() var current = 0 for (line in input) { if (line.isEmpty()) { groups.add(current) current = 0 } else { current += line.toInt() } } groups.add(current) return groups.sortedDescending().take(3).reduce { a, b -> a + b } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") assertThat(part1(testInput)).isEqualTo(24000) check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) assertThat(part2(testInput)).isEqualTo(45000) println(part2(input)) }
0
Kotlin
0
0
0be1409ceea72963f596e702327c5a875aca305c
1,280
aoc-2022
Apache License 2.0
src/main/kotlin/dev/dakoda/dvr/skills/Skills.kt
vanilla-refresh
707,433,202
false
{"Kotlin": 116265, "Java": 31150}
package dev.dakoda.dvr.skills import dev.dakoda.dvr.skills.exp.data.EXPGain class Skills( val values: MutableMap<Skill, EXP> = mutableMapOf() ) { fun increase(inc: Int, subSkill: Skill.Sub) = increase(inc, subSkill as Skill) fun increase(gain: EXPGain) = increase(gain.amount, gain.skill) fun increase(gain: Pair<Int, Skill.Sub>) = increase(gain.first, gain.second as Skill) private fun increase(inc: Int, skill: Skill) { if (skill is Skill.Category) return if (skill in values.keys) { val exp = values[skill] ?: return with(exp) { val i = (raw + inc) val l = this.level if (i >= EXP.perLevel) { val levels = i / EXP.perLevel val leftOver = i % EXP.perLevel values[skill] = ( values[skill]?.apply { raw = leftOver level = l + levels } ?: return ) // println("${skill.name} level was $beforeLevel, increased to ${values[skill]?.level} ") } else { values[skill] = ( values[skill]?.apply { raw = i } ?: return ) } } // println("${skill.name} EXP was $beforeEXP, increased to ${values[skill]?.raw}") } } fun levelOf(skill: Skill): Long { if (skill is Skill.Category) skill.updateRaw() return values[skill]?.level ?: 0L } private fun Skill.Category.updateRaw() { values[this]?.raw = this.subSkills.sumOf { values[it]?.raw ?: 0 } } operator fun get(skill: Skill) = progressOf(skill) fun progressOf(skill: Skill): EXP { if (skill is Skill.Category) skill.updateRaw() return values[skill] ?: EXP.NULL } fun categories(): List<EXP> = Skill.allCategories.mapNotNull { it.updateRaw() values[it] } fun subSkills(): List<EXP> = Skill.allSubSkills.mapNotNull { values[it] } fun subSkills(category: Skill.Category): List<EXP> = category.subSkills.mapNotNull { values[it] } fun all(): List<EXP> = categories() + subSkills() class EXP(val skill: Skill) { companion object { const val perLevel = 100 val NULL get() = EXP(Skill.NULL_CAT) } var raw: Long = 0 var level: Long = 1 } companion object { val BLANK: Skills get() { val values: MutableMap<Skill, EXP> = mutableMapOf() Skill.all.forEach { skill: Skill -> values[skill] = EXP(skill) } return Skills(values) } } }
0
Kotlin
0
0
89680960c244f892f7859ee5edfd5e7136860534
2,907
dvr-skills
MIT License
src/main/kotlin/com/manalili/advent/Day03.kt
maines-pet
162,116,190
false
null
package com.manalili.advent typealias Coordinates = Pair<Int, Int> class Day03(input: List<String>) { val claims = input.map { Claim.destructureClaim(it) } var singleClaimedSections: Set<Coordinates>? = null fun overlapSection(): Int{ val sections: MutableMap<Coordinates, Int> = mutableMapOf() claims.forEach { claim -> claim.area().forEach { sections[it] = sections.getOrDefault(it.first to it.second, 0) + 1} } singleClaimedSections = sections.filterValues { it == 1 }.keys return sections.count { it.value > 1 } } fun nonOverlapSection(): Int { if (singleClaimedSections == null) { overlapSection() } return claims.first { claim -> claim.area().all { singleClaimedSections?.contains(it)!! } }.id } } class Claim private constructor(val id: Int, val x: Int, val y: Int, val width: Int, val length: Int){ fun area(): List<Coordinates>{ val section = mutableListOf<Coordinates>() for (i in x until x + width) { for (j in y until y + length) { section.add(i to j) } } return section.toList() } companion object { //#1 @ 1,3: 4x4 fun destructureClaim(s: String): Claim { val (id, x, y, length, width) = Regex("""^#(\d+) @ (\d+),(\d+): (\d+)x(\d+)""").find(s)!!.destructured return Claim(id.toInt(), x.toInt(), y.toInt(), length.toInt(), width.toInt()) } } }
0
Kotlin
0
0
25a01e13b0e3374c4abb6d00cd9b8d7873ea6c25
1,553
adventOfCode2018
MIT License
src/main/kotlin/com/github/rloic/quadinsa5if/findindandqueryingtext/service/implementation/FaginSolverImp.kt
Quad-INSA-5IF
150,790,729
false
{"Java": 94105, "Kotlin": 33850, "Batchfile": 251, "Shell": 183}
package com.github.rloic.quadinsa5if.findindandqueryingtext.service.implementation import com.github.quadinsa5if.findingandqueryingtext.lang.Iter import com.github.quadinsa5if.findingandqueryingtext.model.Entry import com.github.quadinsa5if.findingandqueryingtext.model.vocabulary.Vocabulary import com.github.quadinsa5if.findingandqueryingtext.service.QuerySolver import java.util.* typealias Term = String typealias ArticleId = Int typealias Score = Float typealias ScoreMatrix = MutableMap<ArticleId, MutableMap<Term, Score>> class FaginSolverImp : QuerySolver { override fun answer(vocabulary: Vocabulary, terms: Array<String>, k: Int): Iter<Int> { val scoreSortEntries = mutableMapOf<Term, MutableList<Entry>>() val randomAccessEntries = mutableMapOf<Term, MutableMap<ArticleId, Entry>>() for (term in terms) { val sortedEntriesForTerm = vocabulary.getPostingList(term).toMutableList() val randomAccessEntriesForTerm = randomAccessEntries[term] ?: mutableMapOf() scoreSortEntries[term] = sortedEntriesForTerm for (entry in sortedEntriesForTerm) { randomAccessEntriesForTerm[entry.articleId] = entry } randomAccessEntries[term] = randomAccessEntriesForTerm } val entries: ScoreMatrix = mutableMapOf() while (countAllTerms(terms, entries) < k && !areAllEmpty(scoreSortEntries)) { for (entriesOfTerm in scoreSortEntries) { if (entriesOfTerm.value.isNotEmpty()) { val highestEntry = entriesOfTerm.value.removeAt(0) val scoresForArticle = entries.getOrPut(highestEntry.articleId) { mutableMapOf() } scoresForArticle[entriesOfTerm.key] = highestEntry.score } } } for ((articleId, articleScores) in entries) { if (!hasAllTerms(terms, articleScores)) { val unknownTerms = terms.filter { it !in articleScores.keys } for (term in unknownTerms) { articleScores[term] = randomAccessEntries[term]!![articleId]?.score ?: .0f } } } val firstArticles = entries .asSequence() .map { aggregate(it) } .sortedByDescending { it.second } .map { it.first } .toList() return object : Iter<Int> { var i = 0 override fun next(): Optional<Int> { return if (i < k && i < firstArticles.size) { val result = Optional.of(firstArticles[i]) i += 1 result } else { Optional.empty() } } } } private fun hasAllTerms(terms: Array<String>, entries: Map<String, Float>): Boolean { val keys = entries.keys return terms.all { it in keys } } private fun countAllTerms(terms: Array<String>, entriesMap: ScoreMatrix): Int { var count = 0 for (entries in entriesMap.values) { if (hasAllTerms(terms, entries)) { count += 1 } } return count } private fun areAllEmpty(entriesMap: Map<Term, List<Entry>>): Boolean { return entriesMap.values.all { it.isEmpty() } } fun aggregate(articleToScores: Map.Entry<ArticleId, Map<Term, Score>>): Pair<ArticleId, Score> { var score = 0f for (scoreEntry in articleToScores.value) { score += scoreEntry.value } return articleToScores.key to score } }
0
Java
1
0
4d2fd34e3e0637f041fbc4b1fbfc9c565a3100aa
3,678
finding-and-querying-text
MIT License
src/src/main/kotlin/sort/quicksort/QuickSort.kt
Akardian
406,427,845
false
{"Kotlin": 10155}
/** * This Class Implements the sorting algorithm Bubble Sort */ package sort.quicksort import sort.Sort abstract class QuickSort<T> : Sort<T> { constructor(_array: Array<T>) : super(_array){ } override fun sort() { quicksort(lowIndex = 0, highIndex = size - 1) } private fun quicksort(lowIndex: Int, highIndex: Int) { //Correct Order if(lowIndex >= highIndex || lowIndex < 0) { return } //Find the pivot index val partition = lomutoPartition(lowIndex, highIndex) //Sort left and right of the pivot quicksort(lowIndex = lowIndex, highIndex = partition - 1) quicksort(lowIndex = partition + 1, highIndex = highIndex) } private fun lomutoPartition(lowIndex: Int, highIndex: Int) : Int{ val pivot = array[highIndex] //Last element selected as pivot print("pivot = $pivot array = ") var newPivot = lowIndex - 1 //Temporary pivot Index for (index in lowIndex .. highIndex) { print(array[index]) } for (index in lowIndex until highIndex) { if(compare(array[index], pivot) <= 0) { newPivot++ //Move Index swap(newPivot, index) } } newPivot++ swap(newPivot, highIndex) print(" sorted = ") for (index in lowIndex .. highIndex) { print(array[index]) } println() return newPivot } } /* pivot := A[hi] // Choose the last element as the pivot // Temporary pivot index i := lo - 1 for j := lo to hi - 1 do // If the current element is less than or equal to the pivot if A[j] <= pivot then // Move the temporary pivot index forward i := i + 1 // Swap the current element with the element at the temporary pivot index swap A[i] with A[j] // Move the pivot element to the correct pivot position (between the smaller and larger elements) i := i + 1 swap A[i] with A[hi] */
0
Kotlin
0
0
b3557400236e904b8f443c5a43ed90d99a712d4c
1,976
Kotlin-Sorting
MIT License
src/Day03.kt
theofarris27
574,591,163
false
null
fun main() { fun part1(input: List<String>): Int { var sum = 0; for (line in input) { var half1 = line.substring(0, line.length / 2) var half2 = line.substring(line.length / 2) for (letters in half1) { if (half2.contains(letters)) { println("half1 $half1 half2 $half2 letters $letters") for (x in input) { var half1 = x.substring(0, x.length / 2) var half2 = x.substring(x.length / 2) for (letters in half1) { if (half2.contains(letters)) { var letter = letters when (letter) { 'a' -> sum += 1 'b' -> sum += 2 'c' -> sum += 3 'd' -> sum += 4 'e' -> sum += 5 'f' -> sum += 6 'g' -> sum += 7 'h' -> sum += 8 'i' -> sum += 9 'j' -> sum += 10 'k' -> sum += 11 'l' -> sum += 12 'm' -> sum += 13 'n' -> sum += 14 'o' -> sum += 15 'p' -> sum += 16 'q' -> sum += 17 'r' -> sum += 18 's' -> sum += 19 't' -> sum += 20 'u' -> sum += 21 'v' -> sum += 22 'w' -> sum += 23 'x' -> sum += 24 'y' -> sum += 25 'z' -> sum += 26 'A' -> sum += 27 'B' -> sum += 28 'C' -> sum += 29 'D' -> sum += 30 'E' -> sum += 31 'F' -> sum += 32 'G' -> sum += 33 'H' -> sum += 34 'I' -> sum += 35 'J' -> sum += 36 'K' -> sum += 37 'L' -> sum += 38 'M' -> sum += 39 'N' -> sum += 40 'O' -> sum += 41 'P' -> sum += 42 'Q' -> sum += 43 'R' -> sum += 44 'S' -> sum += 45 'T' -> sum += 46 'U' -> sum += 47 'V' -> sum += 48 'W' -> sum += 49 'X' -> sum += 50 'Y' -> sum += 51 'Z' -> sum += 52 } break } } } } } } return sum } fun part2(input: List<String>): Int { var sum = 0; var index = 0 for (i in 0..input.size - 3 step 3) { index = i for (letters in input[i]) { if (input[index + 1].contains(letters) && input[index + 2].contains(letters)) { println(letters) var letter = letters when (letter) { 'a' -> sum += 1 'b' -> sum += 2 'c' -> sum += 3 'd' -> sum += 4 'e' -> sum += 5 'f' -> sum += 6 'g' -> sum += 7 'h' -> sum += 8 'i' -> sum += 9 'j' -> sum += 10 'k' -> sum += 11 'l' -> sum += 12 'm' -> sum += 13 'n' -> sum += 14 'o' -> sum += 15 'p' -> sum += 16 'q' -> sum += 17 'r' -> sum += 18 's' -> sum += 19 't' -> sum += 20 'u' -> sum += 21 'v' -> sum += 22 'w' -> sum += 23 'x' -> sum += 24 'y' -> sum += 25 'z' -> sum += 26 'A' -> sum += 27 'B' -> sum += 28 'C' -> sum += 29 'D' -> sum += 30 'E' -> sum += 31 'F' -> sum += 32 'G' -> sum += 33 'H' -> sum += 34 'I' -> sum += 35 'J' -> sum += 36 'K' -> sum += 37 'L' -> sum += 38 'M' -> sum += 39 'N' -> sum += 40 'O' -> sum += 41 'P' -> sum += 42 'Q' -> sum += 43 'R' -> sum += 44 'S' -> sum += 45 'T' -> sum += 46 'U' -> sum += 47 'V' -> sum += 48 'W' -> sum += 49 'X' -> sum += 50 'Y' -> sum += 51 'Z' -> sum += 52 } break } } } return sum } val input = readInput("Rucksacks") println(part2(input)) }
0
Kotlin
0
0
cf77115471a7f1caeedf13ae7a5cdcbdcec3eab7
6,432
AdventOfCode
Apache License 2.0
src/main/kotlin/days/Day13.kt
hughjdavey
225,440,374
false
null
package days import common.IntcodeComputer import common.stackOf class Day13 : Day(13) { private fun program() = inputString.split(",").map { it.trim().toLong() }.toMutableList() override fun partOne(): Any { val arcadeCabinet = ArcadeCabinet(program()) return arcadeCabinet.runGame().count { it.tileType == TileType.BLOCK } } // todo perhaps refactor as takes ~1.9s to run override fun partTwo(): Any { val program = program() program[0] = 2L val arcadeCabinet = ArcadeCabinet(program) return arcadeCabinet.runGameWithJoystick() } enum class TileType { EMPTY, WALL, BLOCK, PADDLE, BALL, SCORE } data class GameTile(val x: Long, val y: Long, val tileId: Long) { val tileType = when (tileId) { 0L -> TileType.EMPTY 1L -> TileType.WALL 2L -> TileType.BLOCK 3L -> TileType.PADDLE 4L -> TileType.BALL else -> { if (!isScoreTile()) { throw IllegalArgumentException("Unknown Tile $tileId") } TileType.SCORE } } private fun isScoreTile() = x == -1L && y == 0L } class ArcadeCabinet(program: MutableList<Long>) { private val computer = IntcodeComputer(program) fun runGame(): List<GameTile> { val output = computer.runWithIO(stackOf()) return toTiles(output) } fun runGameWithJoystick(): Long { var tiles = toTiles(computer.runWithIO(stackOf())) while (!computer.halted) { val ball = tiles.findLast { it.tileType == TileType.BALL }!! val paddle = tiles.findLast { it.tileType == TileType.PADDLE }!! val joystickInput = when { ball.x > paddle.x -> 1L ball.x < paddle.x -> -1L else -> 0L } tiles = toTiles(computer.runWithIO(joystickInput)) } return tiles.findLast { it.tileType == TileType.SCORE }!!.tileId } companion object { fun toTiles(output: List<Long>) = output.chunked(3).map { GameTile(it[0], it[1], it[2]) } } } }
0
Kotlin
0
1
84db818b023668c2bf701cebe7c07f30bc08def0
2,279
aoc-2019
Creative Commons Zero v1.0 Universal
15.kts
pin2t
725,922,444
false
{"Kotlin": 48856, "Go": 48364, "Shell": 54}
val steps = System.`in`.bufferedReader().readLine().split(',') fun hash(s: String): Int { var result = 0 for (c in s) { result += c.code; result *= 17; result %= 256 } return result } val boxes = ArrayList<ArrayList<Pair<String, Int>>>() for (i in 0..255) boxes.add(ArrayList()) for (step in steps) { if (step.contains('=')) { val lens = Pair(step.split('=')[0], step.split('=')[1].toInt()) val i = hash(lens.first) if (boxes[i].any { it.first == lens.first }) { boxes[i][boxes[i].indexOfFirst { it.first == lens.first }] = lens } else { boxes[i].add(lens) } } else if (step.endsWith('-')) { val label = step.split('-')[0] boxes[hash(label)].removeIf { it.first == label } } } var total = 0 boxes.forEachIndexed { i, lenses -> lenses.forEachIndexed { j, lens -> total += (i + 1) * (j + 1) * lens.second } } println(listOf(steps.sumOf { hash(it) }, total))
0
Kotlin
1
0
7575ab03cdadcd581acabd0b603a6f999119bbb6
960
aoc2023
MIT License
common/number/src/main/kotlin/com/curtislb/adventofcode/common/number/Primes.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
package com.curtislb.adventofcode.common.number /** * Finds the unique prime factorization of the natural number [n]. * * Returns a map from each prime factor of [n] to that factor's corresponding power in the prime * factorization of [n]. If [n] is 1, this function instead returns an empty map. * * @throws IllegalArgumentException If the number is negative or 0. */ fun primeFactorization(n: Long): Map<Long, Int> { require(n > 0L) { "Number must be positive: $n" } // The number 1 has no prime factors if (n == 1L) { return emptyMap() } // Search for prime factors up to min(sqrt(Long.MAX_VALUE), sqrt(remainder)) var factor = 2L var remainder = n val factorization = mutableMapOf<Long, Int>() while (factor <= 3037000499L && factor * factor <= remainder) { // Find this factor's power by dividing n var power = 0 while (remainder % factor == 0L) { remainder /= factor power++ } // Record this factor's power and continue if (power > 0) { factorization[factor] = power } // All factors above 2 must be odd if (factor == 2L) { factor = 3L } else { factor += 2L } } // A remainder greater than 1 must be prime if (remainder > 1L) { factorization[remainder] = 1 } return factorization }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
1,422
AdventOfCode
MIT License
src/day01/Day01.kt
Volifter
572,720,551
false
{"Kotlin": 65483}
package day01 import utils.* fun getElvesCalories(input: List<String>): List<Int> = (input + listOf("")).fold(Pair(listOf<Int>(), 0)) { (cals, n), line -> if (line.isEmpty()) Pair(cals + listOf(n), 0) else Pair(cals, n + line.toInt()) }.first fun part1(input: List<String>): Int = getElvesCalories(input).maxOf { it } fun part2(input: List<String>): Int = getElvesCalories(input).sortedDescending().take(3).sum() fun main() { val testInput = readInput("Day01_test") expect(part1(testInput), 24000) expect(part2(testInput), 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
c2c386844c09087c3eac4b66ee675d0a95bc8ccc
689
AOC-2022-Kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/ContainsDuplicate.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 dev.shtanko.algorithms.OCTAL import kotlin.experimental.and import kotlin.experimental.or /** * Given an array of integers, find if the array contains any duplicates. * @see <a href="https://leetcode.com/problems/contains-duplicate/">Source</a> */ fun interface ContainsDuplicateStrategy { operator fun invoke(arr: IntArray): Boolean } /** * Approach #1 (Naive Linear Search) [Time Limit Exceeded] * Time complexity: O(n^2). * Space complexity: O(1). */ class IsContainsDuplicateBrutForce : ContainsDuplicateStrategy { override operator fun invoke(arr: IntArray): Boolean { for (i in arr.indices) { for (j in i + 1 until arr.size) { if (arr[i] == arr[j]) return true } } return false } } /** * Time complexity: O(n log n). * Space complexity: O(1) - not counting the memory used by sort */ class IsContainsDuplicateSort : ContainsDuplicateStrategy { override operator fun invoke(arr: IntArray): Boolean { arr.sort() for (i in 0 until arr.size - 1) { if (arr[i] == arr[i + 1]) return true } return false } } /** * Time complexity: O(n). * Space complexity: O(n). */ class IsContainsDuplicateSortSetSize : ContainsDuplicateStrategy { override operator fun invoke(arr: IntArray): Boolean { return arr.toHashSet().size < arr.size } } /** * Time complexity: O(n). * Space complexity: O(n). */ class IsContainsDuplicateSortSet : ContainsDuplicateStrategy { override operator fun invoke(arr: IntArray): Boolean { val set = hashSetOf<Int>() for (i in arr.indices) { if (set.contains(arr[i])) return true set.add(arr[i]) } return false } } class IsContainsDuplicateSortSetOptimized : ContainsDuplicateStrategy { override operator fun invoke(arr: IntArray): Boolean { val set = hashSetOf<Int>() for (i in arr.indices) { if (!set.add(arr[i])) return true } return false } } class IsContainsDuplicateBitManipulation : ContainsDuplicateStrategy { override operator fun invoke(arr: IntArray): Boolean { val mark = ByteArray(ARR_SIZE) for (i in arr) { val j = i / OCTAL val k = i % OCTAL val check = 1 shl k if (mark[j] and check.toByte() != 0.toByte()) { return true } mark[j] = mark[j] or check.toByte() } return false } companion object { private const val ARR_SIZE = 150000 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,248
kotlab
Apache License 2.0
src/main/kotlin/ru/itmo/ctlab/gmwcs/solver/preprocessing/Dijkstra.kt
ctlab
290,164,889
false
{"Java": 250115, "Kotlin": 21543}
package ru.itmo.ctlab.gmwcs.solver.preprocessing import ru.itmo.ctlab.virgo.gmwcs.graph.Edge import ru.itmo.ctlab.virgo.gmwcs.graph.Elem import ru.itmo.ctlab.virgo.gmwcs.graph.Node import ru.itmo.ctlab.virgo.gmwcs.graph.Graph import java.util.* import kotlin.math.abs /** * Created by <NAME> on 04/10/2017. */ class Dijkstra(private val graph: Graph, private val from: Node) { private val s = from.num private val n = graph.vertexSet().maxBy { it.num }!!.num + 1 private val visited = BooleanArray(n) { false } private var d = DoubleArray(n) { Double.MAX_VALUE } private fun solve(neighbors: Set<Node>) { if (d[s] != Double.MAX_VALUE) return val queue = PriorityQueue<Node> { n1, n2 -> (d[n1.num] - d[n2.num]).compareTo(0) } d[s] = 0.0 queue.add(from) while (queue.isNotEmpty()) { val cur = queue.poll() if (visited[cur.num]) continue visited[cur.num] = true // Stop searching if shortest paths are found if (neighbors.contains(cur) && neighbors.all { visited[it.num] }) break for (adj in graph.neighborListOf(cur).filter { !visited[it.num] }) { // 0 for positive, -weight for negative val e = graph.getEdge(cur, adj) val ew = p(e, adj) val w = d[cur.num] + ew if (d[adj.num] > w) { d[adj.num] = w queue.add(adj) } } } } fun negativeDistances(neighbors: NodeSet): Map<Node, Double> = distances(neighbors).mapValues { -it.value } private fun distances(neighbors: Set<Node>): Map<Node, Double> { solve(neighbors) return neighbors.associateWith { d[it.num] + p(from) } } fun negativeEdges(neighbors: Set<Node>): List<Edge> { solve(neighbors) return graph.edgesOf(from).filter { val end = graph.opposite(from, it) it.weight < 0 && !almostEquals(d[end.num] - p(it), p(end)) // it.weight <= 0 && d[end] < -it.weight } } fun negativeVertex(dest: Node, candidate: Node): Boolean { solve(setOf(dest)) // test is passed if candidate for removal is not in the solution val candPathW = p(graph.getEdge(from, candidate), graph.getEdge(candidate, dest), candidate) return !almostEquals(d[dest.num] - p(dest), candPathW) } private fun almostEquals(a: Double, b: Double): Boolean { return abs(a - b) < 1e-10 } private fun p(vararg e: Elem): Double { return -e.sumByDouble { minOf(it.weight, 0.0) } } }
0
Java
0
3
f561bdce02f43b7c58cd5334896c2aec513bda15
2,750
virgo-solver
Apache License 2.0
src/Day23.kt
ech0matrix
572,692,409
false
{"Kotlin": 116274}
fun main() { fun print(elves: Set<Coordinates>) { // for(row in elves.minOf { it.row } .. elves.maxOf { it.row }) { // for(col in elves.minOf { it.col } .. elves.maxOf { it.col }) { for(row in -2 .. 9) { for(col in -3 .. 10) { if (elves.contains(Coordinates(row,col))) { print('#') } else { print('.') } } println() } println() } fun parse(input: List<String>): MutableSet<Coordinates> { val elves = mutableSetOf<Coordinates>() for(row in 0 until input.size) { for(col in 0 until input[row].length) { if (input[row][col] == '#') { elves.add(Coordinates(row,col)) } } } return elves } val standingChecks = listOf( Coordinates(-1,-1),Coordinates(-1,0),Coordinates(-1,1), Coordinates(0,-1), Coordinates(0,1), Coordinates(1,-1), Coordinates(1,0), Coordinates(1,1) ) val walkingChecks = listOf( listOf(Coordinates(-1,-1),Coordinates(-1,0),Coordinates(-1,1)),// North listOf(Coordinates(1,-1), Coordinates(1,0), Coordinates(1,1)), // South listOf(Coordinates(-1,-1),Coordinates(0,-1),Coordinates(1,-1)),// West listOf(Coordinates(-1,1),Coordinates(0,1),Coordinates(1,1)) // East ) val walkDirectionIndex = 1 fun move(elves: MutableSet<Coordinates>, walkingCheckIndex: Int): Boolean { val totalElves = elves.size var didMove = false // Key = proposed positions // Value = previous positions val proposals = mutableMapOf<Coordinates, MutableSet<Coordinates>>() fun addProposal(proposal: Coordinates, elf: Coordinates) { val p = proposals[proposal] if (p == null) { proposals[proposal] = mutableSetOf(elf) } else { p.add(elf) } } for(elf in elves) { if(standingChecks.map { elf.add(it) }.intersect(elves).isEmpty()) { // Don't walk addProposal(elf, elf) } else { var hasProposed = false for(i in walkingCheckIndex until walkingCheckIndex+4) { val checkIndex = i%4 if(walkingChecks[checkIndex].map { elf.add(it) }.intersect(elves).isEmpty()) { addProposal(walkingChecks[checkIndex][walkDirectionIndex].add(elf), elf) hasProposed = true break } } if(!hasProposed) { addProposal(elf,elf) } } } elves.clear() for((proposal, previous) in proposals) { if (previous.size == 1) { elves.add(proposal) if(proposal != previous.first()) { didMove = true } } else { elves.addAll(previous) } } //print(elves) check(totalElves == elves.size) return didMove } fun part1(input: List<String>): Int { val elves = parse(input) var walkingCheckIndex = 0 //print(elves) repeat(10) { move(elves, walkingCheckIndex) walkingCheckIndex++ } val minCol = elves.minOf { it.col } val maxCol = elves.maxOf { it.col } val minRow = elves.minOf { it.row } val maxRow = elves.maxOf { it.row } val area = (maxCol - minCol + 1) * (maxRow - minRow + 1) // println("Rows: $minRow -> $maxRow") // println("Cols: $minCol -> $maxCol") return area - elves.size } fun part2(input: List<String>): Int { val elves = parse(input) var walkingCheckIndex = 0 while(move(elves, walkingCheckIndex)) { walkingCheckIndex++ } return walkingCheckIndex+1 } // fun part2(input: List<String>): Int { // return input.size // } val testInput = readInput("Day23_test") check(part1(testInput) == 110) check(part2(testInput) == 20) val input = readInput("Day23") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
50885e12813002be09fb6186ecdaa3cc83b6a5ea
4,410
aoc2022
Apache License 2.0
quantum/src/main/kotlin/me/khol/quantum/gate/PermutationGates.kt
Antimonit
210,850,479
false
null
package me.khol.quantum.gate import me.khol.quantum.util.WeakCache import me.khol.quantum.math.Complex import me.khol.quantum.math.Matrix typealias Permutation = List<Int> /** * Reorders input and output qubits of [this] gate. * * This is most useful when we need to use some kind of a controlled gate where the control and * target qubits are in a different order than the original gate is expecting them. * * For example, a [GateCCNot] expects the first two qubits to be control qubits (C0, C1) and the * last qubit to be target (T) qubit (C0 C1 T). Calling `GateCCNot.withOrder(0, 2, 1)` will return * a Gate whose target qubit sits in between the control qubits (C0 T C1). */ fun Gate.withOrder(vararg qubitOrder: Int) = withOrder(qubitOrder.toList()) fun Gate.withOrder(qubitOrder: Permutation): Gate { val permutationGate = permutationGate(*qubitOrder.toIntArray()) return permutationGate.adjoint * this * permutationGate } private val permutationsCache: WeakCache<Permutation, Gate> = WeakCache() /** * Generates a Gate with permutation matrix that reorders input qubits. * * PermutationGate is technically not a valid Gate because it is not always reversible. Shouldn't * be used for anything other than reordering input qubits of a Gate. */ fun permutationGate(vararg order: Int) = permutationGate(order.toList()) fun permutationGate(order: Permutation): Gate { return permutationsCache.getOrPut(order) { PermutationGate(order) } } private class PermutationGate(order: Permutation) : Gate() { override val qubits = order.size override val matrix: Matrix = run { val permutation = permutationVector(order) Matrix(permutation.map { permutedIndex -> List(permutation.size) { if (it == permutedIndex) Complex.ONE else Complex.ZERO } }) } }
0
Kotlin
1
12
97975ba74728ee7a71f96d12a80282ed38890148
1,828
Quantum
Apache License 2.0
src/main/kotlin/com/ikueb/advent18/Day25.kt
h-j-k
159,901,179
false
null
package com.ikueb.advent18 import java.util.* object Day25 { private const val DEFINITION = "([-\\d ]+),([-\\d ]+),([-\\d ]+),([-\\d ]+)" fun getConstellations(input: List<String>) = with( input.parseWith(DEFINITION) { (a, b, c, d) -> Point4d(a.trimInt(), b.trimInt(), c.trimInt(), d.trimInt()) }) { associateWith { point -> filter { point.isNearby(it) }.toSet() } }.let { formConstellations(it).count() } private fun formConstellations(nearby: Map<Point4d, Set<Point4d>>) = sequence { val remaining = nearby.keys.toDeque() while (remaining.isNotEmpty()) { val (current, toProcess) = with(remaining.removeFirst()) { mutableSetOf(this) to nearby[this]!!.toDeque() } while (toProcess.isNotEmpty()) { toProcess.removeFirst().let { point -> remaining.remove(point) current.add(point) toProcess.addAll(nearby[point]!!.filterNot { it in current }) } } yield(current) } } } private data class Point4d(val a: Int, val b: Int, val c: Int, val d: Int) { fun isNearby(other: Point4d) = this != other && manhattanDistance(other) <= 3 private fun manhattanDistance(other: Point4d) = listOf(a - other.a, b - other.b, c - other.c, d - other.d) .sumBy { Math.abs(it) } } private fun String.trimInt() = trim().toInt() private fun <T> Iterable<T>.toDeque() = toCollection(ArrayDeque<T>())
0
Kotlin
0
0
f1d5c58777968e37e81e61a8ed972dc24b30ac76
1,580
advent18
Apache License 2.0
src/Day06.kt
rickbijkerk
572,911,701
false
{"Kotlin": 31571}
fun main() { fun part1(input: List<String>): Int { val line = input.first() val result = (0..line.length - 4).first { index -> line.substring(index, index + 4).toSet().size == 4 } return result + 4 } fun part2(input: List<String>): Int { val line = input.first() val result = (0..line.length - 14).first { index -> line.substring(index, index + 14).toSet().size == 14 } return result + 14 } val testInput = readInput("day06_test") // TEST PART 1 val resultPart1 = part1(testInput) val expectedPart1 = 11 //TODO Change me println("testresult:$resultPart1 expected:$expectedPart1 \n") check(resultPart1 == expectedPart1) //Check results part1 val input = readInput("day06") println("ANSWER 1: ${part1(input)}") // TEST PART 2 val resultPart2 = part2(testInput) val expectedPart2 = 26 //TODO Change me println("testresult:$resultPart2 expected:$expectedPart2 \n") check(resultPart2 == expectedPart2) //Check results part2 println("ANSWER 2: ${part2(input)}") }
0
Kotlin
0
0
817a6348486c8865dbe2f1acf5e87e9403ef42fe
1,141
aoc-2022
Apache License 2.0
src/test/kotlin/aoc/Day3.kt
Lea369
728,236,141
false
{"Kotlin": 36118}
package aoc import org.junit.jupiter.api.Nested import java.nio.file.Files import java.nio.file.Paths import java.util.stream.Collectors import kotlin.test.Test import kotlin.test.assertEquals class Day3 { @Nested internal inner class Day3Test { private val day3: Day3 = Day3() @Test fun testPart1() { val expected = 467835 assertEquals(expected, day3.solveP2("./src/test/resources/input3")) } @Test fun testFindNumbers() { val expected: List<IntRange> = listOf(0..2, 5..7) assertEquals(expected, day3.findNumbers("467..114..")) } @Test fun testFilterNumbers() { assertEquals(false, day3.isIsland(0, 0..2, listOf("467..114..", "...*......"))) assertEquals(true, day3.isIsland(0, 5..7, listOf("467..114..", "...*......"))) } @Test fun testGearRatio() { assertEquals(16345, day3.gearRatio(1, 3, listOf("467..114..", "...*......", "..35..633."))) } } private fun gearRatio(lineIndex: Int, colIndex: Int, ref: List<String>): Int { val numbersPrevLine: List<Int> = findNumbers(ref.getOrElse(lineIndex-1){""}) .filter { colIndex in it || colIndex+1 in it || colIndex-1 in it } .map { ref.getOrElse(lineIndex-1){""}.substring(it).toInt() } val numbersNextLine: List<Int> = findNumbers(ref.getOrElse(lineIndex+1){""}) .filter { colIndex in it || colIndex+1 in it || colIndex-1 in it } .map { ref.getOrElse(lineIndex+1){""}.substring(it).toInt() } val numbersLine: List<Int> = findNumbers(ref.getOrElse(lineIndex){""}) .filter { colIndex+1 in it || colIndex-1 in it } .map { ref.getOrElse(lineIndex){""}.substring(it).toInt() } val allNumbers = numbersLine + numbersPrevLine + numbersNextLine if (allNumbers.size == 2) return allNumbers.first() * allNumbers.last() return 0 } private fun solveP2(filename: String): Int { val lines: List<String> = Files.lines(Paths.get(filename)).collect(Collectors.toList()) return lines.flatMapIndexed { index, line -> line.mapIndexed { i, c -> i to c }.filter { it.second == '*' }.map { index to it.first } }.sumOf { gearRatio(it.first, it.second, lines) } } private fun solveP1(filename: String): Int { val lines: List<String> = Files.lines(Paths.get(filename)).collect(Collectors.toList()) return lines.flatMapIndexed { index, line -> findNumbers(line).map { index to it } } .filter { !isIsland(it.first, it.second, lines) } .sumOf { lines.get(it.first).substring(it.second).toInt() } } private fun isIsland(lineIndex: Int, intRange: IntRange, ref: List<String>): Boolean { val nextLine = ref.getOrElse(lineIndex + 1) { "" } .filterIndexed { i, _ -> i in intRange.first - 1..intRange.last + 1 } .all { it.isDigit() || it == '.' } val prevLine = ref.getOrElse(lineIndex - 1) { "" } .filterIndexed { i, _ -> i in intRange.first - 1..intRange.last + 1 } .all { it.isDigit() || it == '.' } val thisLine = ref.getOrElse(lineIndex) { "" } .filterIndexed { i, _ -> i in intRange.first - 1..intRange.last + 1 } .all { it.isDigit() || it == '.' } return prevLine && nextLine && thisLine } private fun findNumbers(line: String): List<IntRange> { return line.toList() .mapIndexed { index, c -> index to c } .filter { it.second.isDigit() } .map { it.first } .fold(mutableListOf<MutableList<Int>>()) { acc, i -> if (acc.isEmpty() || acc.last().last() != i - 1) { acc.add(mutableListOf(i)) } else acc.last().add(i) acc } .map { listofIndexes -> IntRange(listofIndexes.first(), listofIndexes.last()) } .toList() } }
0
Kotlin
0
0
1874184df87d7e494c0ff787ea187ea3566fbfbb
4,046
AoC
Apache License 2.0
src/Day02/Day02.kt
SelenaChen123
573,253,480
false
{"Kotlin": 14884}
import java.io.File fun main() { fun part1(input: List<String>): Int { var points = 0 for (line in input) { val them = line.split(" ")[0] val you = line.split(" ")[1] val theirValue = when (them) { "A" -> 1 "B" -> 2 "C" -> 3 else -> 0 } val yourValue = when (you) { "X" -> 1 "Y" -> 2 "Z" -> 3 else -> 0 } if (theirValue == yourValue) { points += 3 } else if (theirValue + 1 == yourValue || (theirValue == 3 && yourValue == 1)) { points += 6 } points += yourValue } return points } fun part2(input: List<String>): Int { var points = 0 for (line in input) { val them = line.split(" ")[0] val you = line.split(" ")[1] val theirValue = when (them) { "A" -> 1 "B" -> 2 "C" -> 3 else -> 0 } if (you == "Y") { points += theirValue points += 3 } else if (you == "Z") { if (theirValue != 3) { points += theirValue + 1 } else { points += 1 } points += 6 } else { if (theirValue != 1) { points += theirValue - 1 } else { points += 3 } } } return points } val testInput = File("input", "Day02_test.txt").readLines() val input = File("input", "Day02.txt").readLines() val part1TestOutput = part1(testInput) check(part1TestOutput == 15) println(part1(input)) val part2TestOutput = part2(testInput) check(part2TestOutput == 12) println(part2(input)) }
0
Kotlin
0
0
551af4f0efe11744f918d1ff5bb2259e34c5ecd3
2,208
AdventOfCode2022
Apache License 2.0
kmath-stat/src/commonMain/kotlin/space/kscience/kmath/optimization/FunctionOptimization.kt
therealansh
373,284,570
true
{"Kotlin": 1071813, "ANTLR": 887}
/* * Copyright 2018-2021 KMath contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package space.kscience.kmath.optimization import space.kscience.kmath.expressions.AutoDiffProcessor import space.kscience.kmath.expressions.DifferentiableExpression import space.kscience.kmath.expressions.Expression import space.kscience.kmath.expressions.ExpressionAlgebra import space.kscience.kmath.misc.Symbol import space.kscience.kmath.operations.ExtendedField import space.kscience.kmath.structures.Buffer import space.kscience.kmath.structures.indices /** * A likelihood function optimization problem with provided derivatives */ public interface FunctionOptimization<T : Any> : Optimization<T> { /** * The optimization direction. If true search for function maximum, if false, search for the minimum */ public var maximize: Boolean /** * Define the initial guess for the optimization problem */ public fun initialGuess(map: Map<Symbol, T>) /** * Set a differentiable expression as objective function as function and gradient provider */ public fun diffFunction(expression: DifferentiableExpression<T, Expression<T>>) public companion object { /** * Generate a chi squared expression from given x-y-sigma data and inline model. Provides automatic differentiation */ public fun <T : Any, I : Any, A> chiSquared( autoDiff: AutoDiffProcessor<T, I, A, Expression<T>>, x: Buffer<T>, y: Buffer<T>, yErr: Buffer<T>, model: A.(I) -> I, ): DifferentiableExpression<T, Expression<T>> where A : ExtendedField<I>, A : ExpressionAlgebra<T, I> { require(x.size == y.size) { "X and y buffers should be of the same size" } require(y.size == yErr.size) { "Y and yErr buffer should of the same size" } return autoDiff.process { var sum = zero x.indices.forEach { val xValue = const(x[it]) val yValue = const(y[it]) val yErrValue = const(yErr[it]) val modelValue = model(xValue) sum += ((yValue - modelValue) / yErrValue).pow(2) } sum } } } } /** * Define a chi-squared-based objective function */ public fun <T: Any, I : Any, A> FunctionOptimization<T>.chiSquared( autoDiff: AutoDiffProcessor<T, I, A, Expression<T>>, x: Buffer<T>, y: Buffer<T>, yErr: Buffer<T>, model: A.(I) -> I, ) where A : ExtendedField<I>, A : ExpressionAlgebra<T, I> { val chiSquared = FunctionOptimization.chiSquared(autoDiff, x, y, yErr, model) diffFunction(chiSquared) maximize = false } /** * Optimize differentiable expression using specific [OptimizationProblemFactory] */ public fun <T : Any, F : FunctionOptimization<T>> DifferentiableExpression<T, Expression<T>>.optimizeWith( factory: OptimizationProblemFactory<T, F>, vararg symbols: Symbol, configuration: F.() -> Unit, ): OptimizationResult<T> { require(symbols.isNotEmpty()) { "Must provide a list of symbols for optimization" } val problem = factory(symbols.toList(), configuration) problem.diffFunction(this) return problem.optimize() }
0
null
0
0
4065466be339017780b0ac4b98a9eda2cc2378e4
3,393
kmath
Apache License 2.0
exercises/src/test/kotlin/solutions/chapter5/SolutionTest.kt
rmolinamir
705,132,794
false
{"Kotlin": 690308, "HTML": 34654, "CSS": 1900, "Shell": 593}
package solutions.chapter5 import org.junit.jupiter.api.Test import strikt.api.expectThat import strikt.assertions.isEqualTo class E1SolutionTest { @Test fun `collatzR returns the correct sequence`() { expectThat(13.collatz()).isEqualTo(listOf(13, 40, 20, 10, 5, 16, 8, 4, 2, 1)) expectThat(8.collatz()).isEqualTo(listOf(8, 4, 2, 1)) } } class E2SolutionTest { @Test fun `elevator is not stuck in the shaft`() { val values = listOf(Up, Up, Down, Up, Down, Down, Up, Up, Up, Down) val tot = values.fold(Elevator(0)){ elevator, direction -> when(direction) { Up -> Elevator(elevator.floor + 1) Down -> Elevator(elevator.floor - 1) } } expectThat(tot).isEqualTo(Elevator(2)) } } class E3SolutionTest { @Test fun `compacts json`() { val jsonText = """{ "my greetings" : "hello world! \"How are you?\"" }""" val expected = """{"my greetings":"hello world! \"How are you?\""}""" expectThat(compactJson(jsonText)).isEqualTo(expected) } @Test fun `compacts multi-line json`() { val jsonText = """{ "my greetings" : "hello world! \"How are you?\"" }""" val expected = """{"my greetings":"hello world! \"How are you?\""}""" expectThat(compactJson(jsonText)).isEqualTo(expected) } } class E4SolutionTest { @Test fun `monoid folding lists`() { with( Monoid(0, Int::plus)){ expectThat( listOf(1,2,3,4,10).fold() ) .isEqualTo(20) } with( Monoid("", String::plus)){ expectThat( listOf( "My", "Fair", "Lady").fold() ) .isEqualTo("MyFairLady") } data class Money(val amount: Double) { fun sum(other: Money) = Money(this.amount + other.amount) } val zeroMoney = Money(0.0) with( Monoid(zeroMoney, Money::sum) ) { expectThat( listOf(Money(2.1), Money(3.9), Money(4.0)).fold() ) .isEqualTo(Money(10.0)) } } }
0
Kotlin
0
0
ccfed75476263e780c5a8c61e02178532cc9f3f4
1,835
fotf
MIT License
jetbrains-core/src/software/aws/toolkits/jetbrains/core/tools/Versions.kt
aws
91,485,909
false
{"Kotlin": 6503168, "C#": 96334, "TypeScript": 84848, "Java": 20765, "JavaScript": 8806, "Shell": 2920, "Dockerfile": 2209, "SCSS": 242, "Batchfile": 77}
// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.aws.toolkits.jetbrains.core.tools /** * Top level interface for different versioning schemes such as semantic version */ interface Version : Comparable<Version> { /** * @return Human-readable representation of the version */ fun displayValue(): String } /** * @return true if the specified version is compatible with the specified version ranges. Always returns true if no range is specified. */ fun <T : Version> T.isValid(range: VersionRange<T>?): Validity = when { range == null -> Validity.Valid(this) this < range.minVersion -> Validity.VersionTooOld(this, range.minVersion) range.maxVersion <= this -> Validity.VersionTooNew(this, range.maxVersion) else -> Validity.Valid(this) } /** * Represents a range of versions. * * @property minVersion The minimum version supported, inclusive. * @property maxVersion The maximum version supported, exclusive. */ data class VersionRange<T : Version>(val minVersion: T, val maxVersion: T) { fun displayValue() = "${minVersion.displayValue()} ≤ X < ${maxVersion.displayValue()}" } infix fun <T : Version> T.until(that: T): VersionRange<T> = VersionRange(this, that)
405
Kotlin
184
719
8a8ba8859d3b711b1a90a357913adb9bb920ca26
1,295
aws-toolkit-jetbrains
Apache License 2.0
src/main/kotlin/com/jacobhyphenated/day3/Day3.kt
jacobhyphenated
572,119,677
false
{"Kotlin": 157591}
package com.jacobhyphenated.day3 import com.jacobhyphenated.Day import java.io.File import kotlin.math.absoluteValue // Crossed Wires class Day3: Day<Pair<List<String>, List<String>>> { override fun getInput(): Pair<List<String>, List<String>> { val lines = this.javaClass.classLoader.getResource("day3/input.txt")!! .readText() .lines() .map { it.split(",") } return Pair(lines[0], lines[1]) } /** * Given instructions for the path of 2 wires, assuming the wires start at the same point, * find the point where the wires intersect that is the closest manhattan distance to the start point */ override fun part1(input: Pair<List<String>, List<String>>): Int { val cord1 = followCord(input.first) val cord2 = followCord(input.second) return cord1.keys.intersect(cord2.keys) .minOf { it.first.absoluteValue + it.second.absoluteValue } } /** * Find the point where the wires intersect that is the closest along the wires from the start, * calculated by taking the steps to reach the intersection for each wire added together */ override fun part2(input: Pair<List<String>, List<String>>): Int { val cord1 = followCord(input.first) val cord2 = followCord(input.second) return cord1.keys.intersect(cord2.keys) .minOf { cord1[it]!! + cord2[it]!! } } /** * Maps out the path of the cord in a way that can be used in both part 1 and 2 * * The result is a Map of points in a coordinate plane with 0,0 as the start point * The value of each mapped point is the number of steps needed to reach that point along the cord. * If a point is reached multiple times, the lower step count is used. * * Instructions have the form of U7 - go up 7 steps */ private fun followCord(cord: List<String>): Map<Pair<Int, Int>, Int> { var x = 0 var y = 0 var steps = 0; val coordinates = mutableMapOf<Pair<Int, Int>, Int>() for (path in cord) { val direction = path[0] val len = path.substring(1).toInt() repeat(len) { steps += 1 when(direction) { 'R' -> x += 1 'L' -> x -= 1 'U' -> y += 1 'D' -> y -= 1 else -> throw IllegalArgumentException("Invlid direction character $direction") } coordinates.putIfAbsent(Pair(x, y), steps) } } return coordinates } }
0
Kotlin
0
0
1a0b9cb6e9a11750c5b3b5a9e6b3d63649bf78e4
2,638
advent2019
The Unlicense
src/Day10.kt
ChAoSUnItY
572,814,842
false
{"Kotlin": 19036}
fun main() { data class CycleState( val crtGeneration: Boolean, var cycle: Int = 0, var regX: Int = 1, var rayPosition: Int = 0, var signalSum: Int = 0, var crtImage: MutableList<Char> = mutableListOf() ) { fun processInstruction(instruction: String): CycleState { val instructionSegments = instruction.split(" ") when (instructionSegments[0]) { "noop" -> { nextCycle(1) } "addx" -> { nextCycle(2) regX += instructionSegments[1].toInt() } else -> {} } return this } fun nextCycle(cycleCount: Int) { for (_i in 0 until cycleCount) { crtImage += if (rayPosition >= regX - 1 && rayPosition <= regX + 1) '.' else '#' if (crtGeneration && ++rayPosition % 40 == 0) { rayPosition = 0 crtImage += '\n' } else if (++cycle == 20 || (cycle - 20) % 40 == 0) { signalSum += cycle * regX } } } } fun part1(data: List<String>): Int = data.fold(CycleState(false), CycleState::processInstruction).signalSum fun part2(data: List<String>): String = data.fold(CycleState(true), CycleState::processInstruction).crtImage.joinToString("") val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
3
4fae89104aba1428820821dbf050822750a736bb
1,607
advent-of-code-2022-kt
Apache License 2.0
src/main/kotlin/com/hj/leetcode/kotlin/problem640/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem640 /** * LeetCode page: [640. Solve the Equation](https://leetcode.com/problems/solve-the-equation/); */ class Solution { /* Complexity: * Time O(N) and Space O(1) where N is the length of equation; */ fun solveEquation(equation: String): String { val solver = SingleVariableLinearEquationSolver() return solver.parseAndSolve(equation) } private class SingleVariableLinearEquationSolver { private var coefficient: Int = 0 private var constant: Int = 0 private val auxBuilder = StringBuilder() fun parseAndSolve(equation: String): String { parse(equation) return solve() } private fun parse(equation: String) { for (char in equation) { when (char) { '+', '-' -> { concludeAndClearAuxBuilder() auxBuilder.append(char) } '=' -> { concludeAndClearAuxBuilder() reverseSign() } else -> auxBuilder.append(char) } } concludeAndClearAuxBuilder() } private fun concludeAndClearAuxBuilder() { if (auxBuilder.isEmpty()) return if (auxBuilder.last() == 'x') { auxBuilder.deleteCharAt(auxBuilder.lastIndex) when (auxBuilder.length) { 0 -> auxBuilder.append(1) 1 -> if (auxBuilder[0] == '+' || auxBuilder[0] == '-') auxBuilder.append(1) } coefficient -= auxBuilder.toString().toInt() } else { constant += auxBuilder.toString().toInt() } auxBuilder.clear() } private fun reverseSign() { coefficient = -coefficient constant = -constant } private fun solve(): String { return when { coefficient != 0 -> "x=${constant / coefficient}" constant == 0 -> "Infinite solutions" else -> "No solution" } } } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
2,246
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/Day3.kt
clechasseur
264,758,910
false
null
import org.clechasseur.adventofcode2017.Direction import org.clechasseur.adventofcode2017.Pt import org.clechasseur.adventofcode2017.manhattan object Day3 { private const val input = 368078 private val allAround = listOf( Pt(-1, -1), Pt(-1, 0), Pt(-1, 1), Pt(0, -1), Pt(0, 1), Pt(1, -1), Pt(1, 0), Pt(1, 1) ) fun part1() = manhattan(spiral().drop(input - 1).first(), Pt.ZERO) fun part2() = spiralTestValues().dropWhile { it < input }.first() private fun spiral(): Sequence<Pt> = sequence { var pt = Pt.ZERO var dir = Direction.RIGHT var moves = 1 yield(pt) while (true) { (0 until moves).forEach { _ -> pt += dir.displacement yield(pt) } dir = dir.right (0 until moves).forEach { _ -> pt += dir.displacement yield(pt) } dir = dir.right moves++ } } private fun spiralTestValues(): Sequence<Int> = sequence { val spir = spiral().iterator() val map = mutableMapOf<Pt, Int>() map[spir.next()] = 1 while (true) { val pt = spir.next() val value = allAround.mapNotNull { map[pt + it] }.sum() yield(value) map[pt] = value } } }
0
Kotlin
0
0
f3e8840700e4c71e59d34fb22850f152f4e6e739
1,370
adventofcode2017
MIT License
Lab 4/src/main/kotlin/Tree2D.kt
knu-3-tochanenko
273,874,096
false
null
import kotlin.math.pow class Tree2D { companion object { private var result = mutableListOf<Dot>() fun calculate(dots: List<Dot>, rectangle: Rectangle): List<Dot> { val root = buildTree(dots) findDotsInRectangle(root, rectangle) return result } private fun buildTree(dots: List<Dot>, split: Split = Split.VERTICAL): TreeNode? { if (dots.size == 1) return TreeNode(dots[0]) else if (dots.isEmpty()) return null val median = findMedian(dots, split) val dot = dots[median] val x: Double? val y: Double? val nextSplit: Split if (split == Split.VERTICAL) { nextSplit = Split.HORIZONTAL x = dot.x y = null } else { nextSplit = Split.VERTICAL x = null y = dot.y } val node = TreeNode(dot, x = x, y = y) node.left = buildTree(dots.subList(0, median), nextSplit) node.right = buildTree(dots.subList(median, dots.size), nextSplit) return node } private fun findDotsInRectangle(node: TreeNode?, rectangle: Rectangle) { if (node == null) return if (isInRectangle(node.dot, rectangle)) result.add(node.dot) if (isOutside(node, rectangle)) { println("${node.dot.x} --- ${node.dot.y} for left") findDotsInRectangle(node.left, rectangle) } if (isOutside(node, rectangle)) { println("${node.dot.x} --- ${node.dot.y} for right") findDotsInRectangle(node.right, rectangle) } if (!isOutside(node, rectangle) && !isOutside(node, rectangle)) println("${node.dot.x} --- ${node.dot.y} ${"SKIPPED".red()}") } private fun equalDelta(a: Double, b: Double, delta: Double = .1.pow(8)): Boolean = kotlin.math.abs(a - b) < delta private fun isOutside(node: TreeNode, rectangle: Rectangle): Boolean { if (node.x == null && node.y != null) { return if (rectangle.topRight.y < node.y!! || equalDelta(rectangle.topRight.y, node.y!!)) { true } else if (rectangle.bottomLeft.y < node.y!! || equalDelta(rectangle.bottomLeft.y, node.y!!)) { true } else { true } } else if (node.x != null && node.y == null) { return if (rectangle.topRight.x <= node.x!! || equalDelta(rectangle.topRight.x, node.x!!)) { true } else if (rectangle.bottomLeft.x < node.x!! || equalDelta(rectangle.bottomLeft.x, node.x!!)) { true } else { true } } return false } private fun findMedian(dots: List<Dot>, type: Split): Int { if (type == Split.VERTICAL) dots.sortedBy { dot -> dot.x } if (type == Split.HORIZONTAL) dots.sortedBy { dot -> dot.y } return dots.size / 2 } private fun isInRectangle(dot: Dot, rectangle: Rectangle): Boolean { return (dot.x >= rectangle.bottomLeft.x && dot.x <= rectangle.topRight.x) && (dot.y >= rectangle.bottomLeft.y && dot.y <= rectangle.topRight.y) } } }
0
Kotlin
0
0
d33c5e03ccec496ffa6400c7824780886a46b1ba
3,578
ComputerGraphics
MIT License
modulo4/src/aula14/Exercicio08.kt
ProgramaCatalisa
491,134,850
false
{"Kotlin": 80614}
package aula14 /*Exercício 04 da parte 'Exercícios gerais'*/ fun main() { print("Informe a quantidade de alunes a turma tem: ") val quantidadeAlunos = readln().toInt() val turma = receberDadosAlune(quantidadeAlunos) val medias = calcularMedia(quantidadeAlunos, turma) printarMedias(turma, medias) } fun receberDadosAlune(quantidadeAlunos: Int): ArrayList<String> { val turma = ArrayList<String>() var contador = 0 while (contador < quantidadeAlunos) { print("Informe o nome da pessoa número ${contador + 1}: ") val nome = readln() turma.add(nome) contador++ } return turma } fun calcularMedia(quantidadeAlunos: Int, turma: ArrayList<String>): DoubleArray { val medias = DoubleArray(quantidadeAlunos) turma.forEachIndexed { index, alune -> print("Digite a primeira nota de $alune: ") val nota1 = readln().toDouble() print("Digite a segunda nota de $alune: ") val nota2 = readln().toDouble() print("Digite a terceira nota de $alune: ") val nota3 = readln().toDouble() val media = (nota1 + nota2 + nota3) / 3 medias[index] = media } return medias } fun printarMedias(turma: ArrayList<String>, medias: DoubleArray) { turma.forEachIndexed { index, alune -> println("Alune $alune teve média ${medias[index]}") } }
0
Kotlin
0
0
e0b994cd6b173da0f791fd3cb2eca96316cb6a6d
1,393
ResolucaoExerciciosKotlin
Apache License 2.0
src/main/kotlin/aoc2022/Day02.kt
w8mr
572,700,604
false
{"Kotlin": 140954}
package aoc2022 import aoc.parser.* import aoc.parser.Parsers.eol class Day02() { enum class Item(val name1: String, val name2: String, val score: Int) { ROCK("A", "X", 1), PAPER("B", "Y", 2), SCISSOR("C", "Z", 3), } enum class Result(val name1: String, val score: Int) { LOSE("X", 0), DRAW("Y", 3), WIN("Z", 6) } /** pair of items @result if second wins, looses or draw of first */ fun result(input: Pair<Item, Item>): Result = Result.values()[(input.second.ordinal-input.first.ordinal+1).mod(3)] fun needsTo(input: Pair<Item, Result>): Item = Item.values()[(input.second.ordinal+input.first.ordinal-1).mod(3)] fun score1(input: Pair<Item, Item>) = result(input).score + input.second.score fun scores2(input: Pair<Item, Result>): Int { val you = needsTo(input) return score1(Pair(input.first, you)) } fun part1(input: String): Int { val parsed = parser1(input) return parsed.sumOf(::score1) } fun part2(input: String): Int { val parsed = parser2(input) return parsed.sumOf(::scores2) } val col1 = Item::class.asParser(Item::name1) val col2Part1 = Item::class.asParser(Item::name2) val col2Part2 = Result::class.asParser(Result::name1) val parser1 = zeroOrMore(seq(col1 and " ", col2Part1 and eol)) val parser2 = zeroOrMore(seq(col1 and " ", col2Part2 and eol)) }
0
Kotlin
0
0
e9bd07770ccf8949f718a02db8d09daf5804273d
1,491
aoc-kotlin
Apache License 2.0
src/main/kotlin/endredeak/aoc2022/Day09.kt
edeak
571,891,076
false
{"Kotlin": 44975}
package endredeak.aoc2022 import kotlin.math.absoluteValue import kotlin.math.sign fun main() { solve("Rope Bridge") { val input = lines .map { it.split(" ") } .map { (d, a) -> d to a.toInt() } operator fun Pair<Int, Int>.plus(p: Pair<Int, Int>) = this.first + p.first to this.second + p.second operator fun Pair<Int, Int>.minus(p: Pair<Int, Int>) = this.first - p.first to this.second - p.second fun Pair<Int, Int>.notInRange() = listOf(this.first.absoluteValue, this.second.absoluteValue).any { it > 1 } infix fun Pair<Int, Int>.follow(p: Pair<Int, Int>) = this.first + (p.first - this.first).sign to this.second + (p.second - this.second).sign fun move(dir: String) = when (dir) { "R" -> 1 to 0 "U" -> 0 to 1 "L" -> -1 to 0 else -> 0 to -1 } fun simulateRope(n: Int = 2) = run { val knots = MutableList(n) { 0 to 0 } val path = mutableSetOf(0 to 0) input.forEach { (dir, dist) -> repeat(dist) { knots[0] += move(dir) repeat(knots.size - 1) { i -> val h = knots[i] val t = knots[i + 1] if ((h - t).notInRange()) { knots[i + 1] = t follow h } path += knots.last() } } } path.size } part1(6314) { simulateRope(2) } part2(2504) { simulateRope(10) } } }
0
Kotlin
0
0
e0b95e35c98b15d2b479b28f8548d8c8ac457e3a
1,675
AdventOfCode2022
Do What The F*ck You Want To Public License
src/main/kotlin/de/mbdevelopment/adventofcode/year2021/solvers/day12/Day12Puzzle2.kt
Any1s
433,954,562
false
{"Kotlin": 96683}
package de.mbdevelopment.adventofcode.year2021.solvers.day12 class Day12Puzzle2 : Day12Puzzle() { override fun countWaysThroughCaves(caveConnections: Map<Cave, Set<Cave>>) = caveConnections.keys .filterIsInstance<Cave.SmallCave>() .minus(setOf(START, END)) .flatMap { waysThroughCaves(caveConnections, listOf(START), it) } .distinct() .size private fun waysThroughCaves( caveConnections: Map<Cave, Set<Cave>>, currentPath: List<Cave>, specialSmallCave: Cave, visitsToSpecialCave: Int = 0 ): List<List<Cave>> { return if (currentPath.last() == END) { listOf(currentPath) } else { val forbiddenCaves = currentPath .filterIsInstance<Cave.SmallCave>() .filter { it != specialSmallCave || (it == specialSmallCave && visitsToSpecialCave > 1) } .toSet() caveConnections[currentPath.last()] ?.minus(forbiddenCaves) ?.flatMap { waysThroughCaves( caveConnections, currentPath + it, specialSmallCave, if (currentPath.last() == specialSmallCave) visitsToSpecialCave + 1 else visitsToSpecialCave ) } ?: throw IllegalArgumentException("Cave $currentPath does not have any connections.") } } }
0
Kotlin
0
0
21d3a0e69d39a643ca1fe22771099144e580f30e
1,479
AdventOfCode2021
Apache License 2.0
src/Day01.kt
TheGreatJakester
573,222,328
false
{"Kotlin": 47612}
import utils.readInputAsLines fun main() { fun part1(input: List<String>): Int { val elves = buildElfList(input) return elves.maxOf { it.sum() } } fun part2(input: List<String>): Int { val elves = buildElfList(input) return elves.map { it.sum() }.sorted().takeLast(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInputAsLines("Day01_test") check(part1(testInput) == 24000) val input = readInputAsLines("Day01") println(part1(input)) println(part2(input)) } fun buildElfList(input: List<String>): List<List<Int>> { val elves = mutableListOf<List<Int>>() var currentList = mutableListOf<Int>() input.forEach { if (it.isEmpty()){ elves.add(currentList) currentList = mutableListOf() } else { currentList.add(it.toInt()) } } return elves }
0
Kotlin
0
0
c76c213006eb8dfb44b26822a44324b66600f933
946
2022-AOC-Kotlin
Apache License 2.0
src/main/kotlin/File09.kt
andrewrlee
319,095,151
false
null
import java.io.File import java.nio.charset.StandardCharsets.UTF_8 private class Challenge09 { val numbers = File("src/main/resources/09-input.txt").readLines(UTF_8).map { it.toLong() } fun <A, B> cartesianProduct(listA: Iterable<A>, listB: Iterable<B>): Sequence<Pair<A, B>> = sequence { listA.forEach { a -> listB.forEach { b -> yield(a to b) } } } fun findAnswer1v1() = numbers.toList() .windowed(26, 1) .map { it.take(25).toSet() to it.last() } .find { (previous, number) -> cartesianProduct(previous, previous).filter { (i, j) -> i != j }.find { (i, j) -> i + j == number } == null }?.second fun List<Long>.findContiguousRangeThatSumsTo(resultToFind: Long): List<Long>? { var sum = 0L val trimmedList = this.reversed().takeWhile { ((sum + it) <= resultToFind).also { _ -> sum += it } }.sorted() return if (trimmedList.sum() == resultToFind) trimmedList else null } fun findContiguousRange(resultToFind: Long): List<Long> = (0..numbers.size).mapNotNull { i -> (0..i).map(numbers::get).findContiguousRangeThatSumsTo(resultToFind)?.let { return it } } fun findAnswer2v1() = findContiguousRange(findAnswer1v1()!!).let { it.first() + it.last() } fun solve() { println(findAnswer1v1()) println(findAnswer2v1()) } } fun main() = Challenge09().solve()
0
Kotlin
0
0
a9c21a6563f42af7fada3dd2e93bf75a6d7d714c
1,417
adventOfCode2020
MIT License
src/main/kotlin/com/hj/leetcode/kotlin/problem109/Solution2.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem109 import com.hj.leetcode.kotlin.common.model.ListNode import com.hj.leetcode.kotlin.common.model.TreeNode /** * LeetCode page: [109. Convert Sorted List to Binary Search Tree](https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/); */ class Solution2 { /* Complexity: * Time O(N) and Space O(LogN) where N is the number of nodes in head; */ fun sortedListToBST(head: ListNode?): TreeNode? { val lastIndex = head.size() - 1 val nodePointer = NodePointer(head) return buildBstFromSortedList(0, lastIndex, nodePointer) } private fun ListNode?.size(): Int { var size = 0 var currNode = this while (currNode != null) { size++ currNode = currNode.next } return size } private class NodePointer(var node: ListNode?) { fun getValue() = checkNotNull(node).`val` fun moveToNext() { node = node?.next } } private fun buildBstFromSortedList( fromIndex: Int, toIndex: Int, inOrderPointer: NodePointer ): TreeNode? { if (fromIndex > toIndex) return null if (fromIndex == toIndex) return TreeNode(inOrderPointer.getValue()) val midIndex = (fromIndex + toIndex + 1) ushr 1 val leftTree = buildBstFromSortedList(fromIndex, midIndex - 1, inOrderPointer) inOrderPointer.moveToNext() val midValue = inOrderPointer.getValue() var rightTree: TreeNode? = null val hasRightTree = toIndex > midIndex if (hasRightTree) { inOrderPointer.moveToNext() rightTree = buildBstFromSortedList(midIndex + 1, toIndex, inOrderPointer) } return TreeNode(midValue).apply { left = leftTree right = rightTree } } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,887
hj-leetcode-kotlin
Apache License 2.0
17/kotlin/src/main/kotlin/se/nyquist/Main.kt
erinyq712
437,223,266
false
{"Kotlin": 91638, "C#": 10293, "Emacs Lisp": 4331, "Java": 3068, "JavaScript": 2766, "Perl": 1098}
package se.nyquist import java.io.File import kotlin.math.absoluteValue fun readRange(input: String): IntRange { val xCoordStr = input.split("..") return IntRange(xCoordStr[0].toInt(), xCoordStr[1].toInt()) } fun main() { val ranges = readInput("input.txt") val targetArea = TargetArea(ranges) val hits = mutableListOf<Pair<Int, Int>>() var xVelocity = if (targetArea.xRange.first > 0) 1 else -1 var yVelocity = targetArea.yRange.first var maxPos = 0 var prevWasHit = false while (true) { val xLimit = xVelocity * (xVelocity + 1) / 2 if (xLimit > targetArea.xRange.first) { var thisIsHit = false val startVelocity = Pair(xVelocity, yVelocity) val startPosition = Pair(0, 0) val state = Probe(targetArea, startPosition, startVelocity) if (state.search(hits)) { thisIsHit = true if (state.maxPos > maxPos) maxPos = state.maxPos println("$startVelocity $state") } else { if (yVelocity > targetArea.yRange.first.absoluteValue) { break } } if (!thisIsHit && prevWasHit || xVelocity+1 > targetArea.xRange.last) { xVelocity = if (targetArea.xRange.first > 0) 1 else -1 yVelocity++ // prevWasHit = false } else { xVelocity = if (targetArea.xRange.first > 0) xVelocity+1 else xVelocity-1 } prevWasHit = thisIsHit } else { if (xVelocity+1 > targetArea.xRange.last) { xVelocity = if (targetArea.xRange.first > 0) 1 else -1 yVelocity++ // prevWasHit = false } else { xVelocity = if (targetArea.xRange.first > 0) xVelocity+1 else xVelocity-1 } prevWasHit = false } } println("$maxPos") println("${hits.count()}") } private fun readInput(input: String): Array<IntRange> { val line = File(input).readText() val data = line.split((":")) val ranges = data[1].split(",") val xRangeStr = ranges[0].split("=") val yRangeStr = ranges[1].split("=") return arrayOf(readRange(xRangeStr[1]), readRange(yRangeStr[1])) }
0
Kotlin
0
0
b463e53f5cd503fe291df692618ef5a30673ac6f
2,334
adventofcode2021
Apache License 2.0
src/hard/_212WordSearchII.kt
ilinqh
390,190,883
false
{"Kotlin": 382147, "Java": 32712}
package hard class _212WordSearchII { class Solution { var dirs = arrayOf(intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(0, 1), intArrayOf(0, -1)) fun findWords(board: Array<CharArray>, words: Array<String>): List<String> { val trie = Trie() for (word in words) { trie.insert(word) } val ans: MutableSet<String> = HashSet() for (i in board.indices) { for (j in 0 until board[0].size) { dfs(board, trie, i, j, ans) } } return ArrayList(ans) } private fun dfs(board: Array<CharArray>, tempNow: Trie?, i1: Int, j1: Int, ans: MutableSet<String>) { var now = tempNow if (!now!!.children.containsKey(board[i1][j1])) { return } val ch = board[i1][j1] now = now.children[ch] if ("" != now!!.word) { ans.add(now.word) } board[i1][j1] = '#' for (dir in dirs) { val i2 = i1 + dir[0] val j2 = j1 + dir[1] if (i2 >= 0 && i2 < board.size && j2 >= 0 && j2 < board[0].size) { dfs(board, now, i2, j2, ans) } } board[i1][j1] = ch } } class Trie { var word = "" var children: MutableMap<Char, Trie> = HashMap() fun insert(word: String) { var cur: Trie = this for (element in word) { if (!cur.children.containsKey(element)) { cur.children[element] = Trie() } cur = cur.children[element]!! } cur.word = word } } }
0
Kotlin
0
0
8d2060888123915d2ef2ade293e5b12c66fb3a3f
1,802
AlgorithmsProject
Apache License 2.0
src/main/kotlin/d16/D16.kt
MTender
734,007,442
false
{"Kotlin": 108628}
package d16 enum class Direction { LEFT, RIGHT, BELOW, ABOVE } data class Tile( val content: Char, var energized: Boolean = false, val incomingLightDirections: MutableList<Direction> = mutableListOf() ) fun move(contraption: List<List<Tile>>, row: Int, col: Int, from: Direction) { if ( row < 0 || row >= contraption.size || col < 0 || col >= contraption[0].size ) return val tile = contraption[row][col] tile.energized = true if (tile.incomingLightDirections.contains(from)) return tile.incomingLightDirections.add(from) when (tile.content) { '.' -> { when (from) { Direction.LEFT -> move(contraption, row, col + 1, from) Direction.RIGHT -> move(contraption, row, col - 1, from) Direction.BELOW -> move(contraption, row - 1, col, from) Direction.ABOVE -> move(contraption, row + 1, col, from) } } '/' -> { when (from) { Direction.LEFT -> move(contraption, row - 1, col, Direction.BELOW) Direction.RIGHT -> move(contraption, row + 1, col, Direction.ABOVE) Direction.BELOW -> move(contraption, row, col + 1, Direction.LEFT) Direction.ABOVE -> move(contraption, row, col - 1, Direction.RIGHT) } } '\\' -> { when (from) { Direction.LEFT -> move(contraption, row + 1, col, Direction.ABOVE) Direction.RIGHT -> move(contraption, row - 1, col, Direction.BELOW) Direction.BELOW -> move(contraption, row, col - 1, Direction.RIGHT) Direction.ABOVE -> move(contraption, row, col + 1, Direction.LEFT) } } '|' -> { when (from) { Direction.LEFT, Direction.RIGHT -> { move(contraption, row - 1, col, Direction.BELOW) move(contraption, row + 1, col, Direction.ABOVE) } Direction.BELOW -> move(contraption, row - 1, col, from) Direction.ABOVE -> move(contraption, row + 1, col, from) } } '-' -> { when (from) { Direction.LEFT -> move(contraption, row, col + 1, from) Direction.RIGHT -> move(contraption, row, col - 1, from) Direction.BELOW, Direction.ABOVE -> { move(contraption, row, col - 1, Direction.RIGHT) move(contraption, row, col + 1, Direction.LEFT) } } } } } fun parseInput(lines: List<String>): List<List<Tile>> { return lines.map { line -> line.toCharArray().map { Tile(it) } } } fun countEnergized(contraption: List<List<Tile>>): Int { var sum = 0 for (line in contraption) { for (tile in line) { if (tile.energized) sum++ } } return sum }
0
Kotlin
0
0
a6eec4168b4a98b73d4496c9d610854a0165dbeb
2,989
aoc2023-kotlin
MIT License
src/main/kotlin/Model.kt
thomasnield
150,822,564
false
null
import koma.pow import org.apache.commons.math3.distribution.TDistribution import org.nield.kotlinstatistics.sum import org.nield.kotlinstatistics.weightedCoinFlip import java.math.MathContext import java.math.RoundingMode import kotlin.math.exp enum class Solver { ORDINARY_LEAST_SQUARES { // great reference: https://youtu.be/Qa2APhWjQPc override fun solve(points: List<Point>): LineSolution { // convert to BigDecimal for precision fun Int.convert() = toBigDecimal(MathContext(4, RoundingMode.HALF_UP)) fun Double.convert() = toBigDecimal(MathContext(4, RoundingMode.HALF_UP)) // number of samples val n = points.size.convert() // averages of x and y val meanX = points.map { it.x.convert() }.sum() / n val meanY = points.map { it.y.convert() }.sum() / n // calculating m val m = points.map { (it.x.convert() - meanX) * (it.y.convert() - meanY) }.sum() / points.map { (it.x.convert() - meanX).pow(2) }.sum() // calculating b val b = meanY - (m * meanX) return LineSolution(m.toDouble(),b.toDouble(), points).also { currentLine.set(it) } } }, HILL_CLIMBING { override fun solve(points: List<Point>): LineSolution { val scale = 0.1 val tDistribution = TDistribution(3.0) var currentFit = LineSolution(0.0,0.0, points) var bestSumOfSquaredError = Double.MAX_VALUE repeat(24000){ index -> val proposedM = currentFit.m + scale * tDistribution.sample() val proposedB = currentFit.b + scale * tDistribution.sample() val yPredictions = points.map { (proposedM * it.x) + proposedB } val sumOfSquaredError = points.map { it.y }.zip(yPredictions).map { (yActual, yPredicted) -> (yPredicted-yActual).pow(2) }.sum() if (sumOfSquaredError < bestSumOfSquaredError) { bestSumOfSquaredError = sumOfSquaredError currentFit = LineSolution(proposedM, proposedB, points) // only animate every 50 iterations if (index % 500 == 0) currentLine.set(currentFit) } } currentLine.set(currentFit) return currentFit } }, HILL_CLIMBING_80_QUANTILE { override fun solve(points: List<Point>): LineSolution { val scale = 0.1 val underCurveTarget = .80 val tDistribution = TDistribution(3.0) var currentFit = LineSolution(0.0,0.0, points) var bestFit = LineSolution(0.0,0.0, points) var bestFitLoss = Double.MAX_VALUE var bestPctUnderCurve = Double.MAX_VALUE repeat(24000) { index -> val proposedM = currentFit.m + scale * tDistribution.sample() val proposedB = currentFit.b + scale * tDistribution.sample() val yPredictions = points.map { (proposedM * it.x) + proposedB } val pctUnderCurve = points.map { it.y }.zip(yPredictions).count { (yActual, yPredicted) -> yPredicted >= yActual }.toDouble() / points.count().toDouble() val fitLoss = points.map { it.y }.zip(yPredictions).map { (yActual, yPredicted) -> (yPredicted-yActual).pow(2) }.sum() val takeMove = when { bestPctUnderCurve < underCurveTarget && pctUnderCurve > bestPctUnderCurve -> { bestPctUnderCurve = pctUnderCurve bestFit = currentFit true } bestPctUnderCurve >= underCurveTarget && pctUnderCurve >= underCurveTarget && fitLoss < bestFitLoss -> { bestFitLoss = fitLoss bestFit = currentFit true } else -> false } if (takeMove) { currentFit = LineSolution(proposedM, proposedB, points) } // only animate every 500 iterations if (index % 500 == 0 && currentLine.get () != bestFit) currentLine.set(bestFit) } currentLine.set(bestFit) bestFit.apply { println("${ pts.count { evaluate(it.x) >= it.y }}/${pts.count()}") println(bestFit.pctUnderCurve) } return currentFit } }, SIMULATED_ANNEALING{ // https://stats.stackexchange.com/questions/340626/simulated-annealing-for-least-squares-linear-regression // https://stats.stackexchange.com/questions/28946/what-does-the-rta-b-function-do-in-r override fun solve(points: List<Point>): LineSolution { val scale = 0.1 val tDistribution = TDistribution(3.0) var currentFit = LineSolution(0.0,0.0, points) var bestFit = LineSolution(0.0,0.0, points) var bestSumOfSquaredError = Double.MAX_VALUE // kick off temperature from 120.0 down to 0.0 at step -.005 generateSequence(120.0) { it - .005 }.takeWhile { it >= 0.0 } .withIndex() .forEach { (index,temp) -> val proposedM = currentFit.m + scale * tDistribution.sample() val proposedB = currentFit.b + scale * tDistribution.sample() val yPredictions = points.map { (proposedM * it.x) + proposedB } val sumOfSquaredError = points.map { it.y }.zip(yPredictions).map { (yActual, yPredicted) -> (yPredicted-yActual).pow(2) }.sum() if (sumOfSquaredError < bestSumOfSquaredError || weightedCoinFlip(exp((-(sumOfSquaredError - bestSumOfSquaredError)) / temp))) { currentFit = LineSolution(proposedM, proposedB, points) } // only animate every 500 iterations if (index % 500 == 0 && currentLine.get () != bestFit) currentLine.set(bestFit) if (sumOfSquaredError < bestSumOfSquaredError) { bestSumOfSquaredError = sumOfSquaredError bestFit = currentFit } } currentLine.set(bestFit) return currentFit } }, SIMULATED_ANNEALING_80_QUANTILE{ // https://stats.stackexchange.com/questions/340626/simulated-annealing-for-least-squares-linear-regression // https://stats.stackexchange.com/questions/28946/what-does-the-rta-b-function-do-in-r override fun solve(points: List<Point>): LineSolution { val scale = 0.1 val underCurveTarget = .80 val tDistribution = TDistribution(3.0) var currentFit = LineSolution(0.0,0.0, points) var bestFit = LineSolution(0.0,0.0, points) var bestFitLoss = Double.MAX_VALUE var bestPctUnderCurve = Double.MAX_VALUE // kick off temperature from 120.0 down to 0.0 at step -.005 generateSequence(120.0) { it - .005 }.takeWhile { it >= 0.0 } .withIndex() .forEach { (index,temp) -> val proposedM = currentFit.m + scale * tDistribution.sample() val proposedB = currentFit.b + scale * tDistribution.sample() val yPredictions = points.map { (proposedM * it.x) + proposedB } val pctUnderCurve = points.map { it.y }.zip(yPredictions).count { (yActual, yPredicted) -> yPredicted >= yActual }.toDouble() / points.count().toDouble() val fitLoss = points.map { it.y }.zip(yPredictions).map { (yActual, yPredicted) -> (yPredicted-yActual).pow(2) }.sum() val takeMove = when { bestPctUnderCurve < underCurveTarget && pctUnderCurve > bestPctUnderCurve -> { bestPctUnderCurve = pctUnderCurve bestFit = currentFit true } bestPctUnderCurve >= underCurveTarget && pctUnderCurve >= underCurveTarget && fitLoss < bestFitLoss -> { bestFitLoss = fitLoss bestFit = currentFit true } bestPctUnderCurve >= underCurveTarget && pctUnderCurve >= underCurveTarget && fitLoss > bestFitLoss -> weightedCoinFlip(exp((-(fitLoss - bestFitLoss)) / temp)) else -> false } if (takeMove) { currentFit = LineSolution(proposedM, proposedB, points) } if (index % 500 == 0 && currentLine.get () != bestFit) currentLine.set(bestFit) } currentLine.set(bestFit) bestFit.apply { println("${ pts.count { evaluate(it.x) >= it.y }}/${pts.count()}") println(bestFit.pctUnderCurve) } return currentFit } }, GRADIENT_DESCENT { override fun solve(points: List<Point>): LineSolution { val n = points.count().toDouble() // partial derivative with respect to M fun dM(expectedYs: List<Double>) = (-2.0 / n) * points.mapIndexed { i, p -> p.x * (p.y - expectedYs[i]) }.sum() // partial derivative with respect to B fun dB(expectedYs: List<Double>) = (-2.0 / n) * points.mapIndexed { i, p -> p.y - expectedYs[i] }.sum() val learningRate = .00001 var m = 0.0 var b = 0.0 val epochs = 1000000 // epochs is a fancy name for # of iterations repeat(epochs) { epoch -> val yPredictions = points.map { (m * it.x) + b } val dM = dM(yPredictions) val dB = dB(yPredictions) m -= learningRate * dM b -= learningRate * dB // only animate once every 30K iterations if (epoch % 30000 == 0) currentLine.set(LineSolution(m,b, points)) } currentLine.set(LineSolution(m,b, points)) return LineSolution(m, b, points) } }; abstract fun solve(points: List<Point>): LineSolution override fun toString() = name.replace("_", " ") } data class Point(val x: Double, val y: Double) { constructor(x: Int, y: Int): this(x.toDouble(), y.toDouble()) } class LineSolution(val m: Double, val b: Double, val pts: List<Point>) { fun evaluate(x: Double) = (m*x) + b val pctUnderCurve get() = pts.count { evaluate(it.x) >= it.y }.toDouble() / pts.count().toDouble() val loss get() = points.map { (evaluate(it.x) - it.y).pow(2) }.sum() }
0
Kotlin
2
5
26f92910c8528f13caae1477dd2be0af45124b28
11,587
kotlin_linear_regression
Apache License 2.0
2022/src/main/kotlin/Day25.kt
dlew
498,498,097
false
{"Kotlin": 331659, "TypeScript": 60083, "JavaScript": 262}
import kotlin.math.pow object Day25 { fun part1(input: String) = numToSnafu(input.splitNewlines().sumOf(::snafuToNum)) private fun snafuToNum(snafu: String): Long { return snafu .reversed() .withIndex() .sumOf { (index, char) -> 5.0.pow(index).toLong() * snafuCharToNum(char) } } private fun snafuCharToNum(a: Char) = when (a) { '-' -> -1L '=' -> -2L else -> a.digitToInt().toLong() } private fun numToSnafu(n: Long): String { var curr = n var carry = 0 val snafu = mutableListOf<Int>() while (curr != 0L) { var result = carry + (curr % 5).toInt() if (result < 3) { carry = 0 } else { carry = 1 result -= 5 } snafu.add(result) curr /= 5 } if (carry == 1) { snafu.add(1) } return snafu .reversed() .map(::digitToSnafu) .joinToString("") } private fun digitToSnafu(n: Int) = when (n) { -2 -> '=' -1 -> '-' else -> n.digitToChar() } }
0
Kotlin
0
0
6972f6e3addae03ec1090b64fa1dcecac3bc275c
1,040
advent-of-code
MIT License
src/main/kotlin/aoc2018/day10/PointsInTheSky.kt
arnab
75,525,311
false
null
package aoc2018.day10 data class Point(val x: Int, val y: Int, val vX: Int, val vY: Int) { companion object { // Matches "position=< 9, 1> velocity=< 0, 2>" private val dataLineRegex = """position=<\s*(-?\d+),\s*(-?\d+)> velocity=<\s*(-?\d+),\s*(-?\d+)>""".toRegex() fun from(data: String): Point { val (x, y, vX, vY) = dataLineRegex.find(data)!!.destructured return Point(x.toInt(), y.toInt(), vX.toInt(), vY.toInt()) } } fun atTime(t: Int) = Point(x + vX * t, y + vY * t, vX, vY) } object PointsInTheSky { fun findTimeForMostCompactPositons(points: List<Point>, maxTime: Int = 20_000): List<Pair<Int, Int>> { return (0..maxTime).map { t -> val pointsAtTime = points.map { it.atTime(t) } val minX = pointsAtTime.minBy { it.x }!!.x val maxX = pointsAtTime.maxBy { it.x }!!.x val minY = pointsAtTime.minBy { it.y }!!.y val maxY = pointsAtTime.maxBy { it.y }!!.y val spread = maxX - minX + maxY - minY Pair(t, spread) }.sortedBy { it.second }.take(3) } fun printPositions(points: List<Point>, time: Int) { val pointsAtTime = points.map { it.atTime(time) } display(time, pointsAtTime, displayFull = true) } private fun display(t: Int, pointsAtTime: List<Point>, displayFull: Boolean = false) { val minX = pointsAtTime.minBy { it.x }!!.x val maxX = pointsAtTime.maxBy { it.x }!!.x val minY = pointsAtTime.minBy { it.y }!!.y val maxY = pointsAtTime.maxBy { it.y }!!.y val spread = maxX - minX + maxY - minY println("Time: $t, Spread: $spread") if (displayFull) { (minY..maxY).forEach { j -> (minX..maxX).forEach { i -> val pointFound: Point? = pointsAtTime.find { it.x == i && it.y == j } print(if (pointFound == null) " " else "X") } println("") } } } }
0
Kotlin
0
0
1d9f6bc569f361e37ccb461bd564efa3e1fccdbd
2,048
adventofcode
MIT License
src/main/kotlin/ctci/chaptersixteen/ContiguousSequence.kt
amykv
538,632,477
false
{"Kotlin": 169929}
package ctci.chaptersixteen // 16.17 - page 183 // You are given an array of integers (both positive and negative). Find the contiguous sequence with the largest // sum. Return the sum. fun main() { val arr1 = intArrayOf(1, -2, 3, 10, -4, 7, 2, -5) val arr2 = intArrayOf(-2, -3, 4, -1, -2, 1, 5, -3) val arr3 = intArrayOf(-2, 1, -3, 4, -1, 2, 1, -5, 4) assert(maxSubarraySum(arr1) == 18) assert(maxSubarraySum(arr2) == 7) assert(maxSubarraySum(arr3) == 6) } //This function takes an integer array as input and returns the maximum sum of any contiguous subarray in the array. // We initialize two variables, maxSum and currentSum, to the first element of the array. We then loop through the // array, updating currentSum to be the maximum of the current element and the sum of the current element and the // previous subarray, and updating maxSum to be the maximum of the current value of maxSum and the current value // of currentSum. fun maxSubarraySum(arr: IntArray): Int { var maxSum = arr[0] var currentSum = arr[0] for (i in 1 until arr.size) { currentSum = maxOf(arr[i], currentSum + arr[i]) maxSum = maxOf(maxSum, currentSum) } return maxSum } //time complexity of O(n) and a space complexity of O(1).
0
Kotlin
0
2
93365cddc95a2f5c8f2c136e5c18b438b38d915f
1,274
dsa-kotlin
MIT License
archive/406/solve.kt
daniellionel01
435,306,139
false
null
/* === #406 Guessing Game - Project Euler === We are trying to find a hidden number selected from the set of integers {1, 2, ..., n} by asking questions. Each number (question) we ask, we get one of three possible answers: "Your guess is lower than the hidden number" (and you incur a cost of a), or "Your guess is higher than the hidden number" (and you incur a cost of b), or "Yes, that's it!" (and the game ends). Given the value of n, a, and b, an optimal strategy minimizes the total cost for the worst possible case. For example, if n = 5, a = 2, and b = 3, then we may begin by asking "2" as our first question. If we are told that 2 is higher than the hidden number (for a cost of b=3), then we are sure that "1" is the hidden number (for a total cost of 3). If we are told that 2 is lower than the hidden number (for a cost of a=2), then our next question will be "4". If we are told that 4 is higher than the hidden number (for a cost of b=3), then we are sure that "3" is the hidden number (for a total cost of 2+3=5). If we are told that 4 is lower than the hidden number (for a cost of a=2), then we are sure that "5" is the hidden number (for a total cost of 2+2=4). Thus, the worst-case cost achieved by this strategy is 5. It can also be shown that this is the lowest worst-case cost that can be achieved. So, in fact, we have just described an optimal strategy for the given values of n, a, and b. Let $C(n, a, b)$ be the worst-case cost achieved by an optimal strategy for the given values of n, a and b. Here are a few examples: $C(5, 2, 3) = 5$ $C(500, \sqrt 2, \sqrt 3) = 13.22073197\dots$ $C(20000, 5, 7) = 82$ $C(2000000, \sqrt 5, \sqrt 7) = 49.63755955\dots$ Let $F_k$ be the Fibonacci numbers: $F_k=F_{k-1}+F_{k-2}$ with base cases $F_1=F_2= 1$.Find $\displaystyle \sum \limits_{k = 1}^{30} {C \left (10^{12}, \sqrt{k}, \sqrt{F_k} \right )}$, and give your answer rounded to 8 decimal places behind the decimal point. Difficulty rating: 50% */ fun solve(x: Int): Int { return x*2; } fun main() { val a = solve(10); println("solution: $a"); }
0
Kotlin
0
1
1ad6a549a0a420ac04906cfa86d99d8c612056f6
2,080
euler
MIT License
src/main/java/Exercise20.kt
cortinico
317,667,457
false
null
fun main() { val tiles = object {}.javaClass.getResource("input-20.txt").readText().split("\n\n").map { val number = it.split("\n")[0].replace(":", "").replace("Tile ", "").toLong() val top = it.split("\n")[1] val bottom = it.split("\n").last() val (left, right) = it .split("\n") .drop(1) .map { it.toCharArray().let { it.first() to it.last() } } .fold("" to "") { acc, pair -> (acc.first + pair.first) to (acc.second + pair.second) } val body = it.split("\n") .drop(1) .map { it.replace("\n", "") } .map { it.toCharArray() } .toTypedArray() Tile(number, top, bottom, left, right, body) } tiles .filter { tiles.countNeighbor(it) == 2 } .fold(1L) { acc, tile -> acc * tile.number } .also(::println) } fun List<Tile>.countNeighbor( input: Tile, sides: List<String> = listOf(input.left, input.top, input.right, input.bottom) ): Int { return sides .filter { regularSide -> val reversedSide = regularSide.reversed() this.any { it.number != input.number && (it.top == regularSide || it.top == reversedSide || it.bottom == regularSide || it.bottom == reversedSide || it.left == regularSide || it.left == reversedSide || it.right == regularSide || it.right == reversedSide) } } .count() } class Tile( val number: Long, var top: String, var bottom: String, var left: String, var right: String, var body: Array<CharArray> ) { private val n: Int get() = body.size fun rotateRight() { body.rotatedRight() recomputeStrings() } fun rotateLeft() { body.rotatedLeft() recomputeStrings() } fun flipHorizontally() { body.flipHorizontally() recomputeStrings() } fun flipVertically() { body.flipVertically() recomputeStrings() } private fun recomputeStrings() { top = body[0].joinToString("") bottom = body.last().joinToString("") left = body.map { it.first() }.joinToString("") right = body.map { it.last() }.joinToString("") } } fun Array<CharArray>.flipHorizontally() { val n = this.size for (i in 0 until n / 2) { for (j in 0 until n) { val t = this[i][j] this[i][j] = this[n - i - 1][j] this[n - i - 1][j] = t } } } fun Array<CharArray>.flipVertically() { val n = this.size for (i in 0 until n / 2) { for (j in 0 until n) { val t = this[j][i] this[j][i] = this[j][n - i - 1] this[j][n - i - 1] = t } } } fun Array<CharArray>.rotatedRight() { val n = this.size val rotated = Array(n) { CharArray(n) } for (i in 0 until n) { for (j in 0 until n) { rotated[i][j] = this[n - j - 1][i] } } for (i in 0 until n) { for (j in 0 until n) { this[i][j] = rotated[i][j] } } } fun Array<CharArray>.rotatedLeft() { val n = this.size val rotated = Array(n) { CharArray(n) } for (i in 0 until n) { for (j in 0 until n) { rotated[i][j] = this[j][n - i - 1] } } for (i in 0 until n) { for (j in 0 until n) { this[i][j] = rotated[i][j] } } }
1
Kotlin
0
4
a0d980a6253ec210433e2688cfc6df35104aa9df
3,773
adventofcode-2020
MIT License
src/Day06.kt
jamOne-
573,851,509
false
{"Kotlin": 20355}
fun main() { fun searchForMarker(buffer: String, markerLength: Int): Int { val lettersCount = mutableMapOf<Char, Int>() for (i in buffer.indices) { if (i >= markerLength) { val letterToRemove = buffer[i - markerLength] if (lettersCount[letterToRemove] == 1) { lettersCount.remove(letterToRemove) } else { lettersCount[letterToRemove] = lettersCount[letterToRemove]!! - 1 } } val newLetter = buffer[i] lettersCount[newLetter] = lettersCount.getOrDefault(newLetter, 0) + 1 if (lettersCount.keys.size == markerLength) { return i + 1 } } return -1 } fun part1(input: List<String>): Int { return searchForMarker(input[0], 4) } fun part2(input: List<String>): Int { return searchForMarker(input[0], 14) } val testInput = readInput("Day06_test") check(part1(testInput) == 7) check(part2(testInput) == 19) val input = readInput("Day06") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
77795045bc8e800190f00cd2051fe93eebad2aec
1,169
adventofcode2022
Apache License 2.0
src/main/kotlin/solutions/constantTime/iteration2/BoundedMemorizedTaxCalculator.kt
daniel-rusu
669,564,782
false
{"Kotlin": 70755}
package solutions.constantTime.iteration2 import dataModel.base.Money import dataModel.base.Money.Companion.cents import dataModel.base.TaxBracket import dataModel.base.TaxCalculator import solutions.constantTime.iteration1.MemorizedTaxCalculator import solutions.logN.LogNTaxCalculator import dataModel.v2.toAccumulatedBrackets /** * An improved version of [MemorizedTaxCalculator] as it's bounded by the lower bound of the highest tax bracket. All * incomes that are greater than that bound can be computed in constant time without having to memorize them. * * The boundary of the highest tax bracket is expected to be thousands of times less than the max reported income. * However, this is still horribly inefficient. See the iteration 2 writeup for details: * * https://itnext.io/impossible-algorithm-computing-income-tax-in-constant-time-716b3c36c012 */ class BoundedMemorizedTaxCalculator(taxBrackets: List<TaxBracket>) : TaxCalculator { private val highestBracket = taxBrackets.toAccumulatedBrackets().last() private val memorizedIncomeToTaxAmount: Map<Money, Money> init { val taxCalculator = LogNTaxCalculator(taxBrackets) // manually create a hashMap as "associateWith" creates a LinkedHashMap by default which uses more memory memorizedIncomeToTaxAmount = generateSequence(0.cents) { it + 1.cents } .takeWhile { it < highestBracket.from } // create a hashMap as "associateWith" creates a LinkedHashMap by default which uses more memory .associateWithTo(HashMap()) { income -> taxCalculator.computeTax(income) } } override fun computeTax(income: Money): Money { return memorizedIncomeToTaxAmount[income] ?: highestBracket.computeTotalTax(income) } }
0
Kotlin
0
1
166d8bc05c355929ffc5b216755702a77bb05c54
1,768
tax-calculator
MIT License
src/commonTest/kotlin/io/github/arashiyama11/PolynomialTest.kt
arashiyama11
581,833,835
false
{"Kotlin": 69471}
package io.github.arashiyama11 import kotlin.test.Test import kotlin.test.assertEquals class PolynomialTest { @Test fun parseAndToStringTest() { assert(Polynomial("1 + 5 * 2 - 8 / 2"), "1+10-4") assert(Polynomial("1.2+5.4-3.2/2"), "6/5+27/5-8/5") assert(Polynomial("2x^2-5x+ 3x -1"), "2x^2-5x+3x-1") assert(Polynomial("x^2+2x"), "x^2+2x") assert(Polynomial("sin(x)+cos(y)"), "sin(x)+cos(y)") assert(Polynomial("max(min(sin(x),cos(y)),max(1,3))"), "max(min(sin(x),cos(y)),max(1,3))") } @Test fun evaluateTest() { assert(Polynomial("x^2+2x+3x+3x^3").evaluate(), "3x^3+x^2+5x") assert(Polynomial("(x+1)(x+2)").evaluate(), "x^2+3x+2") assert(Polynomial("(x+2)^2(x+1)").evaluate(), "x^3+5x^2+8x+4") assert(Polynomial("(x+2y-z)^2").evaluate(), "x^2+4xy-2xz+4y^2-4yz+z^2") assert( Polynomial("(x+1)(x+2)(x+3)").evaluate(), (Polynomial("x+1") * Polynomial("x+2") * Polynomial("x+3")).evaluate().toString() ) assert(Polynomial("(x+1)(x-2)").evaluate(), "x^2-x-2") assert(Polynomial("xyz^2-xy").evaluate(), "xyz^2-xy") assert(Polynomial("(x+1)(x+y)").evaluate(), "x^2+xy+x+y") assert(Polynomial("a(x^2+2y)").evaluate(), "ax^2+2ay") assert(Polynomial("(x+y)(x-y)").evaluate(), "x^2-y^2") } @Test fun powTest() { assert(Polynomial("x+2").pow(2), "x^2+4x+4") assert(Polynomial("x+1").pow(3), "x^3+3x^2+3x+1") } @Test fun substituteTest() { assert(Polynomial("x^2+x+3").substitute(mapOf(Letter('x') to Rational(1))).evaluate(), "5") assert(Polynomial("(x+1)(x+2)-2").substitute(mapOf(Letter('x') to Rational(1.0))).evaluate(), "4") assert(Polynomial("x^2+y^2").substitute(mapOf(Letter('x') to Letter('y'))).evaluate(), "2y^2") assert(Polynomial("x^2").substitute(mapOf(Letter('x') to Polynomial("x+1"))).evaluate(), "x^2+2x+1") assert( Polynomial("sin(xsin(x))").substitute(mapOf(Letter('x') to Func("cos", listOf(Letter('x'))))).evaluate(), "sin(cos(x)sin(cos(x)))" ) } @Test fun approximationTest() { assert(Polynomial("max(2,3)-min(2,3)").approximation(), "3-2") assert(Polynomial("sin(0)cos(0)-sqrt(4)").approximation(), "-2") } @Test fun divTest() { assert(Polynomial("x^3-4x^2+x+6").divSafe(Polynomial("x-2")), "(x^2-2x-3, 0)") assert(Polynomial("x^2+4x+3").divSafe(Polynomial("x+1")), "(x+3, 0)") assert(Polynomial("(x+2)(x+1)(x+3)").evaluate() / Polynomial("x^2+5x+6"), "x+1") assert(Polynomial("x^2+x+3").divSafe(Polynomial("x+1")), "(x, 3)") assert(Polynomial("x^2+xy+y").divSafe(Polynomial("x+y")), "(x, y)") assert(Polynomial("x^2+xy+y").divSafe(Polynomial("x+y")), "(x, y)") assert(Polynomial("a^2-a-6").divSafe(Polynomial("a-3")), "(2+a, 0)") assert(Polynomial("a^2-a-8").divSafe(Polynomial("a-3")), "(2+a, -2)") assert(Polynomial("2x^2+3x+1").divSafe(Polynomial("x+1/2")), "(2x+2, 0)") assert(Polynomial("(3x+2)(2x+1)").evaluate().divSafe(Polynomial("x+2/3")), "(6x+3, 0)") } @Test fun factorizationTest() { assert(Polynomial("6x^2+7x+2").factorization(), "(2x+1)(3x+2)") assert(Polynomial("3x^2-2x-1").factorization(), "(x-1)(3x+1)") assert(Polynomial("x^3+2x^2-2x-12").factorization(), "(x-2)(x^2+4x+6)") assert(Polynomial("x^3-3x-2").factorization(), "(x+1)^2(x-2)") assert(Polynomial("6x^3+x^2+2x-1").factorization(), "(3x-1)(2x^2+x+1)") assert(Polynomial("2x^4+2x^3-4x^2-16x").factorization(), "2x(x-2)(x^2+3x+4)") assert(Polynomial("2a^2+2ax+ab+bx").factorization(), "(x+a)(b+2a)") assert(Polynomial("(a+b)(b+c)(c+a)").evaluate().factorization(), "(a+b)(c+a)(b+c)") } @Test fun solveTest() { assert(Polynomial("2x-4").solve(), "[2]") assert(Polynomial("2a-4").solve(Letter('a')), "[2]") assert(Polynomial("a+2b").solve(Letter('b')), "[-a/2]") assert(Polynomial("3x+5").solve(), "[-5/3]") assert(Polynomial("x^2+5x+4").solve(), "[-1, -4]") assert(Polynomial("k^2+5k+4").solve(Letter('k')), "[-1, -4]") assert(Polynomial("x^2+4xy+4y^2").solve(Letter('x')), "[-2y, -2y]") assert(Polynomial("x^2+x+5").solve(), "[(-1+isqrt(19))/2, (-1-isqrt(19))/2]") assert(Polynomial("x^2-4").solve(), "[-2, 2]") assert(Polynomial("x^2+3x").solve(), "[0, -3]") assert(Polynomial("(x+1)(x-2)(x+3)").evaluate().solve(), "[-1, 2, -3]") assert(Polynomial("9x(x-a)(x-b)(x-c)").solve(), "[0, a, b, c]") assert(Polynomial("x^3-1").solve(), "[1, (-1+isqrt(3))/2, (-1-isqrt(3))/2]") assert(Polynomial("x^3-6x^2+11x-30").solve(), "[5, (1+isqrt(23))/2, (1-isqrt(23))/2]") } @Test fun calculusTest() { assert(Polynomial("x^2").differential(), "2x") assert(Polynomial("3x^2+5x+1").differential(), "6x+5") assert(Polynomial("(x+1)(x-2)+3").differential(), "2x-1") assert(Polynomial("-a^3-2a+10").differential(Letter('a')), "-3a^2-2") assert(Polynomial("2sin(2x+1)").differential(), "4cos(2x+1)") assert(Polynomial("tan(2x)").differential(), "2/cos(2x)^2") assert(Polynomial("log(x)").differential().evaluate(), "1/x") assert(Polynomial("3sin(3cos(4x))sin(zcos(o)(a-b))").differential(), "-36sin(4x)cos(3cos(4x))sin(zcos(o)(a-b))") assert(Polynomial("sin(x)cos(2x)").differential(), "cos(x)cos(2x)-2sin(x)sin(2x)") assert(Polynomial("3sin(a)/(2a)").differential(Letter('a')), "(6acos(a)-6sin(a))/4a^2") assert(Polynomial("2x^2+4x-1").integral(), "2x^3/3+2x^2-x+C") assert(Polynomial("v+at").integral(Letter('t')), "tv+at^2/2+C") assert(Polynomial("sin(x)").integral(), "-cos(x)+C") assert(Polynomial("2cos(x)y").integral(), "2ysin(x)+C") assert(Polynomial("2/x^3").integral(), "C-1/x^2") assert(Polynomial("2/x").integral(), "2log(x)+C") assert(Polynomial("6x^2+4x+1").integral(from = Rational(0), to = Rational(2)), "26") assert(Polynomial("12y^3+4y+5/y^2").integral(Letter('y'), Rational(-3), Rational(-1)), "-758/3") assert(Polynomial("sin(x)+cos(x)").integral(from = Rational(0), to = Rational(1)), "-cos(1)+sin(1)+cos(0)-sin(0)") } @Test fun functionTest() { assert(Polynomial("log(2)+log(5)").evaluate(), "log(10)") assert(Polynomial("3log(2)+log(5)-2log(3)").evaluate(), "log(40/9)") } private fun assert(a: Any?, b: Any?) = assertEquals(b.toString(), a.toString()) }
0
Kotlin
0
0
c3832fb4248060b55d2a0528ece479ac799002d8
6,269
mojishiki
MIT License
src/main/java/com/barneyb/aoc/aoc2022/day15/BeaconExclusionZone.kt
barneyb
553,291,150
false
{"Kotlin": 184395, "Java": 104225, "HTML": 6307, "JavaScript": 5601, "Shell": 3219, "CSS": 1020}
package com.barneyb.aoc.aoc2022.day15 import com.barneyb.aoc.util.* import com.barneyb.util.HashSet import com.barneyb.util.Rect import com.barneyb.util.Vec2 import kotlin.math.abs import kotlin.math.max import kotlin.text.toInt fun main() { Solver.execute( ::parse, ::countNonBeaconPositionsOnRow, // 5878678 ::distressBeaconTuningFrequency, // 11796491041245 ) } private const val ROW_TO_SCAN = 2_000_000 private const val LOW = 0 private const val HIGH = 4_000_000 internal data class Sensor(val id: Int, val pos: Vec2, val range: Int) { val x get() = pos.x val y get() = pos.y fun inRange(p: Vec2) = pos.getManhattanDistance(p) <= range fun separation(other: Sensor) = pos.getManhattanDistance(other.pos) fun inRangeXsOnRow(row: Int): IntRange { val extra = range - abs(y - row) return if (extra < 0) IntRange.EMPTY else x - extra..x + extra } } typealias Beacon = Vec2 internal data class Model( val sensors: List<Sensor>, val beacons: HashSet<Beacon> ) { private val bounds = sensors.fold( beacons.fold( Rect.EMPTY, Rect::coerceToInclude ) ) { r, s -> r.coerceToInclude(s.pos) } fun draw(bounds: Rect = this.bounds) = buildString { val rowLabelWidth = max( bounds.y1.toString().length, bounds.y2.toString().length, ) append('\n') val skip = abs(bounds.x1 - bounds.x1 / 10 * 10) append(" ".repeat(rowLabelWidth + 1 + skip)) for (x in bounds.x1 + skip..bounds.x2 step 10) { val lbl = x.toString() if (x + 1 + lbl.length > bounds.x2) break append('|') append(lbl.padEnd(9)) } for (y in bounds.yRange) { append('\n') append(y.toString().padStart(rowLabelWidth)) append(' ') for (x in bounds.xRange) { val p = Vec2(x, y) if (beacons.contains(p)) append('B') else { val idx = sensors.indexOfFirst { it.pos == p } if (idx >= 0) append('S') else append('.') } } } } } internal fun parse(input: String) = input.toSlice() .trim() .lines() .withIndex() .map { (i, it) -> parseLine(i, it) } .unzip() .let { (ss, bs) -> Model(ss, HashSet(bs)) } // Sensor at x=2, y=18: closest beacon is at x=-2, y=15 private val RE = Regex( "Sensor at x=(-?\\d+), y=(-?\\d+): closest beacon is at x=(-?\\d+), y=(-?\\d+)" ) internal fun parseLine(idx: Int, input: CharSequence) = RE.matchEntire(input)!!.let { m -> val (sx, sy, bx, by) = m.groupValues .drop(1) // entire match .map(String::toInt) val beacon = Beacon(bx, by) val pos = Vec2(sx, sy) val sensor = Sensor(idx, pos, pos.getManhattanDistance(beacon)) Pair(sensor, beacon) } internal fun countNonBeaconPositionsOnRow( model: Model, row: Int = ROW_TO_SCAN ): Int { val ranges = arrayListOf<IntRange>() fun add(r: IntRange) { val idx = ranges.indexOfFirst { it.overlaps(r) } if (idx < 0) ranges.add(r) else add(ranges.removeAt(idx) + r) } model.sensors.forEach { add(it.inRangeXsOnRow(row)) } return ranges.sumOf(IntRange::size) - model.beacons.count { it.y == row } } internal val Vec2.tuningFrequency get() = x.toLong() * HIGH + y /* <dependency> <groupId>org.choco-solver</groupId> <artifactId>choco-solver</artifactId> <version>4.10.10</version> </dependency> internal fun distressBeaconTuningFrequency( model: Model, lo: Int = LOW, hi: Int = HIGH ): Long { val m = org.chocosolver.solver.Model("Beacon Exclusion Zone") val xVar = m.intVar("x", lo, hi) val yVar = m.intVar("y", lo, hi) // not a beacon for (b in model.beacons) { m.or( xVar.ne(b.x).decompose(), yVar.ne(b.y).decompose(), ) } // not in range of a sensor for (s in model.sensors) { xVar.sub(s.x).abs() .add(yVar.sub(s.y).abs()) .gt(s.range) .post() } println(m.solver.findSolution()) return Vec2(xVar.value, yVar.value).tuningFrequency } */ internal fun distressBeaconTuningFrequency( model: Model, lo: Int = LOW, hi: Int = HIGH ): Long { val lines = mutableListOf<Line>() for ((i, u) in model.sensors.withIndex()) { for (v in model.sensors.drop(i + 1)) { if (u.separation(v) == u.range + v.range + 2) { lines.add( Line.between( u.pos.north(u.range + 1), u.pos.west(u.range + 1), ) ) lines.add( Line.between( u.pos.north(u.range + 1), u.pos.east(u.range + 1), ) ) lines.add( Line.between( u.pos.south(u.range + 1), u.pos.west(u.range + 1), ) ) lines.add( Line.between( u.pos.south(u.range + 1), u.pos.east(u.range + 1), ) ) } } } val bySlope = lines .distinct() .groupBy(Line::slope) val points = HashSet<Vec2>() bySlope[1]!!.forEach { a -> bySlope[-1]!!.forEach { b -> points.add(a.intersection(b)) } } return points .filter { it.x >= lo && it.y >= lo } .filter { it.x <= hi && it.y <= hi } .filter { !model.beacons.contains(it) } .first { p -> model.sensors.none { it.inRange(p) } } .tuningFrequency } internal data class Line(val slope: Int, val intercept: Int) { companion object { fun between(p1: Vec2, p2: Vec2) = ((p2.y - p1.y) / (p2.x - p1.x)).let { slope -> Line(slope, p1.y - slope * p1.x) } } fun intersection(other: Line) = ((other.intercept + intercept) / 2).let { y -> Vec2(y - intercept, y) } }
0
Kotlin
0
0
8b5956164ff0be79a27f68ef09a9e7171cc91995
6,591
aoc-2022
MIT License
src/main/kotlin/be/tabs_spaces/advent2021/days/Day06.kt
janvryck
433,393,768
false
{"Kotlin": 58803}
package be.tabs_spaces.advent2021.days class Day06 : Day(6) { companion object { private const val HAS_SPAWNED = 6 } private val numberOfFishByAge = groupFishByAge() override fun partOne() = iterateSpawnCycle(numberOfFishByAge, 80).values.sum() override fun partTwo() = iterateSpawnCycle(numberOfFishByAge, 256).values.sum() private fun groupFishByAge(): Map<Int, Long> { val fishAtStart = inputString.split(",").map { it.toInt() } return (0..8).associateWith { day -> fishAtStart.count { it == day }.toLong() } } private fun iterateSpawnCycle(numberOfFishByAge: Map<Int, Long>, iterations: Int): Map<Int, Long> { return if (iterations > 1) iterateSpawnCycle(cycle(numberOfFishByAge), iterations.dec()) else cycle(numberOfFishByAge) } private fun cycle(numberOfFishByAge: Map<Int, Long>): Map<Int, Long> { val spawned = numberOfFishByAge[0] ?: 0 val agedFish = numberOfFishByAge .map { entry -> this.progressAge(entry, spawned) } .filterNot { it.first < 0 } .toMutableList() agedFish.add(8 to spawned) return agedFish.toMap() } private fun progressAge(entry: Map.Entry<Int, Long>, spawned: Long): Pair<Int, Long> { val age = entry.key.dec() val amount = when (age) { HAS_SPAWNED -> entry.value + spawned else -> entry.value } return age to amount } }
0
Kotlin
0
0
f6c8dc0cf28abfa7f610ffb69ffe837ba14bafa9
1,499
advent-2021
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/colinodell/advent2016/Day14.kt
colinodell
495,627,767
false
{"Kotlin": 80872}
package com.colinodell.advent2016 class Day14(private val salt: String) { fun solvePart1(): Int = solve(0) fun solvePart2(): Int = solve(2016) private fun solve(stretchFactor: Int) = generateHashes(1, stretchFactor) .map { PossibleKey(it, findTripleDigit(it.hash)) } .filter { it.tripleChar != null } .filter { futureHashContainsFiveRepeats(it.tripleChar!!, it.hash.index, stretchFactor) } .take(64) .last() .hash.index private var hashCache = mapOf<Int, String>() private fun generateHashes(startingAt: Int = 1, stretchFactor: Int) = sequence { var i = startingAt while (true) { if (!hashCache.containsKey(i)) { var newHash = md5(salt + i) // Apply an additional stretchFactor times for (j in 1..stretchFactor) { newHash = md5(newHash) } // Cache the new hash along with the most-recent 1,000 items hashCache = hashCache.filterNot { it.key < i - 1000 }.plus(Pair(i, newHash)) } yield(IndexedHash(i, hashCache[i]!!)) i++ } } private fun futureHashContainsFiveRepeats(match: Char, iteration: Int, stretchFactor: Int) = generateHashes(iteration + 1, stretchFactor) .take(1000) .any { it.hash.contains(match.toString().repeat(5)) } private val threeDigits = Regex("([0-9a-f])\\1\\1") private fun findTripleDigit(hash: String) = threeDigits.find(hash)?.groupValues?.get(1)?.first() private data class IndexedHash(val index: Int, val hash: String) private data class PossibleKey(val hash: IndexedHash, val tripleChar: Char?) }
0
Kotlin
0
0
8a387ddc60025a74ace8d4bc874310f4fbee1b65
1,775
advent-2016
Apache License 2.0
src/Day10.kt
sbaumeister
572,855,566
false
{"Kotlin": 38905}
fun main() { fun part1(input: List<String>): Int { var registerX = 1 var instructionPointer = 0 var instructionCyclesLeftToComplete = 0 var cycle = 0 var signalStrenghtSum = 0 while (instructionPointer < input.size) { cycle++ val instruction = input[instructionPointer].take(4) if (instructionCyclesLeftToComplete == 0) { when (instruction) { "addx" -> instructionCyclesLeftToComplete = 2 "noop" -> instructionCyclesLeftToComplete = 1 } } if (cycle == 20 || (cycle > 20 && ((cycle - 20) % 40 == 0))) { signalStrenghtSum += cycle * registerX } instructionCyclesLeftToComplete-- if (instructionCyclesLeftToComplete == 0) { when (instruction) { "addx" -> registerX += input[instructionPointer].substring(5).toInt() } instructionPointer++ } } return signalStrenghtSum } fun part2(input: List<String>): String { var registerX = 1 var instructionPointer = 0 var instructionCyclesLeftToComplete = 0 var cycle = 0 val chars = mutableListOf<Char>() while (instructionPointer < input.size) { cycle++ val instruction = input[instructionPointer].take(4) if (instructionCyclesLeftToComplete == 0) { when (instruction) { "addx" -> instructionCyclesLeftToComplete = 2 "noop" -> instructionCyclesLeftToComplete = 1 } } val pos = (cycle - 1) % 40 if (pos >= registerX - 1 && pos <= registerX + 1) { chars.add('#') } else { chars.add('.') } if (cycle % 40 == 0) { chars.add('\n') } instructionCyclesLeftToComplete-- if (instructionCyclesLeftToComplete == 0) { when (instruction) { "addx" -> registerX += input[instructionPointer].substring(5).toInt() } instructionPointer++ } } return chars.joinToString("") } val testInput = readInput("Day10_test") val part1 = part1(testInput) check(part1 == 13140) print(part2(testInput)) val input = readInput("Day10") println(part1(input)) print(part2(input)) }
0
Kotlin
0
0
e3afbe3f4c2dc9ece1da7cf176ae0f8dce872a84
2,579
advent-of-code-2022
Apache License 2.0
app/src/main/kotlin/com/resurtm/aoc2023/day19/Parse.kt
resurtm
726,078,755
false
{"Kotlin": 119665}
package com.resurtm.aoc2023.day19 internal fun readInput(testCase: String): Input { val reader = object {}.javaClass.getResourceAsStream(testCase)?.bufferedReader() ?: throw Exception("Cannot read an input, probably an invalid input provided") val rules = mutableMapOf<String, Rule>() val workflows = mutableListOf<Workflow>() while (true) { val rawLine = (reader.readLine() ?: break).trim() if (rawLine.isEmpty()) continue if (rawLine.firstOrNull() == '{') workflows.add(parseWorkflow(rawLine)) else if (rawLine.firstOrNull() != '{') { val rule = parseRule(rawLine) rules[rule.name] = rule } } return Input(rules, workflows) } internal fun parseRule(line: String): Rule { if (line.trim().trim('{', '}').isEmpty()) throw Exception("An invalid rule passed for parse") val parts0 = line.split('{').map { it.trim().trim('}') } val parts1 = parts0[1].split(',').map { it.trim() } return Rule(name = parts0[0], conditions = parts1.map { parseCondition(it) }) } private fun parseCondition(rawCondition: String): Condition { val parts = rawCondition.split(CompOp.Less.value, CompOp.Greater.value, ':') return when (parts.size) { 1 -> Condition.Short(nextRule = parts[0]) 3 -> Condition.Full( token = Token.fromValue(parts[0][0]), compOp = CompOp.fromRawCondition(rawCondition), compVal = parts[1].toLong(), nextRule = parts[2], ) else -> throw Exception("An invalid rule passed for parse") } } internal fun parseWorkflow(line: String): Workflow { if (line.trim().trim('{', '}').isEmpty() || line.trim()[0] != '{') throw Exception("An invalid workflow passed for parse") val parts0 = line.trim('{', '}').split(',').map { it.trim() } val entries = mutableMapOf<Token, Long>() parts0.forEach { val parts1 = it.split('=') entries[Token.fromValue(parts1[0][0])] = parts1[1].toLong() } return Workflow(entries = entries) }
0
Kotlin
0
0
fb8da6c246b0e2ffadb046401502f945a82cfed9
2,108
advent-of-code-2023
MIT License
facebook/y2019/round1/a.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package facebook.y2019.round1 private const val INF = Int.MAX_VALUE / 3 private fun solve(): String { val (n, m) = readInts() val edgesInput = List(m) { readInts() } val graph = Array(n) { IntArray(n) { INF } } for ((aInput, bInput, d) in edgesInput) { val a = aInput - 1 val b = bInput - 1 graph[a][b] = d graph[b][a] = d } val e = graph.copy() for (k in 0 until n) { for (i in 0 until n) { for (j in 0 until n) { e[i][j] = minOf(e[i][j], e[i][k] + e[k][j]) if ((e[i][j] < graph[i][j]) && (graph[i][j] < INF)) { return "Impossible" } } } } return "$m\n${edgesInput.joinToString("\n") { it.joinToString(" ") }}" } fun main() = repeat(readInt()) { println("Case #${it + 1}: ${solve()}") } private fun Array<IntArray>.copy() = Array(size) { get(it).clone() } private val isOnlineJudge = System.getProperty("ONLINE_JUDGE") == "true" @Suppress("unused") private val stdStreams = (false to false).apply { if (!isOnlineJudge) { print(java.io.File(".").canonicalPath) if (!first) System.setIn(java.io.File("input.txt").inputStream()) if (!second) System.setOut(java.io.PrintStream("output.txt")) }} private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,318
competitions
The Unlicense
src/main/kotlin/wk269/Problem2.kt
yvelianyk
405,919,452
false
{"Kotlin": 147854, "Java": 610}
package wk269 // fun main() { val result = Problem2().getAverages(intArrayOf(7, 4, 3, 9, 1, 8, 5, 2, 6), 3) // val result = Problem2().getAverages(intArr, 10) println(result) } class Problem2 { fun getAverages(nums: IntArray, k: Int): IntArray { if (k * 2 > nums.size - 1) return IntArray(nums.size) { -1 } var initSum: Long = 0 val result = IntArray(nums.size) for (index in 0..k * 2) { initSum += nums[index] } result[k] = (initSum / (k * 2 + 1)).toInt() for (index in nums.indices) { val prevIndex = index - 1 - k val nextIndex = index + k if (index == k) continue if (prevIndex < 0 || nextIndex >= nums.size) { result[index] = -1 continue } val prev = nums[prevIndex] val next = nums[nextIndex] initSum = initSum - prev + next result[index] = (initSum / (k * 2 + 1)).toInt() } return result } }
0
Kotlin
0
0
780d6597d0f29154b3c2fb7850a8b1b8c7ee4bcd
1,047
leetcode-kotlin
MIT License
core/compiler.common/src/org/jetbrains/kotlin/contracts/description/EventOccurrencesRange.kt
JetBrains
3,432,266
false
{"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80}
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.contracts.description import kotlin.math.max import kotlin.math.min enum class EventOccurrencesRange(private val left: Int, private val right: Int) { ZERO(0, 0), // 0..0 AT_MOST_ONCE(0, 1), // 0..1 EXACTLY_ONCE(1, 1), // 1..1 AT_LEAST_ONCE(1, 3), // 1..* MORE_THAN_ONCE(2, 3), // 2..* UNKNOWN(0, 3); // 0..* companion object { private fun fromRange(left: Int, right: Int): EventOccurrencesRange = when (min(left, 2) to min(right, 3)) { 0 to 0 -> ZERO 0 to 1 -> AT_MOST_ONCE 0 to 2 -> UNKNOWN 0 to 3 -> UNKNOWN 1 to 1 -> EXACTLY_ONCE 1 to 2 -> AT_LEAST_ONCE 1 to 3 -> AT_LEAST_ONCE 2 to 2 -> MORE_THAN_ONCE 2 to 3 -> MORE_THAN_ONCE 3 to 3 -> MORE_THAN_ONCE else -> throw IllegalArgumentException() } fun or(x: EventOccurrencesRange, y: EventOccurrencesRange): EventOccurrencesRange = fromRange(min(x.left, y.left), max(x.right, y.right)) fun plus(x: EventOccurrencesRange, y: EventOccurrencesRange): EventOccurrencesRange = fromRange(x.left + y.left, x.right + y.right) } infix fun or(other: EventOccurrencesRange): EventOccurrencesRange = Companion.or(this, other) operator fun plus(other: EventOccurrencesRange): EventOccurrencesRange = Companion.plus(this, other) operator fun contains(other: EventOccurrencesRange): Boolean = left <= other.left && other.right <= right } fun EventOccurrencesRange.isDefinitelyVisited(): Boolean = this == EventOccurrencesRange.EXACTLY_ONCE || this == EventOccurrencesRange.AT_LEAST_ONCE || this == EventOccurrencesRange.MORE_THAN_ONCE fun EventOccurrencesRange.canBeVisited(): Boolean = this != EventOccurrencesRange.ZERO fun EventOccurrencesRange.canBeRevisited(): Boolean = this == EventOccurrencesRange.UNKNOWN || this == EventOccurrencesRange.AT_LEAST_ONCE || this == EventOccurrencesRange.MORE_THAN_ONCE val EventOccurrencesRange?.isInPlace: Boolean get() = this != null
166
Kotlin
5,771
46,772
bef0946ab7e5acd5b24b971eca532c43c8eba750
2,326
kotlin
Apache License 2.0
src/main/kotlin/de/tek/adventofcode/y2022/day14/RegolithReservoir.kt
Thumas
576,671,911
false
{"Kotlin": 192328}
package de.tek.adventofcode.y2022.day14 import de.tek.adventofcode.y2022.util.math.* import de.tek.adventofcode.y2022.util.readInputLines enum class Material(private val visualization: Char) { AIR('.'), SAND('o'), ROCK('#'); override fun toString() = visualization.toString() } class Cave(private val sandSource: Point, rockPositions: Set<Point>) { private val grid: GridWithPoints<Material, Material> init { val array = buildArrayFrom(rockPositions) grid = Grid.withPoints(array) } private fun buildArrayFrom(rockPositions: Set<Point>): Array<Array<Material>> { val givenPositions = rockPositions + sandSource val lowestPosition = givenPositions.maxOfOrNull { it.y } ?: throw IllegalArgumentException("No rock positions given, so the sand flows unobstructed.") val rightmostPosition = givenPositions.maxOfOrNull { it.x }!! val array = Array(lowestPosition + 1) { y -> Array(rightmostPosition + 1) { x -> if (Point(x, y) in rockPositions) Material.ROCK else Material.AIR } } return array } fun runSimulation(): Int { var sandCounter = -1 do { if (!sandSource.isFree()) { return sandCounter + 1 } produceSand() sandCounter++ val sandPath = generateSequence(sandSource) { oldPosition -> moveSand(oldPosition) } val firstPositionOutsideTheGrid = sandPath.filter { !(it isIn grid) }.firstOrNull() } while (firstPositionOutsideTheGrid == null) return sandCounter } private fun produceSand() { if (sandSource.isFree()) { grid[sandSource] = Material.SAND } else { throw SandOverflowException("Sand source at $sandSource is blocked by ${grid[sandSource]}, cannot produce sand.") } } private fun Point.isFree(): Boolean = grid[this].let { it == null || it == Material.AIR } private fun moveSand(position: Point): Point? { val newPosition = determineNewPosition(position) ?: return null updateMaterial(position, newPosition) return newPosition } private fun determineNewPosition(position: Point) = // gravity is pointing in the opposite direction because of array index order sequenceOf(Vector(0, 1), Vector(-1, 1), Vector(1, 1)) .map { position + it } .filter { it.isFree() } .firstOrNull() private fun updateMaterial( position: Point, newPosition: Point ) { grid[position] = Material.AIR if (newPosition isIn grid) { grid[newPosition] = Material.SAND } } override fun toString(): String { val pointsToVisualize = grid.iterator().asSequence().filter { it.value != Material.AIR }.map { it.point }.toList() + sandSource val lowerLeftCorner = pointsToVisualize.lowerLeftCorner()!! val upperRightCorner = pointsToVisualize.upperRightCorner()!! val diagonal = upperRightCorner - lowerLeftCorner val correctToOrigin = ORIGIN - lowerLeftCorner val array = Array(diagonal.y + 1) { y -> Array(diagonal.x + 1) { x -> val positionInGrid = Point(x, y) - correctToOrigin if (positionInGrid == sandSource) { '+' } else { val value = grid.at(positionInGrid)?.value ?: throw IllegalStateException("Position ($x,$y) is outside of the grid.") value.toString()[0] } } } return array.joinToString("\n") { it.joinToString("") } } } class SandOverflowException(s: String) : Exception(s) fun main() { val input = readInputLines(Cave::class) println("${part1(input)} units of sand come to rest before sand starts flowing into the abyss below.") println("${part2(input)} units of sand come to rest before the sand clogs its source.") } fun part1(input: List<String>): Int { val rockPositions = parseRockPositions(input) val cave = Cave(Point(500, 0), rockPositions) return cave.runSimulation().also { println(cave) } } fun part2(input: List<String>): Int { val sandSource = Point(500, 0) val rockPositions = parseRockPositions(input) val ground = determineGroundPositions(sandSource, rockPositions) val cave = Cave(sandSource, rockPositions + ground) return cave.runSimulation().also { println(cave) } } private fun parseRockPositions(input: List<String>) = input.flatMap(::parseLineSegments).flatMap(AxisParallelLineSegment::toListOfPoints).toSet() private fun determineGroundPositions( sandSource: Point, rockPositions: Set<Point> ): List<Point> { val heightOfSandSource = heightOfSandSource(rockPositions) // sand can move at most its fall height to the left and to the right val ground = AxisParallelLineSegment( sandSource + Vector(heightOfSandSource, heightOfSandSource), sandSource + Vector(-heightOfSandSource, heightOfSandSource) ) return ground.toListOfPoints() } private fun parseLineSegments(string: String): List<AxisParallelLineSegment> { val nodes = string.split(" -> ").map(::parseCommaSeparatedInts).map { Point(it[0], it[1]) } val nodePairs = nodes.zip(nodes.drop(1)) return nodePairs.map(::AxisParallelLineSegment) } private fun parseCommaSeparatedInts(it: String) = it.split(",").take(2).map(String::toInt) private fun heightOfSandSource(rockPositions: Set<Point>): Int { val lowestScanPosition = (rockPositions + Point(500, 0)).maxOf { it.y } return lowestScanPosition + 2 }
0
Kotlin
0
0
551069a21a45690c80c8d96bce3bb095b5982bf0
5,750
advent-of-code-2022
Apache License 2.0