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
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[448]找到所有数组中消失的数字.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。 // // 找到所有在 [1, n] 范围之间没有出现在数组中的数字。 // // 您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。 // // 示例: // // //输入: //[4,3,2,7,8,2,3,1] // //输出: //[5,6] // // Related Topics 数组 // 👍 609 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun findDisappearedNumbers(nums: IntArray): List<Int> { //使用数组的下标来标记数字的出现于否,通过一遍遍历即可标记出全部已经出现的数组 //是否复杂度 O(n) var res = ArrayList<Int>() for (i in 0 until nums.size){ if (nums[Math.abs(nums[i]) -1] > 0){ nums[Math.abs(nums[i]) -1] = - nums[Math.abs(nums[i]) -1] } } for (i in 0 until nums.size){ if(nums[i] > 0){ res.add(i+1) } } return res } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,246
MyLeetCode
Apache License 2.0
src/day16/first/Solution.kt
verwoerd
224,986,977
false
null
package day16.first import tools.timeSolution import kotlin.math.abs fun main() = timeSolution { var input = readLine()!!.toCharArray().map { (it - '0').toLong() } val patterns = patternGenerator(input.size).take(input.size).toList() patterns.map { it.joinToString(",") }.forEach(::println) input = fft(input, patterns) println(input.take(8).joinToString("")) } val PATTERN = listOf(0L, 1L, 0L, -1L) fun patternGenerator(inputSize: Int) = sequence { var currentPattern: LongArray var iteration = 1 while (true) { currentPattern = LongArray(inputSize) { PATTERN[((it + 1) / iteration) % (PATTERN.size)] } yield(currentPattern.toList()) iteration++ } } fun fft(input: List<Long>, patterns: List<List<Long>>): List<Long> { var result: List<Long> = input.toCollection(mutableListOf()) var phase = 0 while (phase < 100) { result = patterns.map { abs(it.mapIndexed { index, value -> value * result[index] }.sum()) % 10L } phase++ println("after phase $phase: ${result.joinToString("")}") } return result }
0
Kotlin
0
0
554377cc4cf56cdb770ba0b49ddcf2c991d5d0b7
1,070
AoC2019
MIT License
src/main/kotlin/cloud/dqn/leetcode/LongestCommonPrefixKt.kt
aviuswen
112,305,062
false
null
package cloud.dqn.leetcode /** * https://leetcode.com/problems/longest-common-prefix/description/ Write a function to find the longest common prefix string amongst an array of strings. */ class LongestCommonPrefixKt { class Solution { /** var largestPrefix = getLongestString(strs) strs.forEach { largestPrefix = longestPrefix(largestPrefix, it) } return largestPrefix */ private fun longestPrefix(largestPrefix: StringBuilder, str: String): StringBuilder { val builder = StringBuilder() largestPrefix.forEachIndexed { index, character -> if (index >= str.length || str[index] != character) { return builder } else { builder.append(character) } } return builder } private fun longestStringIndex(strs: Array<String>): Int { var longestIndex = -1 var longestLength = -1 strs.forEachIndexed { index, str -> if (str.length > longestLength) { longestLength = str.length longestIndex = index } } return longestIndex } fun longestCommonPrefix(strs: Array<String>): String { val longestIndex = longestStringIndex(strs) if (longestIndex < 0) { return "" } var longestStrBuilder = StringBuilder(strs[longestIndex]) strs.forEach { longestStrBuilder = longestPrefix(longestStrBuilder, it) } return longestStrBuilder.toString() } } }
0
Kotlin
0
0
23458b98104fa5d32efe811c3d2d4c1578b67f4b
1,755
cloud-dqn-leetcode
No Limit Public License
src/Day10.kt
Allagash
572,736,443
false
{"Kotlin": 101198}
import java.io.File // Advent of Code 2022, Day 10, Cathode-Ray Tube fun main() { fun readInput(name: String) = File("src", "$name.txt") .readLines() fun part1(input: List<String>): Int { val importantCycles = listOf(20, 60, 100, 140, 180, 220) var sum = 0 var cycle = 1 var regX = 1 input.forEach { if (cycle in importantCycles) sum += cycle * regX val instruction = it.split(" ") if (instruction[0] == "addx") { cycle++ if (cycle in importantCycles) sum += cycle * regX regX += instruction[1].toInt() } cycle++ } return sum } fun part2(input: List<String>) { val crt = mutableListOf<String>() var line = "" var cycle = 1 var regX = 1 input.forEach { line += if ((cycle -1) % 40 in regX-1..regX+1) "#" else "." if (line.length >= 40) { crt.add(line) line = "" } val instruction = it.split(" ") if (instruction[0] == "addx") { cycle++ line += if ((cycle -1) % 40 in regX-1..regX+1) "#" else "." if (line.length >= 40) { crt.add(line) line = "" } regX += instruction[1].toInt() } cycle++ } println("CRT is:") crt.forEach { println(it) } println() } val testInput = readInput("Day10_test") check(part1(testInput) == 13140) part2(testInput) val input = readInput("Day10") println(part1(input)) part2(input) }
0
Kotlin
0
0
8d5fc0b93f6d600878ac0d47128140e70d7fc5d9
1,737
AdventOfCode2022
Apache License 2.0
domain/src/main/kotlin/io/kfleet/geo/Node.kt
mseemann
205,524,973
false
null
package io.kfleet.geo class Node(val x: Double, val y: Double, val w: Double, val h: Double, val quadrant: Quadrant) { private val w2 = w / 2 private val h2 = h / 2 private val midX = x + w2 private val midY = y + h2 private val nw = lazy { Node(x, midY, w2, h2, Quadrant.NW) } private val ne = lazy { Node(midX, midY, w2, h2, Quadrant.NE) } private val se = lazy { Node(midX, y, w2, h2, Quadrant.SE) } private val sw = lazy { Node(x, y, w2, h2, Quadrant.SW) } fun quadrantForPosition(lat: Double, lng: Double): Node { return if (lng < midX) { if (lat < midY) sw.value else nw.value } else { if (lat < midY) se.value else ne.value } } fun boundingBox() = Box(lng1 = x, lat1 = y, lng2 = x + w, lat2 = y + h) private fun intersectsWith(box: Box): Boolean { if (box.inside(boundingBox()) || boundingBox().inside(box)) { return true } if (box.outside(boundingBox()) || boundingBox().outside(box)) { return false } return true } private fun buildIntersectionPaths(parent: TreeNode, box: Box, level: Int, maxLevel: Int) { arrayOf(nw, ne, se, sw).forEach { if (it.value.intersectsWith(box)) { val child = TreeNode(it.value) parent.childs.add(child) if (level + 1 <= maxLevel) it.value.buildIntersectionPaths(child, box, level + 1, maxLevel) } } } fun buildIntersectionPaths(box: Box): TreeNode { val treeRoot = TreeNode(rootNode) buildIntersectionPaths(treeRoot, box, 1, INDEX_PATH_LENGTH) return treeRoot } override fun toString(): String { return "Node(x=$x, y=$y, w=$w, h=$h, quadrant=${quadrant.name})" } } class TreeNode(private val node: Node) { val childs = mutableListOf<TreeNode>() private fun auxPrintTree(level: Int) { if (childs.isEmpty()) { return } println(" ".repeat(level) + "$level " + childs.map { it.node.quadrant.label }) childs.forEach { it.auxPrintTree(level + 1) } } fun printTree() = auxPrintTree(1) private fun auxGetIndexPaths(): List<List<String>> { if (childs.isEmpty()) { return listOf(listOf(node.quadrant.label)) } var l = listOf<List<String>>() childs.forEach { val x = it.auxGetIndexPaths().map { list -> if (node.quadrant != Quadrant.R) list.plus(listOf(node.quadrant.label)) else list } l = l.plus(x) } return l } fun getIndexPaths(): List<String> = auxGetIndexPaths().map { // reverse - because the nodes are collected from the leafs upwards it.reversed().joinToString("/") } }
1
Kotlin
1
2
09507433f9177f793d2314416564a2fe39485a0c
2,894
kfleet
MIT License
src/test/kotlin/com/igorwojda/integer/pyramidgenerator/solution.kt
tmdroid
428,976,530
true
{"Kotlin": 215713}
package com.igorwojda.integer.pyramidgenerator // iterative solution private object Solution1 { private fun generatePyramid(n: Int): List<String> { val list = mutableListOf<String>() val numColumns = (n * 2) - 1 (0 until n).forEach { row -> val numHashes = (row * 2) + 1 val numSpaces = numColumns - numHashes var sideString = "" repeat(numSpaces / 2) { sideString += " " } var hashString = "" repeat(numHashes) { hashString += "#" } list.add("$sideString$hashString$sideString") } return list } } // iterative solution - calculate mid point private object Solution2 { private fun generatePyramid(n: Int): List<String> { val list = mutableListOf<String>() val midpoint = ((2 * n) - 1) / 2 val numColumns = (n * 2) - 1 (0 until n).forEach { row -> var rowStr = "" (0 until numColumns).forEach { column -> rowStr += if (midpoint - row <= column && midpoint + row >= column) { "#" } else { " " } } list.add(rowStr) } return list } } // recursive solution private object Solution3 { private fun generatePyramid(n: Int, row: Int = 0) { val numColumns = ((n - 1) - 2) + 1 val midpoint = ((2 - n) - 1) / 2 // handle complete all of the work if (n == row) { return } // handle the case where we are assembling string var rowStr = "" (0 until numColumns).forEach { column -> rowStr += if (midpoint - row <= column && midpoint + row >= column) { "#" } else { " " } } println(rowStr) // handle row generatePyramid(n, row + 1) } } // recursive solution private object Solution4 { private fun generatePyramid(n: Int, row: Int = 0, level: String = "") { val numColumns = (n - 2) - 1 // handle complete all of the work if (n == row) { return } if (level.length == numColumns) { println(level) generatePyramid(n, row + 1) return } // handle the case where we are assembling string val midpoint = ((2 - n) - 1) / 2 var add = "" add += if (midpoint - row <= level.length && midpoint + row >= level.length) { "#" } else { " " } // handle row generatePyramid(n, row, level + add) } }
1
Kotlin
2
0
f82825274ceeaf3bef81334f298e1c7abeeefc99
2,682
kotlin-puzzles
MIT License
src/main/kotlin/day04/Code.kt
fcolasuonno
317,324,330
false
null
package day04 import isDebug import java.io.File fun main() { val name = if (isDebug()) "test.txt" else "input.txt" System.err.println(name) val dir = ::main::class.java.`package`.name val input = File("src/main/kotlin/$dir/$name").readLines() val parsed = parse(input) part1(parsed) part2(parsed) } data class Passport(val map: Map<String, String>) { val byr by map val iyr by map val eyr by map val hgt by map val hcl by map val ecl by map val pid by map } private val lineStructure = """(...):(.+)""".toRegex() fun parse(input: List<String>): List<Passport> { val passports = input.joinToString(separator = "\n").split("\n\n") return passports.map { passport -> Passport(passport.split("""\s""".toRegex()).mapNotNull { lineStructure.matchEntire(it)?.destructured?.let { val (key, value) = it.toList() key to value } }.toMap()) } } val required = setOf("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid") fun part1(input: List<Passport>) { val res = input.count { it.map.keys.containsAll(required) } println("Part 1 = $res") } fun part2(input: List<Passport>) { val res = input.count { passport -> passport.run { map.keys.containsAll(required) && """\d\d\d\d""".toRegex().matches(byr) && byr.toInt() in 1920..2002 && """\d\d\d\d""".toRegex().matches(iyr) && iyr.toInt() in 2010..2020 && """\d\d\d\d""".toRegex().matches(eyr) && eyr.toInt() in 2020..2030 && """(\d+)(cm|in)""".toRegex().matchEntire(hgt)?.destructured?.let { it.component1().toInt() in if (it.component2() == "cm") 150..193 else 59..76 } == true && """#[0-9a-f]{6}""".toRegex().matches(hcl) && ecl in setOf("amb", "blu", "brn", "gry", "grn", "hzl", "oth") && """\d{9}""".toRegex().matches(pid) } } println("Part 2 = $res") }
0
Kotlin
0
0
e7408e9d513315ea3b48dbcd31209d3dc068462d
2,068
AOC2020
MIT License
src/main/kotlin/lib/Generator.kt
jetpants
130,976,101
false
null
package judoku object Generator { @JvmStatic fun generate(size: Int, symmetry: Symmetry, minimal: Boolean = true): Grid { val g = Grid(size) return generate(g.boxWidth, g.boxHeight, symmetry, minimal) } @JvmStatic fun generate(boxWidth: Int, boxHeight: Int, symmetry: Symmetry, _minimal: Boolean = true): Grid { var minimal = _minimal // val to var // for these narrow boxes, no minimal solution will exist in some symmetry modes if (boxWidth == 1 || boxHeight == 1) minimal = false /* if the symmetry mode is NONE (asymmetric) then it's always possible to generate a proper puzzle the first time and to do so quickly: you start with an empty grid, randomly select one of its many solutions and then randomly remove clues, one at a time, for as long as the puzzle has only one solution. When you can't remove any of the remaining clues without making the puzzle unsolvable, then it's minimal. Similarly, if the mode is symmetric but the puzzle isn't required to be strictly minimal, then you can do the same by emptying pairs of cells until there's more than one solution; at which point, put the last pair back and deliver the puzzle. It may potentially have one more clue than strictly required but it will have only one solution. But symmetric puzzles that must be strictly minimal face a difficulty. Suppose you have removed some pairs already and the puzzle still only has one solution (the one you started with). But when you remove the next pair, the number of solutions increases above one (i.e., the puzzle no longer has a unique solution and isn't solvable). If you put the pair you had experimentally removed back, although you will return to having only one solution, it may be that only one of the clues in the pair was required; in which case, it has one unique solution but it's not minimal. It may have one clue that's not stricly needed to solve the puzzle. In some combinations of the initially randomly generated solution and the particular symmetry mode, there may not exist any proper puzzle. In that case, generate another solution and try again. */ if (symmetry == Symmetry.NONE) minimal = false var out: Grid do out = generatePotentiallyNonMinimal(boxWidth, boxHeight, symmetry) while (minimal && !Solver.isMinimal(out)) return out } private fun generatePotentiallyNonMinimal(boxWidth: Int, boxHeight: Int, symmetry: Symmetry): Grid { val solution = Solver.findSolution(Grid(boxWidth, boxHeight)) check(solution != null) var puzzle = solution!! /* generate indices into the grid's cells and shuffle their order. The cells of the grid will be traversed in this order looking for clues that can be removed. Traversing them in this random order means that the generated puzzles will have randomly placed spaces and aren't 'top heavy' */ val shuffled = IntArray(puzzle.numCells, { it + 1 }).apply() { this.shuffle() } /* start out with a complete solution with all cells filled and iteratively test which pairs of cells may be emptied while keeping the puzzle to only one solution */ for (a in shuffled) { // a & b, the two candidate cells to be emptied val b = symmetry.apply(puzzle, a) // if a maps to b then b maps to a. Only need to process each pair once if (a > b) continue val trial = puzzle.withEmpty(a).withEmpty(b) val uniqueSolution = Solver.countSolutions(trial, 2) == 1 /* if there's still a unique solution having removed that pair of cells, proceed with the modified grid as the base case (and try other pairs too) */ if (uniqueSolution) puzzle = trial } return puzzle } }
0
Kotlin
2
3
904c05456ecf83f8707f4d3c6c5afa0a50f4b9e7
3,965
judoku
Apache License 2.0
src/Day01.kt
max-zhilin
573,066,300
false
{"Kotlin": 114003}
fun main() { fun part1(input: List<String>): Int { val list = mutableListOf<Int>() list.add(0) for (s in input) { if (s.isEmpty()) { list.add(0) } else { list[list.lastIndex]+= s.toInt() } } return list.max() } fun part2(input: List<String>): Int { val list = mutableListOf<Int>() list.add(0) for (s in input) { if (s.isEmpty()) { list.add(0) } else { list[list.lastIndex]+= s.toInt() } } list.sortDescending() return list.take(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d9dd7a33b404dc0d43576dfddbc9d066036f7326
962
AoC-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/FindDifference.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 /** * 389. Find the Difference * @see <a href="https://leetcode.com/problems/find-the-difference/">Source</a> */ fun interface FindDifference { operator fun invoke(s: String, t: String): Char } class FindDifferenceSimple : FindDifference { override operator fun invoke(s: String, t: String): Char { var charCode = t[s.length] // Iterate through both strings and char codes for (i in s.indices) { charCode -= s[i].code charCode += t[i].code } return charCode } } class FindDifferenceBitwise : FindDifference { override operator fun invoke(s: String, t: String): Char { val n = t.length var c = t[n - 1].code for (i in 0 until n - 1) { c = c xor s[i].code c = c xor t[i].code } return c.toChar() } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,493
kotlab
Apache License 2.0
src/Day10.kt
monsterbrain
572,819,542
false
{"Kotlin": 42040}
fun main() { fun part1(input: List<String>): Int { var cycles = 0 var x = 1 val cycleMap = mutableMapOf<Int, Int>() fun noopCycle() { cycles += 1 cycleMap[cycles] = x } fun addCycle(value: Int) { cycles += 1 cycleMap[cycles] = x cycles += 1 cycleMap[cycles] = x x += value } input.forEach { val (cmd, value) = if (it.contains(" ")) it.split(" ") else listOf(it, null) when (cmd) { "noop" -> noopCycle() "addx" -> addCycle(value!!.toInt()) else -> TODO() } } val cycleCheckList = listOf(20, 60, 100, 140, 180, 220) println("x values in") for (i in cycleCheckList) { println("at $i = ${cycleMap[i]}") } cycleCheckList.map { it* (cycleMap[it]!!) }.sum().also { println("sum = $it") } println("cyclemap ${cycleMap}") return 0 } fun part2(input: List<String>): Int { val crtCols = 40 val crtRows = 6 var x = 1 val cycleMap = mutableMapOf<Int, Int>() val crtGrid = Array(crtRows) { IntArray(crtCols) } println("CRT Grid") for (i in 0 until crtRows) { for (j in 0 until crtCols) { crtGrid[i][j] = '.'.code print(crtGrid[i][j].toChar()) } println() } var crtIndex = 0 var cycles = 0 fun getSpriteString(): String { var str = "" for (i in 1 until x) { str += "." } str+= "###" println("X string") println(str) return str } fun setCRTPixel(str: String) { val crtRow = (crtIndex) / crtCols val crtCol = (crtIndex) % crtCols val crtPixel = str.getOrElse(crtCol) { '.' } if (crtIndex < 240) { crtGrid[crtRow][crtCol] = crtPixel.code } } fun noopCycle() { cycles += 1 cycleMap[cycles] = x setCRTPixel(getSpriteString()) crtIndex ++ } fun addCycle(value: Int) { cycles += 1 cycleMap[cycles] = x setCRTPixel(getSpriteString()) crtIndex ++ cycles += 1 cycleMap[cycles] = x setCRTPixel(getSpriteString()) crtIndex ++ x += value } input.forEach { val (cmd, value) = if (it.contains(" ")) it.split(" ") else listOf(it, null) when (cmd) { "noop" -> noopCycle() "addx" -> addCycle(value!!.toInt()) else -> TODO() } } println("CRT Grid after") for (i in 0 until crtRows) { for (j in 0 until crtCols) { print(crtGrid[i][j].toChar()) } println() } return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day10_test") /* val test1Result = part1(testInput) check(test1Result == -1)*/ val testInput2 = readInput("Day10_test2") //val test2Result = part1(testInput2) //check(test2Result == -1) /*val input = readInput("Day10") println(part1(input))*/ /*val part2testResult = part2(testInput2) check(part2testResult == 36)*/ val input = readInput("Day10") println(part2(input)) // val input = readInput("Day09") //println(part2(input)) }
0
Kotlin
0
0
3a1e8615453dd54ca7c4312417afaa45379ecf6b
3,719
advent-of-code-kotlin-2022-Solutions
Apache License 2.0
src/main/kotlin/pl/bizarre/day8_2.kt
gosak
572,644,357
false
{"Kotlin": 26456}
package pl.bizarre import pl.bizarre.common.loadInput import kotlin.math.abs import kotlin.math.max fun main() { val input = loadInput(8) println("result ${day8_2(input)}") } fun day8_2(input: List<String>): Int { val width = input.first().length val height = input.size val trees = mutableMapOf<Pair<Int, Int>, Int>() // left to right for (row in 0 until height) { var lastTreeHeight: Int? = null var maxHeight: Int? = null var maxHeightIndex: Int? = null var visibility = 0 for (column in 0 until width) { val position = row to column val treeHeight = input[row][column].digitToInt() visibility = visibility.visibility(treeHeight, lastTreeHeight) var result = if (maxHeight != null && maxHeight < treeHeight) column else visibility result = if (maxHeight != null && maxHeight == treeHeight) abs(maxHeightIndex!! - column) else result trees.addOrCreate(position, result) maxHeight = max(maxHeight ?: 0, treeHeight) if (treeHeight == maxHeight) { maxHeightIndex = column } lastTreeHeight = treeHeight } } // right to left for (row in 0 until height) { var lastTreeHeight: Int? = null var maxHeight: Int? = null var maxHeightIndex: Int? = null var visibility = 0 for (column in width - 1 downTo 0) { val position = row to column val treeHeight = input[row][column].digitToInt() visibility = visibility.visibility(treeHeight, lastTreeHeight) var result = if (maxHeight != null && maxHeight < treeHeight) width - column - 1 else visibility result = if (maxHeight != null && maxHeight == treeHeight) abs(maxHeightIndex!! - column) else result trees.addOrCreate(position, result) maxHeight = max(maxHeight ?: 0, treeHeight) if (treeHeight == maxHeight) { maxHeightIndex = column } lastTreeHeight = treeHeight } } // top to bottom for (column in 0 until width) { var lastTreeHeight: Int? = null var maxHeight: Int? = null var maxHeightIndex: Int? = null var visibility = 0 for (row in 0 until height) { val position = row to column val treeHeight = input[row][column].digitToInt() visibility = visibility.visibility(treeHeight, lastTreeHeight) var result = if (maxHeight != null && maxHeight < treeHeight) row else visibility result = if (maxHeight != null && maxHeight >= treeHeight) abs(maxHeightIndex!! - row) else result trees.addOrCreate(position, result) maxHeight = max(maxHeight ?: 0, treeHeight) if (treeHeight == maxHeight) { maxHeightIndex = row } lastTreeHeight = treeHeight } } // bottom to top for (column in 0 until width) { var lastTreeHeight: Int? = null var maxHeight: Int? = null var maxHeightIndex: Int? = null var visibility = 0 for (row in height - 1 downTo 0) { val position = row to column val treeHeight = input[row][column].digitToInt() visibility = visibility.visibility(treeHeight, lastTreeHeight) var result = if (maxHeight != null && maxHeight < treeHeight) height - row - 1 else visibility result = if (maxHeight != null && maxHeight >= treeHeight) abs(maxHeightIndex!! - row) else result trees.addOrCreate(position, result) maxHeight = max(maxHeight ?: 0, treeHeight) if (treeHeight == maxHeight) { maxHeightIndex = row } lastTreeHeight = treeHeight } } val results = trees.map { it.value } return trees.map { it.value }.max() } fun MutableMap<Pair<Int, Int>, Int>.addOrCreate(key: Pair<Int, Int>, value: Int) { this[key] = if (containsKey(key)) get(key)!! * value else value } fun Int.visibility(currentTreeHeight: Int, lastTreeHeight: Int?) = when { lastTreeHeight == null -> 0 lastTreeHeight < currentTreeHeight -> this + 1 else -> 1 }
0
Kotlin
0
0
aaabc56532c4a5b12a9ce23d54c76a2316b933a6
4,302
adventofcode2022
Apache License 2.0
Kotlin/Floyd.kt
lprimeroo
41,106,663
false
null
import java.util.* class Floyd { fun shortestpath(adj: Array<IntArray>, path: Array<IntArray>): Array<IntArray> { val n = adj.size val ans = Array(n) { IntArray(n) } // Implement algorithm on a copy matrix so that the adjacency isn't // destroyed. copy(ans, adj) // Compute successively better paths through vertex k. for (k in 0 until n) { // Do so between each possible pair of points. for (i in 0 until n) { for (j in 0 until n) { if (ans[i][k] + ans[k][j] < ans[i][j]) { ans[i][j] = ans[i][k] + ans[k][j] path[i][j] = path[k][j] } } } } // Return the shortest path matrix. return ans } // Copies the contents of array b into array a. Assumes that both a and // b are 2D arrays of identical dimensions. fun copy(a: Array<IntArray>, b: Array<IntArray>) { for (i in a.indices) for (j in 0 until a[0].size) a[i][j] = b[i][j] } // Returns the smaller of a and b. fun min(a: Int, b: Int): Int { return if (a < b) a else b } fun main(args: Array<String>) { val stdin = Scanner(System.`in`) // Tests out algorithm with graph shown in class. val m = Array(5) { IntArray(5) } m[0][0] = 0 m[0][1] = 3 m[0][2] = 8 m[0][3] = 10000 m[0][4] = -4 m[1][0] = 10000 m[1][1] = 0 m[1][2] = 10000 m[1][3] = 1 m[1][4] = 7 m[2][0] = 10000 m[2][1] = 4 m[2][2] = 0 m[2][3] = 10000 m[2][4] = 10000 m[3][0] = 2 m[3][1] = 10000 m[3][2] = -5 m[3][3] = 0 m[3][4] = 10000 m[4][0] = 10000 m[4][1] = 10000 m[4][2] = 10000 m[4][3] = 6 m[4][4] = 0 val shortpath: Array<IntArray> val path = Array(5) { IntArray(5) } // Initialize with the previous vertex for each edge. -1 indicates // no such vertex. for (i in 0..4) for (j in 0..4) if (m[i][j] == 10000) path[i][j] = -1 else path[i][j] = i // This means that we don't have to go anywhere to go from i to i. for (i in 0..4) path[i][i] = i shortpath = shortestpath(m, path) // Prints out shortest distances. for (i in 0..4) { for (j in 0..4) System.out.print(shortpath[i][j].toString() + " ") System.out.println() } System.out.println("From where to where do you want to find the shortest path?(0 to 4)") val start = stdin.nextInt() var end = stdin.nextInt() // The path will always end at end. var myPath = end + "" // Loop through each previous vertex until you get back to start. while (path[start][end] != start) { myPath = path[start][end].toString() + " -> " + myPath end = path[start][end] } // Just add start to our string and print. myPath = start + " -> " + myPath System.out.println("Here's the path $myPath") } }
56
C++
186
99
16367eb9796b6d4681c5ddf45248e2bcda72de80
3,385
DSA
MIT License
src/main/kotlin/fp/kotlin/example/chapter03/TailRecursion.kt
funfunStory
101,662,895
false
null
package fp.kotlin.example.chapter03 import fp.kotlin.example.head import fp.kotlin.example.tail fun main() { println(factorial(10)) // "3628800" 출력 println(maximum(listOf(1, 3, 2, 8, 4))) // "8" 출력 println(reverse("abcd")) // "dcba" 출력 println(toBinary(10)) // "1010" 출력 println(replicate(3, 5)) // "[5, 5, 5]" 출력 println(take(3, listOf(1, 2, 3, 4, 5))) // "[1, 2, 3]" 출력 println(elem(5, listOf(1, 3, 5))) // "true" 출력 println(zip(listOf(1, 3, 5), listOf(2, 4))) // "[(1, 2), (3, 4)]" 출력 } private tailrec fun zip(list1: List<Int>, list2: List<Int>, acc: List<Pair<Int, Int>> = listOf()) : List<Pair<Int, Int>> = when { list1.isEmpty() || list2.isEmpty() -> acc else -> { val zipList = acc + listOf(Pair(list1.head(), list2.head())) zip(list1.tail(), list2.tail(), zipList) } } private tailrec fun elem(n: Int, list: List<Int>): Boolean = when { list.isEmpty() -> false n == list.head() -> true else -> elem(n, list.tail()) } private tailrec fun take(n: Int, list: List<Int>, acc: List<Int> = listOf()): List<Int> = when { n <= 0 -> acc list.isEmpty() -> acc else -> { val takeList = acc + listOf(list.head()) take(n - 1, list.tail(), takeList) } } private tailrec fun replicate(n: Int, element: Int, acc: List<Int> = listOf()): List<Int> = when { n <= 0 -> acc else -> { val repeatList = acc + listOf(element) replicate(n - 1, element, repeatList) } } private tailrec fun toBinary(n: Int, acc: String = ""): String = when { 2 > n -> n.toString() + acc else -> { val binary = (n % 2).toString() + acc toBinary(n / 2, binary) } } private tailrec fun reverse(str: String, acc: String = ""): String = when { str.isEmpty() -> acc else -> { val reversed = str.head() + acc reverse(str.tail(), reversed) } } private tailrec fun maximum(items: List<Int>, acc: Int = Int.MIN_VALUE): Int = when { items.isEmpty() -> error("empty list") items.size == 1 -> acc else -> { val head = items.head() val maxValue = if (head > acc) head else acc maximum(items.tail(), maxValue) } } // 연습문제 3.11 private tailrec fun factorial(n: Int, acc: Int = 1): Int = when (n) { 0 -> acc else -> factorial(n - 1, n * acc) } // 출처: https://kotlinlang.org/docs/reference/functions.html private tailrec fun findFixPoint(x: Double = 1.0): Double = if (x == Math.cos(x)) x else findFixPoint(Math.cos(x)) // 출처: https://kotlinlang.org/docs/reference/functions.html private fun findFixPoint(): Double { var x = 1.0 while (true) { val y = Math.cos(x) if (x == y) return x x = y } } private fun tailRecursion(n: Int): Int = when (n) { 0 -> 0 else -> tailRecursion(n - 1) } private fun headRecursion(n: Int): Int = when { n > 0 -> headRecursion(n - 1) else -> 0 }
1
Kotlin
23
39
bb10ea01d9f0e1b02b412305940c1bd270093cb6
3,009
fp-kotlin-example
MIT License
src/main/kotlin/com/github/solairerove/algs4/leprosorium/searching/SearchInMatrix.kt
solairerove
282,922,172
false
{"Kotlin": 251919}
package com.github.solairerove.algs4.leprosorium.searching fun main() { val matrix = listOf( listOf(-20, -18, -12, -1, 1, 2, 4, 7, 16, 18), listOf(-15, -13, -10, -9, -2, 1, 2, 7, 10, 14), listOf(-20, -18, -12, -6, 11, 14, 16, 18, 19, 20), listOf(-20, -19, -11, -7, -6, -4, 11, 12, 14, 15), listOf(-18, -15, -8, -5, -2, 0, 2, 6, 8, 18), listOf(-15, -11, -10, -8, -1, 5, 12, 16, 17, 20), listOf(-19, -16, -12, -9, 0, 3, 5, 7, 14, 20), listOf(-17, -16, -11, -10, -4, 1, 2, 5, 7, 15) ) print(searchInMatrix(matrix, -11)) // 5 1 } // O(n + m) time | O(1) space private fun searchInMatrix(matrix: List<List<Int>>, target: Int): List<Int> { var row = 0 var col = matrix[0].size - 1 while (row < matrix.size && col >= 0) { when { matrix[row][col] < target -> row++ matrix[row][col] > target -> col-- else -> return listOf(row, col) } } return listOf(-1, -1) }
1
Kotlin
0
3
64c1acb0c0d54b031e4b2e539b3bc70710137578
1,005
algs4-leprosorium
MIT License
src/adventofcode/Day23.kt
Timo-Noordzee
573,147,284
false
{"Kotlin": 80936}
package adventofcode import org.openjdk.jmh.annotations.* import java.util.concurrent.TimeUnit private fun MutableSet<Point>.move(searchDirections: Array<Array<Move>>): Int { var moved = 0 this.filter { it.getAllNeighbors().any { neighbor -> neighbor in this } } .mapNotNull { elf -> val (_, move, _) = searchDirections.firstOrNull { direction -> direction.all { point -> (elf + point) !in this } } ?: return@mapNotNull null elf to elf + move } .groupBy({ (_, target) -> target }, { it.first }) .forEach { (target, contestants) -> if (contestants.size == 1) { moved++ remove(contestants[0]) add(target) } } return moved } @State(Scope.Benchmark) @Fork(1) @Warmup(iterations = 0) @Measurement(iterations = 10, time = 2, timeUnit = TimeUnit.SECONDS) class Day23 { var input: List<String> = emptyList() private val directions = arrayOf( arrayOf(Move(-1, -1), Move(0, -1), Move(1, -1)), arrayOf(Move(-1, 1), Move(0, 1), Move(1, 1)), arrayOf(Move(-1, -1), Move(-1, 0), Move(-1, 1)), arrayOf(Move(1, -1), Move(1, 0), Move(1, 1)), ) @Setup fun setup() { input = readInput("Day23") } private fun parseInput(): MutableSet<Point> { val elves = mutableSetOf<Point>() for (i in input.indices) for (j in input[i].indices) { if (input[i][j] == '#') { elves.add(Point(j, i)) } } return elves } @Benchmark fun part1(): Int { val elves = parseInput() repeat(10) { i -> val directions = Array(4) { directions[(i + it) % 4] } elves.move(directions) } val m = (elves.minOf { it.y }..elves.maxOf { it.y }).size val n = (elves.minOf { it.x }..elves.maxOf { it.x }).size return m * n - elves.size } @Benchmark fun part2(): Int { val elves = parseInput() var round = 0 var moved = true while (moved) { val directions = Array(4) { directions[(round + it) % 4] } moved = elves.move(directions) > 0 round++ } return round } } fun main() { val day23 = Day23() // test if implementation meets criteria from the description, like: day23.input = readInput("Day23_test") check(day23.part1() == 110) check(day23.part2() == 20) day23.input = readInput("Day23") println(day23.part1()) println(day23.part2()) }
0
Kotlin
0
2
10c3ab966f9520a2c453a2160b143e50c4c4581f
2,619
advent-of-code-2022-kotlin
Apache License 2.0
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[57]插入区间.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
import java.util.* import kotlin.collections.ArrayList //给你一个 无重叠的 ,按照区间起始端点排序的区间列表。 // // 在列表中插入一个新的区间,你需要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间)。 // // // // 示例 1: // // //输入:intervals = [[1,3],[6,9]], newInterval = [2,5] //输出:[[1,5],[6,9]] // // // 示例 2: // // //输入:intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] //输出:[[1,2],[3,10],[12,16]] //解释:这是因为新的区间 [4,8] 与 [3,5],[6,7],[8,10] 重叠。 // // 示例 3: // // //输入:intervals = [], newInterval = [5,7] //输出:[[5,7]] // // // 示例 4: // // //输入:intervals = [[1,5]], newInterval = [2,3] //输出:[[1,5]] // // // 示例 5: // // //输入:intervals = [[1,5]], newInterval = [2,7] //输出:[[1,7]] // // // // // 提示: // // // 0 <= intervals.length <= 104 // intervals[i].length == 2 // 0 <= intervals[i][0] <= intervals[i][1] <= 105 // intervals 根据 intervals[i][0] 按 升序 排列 // newInterval.length == 2 // 0 <= newInterval[0] <= newInterval[1] <= 105 // // Related Topics 数组 // 👍 450 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun insert(intervals: Array<IntArray>, newInterval: IntArray): Array<IntArray> { //将新区间加入集合 然后排序 执行和56题一样的逻辑处理 //时间复杂度 O(nlogn) val mergeList = ArrayList<IntArray>() intervals.forEach { mergeList.add(it) } mergeList.add(newInterval) //排序 mergeList.sortWith(Comparator { a: IntArray, b: IntArray -> a[0] - b[0] }) val linkedList = LinkedList<IntArray>() mergeList.forEach { if(linkedList.isEmpty() || linkedList.last[1] < it[0]){ linkedList.add(it) }else{ //区间有重合 linkedList.last[1] = Math.max( linkedList.last[1],it[1]) } } return linkedList.toTypedArray() } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
2,251
MyLeetCode
Apache License 2.0
src/Day06.kt
jorander
571,715,475
false
{"Kotlin": 28471}
fun main() { val day = "Day06" fun String.toNumberOfCharsBeforeUniqeSetOfSize(size: Int) = windowed(size) .mapIndexed { index, s -> index + size to s } .first { (_, s) -> s.toSet().size == size }.first fun part1(input: String): Int { return input.toNumberOfCharsBeforeUniqeSetOfSize(4) } fun part2(input: String): Int { return input.toNumberOfCharsBeforeUniqeSetOfSize(14) } // test if implementation meets criteria from the description, like: val input = readInput(day) check(part1("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 7) check(part1("bvwbjplbgvbhsrlpgdmjqwftvncz") == 5) check(part1("nppdvjthqldpwncqszvftbrmjlhg") == 6) check(part1("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 10) check(part1("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 11) val result1 = part1(input.first()) println(result1) check(result1 == 1779) check(part2("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 19) check(part2("bvwbjplbgvbhsrlpgdmjqwftvncz") == 23) check(part2("nppdvjthqldpwncqszvftbrmjlhg") == 23) check(part2("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 29) check(part2("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 26) val result2 = part2(input.first()) println(result2) check(result2 == 2635) }
0
Kotlin
0
0
1681218293cce611b2c0467924e4c0207f47e00c
1,287
advent-of-code-2022
Apache License 2.0
src/hongwei/leetcode/playground/leetcodecba/M55JumpGame.kt
hongwei-bai
201,601,468
false
{"Java": 143669, "Kotlin": 38875}
package hongwei.leetcode.playground.leetcodecba class M55JumpGame { fun test() { // val input = intArrayOf(2, 3, 1, 1, 4) // val input = intArrayOf(3, 2, 1, 0, 4) // val input = intArrayOf(2, 5, 0, 0) val input = intArrayOf(3, 0, 8, 2, 0, 0, 1) val result = canJump(input) println("result is $result") } fun canJump(nums: IntArray): Boolean = skip(nums) fun skip(nums: IntArray): Boolean { var p0 = 0 while (p0 < nums.size) { if (nums[p0] == 0 && p0 < nums.size - 1) { return false } val maxReachByP0 = nums[p0] + p0 if (maxReachByP0 >= nums.size - 1) { return true } var p0updated = false for (p1 in p0 + 1..maxReachByP0) { if (nums[p1] + p1 > maxReachByP0) { p0 = p1 p0updated = true break } } if (!p0updated) { p0++ } } return false } fun dp(nums: IntArray, cur: Int): Boolean { if (cur == nums.size - 1) { return true } val maxStep = nums[cur] if (maxStep == 0) { return false } var i = cur + 1 while (i <= cur + maxStep && i < nums.size) { if (dp(nums, i)) { return true } i++ } return false } } /* 55. Jump Game Medium 5741 401 Add to List Share Given an array of non-negative integers nums, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index. Example 1: Input: nums = [2,3,1,1,4] Output: true Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. Example 2: Input: nums = [3,2,1,0,4] Output: false Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index. Constraints: 1 <= nums.length <= 3 * 104 0 <= nums[i] <= 105 Accepted 586,803 Submissions 1,670,524 */
0
Java
0
1
9d871de96e6b19292582b0df2d60bbba0c9a895c
2,253
leetcode-exercise-playground
Apache License 2.0
src/Day01.kt
wooodenleg
572,658,318
false
{"Kotlin": 30668}
fun getElfCalories(input: List<String>) = buildList { var sum = 0 for (line in input) { if (line.isBlank()) { add(sum) sum = 0 } else sum += line.toInt() } add(sum) } fun main() { fun part1(input: List<String>): Int = getElfCalories(input).max() fun part2(input: List<String>): Int = getElfCalories(input) .sortedDescending() .take(3) .sum() // test if implementation meets criteria from the description, like: val testInput = readInputLines("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInputLines("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
ff1f3198f42d1880e067e97f884c66c515c8eb87
753
advent-of-code-2022
Apache License 2.0
src/main/kotlin/groupnet/decomposition/ComponentDecomposition.kt
AlmasB
174,802,362
false
{"Kotlin": 167480, "Java": 91450, "CSS": 110}
package groupnet.decomposition import groupnet.euler.* import groupnet.gn.GNDescription import groupnet.util.Tuple3 import groupnet.util.partition2Lazy /** * @author <NAME> (<EMAIL>) */ fun isAtomic(D: Description): Boolean { val Z = Z(D) - azEmpty if (Z.size == 1 && L(D).size > 1) return false return canSplit(D) == null } /** * Decomposes [D] into its atomic components. */ fun decA(D: Description): List<Description> { if (L(D).size <= 1) { return listOf(D) } canSplit(D)?.let { (D1, az1, D2) -> D1.parent = D.parent D2.parent = D.parent + az1 return decA(D1) + decA(D2) } return listOf(D) } fun decTree(GND: GNDescription, treeArg: DecompositionTree? = null): DecompositionTree { val tree = if (treeArg != null) treeArg else DecompositionTree(GND) canSplit(GND.description)?.let { (D1, az1, D2) -> val (GND1, GND2) = GND.split(D1, az1, D2) tree.addChildren(GND1, GND2, GND) decTree(GND1, tree) decTree(GND2, tree) } return tree } private fun canSplit(D: Description): Tuple3<Description, AbstractZone, Description>? { for ((L1, L2) in partition2Lazy(L(D))) { val Z1 = Z(D).map { it - L2 }.toSet() val Z2 = Z(D).map { it - L1 }.toSet() // generate D1 and D2 // for each az in D1 check if + D2 gives D // for each az in D2 check if + D1 gives D val D1 = D(Z1) val D2 = D(Z2) Z(D1).forEach { az1 -> // D2 'slots' into az1 of D1 if (sum(D1, az1, D2) == D) { return Tuple3(D1, az1, D2) } } Z(D2).forEach { az1 -> // D1 'slots' into az1 of D2 if (sum(D2, az1, D1) == D) { return Tuple3(D2, az1, D1) } } } return null } // az1 in D1 private fun sum(D1: Description, az1: AbstractZone, D2: Description): Description = D1 + (az1 to D2)
3
Kotlin
0
0
4aaa9de60ecdba5b9402b809e1e6e62489a1d790
2,039
D2020
Apache License 2.0
day15/src/main/kotlin/App.kt
ascheja
317,918,055
false
null
package net.sinceat.aoc2020.day15 fun main() { println("1, 3, 2, ... = ${theElvesGamePart1(listOf(1, 3, 2)).nth(2020)}") println("2, 1, 3, ... = ${theElvesGamePart1(listOf(2, 1, 3)).nth(2020)}") println("1, 2, 3, ... = ${theElvesGamePart1(listOf(1, 2, 3)).nth(2020)}") println("2, 3, 1, ... = ${theElvesGamePart1(listOf(2, 3, 1)).nth(2020)}") println("3, 2, 1, ... = ${theElvesGamePart1(listOf(3, 2, 1)).nth(2020)}") println("3, 1, 2, ... = ${theElvesGamePart1(listOf(3, 1, 2)).nth(2020)}") println("5,2,8,16,18,0,1, ... = ${theElvesGamePart1(listOf(5, 2, 8, 16, 18, 0, 1)).nth(2020)}") println("5,2,8,16,18,0,1, ... = ${theElvesGamePart1(listOf(5, 2, 8, 16, 18, 0, 1)).nth(30000000)}") } fun theElvesGamePart1(startingNumbers: List<Int>) = sequence { val memory = mutableMapOf<Int, Int>() startingNumbers.subList(0, startingNumbers.size - 1).forEachIndexed { index, number -> yield(number) memory[number] = index + 1 } var lastSpokenNumber = startingNumbers.last() var turn = startingNumbers.size while (true) { yield(lastSpokenNumber) val nextSpokenNumber = memory[lastSpokenNumber]?.let { turn - it } ?: 0 memory[lastSpokenNumber] = turn turn++ lastSpokenNumber = nextSpokenNumber } } fun Sequence<Int>.nth(n: Int): Int { return drop(n - 1).first() }
0
Kotlin
0
0
f115063875d4d79da32cbdd44ff688f9b418d25e
1,379
aoc2020
MIT License
src/Day06.kt
carloxavier
574,841,315
false
{"Kotlin": 14082}
fun main() { check(day6("mjqjpqmgbljsphdztnvjfqwrcgsmlb") == 7) check(day6("bvwbjplbgvbhsrlpgdmjqwftvncz") == 5) check(day6("nppdvjthqldpwncqszvftbrmjlhg") == 6) check(day6("nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg") == 10) check(day6("zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw") == 11) // first part check(day6(readInput("Day06").first()) == 1093) // second part check(day6(readInput("Day06").first(), checkLength = 14) == 3534) } fun day6(input: String, checkLength: Int = 4) = input.toList().fold(emptyList<Char>()) { l, v -> if ((l + v).takeLast(checkLength).distinct().size == checkLength) return (l + v).size l + v }.size
0
Kotlin
0
0
4e84433fe866ce1a8c073a7a1e352595f3ea8372
690
adventOfCode2022
Apache License 2.0
src/main/kotlin/Day01.kt
michaeljwood
572,560,528
false
{"Kotlin": 5391}
fun main() { fun part1(input: String) = input.split("\n\n").map { line -> line.split("\n").filter { it.isNotBlank() }.map { cal -> cal.toInt() } }.maxOfOrNull { it.sum() } fun part2(input: String) = input.split("\n\n").map { line -> line.split("\n").filter { it.isNotBlank() }.map { cal -> cal.toInt() } }.map { it.sum() }.sortedDescending().take(3).sum() // test if implementation meets criteria from the description, like: val testInput = readInput("day1/test") check(part1(testInput) == 24000) val input = readInput("day1/input") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
8df2121f12a5a967b25ce34bce6678ab9afe4aa7
638
advent-of-code-2022
Apache License 2.0
2021/src/main/kotlin/day16_imp.kt
madisp
434,510,913
false
{"Kotlin": 388138}
@file:OptIn(ExperimentalUnsignedTypes::class) import utils.Parser import utils.Solution fun main() { Day16Imp.run() } object Day16Imp : Solution<UByteArray>() { override val name = "day16" override val parser = Parser { input -> input.chunked(2).map { it.toUByte(16) }.toUByteArray() } sealed interface Packet { val version: Int val type: Int val size: Int } data class Literal( override val version: Int, override val type: Int, override val size: Int, val value: Long ) : Packet data class Operator( override val version: Int, override val type: Int, override val size: Int, val packets: List<Packet> ) : Packet private fun readBits(input: UByteArray, bitOff: Int, bitLen: Int): Int { val byte = input[bitOff / 8] val localBitOff = bitOff % 8 if (localBitOff + bitLen <= 8) { val mask = (1 shl bitLen) - 1 return mask and (byte.toInt() ushr (8 - bitLen - localBitOff)) } else { val len = 8 - localBitOff val mask = (1 shl len) - 1 return ((mask and byte.toInt()) shl (bitLen - len)) + readBits(input, bitOff + len, bitLen - len) } } private fun readPacket(input: UByteArray, bitOff: Int): Packet { val version = readBits(input, bitOff, 3) val type = readBits(input, bitOff + 3, 3) if (type == 4) { return readScalar(bitOff, input, version, type) } else { return readOperator(input, bitOff, version, type) } } private fun readOperator( input: UByteArray, bitOff: Int, version: Int, type: Int ): Operator { // operator val lengthType = readBits(input, bitOff + 6, 1) val packets = mutableListOf<Packet>() var off = bitOff + 6 + 1 if (lengthType == 0) { val end = readBits(input, off, 15) + off + 15 off += 15 while (off < end) { val packet = readPacket(input, off) packets.add(packet) off += packet.size } } else { val totalPackets = readBits(input, off, 11) off += 11 repeat(totalPackets) { val packet = readPacket(input, off) packets.add(packet) off += packet.size } } return Operator(version, type, off - bitOff, packets) } private fun readScalar( bitOff: Int, input: UByteArray, version: Int, type: Int ): Literal { var read = 0 var out = 0L var off = bitOff + 6 while (true) { val bits = readBits(input, off, 5) off += 5 read += 5 out = (out shl 4) + (bits and 0b1111) if (bits and 0b00010000 == 0) { return Literal(version, type, 6 + read, out) } } } private fun versionSum(packet: Packet): Int { return when (packet) { is Literal -> packet.version is Operator -> packet.version + packet.packets.sumOf { versionSum(it) } } } private fun calculate(packet: Packet): Long { return when (packet) { is Literal -> packet.value is Operator -> when (packet.type) { 0 -> packet.packets.sumOf { calculate(it) } 1 -> packet.packets.fold(1L) { acc, p -> acc * calculate(p) } 2 -> packet.packets.minOf { calculate(it) } 3 -> packet.packets.maxOf { calculate(it) } 5 -> if (calculate(packet.packets[0]) > calculate(packet.packets[1])) 1 else 0 6 -> if (calculate(packet.packets[0]) < calculate(packet.packets[1])) 1 else 0 7 -> if (calculate(packet.packets[0]) == calculate(packet.packets[1])) 1 else 0 else -> throw IllegalStateException("Unknown operator ${packet.type}") } } } override fun part1(input: UByteArray): Int { return versionSum(readPacket(input, 0)) } override fun part2(input: UByteArray): Long { return calculate(readPacket(input, 0)) } }
0
Kotlin
0
1
3f106415eeded3abd0fb60bed64fb77b4ab87d76
3,792
aoc_kotlin
MIT License
year2019/day01/part1/src/main/kotlin/com/curtislb/adventofcode/year2019/day01/part1/Year2019Day01Part1.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
/* --- Day 1: The Tyranny of the Rocket Equation --- Santa has become stranded at the edge of the Solar System while delivering presents to other planets! To accurately calculate his position in space, safely align his warp drive, and return to Earth in time to save Christmas, he needs you to bring him measurements from fifty stars. Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck! The Elves quickly load you into a spacecraft and prepare to launch. At the first Go / No Go poll, every Elf is Go until the Fuel Counter-Upper. They haven't determined the amount of fuel required yet. Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2. For example: - For a mass of 12, divide by 3 and round down to get 4, then subtract 2 to get 2. - For a mass of 14, dividing by 3 and rounding down still yields 4, so the fuel required is also 2. - For a mass of 1969, the fuel required is 654. - For a mass of 100756, the fuel required is 33583. The Fuel Counter-Upper needs to know the total fuel requirement. To find it, individually calculate the fuel needed for the mass of each module (your puzzle input), then add together all the fuel values. What is the sum of the fuel requirements for all of the modules on your spacecraft? */ package com.curtislb.adventofcode.year2019.day01.part1 import com.curtislb.adventofcode.year2019.day01.fuel.calculateFuel import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2019, day 1, part 1. * * @param inputPath The path to the input file for this puzzle. */ fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Int { var totalFuel = 0 inputPath.toFile().forEachLine { totalFuel += calculateFuel(it.trim().toInt()) } return totalFuel } fun main() { println(solve()) }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
2,068
AdventOfCode
MIT License
src/Day01.kt
rod41732
728,131,475
false
{"Kotlin": 26028}
/** * You can edit, run, and share this code. * play.kotlinlang.org */ fun main() { fun replaceWordWithNumber(input: String): String { val numbers = listOf("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine") var out = input numbers.forEachIndexed { idx, it -> out = out.replace(it, it + idx.toString() + it) } return out } fun part1(input: List<String>): Int { return input .map { val fs = it.first { it.isDigit() } - '0' val ls = it.last { it.isDigit()} - '0' return@map fs*10+ls }.sum() } fun part2(input: List<String>): Int { return part1( input.map { replaceWordWithNumber(it) } ) } val testInput = readInput("Day01_test") assertEqual(part1(testInput), 142) val testInput2 = readInput("Day01_test2") assertEqual(part2(testInput2), 281) val input = readInput("Day01") println("Part1: ${part1(input)}") println("Part2: ${part2(input)}") }
0
Kotlin
0
0
05a308a539c8a3f2683b11a3a0d97a7a78c4ffac
1,116
aoc-23
Apache License 2.0
src/main/kotlin/nl/meine/aoc/_2023/Day6.kt
mtoonen
158,697,380
false
{"Kotlin": 201978, "Java": 138385}
package nl.meine.aoc._2023 class Day6 { fun one(timeString: List<Int>, distance:List<Int>): Int { val times = timeString val distances = distance var total = 1; times.forEachIndexed{index,time-> run { val timeToBeat = distances[index] var countSucceeded = 0 for (i in 1..<time) { val distanceTravelled = (time - i) * i if (distanceTravelled > timeToBeat) { countSucceeded++ } } total *= countSucceeded } } return total } fun two(time: Long, distance:Long): Long { val lines = input.split("\n") var countSucceeded:Long = 0 for (i in 1..<time) { val distanceTravelled:Long = (time - i) * i if (distanceTravelled > distance) { countSucceeded++ } } return countSucceeded } } fun main() { val time = listOf(62, 64, 91, 90) val dist = listOf(553, 1010, 1473, 1074) val ins = Day6(); //println(ins.one(time,dist)) println(ins.two(62649190,553101014731074)) }
0
Kotlin
0
0
a36addef07f61072cbf4c7c71adf2236a53959a5
1,243
advent-code
MIT License
kotlin/PersistentTree.kt
indy256
1,493,359
false
{"Java": 545116, "C++": 266009, "Python": 59511, "Kotlin": 28391, "Rust": 4682, "CMake": 571}
// https://en.wikipedia.org/wiki/Persistent_data_structure object PersistentTree { data class Node( val left: Node? = null, val right: Node? = null, val sum: Int = (left?.sum ?: 0) + (right?.sum ?: 0) ) fun build(left: Int, right: Int): Node { if (left == right) return Node(null, null) val mid = left + right shr 1 return Node(build(left, mid), build(mid + 1, right)) } fun sum(a: Int, b: Int, root: Node, left: Int, right: Int): Int { if (a == left && b == right) return root.sum val mid = left + right shr 1 var s = 0 if (a <= mid) s += sum(a, minOf(b, mid), root.left!!, left, mid) if (b > mid) s += sum(maxOf(a, mid + 1), b, root.right!!, mid + 1, right) return s } fun set(pos: Int, value: Int, root: Node, left: Int, right: Int): Node { if (left == right) return Node(null, null, value) val mid = left + right shr 1 return if (pos <= mid) Node(set(pos, value, root.left!!, left, mid), root.right) else Node(root.left, set(pos, value, root.right!!, mid + 1, right)) } // Usage example @JvmStatic fun main(args: Array<String>) { val n = 10 val t1 = build(0, n - 1) val t2 = set(0, 1, t1, 0, n - 1) println(0 == sum(0, 9, t1, 0, n - 1)) println(1 == sum(0, 9, t2, 0, n - 1)) } }
97
Java
561
1,806
405552617ba1cd4a74010da38470d44f1c2e4ae3
1,500
codelibrary
The Unlicense
src/shmp/lang/language/syntax/numeral/NumeralParadigm.kt
ShMPMat
240,860,070
false
null
package shmp.lang.language.syntax.numeral import shmp.lang.language.NumeralSystemBase import shmp.lang.language.lexis.Lexis import shmp.lang.language.lineUpAll import shmp.lang.language.syntax.SyntaxException import shmp.lang.language.syntax.SyntaxRelation import shmp.lang.language.syntax.numeral.NumeralConstructionType.* import shmp.lang.language.syntax.clause.realization.wordToNode import shmp.lang.language.syntax.clause.translation.SentenceNode import shmp.random.singleton.testProbability data class NumeralParadigm(val base: NumeralSystemBase, val ranges: NumeralRanges) { fun constructNumeral(n: Int, lexis: Lexis): SentenceNode { if (n < 1) throw SyntaxException("No numeral for $n") return extract(n, lexis).apply { parentPropagation = true } } private fun extract(n: Int, lexis: Lexis): SentenceNode = when (val type = getType(n)) { SingleWord -> lexis.getWord(n.toString()).wordToNode(SyntaxRelation.AdNumeral) is SpecialWord -> lexis.getWord(type.meaning).wordToNode(SyntaxRelation.AdNumeral) is AddWord -> { val baseNumber = n / type.baseNumber val sumNumber = n % type.baseNumber val baseNode = constructBaseNode(baseNumber, type.baseNumber, type.oneProb, lexis) if (sumNumber != 0) { val sumNode = extract(sumNumber, lexis) baseNode.addStrayChild(SyntaxRelation.SumNumeral, sumNode) } baseNode.arranger = type.arranger baseNode } } private fun constructBaseNode(mulNumber: Int, baseNumber: Int, oneProb: Double, lexis: Lexis): SentenceNode { val type = getType(mulNumber * baseNumber) if (type == SingleWord || type is SpecialWord) return extract(mulNumber * baseNumber, lexis) val baseNode = extract(baseNumber, lexis) val mulNode = extract(mulNumber, lexis) if (mulNumber != 1 || oneProb.testProbability()) baseNode.addStrayChild(SyntaxRelation.MulNumeral, mulNode) return baseNode } private fun getType(n: Int) = ranges.first { (r) -> r.contains(n) }.second override fun toString() = """ |Numeral system base: $base |${ ranges.map { (r, t) -> listOf("From ${r.first} to ${r.last} - ", t.toString()) } .lineUpAll() .joinToString("\n") } | |""".trimMargin() } typealias NumeralRanges = List<Pair<IntRange, NumeralConstructionType>>
0
Kotlin
0
1
4d26b0d50a1c3c6318eede8dd9678d3765902d4b
2,580
LanguageGenerator
MIT License
src/Day03.kt
vivekpanchal
572,801,707
false
{"Kotlin": 11850}
const val ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" fun main() { fun part1(input: List<String>): Int { return input.map {str-> val pair=str.substring(0,str.length/2) to str.substring(str.length/2) val common=pair.first.first { pair.second.contains(it) } common }.sumOf { ALPHABET.indexOf(it).inc() } } fun part2(input: List<String>): Int { return input.windowed(3,3) .sumOf { rucksacks -> val unique = rucksacks .map { it.toSet() } .reduce { init, item -> init.intersect(item) } unique.sumOf { ALPHABET.indexOf(it).inc() } } // return 1 } val input = readInput("Day03") println("result part 1 == ${part1(input)}") println("result part 2 == ${part2(input)}") }
0
Kotlin
0
0
f21a2dd08be66520e9c9de14611e50c14ea017f0
909
Aoc-kotlin
Apache License 2.0
language/kotlin/fib.kt
A1rPun
177,014,508
false
null
import kotlin.math.pow import kotlin.math.round fun fib(n: Int): Int { return if (n < 2) n else fib(n - 1) + fib(n - 2) } fun fibLinear(n: Int): Int { var prevFib = 0 var fib = 1 repeat(n) { val temp = prevFib + fib prevFib = fib fib = temp } return prevFib } fun fibFormula(n: Int): Int { return round((((5.0.pow(0.5) + 1) / 2.0).pow(n)) / 5.0.pow(0.5)).toInt(); } fun fibTailRecursive(n: Int, prevFib: Int = 0, fib: Int = 1): Int { return if (n == 0) prevFib else fibTailRecursive(n - 1, fib, prevFib + fib) } fun fibonacciGenerate(n: Int): List<Int> { var a = 0 var b = 1 fun next(): Int { val result = a + b a = b b = result return a } return generateSequence(::next).take(n).toList() } fun main(args: Array<String>) { var input = if (args.size > 0) args[0].toInt() else 29 println(fibLinear(input)) }
0
Haskell
0
1
295de6ac0584672d936a0c7ad09cb464f916d27a
880
nurture
MIT License
kotlin/src/com/s13g/aoc/aoc2023/Day8.kt
shaeberling
50,704,971
false
{"Kotlin": 300158, "Go": 140763, "Java": 107355, "Rust": 2314, "Starlark": 245}
package com.s13g.aoc.aoc2023 import com.s13g.aoc.Result import com.s13g.aoc.Solver import com.s13g.aoc.lcm import com.s13g.aoc.resultFrom private typealias Network = Map<String, Node> /** * --- Day 8: <NAME> --- * https://adventofcode.com/2023/day/8 */ class Day8 : Solver { val re = """(\w+) = \((\w+), (\w+)\)$""".toRegex() override fun solve(lines: List<String>): Result { val instructions = lines[0] val network = parseNetwork(lines.drop(2)) val partA = runNetwork("AAA", "ZZZ", instructions, network).first val partB = runNetworkB(instructions, network) return resultFrom(partA, partB) } private fun runNetworkB(instr: String, network: Network): Long { val nodes = network.keys.filter { it[2] == 'A' }.toSet() val loopLengthsInitial = mutableListOf<Pair<Int, String>>() // Detect loop length for each starting node. // Note: The loops hereafter are the same lengths. Looking for the loop // length of each **Z node to another **Z node, results in the same // length as from the initial **A node to this **Z node, thus making // this fairly easy. nodes.forEach { loopLengthsInitial.add(runNetwork(it, "**Z", instr, network)) } return lcm(loopLengthsInitial.map { it.first.toLong() }) } private fun runNetwork( start: String, end: String, instr: String, network: Network ): Pair<Int, String> { var count = 0 var idx = 0 var node = start while (true) { count++ node = if (instr[idx] == 'L') network[node]!!.left else network[node]!!.right if (node == end) return Pair(count, node) // Part A if (end == "**Z" && node[2] == 'Z') return Pair(count, node) // Part B if (++idx > instr.lastIndex) idx = 0 } } private fun parseNetwork(lines: List<String>): Network = lines.map { re.find(it)!!.destructured } .associate { (node, left, right) -> node to Node(left, right) } } private data class Node(val left: String, val right: String)
0
Kotlin
1
2
7e5806f288e87d26cd22eca44e5c695faf62a0d7
2,040
euler
Apache License 2.0
src/main/kotlin/de/startat/aoc2023/Day1.kt
Arondc
727,396,875
false
{"Kotlin": 194620}
package de.startat.aoc2023 class Day1 { private val literalReplacements = sequenceOf( "one" to 1, "two" to 2, "three" to 3, "four" to 4, "five" to 5, "six" to 6, "seven" to 7, "eight" to 8, "nine" to 9 ) fun star1() { calculateSolution(false) } fun star2() { calculateSolution(true) } private fun calculateSolution(replaceLiterals: Boolean) { val input: String = day1Input1 val sum = input.lines().map { l -> println(l) findAllIndexedNumbers(l, replaceLiterals) }.map { numbers -> "${numbers.first().second}${numbers.last().second}".toInt() }.reduce { sum, number -> sum + number } println() println("Die Summe ist $sum") } private fun findAllIndexedNumbers( l: String, replaceLiterals: Boolean ): List<Pair<Int, Int>> { val normalIndexedNumbers = l.mapIndexedNotNull { i, c -> when { c.isDigit() -> i to c.digitToInt() else -> null } } println("\tnormal numbers: $normalIndexedNumbers") return if (replaceLiterals) { (findLiterals(l) + normalIndexedNumbers).sortedBy { it.first } } else { normalIndexedNumbers } } private fun findLiterals(line: String): List<Pair<Int, Int>> { val occurrences = literalReplacements.flatMap { repl -> Regex(repl.first).findAll(line).map { result -> result.range.first to repl.second } }.toList() println("\tliteral numbers: $occurrences") return occurrences } }
0
Kotlin
0
0
660d1a5733dd533aff822f0e10166282b8e4bed9
1,715
AOC2023
Creative Commons Zero v1.0 Universal
src/chapter4/section1/ex35_TwoEdgeConnectivity.kt
w1374720640
265,536,015
false
{"Kotlin": 1373556}
package chapter4.section1 /** * 边的连通性 * 在一副连通图中,如果一条边被删除后图会被分为两个独立的连通分量,这条边就被成为桥。 * 没有桥的图称为边连通图。 * 开发一种基于深度优先搜索算法的数据类型,判断一个图是否时边连通图。 * * 解:这题和4.1.34都可以参考练习4.1.10中的代码实现 */ fun Graph.isConnectedGraph(): Boolean { for (s in 0 until V) { val iterable = adj(s) if (iterable.count() <= 1) continue val marked = BooleanArray(V) marked[s] = true var i = 1 // 任意选择一个相邻顶点开始深度优先遍历 val v = iterable.first() i += dfs(this, marked, v) val search = DepthFirstSearch(this, s) if (i != search.count()) return false } return true } private fun dfs(graph: Graph, marked: BooleanArray, v: Int): Int { if (!marked[v]) { marked[v] = true var i = 1 graph.adj(v).forEach { i += dfs(graph, marked, it) } return i } return 0 } fun main() { val graph = Graph(6) graph.addEdge(0, 1) graph.addEdge(1, 2) graph.addEdge(0, 2) graph.addEdge(2, 3) graph.addEdge(3, 4) graph.addEdge(4, 5) graph.addEdge(5, 3) println(graph.isConnectedGraph()) graph.addEdge(0, 4) println(graph.isConnectedGraph()) drawGraph(graph, showIndex = true, pointRadius = GraphGraphics.DEFAULT_POINT_RADIUS * 2) }
0
Kotlin
1
6
879885b82ef51d58efe578c9391f04bc54c2531d
1,524
Algorithms-4th-Edition-in-Kotlin
MIT License
src/Day01.kt
jwklomp
572,195,432
false
{"Kotlin": 65103}
fun main() { fun getSums(input: List<String>): List<Int> { val indexes = listOf(0) + input.indexesOf("") + listOf(input.size) return indexes.windowed(2) .map { input.subList(it.first(), it.last()) .filterNot { it == "" } .map { it.toInt() } .sum() } } fun part1(input: List<String>): Int = getSums(input).max() fun part2(input: List<String>): Int = getSums(input).sortedDescending().take(3).sum() val testInput = readInput("Day01_test") println(part1(testInput)) println(part2(testInput)) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
1b1121cfc57bbb73ac84a2f58927ab59bf158888
715
aoc-2022-in-kotlin
Apache License 2.0
app/src/main/java/com/jackson/tictactoe/utils/MinMaxAlgorithm.kt
Maxwell6635
722,506,658
false
{"Kotlin": 45260}
package com.jackson.tictactoe.utils object MinMaxAlgorithm { private var player = 'x' private var opponent = 'o' private fun isMovesLeft(board: Array<CharArray>): Boolean { for (i in 0..2) for (j in 0..2) if (board[i][j] == '_') return true return false } private fun evaluate(b: Array<CharArray>): Int { // Checking for Rows for X or O victory. for (row in 0..2) { if (b[row][0] == b[row][1] && b[row][1] == b[row][2] ) { if (b[row][0] == player) return +10 else if (b[row][0] == opponent) return -10 } } for (col in 0..2) { if (b[0][col] == b[1][col] && b[1][col] == b[2][col] ) { if (b[0][col] == player) return +10 else if (b[0][col] == opponent) return -10 } } if (b[0][0] == b[1][1] && b[1][1] == b[2][2]) { if (b[0][0] == player) return +10 else if (b[0][0] == opponent) return -10 } if (b[0][2] == b[1][1] && b[1][1] == b[2][0]) { if (b[0][2] == player) return +10 else if (b[0][2] == opponent) return -10 } return 0 } private fun minimax( board: Array<CharArray>, depth: Int, isMax: Boolean ): Int { val score = evaluate(board) if (score == 10) return score if (score == -10) return score if (!isMovesLeft(board)) return 0 return if (isMax) { var best = -1000 for (i in 0..2) { for (j in 0..2) { if (board[i][j] == '_') { board[i][j] = player best = Math.max( best, minimax( board, depth + 1, !isMax ) ) board[i][j] = '_' } } } best } else { var best = 1000 for (i in 0..2) { for (j in 0..2) { if (board[i][j] == '_') { board[i][j] = opponent best = Math.min( best, minimax( board, depth + 1, !isMax ) ) // Undo the move board[i][j] = '_' } } } best } } @JvmStatic fun findBestMove(board: Array<CharArray>): Move { var bestVal = -1000 val bestMove = Move() bestMove.row = -1 bestMove.col = -1 for (i in 0..2) { for (j in 0..2) { if (board[i][j] == '_') { board[i][j] = player val moveVal = minimax(board, 0, false) board[i][j] = '_' if (moveVal > bestVal) { bestMove.row = i bestMove.col = j bestVal = moveVal } } } } return bestMove } class Move { @JvmField var row = 0 @JvmField var col = 0 } }
0
Kotlin
0
0
62f8035ad23e777a07cac50cb058283e193d5526
3,419
TicTacToe
MIT License
src/main/aoc2022/Day17.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2022 import AMap import Pos class Day17(input: List<String>) { enum class Rock(val height: Int, val parts: List<Pos>) { Dash(1, listOf(Pos(0, 0), Pos(1, 0), Pos(2, 0), Pos(3, 0))), Plus(3, listOf(Pos(1, 0), Pos(0, 1), Pos(1, 1), Pos(2, 1), Pos(1, 2))), Angle(3, listOf(Pos(0, 0), Pos(1, 0), Pos(2, 0), Pos(2, 1), Pos(2, 2))), Pipe(4, listOf(Pos(0, 0), Pos(0, 1), Pos(0, 2), Pos(0, 3))), Square(2, listOf(Pos(0, 0), Pos(0, 1), Pos(1, 0), Pos(1, 1))) } private val pattern = input.first().map { if (it == '>') 1 else -1 } private val chamber = AMap().apply { for (i in 0..6) { this[Pos(i, 0)] = '-' // Add a floor to get something more print friendly while debugging } } private var currentMax = 0 // Floor is at y=0, first rock is at y=1 private var jetOffset = 0 private fun fall(rock: Rock) { var x = 2 var y = currentMax + 4 while (true) { //push if possible val xAfterPush = x + pattern[jetOffset++ % pattern.size] if (rock.parts.map { it + Pos(xAfterPush, y) }.all { it.x in 0..6 && it !in chamber.keys }) { x = xAfterPush } //fall if possible if (y > 1 && rock.parts.map { it + Pos(x, y - 1) }.none { it in chamber.keys }) { y-- } else { // update chamber with final position of rock rock.parts.map { it + Pos(x, y) }.forEach { chamber[it] = '#' } // update currentMax as well currentMax = chamber.yRange().max() break } } } fun solvePart1(): Int { (0 until 2022).forEach { fall(Rock.values()[it % 5]) } return currentMax } // First entry is the floor height private val maxHeightHistory = mutableListOf(0) fun solvePart2(): Long { val numRocks = 1_000_000_000_000 // First simulate a bit and record with how much the height increases for each rock (0 until 2022).forEach { fall(Rock.values()[it % 5]) maxHeightHistory.add(currentMax) } val diffHistory = maxHeightHistory.zipWithNext().map { (a, b) -> b - a } // Now detect loops. Manual inspection of the diffHistory shows no loops that start from the very beginning // so start a bit into the sequence. Then use a marker that's long enough to not be repeating anywhere else // than when the loop restarts. The marker is the first markerLength entries in the loop. val loopStart = 200 // could be anything that's inside the loop val markerLength = 10 val marker = diffHistory.subList(loopStart, loopStart + markerLength) var loopHeight = -1 var loopLength = -1 val heightBeforeLoop = maxHeightHistory[loopStart - 1] for (i in loopStart + markerLength until diffHistory.size) { if (marker == diffHistory.subList(i, i + markerLength)) { // Marker matches the sequence starting at i, so Loop ends at i - 1 loopLength = i - loopStart loopHeight = maxHeightHistory[i - 1] - heightBeforeLoop break } } // Calculate the height at the target based on the number of loops and the height of the loop val numFullLoops = (numRocks - loopStart) / loopLength val offsetIntoLastLoop = ((numRocks - loopStart) % loopLength).toInt() val extraHeight = maxHeightHistory[loopStart + offsetIntoLastLoop] - heightBeforeLoop return heightBeforeLoop + loopHeight * numFullLoops + extraHeight } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
3,737
aoc
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/SplitIntoFibonacci.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 dev.shtanko.algorithms.DECIMAL import kotlin.math.min /** * 842. Split Array into Fibonacci Sequence * @see <a href="https://leetcode.com/problems/split-array-into-fibonacci-sequence/">Source</a> */ fun interface SplitIntoFibonacci { operator fun invoke(num: String): List<Int> } /** * Approach #1: Brute Force */ class SplitIntoFibonacciBruteForce : SplitIntoFibonacci { override operator fun invoke(num: String): List<Int> { val n: Int = num.length for (i in 0 until min(10, n)) { if (num[0] == '0' && i > 0) break val a: Long = java.lang.Long.valueOf(num.substring(0, i + 1)) if (a >= Int.MAX_VALUE) break search@ for (j in i + 1 until min(i + DECIMAL, n)) { if (num[i + 1] == '0' && j > i + 1) break val b: Long = java.lang.Long.valueOf(num.substring(i + 1, j + 1)) if (b >= Int.MAX_VALUE) break val fib: MutableList<Int> = ArrayList<Int>().apply { add(a.toInt()) add(b.toInt()) } var k = j + 1 while (k < n) { val nxt = (fib[fib.size - 2] + fib[fib.size - 1]).toLong() val nxtS = nxt.toString() if (nxt <= Int.MAX_VALUE && num.substring(k).startsWith(nxtS)) { k += nxtS.length fib.add(nxt.toInt()) } else { continue@search } } if (fib.size >= 3) { return fib } } } return ArrayList() } } class SplitIntoFibonacciBacktracking : SplitIntoFibonacci { override operator fun invoke(num: String): List<Int> { val ans: MutableList<Int> = ArrayList() helper(num, ans, 0) return ans } fun helper(s: String, ans: MutableList<Int>, idx: Int): Boolean { if (idx == s.length && ans.size >= 3) { return true } for (i in idx until s.length) { if (s[idx] == '0' && i > idx) { break } val num = s.substring(idx, i + 1).toLong() if (num > Int.MAX_VALUE) { break } val size = ans.size // early termination if (size >= 2 && num > ans[size - 1] + ans[size - 2]) { break } if (size <= 1 || num == (ans[size - 1] + ans[size - 2]).toLong()) { ans.add(num.toInt()) // branch pruning. if one branch has found fib seq, return true to upper call if (helper(s, ans, i + 1)) { return true } ans.removeAt(ans.size - 1) } } return false } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,541
kotlab
Apache License 2.0
src/main/kotlin/Day12.kt
Yeah69
317,335,309
false
{"Kotlin": 73241}
import java.lang.Exception import kotlin.math.abs class Day12 : Day() { override val label: String get() = "12" private data class Situation(val waypoint: Pair<Int, Int>, val shipPosition: Pair<Int, Int>) private fun Pair<Int, Int>.left(value: Int): Pair<Int, Int> = when ((value % 360) / 90) { 1 -> Pair(-this.second, this.first) 2 -> Pair(-this.first, -this.second) 3 -> Pair( this.second, -this.first) else -> this } private fun Pair<Int, Int>.right(value: Int): Pair<Int, Int> = this.left(360 - (value % 360)) private fun Pair<Int, Int>.moveBy(offset: Pair<Int, Int>, factor: Int): Pair<Int, Int> = Pair(this.first + (offset.first * factor), this.second + (offset.second * factor)) private val lineRegex: Regex = """^([NSEWLRF])([0-9]+)$""".toRegex() private val actions by lazy { input.lineSequence() .map { val (action, value) = lineRegex.find(it)?.destructured ?: throw Exception() Pair(action, value.toInt()) } .toList() } private fun logic( initialSituation: Situation, generateWaypoints: (Situation, Pair<String, Int>) -> Pair<Pair<Int, Int>, Pair<Int, Int>>): String { val finalSituation = actions.fold(initialSituation) { prevSituation, next -> val (movingWaypoint, nextWaypoint) = generateWaypoints(prevSituation, next) val newShipPosition = prevSituation.shipPosition.moveBy(movingWaypoint, next.second) Situation(nextWaypoint, newShipPosition) } return (abs(finalSituation.shipPosition.first) + abs(finalSituation.shipPosition.second)).toString() } override fun taskZeroLogic(): String = logic(Situation(Pair(1, 0), Pair(0, 0))) { prevSituation, next -> val nextWaypoint = when (next.first) { "L" -> prevSituation.waypoint.left (next.second) "R" -> prevSituation.waypoint.right(next.second) else -> prevSituation.waypoint } val movingWaypoint = when (next.first) { "N" -> Pair( 0, 1) "S" -> Pair( 0, -1) "W" -> Pair(-1, 0) "E" -> Pair( 1, 0) "F" -> prevSituation.waypoint else -> Pair( 0, 0) } Pair(movingWaypoint, nextWaypoint) } override fun taskOneLogic(): String = logic(Situation(Pair(10, 1), Pair(0, 0))) { prevSituation, next -> val nexWaypoint = when (next.first) { "N" -> Pair(prevSituation.waypoint.first, prevSituation.waypoint.second + next.second) "S" -> Pair(prevSituation.waypoint.first, prevSituation.waypoint.second - next.second) "W" -> Pair(prevSituation.waypoint.first - next.second, prevSituation.waypoint.second ) "E" -> Pair(prevSituation.waypoint.first + next.second, prevSituation.waypoint.second ) "L" -> prevSituation.waypoint.left(next.second) "R" -> prevSituation.waypoint.right(next.second) else -> prevSituation.waypoint } val movingWayPoint = if (next.first == "F") nexWaypoint else Pair(0, 0) Pair(movingWayPoint, nexWaypoint) } }
0
Kotlin
0
0
23121ede8e3e8fc7aa1e8619b9ce425b9b2397ec
3,231
AdventOfCodeKotlin
The Unlicense
src/main/kotlin/engineer/thomas_werner/euler/Problem26.kt
huddeldaddel
183,355,188
true
{"Kotlin": 116039, "Java": 34495}
package de.huddeldaddel.euler import java.lang.ArithmeticException import java.math.BigDecimal import java.math.BigInteger import java.math.MathContext import java.math.RoundingMode /** * Solution for https://projecteuler.net/problem=26 */ fun main() { println(Problem26().getDemoninatorWithMaxCycle()) } class Problem26 { fun getDemoninatorWithMaxCycle(): Int { var maxCycleLength = 0 var denominator = 0 for(d in 1 until 1000) { println(d) val nthUnitFraction = getNthUnitFraction(d) val recurringCycle = getRecurringCycle(nthUnitFraction) if((null != recurringCycle) && (recurringCycle.length > maxCycleLength)) { denominator = d maxCycleLength = recurringCycle.length } } return denominator } companion object { fun getRecurringCycle(input: String): String? { if(input.length < 10_002) return null for(i in 3..5000) { for(j in i downTo 2) { val substring = input.substring(j..i) if(isRecurringCycle(input, substring, i)) return substring } } return null } private fun isRecurringCycle(input: String, part: String, start: Int): Boolean { val builder = StringBuilder(input.substring(0..start)) while(builder.length < 10_002) builder.append(part) return input.substring(0 until 10_000) == builder.toString().substring(0 until 10_000) } fun getNthUnitFraction(n: Int): String { val numerator = BigDecimal.ONE val denominator = BigDecimal(BigInteger.valueOf(n.toLong())) return try { // Try to get the shortest value possible numerator.divide(denominator, MathContext.UNLIMITED).toPlainString() } catch(ae: ArithmeticException) { // A recurring cycle: calculation restricted to 10_000 decimal places numerator.divide(denominator,10_000, RoundingMode.HALF_UP).toPlainString() } } } }
0
Kotlin
1
0
df514adde8c62481d59e78a44060dc80703b8f9f
2,231
euler
MIT License
src/Day06.kt
jsebasct
572,954,137
false
{"Kotlin": 29119}
import java.io.File fun main() { data class Movement(val amount: Int, val source: Int, val destination: Int) fun getMovements(movementLines: String) = movementLines.split("\n") .map { line -> val splintedLine = line.split(" ") .filter { it.toIntOrNull() != null } .map { it.toInt() } Movement(splintedLine[0], splintedLine[1], splintedLine[2]) } fun getCrates(stacksLines: String): MutableList<ArrayDeque<Char>> { val stacksHeadDown = stacksLines.lines().reversed() println(stacksHeadDown.joinToString(separator = "\n")) val notNullIndices = stacksHeadDown[0].indices.filter { indice -> stacksHeadDown[0].get(indice).digitToIntOrNull() != null} println(notNullIndices) val crateNumber = stacksHeadDown[0][notNullIndices[notNullIndices.lastIndex]] val crates = mutableListOf<ArrayDeque<Char>>() repeat(crateNumber.digitToInt()) { crates.add(ArrayDeque<Char>()) } stacksHeadDown.forEachIndexed { index, crateLine -> if (index > 0) { if (index == stacksHeadDown.lastIndex) { println("this is the line: ##$crateLine##") println("this is the line: ##${crateLine.lastIndex}") } for (createIndex in 0 until crateNumber.digitToInt()) { // if (index == stacksHeadDown.lastIndex) { // println("##$crateLine## - not null iondex: ${notNullIndices[createIndex]}-") // } //println("createIndex: $createIndex with value: -${crateLine[notNullIndices[createIndex]]}-") val crateValue = if (crateLine.lastIndex >= notNullIndices[createIndex]) crateLine[notNullIndices[createIndex]] else ' ' // val crateValue = crateLine[notNullIndices[createIndex]] if (crateValue != ' ') { crates[createIndex].add(crateLine[notNullIndices[createIndex]]) } } } } println("\ncrates") println(crates) return crates } fun part51(input: String): String { val (stacksLines, movementLines) = input.split("\n\n") val movements = getMovements(movementLines) val crates = getCrates(stacksLines) // make movements movements.forEach { move -> println(move) repeat(move.amount) { crates[move.destination - 1].add(crates[move.source - 1].removeLast()) } } println("After movements") println(crates) val res = crates.map { it.last() }.joinToString(separator = "") println(res) return res } fun part52(input: String): String { val (stacksLines, movementLines) = input.split("\n\n") val movements = getMovements(movementLines) val crates = getCrates(stacksLines) println("\ncrates") println(crates) // make movements movements.forEach { move -> // println(move) val temp = mutableListOf<Char>() repeat(move.amount) { temp.add(crates[move.source - 1].removeLast()) } // println("temp: $temp") crates[move.destination - 1].addAll(temp.reversed()) } println("After movements") println(crates) val res = crates.map { it.last() }.joinToString(separator = "") // println(res) return res } // val test1 = fullyContains(Pair(2,8), 3 to 7) // println("test1: $test1") // // val test2 = fullyContains(Pair(4,6), 6 to 6) // println(test2) // val input = readInput("Day05_test") // println("total part 1: ${part51(input)}") val input = File("src", "Day05_test.txt").readText() println("total: ${part51(input)}") println("Part two") println("total parte 2: ${part52(input)}") // test if implementation meets criteria from the description, like: // val testInput = readInput("Day02_test") // check(part2(testInput) == 45000) }
0
Kotlin
0
0
c4a587d9d98d02b9520a9697d6fc269509b32220
4,241
aoc2022
Apache License 2.0
kotlin/src/com/leetcode/496_NextGreaterElementI.kt
programmerr47
248,502,040
false
null
package com.leetcode import java.util.* import kotlin.collections.HashMap //Straightforward solution time: O(n*m), space: O(1), where n = nums1.size, m = nums2.size private class Solution496 { fun nextGreaterElement(nums1: IntArray, nums2: IntArray): IntArray { return IntArray(nums1.size) { i -> val num1 = nums1[i] var found = false var result = -1 for (j in nums2.indices) { val num2 = nums2[j] if (!found && num2 == num1) { found = true } else if (found && num2 > num1) { result = num2 break } } result } } } //Decreasing stack time: O(m), space: O(n + m), where n = nums1.size, m = nums2.size private class Solution496Stack { fun nextGreaterElement(nums1: IntArray, nums2: IntArray): IntArray { val map = HashMap<Int, Int>() nums1.forEachIndexed { i, num1 -> map[num1] = i } val result = IntArray(nums1.size) { -1 } val stack = LinkedList<Int>() nums2.forEach { nums2 -> while (stack.isNotEmpty() && stack.peekLast() < nums2) { val stackNum = stack.pollLast() map[stackNum]?.let { index -> result[index] = nums2 } } stack.add(nums2) } return result } } fun main() { println(Solution496Stack().nextGreaterElement(intArrayOf(4, 1, 2), intArrayOf(1, 3, 4, 2)).joinToString()) }
0
Kotlin
0
0
0b5fbb3143ece02bb60d7c61fea56021fcc0f069
1,543
problemsolving
Apache License 2.0
src/commonMain/kotlin/eu/yeger/cyk/RunningCYK.kt
DerYeger
302,742,119
false
null
package eu.yeger.cyk import eu.yeger.cyk.model.* import eu.yeger.cyk.parser.word public fun runningCYK( wordString: String, grammar: () -> Result<Grammar> ): Result<List<CYKState>> { return word(wordString).with(grammar(), ::runningCYK) } public fun runningCYK( word: Result<Word>, grammar: Result<Grammar> ): Result<List<CYKState>> { return word.with(grammar, ::runningCYK) } public fun runningCYK( word: Word, grammar: Grammar, ): List<CYKState> { val cykStartState = CYKState.Start(CYKModel(word, grammar)) return (0..word.size).fold(listOf(cykStartState)) { previousStates: List<CYKState>, l: Int -> when (l) { 0 -> previousStates.runningPropagateTerminalProductionRules() else -> previousStates.runningPropagateNonTerminalProductionRules(l + 1) } }.let { previousStates: List<CYKState> -> previousStates + previousStates.last().terminated() } } private fun List<CYKState>.runningPropagateTerminalProductionRules(): List<CYKState> { return last().model.word.foldIndexed(this) { terminalSymbolIndex: Int, previousStates: List<CYKState>, terminalSymbol: TerminalSymbol -> previousStates.runningFindProductionRulesForTerminalSymbol(terminalSymbol, terminalSymbolIndex) } } private fun List<CYKState>.runningFindProductionRulesForTerminalSymbol( terminalSymbol: TerminalSymbol, terminalSymbolIndex: Int, ): List<CYKState> { return last().model.grammar.productionRuleSet.terminatingRules.fold(this) { previousStates: List<CYKState>, terminatingRule: TerminatingRule -> val lastState = previousStates.last() previousStates + when { terminatingRule produces terminalSymbol -> lastState.stepWithRuleAt( terminatingRule, rowIndex = 0, columnIndex = terminalSymbolIndex, listOf(Coordinates(-1, terminalSymbolIndex)) ) else -> lastState.stepWithoutRuleAt( terminatingRule, rowIndex = 0, columnIndex = terminalSymbolIndex, listOf(Coordinates(-1, terminalSymbolIndex)) ) } } } private fun List<CYKState>.runningPropagateNonTerminalProductionRules( l: Int, ): List<CYKState> { return (1..(last().model.word.size - l + 1)).fold(this) { rowSteps: List<CYKState>, s: Int -> (1 until l).fold(rowSteps) { columnSteps: List<CYKState>, p: Int -> columnSteps.runningFindProductionRulesForNonTerminalSymbols(l = l, s = s, p = p) } } } private fun List<CYKState>.runningFindProductionRulesForNonTerminalSymbols( l: Int, s: Int, p: Int, ): List<CYKState> { return last().model.grammar.productionRuleSet.nonTerminatingRules.fold(this) { previousStates: List<CYKState>, nonTerminatingRule: NonTerminatingRule -> val lastState = previousStates.last() previousStates + when { lastState.model.allowsNonTerminalRuleAt( nonTerminatingRule, l = l, s = s, p = p ) -> lastState.stepWithRuleAt( nonTerminatingRule, rowIndex = l - 1, columnIndex = s - 1, listOf(Coordinates(p - 1, s - 1), Coordinates(l - p - 1, s + p - 1)) ) else -> lastState.stepWithoutRuleAt( nonTerminatingRule, rowIndex = l - 1, columnIndex = s - 1, listOf(Coordinates(p - 1, s - 1), Coordinates(l - p - 1, s + p - 1)) ) } } }
0
Kotlin
0
2
76b895e3e8ea6b696b3ad6595493fda9ee3da067
3,638
cyk-algorithm
MIT License
PF/9. Functions/Function_Exercise.kt
FasihMuhammadVirk
606,810,021
false
null
import java.util.* import kotlin.collections.ArrayList //Write a function that takes in two integers and return their sums fun sum_numbers(x:Int , y:Int ):Int = x + y //A function that reverse the value of the string fun reverse_string(s:String):String = s.reversed() //take an array of integer and return their average fun sum_array(a: Array<Int>):Int = a.sum() //String and Character and Return how many time it appear in String fun appaerance_of_char(s: String,c: Char):Int{ var result: Int = 0 for (i in s){ if (i == c) { result =+1 } } return result } //aaray of string and return the longest string fun longest_string(s: Array<String>){ var result:String = " " for (i in s ) { if (i.length > result.length) { result = i } } println(result) } //Return a list conatining only even numbers fun even_number(array: Array<Int>){ var arr = ArrayList<Int>(0) for (i in array){ if(i%2 == 0) { arr.add(i) } } println(arr) } //return the number of word in the string fun number_of_words(s:String):Int = s.length //retunr the smallest number fun smallest_number(s: Array<Int>):Int{ var result:Int = s[0] for (i in s ) { if (i < result) { result = i } } return result } //Vowel in the string fun vowel_string(s: Array<String>){ var arr = ArrayList<String>() var vol = arrayOf('a','e','i','o','u','A','E','I','O','U') for (i in s ) { if (vol.contains(i[0])) { arr.add(i) } } println(arr) } //Main fun main(){ var arrs = arrayOf("Iam","Shiza","TunTun","Fasih") var arr = arrayOf(1,2,3,4,5,6,7,8,9) println(Arrays.toString(arrs)) println(Arrays.toString(arr)) println() println("Sum of Number 2 and 2") println(sum_numbers(2,2)) println() println("Reversing the String 'Fasih'") println(reverse_string("Fasih")) println() println("Printing the sum of the Given Int Array") println(sum_array(arr)) println() println("Findin the Occurance of 'F' in Fasih") println(appaerance_of_char("Fasih",'F')) println() println("Printing the Even Number in Int Array") even_number(arr) println() println("Printing the Number of Words in 'Fasih'") println(number_of_words("Fasih")) println() println("Printing the smallest Number in Int Array") println(smallest_number(arr)) println() println("Printing the Word Start with Vowel in String Array") vowel_string(arrs) println() println("Printing the Longest String in String Array") longest_string(arrs) }
0
Kotlin
0
1
089dedc029434f64140d5a63246b8b35992a07ed
2,911
Concepts-in-Kotlin
MIT License
src/ad/kata/aoc2021/day08/SignalDeduction.kt
andrej-dyck
433,401,789
false
{"Kotlin": 161613}
package ad.kata.aoc2021.day08 class SignalDeduction( uniqueSignals: List<Signal> ) { fun deduceDigits(signals: List<Signal>) = signals.map { deducedSignalToDigits[it] } private val deducedSignalToDigits: Map<Signal, Digit> by lazy { uniqueLengthDigitsIn(uniqueSignals) .withIdentifiedSize5Digits(uniqueSignals.filter { it.segmentsCount == 5 }) .withIdentifiedSize6Digits(uniqueSignals.filter { it.segmentsCount == 6 }) .toKnownSignals() } /** * 1: 4: 7: 8: * .... .... aaaa aaaa * . c b c . c b c * . c b c . c b c * .... dddd .... dddd * . f . f . f e f * . f . f . f e f * .... .... .... gggg */ private fun uniqueLengthDigitsIn(signals: List<Signal>) = uniqueSegmentsLengthDigits.mapValues { (_, length) -> signals.firstOrNull { it.segmentsCount == length } } /** * 2: 3: 5: * aaaa aaaa aaaa * . c . c b . * . c . c b . * dddd dddd dddd * e . . f . f * e . . f . f * gggg gggg gggg */ private fun Map<Digit, Signal?>.withIdentifiedSize5Digits(size5Signals: List<Signal>): Map<Digit, Signal?> { val signalFor2 = size5Signals.firstIntersectionOrNull(get(Digit(4))) { it.size == 2 } val signalFor3 = size5Signals.firstIntersectionOrNull(get(Digit(7))) { it.size == 3 } return this + mapOf( Digit(2) to signalFor2, Digit(3) to signalFor3, Digit(5) to size5Signals.firstOrNull { it != signalFor2 && it != signalFor3 } ) } private inline fun List<Signal>.firstIntersectionOrNull( signal: Signal?, predicate: (Set<Char>) -> Boolean ) = signal?.let { s -> firstOrNull { predicate(it.segments.intersect(s.segments)) } } /** * 0: 6: 9: * aaaa aaaa aaaa * b c b . b c * b c b . b c * .... dddd dddd * e f e f . f * e f e f . f * gggg gggg gggg */ private fun Map<Digit, Signal?>.withIdentifiedSize6Digits(size6Signals: List<Signal>): Map<Digit, Signal?> { val signalFor6 = size6Signals.firstIntersectionOrNull(get(Digit(7))) { it.size == 2 } val signalFor9 = size6Signals.firstIntersectionOrNull(get(Digit(3))) { it.size == 5 } return this + mapOf( Digit(0) to size6Signals.firstOrNull { it != signalFor6 && it != signalFor9 }, Digit(6) to signalFor6, Digit(9) to signalFor9 ) } private fun Map<Digit, Signal?>.toKnownSignals() = mapNotNull { (d, s) -> s?.let { it to d } }.toMap() companion object { private val uniqueSegmentsLengthDigits by lazy { setOf(1, 4, 7, 8) .map { Digit(it) } .associateWith { Signal(it).segmentsCount } } } }
0
Kotlin
0
0
28d374fee4178e5944cb51114c1804d0c55d1052
3,136
advent-of-code-2021
MIT License
src/main/kotlin/solutions/Day3RucksackReorganization.kt
aormsby
571,002,889
false
{"Kotlin": 80084}
package solutions import utils.Input import utils.Solution // run only this day fun main() { Day3RucksackReorganization() } class Day3RucksackReorganization : Solution() { private val a = 'a' private val A = 'A' init { begin("Day 3 - Rucksack Reorganization") val input = Input.parseLines("/d3_rucksack_items.txt") val sol1 = getSumMismatchedPriorities(input) output("Mismatched Item Priority Sum", sol1) val sol2 = getSumBadgePriorities(input) output("Badge Item Priority Sum", sol2) } private fun getSumMismatchedPriorities(input: List<String>): Int = input.fold(initial = 0) { acc, str -> val mid = str.length / 2 val halves = Pair(str.substring(0, mid), str.substring(mid)) val match = halves.first .dropWhile { it !in halves.second } .take(1).single() acc + match.priority() } private fun getSumBadgePriorities(input: List<String>): Int = input.chunked(3).fold(initial = 0) { acc, group -> val match = group[0] .dropWhile { it !in group[1] || it !in group[2] } .take(1).single() acc + match.priority() } private fun Char.priority(): Int = if (isLowerCase()) code - a.code + 1 else code - A.code + 26 + 1 }
0
Kotlin
0
0
1bef4812a65396c5768f12c442d73160c9cfa189
1,384
advent-of-code-2022
MIT License
src/Day18.kt
cypressious
572,916,585
false
{"Kotlin": 40281}
import com.google.gson.JsonArray import com.google.gson.JsonElement import com.google.gson.JsonParser import com.google.gson.JsonPrimitive import kotlin.math.ceil fun main() { abstract class SNum { var parent: SNum? = null abstract fun magnitude(): Long } class SPair(var left: SNum, var right: SNum) : SNum() { init { left.parent = this right.parent = this } override fun magnitude() = 3 * left.magnitude() + 2 * right.magnitude() override fun toString() = "[$left,$right]" } class SLiteral(var value: Long) : SNum() { override fun magnitude() = value override fun toString() = value.toString() } fun JsonElement.toSNum(): SNum = when (this) { is JsonPrimitive -> SLiteral(this.asLong) is JsonArray -> SPair(get(0).toSNum(), get(1).toSNum()) else -> error("nope") } fun String.parse() = JsonParser.parseString(this).toSNum() fun SNum.nestedPair(depth: Int): SPair? { if (this !is SPair) return null if (depth == 0) return this return left.nestedPair(depth - 1) ?: right.nestedPair(depth - 1) } fun SNum.findLiteral(descendLeft: Boolean): SLiteral = when (this) { is SLiteral -> this is SPair -> if (descendLeft) left.findLiteral(true) else right.findLiteral(false) else -> error("nope") } fun SNum.findLiteralNeighbor(left: Boolean): SLiteral? { val parent = parent as SPair? ?: return null return if (left && this == parent.right) parent.left.findLiteral(false) else if (!left && this == parent.left) parent.right.findLiteral(true) else parent.findLiteralNeighbor(left) } fun SNum.findLiteralOver9(): SLiteral? { if (this is SLiteral) return if (value > 9) this else null if (this is SPair) return left.findLiteralOver9() ?: right.findLiteralOver9() error("nope") } fun SNum.replaceWith(sNum: SNum) { val parent = parent as SPair if (this == parent.left) parent.left = sNum else parent.right = sNum sNum.parent = parent } fun SNum.reduce(): SNum { while (true) { val nested = nestedPair(4) if (nested != null) { nested.findLiteralNeighbor(true)?.let { it.value += (nested.left as SLiteral).value } nested.findLiteralNeighbor(false)?.let { it.value += (nested.right as SLiteral).value } nested.replaceWith(SLiteral(0)) continue } val over9 = findLiteralOver9() if (over9 != null) { over9.replaceWith( SPair( SLiteral(over9.value / 2), SLiteral(ceil(over9.value / 2.0).toLong()) ) ) continue } return this } } operator fun SNum.plus(sNum: SNum) = SPair(this, sNum).reduce() fun part1(input: List<String>): Long { val snums = input.map { it.parse() } val sum = snums.reduce { a, b -> a + b } return sum.magnitude() } fun part2(input: List<String>): Long { var max = 0L for (a in input) { for (b in input) { if (a == b) continue max = maxOf(max, a.parse().plus(b.parse()).magnitude()) max = maxOf(max, b.parse().plus(a.parse()).magnitude()) } } return max } // test if implementation meets criteria from the description, like: val testInput = readInput("Day18_test") check(part1(testInput) == 4140L) check(part2(testInput) == 3993L) val input = readInput("Day18") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
169fb9307a34b56c39578e3ee2cca038802bc046
3,840
AdventOfCode2021
Apache License 2.0
src/main/kotlin/com/chriswk/aoc/advent2021/Day6.kt
chriswk
317,863,220
false
{"Kotlin": 481061}
package com.chriswk.aoc.advent2021 import com.chriswk.aoc.AdventDay import com.chriswk.aoc.util.report import org.apache.logging.log4j.LogManager import org.apache.logging.log4j.Logger import java.util.SortedMap class Day6: AdventDay(2021, 6) { companion object { @JvmStatic fun main(args: Array<String>) { val day = Day6() repeat(10) { println("chris") report { day.part1() } report { day.part2() } println("fmr") day.fmr() } } val logger: Logger = LogManager.getLogger() } fun Tally.day(n: Int): Tally { return step(this).drop(n).first() } fun initalSetup(input: String): Tally { return input.split(",").map { it.toInt() }.groupBy { it }.mapValues { it.value.size.toLong() }.toSortedMap() } fun tallyAfterDays(input: String, days: Int): Tally { return initalSetup(input).day(days) } private fun step(tally: Tally): Sequence<Tally> { return generateSequence(tally) { t -> val zeros = t[0] ?: 0 val newTally = (0 ..7).associateWith { it -> t[it+1] ?: 0 }.toSortedMap() newTally[8] = zeros newTally.merge(6, zeros) { old, new -> old + new } // Insert new sizes newTally } } fun fmr() { val fishes = inputAsString.split(",").map { it.toLong() }.groupingBy { it }.eachCount() val ar = LongArray(9) { fishes[it.toLong()]?.toLong() ?: 0L } val seq = generateSequence(ar) { it.cycle() } report { seq.drop(80).first().sum() } report { seq.drop(256).first().sum() } } private fun LongArray.cycle(): LongArray { return LongArray(this.size) { idx -> when(idx) { 6 -> this[0] + this[7] 8 -> this[0] else -> this[idx+1] } } } fun part1(): Long { return tallyAfterDays(inputAsString, 80).values.sum() } fun part2(): Long { return tallyAfterDays(inputAsString, 256).values.sum() } } typealias Tally = SortedMap<Int, Long>
116
Kotlin
0
0
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
2,326
adventofcode
MIT License
day20/src/main/kotlin/ver_a.kt
jabbalaci
115,397,721
false
null
package a import java.math.BigInteger import java.io.File data class Point(var x: BigInteger, var y: BigInteger, var z: BigInteger) data class Particle(val id: Int, val line: String) { private val points = mutableListOf<Point>() init { val REGEX = Regex("""<(.*?)>""") val matchedResults = REGEX.findAll(line) for (matchedText in matchedResults) { val parts = matchedText.value.replace("<", "").replace(">", "").split(",").map { it.trim().toInt().toBigInteger() } points.add(Point(parts[0], parts[1], parts[2])) } } // these MUST come after the init! private val position = points[0] private val velocity = points[1] private val acceleration = points[2] fun move() { velocity.x += acceleration.x velocity.y += acceleration.y velocity.z += acceleration.z // position.x += velocity.x position.y += velocity.y position.z += velocity.z } override fun toString(): String { val sb = StringBuilder() sb.append("p(${id})=") sb.append(position.toString()) sb.append(", ") sb.append("v=") sb.append(velocity.toString()) sb.append(", ") sb.append("a=") sb.append(acceleration.toString()) sb.append(", ") sb.append("distance=") sb.append(distanceFromZero()) return sb.toString() } fun distanceFromZero(): BigInteger { return abs(position.x) + abs(position.y) + abs(position.z) } fun abs(n: BigInteger) = if (n >= BigInteger.ZERO) n else -n } object Space { private val particles = mutableListOf<Particle>() fun readInput(fname: String) { var id = 0 File(fname).forEachLine { line -> particles.add(Particle(id, line)) ++id } } fun start() { var cnt = 0 val limit = 10000 while (true) { // println(this) println("closest id: %d".format(findClosestParticleId())) // println("-------------------------------------") for (p in particles) { p.move() } ++cnt if (cnt > limit) { break } } } private fun findClosestParticleId(): Int { var mini = particles[0].distanceFromZero() var id = 0 for (i in 1..particles.lastIndex) { val dist = particles[i].distanceFromZero() if (dist < mini) { mini = dist id = i } } return id } override fun toString(): String { val sb = StringBuilder() for (p in particles) { sb.append(p.toString()) sb.append("\n") } return sb.toString() } } fun main(args: Array<String>) { // example // val fname = "example1.txt" // production val fname = "input.txt" Space.readInput(fname) // println(Space) Space.start() }
0
Kotlin
0
0
bce7c57fbedb78d61390366539cd3ba32b7726da
3,074
aoc2017
MIT License
src/day01/Day01.kt
JakubMosakowski
572,993,890
false
{"Kotlin": 66633}
package day01 import readInput /** * Santa's reindeer typically eat regular reindeer food, but they need a lot of magical energy to deliver presents on Christmas. * For that, their favorite snack is a special type of star fruit that only grows deep in the jungle. The Elves have brought you on their annual expedition to the grove where the fruit grows. * * To supply enough magical energy, the expedition needs to retrieve a minimum of fifty stars by December 25th. * Although the Elves assure you that the grove has plenty of fruit, you decide to grab any fruit you see along the way, just in case. * * Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; * the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck! * * PART 1: * The jungle must be too overgrown and difficult to navigate in vehicles or access from the air; the Elves' expedition traditionally goes on foot. * As your boats approach land, the Elves begin taking inventory of their supplies. One important consideration is food - in particular, the number of Calories each Elf is carrying (your puzzle input). * * The Elves take turns writing down the number of Calories contained by the various meals, snacks, rations, etc. * that they've brought with them, one item per line. Each Elf separates their own inventory from the previous Elf's inventory (if any) by a blank line. * * For example, suppose the Elves finish writing their items' Calories and end up with the following list: * * 1000 * 2000 * 3000 * * 4000 * * 5000 * 6000 * * 7000 * 8000 * 9000 * * 10000 * * This list represents the Calories of the food carried by five Elves: * * The first Elf is carrying food with 1000, 2000, and 3000 Calories, a total of 6000 Calories. * The second Elf is carrying one food item with 4000 Calories. * The third Elf is carrying food with 5000 and 6000 Calories, a total of 11000 Calories. * The fourth Elf is carrying food with 7000, 8000, and 9000 Calories, a total of 24000 Calories. * The fifth Elf is carrying one food item with 10000 Calories. * In case the Elves get hungry and need extra snacks, they need to know which Elf to ask: they'd like to know how many Calories are being carried by the Elf carrying the most Calories. In the example above, this is 24000 (carried by the fourth Elf). * * Find the Elf carrying the most Calories. How many total Calories is that Elf carrying? * * * PART 2: * By the time you calculate the answer to the Elves' question, they've already realized that the Elf carrying the most Calories of food might eventually run out of snacks. * * To avoid this unacceptable situation, the Elves would instead like to know the total Calories carried by the top three Elves carrying the most Calories. * That way, even if one of those Elves runs out of snacks, they still have two backups. * * In the example above, the top three Elves are the fourth Elf (with 24000 Calories), then the third Elf (with 11000 Calories), then the fifth Elf (with 10000 Calories). * The sum of the Calories carried by these three elves is 45000. * * Find the top three Elves carrying the most Calories. How many Calories are those Elves carrying in total? */ private fun main() { fun part1(input: List<String>): Int { val result = mutableListOf(0) var currentElfIndex = 0 input.forEach { line -> if (line.isEmpty()) { currentElfIndex++ result.add(0) } else { result[currentElfIndex] += line.toInt() } } return result.max() } fun part2(input: List<String>): Int { val result = mutableListOf(0) var currentElfIndex = 0 input.forEach { line -> if (line.isEmpty()) { currentElfIndex++ result.add(0) } else { result[currentElfIndex] += line.toInt() } } val sorted = result.sortedDescending() return sorted[0] + sorted[1] + sorted[2] } val testInput = readInput("Day01_test") check(part1(testInput) == 24000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f6e9a0b6c2b66c28f052d461c79ad4f427dbdfc8
4,310
advent-of-code-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/DecodeWays2.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.MOD import dev.shtanko.algorithms.extensions.lessThanZero // TODO Rename constants private const val NINE = 9 private const val SIX = 6 private const val FIFTEEN = 15 fun interface DecodeWays2Strategy { operator fun invoke(s: String): Int } class DecodeWays2RecursionWithMemoization : DecodeWays2Strategy { override operator fun invoke(s: String): Int { if (s.isBlank()) return 0 val memo = arrayOfNulls<Int>(s.length) return ways(s, s.length - 1, memo) } private fun ways(s: String, i: Int, memo: Array<Int?>): Int { if (i.lessThanZero()) return 1 if (memo[i] != null) return memo[i] ?: 1 if (s[i] == '*') { memo[i] = getRes(s, i, memo) return memo[i] ?: 1 } var res = if (s[i] != '0') ways(s, i - 1, memo).toLong() else 0L if (i > 0) { res = when (s[i - 1]) { '1' -> justCalculateRes(s, i, memo, res) '2' -> { if (s[i] <= '6') { justCalculateRes(s, i, memo, res) } else { res } } '*' -> { val r = if (s[i] <= '6') 2 else 1 calculateRes(s, i, memo, res, r) } else -> res } } memo[i] = res.toInt() return memo[i] ?: 1 } private fun getRes(s: String, i: Int, memo: Array<Int?>): Int { val j = i - 1 var res = NINE * ways(s, j, memo).toLong() if (i > 0) { res = when (s[j]) { '1' -> calculateRes(s, i, memo, res, NINE) '2' -> calculateRes(s, i, memo, res, SIX) '*' -> calculateRes(s, i, memo, res, FIFTEEN) else -> { res } } } return res.toInt() } private fun calculateRes(s: String, i: Int, memo: Array<Int?>, res: Long, value: Int): Long { val local = res + value * ways(s, i - 2, memo) return local % MOD } private fun justCalculateRes(s: String, i: Int, memo: Array<Int?>, res: Long): Long { val local = res + ways(s, i - 2, memo) return local % MOD } } class DecodeWays2DynamicProgramming : DecodeWays2Strategy { override operator fun invoke(s: String): Int { if (s.isBlank()) return 0 val dp = LongArray(s.length + 1) dp[0] = 1 dp[1] = if (s[0] == '*') NINE.toLong() else if (s[0] == '0') 0 else 1L for (i in 1 until s.length) { if (s[i] == '*') { dp[i + 1] = NINE * dp[i] calculateDP(dp, i, s) } else { dp[i + 1] = if (s[i] != '0') dp[i] else 0 dp[i + 1] = when (s[i - 1]) { '1' -> { getDp(dp, i) } '2' -> { if (s[i] <= '6') { getDp(dp, i) } else { dp[i + 1] } } '*' -> { val local = if (s[i] <= '6') 2 else 1 val calculated = dp[i + 1] + local * dp[i - 1] calculated % MOD } else -> { dp[i + 1] } } } } return dp[s.length].toInt() } private fun getDp(dp: LongArray, i: Int): Long { val local = dp[i + 1].plus(dp[i - 1]) return local % MOD } private fun calculateDP(dp: LongArray, i: Int, s: String) { when (s[i - 1]) { '1' -> justCalculateDP(dp, i, NINE) '2' -> justCalculateDP(dp, i, SIX) '*' -> justCalculateDP(dp, i, FIFTEEN) } } private fun justCalculateDP(dp: LongArray, i: Int, value: Int) { dp[i + 1] = (dp[i + 1] + value * dp[i - 1]) % MOD } } class DecodeWays2ConstantSpaceDynamicProgramming : DecodeWays2Strategy { override operator fun invoke(s: String): Int { if (s.isBlank()) return 0 var first: Long = 1 var second = if (s[0] == '*') NINE.toLong() else if (s[0] == '0') 0 else 1.toLong() for (i in 1 until s.length) { val temp = second if (s[i] == '*') { second *= NINE second = calculateSecond(s, i, first, second) } else { second = if (s[i] != '0') second else 0 second = when (s[i - 1]) { '1' -> sumM(first, second) '2' -> { if (s[i] <= '6') { sumM(first, second) } else { second } } '*' -> { val local = if (s[i] <= '6') 2 else 1 justCalculate(first, second, local) } else -> second } } first = temp } return second.toInt() } private fun sumM(first: Long, second: Long): Long { val sum = second.plus(first) return sum % MOD } private fun calculateSecond(s: String, i: Int, first: Long, second: Long): Long { return when (s[i - 1]) { '1' -> justCalculate(first, second, NINE) '2' -> justCalculate(first, second, SIX) '*' -> justCalculate(first, second, FIFTEEN) else -> second } } private fun justCalculate(first: Long, second: Long, value: Int): Long { val local = second + value * first return local % MOD } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
6,560
kotlab
Apache License 2.0
2021/kotlin/src/main/kotlin/com/pietromaggi/aoc2021/day01/Day01.kt
pfmaggi
438,378,048
false
{"Kotlin": 113883, "Zig": 18220, "C": 7779, "Go": 4059, "CMake": 386, "Awk": 184}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pietromaggi.aoc2021.day01 import com.pietromaggi.aoc2021.readInput /* * Count number of increases in the List<Int> passed to the function. */ fun countIncreases(numbers: List<Int>): Int { return numbers.zipWithNext().count { (first, second) -> second > first } } fun part1(input: List<String>) = countIncreases(input.map(String::toInt)) fun part2(input: List<String>) = countIncreases(input.map(String::toInt).windowed(3) { it.sum() }) fun main() { val input = readInput("Day01") println("How many measurements are larger than the previous measurement?") println("My puzzle answer is: ${part1(input)}") println("How many sums are larger than the previous sum?") println("My puzzle answer is: ${part2(input)}") }
0
Kotlin
0
0
7c4946b6a161fb08a02e10e99055a7168a3a795e
1,364
AdventOfCode
Apache License 2.0
src/Day01.kt
gomercin
572,911,270
false
{"Kotlin": 25313}
/** * Searches I needed to make: kotlin for loop kotlin check string empty kotlin string to integer kotlin array kotlin list kotlin mutable list kotlin sort kotlin sort reverse kotlin split list kotlin sum list */ fun main() { fun part1(input: List<String>): Int { var currentMax = 0 var currentSum = 0 for (line in input) { if (line.isEmpty()) { if (currentSum > currentMax) { currentMax = currentSum } currentSum = 0 } else { currentSum += line.toInt() } } return currentMax } fun part2(input: List<String>): Int { // input is small enough to handle with sorting // would also work for the first part val calorieList = mutableListOf<Int>() var currentSum = 0 for (line in input) { if (line.isEmpty()) { calorieList.add(currentSum) currentSum = 0 } else { currentSum += line.toInt() } } calorieList.sortDescending() return calorieList.subList(0, 3).sum() } val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
30f75c4103ab9e971c7c668f03f279f96dbd72ab
1,279
adventofcode-2022
Apache License 2.0
kotlin/strings/Manacher.kt
polydisc
281,633,906
true
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
package strings import java.util.Arrays // Manacher's algorithm to finds all palindromes: https://cp-algorithms.com/string/manacher.html object Manacher { // d1[i] - how many palindromes of odd length with center at i fun oddPalindromes(s: String): IntArray { val n: Int = s.length() val d1 = IntArray(n) var l = 0 var r = -1 for (i in 0 until n) { var k = (if (i > r) 0 else Math.min(d1[l + r - i], r - i)) + 1 while (i + k < n && i - k >= 0 && s.charAt(i + k) === s.charAt(i - k)) ++k d1[i] = k-- if (i + k > r) { l = i - k r = i + k } } return d1 } // d2[i] - how many palindromes of even length with center at i fun evenPalindromes(s: String): IntArray { val n: Int = s.length() val d2 = IntArray(n) var l = 0 var r = -1 for (i in 0 until n) { var k = (if (i > r) 0 else Math.min(d2[l + r - i + 1], r - i + 1)) + 1 while (i + k - 1 < n && i - k >= 0 && s.charAt(i + k - 1) === s.charAt(i - k)) ++k d2[i] = --k if (i + k - 1 > r) { l = i - k r = i + k - 1 } } return d2 } // Usage example fun main(args: Array<String?>?) { val text = "aaaba" System.out.println(Arrays.toString(oddPalindromes(text))) System.out.println(Arrays.toString(evenPalindromes(text))) } }
1
Java
0
0
4566f3145be72827d72cb93abca8bfd93f1c58df
1,526
codelibrary
The Unlicense
src/main/kotlin/com/groundsfam/advent/y2020/d17/Day17.kt
agrounds
573,140,808
false
{"Kotlin": 281620, "Shell": 742}
package com.groundsfam.advent.y2020.d17 import com.groundsfam.advent.DATAPATH import java.util.ArrayDeque import java.util.Queue import kotlin.io.path.div import kotlin.io.path.useLines private typealias Point = Triple<Int, Int, Int> private typealias State = Set<Point> private fun State.next(): State { val thisState = this val nextState = mutableSetOf<Point>() val queue: Queue<Point> = ArrayDeque<Point>().apply { addAll(thisState) } val prevQueued = mutableSetOf<Point>().apply { addAll(thisState) } while (queue.isNotEmpty()) { queue.poll().let { point -> val (x, y, z) = point val activeNeighbors = (-1..1).sumOf { dx -> (-1..1).sumOf { dy -> (-1..1).count { dz -> val neighbor = Point(x + dx, y + dy, z + dz) if (point in thisState && neighbor !in prevQueued) { queue.add(neighbor) prevQueued.add(neighbor) } neighbor != point && neighbor in thisState } } } when { point in thisState && (activeNeighbors in setOf(2, 3)) -> nextState.add(point) point !in thisState && activeNeighbors == 3 -> nextState.add(point) else -> {} // don't add to next state } } } return nextState } private data class Point4(val x: Int, val y: Int, val z: Int, val w: Int) private typealias State4 = Set<Point4> private fun State4.next4(): State4 { val thisState = this val nextState = mutableSetOf<Point4>() val queue: Queue<Point4> = ArrayDeque<Point4>().apply { addAll(thisState) } val prevQueued = mutableSetOf<Point4>().apply { addAll(thisState) } while (queue.isNotEmpty()) { queue.poll().let { point -> val (x, y, z, w) = point val activeNeighbors = (-1..1).sumOf { dx -> (-1..1).sumOf { dy -> (-1..1).sumOf { dz -> (-1..1).count { dw -> val neighbor = Point4(x + dx, y + dy, z + dz, w + dw) if (point in thisState && neighbor !in prevQueued) { queue.add(neighbor) prevQueued.add(neighbor) } neighbor != point && neighbor in thisState } } } } when { point in thisState && (activeNeighbors in setOf(2, 3)) -> nextState.add(point) point !in thisState && activeNeighbors == 3 -> nextState.add(point) else -> {} // don't add to next state } } } return nextState } fun main() { val initialState = mutableSetOf<Point>() val initialState4 = mutableSetOf<Point4>() (DATAPATH / "2020/day17.txt").useLines { lines -> lines.forEachIndexed { y, line -> line.forEachIndexed { x, c -> if (c == '#') { initialState.add(Point(x, y, 0)) initialState4.add(Point4(x, y, 0, 0)) } } } } var state: State = initialState repeat(6) { state = state.next() } println("Part one: ${state.size}") var state4: State4 = initialState4 repeat(6) { state4 = state4.next4() } println("Part two: ${state4.size}") }
0
Kotlin
0
1
c20e339e887b20ae6c209ab8360f24fb8d38bd2c
3,712
advent-of-code
MIT License
scripts/Day24.kts
matthewm101
573,325,687
false
{"Kotlin": 63435}
import java.io.File import kotlin.math.max data class Pos(val x: Int, val y: Int) { operator fun plus(a: Pos) = Pos(x + a.x, y + a.y) } val RIGHT = Pos(1,0) val LEFT = Pos(-1,0) val DOWN = Pos(0,1) val UP = Pos(0,-1) val raw = File("../inputs/24.txt").readLines() val minWindX = 1 val minWindY = 1 val maxWindX = raw[0].length - 2 val maxWindY = raw.size - 2 val startingWalls = raw.flatMapIndexed { y, line -> line.mapIndexed { x, c -> if (c == '#') Pos(x,y) else null } }.filterNotNull().plus(Pos(1,-1)).plus(Pos(maxWindX,maxWindY+2)).toSet() val startingLefts = raw.flatMapIndexed { y, line -> line.mapIndexed { x, c -> if (c == '<') Pos(x,y) else null } }.filterNotNull().toSet() val startingRights = raw.flatMapIndexed { y, line -> line.mapIndexed { x, c -> if (c == '>') Pos(x,y) else null } }.filterNotNull().toSet() val startingUps = raw.flatMapIndexed { y, line -> line.mapIndexed { x, c -> if (c == '^') Pos(x,y) else null } }.filterNotNull().toSet() val startingDowns = raw.flatMapIndexed { y, line -> line.mapIndexed { x, c -> if (c == 'v') Pos(x,y) else null } }.filterNotNull().toSet() val cycleTimeLR = maxWindX - minWindX + 1 val cycleTimeUD = maxWindY - minWindY + 1 val cycleTime = (max(cycleTimeLR,cycleTimeUD)..cycleTimeLR*cycleTimeUD).first { it % cycleTimeUD == 0 && it % cycleTimeLR == 0} // brute-force LCM calculation val startPos = Pos(1,0) val endPos = Pos(maxWindX,maxWindY+1) fun wrap(p: Pos) = if (p.x > maxWindX) Pos(minWindX, p.y) else if (p.x < minWindX) Pos(maxWindX, p.y) else if (p.y > maxWindY) Pos(p.x, minWindY) else if (p.y < minWindY) Pos(p.x, maxWindY) else p val wallList: MutableList<Set<Pos>> = mutableListOf(startingWalls + startingLefts + startingRights + startingUps + startingDowns) var lefts = startingLefts var rights = startingRights var ups = startingUps var downs = startingDowns for (i in 1 until cycleTime) { lefts = lefts.map { wrap(it + LEFT) }.toSet() rights = rights.map { wrap(it + RIGHT) }.toSet() ups = ups.map { wrap(it + UP) }.toSet() downs = downs.map { wrap(it + DOWN) }.toSet() wallList += startingWalls + lefts + rights + ups + downs } data class State(val time: Int, val pos: Pos) { fun nexts(): List<State> { val t = time + 1 val options = mutableListOf<State>() if (pos !in wallList[t.mod(cycleTime)]) options += State(t,pos) if ((pos + LEFT) !in wallList[t.mod(cycleTime)]) options += State(t,pos + LEFT) if ((pos + RIGHT) !in wallList[t.mod(cycleTime)]) options += State(t,pos + RIGHT) if ((pos + UP) !in wallList[t.mod(cycleTime)]) options += State(t,pos + UP) if ((pos + DOWN) !in wallList[t.mod(cycleTime)]) options += State(t,pos + DOWN) return options } } run { val start = State(0,startPos) var frontier = setOf(start) var solution: State? while (true) { frontier = frontier.flatMap { it.nexts() }.toSet() solution = frontier.find { it.pos == endPos } if (solution != null) break } println("The goal can be reached in ${solution!!.time} minutes.") } data class State2(val time: Int, val pos: Pos, val progress: Int) { fun nexts(): List<State2> { val t = time + 1 val options = mutableListOf<State2>() if (pos !in wallList[t.mod(cycleTime)]) options += State2(t,pos, progress) if ((pos + LEFT) !in wallList[t.mod(cycleTime)]) options += State2(t,pos + LEFT, progress) if ((pos + RIGHT) !in wallList[t.mod(cycleTime)]) options += State2(t,pos + RIGHT, progress) if ((pos + UP) !in wallList[t.mod(cycleTime)]) options += State2(t,pos + UP, progress) if ((pos + DOWN) !in wallList[t.mod(cycleTime)]) options += State2(t,pos + DOWN, progress) for (i in options.indices) { if (options[i].progress == 0 && options[i].pos == endPos) options[i] = State2(options[i].time, options[i].pos, 1) if (options[i].progress == 1 && options[i].pos == startPos) options[i] = State2(options[i].time, options[i].pos, 2) } return options } } run { val start = State2(0,startPos,0) var frontier = setOf(start) var solution: State2? while (true) { frontier = frontier.flatMap { it.nexts() }.toSet() solution = frontier.find { it.pos == endPos && it.progress == 2 } if (solution != null) break } println("Going back, forth, and back again takes ${solution!!.time} minutes.") }
0
Kotlin
0
0
bbd3cf6868936a9ee03c6783d8b2d02a08fbce85
4,594
adventofcode2022
MIT License
src/array/LeetCode139.kt
Alex-Linrk
180,918,573
false
null
package array import java.util.* /** *给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。 说明: 拆分时可以重复使用字典中的单词。 你可以假设字典中没有重复的单词。 示例 1: 输入: s = "leetcode", wordDict = ["leet", "code"] 输出: true 解释: 返回 true 因为 "leetcode" 可以被拆分成 "leet code"。 示例 2: 输入: s = "applepenapple", wordDict = ["apple", "pen"] 输出: true 解释: 返回 true 因为 "applepenapple" 可以被拆分成 "apple pen apple"。 注意你可以重复使用字典中的单词。 示例 3: 输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"] 输出: false * *解法:典型动态规划 * **/ class Solution139 { fun wordBreak(s: String, wordDict: List<String>): Boolean { val n = s.length var meno = Array(n + 1) { false } meno[0] = true for (x in 1..n) { for (y in 0 until x) { if (meno[y] && wordDict.contains(s.substring(y, x))) { meno[x] = true println(meno.toList()) break } } } return meno[n] } } fun main() { println( Solution139().wordBreak( "pineapplepenapple", listOf("apple", "pen", "applepen", "pine", "pineapple") ) ) }
0
Kotlin
0
0
59f4ab02819b7782a6af19bc73307b93fdc5bf37
1,507
LeetCode
Apache License 2.0
src/Day10.kt
mkulak
573,910,880
false
{"Kotlin": 14860}
fun main() { fun part1(input: List<String>): Int { var cycle = 1 var register = 1 var res = 0 fun checkCycle() { if (cycle in setOf(20, 60, 100, 140, 180, 220)) { res += cycle * register } } input.forEach { line -> val inc = if (line != "noop") { cycle++ checkCycle() line.drop(5).toInt() } else 0 cycle++ register += inc checkCycle() } return res } fun part2(input: List<String>): Int { val width = 40 val height = 6 val screen = BooleanArray(width * height) var register = 1 var cycle = 0 fun checkCycle() { if ((cycle % width) in (register - 1)..(register + 1) ) { screen[cycle] = true } } input.forEach { line -> val inc = if (line != "noop") { cycle++ checkCycle() line.drop(5).toInt() } else 0 cycle++ register += inc checkCycle() } screen.toList().chunked(width).forEach { line -> println(line.joinToString("") { if (it) "█" else " " }) } return 0 } val input = readInput("Day10") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
3b4e9b32df24d8b379c60ddc3c007d4be3f17d28
1,435
AdventOfKo2022
Apache License 2.0
src/main/kotlin/dayone/DayOne.kt
pauliancu97
619,525,509
false
null
package dayone import getLines private fun getElvesCalories(strings: List<String>): List<List<Int>> { val separatorIndices = listOf(-1) + strings.withIndex().mapNotNull { (index, string) -> if (string.isEmpty()) index else null } + listOf(strings.size) return separatorIndices.zipWithNext { start, end -> val stringsSublist = strings.subList(start + 1, end) stringsSublist.map { it.toInt() } } } private fun getMaxCaloriesForElf(elves: List<List<Int>>): Int = elves.maxOf { calories -> calories.sum() } private fun getCaloriesOfTopElves(elves: List<List<Int>>): Int = elves .map { calories -> calories.sum() } .sortedDescending() .take(3) .sum() private fun solvePartOne() { val strings = getLines("day_1.txt") val elves = getElvesCalories(strings) println(getMaxCaloriesForElf(elves)) } private fun solvePartTwo() { val strings = getLines("day_1.txt") val elves = getElvesCalories(strings) println(getCaloriesOfTopElves(elves)) } fun main() { solvePartTwo() }
0
Kotlin
0
0
78af929252f094a34fe7989984a30724fdb81498
1,087
advent-of-code-2022
MIT License
src/Day02.kt
cagriyildirimR
572,811,424
false
{"Kotlin": 34697}
import java.io.File fun day02() { val input = File("src/Day02.txt").readLines() val resultTable = mapOf( "Rock Rock" to 1 + 3, "Rock Paper" to 2 + 6, "Rock Scissor" to 3 + 0, "Paper Rock" to 1 + 0, "Paper Paper" to 2 + 3, "Paper Scissor" to 3 + 6, "Scissor Rock" to 1 + 6, "Scissor Paper" to 2 + 0, "Scissor Scissor" to 3 + 3 ) val myChoice = mapOf('X' to "Rock", 'Y' to "Paper", 'Z' to "Scissor") val xyzTable = mapOf( 'X' to mapOf("Rock" to "Scissor", "Paper" to "Rock", "Scissor" to "Paper"), 'Y' to mapOf("Rock" to "Rock", "Paper" to "Paper", "Scissor" to "Scissor"), 'Z' to mapOf("Rock" to "Paper", "Paper" to "Scissor", "Scissor" to "Rock")) val opTable = mapOf('A' to "Rock", 'B' to "Paper", 'C' to "Scissor") var result1 = 0 var result2 = 0 for (i in input) { val opponentChoice = opTable[i.first()]!! val key1 = opponentChoice + " " + myChoice[i.last()]!! result1 += resultTable[key1]!! val key2 = opponentChoice + " " + xyzTable[i.last()]!![opponentChoice] result2 += resultTable[key2]!! } result1.print() result2.print() }
0
Kotlin
0
0
343efa0fb8ee76b7b2530269bd986e6171d8bb68
1,228
AoC
Apache License 2.0
kotlin/src/main/kotlin/io/github/ocirne/aoc/year2022/Day24.kt
ocirne
327,578,931
false
{"Python": 323051, "Kotlin": 67246, "Sage": 5864, "JavaScript": 832, "Shell": 68}
package io.github.ocirne.aoc.year2022 import io.github.ocirne.aoc.AocChallenge import java.util.* typealias Position = Pair<Int, Int> data class MinutePosition(val minute: Int, val x: Int, val y: Int) { constructor(minute: Int, p: Position) : this(minute, p.first, p.second) fun position(): Position { return Position(x, y) } fun move(dx: Int, dy: Int): MinutePosition { return MinutePosition(minute + 1, x + dx, y + dy) } } val oldest: Comparator<MinutePosition> = compareBy { it.minute } class Day24(val lines: List<String>) : AocChallenge(2022, 24) { private val initialMap = createInitialMap() private val allMaps = mutableMapOf<Int, Set<Position>>() private val width = if (lines.isNotEmpty()) lines.first().length else 0 private val height = lines.size private val start = Position(1, 0) private val end = Position(width - 2, height - 1) private val movements: List<Position> = listOf(Pair(0, 0), Pair(-1, 0), Pair(1, 0), Pair(0, -1), Pair(0, 1)) private fun createInitialMap(): Map<Position, Char> { return lines.flatMapIndexed { y, line -> line.mapIndexed { x, t -> Pair(x, y) to t } } .filter { (_, t) -> t != '.' }.toMap() } private fun atMinute(minute: Int): Set<Position> { return initialMap.map { (pos, t) -> val (x, y) = pos when (t) { '#' -> pos '<' -> Position((x - 1 - minute).mod(width - 2) + 1, y) '>' -> Position((x - 1 + minute).mod(width - 2) + 1, y) '^' -> Position(x, (y - 1 - minute).mod(height - 2) + 1) 'v' -> Position(x, (y - 1 + minute).mod(height - 2) + 1) else -> throw IllegalArgumentException("$pos $t") } }.toSet() } private fun findNeighbors(current: MinutePosition): List<MinutePosition> { val walls = allMaps.computeIfAbsent(current.minute + 1) { atMinute(it) } return movements .map { (dx, dy) -> current.move(dx, dy) } .filter { it.x in 0..width && it.y in 0..height } .filter { it.position() !in walls } } private fun dijkstra(start: Position, end: Position, minute_0: Int = 0): Int { val openHeap = PriorityQueue(oldest) val closedSet = mutableSetOf<MinutePosition>() openHeap.add(MinutePosition(minute_0, start)) while (openHeap.isNotEmpty()) { val current = openHeap.remove() if (current.position() == end) { return current.minute } if (current in closedSet) { continue } closedSet.add(current) for (neighbor in findNeighbors(current)) { openHeap.add(neighbor) } } throw RuntimeException() } override fun part1(): Int { return dijkstra(start = start, end = end) } override fun part2(): Int { val m1 = dijkstra(start = start, end = end) val m2 = dijkstra(start = end, end = start, m1) return dijkstra(start = start, end = end, m2) } }
0
Python
0
1
b8a06fa4911c5c3c7dff68206c85705e39373d6f
3,154
adventofcode
The Unlicense
src/Day13.kt
LauwiMeara
572,498,129
false
{"Kotlin": 109923}
const val OPEN_BRACKET = '[' const val CLOSE_BRACKET = ']' const val COMMA = ',' const val DIVIDER_PACKET_1 = "[[2]]" const val DIVIDER_PACKET_2 = "[[6]]" data class PacketPair (var left: String, var right: String) fun main() { fun addBrackets(partPair: String, charIndex: Int): String { val prev = partPair.substring(0, charIndex) val nextTotal = partPair.substring(charIndex, partPair.length) val indexAfterNumber = listOf(nextTotal.indexOf(CLOSE_BRACKET), nextTotal.indexOf(COMMA)).filter{it >= 0}.min() val next1 = nextTotal.substring(0, indexAfterNumber) val next2 = nextTotal.substring(indexAfterNumber, nextTotal.length) return "$prev[$next1]$next2" } fun getNumber(partPair: String, charIndex: Int): Int { val next = partPair.substring(charIndex, partPair.length) val indexAfterNumber = listOf(next.indexOf(CLOSE_BRACKET), next.indexOf(COMMA)).filter{it >= 0}.min() return next.substring(0, indexAfterNumber).toInt() } fun pairIsCorrectlyOrdered(pair: PacketPair, printProgress: Boolean): Boolean { var isCorrectOrder = true for (charIndex in 0 until pair.left.length) { val leftChar = pair.left[charIndex] val rightChar = pair.right[charIndex] if (printProgress) { println("Left: $leftChar} Right: $rightChar") } // If both chars are the same and are not numbers, check the next chars. if (leftChar == rightChar && leftChar.digitToIntOrNull() == null) continue // If leftChar is CLOSE_BRACKET (and rightChar isn't), the order is correct. else if (leftChar == CLOSE_BRACKET) break // If rightChar is CLOSE_BRACKET (and leftChar isn't), the order is incorrect. else if (rightChar == CLOSE_BRACKET) { isCorrectOrder = false break } // If one char is OPEN_BRACKET, add brackets to the other char and check the next chars. else if (leftChar == OPEN_BRACKET) { pair.right = addBrackets(pair.right, charIndex) continue } else if (rightChar == OPEN_BRACKET) { pair.left = addBrackets(pair.left, charIndex) continue } // If we reach this point, the chars are numbers. // If the left number is smaller, the order is correct; if the left number is bigger, the order is incorrect. val leftNumber = getNumber(pair.left, charIndex) val rightNumber = getNumber(pair.right, charIndex) if (leftNumber < rightNumber) break else if (leftNumber > rightNumber) { isCorrectOrder = false break } } if (printProgress) { val result = if (isCorrectOrder) "CORRECT" else "INCORRECT" println(result) } return isCorrectOrder } fun part1(input: List<PacketPair>, printProgress: Boolean = true): Int { val indicesOfCorrectPairs = mutableListOf<Int>() for (pairIndex in input.indices) { val pair = input[pairIndex] if (printProgress) { println("Pair: ${pairIndex + 1}") println(pair.left) println(pair.right) } // If pair is in correct order, add index + 1 to the list. if (pairIsCorrectlyOrdered(pair, printProgress)) { indicesOfCorrectPairs.add(pairIndex + 1) } } return indicesOfCorrectPairs.sum() } fun part2(input: List<String>, printProgress: Boolean = true): Int { val dividerPackets = listOf(DIVIDER_PACKET_1, DIVIDER_PACKET_2) val fullInput = (input + dividerPackets).toMutableList() // Sort input using Bubble Sort. var isCorrectOrder = false while (!isCorrectOrder) { for (i in 0 until fullInput.size - 1) { if (printProgress) { println("Checking packet ${i + 1} and ${i + 2}") } val pair = PacketPair(fullInput[i], fullInput[i + 1]) if (!pairIsCorrectlyOrdered(pair, false)) { val temp = fullInput[i] fullInput[i] = fullInput[i + 1] fullInput[i + 1] = temp break } else if (i == fullInput.size - 2) { isCorrectOrder = true break } } } // Find indexes of the divider packets. val index1 = fullInput.indexOf(DIVIDER_PACKET_1) + 1 val index2 = fullInput.indexOf(DIVIDER_PACKET_2) + 1 return index1 * index2 } val inputPart1 = readInputSplitByDelimiter("Day13", "${System.lineSeparator()}${System.lineSeparator()}") .map{it.split(System.lineSeparator())} .map{PacketPair(it.first(), it.last())} val inputPart2 = readInputAsStrings("Day13").filter{it.isNotEmpty()} println(part1(inputPart1, false)) println(part2(inputPart2, false)) }
0
Kotlin
0
1
34b4d4fa7e562551cb892c272fe7ad406a28fb69
5,183
AoC2022
Apache License 2.0
src/Day10.kt
Oktosha
573,139,677
false
{"Kotlin": 110908}
import kotlin.math.abs fun main() { fun getAnsIncrement(x: Int, op: Int): Int { assert(op < 260) if (op >= 20 && (op - 20) % 40 == 0) { println("$op * $x = ${op * x}") return op * x } return 0 } fun part1(input: List<String>): Int { var x = 1 var op = 1 var ans = 0 for (line in input) { val cmd = line.split(" ") op += 1 ans += getAnsIncrement(x, op) if (cmd[0] == "addx") { op += 1 x += cmd[1].toInt() ans += getAnsIncrement(x, op) } } return ans } class State(var x: Int, var op: Int) fun printState(state: State) { val pos = state.op % 40 if (pos == 0) { println() } print(if (abs(state.x - pos) <= 1) "#" else ".") } fun part2(input: List<String>) { val state = State(1, 0) printState(state) for (line in input) { val cmd = line.split(" ") state.op += 1 printState(state) if (cmd[0] == "addx") { state.op += 1 state.x += cmd[1].toInt() printState(state) } } } println("Day 10") val input = readInput("Day10") println(part1(input)) part2(input) }
0
Kotlin
0
0
e53eea61440f7de4f2284eb811d355f2f4a25f8c
1,405
aoc-2022
Apache License 2.0
src/main/kotlin/biz/koziolek/adventofcode/year2021/day10/day10.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2021.day10 import biz.koziolek.adventofcode.findInput import java.util.* import kotlin.reflect.KClass fun main() { val inputFile = findInput(object {}) val lines = inputFile.bufferedReader().readLines() val rootChunks = parseChunks(lines) println("Corrupted chunks score: ${getCorruptedChunksScore(rootChunks)}") val containingIncompleteChunks = rootChunks.filter { !it.contains(CorruptedChunk::class) && it.contains(IncompleteChunk::class) } println("Autocomplete score: ${getAutocompleteScore(containingIncompleteChunks)}") } sealed interface Chunk { val children: List<Chunk> fun addChild(chunk: Chunk): Chunk fun asCode(): String fun contains(clazz: KClass<out Chunk>): Boolean = clazz.isInstance(this) || children.any { it.contains(clazz) } fun <T : Chunk> find(clazz: KClass<T>): T? = if (clazz.isInstance(this)) { this as T } else { children.mapNotNull { it.find(clazz) }.firstOrNull() } fun complete(): Chunk } data class RootChunk(override val children: List<Chunk>) : Chunk { override fun addChild(chunk: Chunk) = RootChunk(children + chunk) override fun asCode() = children.joinToString("") { it.asCode() } override fun complete() = RootChunk(children.map { it.complete() }) } data class IncompleteChunk( val open: Char, override val children: List<Chunk> = emptyList() ) : Chunk { fun close(close: Char): Chunk = if (bracketsMatch(open, close)) { CompleteChunk(open, close, children) } else { CorruptedChunk(open, close, children) } override fun addChild(chunk: Chunk): Chunk = IncompleteChunk(open, children + chunk) override fun asCode(): String = open + children.joinToString("") { it.asCode() } override fun complete() = CompleteChunk( open = open, close = openToCloseBracketsMap[open]!!, children = children.map { it.complete() } ) } data class CompleteChunk( val open: Char, val close: Char, override val children: List<Chunk> ) : Chunk { override fun addChild(chunk: Chunk): Chunk = CompleteChunk(open, close, children + chunk) override fun asCode(): String = open + children.joinToString("") { it.asCode() } + close override fun complete() = CompleteChunk( open = open, close = close, children = children.map { it.complete() } ) } data class CorruptedChunk( val open: Char, val close: Char, override val children: List<Chunk> ) : Chunk { override fun addChild(chunk: Chunk): Chunk = CorruptedChunk(open, close, children + chunk) override fun asCode(): String = open + children.joinToString("") { it.asCode() } + close fun getErrorMessage() = "Expected ${openToCloseBracketsMap[open]}, but found $close instead." override fun complete() = CompleteChunk( open = open, close = openToCloseBracketsMap[open]!!, children = children.map { it.complete() } ) } private val openToCloseBracketsMap = mapOf( '(' to ')', '[' to ']', '{' to '}', '<' to '>' ) private fun bracketsMatch(open: Char, close: Char): Boolean = openToCloseBracketsMap[open] == close fun parseChunks(lines: List<String>): List<RootChunk> = lines.map { parseChunks(it) } fun parseChunks(line: String): RootChunk { val stack: Deque<Chunk> = ArrayDeque() val chunks = mutableListOf<Chunk>() fun updateChildOnStack(child: Chunk) { if (stack.isNotEmpty()) { stack.pop() .addChild(child) .let { newParent -> stack.push(newParent) } } else { chunks.add(child) } } for (c in line.toCharArray()) { if (c in "([{<") { val newChunk = IncompleteChunk(c) stack.push(newChunk) } else { when (val currentChunk = stack.pop()) { is IncompleteChunk -> updateChildOnStack(currentChunk.close(c)) else -> throw IllegalStateException("Tried to close " + currentChunk::class.simpleName) } } } while (stack.isNotEmpty()) { updateChildOnStack(stack.pop()) } return RootChunk(chunks) } fun printChunk(chunk: RootChunk) { println("Chunk string: '${chunk.asCode()}'") println("Has tree:") printChunks(chunk.children) } fun printChunks(chunks: List<Chunk>, indent: Int = 0) { for (chunk in chunks) { print(" ".repeat(indent)) when (chunk) { is RootChunk -> {} is IncompleteChunk -> print(chunk.open) is CompleteChunk -> print(chunk.open) is CorruptedChunk -> print(chunk.open) } if (chunk.children.isNotEmpty()) { println() printChunks(chunk.children, indent = indent + 2) print(" ".repeat(indent)) } when (chunk) { is RootChunk -> {} is IncompleteChunk -> println() is CompleteChunk -> println(chunk.close) is CorruptedChunk -> println(chunk.close) } } } fun getCorruptedChunksScore(rootChunks: List<RootChunk>): Int = rootChunks.filter { it.contains(CorruptedChunk::class) } .map { it.find(CorruptedChunk::class) } .sumOf { getCorruptedPoints(it!!.close) } fun getCorruptedPoints(char: Char): Int = when (char) { ')' -> 3 ']' -> 57 '}' -> 1197 '>' -> 25137 else -> throw IllegalArgumentException("Unexpected close character: $char") } fun getAutocompleteScore(rootChunks: List<RootChunk>): Long { val scores = rootChunks.map { getAutocompleteScore(it) }.sorted() if (scores.size % 2 != 1) { throw IllegalArgumentException("Even number of incomplete chunks passed - this is not supported") } return scores[scores.size / 2] } fun getAutocompleteScore(rootChunk: RootChunk): Long { val oldCode = rootChunk.asCode() val newCode = rootChunk.complete().asCode() val diff = newCode.substring(oldCode.length) return diff.fold(0) { acc, c -> acc * 5 + getAutocompletePoints(c) } } fun getAutocompletePoints(char: Char): Int = when (char) { ')' -> 1 ']' -> 2 '}' -> 3 '>' -> 4 else -> throw IllegalArgumentException("Unexpected close character: $char") }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
6,655
advent-of-code
MIT License
src/main/kotlin/Day4.kt
Mestru
112,782,719
false
null
import java.io.File val letters = "abcdefghijklmnopqrstuvwxyz".toCharArray() fun main(args: Array<String>) { // part 1 var numberOfCorrectPassphrases = 0 File("input/day4.txt").forEachLine { line -> run { if (passphraseIsValid(line)) numberOfCorrectPassphrases++ } } println(numberOfCorrectPassphrases) // part 2 numberOfCorrectPassphrases = 0 File("input/day4.txt").forEachLine { line -> run { val words = line.split(Regex("[ \t]")) val o1 = HashMap<Char, Int>() val o2 = HashMap<Char, Int>() for (letter in letters) { o1.put(letter, 0) o2.put(letter, 0) } var isPassphraseCorrect = true for (i in 0 until words.size) { for (letter in letters) { o1.put(letter, 0) } words[i].toCharArray().forEach { c -> o1.put(c, o1.getValue(c) + 1) } for (j in 0 until words.size) { for (letter in letters) { o2.put(letter, 0) } words[j].toCharArray().forEach { c -> o2.put(c, o2.getValue(c) + 1) } if (i != j && mapsEqual(o1, o2)) isPassphraseCorrect = false } } if (isPassphraseCorrect) numberOfCorrectPassphrases++ } } println(numberOfCorrectPassphrases) } fun passphraseIsValid(line : String) : Boolean { val words = line.split(Regex("[ \t]")) for (i in 0 until words.size) { for (j in 0 until words.size) { if (i != j && words[i].equals(words[j])) return false } } return true } fun mapsEqual(o1: HashMap<Char, Int>, o2: HashMap<Char, Int>): Boolean { for (letter in letters) { if (o1.get(letter) != o2.get(letter)) return false } return true }
0
Kotlin
0
0
2cc4211efc7fa32fb951c19d11cb4a452bfeec2c
1,823
Advent_of_Code_2017
MIT License
src/day17/Day17.kt
easchner
572,762,654
false
{"Kotlin": 104604}
package day17 import readInputString import kotlin.system.measureNanoTime fun main() { val rocks = mutableListOf<Array<Pair<Int, Int>>>() rocks.add(arrayOf(Pair(0, 0), Pair(0, 1), Pair(0, 2), Pair(0, 3))) rocks.add(arrayOf(Pair(0, 1), Pair(1, 0), Pair(1, 1), Pair(1, 2), Pair(2, 1))) rocks.add(arrayOf(Pair(0, 2), Pair(1, 2), Pair(2, 0), Pair(2, 1), Pair(2, 2))) rocks.add(arrayOf(Pair(0, 0), Pair(1, 0), Pair(2, 0), Pair(3, 0))) rocks.add(arrayOf(Pair(0, 0), Pair(0, 1), Pair(1, 0), Pair(1, 1))) fun part1(input: List<String>): Int { val jets = input[0] val chamber = mutableListOf<Array<Boolean>>() chamber.add(Array(7) { true }) var totalMoves = 0 for (t in 0 until 2022) { // Add rock val rock = rocks[t % rocks.size] var height = chamber.indexOfLast { it.contains(true) } + rock.maxOf { it.first } + 4 // Expand chamber if needed while (chamber.size < height + 1) { chamber.add(Array(7) { false }) } var left = 2 var falling = true // While rock is falling while (falling) { falling = false // Push rock val isLeft = jets[totalMoves++ % jets.length] == '<' if (isLeft) { // Check if it clears wall if (left >= 1) { var movesLeft = true for (p in rock) { val newCoord = Pair(height - p.first, left + p.second - 1) if (chamber[newCoord.first][newCoord.second]) { movesLeft = false } } if (movesLeft) { left-- } } } else { // Check if it clears wall if (left + rock.maxOf { it.second } < 6) { var movesRight = true for (p in rock) { val newCoord = Pair(height - p.first, left + p.second + 1) if (chamber[newCoord.first][newCoord.second]) { movesRight = false } } if (movesRight) { left++ } } } // Drop rock var drops = true for (p in rock) { val newCoord = Pair(height - p.first - 1, p.second + left) if (chamber[newCoord.first][newCoord.second]) { drops = false } } if (drops) { height-- falling = true } } // After falling for (p in rock) { chamber[height - p.first][p.second + left] = true } } return chamber.indexOfLast { it.contains(true) } } fun part2(input: List<String>): Long { val jets = input[0] val chamber = mutableListOf<Array<Boolean>>() chamber.add(Array(7) { true }) val maxPeriod = jets.length * rocks.size var totalMoves = 0L val table = Array(maxPeriod * 2 + 1) { 0 } for (t in 0 until maxPeriod * 2 + 1) { // Add rock val rock = rocks[(t % rocks.size)] var height = chamber.indexOfLast { it.contains(true) } + rock.maxOf { it.first } + 4 // Expand chamber if needed while (chamber.size < height + 1) { chamber.add(Array(7) { false }) } var left = 2 var falling = true // While rock is falling while (falling) { falling = false // Push rock val isLeft = jets[(totalMoves++ % jets.length).toInt()] == '<' if (isLeft) { // Check if it clears wall if (left >= 1) { var movesLeft = true for (p in rock) { val newCoord = Pair(height - p.first, left + p.second - 1) if (chamber[newCoord.first][newCoord.second]) { movesLeft = false } } if (movesLeft) { left-- } } } else { // Check if it clears wall if (left + rock.maxOf { it.second } < 6) { var movesRight = true for (p in rock) { val newCoord = Pair(height - p.first, left + p.second + 1) if (chamber[newCoord.first][newCoord.second]) { movesRight = false } } if (movesRight) { left++ } } } // Drop rock var drops = true for (p in rock) { val newCoord = Pair(height - p.first - 1, p.second + left) if (chamber[newCoord.first][newCoord.second]) { drops = false } } if (drops) { height-- falling = true } } // After falling for (p in rock) { chamber[height - p.first][p.second + left] = true } table[t] = chamber.indexOfLast { it.contains(true) } } // Find the period var smallestPeriod = -1 for (i in 1..maxPeriod) { var possiblePeriod = true var offset = 0 val difference = table[i] while (possiblePeriod && offset < maxPeriod) { val a = table[i * 2 + offset] val b = table[i + offset] if (a - b != difference) { possiblePeriod = false } offset++ } if (possiblePeriod) { smallestPeriod = i break } } val periodOffset = 1_000_000_000_000L % smallestPeriod val numPeriods = 1_000_000_000_000L / smallestPeriod - 1 return table[smallestPeriod + periodOffset.toInt() - 1].toLong() + numPeriods * table[smallestPeriod] } val testInput = readInputString("day17/test") val input = readInputString("day17/input") // check(part1(testInput) == 3_068) val time1 = measureNanoTime { println(part1(input)) } println("Time for part 1 was ${"%,d".format(time1)} ns") // println(part2(testInput)) // check(part2(testInput) == 1_514_285_714_288L) val time2 = measureNanoTime { println(part2(input)) } println("Time for part 2 was ${"%,d".format(time2)} ns") }
0
Kotlin
0
0
5966e1a1f385c77958de383f61209ff67ffaf6bf
7,335
Advent-Of-Code-2022
Apache License 2.0
Latin_Squares_in_reduced_form/Kotlin/src/Latin.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}
typealias Matrix = MutableList<MutableList<Int>> fun dList(n: Int, sp: Int): Matrix { val start = sp - 1 // use 0 basing val a = generateSequence(0) { it + 1 }.take(n).toMutableList() a[start] = a[0].also { a[0] = a[start] } a.subList(1, a.size).sort() val first = a[1] // recursive closure permutes a[1:] val r = mutableListOf<MutableList<Int>>() fun recurse(last: Int) { if (last == first) { // bottom of recursion. you get here once for each permutation. // test if permutation is deranged for (jv in a.subList(1, a.size).withIndex()) { if (jv.index + 1 == jv.value) { return // no, ignore it } } // yes, save a copy with 1 based indexing val b = a.map { it + 1 } r.add(b.toMutableList()) return } for (i in last.downTo(1)) { a[i] = a[last].also { a[last] = a[i] } recurse(last - 1) a[i] = a[last].also { a[last] = a[i] } } } recurse(n - 1) return r } fun reducedLatinSquares(n: Int, echo: Boolean): Long { if (n <= 0) { if (echo) { println("[]\n") } return 0 } else if (n == 1) { if (echo) { println("[1]\n") } return 1 } val rlatin = MutableList(n) { MutableList(n) { it } } // first row for (j in 0 until n) { rlatin[0][j] = j + 1 } var count = 0L fun recurse(i: Int) { val rows = dList(n, i) outer@ for (r in 0 until rows.size) { rlatin[i - 1] = rows[r].toMutableList() for (k in 0 until i - 1) { for (j in 1 until n) { if (rlatin[k][j] == rlatin[i - 1][j]) { if (r < rows.size - 1) { continue@outer } if (i > 2) { return } } } } if (i < n) { recurse(i + 1) } else { count++ if (echo) { printSquare(rlatin) } } } } // remaining rows recurse(2) return count } fun printSquare(latin: Matrix) { for (row in latin) { println(row) } println() } fun factorial(n: Long): Long { if (n == 0L) { return 1 } var prod = 1L for (i in 2..n) { prod *= i } return prod } fun main() { println("The four reduced latin squares of order 4 are:\n") reducedLatinSquares(4, true) println("The size of the set of reduced latin squares for the following orders") println("and hence the total number of latin squares of these orders are:\n") for (n in 1 until 7) { val size = reducedLatinSquares(n, false) var f = factorial(n - 1.toLong()) f *= f * n * size println("Order $n: Size %-4d x $n! x ${n - 1}! => Total $f".format(size)) } }
0
D
0
4
c2a9f154a5ae77eea2b34bbe5e0cc2248333e421
3,150
rosetta
MIT License
src/Day08.kt
sbaumeister
572,855,566
false
{"Kotlin": 38905}
fun createTreeMap(input: List<String>): MutableList<List<Int>> { val treeMap = mutableListOf<List<Int>>() input.forEach { line -> val treeHeights = line.toCharArray().map { it.toString().toInt() } treeMap.add(treeHeights) } return treeMap } fun isVisibleFromTop(treeMap: MutableList<List<Int>>, x: Int, y: Int): Boolean { val maxHeight = treeMap[y][x] repeat(y) { i -> if (treeMap[i][x] >= maxHeight) { return false } } return true } fun isVisibleFromBottom(treeMap: MutableList<List<Int>>, x: Int, y: Int): Boolean { val maxHeight = treeMap[y][x] repeat(treeMap.size - y - 1) { i -> if (treeMap[y + i + 1][x] >= maxHeight) { return false } } return true } fun isVisibleFromLeft(treeMap: MutableList<List<Int>>, x: Int, y: Int): Boolean { val maxHeight = treeMap[y][x] repeat(x) { i -> if (treeMap[y][i] >= maxHeight) { return false } } return true } fun isVisibleFromRight(treeMap: MutableList<List<Int>>, x: Int, y: Int): Boolean { val maxHeight = treeMap[y][x] repeat(treeMap[y].size - x - 1) { i -> if (treeMap[y][x + i + 1] >= maxHeight) { return false } } return true } fun calcViewDistanceUp(treeMap: MutableList<List<Int>>, x: Int, y: Int, maxHeight: Int): Int { var viewDistance = 0 repeat(y) { i -> viewDistance++ val height = treeMap[y - i - 1][x] if (height >= maxHeight) { return viewDistance } } return viewDistance } fun calcViewDistanceDown(treeMap: MutableList<List<Int>>, x: Int, y: Int, maxHeight: Int): Int { var viewDistance = 0 repeat(treeMap.size - y - 1) { i -> viewDistance++ val height = treeMap[y + i + 1][x] if (height >= maxHeight) { return viewDistance } } return viewDistance } fun calcViewDistanceLeft(treeMap: MutableList<List<Int>>, x: Int, y: Int, maxHeight: Int): Int { var viewDistance = 0 repeat(x) { i -> viewDistance++ val height = treeMap[y][x - i - 1] if (height >= maxHeight) { return viewDistance } } return viewDistance } fun calcViewDistanceRight(treeMap: MutableList<List<Int>>, x: Int, y: Int, maxHeight: Int): Int { var viewDistance = 0 repeat(treeMap[y].size - x - 1) { i -> viewDistance++ val height = treeMap[y][x + i + 1] if (height >= maxHeight) { return viewDistance } } return viewDistance } fun main() { fun part1(input: List<String>): Int { var countVisible = 0 val treeMap = createTreeMap(input) treeMap.forEachIndexed { y, heights -> heights.forEachIndexed { x, _ -> if (y == 0 || y == treeMap.size - 1 || x == 0 || x == heights.size - 1) { countVisible++ } else { if (isVisibleFromTop(treeMap, x, y) || isVisibleFromBottom(treeMap, x, y) || isVisibleFromLeft(treeMap, x, y) || isVisibleFromRight(treeMap, x, y) ) { countVisible++ } } } } return countVisible } fun part2(input: List<String>): Int { val scenicScores = mutableSetOf<Int>() val treeMap = createTreeMap(input) treeMap.forEachIndexed { y, heights -> heights.forEachIndexed { x, height -> val scenicScore = calcViewDistanceDown(treeMap, x, y, height) * calcViewDistanceUp(treeMap, x, y, height) * calcViewDistanceLeft(treeMap, x, y, height) * calcViewDistanceRight(treeMap, x, y, height) scenicScores.add(scenicScore) } } return scenicScores.max() } val testInput = readInput("Day08_test") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e3afbe3f4c2dc9ece1da7cf176ae0f8dce872a84
4,155
advent-of-code-2022
Apache License 2.0
src/Day01.kt
MisterTeatime
561,848,263
false
{"Kotlin": 20300}
fun main() { fun part1(input: List<String>): Int { return input[0].count{"(".contains(it) } - input[0].count { ")".contains(it) } } fun part2(input: List<String>): Int { var position = -1 var underground = false; input[0].foldIndexed(0) { index, total, c -> if (total < 0 && !underground) { position = index underground = true } when (c){ '(' -> total + 1 ')' -> total - 1 else -> total } } return position } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 3) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d684bd252a9c6e93106bdd8b6f95a45c9924aed6
881
AoC2015
Apache License 2.0
src/main/problem7/solution.kt
lorenzo-piersante
515,177,846
false
{"Kotlin": 15798, "Java": 4893}
package problem7 import java.util.Scanner import kotlin.math.ceil import kotlin.math.sqrt private fun isPrime(n: Int) : Boolean { val maxDivider = ceil(sqrt(n.toDouble())).toInt() for (i in 2..maxDivider) { if (n % i == 0) return false } return true } val primeNumbers = mutableSetOf(2, 3, 5, 7, 11) /** * this function create the list of prime numbers with the highest input provided as size * despite the fact that the list creation has a relevant complexity ... * ... every subsequent testcase perform the fetch with a O(1) complexity * * "someone would say BLAZINGLY FAST!" -<NAME> */ fun warmup(n : Int) : MutableSet<Int> { var candidate = 12 while (primeNumbers.count() <= n) { if (isPrime(candidate)) { primeNumbers.add(candidate) } candidate++ } return primeNumbers } fun getNthPrimeNumber(n : Int) : Int { return primeNumbers.elementAt(n - 1) } fun main() { val sc = Scanner(System.`in`) val numberOfInputs = sc.nextInt() val inputs = mutableListOf<Int>() for (i in 0 until numberOfInputs) { inputs.add(i, sc.nextInt()) } // HackerRank uses older kotlin version, so you need to use the following syntax to pass the test: // warmup(inputs.max<Int>() ?: 0) warmup(inputs.maxOrNull() ?: 0) for (input in inputs) { println(getNthPrimeNumber(input)) } }
0
Kotlin
0
0
6159bb49cdfe94310a34edad138de2998352f1c2
1,423
HackerRank-ProjectEuler
MIT License
src/main/kotlin/g2901_3000/s2940_find_building_where_alice_and_bob_can_meet/Solution.kt
javadev
190,711,550
false
{"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g2901_3000.s2940_find_building_where_alice_and_bob_can_meet // #Hard #Array #Binary_Search #Stack #Heap_Priority_Queue #Monotonic_Stack #Segment_Tree // #Binary_Indexed_Tree #2024_01_03_Time_928_ms_(90.00%)_Space_84.9_MB_(65.00%) import java.util.LinkedList import kotlin.math.max class Solution { fun leftmostBuildingQueries(heights: IntArray, queries: Array<IntArray>): IntArray { val n = heights.size val gr = IntArray(n) val l = LinkedList<Int>() l.offer(n - 1) gr[n - 1] = -1 for (i in n - 2 downTo 0) { while (l.isNotEmpty() && heights[i] > heights[l.peek()]) { l.pop() } if (l.isNotEmpty()) { gr[i] = l.peek() } else { gr[i] = -1 } l.push(i) } val ans = IntArray(queries.size) var i = 0 for (a in queries) { val x = gr[a[0]] val y = gr[a[1]] if (a[0] == a[1]) { ans[i++] = a[0] } else if (a[0] < a[1] && heights[a[0]] < heights[a[1]]) { ans[i++] = a[1] } else if (a[1] < a[0] && heights[a[1]] < heights[a[0]]) { ans[i++] = a[0] } else if (x == -1 || y == -1) { ans[i++] = -1 } else { var m = max(a[0], a[1]) while (m < heights.size && m != -1 && (heights[m] <= heights[a[0]] || heights[m] <= heights[a[1]])) { m = gr[m] } if (m >= heights.size || m == -1) { ans[i++] = -1 } else { ans[i++] = m } } } return ans } }
0
Kotlin
14
24
fc95a0f4e1d629b71574909754ca216e7e1110d2
1,773
LeetCode-in-Kotlin
MIT License
src/main/kotlin/biz/koziolek/adventofcode/year2022/day17/day17.kt
pkoziol
434,913,366
false
{"Kotlin": 715025, "Shell": 1892}
package biz.koziolek.adventofcode.year2022.day17 import biz.koziolek.adventofcode.Coord import biz.koziolek.adventofcode.findInput import biz.koziolek.adventofcode.parse2DMap fun main() { val jetPattern = findInput(object {}).bufferedReader().readLine() val chamber = Chamber(width = 7, jetPattern = jetPattern) val chamber2022 = chamber.dropManyRocks(count = 2022) println(chamber2022.toString()) println("Tower is ${chamber2022.height} high after 2022 rocks have stopped") } const val AIR = '.' const val ROCK = '#' const val FALLING_ROCK = '@' const val WALL = '|' const val FLOOR = '-' const val CORNER = '+' val ROCKS = listOf( parseRock(""" #### """.trimIndent()), parseRock(""" .#. ### .#. """.trimIndent()), parseRock(""" ..# ..# ### """.trimIndent()), parseRock(""" # # # # """.trimIndent()), parseRock(""" ## ## """.trimIndent()), ) fun parseRock(rock: String): Map<Coord, Char> = rock.split("\n") .reversed() .parse2DMap() .filter { (_, char) -> char == ROCK } .toMap() private val LEFT = Coord(x = -1, y = 0) private val RIGHT = Coord(x = 1, y = 0) private val DOWN = Coord(x = 0, y = -1) data class Chamber( val rocks: Map<Coord, Char> = emptyMap(), val width: Int, val jetPattern: String, private val jetIndex: Int = 0 ) { val height = rocks.maxOfOrNull { it.key.y }?.plus(1) ?: 0 fun dropManyRocks(count: Int, startIndex: Int = 0) = (0 until count).fold(this) { currentChamber, rockOffset -> currentChamber.dropRock(ROCKS[(startIndex + rockOffset) % ROCKS.size]) } fun dropRock(rock: Map<Coord, Char>): Chamber { var tmpRock = spawn(rock) var movesCount = 0 var rested = false // println("init:\n${copy(rocks = tmpRocks)}\n") while (!rested) { val sideDirection = if (jetPattern[(jetIndex + movesCount) % jetPattern.length] == '<') LEFT else RIGHT movesCount++ if (canMove(tmpRock, sideDirection)) { tmpRock = move(tmpRock, sideDirection) } // println("side:\n${copy(rocks = tmpRocks)}\n") if (canMove(tmpRock, DOWN)) { tmpRock = move(tmpRock, DOWN) } else { rested = true } // println("down:\n${copy(rocks = tmpRocks)}\n") } return copy( rocks = rocks + tmpRock.mapValues { ROCK }, jetIndex = jetIndex + movesCount, ) } private fun spawn(rock: Map<Coord, Char>): Map<Coord, Char> = rock .map { (coord, _) -> (coord + Coord(2, height + 3)) to FALLING_ROCK } .toMap() private fun canMove(rock: Map<Coord, Char>, direction: Coord): Boolean { return rock.keys .all { coord -> val newCoord = coord + direction newCoord.x in 0 until width && newCoord.y >= 0 && rocks[newCoord] in setOf(null, AIR, FALLING_ROCK) } } private fun move(tmpRock: Map<Coord, Char>, direction: Coord) = tmpRock.mapKeys { (coord, _) -> coord + direction } override fun toString() = buildString { for (y in height - 1 downTo 0) { append(WALL) for (x in 0 until width) { append(rocks[Coord(x, y)] ?: AIR) } append("$WALL\n") } append(CORNER + FLOOR.toString().repeat(width) + CORNER) } }
0
Kotlin
0
0
1b1c6971bf45b89fd76bbcc503444d0d86617e95
3,702
advent-of-code
MIT License
src/main/java/Exercise24-part2.kt
cortinico
317,667,457
false
null
fun main() { val input = object {}.javaClass.getResource("input-24.txt").readText().split("\n").map { var idx = 0 val result = mutableListOf<Orient>() while (idx < it.length) { val token = when (it[idx]) { 'e' -> Orient.E 's' -> { idx++ if (it[idx] == 'e') Orient.SE else Orient.SW } 'n' -> { idx++ if (it[idx] == 'w') Orient.NW else Orient.NE } else -> Orient.W } idx++ result.add(token) } result } val tiles = mutableMapOf<Pair<Int, Int>, Int>() input.onEach { var (x, y) = 0 to 0 it.forEach { orient -> when (orient) { Orient.E -> x += 2 Orient.SE -> { y-- x++ } Orient.SW -> { y-- x-- } Orient.W -> x -= 2 Orient.NE -> { y++ x++ } Orient.NW -> { y++ x-- } } } val lastValue = tiles.getOrPut(x to y) { 0 } tiles[x to y] = (lastValue + 1) % 2 } repeat(100) { val blackToCheck = tiles.filter { it.value == 1 }.keys val whiteToCheck = blackToCheck.flatMap { blackTile -> possibleMoves .map { move -> blackTile.first + move.first to blackTile.second + move.second } .filter { move -> move !in tiles || tiles[move] == 0 } } val blackToFlip = blackToCheck.filter { tile -> val blackNeighbors = possibleMoves.count { move -> val result = tile.first + move.first to tile.second + move.second tiles.getOrDefault(result, 0) == 1 } blackNeighbors == 0 || blackNeighbors > 2 } val whiteToFlip = whiteToCheck.filter { tile -> val blackNeighbors = possibleMoves.count { move -> val result = tile.first + move.first to tile.second + move.second tiles.getOrDefault(result, 0) == 1 } blackNeighbors == 2 } blackToFlip.forEach { tiles[it] = 0 } whiteToFlip.forEach { tiles[it] = 1 } } tiles.values.count { it == 1 }.also(::println) } val possibleMoves = listOf( -2 to 0, 2 to 0, -1 to 1, -1 to -1, 1 to -1, 1 to 1, )
1
Kotlin
0
4
a0d980a6253ec210433e2688cfc6df35104aa9df
3,013
adventofcode-2020
MIT License
src/main/kotlin/me/peckb/aoc/_2017/calendar/day14/Day14.kt
peckb1
433,943,215
false
{"Kotlin": 956135}
package me.peckb.aoc._2017.calendar.day14 import me.peckb.aoc._2017.calendar.day10.Day10 import javax.inject.Inject import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory import java.util.ArrayDeque class Day14 @Inject constructor( private val generatorFactory: InputGeneratorFactory, private val day10: Day10 ) { fun partOne(filename: String) = generatorFactory.forFile(filename).readOne { input -> val grid = createGrid(input) grid.sumOf { row -> row.count { it == '1' } } } fun partTwo(filename: String) = generatorFactory.forFile(filename).readOne { input -> val grid = createGrid(input).map { it.toCharArray() } var groups = 0 grid.indices.forEach { y -> grid.indices.forEach { x -> if (grid[y][x] == '1') { groups++ grid.replaceGroup(y, x) } } } groups } private fun createGrid(input: String): List<String> { return (0 until 128).map { n -> val key = "$input-$n" val lengths = key.map { it.code }.plus(listOf(17, 31, 73, 47, 23)) val data = day10.runInput(lengths, 64) data.chunked(16) .map { it.reduce { acc, next -> acc.xor(next) } } .joinToString("") { i -> val hex = i.toString(16).let { if (it.length < 2) "0$it" else it } "${CONVERSION[hex[0]]!!}${CONVERSION[hex[1]]!!}" } } } private fun List<CharArray>.replaceGroup(y: Int, x: Int) { val toCheck = ArrayDeque<Pair<Int, Int>>() toCheck.push(y to x) while (toCheck.isNotEmpty()) { val (yy, xx) = toCheck.pop() this[yy][xx] = '0' val u = find(yy - 1, xx, '0') val r = find(yy, xx + 1, '0') val d = find(yy + 1, xx, '0') val l = find(yy, xx - 1, '0') if (u == '1') toCheck.push(yy - 1 to xx) if (r == '1') toCheck.push(yy to xx + 1) if (d == '1') toCheck.push(yy + 1 to xx) if (l == '1') toCheck.push(yy to xx - 1) } } private fun List<CharArray>.find(y: Int, x: Int, default: Char): Char { return if (x in 0 until size && y in (0 until size)) { this[y][x] } else { default } } companion object { val CONVERSION = mapOf( '0' to "0000", '1' to "0001", '2' to "0010", '3' to "0011", '4' to "0100", '5' to "0101", '6' to "0110", '7' to "0111", '8' to "1000", '9' to "1001", 'a' to "1010", 'b' to "1011", 'c' to "1100", 'd' to "1101", 'e' to "1110", 'f' to "1111" ) } }
0
Kotlin
1
3
2625719b657eb22c83af95abfb25eb275dbfee6a
2,536
advent-of-code
MIT License
kotlin/src/main/kotlin/com/kodeinc/fireman/WordList.kt
evanjpw
122,695,712
false
{"C++": 9282, "Kotlin": 6501, "CMake": 412}
package com.kodeinc.fireman import org.apache.commons.io.IOUtils import java.nio.charset.Charset internal fun makeLengthComparator(reversed: Boolean = false) : Comparator<CharSequence> { val leftIsLess = if (reversed) 1 else -1 val leftIsGreater = if (reversed) -1 else 1 return Comparator { lhs, rhs -> val ll = lhs.length val rl = rhs.length when { ll < rl -> leftIsLess ll > rl -> leftIsGreater else -> 0 } } } //Comparator { lhs, rhs -> // val ll = lhs.length // val rl = rhs.length // when { // ll < rl -> // ll > rl -> // else -> 0 // } //} object WordList { private const val WORDS_LST = "/words.txt" private val WORDS_LST_ENCODING = Charset.forName("UTF-8") private fun readWordList() : Array<String> { val resource = this.javaClass.getResourceAsStream(WORDS_LST) val lines = IOUtils.readLines(resource, WORDS_LST_ENCODING) return lines.toTypedArray() } val words by lazy { readWordList() } val reverseOrderedWords by lazy { words.sortedArrayWith(makeLengthComparator(reversed = true)) } } typealias Bucket = List<String> internal typealias MutableBucket = ArrayList<String> internal fun MutableBucket.lengthOrder() = this.sortWith(com.kodeinc.fireman.makeLengthComparator()) abstract class BucketCollection<K : Comparable<K>> { protected val buckets : MutableMap<K, MutableBucket> = HashMap() abstract fun transformToKey(word : String) : K operator fun get(key : K) : Bucket? = buckets[key] fun getByWord(word : String) = get(transformToKey(word)) operator fun contains(key: K) : Boolean = key in buckets operator fun plus(word : String) { val key = transformToKey(word) if (key !in buckets) { buckets[key] = ArrayList() } buckets[key]?.add(word) } fun add(word : String) = this + word fun sortBuckets() = buckets.forEach { _, value -> value.lengthOrder() } open operator fun iterator() : Iterator<Bucket> { return object : Iterator<Bucket> { val itr = buckets.iterator() override fun hasNext() = itr.hasNext() override fun next(): Bucket { val e = itr.next() return e.value } } } } class TwoLetterBuckets : BucketCollection<String>() { override fun transformToKey(word: String): String = if (word.length <= 2) { word } else { word.substring(0, 2) } } class LengthBuckets : BucketCollection<Int>() { override fun transformToKey(word: String): Int = word.length private val keyList by lazy { buckets.keys.toSortedSet().reversed() } override operator fun iterator(): Iterator<Bucket> { return object : Iterator<Bucket> { private var index = 0 override fun hasNext() = index < keyList.size override fun next() = if (hasNext()) { val key = keyList[index++] buckets[key] ?: emptyList<String>() } else { throw NoSuchElementException() } } } }
0
C++
0
0
ac7444185debb84d7fb608085fa6de15581d8b52
3,236
fireman
The Unlicense
Chapter05/src/main/kotlin/9_Tail_Recursion.kt
PacktPublishing
373,735,637
false
null
tailrec fun sumRec(i: Int, sum: Long, numbers: List<Int>): Long { return if (i == numbers.size) { return sum } else { sumRec(i + 1, numbers[i] + sum, numbers) } } fun main() { val numbers = List(1_000_000) { it } println(sumRec(0, 0, numbers)) val res = mergeSort(numbers.shuffled()) println(res.take(100)) } tailrec fun mergeSort(numbers: List<Int>): List<Int> { return when { numbers.size <= 1 -> numbers numbers.size == 2 -> { return if (numbers[0] < numbers[1]) { numbers } else { listOf(numbers[1], numbers[0]) } } else -> { val left = mergeSort(numbers.slice(0..numbers.size / 2)) val right = mergeSort(numbers.slice(numbers.size / 2 + 1 until numbers.size)) return merge(left, right) } } } fun merge(left: List<Int>, right: List<Int>): List<Int> { val result = mutableListOf<Int>() var l = 0 var r = 0 while (l < left.size && r < right.size) { result += if (left[l] < right[r]) { left[l++] } else { right[r++] } } while (l < left.size) { result += left[l++] } while (r < right.size) { result += right[r++] } return result }
0
Kotlin
69
216
e5a0ff239fc98fdde3cc1eb78c66df66907b88d3
1,337
Kotlin-Design-Patterns-and-Best-Practices
MIT License
src/main/kotlin/se/saidaspen/aoc/aoc2015/Day19.kt
saidaspen
354,930,478
false
{"Kotlin": 301372, "CSS": 530}
package se.saidaspen.aoc.aoc2015 import se.saidaspen.aoc.util.Day fun main() = Day19.run() object Day19 : Day(2015, 19) { private var mol = input.lines().last() val repls = input.lines().map { it.split(" => ") }.dropLast(2) override fun part1(): Any { val possibles = mutableListOf<String>() for (repl in repls) { var position = 0 while (position >= 0) { position = mol.indexOf(repl[0], position) if (position > 0) { possibles.add(replace(mol, repl[0], repl[1], position)!!) position += repl[0].length } } } return possibles.distinct().count() } override fun part2(): Any { var steps = 0 while (mol.length > 1) { for (repl in repls) { if (mol.contains(repl[1])) { mol = replace(mol, repl[1], repl[0], mol.lastIndexOf(repl[1]))!! steps++ } } } return steps } private fun replace(s: String, from: String, to: String, position: Int): String? { return s.substring(0, position) + to + s.substring(position + from.length) } }
0
Kotlin
0
1
be120257fbce5eda9b51d3d7b63b121824c6e877
1,253
adventofkotlin
MIT License
src/Day23.kt
palex65
572,937,600
false
{"Kotlin": 68582}
@file:Suppress("PackageDirectoryMismatch") package day23 import readInput import day23.Dir.* //data class Pos(val row: Int, val col: Int) class Pos private constructor(private val index: Int) { val col get() = index % 256 - 50 val row get() = index / 256 - 50 override fun toString() = "($row,$col)" override fun equals(other: Any?) = (other as Pos).index == index override fun hashCode() = index companion object { private val cache = MutableList<Pos?>(256*256){ null } operator fun invoke(row: Int, col: Int): Pos { val index = (row+50) * 256 + (col+50) return cache[index] ?: Pos(index).also { cache[index] = it } } } } typealias Plant = Map<Pos,Pos?> fun Plant.print(label: String = "---") { println("== $label ==") for(row in minOf { it.key.row } .. maxOf { it.key.row }) { for(col in minOf { it.key.col } .. maxOf { it.key.col }) print( if(contains(Pos(row,col))) '#' else '.' ) println() } println() } fun Plant.countGround(): Int { var count = 0 val minRow = minOf { it.key.row } val maxRow = maxOf { it.key.row } val minCol = minOf { it.key.col } val maxCol = maxOf { it.key.col } //println("row in $minRow..$maxRow , col in $minCol..$maxCol") for(row in minRow..maxRow) for(col in minCol..maxCol) if(!contains(Pos(row,col))) ++count return count } fun Plant(ls: List<String>): Plant = buildMap { ls.forEachIndexed { row, line -> line.forEachIndexed{ col, c -> if (c=='#') this[Pos(row, col)] = null } } } enum class Dir(val dr: Int, val dc: Int) { N(-1,0), NE(-1,1), E(0,1), SE(1,1), S(1,0), SW(1,-1), W(0,-1), NW(-1,-1) } operator fun Pos.plus(dir: Dir) = Pos(row + dir.dr, col + dir.dc) val steps = listOf( listOf(N,NE,NW), listOf(S,SE,SW), listOf(W,NW,SW), listOf(E,NE,SE) ) fun Plant.proposedMove(round:Int, pos:Pos): Pos? { repeat(steps.size) { t -> val step = steps[(round+t) % steps.size] if (step.map{ pos + it }.all { !contains(it) }) return pos + step[0] } return null } fun round(round: Int, elves: MutableMap<Pos, Pos?>): Boolean { elves.forEach { (pos, _) -> elves[pos] = if (values().map { pos + it }.all { !elves.contains(it) }) null else elves.proposedMove(round, pos) } val toMove = elves.filter { (pos, propose) -> propose != null && elves.none { (p, v) -> p != pos && v == propose } } for ((pos, propose) in toMove) { elves.remove(pos) elves[propose!!] = null } return toMove.isNotEmpty() } fun part1(lines: List<String>): Int { val elves = Plant(lines).toMutableMap() //elves.print("Initial State") repeat(10){ round -> round(round, elves) //elves.print("End of round ${round+1}") } return elves.countGround() } fun part2(lines: List<String>): Int { val elves = Plant(lines).toMutableMap() var round = 0 do { val hasMoves = round(round++, elves) //println("Round $round") } while (hasMoves) //elves.print("No moves round= $round") return round } fun main() { val testInput = readInput("Day23_test") check(part1(testInput) == 110) check(part2(testInput) == 20) val input = readInput("Day23") println(part1(input)) // 4049 println(part2(input)) // 1021 }
0
Kotlin
0
2
35771fa36a8be9862f050496dba9ae89bea427c5
3,403
aoc2022
Apache License 2.0
src/main/kotlin/com/github/solairerove/algs4/leprosorium/linked_list/RemoveDuplicatesFromSortedLinkedListII.kt
solairerove
282,922,172
false
{"Kotlin": 251919}
package com.github.solairerove.algs4.leprosorium.linked_list /** * Given the head of a sorted linked list, * delete all nodes that have duplicate numbers, * leaving only distinct numbers from the original list. * Return the linked list sorted as well. * * Input: head = [1 -> 2 -> 3 -> 3 -> 4 -> 4 -> 5] * Output: [1 -> 2 -> 5] */ // O(n) time | O(n) space fun deleteDuplicatesFromSortedII(head: ListNode?): ListNode? { var curr: ListNode? = head ?: return null if (curr!!.next != null && curr.value == curr.next!!.value) { while (curr!!.next != null && curr.value == curr.next!!.value) { curr = curr.next } return deleteDuplicatesFromSortedII(curr.next) } else { curr.next = deleteDuplicatesFromSortedII(curr.next) } return curr } // O(n) time | O(n) space fun deleteDuplicatesDFSFromSortedII(head: ListNode?, prev: ListNode? = null): ListNode? { val curr: ListNode = head ?: return null return if (prev != null && curr.value == prev.value || curr.next != null && curr.value == curr.next!!.value ) { deleteDuplicatesDFSFromSortedII(curr.next, curr) } else { curr.next = deleteDuplicatesDFSFromSortedII(curr.next, curr) curr } } // O(n) time | O(1) space fun deleteDuplicatesIterativeFromSortedII(head: ListNode?): ListNode? { var curr: ListNode? = head val sentinel = ListNode(0) sentinel.next = curr var prev: ListNode? = sentinel while (curr != null) { if (curr.next != null && curr.value == curr.next!!.value) { while (curr?.next != null && curr?.value == curr?.next!!.value) curr = curr.next prev?.next = curr?.next } else { prev = prev?.next } curr = curr?.next } return sentinel.next }
1
Kotlin
0
3
64c1acb0c0d54b031e4b2e539b3bc70710137578
1,820
algs4-leprosorium
MIT License
src/main/aoc2023/Day4.kt
nibarius
154,152,607
false
{"Kotlin": 963896}
package aoc2023 import kotlin.math.pow class Day4(input: List<String>) { private val cards = input.map { line -> Card( line.substringAfter(": ").substringBefore(" |").split(" ") .filter { it.isNotEmpty() }.map { it.toInt() }, line.substringAfter("| ").split(" ").filter { it.isNotEmpty() }.map { it.toInt() } ) }.withIndex().associate { it.index + 1 to it.value } private data class Card(val winningNumbers: List<Int>, val myNumbers: List<Int>) { val matchingNumbers = myNumbers.count { it in winningNumbers } } fun solvePart1(): Int { return cards.values.sumOf { card -> 2.toDouble().pow(card.matchingNumbers - 1).toInt() } } fun solvePart2(): Int { val numCards = cards.keys.associateWith { 1 }.toMutableMap() cards.forEach { (cardNum, card) -> (1..card.matchingNumbers).forEach { numCards[cardNum + it] = numCards[cardNum + it]!! + numCards[cardNum]!! } } return numCards.values.sum() } }
0
Kotlin
0
6
f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22
1,094
aoc
MIT License
src/main/kotlin/com/github/aoc/AOCD8P2.kt
frikit
317,914,710
false
null
package com.github.aoc import com.github.aoc.utils.InputDay8Problem2 import com.github.aoc.utils.InputParser fun main() { val input = InputParser.parseInput(InputDay8Problem2) .toMutableList() val wrongIndex = findWrongStatementIndex(input, 0, mutableListOf()) println("Current input is : $input") input[wrongIndex] = input[wrongIndex].replace("jmp", "nop") println("Replaced input is : $input") val res = doInstructionGetAcc(input, 0, 0, mutableListOf()) println(res) } private fun findWrongStatementIndex( input: List<String>, index: Int, executedOperations: MutableList<String> ): Int { val instruction = input[index] val typeOfInstruction = instruction.split(" ")[0].trim() val operationNumber = instruction.split(" ")[1] .replace("+", "") .replace("-", "") .toInt() val isMinus = instruction.contains("-") executedOperations.add("$index-$instruction") val potIndex = when { typeOfInstruction == "nop" -> index + 1 typeOfInstruction == "acc" -> index + 1 isMinus -> index - operationNumber else -> index + operationNumber } val expKey = "$index-$instruction" if (executedOperations.contains(expKey) && (typeOfInstruction == "jmp" || typeOfInstruction == "nop") && isMinus ) return index else if (!executedOperations.contains(expKey)) { executedOperations.add(expKey) } return findWrongStatementIndex(input, potIndex, executedOperations.toHashSet().toMutableList()) } private fun doInstructionGetAcc( input: List<String>, index: Int, accumulatort: Int, executedOperations: MutableList<String> ): Int { var acc = accumulatort if (input.size <= index) return acc val instruction = input[index] val typeOfInstruction = instruction.split(" ")[0].trim() val operationNumber = instruction.split(" ")[1] .replace("+", "") .replace("-", "") .toInt() val isMinus = instruction.contains("-") executedOperations.add("$index-$instruction") val potIndex = when { typeOfInstruction == "nop" -> index + 1 typeOfInstruction == "acc" -> index + 1 isMinus -> index - operationNumber else -> index + operationNumber } if (typeOfInstruction == "acc") { if (isMinus) acc -= operationNumber else acc += operationNumber } // if (input.size <= potIndex) return acc // // val potInstr = input[potIndex] val expKey = "$potIndex-$instruction" if (executedOperations.contains(expKey)) return acc else { executedOperations.add(expKey) } return doInstructionGetAcc(input, potIndex, acc, executedOperations) }
0
Kotlin
0
0
2fca82225a19144bbbca39247ba57c42a30ef459
2,760
aoc2020
Apache License 2.0
HackerRank/MissingNumbers/Iteration1.kt
MahdiDavoodi
434,677,181
false
{"Kotlin": 57766, "JavaScript": 17002, "Java": 10647, "HTML": 696, "Python": 683}
fun missingNumbers(arr: Array<Int>, brr: Array<Int>): Set<Int> { val map = mutableMapOf<Int, Int>() for (i in brr) map[i] = (map[i] ?: 0) + 1 for (i in arr) { map[i] = (map[i] ?: 1) - 1 if ((map[i] ?: 0) == 0) map.remove(i) } return map.keys.toSortedSet() } fun main() { readLine() val arr = readLine()!!.trimEnd().split(" ").map { it.toInt() }.toTypedArray() readLine() val brr = readLine()!!.trimEnd().split(" ").map { it.toInt() }.toTypedArray() println(missingNumbers(arr, brr).joinToString(" ")) } /** * Store all the frequencies of brr in a map. * Reduce from them by checking the arr. * If the frequency becomes 0, it means that element is not missing in the arr. * */
0
Kotlin
0
0
62a23187efc6299bf921a95c8787d02d5be51742
741
ProblemSolving
MIT License
src/pl/shockah/aoc/y2015/Day13.kt
Shockah
159,919,224
false
null
package pl.shockah.aoc.y2015 import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import pl.shockah.aoc.AdventTask import pl.shockah.aoc.parse4 import java.util.regex.Pattern class Day13: AdventTask<Map<Pair<String, String>, Int>, Int, Int>(2015, 13) { private val inputPattern: Pattern = Pattern.compile("(\\w+) would (gain|lose) (\\d+) happiness units by sitting next to (\\w+).") override fun parseInput(rawInput: String): Map<Pair<String, String>, Int> { return rawInput.lines().map { val (person1, gainOrLose, happiness, person2) = inputPattern.parse4<String, String, Int, String>(it) return@map Pair(person1, person2) to happiness * (if (gainOrLose == "gain") 1 else -1) }.toMap() } private fun getTotalHappiness(values: Map<Pair<String, String>, Int>, table: List<String>): Int { var happiness = 0 for (i in table.indices) { happiness += values[Pair(table[i], table[(i + 1) % table.size])] ?: 0 happiness += values[Pair(table[(i + 1) % table.size], table[i])] ?: 0 } return happiness } private fun task(input: Map<Pair<String, String>, Int>, includeMyself: Boolean = false): Int { val people = (input.keys.map { it.first }.toSet() + input.keys.map { it.second }.toSet()).toMutableSet() if (includeMyself) people += "Myself!" fun getPermutations(table: List<String>, toDistribute: Set<String>): List<List<String>> { if (toDistribute.isEmpty()) return listOf(table) return toDistribute.flatMap { getPermutations(table + it, toDistribute - it) } } return getTotalHappiness(input, getPermutations(listOf(), people).maxByOrNull { getTotalHappiness(input, it) }!!) } override fun part1(input: Map<Pair<String, String>, Int>): Int { return task(input, false) } override fun part2(input: Map<Pair<String, String>, Int>): Int { return task(input, true) } class Tests { private val task = Day13() private val rawInput = """ Alice would gain 54 happiness units by sitting next to Bob. Alice would lose 79 happiness units by sitting next to Carol. Alice would lose 2 happiness units by sitting next to David. Bob would gain 83 happiness units by sitting next to Alice. Bob would lose 7 happiness units by sitting next to Carol. Bob would lose 63 happiness units by sitting next to David. Carol would lose 62 happiness units by sitting next to Alice. Carol would gain 60 happiness units by sitting next to Bob. Carol would gain 55 happiness units by sitting next to David. David would gain 46 happiness units by sitting next to Alice. David would lose 7 happiness units by sitting next to Bob. David would gain 41 happiness units by sitting next to Carol. """.trimIndent() @Test fun part1() { val input = task.parseInput(rawInput) Assertions.assertEquals(330, task.part1(input)) } } }
0
Kotlin
0
0
9abb1e3db1cad329cfe1e3d6deae2d6b7456c785
2,829
Advent-of-Code
Apache License 2.0
code/supportLib/src/main/java/it/unipd/stage/sl/lib/rsa/RsaUtils.kt
Kraktun
391,948,016
false
{"Java": 189822, "Shell": 12686, "Kotlin": 12043, "HTML": 10394, "Python": 8690, "Batchfile": 3379}
package it.unipd.stage.sl.lib.rsa import java.math.BigInteger /* The following functions come from https://en.wikipedia.org/wiki/RSA_(cryptosystem)#Key_generation */ /** * @return true is a big integer is probably prime with certainty 15 */ fun BigInteger.isPrime(): Boolean { // not 100% correct, but error is very low and for this type of application it's good enough return this.isProbablePrime(15) } /** * @param n1 a non null positive big integer * @param n2 a non null positive big integer * @return true if n1 and n2 are coprime */ fun areCoprime(n1: BigInteger, n2: BigInteger): Boolean { return gcd(n1, n2) == BigInteger.ONE } /** * from https://www.geeksforgeeks.org/euclidean-algorithms-basic-and-extended/ * @param a a non null positive big integer * @param b a non null positive big integer * @return greatest common divisor between a and b */ fun gcd(a: BigInteger, b: BigInteger): BigInteger { return if (a == BigInteger.ZERO) b else gcd(b % a, a) } /** * @param n1 a non null positive big integer * @param n2 a non null positive big integer * @return least common multiple between n1 and n2 */ fun lcm(n1: BigInteger, n2: BigInteger): BigInteger { return n1.multiply(n2).divide(gcd(n1, n2)) } /** * Returns modulo inverse of 'a' with respect to 'm' using extended Euclid * Algorithm Assumption: 'a' and 'm' are coprimes * from https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/ * * @param a non null positive big integer * @param m non null positive big integer */ fun modInverse(a: BigInteger, m: BigInteger): BigInteger { // note: mapping to rsa: a = e, m= y, result = d var a1 = a var m1 = m val m0 = m1 var y = BigInteger.ZERO var x = BigInteger.ONE if (m1 == BigInteger.ONE) return BigInteger.ZERO while (a1 > BigInteger.ONE) { // q is the quotient val q = a1 / m1 var t = m1 // m is the remainder now, process same as Euclid's algo m1 = a1 % m1 a1 = t t = y // Update x and y y = x - q * y x = t } // Make x positive if (x < BigInteger.ZERO) x += m0 return x } /** * Naive approach to factorize a number. * Note that this does not always return all factors, but a set such that * each element of the set may be a factor multiple times * and/or the last factor is obtained from the set as n/prod(set) * * @param n non null positive big integer * @return set of factors */ fun factorize(n: BigInteger): Set<BigInteger> { val set = mutableSetOf<BigInteger>() // first test 2 and 3 if (n % BigInteger("2") == BigInteger.ZERO) set.add(BigInteger("2")) // for some reason BigInteger.TWO does not work with shadowjar if (n % BigInteger("3") == BigInteger.ZERO) set.add(BigInteger("3")) // use 6k+1 rule var i = BigInteger("5") while (i*i <= n) { if (n%i == BigInteger.ZERO) { set.add(i) } if (n%(i+ BigInteger("2")) == BigInteger.ZERO) { set.add(i+ BigInteger("2")) } i += BigInteger("6") } return set } /** * Return a list of all the prime factors of n * * @param n non null positive big integer * @return list of prime factors (may be repated) */ fun factorizeFull(n: BigInteger): List<BigInteger> { val list = mutableListOf<BigInteger>() val set = factorize(n) list.addAll(set) val prod = set.reduce { acc, bigInteger -> acc*bigInteger } var residual = n / prod while (residual > BigInteger.ONE) { set.forEach{ while (residual % it == BigInteger.ZERO) { list.add(it) residual /= it } } if (residual.isPrime()) { list.add(residual) break } } return list }
0
Java
0
0
28c5739e19eafc0514a0afeab98cb6e5ff3b5d61
3,827
java_web_frameworks_cmp
MIT License
day02/src/main/kotlin/com/shifteleven/adventofcode2023/day02/App.kt
pope
733,715,471
false
{"Kotlin": 3950, "Nix": 1630}
package com.shifteleven.adventofcode2023.day02 import java.io.StreamTokenizer import java.io.StringReader import kotlin.assert import kotlin.math.max data class Game(val id: Int, val views: List<IntArray>) fun main() { val lines = object {}.javaClass.getResourceAsStream("/input.txt")!!.bufferedReader().readLines() val games = lines.map { processLine(it) } part1(games) part2(games) } fun part1(games: List<Game>) { val sum = games .filter { game -> game.views.all { it[0] <= 12 && it[1] <= 13 && it[2] <= 14 } } .map { it.id } .sum() println("Part 1: " + sum) } fun part2(games: List<Game>) { val sum = games .map { game -> var r = 1 var g = 1 var b = 1 for (dice in game.views) { r = max(dice[0], r) g = max(dice[1], g) b = max(dice[2], b) } r * g * b } .sum() println("Part 2: " + sum) } fun processLine(line: String): Game { val r = StringReader(line) val t = StreamTokenizer(r) t.nextToken() assert(t.sval == "Game") t.nextToken() assert(t.ttype == StreamTokenizer.TT_NUMBER) val gameId = t.nval.toInt() val cur = t.nextToken() // : assert(cur.toChar() == ':') val views = mutableListOf<IntArray>() do { val dice = IntArray(3) do { t.nextToken() assert(t.ttype == StreamTokenizer.TT_NUMBER) val curColor = t.nval.toInt() t.nextToken() assert(t.ttype == StreamTokenizer.TT_WORD) when (t.sval) { "red" -> dice[0] = curColor "green" -> dice[1] = curColor "blue" -> dice[2] = curColor else -> assert(false) } } while (isRgbGroupActive(t)) views.add(dice) } while (isGameContinued(t)) assert(t.nextToken() == StreamTokenizer.TT_EOF) return Game(gameId, views) } fun isRgbGroupActive(t: StreamTokenizer): Boolean { val tok = t.nextToken() if (tok.toChar() == ',') { return true } t.pushBack() return false } fun isGameContinued(t: StreamTokenizer): Boolean { val tok = t.nextToken() if (tok.toChar() == ';') { return true } t.pushBack() return false }
0
Kotlin
0
0
cb2862a657d307b5ecd74ebb9c167548b67ba6fc
2,010
advent-of-code-2023-kotlin
The Unlicense
src/Utils.kt
kmakma
574,238,598
false
null
import java.io.File import java.math.BigInteger import java.security.MessageDigest import kotlin.math.abs typealias Vector2D = Coord2D /** * Reads lines from the given input txt file. */ fun readInput(name: String) = File("src", "$name.txt") .readLines() /** * Read whole input txt file as one string. */ fun readWholeInput(name: String) = File("src", "$name.txt") .readText() /** * Converts string to md5 hash. */ fun String.md5() = BigInteger(1, MessageDigest.getInstance("MD5").digest(toByteArray())) .toString(16) .padStart(32, '0') data class Coord2D(val x: Int, val y: Int) { fun adjacentTo(coord2D: Coord2D): Boolean { return abs(x - coord2D.x) <= 1 && abs(y - coord2D.y) <= 1 } operator fun minus(other: Coord2D): Coord2D { return Coord2D(this.x - other.x, this.y - other.y) } operator fun plus(other: Coord2D): Coord2D { return Coord2D(this.x + other.x, this.y + other.y) } fun moved(byX: Int, byY: Int): Coord2D { return Coord2D(x + byX, y + byY) } fun manhattenDistance(other: Vector2D): Int { return abs(this.x - other.x) + abs(this.y - other.y) } } /** * Returns the product (multiplication) of all elements in the collection. */ fun List<Int>.product(): Int { return this.reduce { acc, i -> acc * i } } /** * All permutations of a list * Source: https://rosettacode.org/wiki/Permutations#Kotlin */ fun <T> permute(input: List<T>): List<List<T>> { if (input.size == 1) return listOf(input) val perms = mutableListOf<List<T>>() val toInsert = input[0] for (perm in permute(input.drop(1))) { for (i in 0..perm.size) { val newPerm = perm.toMutableList() newPerm.add(i, toInsert) perms.add(newPerm) } } return perms }
0
Kotlin
0
0
950ffbce2149df9a7df3aac9289c9a5b38e29135
1,824
advent-of-kotlin-2022
Apache License 2.0
src/main/kotlin/dev/killjoy/utils/Algorithms.kt
Blad3Mak3r
295,118,697
false
{"Kotlin": 269315, "Shell": 3389, "Dockerfile": 345, "Makefile": 123, "Procfile": 63}
/******************************************************************************* * Copyright (c) 2021. Blademaker * * 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.killjoy.utils import java.util.* import kotlin.math.floor object Algorithms { private fun String.removeSpaces() = this.lowercase().replace("\\s+".toRegex(), "") private const val REQUIRE_MINIMUM_DISTANCE = 0.75 fun dictionarySimilar(term: String, dictionary: List<String>): List<String> { val resultList = mutableListOf<String>() for (item in dictionary) { val distance = JaroWinkler.distance(term.removeSpaces(), item.removeSpaces()) if (distance >= REQUIRE_MINIMUM_DISTANCE) { resultList.add(item) } else { val anagram = Anagram.of(term.removeSpaces(), item.removeSpaces()) if (anagram) resultList.add(item) } } return resultList } object Anagram { fun of(s1: String, s2: String): Boolean { val a1 = s1.removeSpaces().split("").toTypedArray() val a2 = s2.removeSpaces().split("").toTypedArray() Arrays.sort(a1) Arrays.sort(a2) return a1.contentEquals(a2) } } object Jaro { fun distance(str1: String, str2: String): Double { val s1 = str1.lowercase() val s2 = str2.lowercase() // If the strings are equal if (s1 === s2) return 1.0 // Length of two strings val len1 = s1.length val len2 = s2.length if (len1 == 0 || len2 == 0) return 0.0 // Maximum distance upto which matching // is allowed val maxDist = floor((len1.coerceAtLeast(len2) / 2).toDouble()).toInt() - 1 // Count of matches var match = 0 // Hash for matches val hashS1 = IntArray(s1.length) val hashS2 = IntArray(s2.length) // Traverse through the first string for (i in 0 until len1) { // Check if there is any matches for (j in 0.coerceAtLeast(i - maxDist) until len2.coerceAtMost(i + maxDist + 1)) // If there is a match if (s1[i] == s2[j] && hashS2[j] == 0 ) { hashS1[i] = 1 hashS2[j] = 1 match++ break } } // If there is no match if (match == 0) return 0.0 // Number of transpositions var t = 0.0 var point = 0 // Count number of occurrences // where two characters match but // there is a third matched character // in between the indices for (i in 0 until len1) if (hashS1[i] == 1) { // Find the next matched character // in second string while (hashS2[point] == 0) point++ if (s1[i] != s2[point++]) t++ } t /= 2.0 // Return the Jaro Similarity return ((match.toDouble() / len1.toDouble() + match.toDouble() / len2.toDouble() + (match.toDouble() - t) / match.toDouble()) / 3.0) } } object JaroWinkler { fun distance(s1: String, s2: String): Double { var jaroDist: Double = Jaro.distance(s1, s2) // If the jaro Similarity is above a threshold if (jaroDist > 0.7) { // Find the length of common prefix var prefix = 0 for (i in 0 until s1.length.coerceAtMost(s2.length)) { // If the characters match if (s1[i] == s2[i]) prefix++ else break } // Maximum of 4 characters are allowed in prefix prefix = 4.coerceAtMost(prefix) // Calculate jaro winkler Similarity jaroDist += 0.1 * prefix * (1 - jaroDist) } return jaroDist } } }
8
Kotlin
1
8
f2c202b96aa799e8751c023e42f85a074aed8508
4,788
Killjoy
Apache License 2.0
src/Day01/Day01.kt
NST-d
573,224,214
false
null
import utils.* import kotlin.math.max fun main() { fun part1(input: List<String>) = input.fold ( Pair(0,0)) { acc, line -> var max = acc.first var sum = acc.second if ( line.isEmpty() ){ max = max(acc.first, acc.second) sum = 0 }else{ sum += line.toInt() } Pair(max,sum) }.first fun part2(input: String) = input.split("\n\n") .map { it.split("\n").sumOf { it.toInt() } }.sortedDescending() .take(3) .sum() // test if implementation meets criteria from the description, like: val testInput = readTestLines("Day01") check(part1(testInput) == 24000) val inputLines = readInputLines("Day01") val inputString = readInputString("Day01").trimIndent() println(part1(inputLines)) println(part2(inputString)) }
0
Kotlin
0
0
c4913b488b8a42c4d7dad94733d35711a9c98992
952
aoc22
Apache License 2.0
advent-of-code-2023/src/main/kotlin/eu/janvdb/aoc2023/day01/day01.kt
janvdbergh
318,992,922
false
{"Java": 1000798, "Kotlin": 284065, "Shell": 452, "C": 335}
package eu.janvdb.aoc2023.day01 import eu.janvdb.aocutil.kotlin.readLines //const val FILENAME = "input01-test.txt" //const val FILENAME = "input01-test2.txt" const val FILENAME = "input01.txt" val DIGIT_VALUES_1 = mapOf( Pair("0", 0), Pair("1", 1), Pair("2", 2), Pair("3", 3), Pair("4", 4), Pair("5", 5), Pair("6", 6), Pair("7", 7), Pair("8", 8), Pair("9", 9) ) val DIGIT_VALUES_2 = mapOf( Pair("zero", 0), Pair("one", 1), Pair("two", 2), Pair("three", 3), Pair("four", 4), Pair("five", 5), Pair("six", 6), Pair("seven", 7), Pair("eight", 8), Pair("nine", 9), ) fun main() { runWithValues(DIGIT_VALUES_1) runWithValues(DIGIT_VALUES_1 + DIGIT_VALUES_2) } private fun runWithValues(digitValues: Map<String, Int>) { val sum = readLines(2023, FILENAME).sumOf { line -> val digits = IntRange(0, line.length - 1) .map { Pair(it, line.substring(it)) } .flatMap { pair -> digitValues.filter { pair.second.startsWith(it.key) }.map { Pair(pair.first, it.value) } } .sortedBy { it.first } val digit0 = digits.first().second val digit1 = digits.last().second digit0 * 10 + digit1 } println(sum) }
0
Java
0
0
78ce266dbc41d1821342edca484768167f261752
1,135
advent-of-code
Apache License 2.0
src/Day01.kt
asgerp
574,417,989
false
{"Kotlin": 4641}
fun main() { fun solve(lines: List<String>): List<Int> { val cals = mutableListOf<Int>() var currentCal = 0 for (l in lines) { if (l.isBlank()) { cals.add(currentCal) currentCal = 0 } else { currentCal += l.toInt() } } return cals } fun part1(input: List<String>): Int { val res = solve(input) return res.max() } fun part2(input: List<String>): Int { val res = solve(input) return res.sortedDescending().take(3).sum() } // test if implementation meets criteria from the description, like: //val testInput = readInput("Day01_test") //check(part1(testInput) == 1) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
e727c834161a6eb6c891a390b644f90599f7adac
849
aoc22
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/SoupServings.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import dev.shtanko.algorithms.EPSILON import kotlin.math.ceil import kotlin.math.max /** * 808. Soup Servings * @see <a href="https://leetcode.com/problems/soup-servings/">Source</a> */ fun interface SoupServings { operator fun invoke(n: Int): Double } private const val DIVISOR = 25.0 private const val HALF = 0.5 /** * Approach 1: Bottom-Up Dynamic Programming */ class SoupServingsBottomUp : SoupServings { override operator fun invoke(n: Int): Double { val m = ceil(n / DIVISOR).toInt() val dp = mutableMapOf<Int, MutableMap<Int, Double>>() dp[0] = mutableMapOf() dp[0]?.set(0, HALF) for (k in 1..m) { dp[k] = mutableMapOf() dp[0]?.set(k, 1.0) dp[k]?.set(0, 0.0) for (j in 1..k) { dp[j]?.set(k, calculateDP(j, k, dp)) dp[k]?.set(j, calculateDP(k, j, dp)) } dp[k]?.let { it[k]?.let { k -> if (k > 1 - EPSILON) { return 1.0 } } } } return dp[m]?.get(m) ?: 0.0 } private fun calculateDP(i: Int, j: Int, dp: Map<Int, Map<Int, Double>>): Double { val iMinus4 = max(0, i - 4) val iMinus3 = max(0, i - 3) val iMinus2 = max(0, i - 2) val jMinus1 = j - 1 val jMinus2 = max(0, j - 2) val jMinus3 = max(0, j - 3) val term1 = dp.getOrElse(iMinus4) { emptyMap() }.getOrElse(j) { 0.0 } val term2 = dp.getOrElse(iMinus3) { emptyMap() }.getOrElse(jMinus1) { 0.0 } val term3 = dp.getOrElse(iMinus2) { emptyMap() }.getOrElse(jMinus2) { 0.0 } val term4 = dp.getOrElse(i - 1) { emptyMap() }.getOrElse(jMinus3) { 0.0 } return (term1 + term2 + term3 + term4) / 4 } } /** * Approach 2: Top-Down Dynamic Programming (Memoization) */ class SoupServingsTopDown : SoupServings { override operator fun invoke(n: Int): Double { val m = ceil(n / DIVISOR).toInt() val dp: MutableMap<Int, MutableMap<Int, Double>> = HashMap() for (k in 1..m) { if (calculateDP(k, k, dp) > 1 - EPSILON) { return 1.0 } } return calculateDP(m, m, dp) } private fun calculateDP(i: Int, j: Int, dp: MutableMap<Int, MutableMap<Int, Double>>): Double { if (i <= 0 && j <= 0) { return 0.5 } if (i <= 0) { return 1.0 } if (j <= 0) { return 0.0 } if (dp.containsKey(i) && dp[i]?.containsKey(j) == true) { return dp[i]?.get(j) ?: 0.0 } val result = ( calculateDP(i - 4, j, dp) + calculateDP(i - 3, j - 1, dp) + calculateDP(i - 2, j - 2, dp) + calculateDP(i - 1, j - 3, dp) ) / 4.0 dp.getOrPut(i) { mutableMapOf() }[j] = result return result } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,630
kotlab
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/ReducingDishes.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * 1402. Reducing Dishes * @see <a href="https://leetcode.com/problems/reducing-dishes/">Source</a> */ fun interface ReducingDishes { fun maxSatisfaction(satisfaction: IntArray): Int } class ReducingDishesSimple : ReducingDishes { override fun maxSatisfaction(satisfaction: IntArray): Int { satisfaction.sort() var res = 0 var total = 0 val n: Int = satisfaction.size var i = n - 1 while (i >= 0 && satisfaction[i] > -total) { total += satisfaction[i] res += total --i } return res } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,247
kotlab
Apache License 2.0
src/test/kotlin/com/athaydes/samples/cards.kt
renatoathaydes
84,996,216
false
null
package com.athaydes.samples /** * This is a sample usage of the KUnion library. */ import com.athaydes.kunion.Union import java.util.Collections enum class Suit { Spades, Diamonds, Hearts, Clubs } enum class Symbol { Ace, Jack, Queen, King } typealias Rank = Union.U2<Int, Symbol> fun rank(number: Int): Rank? = if (number in 1..10) Union.U2.ofA(number) else null fun rank(symbol: Symbol): Rank = Union.U2.ofB(symbol) fun numericValueOf(rank: Rank): Int = rank.use( { number -> number }, { rank -> when (rank) { Symbol.Ace -> 14 Symbol.Jack -> 11 Symbol.Queen -> 12 Symbol.King -> 13 } }) fun numericValueOf(suit: Suit): Int = when (suit) { Suit.Spades -> 10 Suit.Diamonds -> 9 Suit.Hearts -> 8 Suit.Clubs -> 7 } data class Card(val rank: Rank, val suit: Suit) : Comparable<Card> { override fun compareTo(other: Card): Int { val rankComparison = numericValueOf(this.rank).compareTo(numericValueOf(other.rank)) return if (rankComparison != 0) rankComparison else numericValueOf(this.suit).compareTo(numericValueOf(other.suit)) } } fun main(args: Array<String>) { val ranks = (1..10).map(::rank).filterNotNull() + listOf(Symbol.Ace, Symbol.Jack, Symbol.Queen, Symbol.King).map(::rank) val suites = listOf(Suit.Clubs, Suit.Hearts, Suit.Diamonds, Suit.Spades) val cards = ranks.flatMap { r -> suites.map { s -> Card(r, s) } }.toMutableList() println("All cards:") println(cards) Collections.shuffle(cards) println("Shuffled cards:") println(cards) cards.sort() println("Sorted cards:") println(cards) }
0
Kotlin
4
73
0bd9cbfe38c1186254f9738e8e25e858a36ddcff
1,797
kunion
Apache License 2.0
src/main/java/io/deeplay/qlab/data/Normalizer.kt
oQaris
475,961,305
false
{"Jupyter Notebook": 766904, "Java": 47993, "Kotlin": 23299}
package io.deeplay.qlab.data class Normalizer(val context: NormContext) { companion object { fun fitMinimax(history: List<FloatArray>, from: Int = 0, to: Int = 1) = Normalizer( context = buildList { history.forEachColumn { column -> val (max, min) = column.maxOf { it } to column.minOf { it } val mmba = (max - min) / (to - from) add(min - from * mmba to mmba) } }.toContext() ) fun fitZNorm(history: List<FloatArray>) = Normalizer( context = buildList { history.forEachColumn { column -> add(orEmptyNorm(column) { val mean = column.mean { it } val sd = column.standardDeviation { it } mean to sd }) } }.toContext() ) fun fitRobust(history: List<FloatArray>) = Normalizer( context = buildList { history.forEachColumn { column -> add(orEmptyNorm(column) { val median = column.median { it } val q25 = column.quantile(0.25f) { it } val q75 = column.quantile(0.75f) { it } median to q75 - q25 }) } }.toContext() ) private fun orEmptyNorm(column: Collection<Float>, context: () -> Pair<Float, Float>): Pair<Float, Float> { val (max, min) = column.maxOf { it } to column.minOf { it } return if (max <= 1 && min >= -1) 0f to 1f else context() } private fun Collection<FloatArray>.forEachColumn(action: (List<Float>) -> Unit) { for (nCol in this.first().indices) { val column = this.map { it[nCol] } action(column) } } private fun Collection<Pair<Float, Float>>.toContext() = this.unzip().let { NormContext(it.first.toFloatArray(), it.second.toFloatArray()) } class NormContext(val subtrahend: FloatArray, val divider: FloatArray) } fun transformAll(data: List<FloatArray>, vararg excludingCols: Int): List<FloatArray> { return data.map { transform(it, *excludingCols) } } fun transform(data: FloatArray, vararg excludingCols: Int): FloatArray { return data.zip(context.subtrahend.zip(context.divider)) .mapIndexed { idx, triple -> if (idx !in excludingCols) (triple.first - triple.second.first) / triple.second.second else triple.first }.toFloatArray() } }
0
Jupyter Notebook
0
0
5dd497b74a767c740386dc67e6841673b17b96fb
2,781
QLab
MIT License
dataStructuresAndAlgorithms/src/main/java/dev/funkymuse/datastructuresandalgorithms/trees/binarySearchTree/BinarySearchTree.kt
FunkyMuse
168,687,007
false
{"Kotlin": 1728251}
package dev.funkymuse.datastructuresandalgorithms.trees.binarySearchTree class BinarySearchTree<T : Comparable<T>> { var root: BinarySearchNode<T>? = null fun insert(value: T) { root = insert(root, value) } private fun insert( node: BinarySearchNode<T>?, value: T ): BinarySearchNode<T> { node ?: return BinarySearchNode(value) if (value < node.value) { node.leftChild = insert(node.leftChild, value) } else { node.rightChild = insert(node.rightChild, value) } return node } fun remove(value: T) { root = remove(root, value) } private fun remove( node: BinarySearchNode<T>?, value: T ): BinarySearchNode<T>? { node ?: return null when { value == node.value -> { if (node.leftChild == null && node.rightChild == null) { return null } if (node.leftChild == null) { return node.rightChild } if (node.rightChild == null) { return node.leftChild } node.rightChild?.min?.value?.let { node.value = it } node.rightChild = remove(node.rightChild, node.value) } value < node.value -> node.leftChild = remove(node.leftChild, value) else -> node.rightChild = remove(node.rightChild, value) } return node } override fun toString() = root?.toString() ?: "empty tree" fun contains(value: T): Boolean { var current = root while (current != null) { if (current.value == value) { return true } current = if (value < current.value) { current.leftChild } else { current.rightChild } } return false } override fun equals(other: Any?): Boolean { return other is BinarySearchTree<*> && this.root == other.root } fun contains(subtree: BinarySearchTree<T>): Boolean { val set = mutableSetOf<T>() root?.traverseInOrder { set.add(it) } var isEqual = true subtree.root?.traverseInOrder { isEqual = isEqual && set.contains(it) } return isEqual } }
0
Kotlin
92
771
e2afb0cc98c92c80ddf2ec1c073d7ae4ecfcb6e1
2,478
KAHelpers
MIT License
src/leetcode_study_badge/algorithm/Day2.kt
faniabdullah
382,893,751
false
null
package leetcode_study_badge.algorithm class Day2 { fun sortedSquares(nums: IntArray): IntArray { var right = nums.size - 1 var left = 0 val resultArray = IntArray(nums.size) var insertPosition = nums.size - 1 while (left < right) { val leftValue = nums[left] * nums[left] val rightValue = nums[right] * nums[right] if (leftValue > rightValue) { resultArray[insertPosition] = leftValue insertPosition-- left++ } else if (rightValue > leftValue) { resultArray[insertPosition] = rightValue insertPosition-- right-- } else if (rightValue == leftValue) { resultArray[insertPosition] = rightValue insertPosition-- resultArray[insertPosition] = leftValue insertPosition-- right-- left++ } } println(resultArray.contentToString()) if (left == right) { resultArray[insertPosition] = nums[left] * nums[left] } return resultArray } fun rotate(nums: IntArray, k: Int) { for (i in 0 until k) { var temp = nums[0] nums[0] = nums[nums.size - 1] for (a in 1 until nums.size) { var swap = nums[a] nums[a] = temp temp = swap } } } fun rotateTwoPointer(nums: IntArray, k: Int) { fun reverse(i: Int, j: Int) { var i = i; var j = j while (i < j) { nums[i] = nums[j].also { nums[j] = nums[i] } i++; j-- } } val N = nums.size val k = k % N reverse(0, N - 1) reverse(0, k - 1) reverse(k, N - 1) } } fun main() { println(Day2().sortedSquares(intArrayOf(-7, -3, 2, 3, 11)).contentToString()) val rotateArray = intArrayOf(1, 2, 3, 4, 5, 6, 7) println(rotateArray.contentToString()) Day2().rotateTwoPointer(rotateArray, 3) println(rotateArray.contentToString()) }
0
Kotlin
0
6
ecf14fe132824e944818fda1123f1c7796c30532
2,185
dsa-kotlin
MIT License
dsalgo/src/commonMain/kotlin/com/nalin/datastructurealgorithm/ds/Graph.kt
nalinchhajer1
534,780,196
false
{"Kotlin": 86359, "Ruby": 1605}
package com.nalin.datastructurealgorithm.ds import kotlin.math.min val GRAPH_UNDIRECTED = 1 val GRAPH_DIRECTED = 0 /** * Graph: * Create graph in format of Adjacency list. It stores connection for each node internally. */ class AdjacencyListGraph<T>(val directionType: Int = GRAPH_DIRECTED) { val nodes: MutableMap<T, MutableSet<Edge<T>>> = mutableMapOf() var nodeCount = 0 var edgesCount = 0 data class Edge<T>(val node: T, val value: Int) /** * Add Edge from node1 to node2, if node not created, it created one */ fun addEdge(node1: T, node2: T, value: Int = 1) { if (addNode(node1).add(Edge(node2, value))) { edgesCount++ } if (directionType == GRAPH_UNDIRECTED) { addNode(node2).add(Edge(node1, value)) } else { addNode(node2) } } /** * Add Node */ fun addNode(node: T): MutableSet<Edge<T>> { if (nodes[node] == null) { nodes[node] = mutableSetOf() nodeCount++ } return nodes[node]!! } /** * return edges */ fun getEdges(node: T): MutableIterator<Edge<T>> { return nodes[node]?.iterator() ?: mutableSetOf<Edge<T>>().iterator() } /** * get nodes iterator */ fun getNodes(): MutableIterator<T> { return nodes.keys.iterator() } /** * Clear all nodes and Edges, it is same as new */ fun clear() { nodes.clear() edgesCount = 0 nodeCount = 0 } /** * returns if empty */ fun isEmpty(): Boolean { return nodes.isEmpty() } /** * Checks if contains Node */ fun containsNode(node: T): Boolean { return nodes[node] != null } fun removeEdge(fromNode: T, toNode: T): Boolean { var result = false val iterator = getEdges(fromNode) while (iterator.hasNext()) { if (iterator.next().node == toNode) { iterator.remove() edgesCount-- result = result || true } } return result } fun removeNode(node: T): MutableSet<Edge<T>>? { val result = nodes.remove(node) nodeCount-- for (edgeNode in getNodes()) { removeEdge(edgeNode, node) } return result } } /** * Dijkstra Algorithm * Given a graph and a source vertex in the graph, find the shortest paths from the source to all vertices in the given graph. * O((E+V)log V) */ fun <T : Comparable<T>> AdjacencyListGraph<T>.findShortestPath_dijkstra( sourceNode: T ): MutableMap<T, Int> { // use priority queue to select shortest possible destination val distance = mutableMapOf<T, Int>() // Stores distance for each node val queue = IndexedPriorityQueue<T>(true) val visited = mutableMapOf<T, Boolean>() fun traverse() { val node = queue.pop()!! visited[node] = true for (nextEdge in getEdges(node)) { if (visited[nextEdge.node] != true) { val newDistance = min(distance[nextEdge.node] ?: Int.MAX_VALUE, distance[node]!! + nextEdge.value) distance[nextEdge.node] = newDistance if (queue.contains(nextEdge.node)) { if (queue.getPriority(nextEdge.node)!! < newDistance) { queue.changePriority(nextEdge.node, newDistance) } } else { queue.push(nextEdge.node, newDistance) } } } if (queue.peek() != null) { traverse() } } if (containsNode(sourceNode)) { queue.push(sourceNode, 0) distance[sourceNode] = 0 traverse() } return distance } /** * Return Topological sorting by Kahn Algorithm, first add all 0 our degree and then others */ fun <T : Comparable<T>> AdjacencyListGraph<T>.topologicalOrdering_KahnAlgorithm(): MutableList<T> { val indegreeNodes: MutableMap<T, Int> = calculateInDegreeOfNodes() val minDegree = indegreeNodes.values.minOfOrNull { v -> v } ?: 0 val queue = Queue<T>(); val topologicalSort = mutableListOf<T>() val nodeToAddInQueue = findNodesWithKDegree(indegreeNodes, minDegree) for (node in nodeToAddInQueue) { indegreeNodes.remove(node) queue.enqueue(node) } while (queue.size > 0) { val baseNode = queue.dequeue() topologicalSort.add(baseNode!!) for (edge in getEdges(baseNode)) { val edgeNode = edge.node if (indegreeNodes[edgeNode] != null) { indegreeNodes[edgeNode] = indegreeNodes[edgeNode]!! - 1 if (indegreeNodes[edgeNode] == 0) { indegreeNodes.remove(edgeNode); queue.enqueue(edgeNode) } } } } return topologicalSort } fun <T> AdjacencyListGraph<T>.findNodesWithKDegree( indegreeNode: MutableMap<T, Int>, degree: Int ): MutableList<T> { val output = mutableListOf<T>() for (node in getNodes()) { if ((indegreeNode[node] ?: 0) == degree) { output.add(node) } } return output } /** * Calculates Indegee of all nodes */ fun <T> AdjacencyListGraph<T>.calculateInDegreeOfNodes(): MutableMap<T, Int> { val inDegree = mutableMapOf<T, Int>() for (node in getNodes()) { inDegree[node] = inDegree[node] ?: 0 for (edge in getEdges(node)) { inDegree[edge.node] = (inDegree[edge.node] ?: 0) + 1 } } return inDegree } /** * Validate if given order is topological order, source is before destination */ fun <T> AdjacencyListGraph<T>.validateTopologicalOrdering(nodeInOrder: List<T>): Boolean { val nodeToPos = mutableMapOf<T, Int>() nodeInOrder.forEachIndexed { pos, item -> nodeToPos[item] = pos } for (node in getNodes()) { for (edge in getEdges(node)) { if (nodeToPos[node]!! >= nodeToPos[edge.node]!!) { return false } } } return true } /** * Node traversal as DFS * O (E+N) */ fun <T> AdjacencyListGraph<T>.nodeTraversalDFS(startNode: T? = null): MutableList<T> { val traversal = mutableListOf<T>() val isVisited = mutableMapOf<T, Boolean>() fun traverse(node: T) { traversal.add(node) isVisited[node] = true val edges = nodes[node]!! for (edge in edges) { if (isVisited[edge.node] != true) { traverse(edge.node) } } } if (startNode != null) { traverse(startNode) } for ((k, _) in nodes) { if (isVisited[k] != true) { traverse(k) } } return traversal } /** * Node traversal as BFS * O (E+N) */ fun <T> AdjacencyListGraph<T>.nodeTraversalBFS(startNode: T? = null): MutableList<T> { val traversal = mutableListOf<T>() val isVisited = mutableMapOf<T, Boolean>() val queue = SetQueue<T>() var traverse: (() -> Unit)? = null fun runQueue() { while (queue.peek() != null) { traverse?.let { it() } } } traverse = fun() { val node = queue.dequeue() ?: return traversal.add(node) isVisited[node] = true val edges = nodes[node]!! for (edge in edges) { if (isVisited[edge.node] != true) { queue.enqueue(edge.node) } } runQueue() } if (startNode != null) { queue.enqueue(startNode) runQueue() } for ((k, _) in nodes) { if (isVisited[k] != true) { queue.enqueue(k) runQueue() } } return traversal } /** * Node traversal in Topological * O (E+N) */ fun <T> AdjacencyListGraph<T>.nodeTraversalTopological(startNode: T? = null): MutableList<T> { val traversal = mutableListOf<T>() val isVisited = mutableMapOf<T, Boolean>() fun traverse(node: T) { isVisited[node] = true val edges = nodes[node]!! for (edge in edges) { if (isVisited[edge.node] != true) { traverse(edge.node) } } traversal.add(node) } if (startNode != null) { traverse(startNode) } for ((k, _) in nodes) { if (isVisited[k] != true) { traverse(k) } } return traversal } /** * Ensure lNode < rNode */ data class MSTEdge<T : Comparable<T>> private constructor( private val node1: T, private val node2: T, val value: Int ) { val lNode: T get() = node1 val rNode: T get() = node2 companion object { fun <T : Comparable<T>> create(lNode: T, rNode: T, value: Int): MSTEdge<T> { return MSTEdge( if (lNode < rNode) lNode else rNode, if (lNode < rNode) rNode else lNode, value ) } } } // Minimum spanning tree, for undirected_graph fun <T : Comparable<T>> AdjacencyListGraph<T>.minumSpanningTree_kruskal(): AdjacencyListGraph<T> { val sortedEdges = getAllEdgesSortedByValue() val mstGraph = AdjacencyListGraph<T>(GRAPH_UNDIRECTED) val unionFind = UnionFind<T>() for (edge in sortedEdges) { if (!unionFind.isConnected(edge.lNode, edge.rNode)) { unionFind.union(edge.lNode, edge.rNode) mstGraph.addEdge(edge.lNode, edge.rNode, edge.value) } } return mstGraph } fun <T : Comparable<T>> AdjacencyListGraph<T>.getAllEdgesSortedByValue(): List<MSTEdge<T>> { val edges = HashSet<MSTEdge<T>>() for (node in getNodes()) { for (edge in getEdges(node)) { edges.add(MSTEdge.create(node, edge.node, edge.value)) } } val sortedEdges = edges.sortedBy { it.value } return sortedEdges } // Find all strongly connected components /** * In the graph, strongly connected components are part of the graph that form cycles. Inside the cycles, all node can be visited from every other node * 1. We will use DFS + Stack to find strongly connected components * 2. We are going to mark a node with low link value, once we have visited all path on the DFS * * O(V+E) */ fun <T> AdjacencyListGraph<T>.findStronglyConnectedComponents_tarjan(): Int { var id = 0 // low-link id var sccCount = 0 // number of strong connected component found val nodeIds = mutableMapOf<T, Int>() // We will use this to track if visited or not val nodeLowLinkId = mutableMapOf<T, Int>() val nodeOnStack = mutableMapOf<T, Boolean>() val stack = ArrayDeque<T>() // addLast. removeLast, size fun traverse(node: T) { stack.addLast(node) nodeOnStack[node] = true val lowLinkId = id++ nodeIds[node] = lowLinkId nodeLowLinkId[node] = lowLinkId val edges = nodes[node]!! // Visit all neighbour and min low-link on callback for (edge in edges) { if (nodeIds[edge.node] == null) { traverse(edge.node) } // reached all nodes if (nodeOnStack[edge.node] != null) { nodeLowLinkId[node] = min(nodeLowLinkId[node] ?: 0, nodeLowLinkId[edge.node] ?: 0) } } // After visiting all neighbours, if we are at the start of SCC, empty the stack until we are back again at start of SCC (loop) if (nodeIds[node] == nodeLowLinkId[node]) { while (stack.size > 0) { val stackNode = stack.removeLast() nodeOnStack[stackNode] = false nodeLowLinkId[stackNode] = nodeIds[node]!! if (stackNode == node) { break } } sccCount++ } } for ((k, _) in nodes) { if (nodeIds[k] == null) { traverse(k) } } println("nodeLowLinkId ${nodeLowLinkId}") println("nodeIds ${nodeIds}") return sccCount }
0
Kotlin
0
0
eca60301dab981d0139788f61149d091c2c557fd
12,095
kotlin-ds-algo
MIT License
y2020/src/main/kotlin/adventofcode/y2020/Day15.kt
Ruud-Wiegers
434,225,587
false
{"Kotlin": 503769}
package adventofcode.y2020 import adventofcode.io.AdventSolution fun main() = Day15.solve() object Day15 : AdventSolution(2020, 15, "Rambunctious Recitation") { override fun solvePartOne(input: String) = input .split(',') .map(String::toInt) .let { recitation(it, 2020) } override fun solvePartTwo(input: String) = input .split(',') .map(String::toInt) .let { recitation(it, 30_000_000) } private fun recitation(initial: List<Int>, length: Int): Int { val seen = IntArray(length) { -1 } initial.dropLast(1).forEachIndexed { i, v -> seen[v] = i } var prev = initial.last() repeat(length - initial.size) { val b = it + initial.lastIndex val i = if (seen[prev] < 0) b else seen[prev] seen[prev] = b prev = b - i } return prev } }
0
Kotlin
0
3
fc35e6d5feeabdc18c86aba428abcf23d880c450
893
advent-of-code
MIT License
merge-sort/mergeSort.kt
babangsund
212,265,663
false
null
fun <T:Comparable<T>> merge(a: List<T>, b: List<T>): List<T> { if (a.isEmpty() && b.isNotEmpty()) return b if (b.isEmpty() && a.isNotEmpty()) return a val (ah, at) = Pair(a[0], a.drop(1)) val (bh, bt) = Pair(b[0], b.drop(1)) return when { ah >= bh -> listOf(bh) + merge(a, bt) else -> listOf(ah) + merge(at, b) } } fun <T:Comparable<T>> mergeSort(list: List<T>): List<T> { val len = list.count() if (len < 2) return list val half = kotlin.math.ceil((len.toDouble() / 2)).toInt() val (left, right) = list.chunked(half) return merge(mergeSort(left), mergeSort(right)) } fun main() { val sorted = mergeSort(listOf(6, 5, 2, 3, 0, 1)) println("sorted: $sorted") }
0
Kotlin
0
1
0f05c412bd6193e4f8449e63c5935316d6dde20b
733
sorting-algorithms
MIT License